1 //=======- X86FrameInfo.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 TargetFrameInfo class.
12 //===----------------------------------------------------------------------===//
14 #include "X86FrameInfo.h"
15 #include "X86InstrBuilder.h"
16 #include "X86InstrInfo.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/Function.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Support/CommandLine.h"
31 // FIXME: completely move here.
32 extern cl::opt<bool> ForceStackAlign;
34 bool X86FrameInfo::hasReservedCallFrame(const MachineFunction &MF) const {
35 return !MF.getFrameInfo()->hasVarSizedObjects();
38 /// hasFP - Return true if the specified function should have a dedicated frame
39 /// pointer register. This is true if the function has variable sized allocas
40 /// or if frame pointer elimination is disabled.
41 bool X86FrameInfo::hasFP(const MachineFunction &MF) const {
42 const MachineFrameInfo *MFI = MF.getFrameInfo();
43 const MachineModuleInfo &MMI = MF.getMMI();
44 const TargetRegisterInfo *RI = TM.getRegisterInfo();
46 return (DisableFramePointerElim(MF) ||
47 RI->needsStackRealignment(MF) ||
48 MFI->hasVarSizedObjects() ||
49 MFI->isFrameAddressTaken() ||
50 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
51 MMI.callsUnwindInit());
54 static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
58 return X86::SUB64ri32;
66 static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
70 return X86::ADD64ri32;
78 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
79 /// stack pointer by a constant value.
81 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
82 unsigned StackPtr, int64_t NumBytes, bool Is64Bit,
83 const TargetInstrInfo &TII) {
84 bool isSub = NumBytes < 0;
85 uint64_t Offset = isSub ? -NumBytes : NumBytes;
86 unsigned Opc = isSub ?
87 getSUBriOpcode(Is64Bit, Offset) :
88 getADDriOpcode(Is64Bit, Offset);
89 uint64_t Chunk = (1LL << 31) - 1;
90 DebugLoc DL = MBB.findDebugLoc(MBBI);
93 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
95 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
98 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
103 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
105 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
106 unsigned StackPtr, uint64_t *NumBytes = NULL) {
107 if (MBBI == MBB.begin()) return;
109 MachineBasicBlock::iterator PI = prior(MBBI);
110 unsigned Opc = PI->getOpcode();
111 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
112 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
113 PI->getOperand(0).getReg() == StackPtr) {
115 *NumBytes += PI->getOperand(2).getImm();
117 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
118 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
119 PI->getOperand(0).getReg() == StackPtr) {
121 *NumBytes -= PI->getOperand(2).getImm();
126 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
128 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
129 MachineBasicBlock::iterator &MBBI,
130 unsigned StackPtr, uint64_t *NumBytes = NULL) {
131 // FIXME: THIS ISN'T RUN!!!
134 if (MBBI == MBB.end()) return;
136 MachineBasicBlock::iterator NI = llvm::next(MBBI);
137 if (NI == MBB.end()) return;
139 unsigned Opc = NI->getOpcode();
140 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
141 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
142 NI->getOperand(0).getReg() == StackPtr) {
144 *NumBytes -= NI->getOperand(2).getImm();
147 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
148 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
149 NI->getOperand(0).getReg() == StackPtr) {
151 *NumBytes += NI->getOperand(2).getImm();
157 /// mergeSPUpdates - Checks the instruction before/after the passed
158 /// instruction. If it is an ADD/SUB instruction it is deleted argument and the
159 /// stack adjustment is returned as a positive value for ADD and a negative for
161 static int mergeSPUpdates(MachineBasicBlock &MBB,
162 MachineBasicBlock::iterator &MBBI,
164 bool doMergeWithPrevious) {
165 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
166 (!doMergeWithPrevious && MBBI == MBB.end()))
169 MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
170 MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
171 unsigned Opc = PI->getOpcode();
174 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
175 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
176 PI->getOperand(0).getReg() == StackPtr){
177 Offset += PI->getOperand(2).getImm();
179 if (!doMergeWithPrevious) MBBI = NI;
180 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
181 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
182 PI->getOperand(0).getReg() == StackPtr) {
183 Offset -= PI->getOperand(2).getImm();
185 if (!doMergeWithPrevious) MBBI = NI;
191 static bool isEAXLiveIn(MachineFunction &MF) {
192 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
193 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
194 unsigned Reg = II->first;
196 if (Reg == X86::EAX || Reg == X86::AX ||
197 Reg == X86::AH || Reg == X86::AL)
204 void X86FrameInfo::emitCalleeSavedFrameMoves(MachineFunction &MF,
206 unsigned FramePtr) const {
207 MachineFrameInfo *MFI = MF.getFrameInfo();
208 MachineModuleInfo &MMI = MF.getMMI();
210 // Add callee saved registers to move list.
211 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
212 if (CSI.empty()) return;
214 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
215 const TargetData *TD = TM.getTargetData();
216 bool HasFP = hasFP(MF);
218 // Calculate amount of bytes used for return address storing.
220 (TM.getFrameInfo()->getStackGrowthDirection() ==
221 TargetFrameInfo::StackGrowsUp ?
222 TD->getPointerSize() : -TD->getPointerSize());
224 // FIXME: This is dirty hack. The code itself is pretty mess right now.
225 // It should be rewritten from scratch and generalized sometimes.
227 // Determine maximum offset (minumum due to stack growth).
228 int64_t MaxOffset = 0;
229 for (std::vector<CalleeSavedInfo>::const_iterator
230 I = CSI.begin(), E = CSI.end(); I != E; ++I)
231 MaxOffset = std::min(MaxOffset,
232 MFI->getObjectOffset(I->getFrameIdx()));
234 // Calculate offsets.
235 int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
236 for (std::vector<CalleeSavedInfo>::const_iterator
237 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
238 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
239 unsigned Reg = I->getReg();
240 Offset = MaxOffset - Offset + saveAreaOffset;
242 // Don't output a new machine move if we're re-saving the frame
243 // pointer. This happens when the PrologEpilogInserter has inserted an extra
244 // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
245 // generates one when frame pointers are used. If we generate a "machine
246 // move" for this extra "PUSH", the linker will lose track of the fact that
247 // the frame pointer should have the value of the first "PUSH" when it's
250 // FIXME: This looks inelegant. It's possibly correct, but it's covering up
251 // another bug. I.e., one where we generate a prolog like this:
259 // The immediate re-push of EBP is unnecessary. At the least, it's an
260 // optimization bug. EBP can be used as a scratch register in certain
261 // cases, but probably not when we have a frame pointer.
262 if (HasFP && FramePtr == Reg)
265 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
266 MachineLocation CSSrc(Reg);
267 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
271 /// emitPrologue - Push callee-saved registers onto the stack, which
272 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
273 /// space for local variables. Also emit labels used by the exception handler to
274 /// generate the exception handling frames.
275 void X86FrameInfo::emitPrologue(MachineFunction &MF) const {
276 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
277 MachineBasicBlock::iterator MBBI = MBB.begin();
278 MachineFrameInfo *MFI = MF.getFrameInfo();
279 const Function *Fn = MF.getFunction();
280 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
281 const X86InstrInfo &TII = *TM.getInstrInfo();
282 MachineModuleInfo &MMI = MF.getMMI();
283 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
284 bool needsFrameMoves = MMI.hasDebugInfo() ||
285 !Fn->doesNotThrow() || UnwindTablesMandatory;
286 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
287 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
288 bool HasFP = hasFP(MF);
289 bool Is64Bit = STI.is64Bit();
290 bool IsWin64 = STI.isTargetWin64();
291 unsigned StackAlign = getStackAlignment();
292 unsigned SlotSize = RegInfo->getSlotSize();
293 unsigned FramePtr = RegInfo->getFrameRegister(MF);
294 unsigned StackPtr = RegInfo->getStackRegister();
298 // If we're forcing a stack realignment we can't rely on just the frame
299 // info, we need to know the ABI stack alignment as well in case we
300 // have a call out. Otherwise just make sure we have some alignment - we'll
301 // go with the minimum SlotSize.
302 if (ForceStackAlign) {
304 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
305 else if (MaxAlign < SlotSize)
309 // Add RETADDR move area to callee saved frame size.
310 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
311 if (TailCallReturnAddrDelta < 0)
312 X86FI->setCalleeSavedFrameSize(
313 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
315 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
316 // function, and use up to 128 bytes of stack space, don't have a frame
317 // pointer, calls, or dynamic alloca then we do not need to adjust the
318 // stack pointer (we fit in the Red Zone).
319 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
320 !RegInfo->needsStackRealignment(MF) &&
321 !MFI->hasVarSizedObjects() && // No dynamic alloca.
322 !MFI->adjustsStack() && // No calls.
323 !IsWin64) { // Win64 has no Red Zone
324 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
325 if (HasFP) MinSize += SlotSize;
326 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
327 MFI->setStackSize(StackSize);
328 } else if (IsWin64) {
329 // We need to always allocate 32 bytes as register spill area.
330 // FIXME: We might reuse these 32 bytes for leaf functions.
332 MFI->setStackSize(StackSize);
335 // Insert stack pointer adjustment for later moving of return addr. Only
336 // applies to tail call optimized functions where the callee argument stack
337 // size is bigger than the callers.
338 if (TailCallReturnAddrDelta < 0) {
340 BuildMI(MBB, MBBI, DL,
341 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
344 .addImm(-TailCallReturnAddrDelta);
345 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
348 // Mapping for machine moves:
350 // DST: VirtualFP AND
351 // SRC: VirtualFP => DW_CFA_def_cfa_offset
352 // ELSE => DW_CFA_def_cfa
354 // SRC: VirtualFP AND
355 // DST: Register => DW_CFA_def_cfa_register
358 // OFFSET < 0 => DW_CFA_offset_extended_sf
359 // REG < 64 => DW_CFA_offset + Reg
360 // ELSE => DW_CFA_offset_extended
362 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
363 const TargetData *TD = MF.getTarget().getTargetData();
364 uint64_t NumBytes = 0;
365 int stackGrowth = -TD->getPointerSize();
368 // Calculate required stack adjustment.
369 uint64_t FrameSize = StackSize - SlotSize;
370 if (RegInfo->needsStackRealignment(MF))
371 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
373 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
375 // Get the offset of the stack slot for the EBP register, which is
376 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
377 // Update the frame offset adjustment.
378 MFI->setOffsetAdjustment(-NumBytes);
380 // Save EBP/RBP into the appropriate stack slot.
381 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
382 .addReg(FramePtr, RegState::Kill);
384 if (needsFrameMoves) {
385 // Mark the place where EBP/RBP was saved.
386 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
387 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
389 // Define the current CFA rule to use the provided offset.
391 MachineLocation SPDst(MachineLocation::VirtualFP);
392 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
393 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
395 // FIXME: Verify & implement for FP
396 MachineLocation SPDst(StackPtr);
397 MachineLocation SPSrc(StackPtr, stackGrowth);
398 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
401 // Change the rule for the FramePtr to be an "offset" rule.
402 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
403 MachineLocation FPSrc(FramePtr);
404 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
407 // Update EBP with the new base value...
408 BuildMI(MBB, MBBI, DL,
409 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
412 if (needsFrameMoves) {
413 // Mark effective beginning of when frame pointer becomes valid.
414 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
415 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
417 // Define the current CFA to use the EBP/RBP register.
418 MachineLocation FPDst(FramePtr);
419 MachineLocation FPSrc(MachineLocation::VirtualFP);
420 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
423 // Mark the FramePtr as live-in in every block except the entry.
424 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
426 I->addLiveIn(FramePtr);
429 if (RegInfo->needsStackRealignment(MF)) {
431 BuildMI(MBB, MBBI, DL,
432 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri),
433 StackPtr).addReg(StackPtr).addImm(-MaxAlign);
435 // The EFLAGS implicit def is dead.
436 MI->getOperand(3).setIsDead();
439 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
442 // Skip the callee-saved push instructions.
443 bool PushedRegs = false;
444 int StackOffset = 2 * stackGrowth;
446 while (MBBI != MBB.end() &&
447 (MBBI->getOpcode() == X86::PUSH32r ||
448 MBBI->getOpcode() == X86::PUSH64r)) {
452 if (!HasFP && needsFrameMoves) {
453 // Mark callee-saved push instruction.
454 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
455 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
457 // Define the current CFA rule to use the provided offset.
458 unsigned Ptr = StackSize ?
459 MachineLocation::VirtualFP : StackPtr;
460 MachineLocation SPDst(Ptr);
461 MachineLocation SPSrc(Ptr, StackOffset);
462 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
463 StackOffset += stackGrowth;
467 DL = MBB.findDebugLoc(MBBI);
469 // If there is an SUB32ri of ESP immediately before this instruction, merge
470 // the two. This can be the case when tail call elimination is enabled and
471 // the callee has more arguments then the caller.
472 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
474 // If there is an ADD32ri or SUB32ri of ESP immediately after this
475 // instruction, merge the two instructions.
476 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
478 // Adjust stack pointer: ESP -= numbytes.
480 // Windows and cygwin/mingw require a prologue helper routine when allocating
481 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
482 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
483 // stack and adjust the stack pointer in one go. The 64-bit version of
484 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
485 // responsible for adjusting the stack pointer. Touching the stack at 4K
486 // increments is necessary to ensure that the guard pages used by the OS
487 // virtual memory manager are allocated in correct sequence.
488 if (NumBytes >= 4096 && (STI.isTargetCygMing() || STI.isTargetWin32())) {
489 // Check whether EAX is livein for this function.
490 bool isEAXAlive = isEAXLiveIn(MF);
492 const char *StackProbeSymbol =
493 STI.isTargetWindows() ? "_chkstk" : "_alloca";
494 unsigned CallOp = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
496 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
498 BuildMI(MBB, MBBI, DL, TII.get(CallOp))
499 .addExternalSymbol(StackProbeSymbol)
500 .addReg(StackPtr, RegState::Define | RegState::Implicit)
501 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
504 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
505 .addReg(X86::EAX, RegState::Kill);
507 // Allocate NumBytes-4 bytes on stack. We'll also use 4 already
508 // allocated bytes for EAX.
509 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
510 .addImm(NumBytes - 4);
511 BuildMI(MBB, MBBI, DL, TII.get(CallOp))
512 .addExternalSymbol(StackProbeSymbol)
513 .addReg(StackPtr, RegState::Define | RegState::Implicit)
514 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
517 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
519 StackPtr, false, NumBytes - 4);
520 MBB.insert(MBBI, MI);
522 } else if (NumBytes >= 4096 && STI.isTargetWin64()) {
523 // Sanity check that EAX is not livein for this function. It should
524 // should not be, so throw an assert.
525 assert(!isEAXLiveIn(MF) && "EAX is livein in the Win64 case!");
527 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
528 // Function prologue is responsible for adjusting the stack pointer.
529 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
531 BuildMI(MBB, MBBI, DL, TII.get(X86::WINCALL64pcrel32))
532 .addExternalSymbol("__chkstk")
533 .addReg(StackPtr, RegState::Define | RegState::Implicit);
534 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, TII);
536 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, TII);
538 if ((NumBytes || PushedRegs) && needsFrameMoves) {
539 // Mark end of stack pointer adjustment.
540 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
541 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
543 if (!HasFP && NumBytes) {
544 // Define the current CFA rule to use the provided offset.
546 MachineLocation SPDst(MachineLocation::VirtualFP);
547 MachineLocation SPSrc(MachineLocation::VirtualFP,
548 -StackSize + stackGrowth);
549 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
551 // FIXME: Verify & implement for FP
552 MachineLocation SPDst(StackPtr);
553 MachineLocation SPSrc(StackPtr, stackGrowth);
554 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
558 // Emit DWARF info specifying the offsets of the callee-saved registers.
560 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
564 void X86FrameInfo::emitEpilogue(MachineFunction &MF,
565 MachineBasicBlock &MBB) const {
566 const MachineFrameInfo *MFI = MF.getFrameInfo();
567 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
568 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
569 const X86InstrInfo &TII = *TM.getInstrInfo();
570 MachineBasicBlock::iterator MBBI = prior(MBB.end());
571 unsigned RetOpcode = MBBI->getOpcode();
572 DebugLoc DL = MBBI->getDebugLoc();
573 bool Is64Bit = STI.is64Bit();
574 unsigned StackAlign = getStackAlignment();
575 unsigned SlotSize = RegInfo->getSlotSize();
576 unsigned FramePtr = RegInfo->getFrameRegister(MF);
577 unsigned StackPtr = RegInfo->getStackRegister();
581 llvm_unreachable("Can only insert epilog into returning blocks");
584 case X86::TCRETURNdi:
585 case X86::TCRETURNri:
586 case X86::TCRETURNmi:
587 case X86::TCRETURNdi64:
588 case X86::TCRETURNri64:
589 case X86::TCRETURNmi64:
591 case X86::EH_RETURN64:
592 break; // These are ok
595 // Get the number of bytes to allocate from the FrameInfo.
596 uint64_t StackSize = MFI->getStackSize();
597 uint64_t MaxAlign = MFI->getMaxAlignment();
598 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
599 uint64_t NumBytes = 0;
601 // If we're forcing a stack realignment we can't rely on just the frame
602 // info, we need to know the ABI stack alignment as well in case we
603 // have a call out. Otherwise just make sure we have some alignment - we'll
604 // go with the minimum.
605 if (ForceStackAlign) {
607 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
609 MaxAlign = MaxAlign ? MaxAlign : 4;
613 // Calculate required stack adjustment.
614 uint64_t FrameSize = StackSize - SlotSize;
615 if (RegInfo->needsStackRealignment(MF))
616 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
618 NumBytes = FrameSize - CSSize;
621 BuildMI(MBB, MBBI, DL,
622 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
624 NumBytes = StackSize - CSSize;
627 // Skip the callee-saved pop instructions.
628 MachineBasicBlock::iterator LastCSPop = MBBI;
629 while (MBBI != MBB.begin()) {
630 MachineBasicBlock::iterator PI = prior(MBBI);
631 unsigned Opc = PI->getOpcode();
633 if (Opc != X86::POP32r && Opc != X86::POP64r &&
634 !PI->getDesc().isTerminator())
640 DL = MBBI->getDebugLoc();
642 // If there is an ADD32ri or SUB32ri of ESP immediately before this
643 // instruction, merge the two instructions.
644 if (NumBytes || MFI->hasVarSizedObjects())
645 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
647 // If dynamic alloca is used, then reset esp to point to the last callee-saved
648 // slot before popping them off! Same applies for the case, when stack was
650 if (RegInfo->needsStackRealignment(MF)) {
651 // We cannot use LEA here, because stack pointer was realigned. We need to
652 // deallocate local frame back.
654 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII);
655 MBBI = prior(LastCSPop);
658 BuildMI(MBB, MBBI, DL,
659 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
660 StackPtr).addReg(FramePtr);
661 } else if (MFI->hasVarSizedObjects()) {
663 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
665 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
666 FramePtr, false, -CSSize);
667 MBB.insert(MBBI, MI);
669 BuildMI(MBB, MBBI, DL,
670 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
673 } else if (NumBytes) {
674 // Adjust stack pointer back: ESP += numbytes.
675 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII);
678 // We're returning from function via eh_return.
679 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
680 MBBI = prior(MBB.end());
681 MachineOperand &DestAddr = MBBI->getOperand(0);
682 assert(DestAddr.isReg() && "Offset should be in register!");
683 BuildMI(MBB, MBBI, DL,
684 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
685 StackPtr).addReg(DestAddr.getReg());
686 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
687 RetOpcode == X86::TCRETURNmi ||
688 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
689 RetOpcode == X86::TCRETURNmi64) {
690 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
691 // Tail call return: adjust the stack pointer and jump to callee.
692 MBBI = prior(MBB.end());
693 MachineOperand &JumpTarget = MBBI->getOperand(0);
694 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
695 assert(StackAdjust.isImm() && "Expecting immediate value.");
697 // Adjust stack pointer.
698 int StackAdj = StackAdjust.getImm();
699 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
701 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
703 // Incoporate the retaddr area.
704 Offset = StackAdj-MaxTCDelta;
705 assert(Offset >= 0 && "Offset should never be negative");
708 // Check for possible merge with preceeding ADD instruction.
709 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
710 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII);
713 // Jump to label or value in register.
714 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
715 MachineInstrBuilder MIB =
716 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
717 ? X86::TAILJMPd : X86::TAILJMPd64));
718 if (JumpTarget.isGlobal())
719 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
720 JumpTarget.getTargetFlags());
722 assert(JumpTarget.isSymbol());
723 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
724 JumpTarget.getTargetFlags());
726 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
727 MachineInstrBuilder MIB =
728 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
729 ? X86::TAILJMPm : X86::TAILJMPm64));
730 for (unsigned i = 0; i != 5; ++i)
731 MIB.addOperand(MBBI->getOperand(i));
732 } else if (RetOpcode == X86::TCRETURNri64) {
733 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
734 addReg(JumpTarget.getReg(), RegState::Kill);
736 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
737 addReg(JumpTarget.getReg(), RegState::Kill);
740 MachineInstr *NewMI = prior(MBBI);
741 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
742 NewMI->addOperand(MBBI->getOperand(i));
744 // Delete the pseudo instruction TCRETURN.
746 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
747 (X86FI->getTCReturnAddrDelta() < 0)) {
748 // Add the return addr area delta back since we are not tail calling.
749 int delta = -1*X86FI->getTCReturnAddrDelta();
750 MBBI = prior(MBB.end());
752 // Check for possible merge with preceeding ADD instruction.
753 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
754 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII);
759 X86FrameInfo::getInitialFrameState(std::vector<MachineMove> &Moves) const {
760 // Calculate amount of bytes used for return address storing
761 int stackGrowth = (STI.is64Bit() ? -8 : -4);
762 const X86RegisterInfo *RI = TM.getRegisterInfo();
764 // Initial state of the frame pointer is esp+stackGrowth.
765 MachineLocation Dst(MachineLocation::VirtualFP);
766 MachineLocation Src(RI->getStackRegister(), stackGrowth);
767 Moves.push_back(MachineMove(0, Dst, Src));
769 // Add return address to move list
770 MachineLocation CSDst(RI->getStackRegister(), stackGrowth);
771 MachineLocation CSSrc(RI->getRARegister());
772 Moves.push_back(MachineMove(0, CSDst, CSSrc));
775 int X86FrameInfo::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
776 const X86RegisterInfo *RI =
777 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
778 const MachineFrameInfo *MFI = MF.getFrameInfo();
779 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
780 uint64_t StackSize = MFI->getStackSize();
782 if (RI->needsStackRealignment(MF)) {
784 // Skip the saved EBP.
785 Offset += RI->getSlotSize();
787 unsigned Align = MFI->getObjectAlignment(FI);
788 assert((-(Offset + StackSize)) % Align == 0);
790 return Offset + StackSize;
792 // FIXME: Support tail calls
795 return Offset + StackSize;
797 // Skip the saved EBP.
798 Offset += RI->getSlotSize();
800 // Skip the RETADDR move area
801 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
802 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
803 if (TailCallReturnAddrDelta < 0)
804 Offset -= TailCallReturnAddrDelta;
810 bool X86FrameInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
811 MachineBasicBlock::iterator MI,
812 const std::vector<CalleeSavedInfo> &CSI,
813 const TargetRegisterInfo *TRI) const {
817 DebugLoc DL = MBB.findDebugLoc(MI);
819 MachineFunction &MF = *MBB.getParent();
821 bool isWin64 = STI.isTargetWin64();
822 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
823 unsigned FPReg = TRI->getFrameRegister(MF);
824 unsigned CalleeFrameSize = 0;
826 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
827 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
829 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
830 for (unsigned i = CSI.size(); i != 0; --i) {
831 unsigned Reg = CSI[i-1].getReg();
832 // Add the callee-saved register as live-in. It's killed at the spill.
835 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
837 if (!X86::VR128RegClass.contains(Reg) && !isWin64) {
838 CalleeFrameSize += SlotSize;
839 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill);
841 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
842 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
847 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
851 bool X86FrameInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
852 MachineBasicBlock::iterator MI,
853 const std::vector<CalleeSavedInfo> &CSI,
854 const TargetRegisterInfo *TRI) const {
858 DebugLoc DL = MBB.findDebugLoc(MI);
860 MachineFunction &MF = *MBB.getParent();
861 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
862 unsigned FPReg = TRI->getFrameRegister(MF);
863 bool isWin64 = STI.isTargetWin64();
864 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
865 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
866 unsigned Reg = CSI[i].getReg();
868 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
870 if (!X86::VR128RegClass.contains(Reg) && !isWin64) {
871 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
873 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
874 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
882 X86FrameInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
883 RegScavenger *RS) const {
884 MachineFrameInfo *MFI = MF.getFrameInfo();
885 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
886 unsigned SlotSize = RegInfo->getSlotSize();
888 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
889 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
891 if (TailCallReturnAddrDelta < 0) {
892 // create RETURNADDR area
901 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
902 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
906 assert((TailCallReturnAddrDelta <= 0) &&
907 "The Delta should always be zero or negative");
908 const TargetFrameInfo &TFI = *MF.getTarget().getFrameInfo();
910 // Create a frame entry for the EBP register that must be saved.
911 int FrameIdx = MFI->CreateFixedObject(SlotSize,
913 TFI.getOffsetOfLocalArea() +
914 TailCallReturnAddrDelta,
916 assert(FrameIdx == MFI->getObjectIndexBegin() &&
917 "Slot for EBP register must be last in order to be found!");