Move callee-saved regs spills / reloads to TFI
[oota-llvm.git] / lib / Target / X86 / X86FrameInfo.cpp
1 //=======- X86FrameInfo.cpp - X86 Frame Information ------------*- C++ -*-====//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the X86 implementation of TargetFrameInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
28
29 using namespace llvm;
30
31 // FIXME: completely move here.
32 extern cl::opt<bool> ForceStackAlign;
33
34 bool X86FrameInfo::hasReservedCallFrame(const MachineFunction &MF) const {
35   return !MF.getFrameInfo()->hasVarSizedObjects();
36 }
37
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();
45
46   return (DisableFramePointerElim(MF) ||
47           RI->needsStackRealignment(MF) ||
48           MFI->hasVarSizedObjects() ||
49           MFI->isFrameAddressTaken() ||
50           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
51           MMI.callsUnwindInit());
52 }
53
54 static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
55   if (is64Bit) {
56     if (isInt<8>(Imm))
57       return X86::SUB64ri8;
58     return X86::SUB64ri32;
59   } else {
60     if (isInt<8>(Imm))
61       return X86::SUB32ri8;
62     return X86::SUB32ri;
63   }
64 }
65
66 static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
67   if (is64Bit) {
68     if (isInt<8>(Imm))
69       return X86::ADD64ri8;
70     return X86::ADD64ri32;
71   } else {
72     if (isInt<8>(Imm))
73       return X86::ADD32ri8;
74     return X86::ADD32ri;
75   }
76 }
77
78 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
79 /// stack pointer by a constant value.
80 static
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);
91
92   while (Offset) {
93     uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
94     MachineInstr *MI =
95       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
96         .addReg(StackPtr)
97         .addImm(ThisVal);
98     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
99     Offset -= ThisVal;
100   }
101 }
102
103 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
104 static
105 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
106                       unsigned StackPtr, uint64_t *NumBytes = NULL) {
107   if (MBBI == MBB.begin()) return;
108
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) {
114     if (NumBytes)
115       *NumBytes += PI->getOperand(2).getImm();
116     MBB.erase(PI);
117   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
118               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
119              PI->getOperand(0).getReg() == StackPtr) {
120     if (NumBytes)
121       *NumBytes -= PI->getOperand(2).getImm();
122     MBB.erase(PI);
123   }
124 }
125
126 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
127 static
128 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
129                         MachineBasicBlock::iterator &MBBI,
130                         unsigned StackPtr, uint64_t *NumBytes = NULL) {
131   // FIXME: THIS ISN'T RUN!!!
132   return;
133
134   if (MBBI == MBB.end()) return;
135
136   MachineBasicBlock::iterator NI = llvm::next(MBBI);
137   if (NI == MBB.end()) return;
138
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) {
143     if (NumBytes)
144       *NumBytes -= NI->getOperand(2).getImm();
145     MBB.erase(NI);
146     MBBI = NI;
147   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
148               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
149              NI->getOperand(0).getReg() == StackPtr) {
150     if (NumBytes)
151       *NumBytes += NI->getOperand(2).getImm();
152     MBB.erase(NI);
153     MBBI = NI;
154   }
155 }
156
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
160 /// SUB.
161 static int mergeSPUpdates(MachineBasicBlock &MBB,
162                            MachineBasicBlock::iterator &MBBI,
163                            unsigned StackPtr,
164                            bool doMergeWithPrevious) {
165   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
166       (!doMergeWithPrevious && MBBI == MBB.end()))
167     return 0;
168
169   MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
170   MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
171   unsigned Opc = PI->getOpcode();
172   int Offset = 0;
173
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();
178     MBB.erase(PI);
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();
184     MBB.erase(PI);
185     if (!doMergeWithPrevious) MBBI = NI;
186   }
187
188   return Offset;
189 }
190
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;
195
196     if (Reg == X86::EAX || Reg == X86::AX ||
197         Reg == X86::AH || Reg == X86::AL)
198       return true;
199   }
200
201   return false;
202 }
203
204 void X86FrameInfo::emitCalleeSavedFrameMoves(MachineFunction &MF,
205                                              MCSymbol *Label,
206                                              unsigned FramePtr) const {
207   MachineFrameInfo *MFI = MF.getFrameInfo();
208   MachineModuleInfo &MMI = MF.getMMI();
209
210   // Add callee saved registers to move list.
211   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
212   if (CSI.empty()) return;
213
214   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
215   const TargetData *TD = TM.getTargetData();
216   bool HasFP = hasFP(MF);
217
218   // Calculate amount of bytes used for return address storing.
219   int stackGrowth =
220     (TM.getFrameInfo()->getStackGrowthDirection() ==
221      TargetFrameInfo::StackGrowsUp ?
222      TD->getPointerSize() : -TD->getPointerSize());
223
224   // FIXME: This is dirty hack. The code itself is pretty mess right now.
225   // It should be rewritten from scratch and generalized sometimes.
226
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()));
233
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;
241
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
248     // trying to unwind.
249     // 
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:
252     //
253     //          pushl  %ebp
254     //          movl   %esp, %ebp
255     //          pushl  %ebp
256     //          pushl  %esi
257     //           ...
258     //
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)
263       continue;
264
265     MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
266     MachineLocation CSSrc(Reg);
267     Moves.push_back(MachineMove(Label, CSDst, CSSrc));
268   }
269 }
270
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();
295
296   DebugLoc DL;
297
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) {
303     if (MFI->hasCalls())
304       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
305     else if (MaxAlign < SlotSize)
306       MaxAlign = SlotSize;
307   }
308
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);
314
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.
331     StackSize += 32;
332     MFI->setStackSize(StackSize);
333   }
334
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) {
339     MachineInstr *MI =
340       BuildMI(MBB, MBBI, DL,
341               TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
342               StackPtr)
343         .addReg(StackPtr)
344         .addImm(-TailCallReturnAddrDelta);
345     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
346   }
347
348   // Mapping for machine moves:
349   //
350   //   DST: VirtualFP AND
351   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
352   //        ELSE                        => DW_CFA_def_cfa
353   //
354   //   SRC: VirtualFP AND
355   //        DST: Register               => DW_CFA_def_cfa_register
356   //
357   //   ELSE
358   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
359   //        REG < 64                    => DW_CFA_offset + Reg
360   //        ELSE                        => DW_CFA_offset_extended
361
362   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
363   const TargetData *TD = MF.getTarget().getTargetData();
364   uint64_t NumBytes = 0;
365   int stackGrowth = -TD->getPointerSize();
366
367   if (HasFP) {
368     // Calculate required stack adjustment.
369     uint64_t FrameSize = StackSize - SlotSize;
370     if (RegInfo->needsStackRealignment(MF))
371       FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
372
373     NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
374
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);
379
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);
383
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);
388
389       // Define the current CFA rule to use the provided offset.
390       if (StackSize) {
391         MachineLocation SPDst(MachineLocation::VirtualFP);
392         MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
393         Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
394       } else {
395         // FIXME: Verify & implement for FP
396         MachineLocation SPDst(StackPtr);
397         MachineLocation SPSrc(StackPtr, stackGrowth);
398         Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
399       }
400
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));
405     }
406
407     // Update EBP with the new base value...
408     BuildMI(MBB, MBBI, DL,
409             TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
410         .addReg(StackPtr);
411
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);
416
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));
421     }
422
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();
425          I != E; ++I)
426       I->addLiveIn(FramePtr);
427
428     // Realign stack
429     if (RegInfo->needsStackRealignment(MF)) {
430       MachineInstr *MI =
431         BuildMI(MBB, MBBI, DL,
432                 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri),
433                 StackPtr).addReg(StackPtr).addImm(-MaxAlign);
434
435       // The EFLAGS implicit def is dead.
436       MI->getOperand(3).setIsDead();
437     }
438   } else {
439     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
440   }
441
442   // Skip the callee-saved push instructions.
443   bool PushedRegs = false;
444   int StackOffset = 2 * stackGrowth;
445
446   while (MBBI != MBB.end() &&
447          (MBBI->getOpcode() == X86::PUSH32r ||
448           MBBI->getOpcode() == X86::PUSH64r)) {
449     PushedRegs = true;
450     ++MBBI;
451
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);
456
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;
464     }
465   }
466
467   DL = MBB.findDebugLoc(MBBI);
468
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);
473
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);
477
478   // Adjust stack pointer: ESP -= numbytes.
479
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);
491
492     const char *StackProbeSymbol =
493       STI.isTargetWindows() ? "_chkstk" : "_alloca";
494     unsigned CallOp = Is64Bit ? X86::CALL64pcrel32 : X86::CALLpcrel32;
495     if (!isEAXAlive) {
496       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
497         .addImm(NumBytes);
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);
502     } else {
503       // Save EAX
504       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
505         .addReg(X86::EAX, RegState::Kill);
506
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);
515
516       // Restore EAX
517       MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
518                                               X86::EAX),
519                                       StackPtr, false, NumBytes - 4);
520       MBB.insert(MBBI, MI);
521     }
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!");
526
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)
530       .addImm(NumBytes);
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);
535   } else if (NumBytes)
536     emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, TII);
537
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);
542
543     if (!HasFP && NumBytes) {
544       // Define the current CFA rule to use the provided offset.
545       if (StackSize) {
546         MachineLocation SPDst(MachineLocation::VirtualFP);
547         MachineLocation SPSrc(MachineLocation::VirtualFP,
548                               -StackSize + stackGrowth);
549         Moves.push_back(MachineMove(Label, SPDst, SPSrc));
550       } else {
551         // FIXME: Verify & implement for FP
552         MachineLocation SPDst(StackPtr);
553         MachineLocation SPSrc(StackPtr, stackGrowth);
554         Moves.push_back(MachineMove(Label, SPDst, SPSrc));
555       }
556     }
557
558     // Emit DWARF info specifying the offsets of the callee-saved registers.
559     if (PushedRegs)
560       emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
561   }
562 }
563
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();
578
579   switch (RetOpcode) {
580   default:
581     llvm_unreachable("Can only insert epilog into returning blocks");
582   case X86::RET:
583   case X86::RETI:
584   case X86::TCRETURNdi:
585   case X86::TCRETURNri:
586   case X86::TCRETURNmi:
587   case X86::TCRETURNdi64:
588   case X86::TCRETURNri64:
589   case X86::TCRETURNmi64:
590   case X86::EH_RETURN:
591   case X86::EH_RETURN64:
592     break;  // These are ok
593   }
594
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;
600
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) {
606     if (MFI->hasCalls())
607       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
608     else
609       MaxAlign = MaxAlign ? MaxAlign : 4;
610   }
611
612   if (hasFP(MF)) {
613     // Calculate required stack adjustment.
614     uint64_t FrameSize = StackSize - SlotSize;
615     if (RegInfo->needsStackRealignment(MF))
616       FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
617
618     NumBytes = FrameSize - CSSize;
619
620     // Pop EBP.
621     BuildMI(MBB, MBBI, DL,
622             TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
623   } else {
624     NumBytes = StackSize - CSSize;
625   }
626
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();
632
633     if (Opc != X86::POP32r && Opc != X86::POP64r &&
634         !PI->getDesc().isTerminator())
635       break;
636
637     --MBBI;
638   }
639
640   DL = MBBI->getDebugLoc();
641
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);
646
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
649   // realigned.
650   if (RegInfo->needsStackRealignment(MF)) {
651     // We cannot use LEA here, because stack pointer was realigned. We need to
652     // deallocate local frame back.
653     if (CSSize) {
654       emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII);
655       MBBI = prior(LastCSPop);
656     }
657
658     BuildMI(MBB, MBBI, DL,
659             TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
660             StackPtr).addReg(FramePtr);
661   } else if (MFI->hasVarSizedObjects()) {
662     if (CSSize) {
663       unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
664       MachineInstr *MI =
665         addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
666                      FramePtr, false, -CSSize);
667       MBB.insert(MBBI, MI);
668     } else {
669       BuildMI(MBB, MBBI, DL,
670               TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
671         .addReg(FramePtr);
672     }
673   } else if (NumBytes) {
674     // Adjust stack pointer back: ESP += numbytes.
675     emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII);
676   }
677
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.");
696
697     // Adjust stack pointer.
698     int StackAdj = StackAdjust.getImm();
699     int MaxTCDelta = X86FI->getTCReturnAddrDelta();
700     int Offset = 0;
701     assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
702
703     // Incoporate the retaddr area.
704     Offset = StackAdj-MaxTCDelta;
705     assert(Offset >= 0 && "Offset should never be negative");
706
707     if (Offset) {
708       // Check for possible merge with preceeding ADD instruction.
709       Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
710       emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII);
711     }
712
713     // Jump to label or value in register.
714     if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
715       BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
716                                      ? X86::TAILJMPd : X86::TAILJMPd64)).
717         addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
718                          JumpTarget.getTargetFlags());
719     } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
720       MachineInstrBuilder MIB =
721         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
722                                        ? X86::TAILJMPm : X86::TAILJMPm64));
723       for (unsigned i = 0; i != 5; ++i)
724         MIB.addOperand(MBBI->getOperand(i));
725     } else if (RetOpcode == X86::TCRETURNri64) {
726       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
727         addReg(JumpTarget.getReg(), RegState::Kill);
728     } else {
729       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
730         addReg(JumpTarget.getReg(), RegState::Kill);
731     }
732
733     MachineInstr *NewMI = prior(MBBI);
734     for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
735       NewMI->addOperand(MBBI->getOperand(i));
736
737     // Delete the pseudo instruction TCRETURN.
738     MBB.erase(MBBI);
739   } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
740              (X86FI->getTCReturnAddrDelta() < 0)) {
741     // Add the return addr area delta back since we are not tail calling.
742     int delta = -1*X86FI->getTCReturnAddrDelta();
743     MBBI = prior(MBB.end());
744
745     // Check for possible merge with preceeding ADD instruction.
746     delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
747     emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII);
748   }
749 }
750
751 void
752 X86FrameInfo::getInitialFrameState(std::vector<MachineMove> &Moves) const {
753   // Calculate amount of bytes used for return address storing
754   int stackGrowth = (STI.is64Bit() ? -8 : -4);
755   const X86RegisterInfo *RI = TM.getRegisterInfo();
756
757   // Initial state of the frame pointer is esp+stackGrowth.
758   MachineLocation Dst(MachineLocation::VirtualFP);
759   MachineLocation Src(RI->getStackRegister(), stackGrowth);
760   Moves.push_back(MachineMove(0, Dst, Src));
761
762   // Add return address to move list
763   MachineLocation CSDst(RI->getStackRegister(), stackGrowth);
764   MachineLocation CSSrc(RI->getRARegister());
765   Moves.push_back(MachineMove(0, CSDst, CSSrc));
766 }
767
768 int X86FrameInfo::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
769   const X86RegisterInfo *RI =
770     static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
771   const MachineFrameInfo *MFI = MF.getFrameInfo();
772   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
773   uint64_t StackSize = MFI->getStackSize();
774
775   if (RI->needsStackRealignment(MF)) {
776     if (FI < 0) {
777       // Skip the saved EBP.
778       Offset += RI->getSlotSize();
779     } else {
780       unsigned Align = MFI->getObjectAlignment(FI);
781       assert((-(Offset + StackSize)) % Align == 0);
782       Align = 0;
783       return Offset + StackSize;
784     }
785     // FIXME: Support tail calls
786   } else {
787     if (!hasFP(MF))
788       return Offset + StackSize;
789
790     // Skip the saved EBP.
791     Offset += RI->getSlotSize();
792
793     // Skip the RETADDR move area
794     const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
795     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
796     if (TailCallReturnAddrDelta < 0)
797       Offset -= TailCallReturnAddrDelta;
798   }
799
800   return Offset;
801 }
802
803 bool X86FrameInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
804                                              MachineBasicBlock::iterator MI,
805                                         const std::vector<CalleeSavedInfo> &CSI,
806                                           const TargetRegisterInfo *TRI) const {
807   if (CSI.empty())
808     return false;
809
810   DebugLoc DL = MBB.findDebugLoc(MI);
811
812   MachineFunction &MF = *MBB.getParent();
813
814   bool isWin64 = STI.isTargetWin64();
815   unsigned SlotSize = STI.is64Bit() ? 8 : 4;
816   unsigned FPReg = TRI->getFrameRegister(MF);
817   unsigned CalleeFrameSize = 0;
818
819   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
820   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
821
822   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
823   for (unsigned i = CSI.size(); i != 0; --i) {
824     unsigned Reg = CSI[i-1].getReg();
825     // Add the callee-saved register as live-in. It's killed at the spill.
826     MBB.addLiveIn(Reg);
827     if (Reg == FPReg)
828       // X86RegisterInfo::emitPrologue will handle spilling of frame register.
829       continue;
830     if (!X86::VR128RegClass.contains(Reg) && !isWin64) {
831       CalleeFrameSize += SlotSize;
832       BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill);
833     } else {
834       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
835       TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
836                               RC, TRI);
837     }
838   }
839
840   X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
841   return true;
842 }
843
844 bool X86FrameInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
845                                                MachineBasicBlock::iterator MI,
846                                         const std::vector<CalleeSavedInfo> &CSI,
847                                           const TargetRegisterInfo *TRI) const {
848   if (CSI.empty())
849     return false;
850
851   DebugLoc DL = MBB.findDebugLoc(MI);
852
853   MachineFunction &MF = *MBB.getParent();
854   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
855   unsigned FPReg = TRI->getFrameRegister(MF);
856   bool isWin64 = STI.isTargetWin64();
857   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
858   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
859     unsigned Reg = CSI[i].getReg();
860     if (Reg == FPReg)
861       // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
862       continue;
863     if (!X86::VR128RegClass.contains(Reg) && !isWin64) {
864       BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
865     } else {
866       const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
867       TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
868                                RC, TRI);
869     }
870   }
871   return true;
872 }