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 getANDriOpcode(bool IsLP64, int64_t Imm) {
89 return X86::AND64ri32;
96 static unsigned getPUSHiOpcode(bool IsLP64, MachineOperand MO) {
97 // We don't support LP64 for now.
100 if (MO.isImm() && isInt<8>(MO.getImm()))
101 return X86::PUSH32i8;
103 return X86::PUSHi32;;
106 static unsigned getLEArOpcode(unsigned IsLP64) {
107 return IsLP64 ? X86::LEA64r : X86::LEA32r;
110 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
111 /// when it reaches the "return" instruction. We can then pop a stack object
112 /// to this register without worry about clobbering it.
113 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
114 MachineBasicBlock::iterator &MBBI,
115 const TargetRegisterInfo &TRI,
117 const MachineFunction *MF = MBB.getParent();
118 const Function *F = MF->getFunction();
119 if (!F || MF->getMMI().callsEHReturn())
122 static const uint16_t CallerSavedRegs32Bit[] = {
123 X86::EAX, X86::EDX, X86::ECX, 0
126 static const uint16_t CallerSavedRegs64Bit[] = {
127 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
128 X86::R8, X86::R9, X86::R10, X86::R11, 0
131 unsigned Opc = MBBI->getOpcode();
138 case X86::TCRETURNdi:
139 case X86::TCRETURNri:
140 case X86::TCRETURNmi:
141 case X86::TCRETURNdi64:
142 case X86::TCRETURNri64:
143 case X86::TCRETURNmi64:
145 case X86::EH_RETURN64: {
146 SmallSet<uint16_t, 8> Uses;
147 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
148 MachineOperand &MO = MBBI->getOperand(i);
149 if (!MO.isReg() || MO.isDef())
151 unsigned Reg = MO.getReg();
154 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
158 const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
160 if (!Uses.count(*CS))
169 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
170 /// stack pointer by a constant value.
172 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
173 unsigned StackPtr, int64_t NumBytes,
174 bool Is64BitTarget, bool Is64BitStackPtr, bool UseLEA,
175 const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
176 bool isSub = NumBytes < 0;
177 uint64_t Offset = isSub ? -NumBytes : NumBytes;
180 Opc = getLEArOpcode(Is64BitStackPtr);
183 ? getSUBriOpcode(Is64BitStackPtr, Offset)
184 : getADDriOpcode(Is64BitStackPtr, Offset);
186 uint64_t Chunk = (1LL << 31) - 1;
187 DebugLoc DL = MBB.findDebugLoc(MBBI);
190 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
191 if (ThisVal == (Is64BitTarget ? 8 : 4)) {
192 // Use push / pop instead.
194 ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
195 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
198 ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
199 : (Is64BitTarget ? X86::POP64r : X86::POP32r);
200 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
201 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
203 MI->setFlag(MachineInstr::FrameSetup);
209 MachineInstr *MI = nullptr;
212 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
213 StackPtr, false, isSub ? -ThisVal : ThisVal);
215 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
218 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
222 MI->setFlag(MachineInstr::FrameSetup);
228 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
230 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
231 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
232 if (MBBI == MBB.begin()) return;
234 MachineBasicBlock::iterator PI = std::prev(MBBI);
235 unsigned Opc = PI->getOpcode();
236 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
237 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
238 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
239 PI->getOperand(0).getReg() == StackPtr) {
241 *NumBytes += PI->getOperand(2).getImm();
243 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
244 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
245 PI->getOperand(0).getReg() == StackPtr) {
247 *NumBytes -= PI->getOperand(2).getImm();
252 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
255 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
256 MachineBasicBlock::iterator &MBBI,
257 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
258 // FIXME: THIS ISN'T RUN!!!
261 if (MBBI == MBB.end()) return;
263 MachineBasicBlock::iterator NI = std::next(MBBI);
264 if (NI == MBB.end()) return;
266 unsigned Opc = NI->getOpcode();
267 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
268 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
269 NI->getOperand(0).getReg() == StackPtr) {
271 *NumBytes -= NI->getOperand(2).getImm();
274 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
275 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
276 NI->getOperand(0).getReg() == StackPtr) {
278 *NumBytes += NI->getOperand(2).getImm();
284 /// mergeSPUpdates - Checks the instruction before/after the passed
285 /// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
286 /// the stack adjustment is returned as a positive value for ADD/LEA and a
287 /// negative for SUB.
288 static int mergeSPUpdates(MachineBasicBlock &MBB,
289 MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
290 bool doMergeWithPrevious) {
291 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
292 (!doMergeWithPrevious && MBBI == MBB.end()))
295 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
296 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
298 unsigned Opc = PI->getOpcode();
301 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
302 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
303 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
304 PI->getOperand(0).getReg() == StackPtr){
305 Offset += PI->getOperand(2).getImm();
307 if (!doMergeWithPrevious) MBBI = NI;
308 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
309 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
310 PI->getOperand(0).getReg() == StackPtr) {
311 Offset -= PI->getOperand(2).getImm();
313 if (!doMergeWithPrevious) MBBI = NI;
319 static bool isEAXLiveIn(MachineFunction &MF) {
320 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
321 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
322 unsigned Reg = II->first;
324 if (Reg == X86::EAX || Reg == X86::AX ||
325 Reg == X86::AH || Reg == X86::AL)
333 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
334 MachineBasicBlock::iterator MBBI,
336 MachineFunction &MF = *MBB.getParent();
337 MachineFrameInfo *MFI = MF.getFrameInfo();
338 MachineModuleInfo &MMI = MF.getMMI();
339 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
340 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
342 // Add callee saved registers to move list.
343 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
344 if (CSI.empty()) return;
346 // Calculate offsets.
347 for (std::vector<CalleeSavedInfo>::const_iterator
348 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
349 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
350 unsigned Reg = I->getReg();
352 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
354 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
356 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
357 .addCFIIndex(CFIIndex);
361 /// usesTheStack - This function checks if any of the users of EFLAGS
362 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
363 /// to use the stack, and if we don't adjust the stack we clobber the first
365 /// See X86InstrInfo::copyPhysReg.
366 static bool usesTheStack(const MachineFunction &MF) {
367 const MachineRegisterInfo &MRI = MF.getRegInfo();
369 for (MachineRegisterInfo::reg_instr_iterator
370 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
378 void X86FrameLowering::getStackProbeFunction(const X86Subtarget &STI,
380 const char *&Symbol) {
381 CallOp = STI.is64Bit() ? X86::W64ALLOCA : X86::CALLpcrel32;
384 if (STI.isTargetCygMing()) {
385 Symbol = "___chkstk_ms";
389 } else if (STI.isTargetCygMing())
395 /// emitPrologue - Push callee-saved registers onto the stack, which
396 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
397 /// space for local variables. Also emit labels used by the exception handler to
398 /// generate the exception handling frames.
401 Here's a gist of what gets emitted:
403 ; Establish frame pointer, if needed
406 .cfi_def_cfa_offset 16
407 .cfi_offset %rbp, -16
410 .cfi_def_cfa_register %rbp
412 ; Spill general-purpose registers
413 [for all callee-saved GPRs]
416 .cfi_def_cfa_offset (offset from RETADDR)
419 ; If the required stack alignment > default stack alignment
420 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
421 ; of unknown size in the stack frame.
422 [if stack needs re-alignment]
425 ; Allocate space for locals
426 [if target is Windows and allocated space > 4096 bytes]
427 ; Windows needs special care for allocations larger
430 call ___chkstk_ms/___chkstk
436 .seh_stackalloc (size of XMM spill slots)
437 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
442 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
443 ; they may get spilled on any platform, if the current function
444 ; calls @llvm.eh.unwind.init
446 [for all callee-saved XMM registers]
447 movaps %<xmm reg>, -MMM(%rbp)
448 [for all callee-saved XMM registers]
449 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
450 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
452 [for all callee-saved XMM registers]
453 movaps %<xmm reg>, KKK(%rsp)
454 [for all callee-saved XMM registers]
455 .seh_savexmm %<xmm reg>, KKK
459 [if needs base pointer]
461 [if needs to restore base pointer]
466 [for all callee-saved registers]
467 .cfi_offset %<reg>, (offset from %rbp)
469 .cfi_def_cfa_offset (offset from RETADDR)
470 [for all callee-saved registers]
471 .cfi_offset %<reg>, (offset from %rsp)
474 - .seh directives are emitted only for Windows 64 ABI
475 - .cfi directives are emitted for all other ABIs
476 - for 32-bit code, substitute %e?? registers for %r??
479 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
480 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
481 MachineBasicBlock::iterator MBBI = MBB.begin();
482 MachineFrameInfo *MFI = MF.getFrameInfo();
483 const Function *Fn = MF.getFunction();
484 const X86RegisterInfo *RegInfo =
485 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
486 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
487 MachineModuleInfo &MMI = MF.getMMI();
488 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
489 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
490 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
491 bool HasFP = hasFP(MF);
492 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
493 bool Is64Bit = STI.is64Bit();
494 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
495 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
496 bool IsWin64 = STI.isTargetWin64();
497 // Not necessarily synonymous with IsWin64.
498 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
499 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
501 !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
502 bool UseLEA = STI.useLeaForSP();
503 unsigned StackAlign = getStackAlignment();
504 unsigned SlotSize = RegInfo->getSlotSize();
505 unsigned FramePtr = RegInfo->getFrameRegister(MF);
506 const unsigned MachineFramePtr = STI.isTarget64BitILP32() ?
507 getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
508 unsigned StackPtr = RegInfo->getStackRegister();
509 unsigned BasePtr = RegInfo->getBaseRegister();
512 // If we're forcing a stack realignment we can't rely on just the frame
513 // info, we need to know the ABI stack alignment as well in case we
514 // have a call out. Otherwise just make sure we have some alignment - we'll
515 // go with the minimum SlotSize.
516 if (ForceStackAlign) {
518 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
519 else if (MaxAlign < SlotSize)
523 // Add RETADDR move area to callee saved frame size.
524 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
525 if (TailCallReturnAddrDelta < 0)
526 X86FI->setCalleeSavedFrameSize(
527 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
529 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
531 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
532 // function, and use up to 128 bytes of stack space, don't have a frame
533 // pointer, calls, or dynamic alloca then we do not need to adjust the
534 // stack pointer (we fit in the Red Zone). We also check that we don't
535 // push and pop from the stack.
536 if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
537 Attribute::NoRedZone) &&
538 !RegInfo->needsStackRealignment(MF) &&
539 !MFI->hasVarSizedObjects() && // No dynamic alloca.
540 !MFI->adjustsStack() && // No calls.
541 !IsWin64 && // Win64 has no Red Zone
542 !usesTheStack(MF) && // Don't push and pop.
543 !MF.shouldSplitStack()) { // Regular stack
544 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
545 if (HasFP) MinSize += SlotSize;
546 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
547 MFI->setStackSize(StackSize);
550 // Insert stack pointer adjustment for later moving of return addr. Only
551 // applies to tail call optimized functions where the callee argument stack
552 // size is bigger than the callers.
553 if (TailCallReturnAddrDelta < 0) {
555 BuildMI(MBB, MBBI, DL,
556 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
559 .addImm(-TailCallReturnAddrDelta)
560 .setMIFlag(MachineInstr::FrameSetup);
561 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
564 // Mapping for machine moves:
566 // DST: VirtualFP AND
567 // SRC: VirtualFP => DW_CFA_def_cfa_offset
568 // ELSE => DW_CFA_def_cfa
570 // SRC: VirtualFP AND
571 // DST: Register => DW_CFA_def_cfa_register
574 // OFFSET < 0 => DW_CFA_offset_extended_sf
575 // REG < 64 => DW_CFA_offset + Reg
576 // ELSE => DW_CFA_offset_extended
578 uint64_t NumBytes = 0;
579 int stackGrowth = -SlotSize;
582 // Calculate required stack adjustment.
583 uint64_t FrameSize = StackSize - SlotSize;
584 // If required, include space for extra hidden slot for stashing base pointer.
585 if (X86FI->getRestoreBasePointer())
586 FrameSize += SlotSize;
587 if (RegInfo->needsStackRealignment(MF)) {
588 // Callee-saved registers are pushed on stack before the stack
590 FrameSize -= X86FI->getCalleeSavedFrameSize();
591 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
593 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
596 // Get the offset of the stack slot for the EBP register, which is
597 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
598 // Update the frame offset adjustment.
599 MFI->setOffsetAdjustment(-NumBytes);
601 // Save EBP/RBP into the appropriate stack slot.
602 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
603 .addReg(MachineFramePtr, RegState::Kill)
604 .setMIFlag(MachineInstr::FrameSetup);
607 // Mark the place where EBP/RBP was saved.
608 // Define the current CFA rule to use the provided offset.
610 unsigned CFIIndex = MMI.addFrameInst(
611 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
612 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
613 .addCFIIndex(CFIIndex);
615 // Change the rule for the FramePtr to be an "offset" rule.
616 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
617 CFIIndex = MMI.addFrameInst(
618 MCCFIInstruction::createOffset(nullptr,
619 DwarfFramePtr, 2 * stackGrowth));
620 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
621 .addCFIIndex(CFIIndex);
625 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
627 .setMIFlag(MachineInstr::FrameSetup);
630 // Update EBP with the new base value.
631 BuildMI(MBB, MBBI, DL,
632 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), FramePtr)
634 .setMIFlag(MachineInstr::FrameSetup);
637 // Mark effective beginning of when frame pointer becomes valid.
638 // Define the current CFA to use the EBP/RBP register.
639 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
640 unsigned CFIIndex = MMI.addFrameInst(
641 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
642 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
643 .addCFIIndex(CFIIndex);
646 // Mark the FramePtr as live-in in every block.
647 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
648 I->addLiveIn(MachineFramePtr);
650 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
653 // Skip the callee-saved push instructions.
654 bool PushedRegs = false;
655 int StackOffset = 2 * stackGrowth;
657 while (MBBI != MBB.end() &&
658 (MBBI->getOpcode() == X86::PUSH32r ||
659 MBBI->getOpcode() == X86::PUSH64r)) {
661 unsigned Reg = MBBI->getOperand(0).getReg();
664 if (!HasFP && NeedsDwarfCFI) {
665 // Mark callee-saved push instruction.
666 // Define the current CFA rule to use the provided offset.
668 unsigned CFIIndex = MMI.addFrameInst(
669 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
670 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
671 .addCFIIndex(CFIIndex);
672 StackOffset += stackGrowth;
676 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
677 MachineInstr::FrameSetup);
681 // Realign stack after we pushed callee-saved registers (so that we'll be
682 // able to calculate their offsets from the frame pointer).
683 if (RegInfo->needsStackRealignment(MF)) {
684 assert(HasFP && "There should be a frame pointer if stack is realigned.");
685 uint64_t Val = -MaxAlign;
687 BuildMI(MBB, MBBI, DL,
688 TII.get(getANDriOpcode(Uses64BitFramePtr, Val)), StackPtr)
691 .setMIFlag(MachineInstr::FrameSetup);
693 // The EFLAGS implicit def is dead.
694 MI->getOperand(3).setIsDead();
697 // If there is an SUB32ri of ESP immediately before this instruction, merge
698 // the two. This can be the case when tail call elimination is enabled and
699 // the callee has more arguments then the caller.
700 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
702 // If there is an ADD32ri or SUB32ri of ESP immediately after this
703 // instruction, merge the two instructions.
704 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
706 // Adjust stack pointer: ESP -= numbytes.
708 static const size_t PageSize = 4096;
710 // Windows and cygwin/mingw require a prologue helper routine when allocating
711 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
712 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
713 // stack and adjust the stack pointer in one go. The 64-bit version of
714 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
715 // responsible for adjusting the stack pointer. Touching the stack at 4K
716 // increments is necessary to ensure that the guard pages used by the OS
717 // virtual memory manager are allocated in correct sequence.
718 if (NumBytes >= PageSize && UseStackProbe) {
719 const char *StackProbeSymbol;
722 getStackProbeFunction(STI, CallOp, StackProbeSymbol);
724 // Check whether EAX is livein for this function.
725 bool isEAXAlive = isEAXLiveIn(MF);
728 // Sanity check that EAX is not livein for this function.
729 // It should not be, so throw an assert.
730 assert(!Is64Bit && "EAX is livein in x64 case!");
733 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
734 .addReg(X86::EAX, RegState::Kill)
735 .setMIFlag(MachineInstr::FrameSetup);
739 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
740 // Function prologue is responsible for adjusting the stack pointer.
741 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
743 .setMIFlag(MachineInstr::FrameSetup);
745 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
746 // We'll also use 4 already allocated bytes for EAX.
747 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
748 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
749 .setMIFlag(MachineInstr::FrameSetup);
752 BuildMI(MBB, MBBI, DL,
754 .addExternalSymbol(StackProbeSymbol)
755 .addReg(StackPtr, RegState::Define | RegState::Implicit)
756 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
757 .setMIFlag(MachineInstr::FrameSetup);
760 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
761 // themself. It also does not clobber %rax so we can reuse it when
763 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), StackPtr)
766 .setMIFlag(MachineInstr::FrameSetup);
770 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
772 StackPtr, false, NumBytes - 4);
773 MI->setFlag(MachineInstr::FrameSetup);
774 MBB.insert(MBBI, MI);
776 } else if (NumBytes) {
777 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
778 UseLEA, TII, *RegInfo);
781 int SEHFrameOffset = 0;
784 // We need to set frame base offset low enough such that all saved
785 // register offsets would be positive relative to it, but we can't
786 // just use NumBytes, because .seh_setframe offset must be <=240.
787 // So we pretend to have only allocated enough space to spill the
788 // non-volatile registers.
789 // We don't care about the rest of stack allocation, because unwinder
790 // will restore SP to (BP - SEHFrameOffset)
791 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
792 int offset = MFI->getObjectOffset(Info.getFrameIdx());
793 SEHFrameOffset = std::max(SEHFrameOffset, std::abs(offset));
795 SEHFrameOffset += SEHFrameOffset % 16; // ensure alignmant
797 // This only needs to account for XMM spill slots, GPR slots
798 // are covered by the .seh_pushreg's emitted above.
799 unsigned Size = SEHFrameOffset - X86FI->getCalleeSavedFrameSize();
801 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
803 .setMIFlag(MachineInstr::FrameSetup);
806 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
808 .addImm(SEHFrameOffset)
809 .setMIFlag(MachineInstr::FrameSetup);
811 // SP will be the base register for restoring XMMs
813 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
815 .setMIFlag(MachineInstr::FrameSetup);
820 // Skip the rest of register spilling code
821 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
824 // Emit SEH info for non-GPRs
826 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
827 unsigned Reg = Info.getReg();
828 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
830 assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
832 int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
833 Offset += SEHFrameOffset;
835 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
838 .setMIFlag(MachineInstr::FrameSetup);
841 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
842 .setMIFlag(MachineInstr::FrameSetup);
845 // If we need a base pointer, set it up here. It's whatever the value
846 // of the stack pointer is at this point. Any variable size objects
847 // will be allocated after this, so we can still use the base pointer
848 // to reference locals.
849 if (RegInfo->hasBasePointer(MF)) {
850 // Update the base pointer with the current stack pointer.
851 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
852 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
854 .setMIFlag(MachineInstr::FrameSetup);
855 if (X86FI->getRestoreBasePointer()) {
856 // Stash value of base pointer. Saving RSP instead of EBP shortens dependence chain.
857 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
858 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
859 FramePtr, true, X86FI->getRestoreBasePointerOffset())
861 .setMIFlag(MachineInstr::FrameSetup);
865 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
866 // Mark end of stack pointer adjustment.
867 if (!HasFP && NumBytes) {
868 // Define the current CFA rule to use the provided offset.
870 unsigned CFIIndex = MMI.addFrameInst(
871 MCCFIInstruction::createDefCfaOffset(nullptr,
872 -StackSize + stackGrowth));
874 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
875 .addCFIIndex(CFIIndex);
878 // Emit DWARF info specifying the offsets of the callee-saved registers.
880 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
884 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
885 MachineBasicBlock &MBB) const {
886 const MachineFrameInfo *MFI = MF.getFrameInfo();
887 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
888 const X86RegisterInfo *RegInfo =
889 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
890 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
891 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
892 assert(MBBI != MBB.end() && "Returning block has no instructions");
893 unsigned RetOpcode = MBBI->getOpcode();
894 DebugLoc DL = MBBI->getDebugLoc();
895 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
896 bool Is64Bit = STI.is64Bit();
897 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
898 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
899 const bool Is64BitILP32 = STI.isTarget64BitILP32();
900 bool UseLEA = STI.useLeaForSP();
901 unsigned StackAlign = getStackAlignment();
902 unsigned SlotSize = RegInfo->getSlotSize();
903 unsigned FramePtr = RegInfo->getFrameRegister(MF);
904 unsigned MachineFramePtr = Is64BitILP32 ?
905 getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
906 unsigned StackPtr = RegInfo->getStackRegister();
908 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
909 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
913 llvm_unreachable("Can only insert epilog into returning blocks");
918 case X86::TCRETURNdi:
919 case X86::TCRETURNri:
920 case X86::TCRETURNmi:
921 case X86::TCRETURNdi64:
922 case X86::TCRETURNri64:
923 case X86::TCRETURNmi64:
925 case X86::EH_RETURN64:
926 break; // These are ok
929 // Get the number of bytes to allocate from the FrameInfo.
930 uint64_t StackSize = MFI->getStackSize();
931 uint64_t MaxAlign = MFI->getMaxAlignment();
932 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
933 uint64_t NumBytes = 0;
935 // If we're forcing a stack realignment we can't rely on just the frame
936 // info, we need to know the ABI stack alignment as well in case we
937 // have a call out. Otherwise just make sure we have some alignment - we'll
938 // go with the minimum.
939 if (ForceStackAlign) {
941 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
943 MaxAlign = MaxAlign ? MaxAlign : 4;
947 // Calculate required stack adjustment.
948 uint64_t FrameSize = StackSize - SlotSize;
949 if (RegInfo->needsStackRealignment(MF)) {
950 // Callee-saved registers were pushed on stack before the stack
953 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
955 NumBytes = FrameSize - CSSize;
959 BuildMI(MBB, MBBI, DL,
960 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
962 NumBytes = StackSize - CSSize;
965 // Skip the callee-saved pop instructions.
966 while (MBBI != MBB.begin()) {
967 MachineBasicBlock::iterator PI = std::prev(MBBI);
968 unsigned Opc = PI->getOpcode();
970 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
976 MachineBasicBlock::iterator FirstCSPop = MBBI;
978 DL = MBBI->getDebugLoc();
980 // If there is an ADD32ri or SUB32ri of ESP immediately before this
981 // instruction, merge the two instructions.
982 if (NumBytes || MFI->hasVarSizedObjects())
983 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
985 // If dynamic alloca is used, then reset esp to point to the last callee-saved
986 // slot before popping them off! Same applies for the case, when stack was
988 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
989 if (RegInfo->needsStackRealignment(MF))
992 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
993 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
994 FramePtr, false, -CSSize);
997 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
998 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1002 } else if (NumBytes) {
1003 // Adjust stack pointer back: ESP += numbytes.
1004 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr, UseLEA,
1009 // Windows unwinder will not invoke function's exception handler if IP is
1010 // either in prologue or in epilogue. This behavior causes a problem when a
1011 // call immediately precedes an epilogue, because the return address points
1012 // into the epilogue. To cope with that, we insert an epilogue marker here,
1013 // then replace it with a 'nop' if it ends up immediately after a CALL in the
1014 // final emitted code.
1016 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1018 // We're returning from function via eh_return.
1019 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
1020 MBBI = MBB.getLastNonDebugInstr();
1021 MachineOperand &DestAddr = MBBI->getOperand(0);
1022 assert(DestAddr.isReg() && "Offset should be in register!");
1023 BuildMI(MBB, MBBI, DL,
1024 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
1025 StackPtr).addReg(DestAddr.getReg());
1026 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1027 RetOpcode == X86::TCRETURNmi ||
1028 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1029 RetOpcode == X86::TCRETURNmi64) {
1030 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1031 // Tail call return: adjust the stack pointer and jump to callee.
1032 MBBI = MBB.getLastNonDebugInstr();
1033 MachineOperand &JumpTarget = MBBI->getOperand(0);
1034 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1035 assert(StackAdjust.isImm() && "Expecting immediate value.");
1037 // Adjust stack pointer.
1038 int StackAdj = StackAdjust.getImm();
1039 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1041 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1043 // Incoporate the retaddr area.
1044 Offset = StackAdj-MaxTCDelta;
1045 assert(Offset >= 0 && "Offset should never be negative");
1048 // Check for possible merge with preceding ADD instruction.
1049 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1050 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1051 UseLEA, TII, *RegInfo);
1054 // Jump to label or value in register.
1055 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1056 MachineInstrBuilder MIB =
1057 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1058 ? X86::TAILJMPd : X86::TAILJMPd64));
1059 if (JumpTarget.isGlobal())
1060 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1061 JumpTarget.getTargetFlags());
1063 assert(JumpTarget.isSymbol());
1064 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1065 JumpTarget.getTargetFlags());
1067 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1068 MachineInstrBuilder MIB =
1069 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1070 ? X86::TAILJMPm : X86::TAILJMPm64));
1071 for (unsigned i = 0; i != 5; ++i)
1072 MIB.addOperand(MBBI->getOperand(i));
1073 } else if (RetOpcode == X86::TCRETURNri64) {
1074 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1075 addReg(JumpTarget.getReg(), RegState::Kill);
1077 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1078 addReg(JumpTarget.getReg(), RegState::Kill);
1081 MachineInstr *NewMI = std::prev(MBBI);
1082 NewMI->copyImplicitOps(MF, MBBI);
1084 // Delete the pseudo instruction TCRETURN.
1086 } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
1087 RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
1088 (X86FI->getTCReturnAddrDelta() < 0)) {
1089 // Add the return addr area delta back since we are not tail calling.
1090 int delta = -1*X86FI->getTCReturnAddrDelta();
1091 MBBI = MBB.getLastNonDebugInstr();
1093 // Check for possible merge with preceding ADD instruction.
1094 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1095 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, Uses64BitFramePtr, UseLEA, TII,
1100 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1102 const X86RegisterInfo *RegInfo =
1103 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1104 const MachineFrameInfo *MFI = MF.getFrameInfo();
1105 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1106 uint64_t StackSize = MFI->getStackSize();
1108 if (RegInfo->hasBasePointer(MF)) {
1109 assert (hasFP(MF) && "VLAs and dynamic stack realign, but no FP?!");
1111 // Skip the saved EBP.
1112 return Offset + RegInfo->getSlotSize();
1114 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1115 return Offset + StackSize;
1117 } else if (RegInfo->needsStackRealignment(MF)) {
1119 // Skip the saved EBP.
1120 return Offset + RegInfo->getSlotSize();
1122 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1123 return Offset + StackSize;
1125 // FIXME: Support tail calls
1128 return Offset + StackSize;
1130 // Skip the saved EBP.
1131 Offset += RegInfo->getSlotSize();
1133 // Skip the RETADDR move area
1134 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1135 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1136 if (TailCallReturnAddrDelta < 0)
1137 Offset -= TailCallReturnAddrDelta;
1143 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1144 unsigned &FrameReg) const {
1145 const X86RegisterInfo *RegInfo =
1146 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1147 // We can't calculate offset from frame pointer if the stack is realigned,
1148 // so enforce usage of stack/base pointer. The base pointer is used when we
1149 // have dynamic allocas in addition to dynamic realignment.
1150 if (RegInfo->hasBasePointer(MF))
1151 FrameReg = RegInfo->getBaseRegister();
1152 else if (RegInfo->needsStackRealignment(MF))
1153 FrameReg = RegInfo->getStackRegister();
1155 FrameReg = RegInfo->getFrameRegister(MF);
1156 return getFrameIndexOffset(MF, FI);
1159 // Simplified from getFrameIndexOffset keeping only StackPointer cases
1160 int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1161 const MachineFrameInfo *MFI = MF.getFrameInfo();
1162 // Does not include any dynamic realign.
1163 const uint64_t StackSize = MFI->getStackSize();
1166 const X86RegisterInfo *RegInfo =
1167 static_cast<const X86RegisterInfo*>(MF.getSubtarget().getRegisterInfo());
1168 // Note: LLVM arranges the stack as:
1169 // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1170 // > "Stack Slots" (<--SP)
1171 // We can always address StackSlots from RSP. We can usually (unless
1172 // needsStackRealignment) address CSRs from RSP, but sometimes need to
1173 // address them from RBP. FixedObjects can be placed anywhere in the stack
1174 // frame depending on their specific requirements (i.e. we can actually
1175 // refer to arguments to the function which are stored in the *callers*
1176 // frame). As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1177 // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1179 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1181 // We don't handle tail calls, and shouldn't be seeing them
1183 int TailCallReturnAddrDelta =
1184 MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1185 assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1189 // This is how the math works out:
1191 // %rsp grows (i.e. gets lower) left to right. Each box below is
1192 // one word (eight bytes). Obj0 is the stack slot we're trying to
1195 // ----------------------------------
1196 // | BP | Obj0 | Obj1 | ... | ObjN |
1197 // ----------------------------------
1201 // A is the incoming stack pointer.
1202 // (B - A) is the local area offset (-8 for x86-64) [1]
1203 // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1205 // |(E - B)| is the StackSize (absolute value, positive). For a
1206 // stack that grown down, this works out to be (B - E). [3]
1208 // E is also the value of %rsp after stack has been set up, and we
1209 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
1210 // (C - E) == (C - A) - (B - A) + (B - E)
1211 // { Using [1], [2] and [3] above }
1212 // == getObjectOffset - LocalAreaOffset + StackSize
1215 // Get the Offset from the StackPointer
1216 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1218 return Offset + StackSize;
1220 // Simplified from getFrameIndexReference keeping only StackPointer cases
1221 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF, int FI,
1222 unsigned &FrameReg) const {
1223 const X86RegisterInfo *RegInfo =
1224 static_cast<const X86RegisterInfo*>(MF.getSubtarget().getRegisterInfo());
1226 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1228 FrameReg = RegInfo->getStackRegister();
1229 return getFrameIndexOffsetFromSP(MF, FI);
1232 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1233 MachineFunction &MF, const TargetRegisterInfo *TRI,
1234 std::vector<CalleeSavedInfo> &CSI) const {
1235 MachineFrameInfo *MFI = MF.getFrameInfo();
1236 const X86RegisterInfo *RegInfo =
1237 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1238 unsigned SlotSize = RegInfo->getSlotSize();
1239 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1241 unsigned CalleeSavedFrameSize = 0;
1242 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1245 // emitPrologue always spills frame register the first thing.
1246 SpillSlotOffset -= SlotSize;
1247 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1249 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1250 // the frame register, we can delete it from CSI list and not have to worry
1251 // about avoiding it later.
1252 unsigned FPReg = RegInfo->getFrameRegister(MF);
1253 for (unsigned i = 0; i < CSI.size(); ++i) {
1254 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1255 CSI.erase(CSI.begin() + i);
1261 // Assign slots for GPRs. It increases frame size.
1262 for (unsigned i = CSI.size(); i != 0; --i) {
1263 unsigned Reg = CSI[i - 1].getReg();
1265 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1268 SpillSlotOffset -= SlotSize;
1269 CalleeSavedFrameSize += SlotSize;
1271 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1272 CSI[i - 1].setFrameIdx(SlotIndex);
1275 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1277 // Assign slots for XMMs.
1278 for (unsigned i = CSI.size(); i != 0; --i) {
1279 unsigned Reg = CSI[i - 1].getReg();
1280 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1283 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1285 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1287 SpillSlotOffset -= RC->getSize();
1289 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1290 CSI[i - 1].setFrameIdx(SlotIndex);
1291 MFI->ensureMaxAlignment(RC->getAlignment());
1297 bool X86FrameLowering::spillCalleeSavedRegisters(
1298 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1299 const std::vector<CalleeSavedInfo> &CSI,
1300 const TargetRegisterInfo *TRI) const {
1301 DebugLoc DL = MBB.findDebugLoc(MI);
1303 MachineFunction &MF = *MBB.getParent();
1304 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1305 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1307 // Push GPRs. It increases frame size.
1308 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1309 for (unsigned i = CSI.size(); i != 0; --i) {
1310 unsigned Reg = CSI[i - 1].getReg();
1312 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1314 // Add the callee-saved register as live-in. It's killed at the spill.
1317 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1318 .setMIFlag(MachineInstr::FrameSetup);
1321 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1322 // It can be done by spilling XMMs to stack frame.
1323 for (unsigned i = CSI.size(); i != 0; --i) {
1324 unsigned Reg = CSI[i-1].getReg();
1325 if (X86::GR64RegClass.contains(Reg) ||
1326 X86::GR32RegClass.contains(Reg))
1328 // Add the callee-saved register as live-in. It's killed at the spill.
1330 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1332 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1335 MI->setFlag(MachineInstr::FrameSetup);
1342 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1343 MachineBasicBlock::iterator MI,
1344 const std::vector<CalleeSavedInfo> &CSI,
1345 const TargetRegisterInfo *TRI) const {
1349 DebugLoc DL = MBB.findDebugLoc(MI);
1351 MachineFunction &MF = *MBB.getParent();
1352 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1353 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1355 // Reload XMMs from stack frame.
1356 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1357 unsigned Reg = CSI[i].getReg();
1358 if (X86::GR64RegClass.contains(Reg) ||
1359 X86::GR32RegClass.contains(Reg))
1362 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1363 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1367 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1368 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1369 unsigned Reg = CSI[i].getReg();
1370 if (!X86::GR64RegClass.contains(Reg) &&
1371 !X86::GR32RegClass.contains(Reg))
1374 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1380 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1381 RegScavenger *RS) const {
1382 MachineFrameInfo *MFI = MF.getFrameInfo();
1383 const X86RegisterInfo *RegInfo =
1384 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1385 unsigned SlotSize = RegInfo->getSlotSize();
1387 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1388 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1390 if (TailCallReturnAddrDelta < 0) {
1391 // create RETURNADDR area
1400 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1401 TailCallReturnAddrDelta - SlotSize, true);
1404 // Spill the BasePtr if it's used.
1405 if (RegInfo->hasBasePointer(MF))
1406 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1410 HasNestArgument(const MachineFunction *MF) {
1411 const Function *F = MF->getFunction();
1412 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1414 if (I->hasNestAttr())
1420 /// GetScratchRegister - Get a temp register for performing work in the
1421 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1422 /// and the properties of the function either one or two registers will be
1423 /// needed. Set primary to true for the first register, false for the second.
1425 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1426 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1429 if (CallingConvention == CallingConv::HiPE) {
1431 return Primary ? X86::R14 : X86::R13;
1433 return Primary ? X86::EBX : X86::EDI;
1438 return Primary ? X86::R11 : X86::R12;
1440 return Primary ? X86::R11D : X86::R12D;
1443 bool IsNested = HasNestArgument(&MF);
1445 if (CallingConvention == CallingConv::X86_FastCall ||
1446 CallingConvention == CallingConv::Fast) {
1448 report_fatal_error("Segmented stacks does not support fastcall with "
1449 "nested function.");
1450 return Primary ? X86::EAX : X86::ECX;
1453 return Primary ? X86::EDX : X86::EAX;
1454 return Primary ? X86::ECX : X86::EAX;
1457 // The stack limit in the TCB is set to this many bytes above the actual stack
1459 static const uint64_t kSplitStackAvailable = 256;
1462 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1463 MachineBasicBlock &prologueMBB = MF.front();
1464 MachineFrameInfo *MFI = MF.getFrameInfo();
1465 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1467 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1468 bool Is64Bit = STI.is64Bit();
1469 const bool IsLP64 = STI.isTarget64BitLP64();
1470 unsigned TlsReg, TlsOffset;
1473 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1474 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1475 "Scratch register is live-in");
1477 if (MF.getFunction()->isVarArg())
1478 report_fatal_error("Segmented stacks do not support vararg functions.");
1479 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1480 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1481 !STI.isTargetDragonFly())
1482 report_fatal_error("Segmented stacks not supported on this platform.");
1484 // Eventually StackSize will be calculated by a link-time pass; which will
1485 // also decide whether checking code needs to be injected into this particular
1487 StackSize = MFI->getStackSize();
1489 // Do not generate a prologue for functions with a stack of size zero
1493 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1494 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1495 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1496 bool IsNested = false;
1498 // We need to know if the function has a nest argument only in 64 bit mode.
1500 IsNested = HasNestArgument(&MF);
1502 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1503 // allocMBB needs to be last (terminating) instruction.
1505 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1506 e = prologueMBB.livein_end(); i != e; i++) {
1507 allocMBB->addLiveIn(*i);
1508 checkMBB->addLiveIn(*i);
1512 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1514 MF.push_front(allocMBB);
1515 MF.push_front(checkMBB);
1517 // When the frame size is less than 256 we just compare the stack
1518 // boundary directly to the value of the stack pointer, per gcc.
1519 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1521 // Read the limit off the current stacklet off the stack_guard location.
1523 if (STI.isTargetLinux()) {
1525 TlsOffset = IsLP64 ? 0x70 : 0x40;
1526 } else if (STI.isTargetDarwin()) {
1528 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1529 } else if (STI.isTargetWin64()) {
1531 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1532 } else if (STI.isTargetFreeBSD()) {
1535 } else if (STI.isTargetDragonFly()) {
1537 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1539 report_fatal_error("Segmented stacks not supported on this platform.");
1542 if (CompareStackPointer)
1543 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1545 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1546 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1548 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1549 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1551 if (STI.isTargetLinux()) {
1554 } else if (STI.isTargetDarwin()) {
1556 TlsOffset = 0x48 + 90*4;
1557 } else if (STI.isTargetWin32()) {
1559 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1560 } else if (STI.isTargetDragonFly()) {
1562 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1563 } else if (STI.isTargetFreeBSD()) {
1564 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1566 report_fatal_error("Segmented stacks not supported on this platform.");
1569 if (CompareStackPointer)
1570 ScratchReg = X86::ESP;
1572 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1573 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1575 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1576 STI.isTargetDragonFly()) {
1577 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1578 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1579 } else if (STI.isTargetDarwin()) {
1581 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1582 unsigned ScratchReg2;
1584 if (CompareStackPointer) {
1585 // The primary scratch register is available for holding the TLS offset.
1586 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1587 SaveScratch2 = false;
1589 // Need to use a second register to hold the TLS offset
1590 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1592 // Unfortunately, with fastcc the second scratch register may hold an
1594 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1597 // If Scratch2 is live-in then it needs to be saved.
1598 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1599 "Scratch register is live-in and not saved");
1602 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1603 .addReg(ScratchReg2, RegState::Kill);
1605 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1607 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1609 .addReg(ScratchReg2).addImm(1).addReg(0)
1614 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1618 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1619 // It jumps to normal execution of the function body.
1620 BuildMI(checkMBB, DL, TII.get(X86::JA_4)).addMBB(&prologueMBB);
1622 // On 32 bit we first push the arguments size and then the frame size. On 64
1623 // bit, we pass the stack frame size in r10 and the argument size in r11.
1625 // Functions with nested arguments use R10, so it needs to be saved across
1626 // the call to _morestack
1628 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1629 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1630 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1631 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1632 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1635 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1637 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1639 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1640 .addImm(X86FI->getArgumentStackSize());
1641 MF.getRegInfo().setPhysRegUsed(Reg10);
1642 MF.getRegInfo().setPhysRegUsed(Reg11);
1644 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1645 .addImm(X86FI->getArgumentStackSize());
1646 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1650 // __morestack is in libgcc
1651 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1652 // Under the large code model, we cannot assume that __morestack lives
1653 // within 2^31 bytes of the call site, so we cannot use pc-relative
1654 // addressing. We cannot perform the call via a temporary register,
1655 // as the rax register may be used to store the static chain, and all
1656 // other suitable registers may be either callee-save or used for
1657 // parameter passing. We cannot use the stack at this point either
1658 // because __morestack manipulates the stack directly.
1660 // To avoid these issues, perform an indirect call via a read-only memory
1661 // location containing the address.
1663 // This solution is not perfect, as it assumes that the .rodata section
1664 // is laid out within 2^31 bytes of each function body, but this seems
1665 // to be sufficient for JIT.
1666 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1670 .addExternalSymbol("__morestack_addr")
1672 MF.getMMI().setUsesMorestackAddr(true);
1675 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1676 .addExternalSymbol("__morestack");
1678 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1679 .addExternalSymbol("__morestack");
1683 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1685 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1687 allocMBB->addSuccessor(&prologueMBB);
1689 checkMBB->addSuccessor(allocMBB);
1690 checkMBB->addSuccessor(&prologueMBB);
1697 /// Erlang programs may need a special prologue to handle the stack size they
1698 /// might need at runtime. That is because Erlang/OTP does not implement a C
1699 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1700 /// (for more information see Eric Stenman's Ph.D. thesis:
1701 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1704 /// temp0 = sp - MaxStack
1705 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1709 /// call inc_stack # doubles the stack space
1710 /// temp0 = sp - MaxStack
1711 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1712 void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
1713 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1714 MachineFrameInfo *MFI = MF.getFrameInfo();
1715 const unsigned SlotSize =
1716 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo())
1718 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1719 const bool Is64Bit = STI.is64Bit();
1720 const bool IsLP64 = STI.isTarget64BitLP64();
1722 // HiPE-specific values
1723 const unsigned HipeLeafWords = 24;
1724 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1725 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1726 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1727 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1728 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1730 assert(STI.isTargetLinux() &&
1731 "HiPE prologue is only supported on Linux operating systems.");
1733 // Compute the largest caller's frame that is needed to fit the callees'
1734 // frames. This 'MaxStack' is computed from:
1736 // a) the fixed frame size, which is the space needed for all spilled temps,
1737 // b) outgoing on-stack parameter areas, and
1738 // c) the minimum stack space this function needs to make available for the
1739 // functions it calls (a tunable ABI property).
1740 if (MFI->hasCalls()) {
1741 unsigned MoreStackForCalls = 0;
1743 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1744 MBBI != MBBE; ++MBBI)
1745 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1750 // Get callee operand.
1751 const MachineOperand &MO = MI->getOperand(0);
1753 // Only take account of global function calls (no closures etc.).
1757 const Function *F = dyn_cast<Function>(MO.getGlobal());
1761 // Do not update 'MaxStack' for primitive and built-in functions
1762 // (encoded with names either starting with "erlang."/"bif_" or not
1763 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1764 // "_", such as the BIF "suspend_0") as they are executed on another
1766 if (F->getName().find("erlang.") != StringRef::npos ||
1767 F->getName().find("bif_") != StringRef::npos ||
1768 F->getName().find_first_of("._") == StringRef::npos)
1771 unsigned CalleeStkArity =
1772 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1773 if (HipeLeafWords - 1 > CalleeStkArity)
1774 MoreStackForCalls = std::max(MoreStackForCalls,
1775 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1777 MaxStack += MoreStackForCalls;
1780 // If the stack frame needed is larger than the guaranteed then runtime checks
1781 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1782 if (MaxStack > Guaranteed) {
1783 MachineBasicBlock &prologueMBB = MF.front();
1784 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1785 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1787 for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
1788 E = prologueMBB.livein_end(); I != E; I++) {
1789 stackCheckMBB->addLiveIn(*I);
1790 incStackMBB->addLiveIn(*I);
1793 MF.push_front(incStackMBB);
1794 MF.push_front(stackCheckMBB);
1796 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1797 unsigned LEAop, CMPop, CALLop;
1801 LEAop = X86::LEA64r;
1802 CMPop = X86::CMP64rm;
1803 CALLop = X86::CALL64pcrel32;
1804 SPLimitOffset = 0x90;
1808 LEAop = X86::LEA32r;
1809 CMPop = X86::CMP32rm;
1810 CALLop = X86::CALLpcrel32;
1811 SPLimitOffset = 0x4c;
1814 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1815 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1816 "HiPE prologue scratch register is live-in");
1818 // Create new MBB for StackCheck:
1819 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1820 SPReg, false, -MaxStack);
1821 // SPLimitOffset is in a fixed heap location (pointed by BP).
1822 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1823 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1824 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_4)).addMBB(&prologueMBB);
1826 // Create new MBB for IncStack:
1827 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1828 addExternalSymbol("inc_stack_0");
1829 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1830 SPReg, false, -MaxStack);
1831 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1832 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1833 BuildMI(incStackMBB, DL, TII.get(X86::JLE_4)).addMBB(incStackMBB);
1835 stackCheckMBB->addSuccessor(&prologueMBB, 99);
1836 stackCheckMBB->addSuccessor(incStackMBB, 1);
1837 incStackMBB->addSuccessor(&prologueMBB, 99);
1838 incStackMBB->addSuccessor(incStackMBB, 1);
1845 bool X86FrameLowering::
1846 convertArgMovsToPushes(MachineFunction &MF, MachineBasicBlock &MBB,
1847 MachineBasicBlock::iterator I, uint64_t Amount) const {
1848 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1849 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
1850 MF.getSubtarget().getRegisterInfo());
1851 unsigned StackPtr = RegInfo.getStackRegister();
1853 // Scan the call setup sequence for the pattern we're looking for.
1854 // We only handle a simple case now - a sequence of MOV32mi or MOV32mr
1855 // instructions, that push a sequence of 32-bit values onto the stack, with
1857 std::map<int64_t, MachineBasicBlock::iterator> MovMap;
1859 int Opcode = I->getOpcode();
1860 if (Opcode != X86::MOV32mi && Opcode != X86::MOV32mr)
1863 // We only want movs of the form:
1864 // movl imm/r32, k(%ecx)
1865 // If we run into something else, bail
1866 // Note that AddrBaseReg may, counterintuitively, not be a register...
1867 if (!I->getOperand(X86::AddrBaseReg).isReg() ||
1868 (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
1869 !I->getOperand(X86::AddrScaleAmt).isImm() ||
1870 (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
1871 (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
1872 (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
1873 !I->getOperand(X86::AddrDisp).isImm())
1876 int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
1878 // We don't want to consider the unaligned case.
1882 // If the same stack slot is being filled twice, something's fishy.
1883 if (!MovMap.insert(std::pair<int64_t, MachineInstr*>(StackDisp, I)).second)
1887 } while (I != MBB.end());
1889 // We now expect the end of the sequence - a call and a stack adjust.
1894 MachineBasicBlock::iterator Call = I;
1895 if ((++I)->getOpcode() != TII.getCallFrameDestroyOpcode())
1898 // Now, go through the map, and see that we don't have any gaps,
1899 // but only a series of 32-bit MOVs.
1900 // Since std::map provides ordered iteration, the original order
1901 // of the MOVs doesn't matter.
1902 int64_t ExpectedDist = 0;
1903 for (auto MMI = MovMap.begin(), MME = MovMap.end(); MMI != MME;
1904 ++MMI, ExpectedDist += 4)
1905 if (MMI->first != ExpectedDist)
1908 // Ok, everything looks fine. Do the transformation.
1909 DebugLoc DL = I->getDebugLoc();
1911 // It's possible the original stack adjustment amount was larger than
1912 // that done by the pushes. If so, we still need a SUB.
1913 Amount -= ExpectedDist;
1915 MachineInstr* Sub = BuildMI(MBB, Call, DL,
1916 TII.get(getSUBriOpcode(false, Amount)), StackPtr)
1917 .addReg(StackPtr).addImm(Amount);
1918 Sub->getOperand(3).setIsDead();
1921 // Now, iterate through the map in reverse order, and replace the movs
1922 // with pushes. MOVmi/MOVmr doesn't have any defs, so need to replace uses.
1923 for (auto MMI = MovMap.rbegin(), MME = MovMap.rend(); MMI != MME; ++MMI) {
1924 MachineBasicBlock::iterator MOV = MMI->second;
1925 MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
1927 // Replace MOVmr with PUSH32r, and MOVmi with PUSHi of appropriate size
1928 int PushOpcode = X86::PUSH32r;
1929 if (MOV->getOpcode() == X86::MOV32mi)
1930 PushOpcode = getPUSHiOpcode(false, PushOp);
1932 BuildMI(MBB, Call, DL, TII.get(PushOpcode)).addOperand(PushOp);
1939 void X86FrameLowering::
1940 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1941 MachineBasicBlock::iterator I) const {
1942 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1943 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
1944 MF.getSubtarget().getRegisterInfo());
1945 unsigned StackPtr = RegInfo.getStackRegister();
1946 bool reserveCallFrame = hasReservedCallFrame(MF);
1947 int Opcode = I->getOpcode();
1948 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1949 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1950 bool IsLP64 = STI.isTarget64BitLP64();
1951 DebugLoc DL = I->getDebugLoc();
1952 uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
1953 uint64_t CalleeAmt = isDestroy ? I->getOperand(1).getImm() : 0;
1956 if (!reserveCallFrame) {
1957 // If the stack pointer can be changed after prologue, turn the
1958 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1959 // adjcallstackdown instruction into 'add ESP, <amt>'
1963 // We need to keep the stack aligned properly. To do this, we round the
1964 // amount of space needed for the outgoing arguments up to the next
1965 // alignment boundary.
1966 unsigned StackAlign = MF.getTarget()
1968 ->getFrameLowering()
1969 ->getStackAlignment();
1970 Amount = (Amount + StackAlign - 1) / StackAlign * StackAlign;
1972 MachineInstr *New = nullptr;
1973 if (Opcode == TII.getCallFrameSetupOpcode()) {
1974 // Try to convert movs to the stack into pushes.
1975 // We currently only look for a pattern that appears in 32-bit
1976 // calling conventions.
1977 if (!IsLP64 && convertArgMovsToPushes(MF, MBB, I, Amount))
1980 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)),
1985 assert(Opcode == TII.getCallFrameDestroyOpcode());
1987 // Factor out the amount the callee already popped.
1988 Amount -= CalleeAmt;
1991 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1992 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1993 .addReg(StackPtr).addImm(Amount);
1998 // The EFLAGS implicit def is dead.
1999 New->getOperand(3).setIsDead();
2001 // Replace the pseudo instruction with a new instruction.
2008 if (Opcode == TII.getCallFrameDestroyOpcode() && CalleeAmt) {
2009 // If we are performing frame pointer elimination and if the callee pops
2010 // something off the stack pointer, add it back. We do this until we have
2011 // more advanced stack pointer tracking ability.
2012 unsigned Opc = getSUBriOpcode(IsLP64, CalleeAmt);
2013 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
2014 .addReg(StackPtr).addImm(CalleeAmt);
2016 // The EFLAGS implicit def is dead.
2017 New->getOperand(3).setIsDead();
2019 // We are not tracking the stack pointer adjustment by the callee, so make
2020 // sure we restore the stack pointer immediately after the call, there may
2021 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
2022 MachineBasicBlock::iterator B = MBB.begin();
2023 while (I != B && !std::prev(I)->isCall())