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 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
39 return !MF.getFrameInfo()->hasVarSizedObjects();
42 /// hasFP - Return true if the specified function should have a dedicated frame
43 /// pointer register. This is true if the function has variable sized allocas
44 /// or if frame pointer elimination is disabled.
45 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
46 const MachineFrameInfo *MFI = MF.getFrameInfo();
47 const MachineModuleInfo &MMI = MF.getMMI();
48 const TargetRegisterInfo *RI = TM.getRegisterInfo();
50 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
51 RI->needsStackRealignment(MF) ||
52 MFI->hasVarSizedObjects() ||
53 MFI->isFrameAddressTaken() ||
54 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
55 MMI.callsUnwindInit());
58 static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
62 return X86::SUB64ri32;
70 static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
74 return X86::ADD64ri32;
82 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
83 /// when it reaches the "return" instruction. We can then pop a stack object
84 /// to this register without worry about clobbering it.
85 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
86 MachineBasicBlock::iterator &MBBI,
87 const TargetRegisterInfo &TRI,
89 const MachineFunction *MF = MBB.getParent();
90 const Function *F = MF->getFunction();
91 if (!F || MF->getMMI().callsEHReturn())
94 static const unsigned CallerSavedRegs32Bit[] = {
95 X86::EAX, X86::EDX, X86::ECX, 0
98 static const unsigned CallerSavedRegs64Bit[] = {
99 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
100 X86::R8, X86::R9, X86::R10, X86::R11, 0
103 unsigned Opc = MBBI->getOpcode();
108 case X86::TCRETURNdi:
109 case X86::TCRETURNri:
110 case X86::TCRETURNmi:
111 case X86::TCRETURNdi64:
112 case X86::TCRETURNri64:
113 case X86::TCRETURNmi64:
115 case X86::EH_RETURN64: {
116 SmallSet<unsigned, 8> Uses;
117 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
118 MachineOperand &MO = MBBI->getOperand(i);
119 if (!MO.isReg() || MO.isDef())
121 unsigned Reg = MO.getReg();
124 for (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
128 const unsigned *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
130 if (!Uses.count(*CS))
139 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
140 /// stack pointer by a constant value.
142 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
143 unsigned StackPtr, int64_t NumBytes,
144 bool Is64Bit, const TargetInstrInfo &TII,
145 const TargetRegisterInfo &TRI) {
146 bool isSub = NumBytes < 0;
147 uint64_t Offset = isSub ? -NumBytes : NumBytes;
148 unsigned Opc = isSub ?
149 getSUBriOpcode(Is64Bit, Offset) :
150 getADDriOpcode(Is64Bit, Offset);
151 uint64_t Chunk = (1LL << 31) - 1;
152 DebugLoc DL = MBB.findDebugLoc(MBBI);
155 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
156 if (ThisVal == (Is64Bit ? 8 : 4)) {
157 // Use push / pop instead.
159 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
160 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
163 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
164 : (Is64Bit ? X86::POP64r : X86::POP32r);
165 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
166 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
168 MI->setFlag(MachineInstr::FrameSetup);
175 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
179 MI->setFlag(MachineInstr::FrameSetup);
180 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
185 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
187 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
188 unsigned StackPtr, uint64_t *NumBytes = NULL) {
189 if (MBBI == MBB.begin()) return;
191 MachineBasicBlock::iterator PI = prior(MBBI);
192 unsigned Opc = PI->getOpcode();
193 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
194 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
195 PI->getOperand(0).getReg() == StackPtr) {
197 *NumBytes += PI->getOperand(2).getImm();
199 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
200 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
201 PI->getOperand(0).getReg() == StackPtr) {
203 *NumBytes -= PI->getOperand(2).getImm();
208 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
210 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
211 MachineBasicBlock::iterator &MBBI,
212 unsigned StackPtr, uint64_t *NumBytes = NULL) {
213 // FIXME: THIS ISN'T RUN!!!
216 if (MBBI == MBB.end()) return;
218 MachineBasicBlock::iterator NI = llvm::next(MBBI);
219 if (NI == MBB.end()) return;
221 unsigned Opc = NI->getOpcode();
222 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
223 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
224 NI->getOperand(0).getReg() == StackPtr) {
226 *NumBytes -= NI->getOperand(2).getImm();
229 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
230 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
231 NI->getOperand(0).getReg() == StackPtr) {
233 *NumBytes += NI->getOperand(2).getImm();
239 /// mergeSPUpdates - Checks the instruction before/after the passed
240 /// instruction. If it is an ADD/SUB instruction it is deleted argument and the
241 /// stack adjustment is returned as a positive value for ADD and a negative for
243 static int mergeSPUpdates(MachineBasicBlock &MBB,
244 MachineBasicBlock::iterator &MBBI,
246 bool doMergeWithPrevious) {
247 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
248 (!doMergeWithPrevious && MBBI == MBB.end()))
251 MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
252 MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
253 unsigned Opc = PI->getOpcode();
256 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
257 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
258 PI->getOperand(0).getReg() == StackPtr){
259 Offset += PI->getOperand(2).getImm();
261 if (!doMergeWithPrevious) MBBI = NI;
262 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
263 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
264 PI->getOperand(0).getReg() == StackPtr) {
265 Offset -= PI->getOperand(2).getImm();
267 if (!doMergeWithPrevious) MBBI = NI;
273 static bool isEAXLiveIn(MachineFunction &MF) {
274 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
275 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
276 unsigned Reg = II->first;
278 if (Reg == X86::EAX || Reg == X86::AX ||
279 Reg == X86::AH || Reg == X86::AL)
286 void X86FrameLowering::emitCalleeSavedFrameMoves(MachineFunction &MF,
288 unsigned FramePtr) const {
289 MachineFrameInfo *MFI = MF.getFrameInfo();
290 MachineModuleInfo &MMI = MF.getMMI();
292 // Add callee saved registers to move list.
293 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
294 if (CSI.empty()) return;
296 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
297 const TargetData *TD = TM.getTargetData();
298 bool HasFP = hasFP(MF);
300 // Calculate amount of bytes used for return address storing.
301 int stackGrowth = -TD->getPointerSize();
303 // FIXME: This is dirty hack. The code itself is pretty mess right now.
304 // It should be rewritten from scratch and generalized sometimes.
306 // Determine maximum offset (minimum due to stack growth).
307 int64_t MaxOffset = 0;
308 for (std::vector<CalleeSavedInfo>::const_iterator
309 I = CSI.begin(), E = CSI.end(); I != E; ++I)
310 MaxOffset = std::min(MaxOffset,
311 MFI->getObjectOffset(I->getFrameIdx()));
313 // Calculate offsets.
314 int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
315 for (std::vector<CalleeSavedInfo>::const_iterator
316 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
317 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
318 unsigned Reg = I->getReg();
319 Offset = MaxOffset - Offset + saveAreaOffset;
321 // Don't output a new machine move if we're re-saving the frame
322 // pointer. This happens when the PrologEpilogInserter has inserted an extra
323 // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
324 // generates one when frame pointers are used. If we generate a "machine
325 // move" for this extra "PUSH", the linker will lose track of the fact that
326 // the frame pointer should have the value of the first "PUSH" when it's
329 // FIXME: This looks inelegant. It's possibly correct, but it's covering up
330 // another bug. I.e., one where we generate a prolog like this:
338 // The immediate re-push of EBP is unnecessary. At the least, it's an
339 // optimization bug. EBP can be used as a scratch register in certain
340 // cases, but probably not when we have a frame pointer.
341 if (HasFP && FramePtr == Reg)
344 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
345 MachineLocation CSSrc(Reg);
346 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
350 /// getCompactUnwindRegNum - Get the compact unwind number for a given
351 /// register. The number corresponds to the enum lists in
352 /// compact_unwind_encoding.h.
353 static int getCompactUnwindRegNum(const unsigned *CURegs, unsigned Reg) {
355 for (; *CURegs; ++CURegs, ++Idx)
362 // Number of registers that can be saved in a compact unwind encoding.
363 #define CU_NUM_SAVED_REGS 6
365 /// encodeCompactUnwindRegistersWithoutFrame - Create the permutation encoding
366 /// used with frameless stacks. It is passed the number of registers to be saved
367 /// and an array of the registers saved.
369 encodeCompactUnwindRegistersWithoutFrame(unsigned SavedRegs[CU_NUM_SAVED_REGS],
370 unsigned RegCount, bool Is64Bit) {
371 // The saved registers are numbered from 1 to 6. In order to encode the order
372 // in which they were saved, we re-number them according to their place in the
373 // register order. The re-numbering is relative to the last re-numbered
374 // register. E.g., if we have registers {6, 2, 4, 5} saved in that order:
383 static const unsigned CU32BitRegs[] = {
384 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
386 static const unsigned CU64BitRegs[] = {
387 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
389 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
391 for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i) {
392 int CUReg = getCompactUnwindRegNum(CURegs, SavedRegs[i]);
393 if (CUReg == -1) return ~0U;
394 SavedRegs[i] = CUReg;
397 uint32_t RenumRegs[CU_NUM_SAVED_REGS];
398 for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i) {
399 unsigned Countless = 0;
400 for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
401 if (SavedRegs[j] < SavedRegs[i])
404 RenumRegs[i] = SavedRegs[i] - Countless - 1;
407 // Take the renumbered values and encode them into a 10-bit number.
408 uint32_t permutationEncoding = 0;
411 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
412 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
416 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
417 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
421 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
422 + 3 * RenumRegs[4] + RenumRegs[5];
425 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
429 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
432 permutationEncoding |= RenumRegs[5];
436 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
437 "Invalid compact register encoding!");
438 return permutationEncoding;
441 /// encodeCompactUnwindRegistersWithFrame - Return the registers encoded for a
442 /// compact encoding with a frame pointer.
444 encodeCompactUnwindRegistersWithFrame(unsigned SavedRegs[CU_NUM_SAVED_REGS],
446 static const unsigned CU32BitRegs[] = {
447 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
449 static const unsigned CU64BitRegs[] = {
450 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
452 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
454 // Encode the registers in the order they were saved, 3-bits per register. The
455 // registers are numbered from 1 to 6.
457 for (int I = 5; I >= 0; --I) {
458 unsigned Reg = SavedRegs[I];
460 int CURegNum = getCompactUnwindRegNum(CURegs, Reg);
464 // Encode the 3-bit register number in order, skipping over 3-bits for each
466 RegEnc |= (CURegNum & 0x7) << ((5 - I) * 3);
469 assert((RegEnc & 0x7FFF) == RegEnc && "Invalid compact register encoding!");
473 uint32_t X86FrameLowering::getCompactUnwindEncoding(MachineFunction &MF) const {
474 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
475 unsigned FramePtr = RegInfo->getFrameRegister(MF);
476 unsigned StackPtr = RegInfo->getStackRegister();
478 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
479 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
481 bool Is64Bit = STI.is64Bit();
482 bool HasFP = hasFP(MF);
484 unsigned SavedRegs[CU_NUM_SAVED_REGS] = { 0, 0, 0, 0, 0, 0 };
485 int SavedRegIdx = CU_NUM_SAVED_REGS;
487 unsigned OffsetSize = (Is64Bit ? 8 : 4);
489 unsigned PushInstr = (Is64Bit ? X86::PUSH64r : X86::PUSH32r);
490 unsigned PushInstrSize = 1;
491 unsigned MoveInstr = (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
492 unsigned MoveInstrSize = (Is64Bit ? 3 : 2);
493 unsigned SubtractInstr = getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta);
494 unsigned SubtractInstrIdx = (Is64Bit ? 3 : 2);
496 unsigned StackDivide = (Is64Bit ? 8 : 4);
498 unsigned InstrOffset = 0;
499 unsigned StackAdjust = 0;
500 unsigned StackSize = 0;
502 MachineBasicBlock &MBB = MF.front(); // Prologue is in entry BB.
503 bool ExpectEnd = false;
504 for (MachineBasicBlock::iterator
505 MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ++MBBI) {
506 MachineInstr &MI = *MBBI;
507 unsigned Opc = MI.getOpcode();
508 if (Opc == X86::PROLOG_LABEL) continue;
509 if (!MI.getFlag(MachineInstr::FrameSetup)) break;
511 // We don't exect any more prolog instructions.
512 if (ExpectEnd) return 0;
514 if (Opc == PushInstr) {
515 // If there are too many saved registers, we cannot use compact encoding.
516 if (--SavedRegIdx < 0) return 0;
518 SavedRegs[SavedRegIdx] = MI.getOperand(0).getReg();
519 StackAdjust += OffsetSize;
520 InstrOffset += PushInstrSize;
521 } else if (Opc == MoveInstr) {
522 unsigned SrcReg = MI.getOperand(1).getReg();
523 unsigned DstReg = MI.getOperand(0).getReg();
525 if (DstReg != FramePtr || SrcReg != StackPtr)
529 memset(SavedRegs, 0, sizeof(SavedRegs));
530 SavedRegIdx = CU_NUM_SAVED_REGS;
531 InstrOffset += MoveInstrSize;
532 } else if (Opc == SubtractInstr) {
534 // We already have a stack size.
537 if (!MI.getOperand(0).isReg() ||
538 MI.getOperand(0).getReg() != MI.getOperand(1).getReg() ||
539 MI.getOperand(0).getReg() != StackPtr || !MI.getOperand(2).isImm())
540 // We need this to be a stack adjustment pointer. Something like:
542 // %RSP<def> = SUB64ri8 %RSP, 48
545 StackSize = MI.getOperand(2).getImm() / StackDivide;
546 SubtractInstrIdx += InstrOffset;
551 // Encode that we are using EBP/RBP as the frame pointer.
552 uint32_t CompactUnwindEncoding = 0;
553 StackAdjust /= StackDivide;
555 if ((StackAdjust & 0xFF) != StackAdjust)
556 // Offset was too big for compact encoding.
559 // Get the encoding of the saved registers when we have a frame pointer.
560 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame(SavedRegs, Is64Bit);
561 if (RegEnc == ~0U) return 0;
563 CompactUnwindEncoding |= 0x01000000;
564 CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
565 CompactUnwindEncoding |= RegEnc & 0x7FFF;
567 if ((StackSize & 0xFF) == StackSize) {
568 // Frameless stack with a small stack size.
569 CompactUnwindEncoding |= 0x02000000;
571 // Encode the stack size.
572 CompactUnwindEncoding |= (StackSize & 0xFF) << 16;
574 if ((StackAdjust & 0x7) != StackAdjust)
575 // The extra stack adjustments are too big for us to handle.
578 // Frameless stack with an offset too large for us to encode compactly.
579 CompactUnwindEncoding |= 0x03000000;
581 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
583 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
585 // Encode any extra stack stack adjustments (done via push instructions).
586 CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
589 // Encode the number of registers saved.
590 CompactUnwindEncoding |= ((CU_NUM_SAVED_REGS - SavedRegIdx) & 0x7) << 10;
592 // Get the encoding of the saved registers when we don't have a frame
595 encodeCompactUnwindRegistersWithoutFrame(SavedRegs,
596 CU_NUM_SAVED_REGS - SavedRegIdx,
598 if (RegEnc == ~0U) return 0;
600 // Encode the register encoding.
601 CompactUnwindEncoding |= RegEnc & 0x3FF;
604 return CompactUnwindEncoding;
607 /// emitPrologue - Push callee-saved registers onto the stack, which
608 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
609 /// space for local variables. Also emit labels used by the exception handler to
610 /// generate the exception handling frames.
611 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
612 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
613 MachineBasicBlock::iterator MBBI = MBB.begin();
614 MachineFrameInfo *MFI = MF.getFrameInfo();
615 const Function *Fn = MF.getFunction();
616 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
617 const X86InstrInfo &TII = *TM.getInstrInfo();
618 MachineModuleInfo &MMI = MF.getMMI();
619 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
620 bool needsFrameMoves = MMI.hasDebugInfo() ||
621 Fn->needsUnwindTableEntry();
622 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
623 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
624 bool HasFP = hasFP(MF);
625 bool Is64Bit = STI.is64Bit();
626 bool IsWin64 = STI.isTargetWin64();
627 unsigned StackAlign = getStackAlignment();
628 unsigned SlotSize = RegInfo->getSlotSize();
629 unsigned FramePtr = RegInfo->getFrameRegister(MF);
630 unsigned StackPtr = RegInfo->getStackRegister();
633 // If we're forcing a stack realignment we can't rely on just the frame
634 // info, we need to know the ABI stack alignment as well in case we
635 // have a call out. Otherwise just make sure we have some alignment - we'll
636 // go with the minimum SlotSize.
637 if (ForceStackAlign) {
639 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
640 else if (MaxAlign < SlotSize)
644 // Add RETADDR move area to callee saved frame size.
645 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
646 if (TailCallReturnAddrDelta < 0)
647 X86FI->setCalleeSavedFrameSize(
648 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
650 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
651 // function, and use up to 128 bytes of stack space, don't have a frame
652 // pointer, calls, or dynamic alloca then we do not need to adjust the
653 // stack pointer (we fit in the Red Zone).
654 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
655 !RegInfo->needsStackRealignment(MF) &&
656 !MFI->hasVarSizedObjects() && // No dynamic alloca.
657 !MFI->adjustsStack() && // No calls.
658 !IsWin64 && // Win64 has no Red Zone
659 !MF.getTarget().Options.EnableSegmentedStacks) { // Regular stack
660 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
661 if (HasFP) MinSize += SlotSize;
662 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
663 MFI->setStackSize(StackSize);
666 // Insert stack pointer adjustment for later moving of return addr. Only
667 // applies to tail call optimized functions where the callee argument stack
668 // size is bigger than the callers.
669 if (TailCallReturnAddrDelta < 0) {
671 BuildMI(MBB, MBBI, DL,
672 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
675 .addImm(-TailCallReturnAddrDelta)
676 .setMIFlag(MachineInstr::FrameSetup);
677 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
680 // Mapping for machine moves:
682 // DST: VirtualFP AND
683 // SRC: VirtualFP => DW_CFA_def_cfa_offset
684 // ELSE => DW_CFA_def_cfa
686 // SRC: VirtualFP AND
687 // DST: Register => DW_CFA_def_cfa_register
690 // OFFSET < 0 => DW_CFA_offset_extended_sf
691 // REG < 64 => DW_CFA_offset + Reg
692 // ELSE => DW_CFA_offset_extended
694 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
695 const TargetData *TD = MF.getTarget().getTargetData();
696 uint64_t NumBytes = 0;
697 int stackGrowth = -TD->getPointerSize();
700 // Calculate required stack adjustment.
701 uint64_t FrameSize = StackSize - SlotSize;
702 if (RegInfo->needsStackRealignment(MF))
703 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
705 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
707 // Get the offset of the stack slot for the EBP register, which is
708 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
709 // Update the frame offset adjustment.
710 MFI->setOffsetAdjustment(-NumBytes);
712 // Save EBP/RBP into the appropriate stack slot.
713 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
714 .addReg(FramePtr, RegState::Kill)
715 .setMIFlag(MachineInstr::FrameSetup);
717 if (needsFrameMoves) {
718 // Mark the place where EBP/RBP was saved.
719 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
720 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
723 // Define the current CFA rule to use the provided offset.
725 MachineLocation SPDst(MachineLocation::VirtualFP);
726 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
727 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
729 MachineLocation SPDst(StackPtr);
730 MachineLocation SPSrc(StackPtr, stackGrowth);
731 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
734 // Change the rule for the FramePtr to be an "offset" rule.
735 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
736 MachineLocation FPSrc(FramePtr);
737 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
740 // Update EBP with the new base value.
741 BuildMI(MBB, MBBI, DL,
742 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
744 .setMIFlag(MachineInstr::FrameSetup);
746 if (needsFrameMoves) {
747 // Mark effective beginning of when frame pointer becomes valid.
748 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
749 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
752 // Define the current CFA to use the EBP/RBP register.
753 MachineLocation FPDst(FramePtr);
754 MachineLocation FPSrc(MachineLocation::VirtualFP);
755 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
758 // Mark the FramePtr as live-in in every block except the entry.
759 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
761 I->addLiveIn(FramePtr);
764 if (RegInfo->needsStackRealignment(MF)) {
766 BuildMI(MBB, MBBI, DL,
767 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
770 .setMIFlag(MachineInstr::FrameSetup);
772 // The EFLAGS implicit def is dead.
773 MI->getOperand(3).setIsDead();
776 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
779 // Skip the callee-saved push instructions.
780 bool PushedRegs = false;
781 int StackOffset = 2 * stackGrowth;
783 while (MBBI != MBB.end() &&
784 (MBBI->getOpcode() == X86::PUSH32r ||
785 MBBI->getOpcode() == X86::PUSH64r)) {
787 MBBI->setFlag(MachineInstr::FrameSetup);
790 if (!HasFP && needsFrameMoves) {
791 // Mark callee-saved push instruction.
792 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
793 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
795 // Define the current CFA rule to use the provided offset.
796 unsigned Ptr = StackSize ? MachineLocation::VirtualFP : StackPtr;
797 MachineLocation SPDst(Ptr);
798 MachineLocation SPSrc(Ptr, StackOffset);
799 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
800 StackOffset += stackGrowth;
804 DL = MBB.findDebugLoc(MBBI);
806 // If there is an SUB32ri of ESP immediately before this instruction, merge
807 // the two. This can be the case when tail call elimination is enabled and
808 // the callee has more arguments then the caller.
809 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
811 // If there is an ADD32ri or SUB32ri of ESP immediately after this
812 // instruction, merge the two instructions.
813 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
815 // Adjust stack pointer: ESP -= numbytes.
817 // Windows and cygwin/mingw require a prologue helper routine when allocating
818 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
819 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
820 // stack and adjust the stack pointer in one go. The 64-bit version of
821 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
822 // responsible for adjusting the stack pointer. Touching the stack at 4K
823 // increments is necessary to ensure that the guard pages used by the OS
824 // virtual memory manager are allocated in correct sequence.
825 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
826 const char *StackProbeSymbol;
827 bool isSPUpdateNeeded = false;
830 if (STI.isTargetCygMing())
831 StackProbeSymbol = "___chkstk";
833 StackProbeSymbol = "__chkstk";
834 isSPUpdateNeeded = true;
836 } else if (STI.isTargetCygMing())
837 StackProbeSymbol = "_alloca";
839 StackProbeSymbol = "_chkstk";
841 // Check whether EAX is livein for this function.
842 bool isEAXAlive = isEAXLiveIn(MF);
845 // Sanity check that EAX is not livein for this function.
846 // It should not be, so throw an assert.
847 assert(!Is64Bit && "EAX is livein in x64 case!");
850 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
851 .addReg(X86::EAX, RegState::Kill)
852 .setMIFlag(MachineInstr::FrameSetup);
856 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
857 // Function prologue is responsible for adjusting the stack pointer.
858 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
860 .setMIFlag(MachineInstr::FrameSetup);
862 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
863 // We'll also use 4 already allocated bytes for EAX.
864 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
865 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
866 .setMIFlag(MachineInstr::FrameSetup);
869 BuildMI(MBB, MBBI, DL,
870 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
871 .addExternalSymbol(StackProbeSymbol)
872 .addReg(StackPtr, RegState::Define | RegState::Implicit)
873 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
874 .setMIFlag(MachineInstr::FrameSetup);
876 // MSVC x64's __chkstk needs to adjust %rsp.
877 // FIXME: %rax preserves the offset and should be available.
878 if (isSPUpdateNeeded)
879 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
884 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
886 StackPtr, false, NumBytes - 4);
887 MI->setFlag(MachineInstr::FrameSetup);
888 MBB.insert(MBBI, MI);
891 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
894 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
895 // Mark end of stack pointer adjustment.
896 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
897 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
900 if (!HasFP && NumBytes) {
901 // Define the current CFA rule to use the provided offset.
903 MachineLocation SPDst(MachineLocation::VirtualFP);
904 MachineLocation SPSrc(MachineLocation::VirtualFP,
905 -StackSize + stackGrowth);
906 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
908 MachineLocation SPDst(StackPtr);
909 MachineLocation SPSrc(StackPtr, stackGrowth);
910 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
914 // Emit DWARF info specifying the offsets of the callee-saved registers.
916 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
919 // Darwin 10.7 and greater has support for compact unwind encoding.
920 if (STI.getTargetTriple().isMacOSX() &&
921 !STI.getTargetTriple().isMacOSXVersionLT(10, 7))
922 MMI.setCompactUnwindEncoding(getCompactUnwindEncoding(MF));
925 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
926 MachineBasicBlock &MBB) const {
927 const MachineFrameInfo *MFI = MF.getFrameInfo();
928 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
929 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
930 const X86InstrInfo &TII = *TM.getInstrInfo();
931 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
932 assert(MBBI != MBB.end() && "Returning block has no instructions");
933 unsigned RetOpcode = MBBI->getOpcode();
934 DebugLoc DL = MBBI->getDebugLoc();
935 bool Is64Bit = STI.is64Bit();
936 unsigned StackAlign = getStackAlignment();
937 unsigned SlotSize = RegInfo->getSlotSize();
938 unsigned FramePtr = RegInfo->getFrameRegister(MF);
939 unsigned StackPtr = RegInfo->getStackRegister();
943 llvm_unreachable("Can only insert epilog into returning blocks");
946 case X86::TCRETURNdi:
947 case X86::TCRETURNri:
948 case X86::TCRETURNmi:
949 case X86::TCRETURNdi64:
950 case X86::TCRETURNri64:
951 case X86::TCRETURNmi64:
953 case X86::EH_RETURN64:
954 break; // These are ok
957 // Get the number of bytes to allocate from the FrameInfo.
958 uint64_t StackSize = MFI->getStackSize();
959 uint64_t MaxAlign = MFI->getMaxAlignment();
960 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
961 uint64_t NumBytes = 0;
963 // If we're forcing a stack realignment we can't rely on just the frame
964 // info, we need to know the ABI stack alignment as well in case we
965 // have a call out. Otherwise just make sure we have some alignment - we'll
966 // go with the minimum.
967 if (ForceStackAlign) {
969 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
971 MaxAlign = MaxAlign ? MaxAlign : 4;
975 // Calculate required stack adjustment.
976 uint64_t FrameSize = StackSize - SlotSize;
977 if (RegInfo->needsStackRealignment(MF))
978 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
980 NumBytes = FrameSize - CSSize;
983 BuildMI(MBB, MBBI, DL,
984 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
986 NumBytes = StackSize - CSSize;
989 // Skip the callee-saved pop instructions.
990 MachineBasicBlock::iterator LastCSPop = MBBI;
991 while (MBBI != MBB.begin()) {
992 MachineBasicBlock::iterator PI = prior(MBBI);
993 unsigned Opc = PI->getOpcode();
995 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
996 !PI->getDesc().isTerminator())
1002 DL = MBBI->getDebugLoc();
1004 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1005 // instruction, merge the two instructions.
1006 if (NumBytes || MFI->hasVarSizedObjects())
1007 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1009 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1010 // slot before popping them off! Same applies for the case, when stack was
1012 if (RegInfo->needsStackRealignment(MF)) {
1013 // We cannot use LEA here, because stack pointer was realigned. We need to
1014 // deallocate local frame back.
1016 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
1017 MBBI = prior(LastCSPop);
1020 BuildMI(MBB, MBBI, DL,
1021 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1022 StackPtr).addReg(FramePtr);
1023 } else if (MFI->hasVarSizedObjects()) {
1025 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
1027 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
1028 FramePtr, false, -CSSize);
1029 MBB.insert(MBBI, MI);
1031 BuildMI(MBB, MBBI, DL,
1032 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
1035 } else if (NumBytes) {
1036 // Adjust stack pointer back: ESP += numbytes.
1037 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
1040 // We're returning from function via eh_return.
1041 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
1042 MBBI = MBB.getLastNonDebugInstr();
1043 MachineOperand &DestAddr = MBBI->getOperand(0);
1044 assert(DestAddr.isReg() && "Offset should be in register!");
1045 BuildMI(MBB, MBBI, DL,
1046 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1047 StackPtr).addReg(DestAddr.getReg());
1048 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1049 RetOpcode == X86::TCRETURNmi ||
1050 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1051 RetOpcode == X86::TCRETURNmi64) {
1052 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1053 // Tail call return: adjust the stack pointer and jump to callee.
1054 MBBI = MBB.getLastNonDebugInstr();
1055 MachineOperand &JumpTarget = MBBI->getOperand(0);
1056 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1057 assert(StackAdjust.isImm() && "Expecting immediate value.");
1059 // Adjust stack pointer.
1060 int StackAdj = StackAdjust.getImm();
1061 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1063 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1065 // Incoporate the retaddr area.
1066 Offset = StackAdj-MaxTCDelta;
1067 assert(Offset >= 0 && "Offset should never be negative");
1070 // Check for possible merge with preceding ADD instruction.
1071 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1072 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
1075 // Jump to label or value in register.
1076 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1077 MachineInstrBuilder MIB =
1078 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1079 ? X86::TAILJMPd : X86::TAILJMPd64));
1080 if (JumpTarget.isGlobal())
1081 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1082 JumpTarget.getTargetFlags());
1084 assert(JumpTarget.isSymbol());
1085 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1086 JumpTarget.getTargetFlags());
1088 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1089 MachineInstrBuilder MIB =
1090 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1091 ? X86::TAILJMPm : X86::TAILJMPm64));
1092 for (unsigned i = 0; i != 5; ++i)
1093 MIB.addOperand(MBBI->getOperand(i));
1094 } else if (RetOpcode == X86::TCRETURNri64) {
1095 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1096 addReg(JumpTarget.getReg(), RegState::Kill);
1098 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1099 addReg(JumpTarget.getReg(), RegState::Kill);
1102 MachineInstr *NewMI = prior(MBBI);
1103 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
1104 NewMI->addOperand(MBBI->getOperand(i));
1106 // Delete the pseudo instruction TCRETURN.
1108 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
1109 (X86FI->getTCReturnAddrDelta() < 0)) {
1110 // Add the return addr area delta back since we are not tail calling.
1111 int delta = -1*X86FI->getTCReturnAddrDelta();
1112 MBBI = MBB.getLastNonDebugInstr();
1114 // Check for possible merge with preceding ADD instruction.
1115 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1116 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
1120 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
1121 const X86RegisterInfo *RI =
1122 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
1123 const MachineFrameInfo *MFI = MF.getFrameInfo();
1124 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1125 uint64_t StackSize = MFI->getStackSize();
1127 if (RI->needsStackRealignment(MF)) {
1129 // Skip the saved EBP.
1130 Offset += RI->getSlotSize();
1132 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1133 return Offset + StackSize;
1135 // FIXME: Support tail calls
1138 return Offset + StackSize;
1140 // Skip the saved EBP.
1141 Offset += RI->getSlotSize();
1143 // Skip the RETADDR move area
1144 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1145 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1146 if (TailCallReturnAddrDelta < 0)
1147 Offset -= TailCallReturnAddrDelta;
1153 bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1154 MachineBasicBlock::iterator MI,
1155 const std::vector<CalleeSavedInfo> &CSI,
1156 const TargetRegisterInfo *TRI) const {
1160 DebugLoc DL = MBB.findDebugLoc(MI);
1162 MachineFunction &MF = *MBB.getParent();
1164 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
1165 unsigned FPReg = TRI->getFrameRegister(MF);
1166 unsigned CalleeFrameSize = 0;
1168 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1169 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1171 // Push GPRs. It increases frame size.
1172 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1173 for (unsigned i = CSI.size(); i != 0; --i) {
1174 unsigned Reg = CSI[i-1].getReg();
1175 if (!X86::GR64RegClass.contains(Reg) &&
1176 !X86::GR32RegClass.contains(Reg))
1178 // Add the callee-saved register as live-in. It's killed at the spill.
1181 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
1183 CalleeFrameSize += SlotSize;
1184 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1185 .setMIFlag(MachineInstr::FrameSetup);
1188 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
1190 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1191 // It can be done by spilling XMMs to stack frame.
1192 // Note that only Win64 ABI might spill XMMs.
1193 for (unsigned i = CSI.size(); i != 0; --i) {
1194 unsigned Reg = CSI[i-1].getReg();
1195 if (X86::GR64RegClass.contains(Reg) ||
1196 X86::GR32RegClass.contains(Reg))
1198 // Add the callee-saved register as live-in. It's killed at the spill.
1200 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1201 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
1208 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1209 MachineBasicBlock::iterator MI,
1210 const std::vector<CalleeSavedInfo> &CSI,
1211 const TargetRegisterInfo *TRI) const {
1215 DebugLoc DL = MBB.findDebugLoc(MI);
1217 MachineFunction &MF = *MBB.getParent();
1218 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1220 // Reload XMMs from stack frame.
1221 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1222 unsigned Reg = CSI[i].getReg();
1223 if (X86::GR64RegClass.contains(Reg) ||
1224 X86::GR32RegClass.contains(Reg))
1226 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1227 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
1232 unsigned FPReg = TRI->getFrameRegister(MF);
1233 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1234 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1235 unsigned Reg = CSI[i].getReg();
1236 if (!X86::GR64RegClass.contains(Reg) &&
1237 !X86::GR32RegClass.contains(Reg))
1240 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
1242 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1248 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1249 RegScavenger *RS) const {
1250 MachineFrameInfo *MFI = MF.getFrameInfo();
1251 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
1252 unsigned SlotSize = RegInfo->getSlotSize();
1254 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1255 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1257 if (TailCallReturnAddrDelta < 0) {
1258 // create RETURNADDR area
1267 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1268 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1272 assert((TailCallReturnAddrDelta <= 0) &&
1273 "The Delta should always be zero or negative");
1274 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
1276 // Create a frame entry for the EBP register that must be saved.
1277 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1279 TFI.getOffsetOfLocalArea() +
1280 TailCallReturnAddrDelta,
1282 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1283 "Slot for EBP register must be last in order to be found!");
1289 HasNestArgument(const MachineFunction *MF) {
1290 const Function *F = MF->getFunction();
1291 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1293 if (I->hasNestAttr())
1300 GetScratchRegister(bool Is64Bit, const MachineFunction &MF) {
1304 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1305 bool IsNested = HasNestArgument(&MF);
1307 if (CallingConvention == CallingConv::X86_FastCall) {
1309 report_fatal_error("Segmented stacks does not support fastcall with "
1310 "nested function.");
1324 // The stack limit in the TCB is set to this many bytes above the actual stack
1326 static const uint64_t kSplitStackAvailable = 256;
1329 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1330 MachineBasicBlock &prologueMBB = MF.front();
1331 MachineFrameInfo *MFI = MF.getFrameInfo();
1332 const X86InstrInfo &TII = *TM.getInstrInfo();
1334 bool Is64Bit = STI.is64Bit();
1335 unsigned TlsReg, TlsOffset;
1337 const X86Subtarget *ST = &MF.getTarget().getSubtarget<X86Subtarget>();
1339 unsigned ScratchReg = GetScratchRegister(Is64Bit, MF);
1340 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1341 "Scratch register is live-in");
1343 if (MF.getFunction()->isVarArg())
1344 report_fatal_error("Segmented stacks do not support vararg functions.");
1345 if (!ST->isTargetLinux())
1346 report_fatal_error("Segmented stacks supported only on linux.");
1348 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1349 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1350 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1351 bool IsNested = false;
1353 // We need to know if the function has a nest argument only in 64 bit mode.
1355 IsNested = HasNestArgument(&MF);
1357 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1358 // allocMBB needs to be last (terminating) instruction.
1360 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1361 e = prologueMBB.livein_end(); i != e; i++) {
1362 allocMBB->addLiveIn(*i);
1363 checkMBB->addLiveIn(*i);
1367 allocMBB->addLiveIn(X86::R10);
1369 MF.push_front(allocMBB);
1370 MF.push_front(checkMBB);
1372 // Eventually StackSize will be calculated by a link-time pass; which will
1373 // also decide whether checking code needs to be injected into this particular
1375 StackSize = MFI->getStackSize();
1377 // Read the limit off the current stacklet off the stack_guard location.
1382 if (StackSize < kSplitStackAvailable)
1383 ScratchReg = X86::RSP;
1385 BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RSP)
1386 .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1388 BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
1389 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1394 if (StackSize < kSplitStackAvailable)
1395 ScratchReg = X86::ESP;
1397 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1398 .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1400 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1401 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1404 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1405 // It jumps to normal execution of the function body.
1406 BuildMI(checkMBB, DL, TII.get(X86::JG_4)).addMBB(&prologueMBB);
1408 // On 32 bit we first push the arguments size and then the frame size. On 64
1409 // bit, we pass the stack frame size in r10 and the argument size in r11.
1411 // Functions with nested arguments use R10, so it needs to be saved across
1412 // the call to _morestack
1415 BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::RAX).addReg(X86::R10);
1417 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R10)
1419 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R11)
1420 .addImm(X86FI->getArgumentStackSize());
1421 MF.getRegInfo().setPhysRegUsed(X86::R10);
1422 MF.getRegInfo().setPhysRegUsed(X86::R11);
1424 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1425 .addImm(X86FI->getArgumentStackSize());
1426 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1430 // __morestack is in libgcc
1432 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1433 .addExternalSymbol("__morestack");
1435 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1436 .addExternalSymbol("__morestack");
1439 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1441 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1443 allocMBB->addSuccessor(&prologueMBB);
1445 checkMBB->addSuccessor(allocMBB);
1446 checkMBB->addSuccessor(&prologueMBB);