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"
36 // FIXME: completely move here.
37 extern cl::opt<bool> ForceStackAlign;
39 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
40 return !MF.getFrameInfo()->hasVarSizedObjects();
43 /// hasFP - Return true if the specified function should have a dedicated frame
44 /// pointer register. This is true if the function has variable sized allocas
45 /// or if frame pointer elimination is disabled.
46 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
47 const MachineFrameInfo *MFI = MF.getFrameInfo();
48 const MachineModuleInfo &MMI = MF.getMMI();
49 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
51 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
52 RegInfo->needsStackRealignment(MF) ||
53 MFI->hasVarSizedObjects() ||
54 MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
55 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
56 MMI.callsUnwindInit() || MMI.callsEHReturn());
59 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
63 return X86::SUB64ri32;
71 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
75 return X86::ADD64ri32;
83 static unsigned getLEArOpcode(unsigned IsLP64) {
84 return IsLP64 ? X86::LEA64r : X86::LEA32r;
87 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
88 /// when it reaches the "return" instruction. We can then pop a stack object
89 /// to this register without worry about clobbering it.
90 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
91 MachineBasicBlock::iterator &MBBI,
92 const TargetRegisterInfo &TRI,
94 const MachineFunction *MF = MBB.getParent();
95 const Function *F = MF->getFunction();
96 if (!F || MF->getMMI().callsEHReturn())
99 static const uint16_t CallerSavedRegs32Bit[] = {
100 X86::EAX, X86::EDX, X86::ECX, 0
103 static const uint16_t CallerSavedRegs64Bit[] = {
104 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
105 X86::R8, X86::R9, X86::R10, X86::R11, 0
108 unsigned Opc = MBBI->getOpcode();
115 case X86::TCRETURNdi:
116 case X86::TCRETURNri:
117 case X86::TCRETURNmi:
118 case X86::TCRETURNdi64:
119 case X86::TCRETURNri64:
120 case X86::TCRETURNmi64:
122 case X86::EH_RETURN64: {
123 SmallSet<uint16_t, 8> Uses;
124 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
125 MachineOperand &MO = MBBI->getOperand(i);
126 if (!MO.isReg() || MO.isDef())
128 unsigned Reg = MO.getReg();
131 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
135 const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
137 if (!Uses.count(*CS))
146 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
147 /// stack pointer by a constant value.
149 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
150 unsigned StackPtr, int64_t NumBytes,
151 bool Is64BitTarget, bool Is64BitStackPtr, bool UseLEA,
152 const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
153 bool isSub = NumBytes < 0;
154 uint64_t Offset = isSub ? -NumBytes : NumBytes;
157 Opc = getLEArOpcode(Is64BitStackPtr);
160 ? getSUBriOpcode(Is64BitStackPtr, Offset)
161 : getADDriOpcode(Is64BitStackPtr, Offset);
163 uint64_t Chunk = (1LL << 31) - 1;
164 DebugLoc DL = MBB.findDebugLoc(MBBI);
167 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
168 if (ThisVal == (Is64BitTarget ? 8 : 4)) {
169 // Use push / pop instead.
171 ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
172 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
175 ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
176 : (Is64BitTarget ? X86::POP64r : X86::POP32r);
177 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
178 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
180 MI->setFlag(MachineInstr::FrameSetup);
186 MachineInstr *MI = nullptr;
189 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
190 StackPtr, false, isSub ? -ThisVal : ThisVal);
192 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
195 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
199 MI->setFlag(MachineInstr::FrameSetup);
205 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
207 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
208 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
209 if (MBBI == MBB.begin()) return;
211 MachineBasicBlock::iterator PI = std::prev(MBBI);
212 unsigned Opc = PI->getOpcode();
213 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
214 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
215 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
216 PI->getOperand(0).getReg() == StackPtr) {
218 *NumBytes += PI->getOperand(2).getImm();
220 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
221 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
222 PI->getOperand(0).getReg() == StackPtr) {
224 *NumBytes -= PI->getOperand(2).getImm();
229 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
232 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
233 MachineBasicBlock::iterator &MBBI,
234 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
235 // FIXME: THIS ISN'T RUN!!!
238 if (MBBI == MBB.end()) return;
240 MachineBasicBlock::iterator NI = std::next(MBBI);
241 if (NI == MBB.end()) return;
243 unsigned Opc = NI->getOpcode();
244 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
245 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
246 NI->getOperand(0).getReg() == StackPtr) {
248 *NumBytes -= NI->getOperand(2).getImm();
251 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
252 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
253 NI->getOperand(0).getReg() == StackPtr) {
255 *NumBytes += NI->getOperand(2).getImm();
261 /// mergeSPUpdates - Checks the instruction before/after the passed
262 /// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
263 /// the stack adjustment is returned as a positive value for ADD/LEA and a
264 /// negative for SUB.
265 static int mergeSPUpdates(MachineBasicBlock &MBB,
266 MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
267 bool doMergeWithPrevious) {
268 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
269 (!doMergeWithPrevious && MBBI == MBB.end()))
272 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
273 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
275 unsigned Opc = PI->getOpcode();
278 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
279 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
280 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
281 PI->getOperand(0).getReg() == StackPtr){
282 Offset += PI->getOperand(2).getImm();
284 if (!doMergeWithPrevious) MBBI = NI;
285 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
286 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
287 PI->getOperand(0).getReg() == StackPtr) {
288 Offset -= PI->getOperand(2).getImm();
290 if (!doMergeWithPrevious) MBBI = NI;
296 static bool isEAXLiveIn(MachineFunction &MF) {
297 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
298 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
299 unsigned Reg = II->first;
301 if (Reg == X86::EAX || Reg == X86::AX ||
302 Reg == X86::AH || Reg == X86::AL)
310 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
311 MachineBasicBlock::iterator MBBI,
313 MachineFunction &MF = *MBB.getParent();
314 MachineFrameInfo *MFI = MF.getFrameInfo();
315 MachineModuleInfo &MMI = MF.getMMI();
316 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
317 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
319 // Add callee saved registers to move list.
320 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
321 if (CSI.empty()) return;
323 // Calculate offsets.
324 for (std::vector<CalleeSavedInfo>::const_iterator
325 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
326 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
327 unsigned Reg = I->getReg();
329 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
331 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
333 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
334 .addCFIIndex(CFIIndex);
338 /// usesTheStack - This function checks if any of the users of EFLAGS
339 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
340 /// to use the stack, and if we don't adjust the stack we clobber the first
342 /// See X86InstrInfo::copyPhysReg.
343 static bool usesTheStack(const MachineFunction &MF) {
344 const MachineRegisterInfo &MRI = MF.getRegInfo();
346 for (MachineRegisterInfo::reg_instr_iterator
347 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
355 void X86FrameLowering::getStackProbeFunction(const X86Subtarget &STI,
357 const char *&Symbol) {
358 CallOp = STI.is64Bit() ? X86::W64ALLOCA : X86::CALLpcrel32;
361 if (STI.isTargetCygMing()) {
362 Symbol = "___chkstk_ms";
366 } else if (STI.isTargetCygMing())
372 /// emitPrologue - Push callee-saved registers onto the stack, which
373 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
374 /// space for local variables. Also emit labels used by the exception handler to
375 /// generate the exception handling frames.
378 Here's a gist of what gets emitted:
380 ; Establish frame pointer, if needed
383 .cfi_def_cfa_offset 16
384 .cfi_offset %rbp, -16
387 .cfi_def_cfa_register %rbp
389 ; Spill general-purpose registers
390 [for all callee-saved GPRs]
393 .cfi_def_cfa_offset (offset from RETADDR)
396 ; If the required stack alignment > default stack alignment
397 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
398 ; of unknown size in the stack frame.
399 [if stack needs re-alignment]
402 ; Allocate space for locals
403 [if target is Windows and allocated space > 4096 bytes]
404 ; Windows needs special care for allocations larger
407 call ___chkstk_ms/___chkstk
413 .seh_stackalloc (size of XMM spill slots)
414 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
419 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
420 ; they may get spilled on any platform, if the current function
421 ; calls @llvm.eh.unwind.init
423 [for all callee-saved XMM registers]
424 movaps %<xmm reg>, -MMM(%rbp)
425 [for all callee-saved XMM registers]
426 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
427 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
429 [for all callee-saved XMM registers]
430 movaps %<xmm reg>, KKK(%rsp)
431 [for all callee-saved XMM registers]
432 .seh_savexmm %<xmm reg>, KKK
436 [if needs base pointer]
441 [for all callee-saved registers]
442 .cfi_offset %<reg>, (offset from %rbp)
444 .cfi_def_cfa_offset (offset from RETADDR)
445 [for all callee-saved registers]
446 .cfi_offset %<reg>, (offset from %rsp)
449 - .seh directives are emitted only for Windows 64 ABI
450 - .cfi directives are emitted for all other ABIs
451 - for 32-bit code, substitute %e?? registers for %r??
454 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
455 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
456 MachineBasicBlock::iterator MBBI = MBB.begin();
457 MachineFrameInfo *MFI = MF.getFrameInfo();
458 const Function *Fn = MF.getFunction();
459 const X86RegisterInfo *RegInfo =
460 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
461 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
462 MachineModuleInfo &MMI = MF.getMMI();
463 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
464 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
465 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
466 bool HasFP = hasFP(MF);
467 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
468 bool Is64Bit = STI.is64Bit();
469 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
470 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
471 bool IsWin64 = STI.isTargetWin64();
473 MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
474 ExceptionHandling::WinEH; // Not necessarily synonymous with IsWin64.
475 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
477 !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
478 bool UseLEA = STI.useLeaForSP();
479 unsigned StackAlign = getStackAlignment();
480 unsigned SlotSize = RegInfo->getSlotSize();
481 unsigned FramePtr = RegInfo->getFrameRegister(MF);
482 const unsigned MachineFramePtr = STI.isTarget64BitILP32() ?
483 getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
484 unsigned StackPtr = RegInfo->getStackRegister();
485 unsigned BasePtr = RegInfo->getBaseRegister();
488 // If we're forcing a stack realignment we can't rely on just the frame
489 // info, we need to know the ABI stack alignment as well in case we
490 // have a call out. Otherwise just make sure we have some alignment - we'll
491 // go with the minimum SlotSize.
492 if (ForceStackAlign) {
494 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
495 else if (MaxAlign < SlotSize)
499 // Add RETADDR move area to callee saved frame size.
500 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
501 if (TailCallReturnAddrDelta < 0)
502 X86FI->setCalleeSavedFrameSize(
503 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
505 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
506 // function, and use up to 128 bytes of stack space, don't have a frame
507 // pointer, calls, or dynamic alloca then we do not need to adjust the
508 // stack pointer (we fit in the Red Zone). We also check that we don't
509 // push and pop from the stack.
510 if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
511 Attribute::NoRedZone) &&
512 !RegInfo->needsStackRealignment(MF) &&
513 !MFI->hasVarSizedObjects() && // No dynamic alloca.
514 !MFI->adjustsStack() && // No calls.
515 !IsWin64 && // Win64 has no Red Zone
516 !usesTheStack(MF) && // Don't push and pop.
517 !MF.shouldSplitStack()) { // Regular stack
518 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
519 if (HasFP) MinSize += SlotSize;
520 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
521 MFI->setStackSize(StackSize);
524 // Insert stack pointer adjustment for later moving of return addr. Only
525 // applies to tail call optimized functions where the callee argument stack
526 // size is bigger than the callers.
527 if (TailCallReturnAddrDelta < 0) {
529 BuildMI(MBB, MBBI, DL,
530 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
533 .addImm(-TailCallReturnAddrDelta)
534 .setMIFlag(MachineInstr::FrameSetup);
535 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
538 // Mapping for machine moves:
540 // DST: VirtualFP AND
541 // SRC: VirtualFP => DW_CFA_def_cfa_offset
542 // ELSE => DW_CFA_def_cfa
544 // SRC: VirtualFP AND
545 // DST: Register => DW_CFA_def_cfa_register
548 // OFFSET < 0 => DW_CFA_offset_extended_sf
549 // REG < 64 => DW_CFA_offset + Reg
550 // ELSE => DW_CFA_offset_extended
552 uint64_t NumBytes = 0;
553 int stackGrowth = -SlotSize;
556 // Calculate required stack adjustment.
557 uint64_t FrameSize = StackSize - SlotSize;
558 if (RegInfo->needsStackRealignment(MF)) {
559 // Callee-saved registers are pushed on stack before the stack
561 FrameSize -= X86FI->getCalleeSavedFrameSize();
562 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
564 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
567 // Get the offset of the stack slot for the EBP register, which is
568 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
569 // Update the frame offset adjustment.
570 MFI->setOffsetAdjustment(-NumBytes);
572 // Save EBP/RBP into the appropriate stack slot.
573 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
574 .addReg(MachineFramePtr, RegState::Kill)
575 .setMIFlag(MachineInstr::FrameSetup);
578 // Mark the place where EBP/RBP was saved.
579 // Define the current CFA rule to use the provided offset.
581 unsigned CFIIndex = MMI.addFrameInst(
582 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
583 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
584 .addCFIIndex(CFIIndex);
586 // Change the rule for the FramePtr to be an "offset" rule.
587 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
588 CFIIndex = MMI.addFrameInst(
589 MCCFIInstruction::createOffset(nullptr,
590 DwarfFramePtr, 2 * stackGrowth));
591 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
592 .addCFIIndex(CFIIndex);
596 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
598 .setMIFlag(MachineInstr::FrameSetup);
601 // Update EBP with the new base value.
602 BuildMI(MBB, MBBI, DL,
603 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), FramePtr)
605 .setMIFlag(MachineInstr::FrameSetup);
608 // Mark effective beginning of when frame pointer becomes valid.
609 // Define the current CFA to use the EBP/RBP register.
610 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
611 unsigned CFIIndex = MMI.addFrameInst(
612 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
613 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
614 .addCFIIndex(CFIIndex);
617 // Mark the FramePtr as live-in in every block.
618 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
619 I->addLiveIn(MachineFramePtr);
621 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
624 // Skip the callee-saved push instructions.
625 bool PushedRegs = false;
626 int StackOffset = 2 * stackGrowth;
628 while (MBBI != MBB.end() &&
629 (MBBI->getOpcode() == X86::PUSH32r ||
630 MBBI->getOpcode() == X86::PUSH64r)) {
632 unsigned Reg = MBBI->getOperand(0).getReg();
635 if (!HasFP && NeedsDwarfCFI) {
636 // Mark callee-saved push instruction.
637 // Define the current CFA rule to use the provided offset.
639 unsigned CFIIndex = MMI.addFrameInst(
640 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
641 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
642 .addCFIIndex(CFIIndex);
643 StackOffset += stackGrowth;
647 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
648 MachineInstr::FrameSetup);
652 // Realign stack after we pushed callee-saved registers (so that we'll be
653 // able to calculate their offsets from the frame pointer).
654 if (RegInfo->needsStackRealignment(MF)) {
655 assert(HasFP && "There should be a frame pointer if stack is realigned.");
657 BuildMI(MBB, MBBI, DL,
658 TII.get(Uses64BitFramePtr ? X86::AND64ri32 : X86::AND32ri), StackPtr)
661 .setMIFlag(MachineInstr::FrameSetup);
663 // The EFLAGS implicit def is dead.
664 MI->getOperand(3).setIsDead();
667 // If there is an SUB32ri of ESP immediately before this instruction, merge
668 // the two. This can be the case when tail call elimination is enabled and
669 // the callee has more arguments then the caller.
670 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
672 // If there is an ADD32ri or SUB32ri of ESP immediately after this
673 // instruction, merge the two instructions.
674 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
676 // Adjust stack pointer: ESP -= numbytes.
678 // Windows and cygwin/mingw require a prologue helper routine when allocating
679 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
680 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
681 // stack and adjust the stack pointer in one go. The 64-bit version of
682 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
683 // responsible for adjusting the stack pointer. Touching the stack at 4K
684 // increments is necessary to ensure that the guard pages used by the OS
685 // virtual memory manager are allocated in correct sequence.
686 if (NumBytes >= 4096 && STI.isOSWindows() && !STI.isTargetMacho()) {
687 const char *StackProbeSymbol;
690 getStackProbeFunction(STI, CallOp, StackProbeSymbol);
692 // Check whether EAX is livein for this function.
693 bool isEAXAlive = isEAXLiveIn(MF);
696 // Sanity check that EAX is not livein for this function.
697 // It should not be, so throw an assert.
698 assert(!Is64Bit && "EAX is livein in x64 case!");
701 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
702 .addReg(X86::EAX, RegState::Kill)
703 .setMIFlag(MachineInstr::FrameSetup);
707 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
708 // Function prologue is responsible for adjusting the stack pointer.
709 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
711 .setMIFlag(MachineInstr::FrameSetup);
713 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
714 // We'll also use 4 already allocated bytes for EAX.
715 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
716 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
717 .setMIFlag(MachineInstr::FrameSetup);
720 BuildMI(MBB, MBBI, DL,
722 .addExternalSymbol(StackProbeSymbol)
723 .addReg(StackPtr, RegState::Define | RegState::Implicit)
724 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
725 .setMIFlag(MachineInstr::FrameSetup);
728 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
729 // themself. It also does not clobber %rax so we can reuse it when
731 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), StackPtr)
734 .setMIFlag(MachineInstr::FrameSetup);
738 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
740 StackPtr, false, NumBytes - 4);
741 MI->setFlag(MachineInstr::FrameSetup);
742 MBB.insert(MBBI, MI);
744 } else if (NumBytes) {
745 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
746 UseLEA, TII, *RegInfo);
749 int SEHFrameOffset = 0;
752 // We need to set frame base offset low enough such that all saved
753 // register offsets would be positive relative to it, but we can't
754 // just use NumBytes, because .seh_setframe offset must be <=240.
755 // So we pretend to have only allocated enough space to spill the
756 // non-volatile registers.
757 // We don't care about the rest of stack allocation, because unwinder
758 // will restore SP to (BP - SEHFrameOffset)
759 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
760 int offset = MFI->getObjectOffset(Info.getFrameIdx());
761 SEHFrameOffset = std::max(SEHFrameOffset, abs(offset));
763 SEHFrameOffset += SEHFrameOffset % 16; // ensure alignmant
765 // This only needs to account for XMM spill slots, GPR slots
766 // are covered by the .seh_pushreg's emitted above.
767 unsigned Size = SEHFrameOffset - X86FI->getCalleeSavedFrameSize();
769 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
771 .setMIFlag(MachineInstr::FrameSetup);
774 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
776 .addImm(SEHFrameOffset)
777 .setMIFlag(MachineInstr::FrameSetup);
779 // SP will be the base register for restoring XMMs
781 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
783 .setMIFlag(MachineInstr::FrameSetup);
788 // Skip the rest of register spilling code
789 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
792 // Emit SEH info for non-GPRs
794 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
795 unsigned Reg = Info.getReg();
796 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
798 assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
800 int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
801 Offset += SEHFrameOffset;
803 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
806 .setMIFlag(MachineInstr::FrameSetup);
809 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
810 .setMIFlag(MachineInstr::FrameSetup);
813 // If we need a base pointer, set it up here. It's whatever the value
814 // of the stack pointer is at this point. Any variable size objects
815 // will be allocated after this, so we can still use the base pointer
816 // to reference locals.
817 if (RegInfo->hasBasePointer(MF)) {
818 // Update the base pointer with the current stack pointer.
819 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
820 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
822 .setMIFlag(MachineInstr::FrameSetup);
825 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
826 // Mark end of stack pointer adjustment.
827 if (!HasFP && NumBytes) {
828 // Define the current CFA rule to use the provided offset.
830 unsigned CFIIndex = MMI.addFrameInst(
831 MCCFIInstruction::createDefCfaOffset(nullptr,
832 -StackSize + stackGrowth));
834 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
835 .addCFIIndex(CFIIndex);
838 // Emit DWARF info specifying the offsets of the callee-saved registers.
840 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
844 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
845 MachineBasicBlock &MBB) const {
846 const MachineFrameInfo *MFI = MF.getFrameInfo();
847 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
848 const X86RegisterInfo *RegInfo =
849 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
850 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
851 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
852 assert(MBBI != MBB.end() && "Returning block has no instructions");
853 unsigned RetOpcode = MBBI->getOpcode();
854 DebugLoc DL = MBBI->getDebugLoc();
855 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
856 bool Is64Bit = STI.is64Bit();
857 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
858 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
859 const bool Is64BitILP32 = STI.isTarget64BitILP32();
860 bool UseLEA = STI.useLeaForSP();
861 unsigned StackAlign = getStackAlignment();
862 unsigned SlotSize = RegInfo->getSlotSize();
863 unsigned FramePtr = RegInfo->getFrameRegister(MF);
864 unsigned MachineFramePtr = Is64BitILP32 ?
865 getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
866 unsigned StackPtr = RegInfo->getStackRegister();
869 MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
870 ExceptionHandling::WinEH;
871 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
875 llvm_unreachable("Can only insert epilog into returning blocks");
880 case X86::TCRETURNdi:
881 case X86::TCRETURNri:
882 case X86::TCRETURNmi:
883 case X86::TCRETURNdi64:
884 case X86::TCRETURNri64:
885 case X86::TCRETURNmi64:
887 case X86::EH_RETURN64:
888 break; // These are ok
891 // Get the number of bytes to allocate from the FrameInfo.
892 uint64_t StackSize = MFI->getStackSize();
893 uint64_t MaxAlign = MFI->getMaxAlignment();
894 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
895 uint64_t NumBytes = 0;
897 // If we're forcing a stack realignment we can't rely on just the frame
898 // info, we need to know the ABI stack alignment as well in case we
899 // have a call out. Otherwise just make sure we have some alignment - we'll
900 // go with the minimum.
901 if (ForceStackAlign) {
903 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
905 MaxAlign = MaxAlign ? MaxAlign : 4;
909 // Calculate required stack adjustment.
910 uint64_t FrameSize = StackSize - SlotSize;
911 if (RegInfo->needsStackRealignment(MF)) {
912 // Callee-saved registers were pushed on stack before the stack
915 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
917 NumBytes = FrameSize - CSSize;
921 BuildMI(MBB, MBBI, DL,
922 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
924 NumBytes = StackSize - CSSize;
927 // Skip the callee-saved pop instructions.
928 while (MBBI != MBB.begin()) {
929 MachineBasicBlock::iterator PI = std::prev(MBBI);
930 unsigned Opc = PI->getOpcode();
932 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
938 MachineBasicBlock::iterator FirstCSPop = MBBI;
940 DL = MBBI->getDebugLoc();
942 // If there is an ADD32ri or SUB32ri of ESP immediately before this
943 // instruction, merge the two instructions.
944 if (NumBytes || MFI->hasVarSizedObjects())
945 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
947 // If dynamic alloca is used, then reset esp to point to the last callee-saved
948 // slot before popping them off! Same applies for the case, when stack was
950 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
951 if (RegInfo->needsStackRealignment(MF))
954 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
955 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
956 FramePtr, false, -CSSize);
959 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
960 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
964 } else if (NumBytes) {
965 // Adjust stack pointer back: ESP += numbytes.
966 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr, UseLEA,
971 // Windows unwinder will not invoke function's exception handler if IP is
972 // either in prologue or in epilogue. This behavior causes a problem when a
973 // call immediately precedes an epilogue, because the return address points
974 // into the epilogue. To cope with that, we insert an epilogue marker here,
975 // then replace it with a 'nop' if it ends up immediately after a CALL in the
976 // final emitted code.
978 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
980 // We're returning from function via eh_return.
981 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
982 MBBI = MBB.getLastNonDebugInstr();
983 MachineOperand &DestAddr = MBBI->getOperand(0);
984 assert(DestAddr.isReg() && "Offset should be in register!");
985 BuildMI(MBB, MBBI, DL,
986 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
987 StackPtr).addReg(DestAddr.getReg());
988 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
989 RetOpcode == X86::TCRETURNmi ||
990 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
991 RetOpcode == X86::TCRETURNmi64) {
992 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
993 // Tail call return: adjust the stack pointer and jump to callee.
994 MBBI = MBB.getLastNonDebugInstr();
995 MachineOperand &JumpTarget = MBBI->getOperand(0);
996 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
997 assert(StackAdjust.isImm() && "Expecting immediate value.");
999 // Adjust stack pointer.
1000 int StackAdj = StackAdjust.getImm();
1001 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1003 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1005 // Incoporate the retaddr area.
1006 Offset = StackAdj-MaxTCDelta;
1007 assert(Offset >= 0 && "Offset should never be negative");
1010 // Check for possible merge with preceding ADD instruction.
1011 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1012 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1013 UseLEA, TII, *RegInfo);
1016 // Jump to label or value in register.
1017 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1018 MachineInstrBuilder MIB =
1019 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1020 ? X86::TAILJMPd : X86::TAILJMPd64));
1021 if (JumpTarget.isGlobal())
1022 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1023 JumpTarget.getTargetFlags());
1025 assert(JumpTarget.isSymbol());
1026 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1027 JumpTarget.getTargetFlags());
1029 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1030 MachineInstrBuilder MIB =
1031 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1032 ? X86::TAILJMPm : X86::TAILJMPm64));
1033 for (unsigned i = 0; i != 5; ++i)
1034 MIB.addOperand(MBBI->getOperand(i));
1035 } else if (RetOpcode == X86::TCRETURNri64) {
1036 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1037 addReg(JumpTarget.getReg(), RegState::Kill);
1039 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1040 addReg(JumpTarget.getReg(), RegState::Kill);
1043 MachineInstr *NewMI = std::prev(MBBI);
1044 NewMI->copyImplicitOps(MF, MBBI);
1046 // Delete the pseudo instruction TCRETURN.
1048 } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
1049 RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
1050 (X86FI->getTCReturnAddrDelta() < 0)) {
1051 // Add the return addr area delta back since we are not tail calling.
1052 int delta = -1*X86FI->getTCReturnAddrDelta();
1053 MBBI = MBB.getLastNonDebugInstr();
1055 // Check for possible merge with preceding ADD instruction.
1056 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1057 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, Uses64BitFramePtr, UseLEA, TII,
1062 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1064 const X86RegisterInfo *RegInfo =
1065 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1066 const MachineFrameInfo *MFI = MF.getFrameInfo();
1067 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1068 uint64_t StackSize = MFI->getStackSize();
1070 if (RegInfo->hasBasePointer(MF)) {
1071 assert (hasFP(MF) && "VLAs and dynamic stack realign, but no FP?!");
1073 // Skip the saved EBP.
1074 return Offset + RegInfo->getSlotSize();
1076 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1077 return Offset + StackSize;
1079 } else if (RegInfo->needsStackRealignment(MF)) {
1081 // Skip the saved EBP.
1082 return Offset + RegInfo->getSlotSize();
1084 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1085 return Offset + StackSize;
1087 // FIXME: Support tail calls
1090 return Offset + StackSize;
1092 // Skip the saved EBP.
1093 Offset += RegInfo->getSlotSize();
1095 // Skip the RETADDR move area
1096 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1097 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1098 if (TailCallReturnAddrDelta < 0)
1099 Offset -= TailCallReturnAddrDelta;
1105 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1106 unsigned &FrameReg) const {
1107 const X86RegisterInfo *RegInfo =
1108 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1109 // We can't calculate offset from frame pointer if the stack is realigned,
1110 // so enforce usage of stack/base pointer. The base pointer is used when we
1111 // have dynamic allocas in addition to dynamic realignment.
1112 if (RegInfo->hasBasePointer(MF))
1113 FrameReg = RegInfo->getBaseRegister();
1114 else if (RegInfo->needsStackRealignment(MF))
1115 FrameReg = RegInfo->getStackRegister();
1117 FrameReg = RegInfo->getFrameRegister(MF);
1118 return getFrameIndexOffset(MF, FI);
1121 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1122 MachineFunction &MF, const TargetRegisterInfo *TRI,
1123 std::vector<CalleeSavedInfo> &CSI) const {
1124 MachineFrameInfo *MFI = MF.getFrameInfo();
1125 const X86RegisterInfo *RegInfo =
1126 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1127 unsigned SlotSize = RegInfo->getSlotSize();
1128 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1130 unsigned CalleeSavedFrameSize = 0;
1131 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1134 // emitPrologue always spills frame register the first thing.
1135 SpillSlotOffset -= SlotSize;
1136 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1138 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1139 // the frame register, we can delete it from CSI list and not have to worry
1140 // about avoiding it later.
1141 unsigned FPReg = RegInfo->getFrameRegister(MF);
1142 for (unsigned i = 0; i < CSI.size(); ++i) {
1143 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1144 CSI.erase(CSI.begin() + i);
1150 // Assign slots for GPRs. It increases frame size.
1151 for (unsigned i = CSI.size(); i != 0; --i) {
1152 unsigned Reg = CSI[i - 1].getReg();
1154 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1157 SpillSlotOffset -= SlotSize;
1158 CalleeSavedFrameSize += SlotSize;
1160 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1161 CSI[i - 1].setFrameIdx(SlotIndex);
1164 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1166 // Assign slots for XMMs.
1167 for (unsigned i = CSI.size(); i != 0; --i) {
1168 unsigned Reg = CSI[i - 1].getReg();
1169 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1172 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1174 SpillSlotOffset -= abs(SpillSlotOffset) % RC->getAlignment();
1176 SpillSlotOffset -= RC->getSize();
1178 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1179 CSI[i - 1].setFrameIdx(SlotIndex);
1180 MFI->ensureMaxAlignment(RC->getAlignment());
1186 bool X86FrameLowering::spillCalleeSavedRegisters(
1187 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1188 const std::vector<CalleeSavedInfo> &CSI,
1189 const TargetRegisterInfo *TRI) const {
1190 DebugLoc DL = MBB.findDebugLoc(MI);
1192 MachineFunction &MF = *MBB.getParent();
1193 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1194 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1196 // Push GPRs. It increases frame size.
1197 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1198 for (unsigned i = CSI.size(); i != 0; --i) {
1199 unsigned Reg = CSI[i - 1].getReg();
1201 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1203 // Add the callee-saved register as live-in. It's killed at the spill.
1206 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1207 .setMIFlag(MachineInstr::FrameSetup);
1210 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1211 // It can be done by spilling XMMs to stack frame.
1212 for (unsigned i = CSI.size(); i != 0; --i) {
1213 unsigned Reg = CSI[i-1].getReg();
1214 if (X86::GR64RegClass.contains(Reg) ||
1215 X86::GR32RegClass.contains(Reg))
1217 // Add the callee-saved register as live-in. It's killed at the spill.
1219 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1221 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1224 MI->setFlag(MachineInstr::FrameSetup);
1231 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1232 MachineBasicBlock::iterator MI,
1233 const std::vector<CalleeSavedInfo> &CSI,
1234 const TargetRegisterInfo *TRI) const {
1238 DebugLoc DL = MBB.findDebugLoc(MI);
1240 MachineFunction &MF = *MBB.getParent();
1241 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1242 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1244 // Reload XMMs from stack frame.
1245 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1246 unsigned Reg = CSI[i].getReg();
1247 if (X86::GR64RegClass.contains(Reg) ||
1248 X86::GR32RegClass.contains(Reg))
1251 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1252 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1256 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1257 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1258 unsigned Reg = CSI[i].getReg();
1259 if (!X86::GR64RegClass.contains(Reg) &&
1260 !X86::GR32RegClass.contains(Reg))
1263 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1269 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1270 RegScavenger *RS) const {
1271 MachineFrameInfo *MFI = MF.getFrameInfo();
1272 const X86RegisterInfo *RegInfo =
1273 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1274 unsigned SlotSize = RegInfo->getSlotSize();
1276 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1277 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1279 if (TailCallReturnAddrDelta < 0) {
1280 // create RETURNADDR area
1289 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1290 TailCallReturnAddrDelta - SlotSize, true);
1293 // Spill the BasePtr if it's used.
1294 if (RegInfo->hasBasePointer(MF))
1295 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1299 HasNestArgument(const MachineFunction *MF) {
1300 const Function *F = MF->getFunction();
1301 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1303 if (I->hasNestAttr())
1309 /// GetScratchRegister - Get a temp register for performing work in the
1310 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1311 /// and the properties of the function either one or two registers will be
1312 /// needed. Set primary to true for the first register, false for the second.
1314 GetScratchRegister(bool Is64Bit, const MachineFunction &MF, bool Primary) {
1315 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1318 if (CallingConvention == CallingConv::HiPE) {
1320 return Primary ? X86::R14 : X86::R13;
1322 return Primary ? X86::EBX : X86::EDI;
1326 return Primary ? X86::R11 : X86::R12;
1328 bool IsNested = HasNestArgument(&MF);
1330 if (CallingConvention == CallingConv::X86_FastCall ||
1331 CallingConvention == CallingConv::Fast) {
1333 report_fatal_error("Segmented stacks does not support fastcall with "
1334 "nested function.");
1335 return Primary ? X86::EAX : X86::ECX;
1338 return Primary ? X86::EDX : X86::EAX;
1339 return Primary ? X86::ECX : X86::EAX;
1342 // The stack limit in the TCB is set to this many bytes above the actual stack
1344 static const uint64_t kSplitStackAvailable = 256;
1347 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1348 MachineBasicBlock &prologueMBB = MF.front();
1349 MachineFrameInfo *MFI = MF.getFrameInfo();
1350 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1352 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1353 bool Is64Bit = STI.is64Bit();
1354 unsigned TlsReg, TlsOffset;
1357 unsigned ScratchReg = GetScratchRegister(Is64Bit, MF, true);
1358 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1359 "Scratch register is live-in");
1361 if (MF.getFunction()->isVarArg())
1362 report_fatal_error("Segmented stacks do not support vararg functions.");
1363 if (!STI.isTargetLinux() && !STI.isTargetDarwin() &&
1364 !STI.isTargetWin32() && !STI.isTargetWin64() && !STI.isTargetFreeBSD())
1365 report_fatal_error("Segmented stacks not supported on this platform.");
1367 // Eventually StackSize will be calculated by a link-time pass; which will
1368 // also decide whether checking code needs to be injected into this particular
1370 StackSize = MFI->getStackSize();
1372 // Do not generate a prologue for functions with a stack of size zero
1376 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1377 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1378 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1379 bool IsNested = false;
1381 // We need to know if the function has a nest argument only in 64 bit mode.
1383 IsNested = HasNestArgument(&MF);
1385 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1386 // allocMBB needs to be last (terminating) instruction.
1388 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1389 e = prologueMBB.livein_end(); i != e; i++) {
1390 allocMBB->addLiveIn(*i);
1391 checkMBB->addLiveIn(*i);
1395 allocMBB->addLiveIn(X86::R10);
1397 MF.push_front(allocMBB);
1398 MF.push_front(checkMBB);
1400 // When the frame size is less than 256 we just compare the stack
1401 // boundary directly to the value of the stack pointer, per gcc.
1402 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1404 // Read the limit off the current stacklet off the stack_guard location.
1406 if (STI.isTargetLinux()) {
1409 } else if (STI.isTargetDarwin()) {
1411 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1412 } else if (STI.isTargetWin64()) {
1414 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1415 } else if (STI.isTargetFreeBSD()) {
1419 report_fatal_error("Segmented stacks not supported on this platform.");
1422 if (CompareStackPointer)
1423 ScratchReg = X86::RSP;
1425 BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RSP)
1426 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1428 BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
1429 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1431 if (STI.isTargetLinux()) {
1434 } else if (STI.isTargetDarwin()) {
1436 TlsOffset = 0x48 + 90*4;
1437 } else if (STI.isTargetWin32()) {
1439 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1440 } else if (STI.isTargetFreeBSD()) {
1441 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1443 report_fatal_error("Segmented stacks not supported on this platform.");
1446 if (CompareStackPointer)
1447 ScratchReg = X86::ESP;
1449 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1450 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1452 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64()) {
1453 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1454 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1455 } else if (STI.isTargetDarwin()) {
1457 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1458 unsigned ScratchReg2;
1460 if (CompareStackPointer) {
1461 // The primary scratch register is available for holding the TLS offset.
1462 ScratchReg2 = GetScratchRegister(Is64Bit, MF, true);
1463 SaveScratch2 = false;
1465 // Need to use a second register to hold the TLS offset
1466 ScratchReg2 = GetScratchRegister(Is64Bit, MF, false);
1468 // Unfortunately, with fastcc the second scratch register may hold an
1470 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1473 // If Scratch2 is live-in then it needs to be saved.
1474 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1475 "Scratch register is live-in and not saved");
1478 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1479 .addReg(ScratchReg2, RegState::Kill);
1481 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1483 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1485 .addReg(ScratchReg2).addImm(1).addReg(0)
1490 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1494 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1495 // It jumps to normal execution of the function body.
1496 BuildMI(checkMBB, DL, TII.get(X86::JA_4)).addMBB(&prologueMBB);
1498 // On 32 bit we first push the arguments size and then the frame size. On 64
1499 // bit, we pass the stack frame size in r10 and the argument size in r11.
1501 // Functions with nested arguments use R10, so it needs to be saved across
1502 // the call to _morestack
1505 BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::RAX).addReg(X86::R10);
1507 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R10)
1509 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R11)
1510 .addImm(X86FI->getArgumentStackSize());
1511 MF.getRegInfo().setPhysRegUsed(X86::R10);
1512 MF.getRegInfo().setPhysRegUsed(X86::R11);
1514 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1515 .addImm(X86FI->getArgumentStackSize());
1516 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1520 // __morestack is in libgcc
1522 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1523 .addExternalSymbol("__morestack");
1525 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1526 .addExternalSymbol("__morestack");
1529 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1531 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1533 allocMBB->addSuccessor(&prologueMBB);
1535 checkMBB->addSuccessor(allocMBB);
1536 checkMBB->addSuccessor(&prologueMBB);
1543 /// Erlang programs may need a special prologue to handle the stack size they
1544 /// might need at runtime. That is because Erlang/OTP does not implement a C
1545 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1546 /// (for more information see Eric Stenman's Ph.D. thesis:
1547 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1550 /// temp0 = sp - MaxStack
1551 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1555 /// call inc_stack # doubles the stack space
1556 /// temp0 = sp - MaxStack
1557 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1558 void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
1559 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1560 MachineFrameInfo *MFI = MF.getFrameInfo();
1561 const unsigned SlotSize =
1562 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo())
1564 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1565 const bool Is64Bit = STI.is64Bit();
1567 // HiPE-specific values
1568 const unsigned HipeLeafWords = 24;
1569 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1570 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1571 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1572 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1573 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1575 assert(STI.isTargetLinux() &&
1576 "HiPE prologue is only supported on Linux operating systems.");
1578 // Compute the largest caller's frame that is needed to fit the callees'
1579 // frames. This 'MaxStack' is computed from:
1581 // a) the fixed frame size, which is the space needed for all spilled temps,
1582 // b) outgoing on-stack parameter areas, and
1583 // c) the minimum stack space this function needs to make available for the
1584 // functions it calls (a tunable ABI property).
1585 if (MFI->hasCalls()) {
1586 unsigned MoreStackForCalls = 0;
1588 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1589 MBBI != MBBE; ++MBBI)
1590 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1595 // Get callee operand.
1596 const MachineOperand &MO = MI->getOperand(0);
1598 // Only take account of global function calls (no closures etc.).
1602 const Function *F = dyn_cast<Function>(MO.getGlobal());
1606 // Do not update 'MaxStack' for primitive and built-in functions
1607 // (encoded with names either starting with "erlang."/"bif_" or not
1608 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1609 // "_", such as the BIF "suspend_0") as they are executed on another
1611 if (F->getName().find("erlang.") != StringRef::npos ||
1612 F->getName().find("bif_") != StringRef::npos ||
1613 F->getName().find_first_of("._") == StringRef::npos)
1616 unsigned CalleeStkArity =
1617 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1618 if (HipeLeafWords - 1 > CalleeStkArity)
1619 MoreStackForCalls = std::max(MoreStackForCalls,
1620 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1622 MaxStack += MoreStackForCalls;
1625 // If the stack frame needed is larger than the guaranteed then runtime checks
1626 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1627 if (MaxStack > Guaranteed) {
1628 MachineBasicBlock &prologueMBB = MF.front();
1629 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1630 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1632 for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
1633 E = prologueMBB.livein_end(); I != E; I++) {
1634 stackCheckMBB->addLiveIn(*I);
1635 incStackMBB->addLiveIn(*I);
1638 MF.push_front(incStackMBB);
1639 MF.push_front(stackCheckMBB);
1641 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1642 unsigned LEAop, CMPop, CALLop;
1646 LEAop = X86::LEA64r;
1647 CMPop = X86::CMP64rm;
1648 CALLop = X86::CALL64pcrel32;
1649 SPLimitOffset = 0x90;
1653 LEAop = X86::LEA32r;
1654 CMPop = X86::CMP32rm;
1655 CALLop = X86::CALLpcrel32;
1656 SPLimitOffset = 0x4c;
1659 ScratchReg = GetScratchRegister(Is64Bit, MF, true);
1660 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1661 "HiPE prologue scratch register is live-in");
1663 // Create new MBB for StackCheck:
1664 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1665 SPReg, false, -MaxStack);
1666 // SPLimitOffset is in a fixed heap location (pointed by BP).
1667 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1668 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1669 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_4)).addMBB(&prologueMBB);
1671 // Create new MBB for IncStack:
1672 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1673 addExternalSymbol("inc_stack_0");
1674 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1675 SPReg, false, -MaxStack);
1676 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1677 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1678 BuildMI(incStackMBB, DL, TII.get(X86::JLE_4)).addMBB(incStackMBB);
1680 stackCheckMBB->addSuccessor(&prologueMBB, 99);
1681 stackCheckMBB->addSuccessor(incStackMBB, 1);
1682 incStackMBB->addSuccessor(&prologueMBB, 99);
1683 incStackMBB->addSuccessor(incStackMBB, 1);
1690 void X86FrameLowering::
1691 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1692 MachineBasicBlock::iterator I) const {
1693 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1694 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
1695 MF.getSubtarget().getRegisterInfo());
1696 unsigned StackPtr = RegInfo.getStackRegister();
1697 bool reseveCallFrame = hasReservedCallFrame(MF);
1698 int Opcode = I->getOpcode();
1699 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1700 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1701 bool IsLP64 = STI.isTarget64BitLP64();
1702 DebugLoc DL = I->getDebugLoc();
1703 uint64_t Amount = !reseveCallFrame ? I->getOperand(0).getImm() : 0;
1704 uint64_t CalleeAmt = isDestroy ? I->getOperand(1).getImm() : 0;
1707 if (!reseveCallFrame) {
1708 // If the stack pointer can be changed after prologue, turn the
1709 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1710 // adjcallstackdown instruction into 'add ESP, <amt>'
1711 // TODO: consider using push / pop instead of sub + store / add
1715 // We need to keep the stack aligned properly. To do this, we round the
1716 // amount of space needed for the outgoing arguments up to the next
1717 // alignment boundary.
1718 unsigned StackAlign = MF.getTarget()
1720 ->getFrameLowering()
1721 ->getStackAlignment();
1722 Amount = (Amount + StackAlign - 1) / StackAlign * StackAlign;
1724 MachineInstr *New = nullptr;
1725 if (Opcode == TII.getCallFrameSetupOpcode()) {
1726 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)),
1731 assert(Opcode == TII.getCallFrameDestroyOpcode());
1733 // Factor out the amount the callee already popped.
1734 Amount -= CalleeAmt;
1737 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1738 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1739 .addReg(StackPtr).addImm(Amount);
1744 // The EFLAGS implicit def is dead.
1745 New->getOperand(3).setIsDead();
1747 // Replace the pseudo instruction with a new instruction.
1754 if (Opcode == TII.getCallFrameDestroyOpcode() && CalleeAmt) {
1755 // If we are performing frame pointer elimination and if the callee pops
1756 // something off the stack pointer, add it back. We do this until we have
1757 // more advanced stack pointer tracking ability.
1758 unsigned Opc = getSUBriOpcode(IsLP64, CalleeAmt);
1759 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1760 .addReg(StackPtr).addImm(CalleeAmt);
1762 // The EFLAGS implicit def is dead.
1763 New->getOperand(3).setIsDead();
1765 // We are not tracking the stack pointer adjustment by the callee, so make
1766 // sure we restore the stack pointer immediately after the call, there may
1767 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1768 MachineBasicBlock::iterator B = MBB.begin();
1769 while (I != B && !std::prev(I)->isCall())