1 //=======- X86FrameLowering.cpp - X86 Frame Information --------*- C++ -*-====//
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/Function.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/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/ADT/SmallSet.h"
35 // FIXME: completely move here.
36 extern cl::opt<bool> ForceStackAlign;
38 // FIXME: Remove once linker support is available. The feature exists only on
39 // Darwin at the moment.
41 GenerateCompactUnwind("gen-compact-unwind",
42 cl::desc("Generate compact unwind encoding"),
45 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
46 return !MF.getFrameInfo()->hasVarSizedObjects();
49 /// hasFP - Return true if the specified function should have a dedicated frame
50 /// pointer register. This is true if the function has variable sized allocas
51 /// or if frame pointer elimination is disabled.
52 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
53 const MachineFrameInfo *MFI = MF.getFrameInfo();
54 const MachineModuleInfo &MMI = MF.getMMI();
55 const TargetRegisterInfo *RI = TM.getRegisterInfo();
57 return (DisableFramePointerElim(MF) ||
58 RI->needsStackRealignment(MF) ||
59 MFI->hasVarSizedObjects() ||
60 MFI->isFrameAddressTaken() ||
61 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
62 MMI.callsUnwindInit());
65 static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
69 return X86::SUB64ri32;
77 static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
81 return X86::ADD64ri32;
89 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
90 /// when it reaches the "return" instruction. We can then pop a stack object
91 /// to this register without worry about clobbering it.
92 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
93 MachineBasicBlock::iterator &MBBI,
94 const TargetRegisterInfo &TRI,
96 const MachineFunction *MF = MBB.getParent();
97 const Function *F = MF->getFunction();
98 if (!F || MF->getMMI().callsEHReturn())
101 static const unsigned CallerSavedRegs32Bit[] = {
102 X86::EAX, X86::EDX, X86::ECX, 0
105 static const unsigned CallerSavedRegs64Bit[] = {
106 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
107 X86::R8, X86::R9, X86::R10, X86::R11, 0
110 unsigned Opc = MBBI->getOpcode();
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<unsigned, 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 (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
135 const unsigned *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 Is64Bit, const TargetInstrInfo &TII,
152 const TargetRegisterInfo &TRI) {
153 bool isSub = NumBytes < 0;
154 uint64_t Offset = isSub ? -NumBytes : NumBytes;
155 unsigned Opc = isSub ?
156 getSUBriOpcode(Is64Bit, Offset) :
157 getADDriOpcode(Is64Bit, Offset);
158 uint64_t Chunk = (1LL << 31) - 1;
159 DebugLoc DL = MBB.findDebugLoc(MBBI);
162 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
163 if (ThisVal == (Is64Bit ? 8 : 4)) {
164 // Use push / pop instead.
166 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
167 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
170 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
171 : (Is64Bit ? X86::POP64r : X86::POP32r);
172 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
173 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
175 MI->setFlag(MachineInstr::FrameSetup);
182 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
186 MI->setFlag(MachineInstr::FrameSetup);
187 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
192 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
194 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
195 unsigned StackPtr, uint64_t *NumBytes = NULL) {
196 if (MBBI == MBB.begin()) return;
198 MachineBasicBlock::iterator PI = prior(MBBI);
199 unsigned Opc = PI->getOpcode();
200 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
201 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
202 PI->getOperand(0).getReg() == StackPtr) {
204 *NumBytes += PI->getOperand(2).getImm();
206 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
207 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
208 PI->getOperand(0).getReg() == StackPtr) {
210 *NumBytes -= PI->getOperand(2).getImm();
215 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
217 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
218 MachineBasicBlock::iterator &MBBI,
219 unsigned StackPtr, uint64_t *NumBytes = NULL) {
220 // FIXME: THIS ISN'T RUN!!!
223 if (MBBI == MBB.end()) return;
225 MachineBasicBlock::iterator NI = llvm::next(MBBI);
226 if (NI == MBB.end()) return;
228 unsigned Opc = NI->getOpcode();
229 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
230 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
231 NI->getOperand(0).getReg() == StackPtr) {
233 *NumBytes -= NI->getOperand(2).getImm();
236 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
237 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
238 NI->getOperand(0).getReg() == StackPtr) {
240 *NumBytes += NI->getOperand(2).getImm();
246 /// mergeSPUpdates - Checks the instruction before/after the passed
247 /// instruction. If it is an ADD/SUB instruction it is deleted argument and the
248 /// stack adjustment is returned as a positive value for ADD and a negative for
250 static int mergeSPUpdates(MachineBasicBlock &MBB,
251 MachineBasicBlock::iterator &MBBI,
253 bool doMergeWithPrevious) {
254 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
255 (!doMergeWithPrevious && MBBI == MBB.end()))
258 MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
259 MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
260 unsigned Opc = PI->getOpcode();
263 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
264 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
265 PI->getOperand(0).getReg() == StackPtr){
266 Offset += PI->getOperand(2).getImm();
268 if (!doMergeWithPrevious) MBBI = NI;
269 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
270 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
271 PI->getOperand(0).getReg() == StackPtr) {
272 Offset -= PI->getOperand(2).getImm();
274 if (!doMergeWithPrevious) MBBI = NI;
280 static bool isEAXLiveIn(MachineFunction &MF) {
281 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
282 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
283 unsigned Reg = II->first;
285 if (Reg == X86::EAX || Reg == X86::AX ||
286 Reg == X86::AH || Reg == X86::AL)
293 void X86FrameLowering::emitCalleeSavedFrameMoves(MachineFunction &MF,
295 unsigned FramePtr) const {
296 MachineFrameInfo *MFI = MF.getFrameInfo();
297 MachineModuleInfo &MMI = MF.getMMI();
299 // Add callee saved registers to move list.
300 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
301 if (CSI.empty()) return;
303 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
304 const TargetData *TD = TM.getTargetData();
305 bool HasFP = hasFP(MF);
307 // Calculate amount of bytes used for return address storing.
308 int stackGrowth = -TD->getPointerSize();
310 // FIXME: This is dirty hack. The code itself is pretty mess right now.
311 // It should be rewritten from scratch and generalized sometimes.
313 // Determine maximum offset (minimum due to stack growth).
314 int64_t MaxOffset = 0;
315 for (std::vector<CalleeSavedInfo>::const_iterator
316 I = CSI.begin(), E = CSI.end(); I != E; ++I)
317 MaxOffset = std::min(MaxOffset,
318 MFI->getObjectOffset(I->getFrameIdx()));
320 // Calculate offsets.
321 int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
322 for (std::vector<CalleeSavedInfo>::const_iterator
323 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
324 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
325 unsigned Reg = I->getReg();
326 Offset = MaxOffset - Offset + saveAreaOffset;
328 // Don't output a new machine move if we're re-saving the frame
329 // pointer. This happens when the PrologEpilogInserter has inserted an extra
330 // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
331 // generates one when frame pointers are used. If we generate a "machine
332 // move" for this extra "PUSH", the linker will lose track of the fact that
333 // the frame pointer should have the value of the first "PUSH" when it's
336 // FIXME: This looks inelegant. It's possibly correct, but it's covering up
337 // another bug. I.e., one where we generate a prolog like this:
345 // The immediate re-push of EBP is unnecessary. At the least, it's an
346 // optimization bug. EBP can be used as a scratch register in certain
347 // cases, but probably not when we have a frame pointer.
348 if (HasFP && FramePtr == Reg)
351 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
352 MachineLocation CSSrc(Reg);
353 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
357 /// getCompactUnwindRegNum - Get the compact unwind number for a given
358 /// register. The number corresponds to the enum lists in
359 /// compact_unwind_encoding.h.
360 static int getCompactUnwindRegNum(const unsigned *CURegs, unsigned Reg) {
362 for (; *CURegs; ++CURegs, ++Idx)
369 /// encodeCompactUnwindRegistersWithoutFrame - Create the permutation encoding
370 /// used with frameless stacks. It is passed the number of registers to be saved
371 /// and an array of the registers saved.
372 static uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned SavedRegs[6],
375 // The saved registers are numbered from 1 to 6. In order to encode the order
376 // in which they were saved, we re-number them according to their place in the
377 // register order. The re-numbering is relative to the last re-numbered
378 // register. E.g., if we have registers {6, 2, 4, 5} saved in that order:
387 static const unsigned CU32BitRegs[] = {
388 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
390 static const unsigned CU64BitRegs[] = {
391 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
393 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
395 uint32_t RenumRegs[6];
396 for (unsigned i = 6 - RegCount; i < 6; ++i) {
397 int CUReg = getCompactUnwindRegNum(CURegs, SavedRegs[i]);
398 if (CUReg == -1) return ~0U;
399 SavedRegs[i] = CUReg;
401 unsigned Countless = 0;
402 for (unsigned j = 6 - RegCount; j < i; ++j)
403 if (SavedRegs[j] < SavedRegs[i])
406 RenumRegs[i] = SavedRegs[i] - Countless - 1;
409 // Take the renumbered values and encode them into a 10-bit number.
410 uint32_t permutationEncoding = 0;
413 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
414 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
418 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
419 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
423 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
424 + 3 * RenumRegs[4] + RenumRegs[5];
427 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
431 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
434 permutationEncoding |= RenumRegs[5];
438 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
439 "Invalid compact register encoding!");
440 return permutationEncoding;
443 /// encodeCompactUnwindRegistersWithFrame - Return the registers encoded for a
444 /// compact encoding with a frame pointer.
445 static uint32_t encodeCompactUnwindRegistersWithFrame(unsigned SavedRegs[6],
447 static const unsigned CU32BitRegs[] = {
448 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
450 static const unsigned CU64BitRegs[] = {
451 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
453 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
455 // Encode the registers in the order they were saved, 3-bits per register. The
456 // registers are numbered from 1 to 6.
458 for (int I = 5; I >= 0; --I) {
459 unsigned Reg = SavedRegs[I];
461 int CURegNum = getCompactUnwindRegNum(CURegs, Reg);
464 RegEnc |= (CURegNum & 0x7) << (5 - I);
467 assert((RegEnc & 0x7FFF) == RegEnc && "Invalid compact register encoding!");
471 uint32_t X86FrameLowering::getCompactUnwindEncoding(MachineFunction &MF) const {
472 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
473 unsigned FramePtr = RegInfo->getFrameRegister(MF);
474 unsigned StackPtr = RegInfo->getStackRegister();
476 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
477 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
479 bool Is64Bit = STI.is64Bit();
480 bool HasFP = hasFP(MF);
482 unsigned SavedRegs[6] = { 0, 0, 0, 0, 0, 0 };
485 unsigned OffsetSize = (Is64Bit ? 8 : 4);
487 unsigned PushInstr = (Is64Bit ? X86::PUSH64r : X86::PUSH32r);
488 unsigned PushInstrSize = 1;
489 unsigned MoveInstr = (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
490 unsigned MoveInstrSize = (Is64Bit ? 3 : 2);
491 unsigned SubtractInstr = getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta);
492 unsigned SubtractInstrIdx = (Is64Bit ? 3 : 2);
494 unsigned StackDivide = (Is64Bit ? 8 : 4);
496 unsigned InstrOffset = 0;
497 unsigned CFAOffset = 0;
498 unsigned StackAdjust = 0;
500 MachineBasicBlock &MBB = MF.front(); // Prologue is in entry BB.
501 bool ExpectEnd = false;
502 for (MachineBasicBlock::iterator
503 MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ++MBBI) {
504 MachineInstr &MI = *MBBI;
505 unsigned Opc = MI.getOpcode();
506 if (Opc == X86::PROLOG_LABEL) continue;
507 if (!MI.getFlag(MachineInstr::FrameSetup)) break;
509 // We don't exect any more prolog instructions.
510 if (ExpectEnd) return 0;
512 if (Opc == PushInstr) {
513 // If there are too many saved registers, we cannot use compact encoding.
514 if (--SavedRegIdx < 0) return 0;
516 SavedRegs[SavedRegIdx] = MI.getOperand(0).getReg();
517 CFAOffset += OffsetSize;
518 InstrOffset += PushInstrSize;
519 } else if (Opc == MoveInstr) {
520 unsigned SrcReg = MI.getOperand(1).getReg();
521 unsigned DstReg = MI.getOperand(0).getReg();
523 if (DstReg != FramePtr || SrcReg != StackPtr)
527 memset(SavedRegs, 0, sizeof(SavedRegs));
528 InstrOffset += MoveInstrSize;
529 } else if (Opc == SubtractInstr) {
531 // We all ready have a stack pointer adjustment.
534 if (!MI.getOperand(0).isReg() ||
535 MI.getOperand(0).getReg() != MI.getOperand(1).getReg() ||
536 MI.getOperand(0).getReg() != StackPtr || !MI.getOperand(2).isImm())
537 // We need this to be a stack adjustment pointer. Something like:
539 // %RSP<def> = SUB64ri8 %RSP, 48
542 StackAdjust = MI.getOperand(2).getImm() / StackDivide;
543 SubtractInstrIdx += InstrOffset;
548 // Encode that we are using EBP/RBP as the frame pointer.
549 uint32_t CompactUnwindEncoding = 0;
550 CFAOffset /= StackDivide;
552 if ((CFAOffset & 0xFF) != CFAOffset)
553 // Offset was too big for compact encoding.
556 // Get the encoding of the saved registers when we have a frame pointer.
557 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame(SavedRegs, Is64Bit);
561 CompactUnwindEncoding |= 0x01000000;
562 CompactUnwindEncoding |= (CFAOffset & 0xFF) << 16;
563 CompactUnwindEncoding |= RegEnc & 0x7FFF;
565 unsigned FullOffset = CFAOffset + StackAdjust;
566 if ((FullOffset & 0xFF) == FullOffset) {
568 CompactUnwindEncoding |= 0x02000000;
569 CompactUnwindEncoding |= (FullOffset & 0xFF) << 16;
571 if ((CFAOffset & 0x7) != CFAOffset)
572 // The extra stack adjustments are too big for us to handle.
575 // Frameless stack with an offset too large for us to encode compactly.
576 CompactUnwindEncoding |= 0x03000000;
578 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
580 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
582 // Encode any extra stack stack changes (done via push instructions).
583 CompactUnwindEncoding |= (CFAOffset & 0x7) << 13;
586 // Get the encoding of the saved registers when we don't have a frame
588 uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegs,
591 if (RegEnc == ~0U) return 0;
592 CompactUnwindEncoding |= RegEnc & 0x3FF;
595 return CompactUnwindEncoding;
598 /// emitPrologue - Push callee-saved registers onto the stack, which
599 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
600 /// space for local variables. Also emit labels used by the exception handler to
601 /// generate the exception handling frames.
602 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
603 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
604 MachineBasicBlock::iterator MBBI = MBB.begin();
605 MachineFrameInfo *MFI = MF.getFrameInfo();
606 const Function *Fn = MF.getFunction();
607 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
608 const X86InstrInfo &TII = *TM.getInstrInfo();
609 MachineModuleInfo &MMI = MF.getMMI();
610 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
611 bool needsFrameMoves = MMI.hasDebugInfo() ||
612 Fn->needsUnwindTableEntry();
613 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
614 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
615 bool HasFP = hasFP(MF);
616 bool Is64Bit = STI.is64Bit();
617 bool IsWin64 = STI.isTargetWin64();
618 unsigned StackAlign = getStackAlignment();
619 unsigned SlotSize = RegInfo->getSlotSize();
620 unsigned FramePtr = RegInfo->getFrameRegister(MF);
621 unsigned StackPtr = RegInfo->getStackRegister();
624 // If we're forcing a stack realignment we can't rely on just the frame
625 // info, we need to know the ABI stack alignment as well in case we
626 // have a call out. Otherwise just make sure we have some alignment - we'll
627 // go with the minimum SlotSize.
628 if (ForceStackAlign) {
630 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
631 else if (MaxAlign < SlotSize)
635 // Add RETADDR move area to callee saved frame size.
636 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
637 if (TailCallReturnAddrDelta < 0)
638 X86FI->setCalleeSavedFrameSize(
639 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
641 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
642 // function, and use up to 128 bytes of stack space, don't have a frame
643 // pointer, calls, or dynamic alloca then we do not need to adjust the
644 // stack pointer (we fit in the Red Zone).
645 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
646 !RegInfo->needsStackRealignment(MF) &&
647 !MFI->hasVarSizedObjects() && // No dynamic alloca.
648 !MFI->adjustsStack() && // No calls.
649 !IsWin64 && // Win64 has no Red Zone
650 !EnableSegmentedStacks) { // Regular stack
651 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
652 if (HasFP) MinSize += SlotSize;
653 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
654 MFI->setStackSize(StackSize);
657 // Insert stack pointer adjustment for later moving of return addr. Only
658 // applies to tail call optimized functions where the callee argument stack
659 // size is bigger than the callers.
660 if (TailCallReturnAddrDelta < 0) {
662 BuildMI(MBB, MBBI, DL,
663 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
666 .addImm(-TailCallReturnAddrDelta)
667 .setMIFlag(MachineInstr::FrameSetup);
668 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
671 // Mapping for machine moves:
673 // DST: VirtualFP AND
674 // SRC: VirtualFP => DW_CFA_def_cfa_offset
675 // ELSE => DW_CFA_def_cfa
677 // SRC: VirtualFP AND
678 // DST: Register => DW_CFA_def_cfa_register
681 // OFFSET < 0 => DW_CFA_offset_extended_sf
682 // REG < 64 => DW_CFA_offset + Reg
683 // ELSE => DW_CFA_offset_extended
685 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
686 const TargetData *TD = MF.getTarget().getTargetData();
687 uint64_t NumBytes = 0;
688 int stackGrowth = -TD->getPointerSize();
691 // Calculate required stack adjustment.
692 uint64_t FrameSize = StackSize - SlotSize;
693 if (RegInfo->needsStackRealignment(MF))
694 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
696 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
698 // Get the offset of the stack slot for the EBP register, which is
699 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
700 // Update the frame offset adjustment.
701 MFI->setOffsetAdjustment(-NumBytes);
703 // Save EBP/RBP into the appropriate stack slot.
704 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
705 .addReg(FramePtr, RegState::Kill)
706 .setMIFlag(MachineInstr::FrameSetup);
708 if (needsFrameMoves) {
709 // Mark the place where EBP/RBP was saved.
710 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
711 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
714 // Define the current CFA rule to use the provided offset.
716 MachineLocation SPDst(MachineLocation::VirtualFP);
717 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
718 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
720 MachineLocation SPDst(StackPtr);
721 MachineLocation SPSrc(StackPtr, stackGrowth);
722 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
725 // Change the rule for the FramePtr to be an "offset" rule.
726 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
727 MachineLocation FPSrc(FramePtr);
728 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
731 // Update EBP with the new base value.
732 BuildMI(MBB, MBBI, DL,
733 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
735 .setMIFlag(MachineInstr::FrameSetup);
737 if (needsFrameMoves) {
738 // Mark effective beginning of when frame pointer becomes valid.
739 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
740 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
743 // Define the current CFA to use the EBP/RBP register.
744 MachineLocation FPDst(FramePtr);
745 MachineLocation FPSrc(MachineLocation::VirtualFP);
746 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
749 // Mark the FramePtr as live-in in every block except the entry.
750 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
752 I->addLiveIn(FramePtr);
755 if (RegInfo->needsStackRealignment(MF)) {
757 BuildMI(MBB, MBBI, DL,
758 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
761 .setMIFlag(MachineInstr::FrameSetup);
763 // The EFLAGS implicit def is dead.
764 MI->getOperand(3).setIsDead();
767 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
770 // Skip the callee-saved push instructions.
771 bool PushedRegs = false;
772 int StackOffset = 2 * stackGrowth;
774 while (MBBI != MBB.end() &&
775 (MBBI->getOpcode() == X86::PUSH32r ||
776 MBBI->getOpcode() == X86::PUSH64r)) {
778 MBBI->setFlag(MachineInstr::FrameSetup);
781 if (!HasFP && needsFrameMoves) {
782 // Mark callee-saved push instruction.
783 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
784 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
786 // Define the current CFA rule to use the provided offset.
787 unsigned Ptr = StackSize ? MachineLocation::VirtualFP : StackPtr;
788 MachineLocation SPDst(Ptr);
789 MachineLocation SPSrc(Ptr, StackOffset);
790 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
791 StackOffset += stackGrowth;
795 DL = MBB.findDebugLoc(MBBI);
797 // If there is an SUB32ri of ESP immediately before this instruction, merge
798 // the two. This can be the case when tail call elimination is enabled and
799 // the callee has more arguments then the caller.
800 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
802 // If there is an ADD32ri or SUB32ri of ESP immediately after this
803 // instruction, merge the two instructions.
804 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
806 // Adjust stack pointer: ESP -= numbytes.
808 // Windows and cygwin/mingw require a prologue helper routine when allocating
809 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
810 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
811 // stack and adjust the stack pointer in one go. The 64-bit version of
812 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
813 // responsible for adjusting the stack pointer. Touching the stack at 4K
814 // increments is necessary to ensure that the guard pages used by the OS
815 // virtual memory manager are allocated in correct sequence.
816 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
817 const char *StackProbeSymbol;
818 bool isSPUpdateNeeded = false;
821 if (STI.isTargetCygMing())
822 StackProbeSymbol = "___chkstk";
824 StackProbeSymbol = "__chkstk";
825 isSPUpdateNeeded = true;
827 } else if (STI.isTargetCygMing())
828 StackProbeSymbol = "_alloca";
830 StackProbeSymbol = "_chkstk";
832 // Check whether EAX is livein for this function.
833 bool isEAXAlive = isEAXLiveIn(MF);
836 // Sanity check that EAX is not livein for this function.
837 // It should not be, so throw an assert.
838 assert(!Is64Bit && "EAX is livein in x64 case!");
841 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
842 .addReg(X86::EAX, RegState::Kill)
843 .setMIFlag(MachineInstr::FrameSetup);
847 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
848 // Function prologue is responsible for adjusting the stack pointer.
849 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
851 .setMIFlag(MachineInstr::FrameSetup);
853 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
854 // We'll also use 4 already allocated bytes for EAX.
855 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
856 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
857 .setMIFlag(MachineInstr::FrameSetup);
860 BuildMI(MBB, MBBI, DL,
861 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
862 .addExternalSymbol(StackProbeSymbol)
863 .addReg(StackPtr, RegState::Define | RegState::Implicit)
864 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
865 .setMIFlag(MachineInstr::FrameSetup);
867 // MSVC x64's __chkstk needs to adjust %rsp.
868 // FIXME: %rax preserves the offset and should be available.
869 if (isSPUpdateNeeded)
870 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
875 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
877 StackPtr, false, NumBytes - 4);
878 MI->setFlag(MachineInstr::FrameSetup);
879 MBB.insert(MBBI, MI);
882 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
885 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
886 // Mark end of stack pointer adjustment.
887 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
888 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
891 if (!HasFP && NumBytes) {
892 // Define the current CFA rule to use the provided offset.
894 MachineLocation SPDst(MachineLocation::VirtualFP);
895 MachineLocation SPSrc(MachineLocation::VirtualFP,
896 -StackSize + stackGrowth);
897 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
899 MachineLocation SPDst(StackPtr);
900 MachineLocation SPSrc(StackPtr, stackGrowth);
901 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
905 // Emit DWARF info specifying the offsets of the callee-saved registers.
907 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
910 // Darwin 10.7 and greater has support for compact unwind encoding.
911 if (GenerateCompactUnwind && STI.getTargetTriple().isMacOSX() &&
912 !STI.getTargetTriple().isMacOSXVersionLT(10, 7))
913 MMI.setCompactUnwindEncoding(getCompactUnwindEncoding(MF));
916 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
917 MachineBasicBlock &MBB) const {
918 const MachineFrameInfo *MFI = MF.getFrameInfo();
919 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
920 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
921 const X86InstrInfo &TII = *TM.getInstrInfo();
922 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
923 assert(MBBI != MBB.end() && "Returning block has no instructions");
924 unsigned RetOpcode = MBBI->getOpcode();
925 DebugLoc DL = MBBI->getDebugLoc();
926 bool Is64Bit = STI.is64Bit();
927 unsigned StackAlign = getStackAlignment();
928 unsigned SlotSize = RegInfo->getSlotSize();
929 unsigned FramePtr = RegInfo->getFrameRegister(MF);
930 unsigned StackPtr = RegInfo->getStackRegister();
934 llvm_unreachable("Can only insert epilog into returning blocks");
937 case X86::TCRETURNdi:
938 case X86::TCRETURNri:
939 case X86::TCRETURNmi:
940 case X86::TCRETURNdi64:
941 case X86::TCRETURNri64:
942 case X86::TCRETURNmi64:
944 case X86::EH_RETURN64:
945 break; // These are ok
948 // Get the number of bytes to allocate from the FrameInfo.
949 uint64_t StackSize = MFI->getStackSize();
950 uint64_t MaxAlign = MFI->getMaxAlignment();
951 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
952 uint64_t NumBytes = 0;
954 // If we're forcing a stack realignment we can't rely on just the frame
955 // info, we need to know the ABI stack alignment as well in case we
956 // have a call out. Otherwise just make sure we have some alignment - we'll
957 // go with the minimum.
958 if (ForceStackAlign) {
960 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
962 MaxAlign = MaxAlign ? MaxAlign : 4;
966 // Calculate required stack adjustment.
967 uint64_t FrameSize = StackSize - SlotSize;
968 if (RegInfo->needsStackRealignment(MF))
969 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
971 NumBytes = FrameSize - CSSize;
974 BuildMI(MBB, MBBI, DL,
975 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
977 NumBytes = StackSize - CSSize;
980 // Skip the callee-saved pop instructions.
981 MachineBasicBlock::iterator LastCSPop = MBBI;
982 while (MBBI != MBB.begin()) {
983 MachineBasicBlock::iterator PI = prior(MBBI);
984 unsigned Opc = PI->getOpcode();
986 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
987 !PI->getDesc().isTerminator())
993 DL = MBBI->getDebugLoc();
995 // If there is an ADD32ri or SUB32ri of ESP immediately before this
996 // instruction, merge the two instructions.
997 if (NumBytes || MFI->hasVarSizedObjects())
998 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1000 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1001 // slot before popping them off! Same applies for the case, when stack was
1003 if (RegInfo->needsStackRealignment(MF)) {
1004 // We cannot use LEA here, because stack pointer was realigned. We need to
1005 // deallocate local frame back.
1007 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
1008 MBBI = prior(LastCSPop);
1011 BuildMI(MBB, MBBI, DL,
1012 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1013 StackPtr).addReg(FramePtr);
1014 } else if (MFI->hasVarSizedObjects()) {
1016 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
1018 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
1019 FramePtr, false, -CSSize);
1020 MBB.insert(MBBI, MI);
1022 BuildMI(MBB, MBBI, DL,
1023 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
1026 } else if (NumBytes) {
1027 // Adjust stack pointer back: ESP += numbytes.
1028 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
1031 // We're returning from function via eh_return.
1032 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
1033 MBBI = MBB.getLastNonDebugInstr();
1034 MachineOperand &DestAddr = MBBI->getOperand(0);
1035 assert(DestAddr.isReg() && "Offset should be in register!");
1036 BuildMI(MBB, MBBI, DL,
1037 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1038 StackPtr).addReg(DestAddr.getReg());
1039 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1040 RetOpcode == X86::TCRETURNmi ||
1041 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1042 RetOpcode == X86::TCRETURNmi64) {
1043 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1044 // Tail call return: adjust the stack pointer and jump to callee.
1045 MBBI = MBB.getLastNonDebugInstr();
1046 MachineOperand &JumpTarget = MBBI->getOperand(0);
1047 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1048 assert(StackAdjust.isImm() && "Expecting immediate value.");
1050 // Adjust stack pointer.
1051 int StackAdj = StackAdjust.getImm();
1052 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1054 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1056 // Incoporate the retaddr area.
1057 Offset = StackAdj-MaxTCDelta;
1058 assert(Offset >= 0 && "Offset should never be negative");
1061 // Check for possible merge with preceding ADD instruction.
1062 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1063 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
1066 // Jump to label or value in register.
1067 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1068 MachineInstrBuilder MIB =
1069 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1070 ? X86::TAILJMPd : X86::TAILJMPd64));
1071 if (JumpTarget.isGlobal())
1072 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1073 JumpTarget.getTargetFlags());
1075 assert(JumpTarget.isSymbol());
1076 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1077 JumpTarget.getTargetFlags());
1079 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1080 MachineInstrBuilder MIB =
1081 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1082 ? X86::TAILJMPm : X86::TAILJMPm64));
1083 for (unsigned i = 0; i != 5; ++i)
1084 MIB.addOperand(MBBI->getOperand(i));
1085 } else if (RetOpcode == X86::TCRETURNri64) {
1086 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1087 addReg(JumpTarget.getReg(), RegState::Kill);
1089 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1090 addReg(JumpTarget.getReg(), RegState::Kill);
1093 MachineInstr *NewMI = prior(MBBI);
1094 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
1095 NewMI->addOperand(MBBI->getOperand(i));
1097 // Delete the pseudo instruction TCRETURN.
1099 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
1100 (X86FI->getTCReturnAddrDelta() < 0)) {
1101 // Add the return addr area delta back since we are not tail calling.
1102 int delta = -1*X86FI->getTCReturnAddrDelta();
1103 MBBI = MBB.getLastNonDebugInstr();
1105 // Check for possible merge with preceding ADD instruction.
1106 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1107 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
1111 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
1112 const X86RegisterInfo *RI =
1113 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
1114 const MachineFrameInfo *MFI = MF.getFrameInfo();
1115 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1116 uint64_t StackSize = MFI->getStackSize();
1118 if (RI->needsStackRealignment(MF)) {
1120 // Skip the saved EBP.
1121 Offset += RI->getSlotSize();
1123 unsigned Align = MFI->getObjectAlignment(FI);
1124 assert((-(Offset + StackSize)) % Align == 0);
1126 return Offset + StackSize;
1128 // FIXME: Support tail calls
1131 return Offset + StackSize;
1133 // Skip the saved EBP.
1134 Offset += RI->getSlotSize();
1136 // Skip the RETADDR move area
1137 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1138 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1139 if (TailCallReturnAddrDelta < 0)
1140 Offset -= TailCallReturnAddrDelta;
1146 bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1147 MachineBasicBlock::iterator MI,
1148 const std::vector<CalleeSavedInfo> &CSI,
1149 const TargetRegisterInfo *TRI) const {
1153 DebugLoc DL = MBB.findDebugLoc(MI);
1155 MachineFunction &MF = *MBB.getParent();
1157 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
1158 unsigned FPReg = TRI->getFrameRegister(MF);
1159 unsigned CalleeFrameSize = 0;
1161 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1162 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1164 // Push GPRs. It increases frame size.
1165 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1166 for (unsigned i = CSI.size(); i != 0; --i) {
1167 unsigned Reg = CSI[i-1].getReg();
1168 if (!X86::GR64RegClass.contains(Reg) &&
1169 !X86::GR32RegClass.contains(Reg))
1171 // Add the callee-saved register as live-in. It's killed at the spill.
1174 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
1176 CalleeFrameSize += SlotSize;
1177 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1178 .setMIFlag(MachineInstr::FrameSetup);
1181 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
1183 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1184 // It can be done by spilling XMMs to stack frame.
1185 // Note that only Win64 ABI might spill XMMs.
1186 for (unsigned i = CSI.size(); i != 0; --i) {
1187 unsigned Reg = CSI[i-1].getReg();
1188 if (X86::GR64RegClass.contains(Reg) ||
1189 X86::GR32RegClass.contains(Reg))
1191 // Add the callee-saved register as live-in. It's killed at the spill.
1193 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1194 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
1201 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1202 MachineBasicBlock::iterator MI,
1203 const std::vector<CalleeSavedInfo> &CSI,
1204 const TargetRegisterInfo *TRI) const {
1208 DebugLoc DL = MBB.findDebugLoc(MI);
1210 MachineFunction &MF = *MBB.getParent();
1211 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1213 // Reload XMMs from stack frame.
1214 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1215 unsigned Reg = CSI[i].getReg();
1216 if (X86::GR64RegClass.contains(Reg) ||
1217 X86::GR32RegClass.contains(Reg))
1219 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1220 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
1225 unsigned FPReg = TRI->getFrameRegister(MF);
1226 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1227 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1228 unsigned Reg = CSI[i].getReg();
1229 if (!X86::GR64RegClass.contains(Reg) &&
1230 !X86::GR32RegClass.contains(Reg))
1233 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
1235 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1241 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1242 RegScavenger *RS) const {
1243 MachineFrameInfo *MFI = MF.getFrameInfo();
1244 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
1245 unsigned SlotSize = RegInfo->getSlotSize();
1247 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1248 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1250 if (TailCallReturnAddrDelta < 0) {
1251 // create RETURNADDR area
1260 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1261 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1265 assert((TailCallReturnAddrDelta <= 0) &&
1266 "The Delta should always be zero or negative");
1267 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
1269 // Create a frame entry for the EBP register that must be saved.
1270 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1272 TFI.getOffsetOfLocalArea() +
1273 TailCallReturnAddrDelta,
1275 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1276 "Slot for EBP register must be last in order to be found!");
1282 HasNestArgument(const MachineFunction *MF) {
1283 const Function *F = MF->getFunction();
1284 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1286 if (I->hasNestAttr())
1293 GetScratchRegister(bool Is64Bit, const MachineFunction &MF) {
1297 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1298 bool IsNested = HasNestArgument(&MF);
1300 if (CallingConvention == CallingConv::X86_FastCall) {
1302 report_fatal_error("Segmented stacks does not support fastcall with "
1303 "nested function.");
1318 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1319 MachineBasicBlock &prologueMBB = MF.front();
1320 MachineFrameInfo *MFI = MF.getFrameInfo();
1321 const X86InstrInfo &TII = *TM.getInstrInfo();
1323 bool Is64Bit = STI.is64Bit();
1324 unsigned TlsReg, TlsOffset;
1326 const X86Subtarget *ST = &MF.getTarget().getSubtarget<X86Subtarget>();
1328 unsigned ScratchReg = GetScratchRegister(Is64Bit, MF);
1329 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1330 "Scratch register is live-in");
1332 if (MF.getFunction()->isVarArg())
1333 report_fatal_error("Segmented stacks do not support vararg functions.");
1334 if (!ST->isTargetLinux())
1335 report_fatal_error("Segmented stacks supported only on linux.");
1337 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1338 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1339 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1340 bool IsNested = false;
1342 // We need to know if the function has a nest argument only in 64 bit mode.
1344 IsNested = HasNestArgument(&MF);
1346 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1347 e = prologueMBB.livein_end(); i != e; i++) {
1348 allocMBB->addLiveIn(*i);
1349 checkMBB->addLiveIn(*i);
1353 allocMBB->addLiveIn(X86::R10);
1355 MF.push_front(allocMBB);
1356 MF.push_front(checkMBB);
1358 // Eventually StackSize will be calculated by a link-time pass; which will
1359 // also decide whether checking code needs to be injected into this particular
1361 StackSize = MFI->getStackSize();
1363 // Read the limit off the current stacklet off the stack_guard location.
1368 BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RSP)
1369 .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1370 BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
1371 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1376 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1377 .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1378 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1379 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1382 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1383 // It jumps to normal execution of the function body.
1384 BuildMI(checkMBB, DL, TII.get(X86::JG_4)).addMBB(&prologueMBB);
1386 // On 32 bit we first push the arguments size and then the frame size. On 64
1387 // bit, we pass the stack frame size in r10 and the argument size in r11.
1389 // Functions with nested arguments use R10, so it needs to be saved across
1390 // the call to _morestack
1393 BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::RAX).addReg(X86::R10);
1395 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R10)
1397 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R11)
1398 .addImm(X86FI->getArgumentStackSize());
1399 MF.getRegInfo().setPhysRegUsed(X86::R10);
1400 MF.getRegInfo().setPhysRegUsed(X86::R11);
1402 // Since we'll call __morestack, stack alignment needs to be preserved.
1403 BuildMI(allocMBB, DL, TII.get(X86::SUB32ri), X86::ESP).addReg(X86::ESP)
1405 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1406 .addImm(X86FI->getArgumentStackSize());
1407 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1411 // __morestack is in libgcc
1413 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1414 .addExternalSymbol("__morestack");
1416 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1417 .addExternalSymbol("__morestack");
1419 // __morestack only seems to remove 8 bytes off the stack. Add back the
1420 // additional 8 bytes we added before pushing the arguments.
1422 BuildMI(allocMBB, DL, TII.get(X86::ADD32ri), X86::ESP).addReg(X86::ESP)
1424 BuildMI(allocMBB, DL, TII.get(X86::RET));
1426 if (Is64Bit && IsNested)
1427 BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::R10).addReg(X86::RAX);
1429 allocMBB->addSuccessor(&prologueMBB);
1430 checkMBB->addSuccessor(allocMBB);
1431 checkMBB->addSuccessor(&prologueMBB);