Update comments to use unreachable instead of llvm.trap, as implemented now
[oota-llvm.git] / lib / Target / X86 / X86FrameLowering.cpp
1 //===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
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 TargetFrameLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "X86FrameLowering.h"
15 #include "X86InstrBuilder.h"
16 #include "X86InstrInfo.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86Subtarget.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Support/Debug.h"
33 #include <cstdlib>
34
35 using namespace llvm;
36
37 // FIXME: completely move here.
38 extern cl::opt<bool> ForceStackAlign;
39
40 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
41   return !MF.getFrameInfo()->hasVarSizedObjects();
42 }
43
44 /// hasFP - Return true if the specified function should have a dedicated frame
45 /// pointer register.  This is true if the function has variable sized allocas
46 /// or if frame pointer elimination is disabled.
47 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
48   const MachineFrameInfo *MFI = MF.getFrameInfo();
49   const MachineModuleInfo &MMI = MF.getMMI();
50   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
51
52   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
53           RegInfo->needsStackRealignment(MF) ||
54           MFI->hasVarSizedObjects() ||
55           MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
56           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
57           MMI.callsUnwindInit() || MMI.callsEHReturn() ||
58           MFI->hasStackMap() || MFI->hasPatchPoint());
59 }
60
61 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
62   if (IsLP64) {
63     if (isInt<8>(Imm))
64       return X86::SUB64ri8;
65     return X86::SUB64ri32;
66   } else {
67     if (isInt<8>(Imm))
68       return X86::SUB32ri8;
69     return X86::SUB32ri;
70   }
71 }
72
73 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
74   if (IsLP64) {
75     if (isInt<8>(Imm))
76       return X86::ADD64ri8;
77     return X86::ADD64ri32;
78   } else {
79     if (isInt<8>(Imm))
80       return X86::ADD32ri8;
81     return X86::ADD32ri;
82   }
83 }
84
85 static unsigned getSUBrrOpcode(unsigned isLP64) {
86   return isLP64 ? X86::SUB64rr : X86::SUB32rr;
87 }
88
89 static unsigned getADDrrOpcode(unsigned isLP64) {
90   return isLP64 ? X86::ADD64rr : X86::ADD32rr;
91 }
92
93 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
94   if (IsLP64) {
95     if (isInt<8>(Imm))
96       return X86::AND64ri8;
97     return X86::AND64ri32;
98   }
99   if (isInt<8>(Imm))
100     return X86::AND32ri8;
101   return X86::AND32ri;
102 }
103
104 static unsigned getPUSHiOpcode(bool IsLP64, MachineOperand MO) {
105   // We don't support LP64 for now.
106   assert(!IsLP64);
107
108   if (MO.isImm() && isInt<8>(MO.getImm()))
109     return X86::PUSH32i8;
110
111   return X86::PUSHi32;;
112 }
113
114 static unsigned getLEArOpcode(unsigned IsLP64) {
115   return IsLP64 ? X86::LEA64r : X86::LEA32r;
116 }
117
118 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
119 /// when it reaches the "return" instruction. We can then pop a stack object
120 /// to this register without worry about clobbering it.
121 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
122                                        MachineBasicBlock::iterator &MBBI,
123                                        const TargetRegisterInfo &TRI,
124                                        bool Is64Bit) {
125   const MachineFunction *MF = MBB.getParent();
126   const Function *F = MF->getFunction();
127   if (!F || MF->getMMI().callsEHReturn())
128     return 0;
129
130   static const uint16_t CallerSavedRegs32Bit[] = {
131     X86::EAX, X86::EDX, X86::ECX, 0
132   };
133
134   static const uint16_t CallerSavedRegs64Bit[] = {
135     X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
136     X86::R8,  X86::R9,  X86::R10, X86::R11, 0
137   };
138
139   unsigned Opc = MBBI->getOpcode();
140   switch (Opc) {
141   default: return 0;
142   case X86::RETL:
143   case X86::RETQ:
144   case X86::RETIL:
145   case X86::RETIQ:
146   case X86::TCRETURNdi:
147   case X86::TCRETURNri:
148   case X86::TCRETURNmi:
149   case X86::TCRETURNdi64:
150   case X86::TCRETURNri64:
151   case X86::TCRETURNmi64:
152   case X86::EH_RETURN:
153   case X86::EH_RETURN64: {
154     SmallSet<uint16_t, 8> Uses;
155     for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
156       MachineOperand &MO = MBBI->getOperand(i);
157       if (!MO.isReg() || MO.isDef())
158         continue;
159       unsigned Reg = MO.getReg();
160       if (!Reg)
161         continue;
162       for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
163         Uses.insert(*AI);
164     }
165
166     const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
167     for (; *CS; ++CS)
168       if (!Uses.count(*CS))
169         return *CS;
170   }
171   }
172
173   return 0;
174 }
175
176 static bool isEAXLiveIn(MachineFunction &MF) {
177   for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
178        EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
179     unsigned Reg = II->first;
180
181     if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
182         Reg == X86::AH || Reg == X86::AL)
183       return true;
184   }
185
186   return false;
187 }
188
189 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
190 /// stack pointer by a constant value.
191 static
192 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
193                   unsigned StackPtr, int64_t NumBytes,
194                   bool Is64BitTarget, bool Is64BitStackPtr, bool UseLEA,
195                   const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
196   bool isSub = NumBytes < 0;
197   uint64_t Offset = isSub ? -NumBytes : NumBytes;
198   unsigned Opc;
199   if (UseLEA)
200     Opc = getLEArOpcode(Is64BitStackPtr);
201   else
202     Opc = isSub
203       ? getSUBriOpcode(Is64BitStackPtr, Offset)
204       : getADDriOpcode(Is64BitStackPtr, Offset);
205
206   uint64_t Chunk = (1LL << 31) - 1;
207   DebugLoc DL = MBB.findDebugLoc(MBBI);
208
209   while (Offset) {
210     if (Offset > Chunk) {
211       // Rather than emit a long series of instructions for large offsets,
212       // load the offset into a register and do one sub/add
213       unsigned Reg = 0;
214
215       if (isSub && !isEAXLiveIn(*MBB.getParent()))
216         Reg = (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX);
217       else
218         Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
219
220       if (Reg) {
221         Opc = Is64BitTarget ? X86::MOV64ri : X86::MOV32ri;
222         BuildMI(MBB, MBBI, DL, TII.get(Opc), Reg)
223           .addImm(Offset);
224         Opc = isSub
225           ? getSUBrrOpcode(Is64BitTarget)
226           : getADDrrOpcode(Is64BitTarget);
227         MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
228           .addReg(StackPtr)
229           .addReg(Reg);
230         MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
231         Offset = 0;
232         continue;
233       }
234     }
235
236     uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
237     if (ThisVal == (Is64BitTarget ? 8 : 4)) {
238       // Use push / pop instead.
239       unsigned Reg = isSub
240         ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
241         : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
242       if (Reg) {
243         Opc = isSub
244           ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
245           : (Is64BitTarget ? X86::POP64r  : X86::POP32r);
246         MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
247           .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
248         if (isSub)
249           MI->setFlag(MachineInstr::FrameSetup);
250         Offset -= ThisVal;
251         continue;
252       }
253     }
254
255     MachineInstr *MI = nullptr;
256
257     if (UseLEA) {
258       MI =  addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
259                           StackPtr, false, isSub ? -ThisVal : ThisVal);
260     } else {
261       MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
262             .addReg(StackPtr)
263             .addImm(ThisVal);
264       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
265     }
266
267     if (isSub)
268       MI->setFlag(MachineInstr::FrameSetup);
269
270     Offset -= ThisVal;
271   }
272 }
273
274 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
275 static
276 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
277                       unsigned StackPtr, uint64_t *NumBytes = nullptr) {
278   if (MBBI == MBB.begin()) return;
279
280   MachineBasicBlock::iterator PI = std::prev(MBBI);
281   unsigned Opc = PI->getOpcode();
282   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
283        Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
284        Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
285       PI->getOperand(0).getReg() == StackPtr) {
286     if (NumBytes)
287       *NumBytes += PI->getOperand(2).getImm();
288     MBB.erase(PI);
289   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
290               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
291              PI->getOperand(0).getReg() == StackPtr) {
292     if (NumBytes)
293       *NumBytes -= PI->getOperand(2).getImm();
294     MBB.erase(PI);
295   }
296 }
297
298 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
299 /// iterator.
300 static
301 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
302                         MachineBasicBlock::iterator &MBBI,
303                         unsigned StackPtr, uint64_t *NumBytes = nullptr) {
304   // FIXME:  THIS ISN'T RUN!!!
305   return;
306
307   if (MBBI == MBB.end()) return;
308
309   MachineBasicBlock::iterator NI = std::next(MBBI);
310   if (NI == MBB.end()) return;
311
312   unsigned Opc = NI->getOpcode();
313   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
314        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
315       NI->getOperand(0).getReg() == StackPtr) {
316     if (NumBytes)
317       *NumBytes -= NI->getOperand(2).getImm();
318     MBB.erase(NI);
319     MBBI = NI;
320   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
321               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
322              NI->getOperand(0).getReg() == StackPtr) {
323     if (NumBytes)
324       *NumBytes += NI->getOperand(2).getImm();
325     MBB.erase(NI);
326     MBBI = NI;
327   }
328 }
329
330 /// mergeSPUpdates - Checks the instruction before/after the passed
331 /// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
332 /// the stack adjustment is returned as a positive value for ADD/LEA and a
333 /// negative for SUB.
334 static int mergeSPUpdates(MachineBasicBlock &MBB,
335                           MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
336                           bool doMergeWithPrevious) {
337   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
338       (!doMergeWithPrevious && MBBI == MBB.end()))
339     return 0;
340
341   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
342   MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
343                                                        : std::next(MBBI);
344   unsigned Opc = PI->getOpcode();
345   int Offset = 0;
346
347   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
348        Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
349        Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
350       PI->getOperand(0).getReg() == StackPtr){
351     Offset += PI->getOperand(2).getImm();
352     MBB.erase(PI);
353     if (!doMergeWithPrevious) MBBI = NI;
354   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
355               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
356              PI->getOperand(0).getReg() == StackPtr) {
357     Offset -= PI->getOperand(2).getImm();
358     MBB.erase(PI);
359     if (!doMergeWithPrevious) MBBI = NI;
360   }
361
362   return Offset;
363 }
364
365 void
366 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
367                                             MachineBasicBlock::iterator MBBI,
368                                             DebugLoc DL) const {
369   MachineFunction &MF = *MBB.getParent();
370   MachineFrameInfo *MFI = MF.getFrameInfo();
371   MachineModuleInfo &MMI = MF.getMMI();
372   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
373   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
374
375   // Add callee saved registers to move list.
376   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
377   if (CSI.empty()) return;
378
379   // Calculate offsets.
380   for (std::vector<CalleeSavedInfo>::const_iterator
381          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
382     int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
383     unsigned Reg = I->getReg();
384
385     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
386     unsigned CFIIndex =
387         MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
388                                                         Offset));
389     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
390         .addCFIIndex(CFIIndex);
391   }
392 }
393
394 /// usesTheStack - This function checks if any of the users of EFLAGS
395 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
396 /// to use the stack, and if we don't adjust the stack we clobber the first
397 /// frame index.
398 /// See X86InstrInfo::copyPhysReg.
399 static bool usesTheStack(const MachineFunction &MF) {
400   const MachineRegisterInfo &MRI = MF.getRegInfo();
401
402   for (MachineRegisterInfo::reg_instr_iterator
403        ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
404        ri != re; ++ri)
405     if (ri->isCopy())
406       return true;
407
408   return false;
409 }
410
411 void X86FrameLowering::getStackProbeFunction(const MachineFunction &MF,
412                                              const X86Subtarget &STI,
413                                              unsigned &CallOp,
414                                              const char *&Symbol) {
415   if (STI.is64Bit())
416     CallOp = MF.getTarget().getCodeModel() == CodeModel::Large
417                  ? X86::CALL64r
418                  : X86::W64ALLOCA;
419   else
420     CallOp = X86::CALLpcrel32;
421
422   if (STI.is64Bit()) {
423     if (STI.isTargetCygMing()) {
424       Symbol = "___chkstk_ms";
425     } else {
426       Symbol = "__chkstk";
427     }
428   } else if (STI.isTargetCygMing())
429     Symbol = "_alloca";
430   else
431     Symbol = "_chkstk";
432 }
433
434 /// emitPrologue - Push callee-saved registers onto the stack, which
435 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
436 /// space for local variables. Also emit labels used by the exception handler to
437 /// generate the exception handling frames.
438
439 /*
440   Here's a gist of what gets emitted:
441
442   ; Establish frame pointer, if needed
443   [if needs FP]
444       push  %rbp
445       .cfi_def_cfa_offset 16
446       .cfi_offset %rbp, -16
447       .seh_pushreg %rpb
448       mov  %rsp, %rbp
449       .cfi_def_cfa_register %rbp
450
451   ; Spill general-purpose registers
452   [for all callee-saved GPRs]
453       pushq %<reg>
454       [if not needs FP]
455          .cfi_def_cfa_offset (offset from RETADDR)
456       .seh_pushreg %<reg>
457
458   ; If the required stack alignment > default stack alignment
459   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
460   ; of unknown size in the stack frame.
461   [if stack needs re-alignment]
462       and  $MASK, %rsp
463
464   ; Allocate space for locals
465   [if target is Windows and allocated space > 4096 bytes]
466       ; Windows needs special care for allocations larger
467       ; than one page.
468       mov $NNN, %rax
469       call ___chkstk_ms/___chkstk
470       sub  %rax, %rsp
471   [else]
472       sub  $NNN, %rsp
473
474   [if needs FP]
475       .seh_stackalloc (size of XMM spill slots)
476       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
477   [else]
478       .seh_stackalloc NNN
479
480   ; Spill XMMs
481   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
482   ; they may get spilled on any platform, if the current function
483   ; calls @llvm.eh.unwind.init
484   [if needs FP]
485       [for all callee-saved XMM registers]
486           movaps  %<xmm reg>, -MMM(%rbp)
487       [for all callee-saved XMM registers]
488           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
489               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
490   [else]
491       [for all callee-saved XMM registers]
492           movaps  %<xmm reg>, KKK(%rsp)
493       [for all callee-saved XMM registers]
494           .seh_savexmm %<xmm reg>, KKK
495
496   .seh_endprologue
497
498   [if needs base pointer]
499       mov  %rsp, %rbx
500       [if needs to restore base pointer]
501           mov %rsp, -MMM(%rbp)
502
503   ; Emit CFI info
504   [if needs FP]
505       [for all callee-saved registers]
506           .cfi_offset %<reg>, (offset from %rbp)
507   [else]
508        .cfi_def_cfa_offset (offset from RETADDR)
509       [for all callee-saved registers]
510           .cfi_offset %<reg>, (offset from %rsp)
511
512   Notes:
513   - .seh directives are emitted only for Windows 64 ABI
514   - .cfi directives are emitted for all other ABIs
515   - for 32-bit code, substitute %e?? registers for %r??
516 */
517
518 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
519   MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
520   MachineBasicBlock::iterator MBBI = MBB.begin();
521   MachineFrameInfo *MFI = MF.getFrameInfo();
522   const Function *Fn = MF.getFunction();
523   const X86RegisterInfo *RegInfo =
524       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
525   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
526   MachineModuleInfo &MMI = MF.getMMI();
527   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
528   uint64_t MaxAlign  = MFI->getMaxAlignment(); // Desired stack alignment.
529   uint64_t StackSize = MFI->getStackSize();    // Number of bytes to allocate.
530   bool HasFP = hasFP(MF);
531   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
532   bool Is64Bit = STI.is64Bit();
533   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
534   const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
535   bool IsWin64 = STI.isTargetWin64();
536   // Not necessarily synonymous with IsWin64.
537   bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
538   bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
539   bool NeedsDwarfCFI =
540       !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
541   bool UseLEA = STI.useLeaForSP();
542   unsigned StackAlign = getStackAlignment();
543   unsigned SlotSize = RegInfo->getSlotSize();
544   unsigned FramePtr = RegInfo->getFrameRegister(MF);
545   const unsigned MachineFramePtr = STI.isTarget64BitILP32() ?
546                  getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
547   unsigned StackPtr = RegInfo->getStackRegister();
548   unsigned BasePtr = RegInfo->getBaseRegister();
549   DebugLoc DL;
550
551   // If we're forcing a stack realignment we can't rely on just the frame
552   // info, we need to know the ABI stack alignment as well in case we
553   // have a call out.  Otherwise just make sure we have some alignment - we'll
554   // go with the minimum SlotSize.
555   if (ForceStackAlign) {
556     if (MFI->hasCalls())
557       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
558     else if (MaxAlign < SlotSize)
559       MaxAlign = SlotSize;
560   }
561
562   // Add RETADDR move area to callee saved frame size.
563   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
564   if (TailCallReturnAddrDelta < 0)
565     X86FI->setCalleeSavedFrameSize(
566       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
567
568   bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
569
570   // The default stack probe size is 4096 if the function has no stackprobesize
571   // attribute.
572   unsigned StackProbeSize = 4096;
573   if (Fn->hasFnAttribute("stack-probe-size"))
574     Fn->getFnAttribute("stack-probe-size")
575         .getValueAsString()
576         .getAsInteger(0, StackProbeSize);
577
578   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
579   // function, and use up to 128 bytes of stack space, don't have a frame
580   // pointer, calls, or dynamic alloca then we do not need to adjust the
581   // stack pointer (we fit in the Red Zone). We also check that we don't
582   // push and pop from the stack.
583   if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
584                                                    Attribute::NoRedZone) &&
585       !RegInfo->needsStackRealignment(MF) &&
586       !MFI->hasVarSizedObjects() &&                     // No dynamic alloca.
587       !MFI->adjustsStack() &&                           // No calls.
588       !IsWin64 &&                                       // Win64 has no Red Zone
589       !usesTheStack(MF) &&                              // Don't push and pop.
590       !MF.shouldSplitStack()) {                         // Regular stack
591     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
592     if (HasFP) MinSize += SlotSize;
593     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
594     MFI->setStackSize(StackSize);
595   }
596
597   // Insert stack pointer adjustment for later moving of return addr.  Only
598   // applies to tail call optimized functions where the callee argument stack
599   // size is bigger than the callers.
600   if (TailCallReturnAddrDelta < 0) {
601     MachineInstr *MI =
602       BuildMI(MBB, MBBI, DL,
603               TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
604               StackPtr)
605         .addReg(StackPtr)
606         .addImm(-TailCallReturnAddrDelta)
607         .setMIFlag(MachineInstr::FrameSetup);
608     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
609   }
610
611   // Mapping for machine moves:
612   //
613   //   DST: VirtualFP AND
614   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
615   //        ELSE                        => DW_CFA_def_cfa
616   //
617   //   SRC: VirtualFP AND
618   //        DST: Register               => DW_CFA_def_cfa_register
619   //
620   //   ELSE
621   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
622   //        REG < 64                    => DW_CFA_offset + Reg
623   //        ELSE                        => DW_CFA_offset_extended
624
625   uint64_t NumBytes = 0;
626   int stackGrowth = -SlotSize;
627
628   if (HasFP) {
629     // Calculate required stack adjustment.
630     uint64_t FrameSize = StackSize - SlotSize;
631     // If required, include space for extra hidden slot for stashing base pointer.
632     if (X86FI->getRestoreBasePointer())
633       FrameSize += SlotSize;
634     if (RegInfo->needsStackRealignment(MF)) {
635       // Callee-saved registers are pushed on stack before the stack
636       // is realigned.
637       FrameSize -= X86FI->getCalleeSavedFrameSize();
638       NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
639     } else {
640       NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
641     }
642
643     // Get the offset of the stack slot for the EBP register, which is
644     // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
645     // Update the frame offset adjustment.
646     MFI->setOffsetAdjustment(-NumBytes);
647
648     // Save EBP/RBP into the appropriate stack slot.
649     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
650       .addReg(MachineFramePtr, RegState::Kill)
651       .setMIFlag(MachineInstr::FrameSetup);
652
653     if (NeedsDwarfCFI) {
654       // Mark the place where EBP/RBP was saved.
655       // Define the current CFA rule to use the provided offset.
656       assert(StackSize);
657       unsigned CFIIndex = MMI.addFrameInst(
658           MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
659       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
660           .addCFIIndex(CFIIndex);
661
662       // Change the rule for the FramePtr to be an "offset" rule.
663       unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
664       CFIIndex = MMI.addFrameInst(
665           MCCFIInstruction::createOffset(nullptr,
666                                          DwarfFramePtr, 2 * stackGrowth));
667       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
668           .addCFIIndex(CFIIndex);
669     }
670
671     if (NeedsWinEH) {
672       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
673           .addImm(FramePtr)
674           .setMIFlag(MachineInstr::FrameSetup);
675     }
676
677     // Update EBP with the new base value.
678     BuildMI(MBB, MBBI, DL,
679             TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), FramePtr)
680         .addReg(StackPtr)
681         .setMIFlag(MachineInstr::FrameSetup);
682
683     if (NeedsDwarfCFI) {
684       // Mark effective beginning of when frame pointer becomes valid.
685       // Define the current CFA to use the EBP/RBP register.
686       unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
687       unsigned CFIIndex = MMI.addFrameInst(
688           MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
689       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
690           .addCFIIndex(CFIIndex);
691     }
692
693     // Mark the FramePtr as live-in in every block.
694     for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
695       I->addLiveIn(MachineFramePtr);
696   } else {
697     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
698   }
699
700   // Skip the callee-saved push instructions.
701   bool PushedRegs = false;
702   int StackOffset = 2 * stackGrowth;
703
704   while (MBBI != MBB.end() &&
705          (MBBI->getOpcode() == X86::PUSH32r ||
706           MBBI->getOpcode() == X86::PUSH64r)) {
707     PushedRegs = true;
708     unsigned Reg = MBBI->getOperand(0).getReg();
709     ++MBBI;
710
711     if (!HasFP && NeedsDwarfCFI) {
712       // Mark callee-saved push instruction.
713       // Define the current CFA rule to use the provided offset.
714       assert(StackSize);
715       unsigned CFIIndex = MMI.addFrameInst(
716           MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
717       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
718           .addCFIIndex(CFIIndex);
719       StackOffset += stackGrowth;
720     }
721
722     if (NeedsWinEH) {
723       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
724           MachineInstr::FrameSetup);
725     }
726   }
727
728   // Realign stack after we pushed callee-saved registers (so that we'll be
729   // able to calculate their offsets from the frame pointer).
730   if (RegInfo->needsStackRealignment(MF)) {
731     assert(HasFP && "There should be a frame pointer if stack is realigned.");
732     uint64_t Val = -MaxAlign;
733     MachineInstr *MI =
734       BuildMI(MBB, MBBI, DL,
735               TII.get(getANDriOpcode(Uses64BitFramePtr, Val)), StackPtr)
736       .addReg(StackPtr)
737       .addImm(Val)
738       .setMIFlag(MachineInstr::FrameSetup);
739
740     // The EFLAGS implicit def is dead.
741     MI->getOperand(3).setIsDead();
742   }
743
744   // If there is an SUB32ri of ESP immediately before this instruction, merge
745   // the two. This can be the case when tail call elimination is enabled and
746   // the callee has more arguments then the caller.
747   NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
748
749   // If there is an ADD32ri or SUB32ri of ESP immediately after this
750   // instruction, merge the two instructions.
751   mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
752
753   // Adjust stack pointer: ESP -= numbytes.
754
755   // Windows and cygwin/mingw require a prologue helper routine when allocating
756   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
757   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
758   // stack and adjust the stack pointer in one go.  The 64-bit version of
759   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
760   // responsible for adjusting the stack pointer.  Touching the stack at 4K
761   // increments is necessary to ensure that the guard pages used by the OS
762   // virtual memory manager are allocated in correct sequence.
763   if (NumBytes >= StackProbeSize && UseStackProbe) {
764     const char *StackProbeSymbol;
765     unsigned CallOp;
766
767     getStackProbeFunction(MF, STI, CallOp, StackProbeSymbol);
768
769     // Check whether EAX is livein for this function.
770     bool isEAXAlive = isEAXLiveIn(MF);
771
772     if (isEAXAlive) {
773       // Sanity check that EAX is not livein for this function.
774       // It should not be, so throw an assert.
775       assert(!Is64Bit && "EAX is livein in x64 case!");
776
777       // Save EAX
778       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
779         .addReg(X86::EAX, RegState::Kill)
780         .setMIFlag(MachineInstr::FrameSetup);
781     }
782
783     if (Is64Bit) {
784       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
785       // Function prologue is responsible for adjusting the stack pointer.
786       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
787         .addImm(NumBytes)
788         .setMIFlag(MachineInstr::FrameSetup);
789     } else {
790       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
791       // We'll also use 4 already allocated bytes for EAX.
792       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
793         .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
794         .setMIFlag(MachineInstr::FrameSetup);
795     }
796
797     if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
798       // For the large code model, we have to call through a register. Use R11,
799       // as it is unused and clobbered by all probe functions.
800       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
801           .addExternalSymbol(StackProbeSymbol);
802       BuildMI(MBB, MBBI, DL, TII.get(CallOp))
803           .addReg(X86::R11)
804           .addReg(StackPtr, RegState::Define | RegState::Implicit)
805           .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
806           .setMIFlag(MachineInstr::FrameSetup);
807     } else {
808       BuildMI(MBB, MBBI, DL, TII.get(CallOp))
809           .addExternalSymbol(StackProbeSymbol)
810           .addReg(StackPtr, RegState::Define | RegState::Implicit)
811           .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
812           .setMIFlag(MachineInstr::FrameSetup);
813     }
814
815     if (Is64Bit) {
816       // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
817       // themself. It also does not clobber %rax so we can reuse it when
818       // adjusting %rsp.
819       BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), StackPtr)
820         .addReg(StackPtr)
821         .addReg(X86::RAX)
822         .setMIFlag(MachineInstr::FrameSetup);
823     }
824     if (isEAXAlive) {
825       // Restore EAX
826       MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
827                                               X86::EAX),
828                                       StackPtr, false, NumBytes - 4);
829       MI->setFlag(MachineInstr::FrameSetup);
830       MBB.insert(MBBI, MI);
831     }
832   } else if (NumBytes) {
833     emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
834                  UseLEA, TII, *RegInfo);
835   }
836
837   int SEHFrameOffset = 0;
838   if (NeedsWinEH) {
839     if (HasFP) {
840       // We need to set frame base offset low enough such that all saved
841       // register offsets would be positive relative to it, but we can't
842       // just use NumBytes, because .seh_setframe offset must be <=240.
843       // So we pretend to have only allocated enough space to spill the
844       // non-volatile registers.
845       // We don't care about the rest of stack allocation, because unwinder
846       // will restore SP to (BP - SEHFrameOffset)
847       for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
848         int offset = MFI->getObjectOffset(Info.getFrameIdx());
849         SEHFrameOffset = std::max(SEHFrameOffset, std::abs(offset));
850       }
851       SEHFrameOffset += SEHFrameOffset % 16; // ensure alignmant
852
853       // This only needs to account for XMM spill slots, GPR slots
854       // are covered by the .seh_pushreg's emitted above.
855       unsigned Size = SEHFrameOffset - X86FI->getCalleeSavedFrameSize();
856       if (Size) {
857         BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
858             .addImm(Size)
859             .setMIFlag(MachineInstr::FrameSetup);
860       }
861
862       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
863           .addImm(FramePtr)
864           .addImm(SEHFrameOffset)
865           .setMIFlag(MachineInstr::FrameSetup);
866     } else {
867       // SP will be the base register for restoring XMMs
868       if (NumBytes) {
869         BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
870             .addImm(NumBytes)
871             .setMIFlag(MachineInstr::FrameSetup);
872       }
873     }
874   }
875
876   // Skip the rest of register spilling code
877   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
878     ++MBBI;
879
880   // Emit SEH info for non-GPRs
881   if (NeedsWinEH) {
882     for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
883       unsigned Reg = Info.getReg();
884       if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
885         continue;
886       assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
887
888       int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
889       Offset += SEHFrameOffset;
890
891       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
892           .addImm(Reg)
893           .addImm(Offset)
894           .setMIFlag(MachineInstr::FrameSetup);
895     }
896
897     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
898         .setMIFlag(MachineInstr::FrameSetup);
899   }
900
901   // If we need a base pointer, set it up here. It's whatever the value
902   // of the stack pointer is at this point. Any variable size objects
903   // will be allocated after this, so we can still use the base pointer
904   // to reference locals.
905   if (RegInfo->hasBasePointer(MF)) {
906     // Update the base pointer with the current stack pointer.
907     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
908     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
909       .addReg(StackPtr)
910       .setMIFlag(MachineInstr::FrameSetup);
911     if (X86FI->getRestoreBasePointer()) {
912       // Stash value of base pointer.  Saving RSP instead of EBP shortens dependence chain.
913       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
914       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
915                    FramePtr, true, X86FI->getRestoreBasePointerOffset())
916         .addReg(StackPtr)
917         .setMIFlag(MachineInstr::FrameSetup);
918     }
919   }
920
921   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
922     // Mark end of stack pointer adjustment.
923     if (!HasFP && NumBytes) {
924       // Define the current CFA rule to use the provided offset.
925       assert(StackSize);
926       unsigned CFIIndex = MMI.addFrameInst(
927           MCCFIInstruction::createDefCfaOffset(nullptr,
928                                                -StackSize + stackGrowth));
929
930       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
931           .addCFIIndex(CFIIndex);
932     }
933
934     // Emit DWARF info specifying the offsets of the callee-saved registers.
935     if (PushedRegs)
936       emitCalleeSavedFrameMoves(MBB, MBBI, DL);
937   }
938 }
939
940 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
941                                     MachineBasicBlock &MBB) const {
942   const MachineFrameInfo *MFI = MF.getFrameInfo();
943   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
944   const X86RegisterInfo *RegInfo =
945       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
946   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
947   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
948   assert(MBBI != MBB.end() && "Returning block has no instructions");
949   unsigned RetOpcode = MBBI->getOpcode();
950   DebugLoc DL = MBBI->getDebugLoc();
951   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
952   bool Is64Bit = STI.is64Bit();
953   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
954   const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
955   const bool Is64BitILP32 = STI.isTarget64BitILP32();
956   bool UseLEA = STI.useLeaForSP();
957   unsigned StackAlign = getStackAlignment();
958   unsigned SlotSize = RegInfo->getSlotSize();
959   unsigned FramePtr = RegInfo->getFrameRegister(MF);
960   unsigned MachineFramePtr = Is64BitILP32 ?
961              getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
962   unsigned StackPtr = RegInfo->getStackRegister();
963
964   bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
965   bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
966
967   switch (RetOpcode) {
968   default:
969     llvm_unreachable("Can only insert epilog into returning blocks");
970   case X86::RETQ:
971   case X86::RETL:
972   case X86::RETIL:
973   case X86::RETIQ:
974   case X86::TCRETURNdi:
975   case X86::TCRETURNri:
976   case X86::TCRETURNmi:
977   case X86::TCRETURNdi64:
978   case X86::TCRETURNri64:
979   case X86::TCRETURNmi64:
980   case X86::EH_RETURN:
981   case X86::EH_RETURN64:
982     break;  // These are ok
983   }
984
985   // Get the number of bytes to allocate from the FrameInfo.
986   uint64_t StackSize = MFI->getStackSize();
987   uint64_t MaxAlign  = MFI->getMaxAlignment();
988   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
989   uint64_t NumBytes = 0;
990
991   // If we're forcing a stack realignment we can't rely on just the frame
992   // info, we need to know the ABI stack alignment as well in case we
993   // have a call out.  Otherwise just make sure we have some alignment - we'll
994   // go with the minimum.
995   if (ForceStackAlign) {
996     if (MFI->hasCalls())
997       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
998     else
999       MaxAlign = MaxAlign ? MaxAlign : 4;
1000   }
1001
1002   if (hasFP(MF)) {
1003     // Calculate required stack adjustment.
1004     uint64_t FrameSize = StackSize - SlotSize;
1005     if (RegInfo->needsStackRealignment(MF)) {
1006       // Callee-saved registers were pushed on stack before the stack
1007       // was realigned.
1008       FrameSize -= CSSize;
1009       NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
1010     } else {
1011       NumBytes = FrameSize - CSSize;
1012     }
1013
1014     // Pop EBP.
1015     BuildMI(MBB, MBBI, DL,
1016             TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1017   } else {
1018     NumBytes = StackSize - CSSize;
1019   }
1020
1021   // Skip the callee-saved pop instructions.
1022   while (MBBI != MBB.begin()) {
1023     MachineBasicBlock::iterator PI = std::prev(MBBI);
1024     unsigned Opc = PI->getOpcode();
1025
1026     if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1027         !PI->isTerminator())
1028       break;
1029
1030     --MBBI;
1031   }
1032   MachineBasicBlock::iterator FirstCSPop = MBBI;
1033
1034   DL = MBBI->getDebugLoc();
1035
1036   // If there is an ADD32ri or SUB32ri of ESP immediately before this
1037   // instruction, merge the two instructions.
1038   if (NumBytes || MFI->hasVarSizedObjects())
1039     mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1040
1041   // If dynamic alloca is used, then reset esp to point to the last callee-saved
1042   // slot before popping them off! Same applies for the case, when stack was
1043   // realigned.
1044   if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1045     if (RegInfo->needsStackRealignment(MF))
1046       MBBI = FirstCSPop;
1047     if (CSSize != 0) {
1048       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1049       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1050                    FramePtr, false, -CSSize);
1051       --MBBI;
1052     } else {
1053       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1054       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1055         .addReg(FramePtr);
1056       --MBBI;
1057     }
1058   } else if (NumBytes) {
1059     // Adjust stack pointer back: ESP += numbytes.
1060     emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr, UseLEA,
1061                  TII, *RegInfo);
1062     --MBBI;
1063   }
1064
1065   // Windows unwinder will not invoke function's exception handler if IP is
1066   // either in prologue or in epilogue.  This behavior causes a problem when a
1067   // call immediately precedes an epilogue, because the return address points
1068   // into the epilogue.  To cope with that, we insert an epilogue marker here,
1069   // then replace it with a 'nop' if it ends up immediately after a CALL in the
1070   // final emitted code.
1071   if (NeedsWinEH)
1072     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1073
1074   // We're returning from function via eh_return.
1075   if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
1076     MBBI = MBB.getLastNonDebugInstr();
1077     MachineOperand &DestAddr  = MBBI->getOperand(0);
1078     assert(DestAddr.isReg() && "Offset should be in register!");
1079     BuildMI(MBB, MBBI, DL,
1080             TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
1081             StackPtr).addReg(DestAddr.getReg());
1082   } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1083              RetOpcode == X86::TCRETURNmi ||
1084              RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1085              RetOpcode == X86::TCRETURNmi64) {
1086     bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1087     // Tail call return: adjust the stack pointer and jump to callee.
1088     MBBI = MBB.getLastNonDebugInstr();
1089     MachineOperand &JumpTarget = MBBI->getOperand(0);
1090     MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1091     assert(StackAdjust.isImm() && "Expecting immediate value.");
1092
1093     // Adjust stack pointer.
1094     int StackAdj = StackAdjust.getImm();
1095     int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1096     int Offset = 0;
1097     assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1098
1099     // Incoporate the retaddr area.
1100     Offset = StackAdj-MaxTCDelta;
1101     assert(Offset >= 0 && "Offset should never be negative");
1102
1103     if (Offset) {
1104       // Check for possible merge with preceding ADD instruction.
1105       Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1106       emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1107                    UseLEA, TII, *RegInfo);
1108     }
1109
1110     // Jump to label or value in register.
1111     if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1112       MachineInstrBuilder MIB =
1113         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1114                                        ? X86::TAILJMPd : X86::TAILJMPd64));
1115       if (JumpTarget.isGlobal())
1116         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1117                              JumpTarget.getTargetFlags());
1118       else {
1119         assert(JumpTarget.isSymbol());
1120         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1121                               JumpTarget.getTargetFlags());
1122       }
1123     } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1124       MachineInstrBuilder MIB =
1125         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1126                                        ? X86::TAILJMPm : X86::TAILJMPm64));
1127       for (unsigned i = 0; i != 5; ++i)
1128         MIB.addOperand(MBBI->getOperand(i));
1129     } else if (RetOpcode == X86::TCRETURNri64) {
1130       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1131         addReg(JumpTarget.getReg(), RegState::Kill);
1132     } else {
1133       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1134         addReg(JumpTarget.getReg(), RegState::Kill);
1135     }
1136
1137     MachineInstr *NewMI = std::prev(MBBI);
1138     NewMI->copyImplicitOps(MF, MBBI);
1139
1140     // Delete the pseudo instruction TCRETURN.
1141     MBB.erase(MBBI);
1142   } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
1143               RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
1144              (X86FI->getTCReturnAddrDelta() < 0)) {
1145     // Add the return addr area delta back since we are not tail calling.
1146     int delta = -1*X86FI->getTCReturnAddrDelta();
1147     MBBI = MBB.getLastNonDebugInstr();
1148
1149     // Check for possible merge with preceding ADD instruction.
1150     delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1151     emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, Uses64BitFramePtr, UseLEA, TII,
1152                  *RegInfo);
1153   }
1154 }
1155
1156 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1157                                           int FI) const {
1158   const X86RegisterInfo *RegInfo =
1159       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1160   const MachineFrameInfo *MFI = MF.getFrameInfo();
1161   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1162   uint64_t StackSize = MFI->getStackSize();
1163
1164   if (RegInfo->hasBasePointer(MF)) {
1165     assert (hasFP(MF) && "VLAs and dynamic stack realign, but no FP?!");
1166     if (FI < 0) {
1167       // Skip the saved EBP.
1168       return Offset + RegInfo->getSlotSize();
1169     } else {
1170       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1171       return Offset + StackSize;
1172     }
1173   } else if (RegInfo->needsStackRealignment(MF)) {
1174     if (FI < 0) {
1175       // Skip the saved EBP.
1176       return Offset + RegInfo->getSlotSize();
1177     } else {
1178       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1179       return Offset + StackSize;
1180     }
1181     // FIXME: Support tail calls
1182   } else {
1183     if (!hasFP(MF))
1184       return Offset + StackSize;
1185
1186     // Skip the saved EBP.
1187     Offset += RegInfo->getSlotSize();
1188
1189     // Skip the RETADDR move area
1190     const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1191     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1192     if (TailCallReturnAddrDelta < 0)
1193       Offset -= TailCallReturnAddrDelta;
1194   }
1195
1196   return Offset;
1197 }
1198
1199 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1200                                              unsigned &FrameReg) const {
1201   const X86RegisterInfo *RegInfo =
1202       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1203   // We can't calculate offset from frame pointer if the stack is realigned,
1204   // so enforce usage of stack/base pointer.  The base pointer is used when we
1205   // have dynamic allocas in addition to dynamic realignment.
1206   if (RegInfo->hasBasePointer(MF))
1207     FrameReg = RegInfo->getBaseRegister();
1208   else if (RegInfo->needsStackRealignment(MF))
1209     FrameReg = RegInfo->getStackRegister();
1210   else
1211     FrameReg = RegInfo->getFrameRegister(MF);
1212   return getFrameIndexOffset(MF, FI);
1213 }
1214
1215 // Simplified from getFrameIndexOffset keeping only StackPointer cases
1216 int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1217   const MachineFrameInfo *MFI = MF.getFrameInfo();
1218   // Does not include any dynamic realign.
1219   const uint64_t StackSize = MFI->getStackSize();
1220   {
1221 #ifndef NDEBUG
1222     const X86RegisterInfo *RegInfo =
1223       static_cast<const X86RegisterInfo*>(MF.getSubtarget().getRegisterInfo());
1224     // Note: LLVM arranges the stack as:
1225     // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1226     //      > "Stack Slots" (<--SP)
1227     // We can always address StackSlots from RSP.  We can usually (unless
1228     // needsStackRealignment) address CSRs from RSP, but sometimes need to
1229     // address them from RBP.  FixedObjects can be placed anywhere in the stack
1230     // frame depending on their specific requirements (i.e. we can actually
1231     // refer to arguments to the function which are stored in the *callers*
1232     // frame).  As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1233     // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1234
1235     assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1236
1237     // We don't handle tail calls, and shouldn't be seeing them
1238     // either.
1239     int TailCallReturnAddrDelta =
1240         MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1241     assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1242 #endif
1243   }
1244
1245   // This is how the math works out:
1246   //
1247   //  %rsp grows (i.e. gets lower) left to right. Each box below is
1248   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
1249   //  get to.
1250   //
1251   //    ----------------------------------
1252   //    | BP | Obj0 | Obj1 | ... | ObjN |
1253   //    ----------------------------------
1254   //    ^    ^      ^                   ^
1255   //    A    B      C                   E
1256   //
1257   // A is the incoming stack pointer.
1258   // (B - A) is the local area offset (-8 for x86-64) [1]
1259   // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1260   //
1261   // |(E - B)| is the StackSize (absolute value, positive).  For a
1262   // stack that grown down, this works out to be (B - E). [3]
1263   //
1264   // E is also the value of %rsp after stack has been set up, and we
1265   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
1266   // (C - E) == (C - A) - (B - A) + (B - E)
1267   //            { Using [1], [2] and [3] above }
1268   //         == getObjectOffset - LocalAreaOffset + StackSize
1269   //
1270
1271   // Get the Offset from the StackPointer
1272   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1273
1274   return Offset + StackSize;
1275 }
1276 // Simplified from getFrameIndexReference keeping only StackPointer cases
1277 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF, int FI,
1278                                                   unsigned &FrameReg) const {
1279   const X86RegisterInfo *RegInfo =
1280     static_cast<const X86RegisterInfo*>(MF.getSubtarget().getRegisterInfo());
1281
1282   assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1283
1284   FrameReg = RegInfo->getStackRegister();
1285   return getFrameIndexOffsetFromSP(MF, FI);
1286 }
1287
1288 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1289     MachineFunction &MF, const TargetRegisterInfo *TRI,
1290     std::vector<CalleeSavedInfo> &CSI) const {
1291   MachineFrameInfo *MFI = MF.getFrameInfo();
1292   const X86RegisterInfo *RegInfo =
1293       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1294   unsigned SlotSize = RegInfo->getSlotSize();
1295   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1296
1297   unsigned CalleeSavedFrameSize = 0;
1298   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1299
1300   if (hasFP(MF)) {
1301     // emitPrologue always spills frame register the first thing.
1302     SpillSlotOffset -= SlotSize;
1303     MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1304
1305     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1306     // the frame register, we can delete it from CSI list and not have to worry
1307     // about avoiding it later.
1308     unsigned FPReg = RegInfo->getFrameRegister(MF);
1309     for (unsigned i = 0; i < CSI.size(); ++i) {
1310       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1311         CSI.erase(CSI.begin() + i);
1312         break;
1313       }
1314     }
1315   }
1316
1317   // Assign slots for GPRs. It increases frame size.
1318   for (unsigned i = CSI.size(); i != 0; --i) {
1319     unsigned Reg = CSI[i - 1].getReg();
1320
1321     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1322       continue;
1323
1324     SpillSlotOffset -= SlotSize;
1325     CalleeSavedFrameSize += SlotSize;
1326
1327     int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1328     CSI[i - 1].setFrameIdx(SlotIndex);
1329   }
1330
1331   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1332
1333   // Assign slots for XMMs.
1334   for (unsigned i = CSI.size(); i != 0; --i) {
1335     unsigned Reg = CSI[i - 1].getReg();
1336     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1337       continue;
1338
1339     const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1340     // ensure alignment
1341     SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1342     // spill into slot
1343     SpillSlotOffset -= RC->getSize();
1344     int SlotIndex =
1345         MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1346     CSI[i - 1].setFrameIdx(SlotIndex);
1347     MFI->ensureMaxAlignment(RC->getAlignment());
1348   }
1349
1350   return true;
1351 }
1352
1353 bool X86FrameLowering::spillCalleeSavedRegisters(
1354     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1355     const std::vector<CalleeSavedInfo> &CSI,
1356     const TargetRegisterInfo *TRI) const {
1357   DebugLoc DL = MBB.findDebugLoc(MI);
1358
1359   MachineFunction &MF = *MBB.getParent();
1360   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1361   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1362
1363   // Push GPRs. It increases frame size.
1364   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1365   for (unsigned i = CSI.size(); i != 0; --i) {
1366     unsigned Reg = CSI[i - 1].getReg();
1367
1368     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1369       continue;
1370     // Add the callee-saved register as live-in. It's killed at the spill.
1371     MBB.addLiveIn(Reg);
1372
1373     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1374       .setMIFlag(MachineInstr::FrameSetup);
1375   }
1376
1377   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1378   // It can be done by spilling XMMs to stack frame.
1379   for (unsigned i = CSI.size(); i != 0; --i) {
1380     unsigned Reg = CSI[i-1].getReg();
1381     if (X86::GR64RegClass.contains(Reg) ||
1382         X86::GR32RegClass.contains(Reg))
1383       continue;
1384     // Add the callee-saved register as live-in. It's killed at the spill.
1385     MBB.addLiveIn(Reg);
1386     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1387
1388     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1389                             TRI);
1390     --MI;
1391     MI->setFlag(MachineInstr::FrameSetup);
1392     ++MI;
1393   }
1394
1395   return true;
1396 }
1397
1398 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1399                                                MachineBasicBlock::iterator MI,
1400                                         const std::vector<CalleeSavedInfo> &CSI,
1401                                           const TargetRegisterInfo *TRI) const {
1402   if (CSI.empty())
1403     return false;
1404
1405   DebugLoc DL = MBB.findDebugLoc(MI);
1406
1407   MachineFunction &MF = *MBB.getParent();
1408   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1409   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1410
1411   // Reload XMMs from stack frame.
1412   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1413     unsigned Reg = CSI[i].getReg();
1414     if (X86::GR64RegClass.contains(Reg) ||
1415         X86::GR32RegClass.contains(Reg))
1416       continue;
1417
1418     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1419     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1420   }
1421
1422   // POP GPRs.
1423   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1424   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1425     unsigned Reg = CSI[i].getReg();
1426     if (!X86::GR64RegClass.contains(Reg) &&
1427         !X86::GR32RegClass.contains(Reg))
1428       continue;
1429
1430     BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1431   }
1432   return true;
1433 }
1434
1435 void
1436 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1437                                                        RegScavenger *RS) const {
1438   MachineFrameInfo *MFI = MF.getFrameInfo();
1439   const X86RegisterInfo *RegInfo =
1440       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1441   unsigned SlotSize = RegInfo->getSlotSize();
1442
1443   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1444   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1445
1446   if (TailCallReturnAddrDelta < 0) {
1447     // create RETURNADDR area
1448     //   arg
1449     //   arg
1450     //   RETADDR
1451     //   { ...
1452     //     RETADDR area
1453     //     ...
1454     //   }
1455     //   [EBP]
1456     MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1457                            TailCallReturnAddrDelta - SlotSize, true);
1458   }
1459
1460   // Spill the BasePtr if it's used.
1461   if (RegInfo->hasBasePointer(MF))
1462     MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1463 }
1464
1465 static bool
1466 HasNestArgument(const MachineFunction *MF) {
1467   const Function *F = MF->getFunction();
1468   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1469        I != E; I++) {
1470     if (I->hasNestAttr())
1471       return true;
1472   }
1473   return false;
1474 }
1475
1476 /// GetScratchRegister - Get a temp register for performing work in the
1477 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1478 /// and the properties of the function either one or two registers will be
1479 /// needed. Set primary to true for the first register, false for the second.
1480 static unsigned
1481 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1482   CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1483
1484   // Erlang stuff.
1485   if (CallingConvention == CallingConv::HiPE) {
1486     if (Is64Bit)
1487       return Primary ? X86::R14 : X86::R13;
1488     else
1489       return Primary ? X86::EBX : X86::EDI;
1490   }
1491
1492   if (Is64Bit) {
1493     if (IsLP64)
1494       return Primary ? X86::R11 : X86::R12;
1495     else
1496       return Primary ? X86::R11D : X86::R12D;
1497   }
1498
1499   bool IsNested = HasNestArgument(&MF);
1500
1501   if (CallingConvention == CallingConv::X86_FastCall ||
1502       CallingConvention == CallingConv::Fast) {
1503     if (IsNested)
1504       report_fatal_error("Segmented stacks does not support fastcall with "
1505                          "nested function.");
1506     return Primary ? X86::EAX : X86::ECX;
1507   }
1508   if (IsNested)
1509     return Primary ? X86::EDX : X86::EAX;
1510   return Primary ? X86::ECX : X86::EAX;
1511 }
1512
1513 // The stack limit in the TCB is set to this many bytes above the actual stack
1514 // limit.
1515 static const uint64_t kSplitStackAvailable = 256;
1516
1517 void
1518 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1519   MachineBasicBlock &prologueMBB = MF.front();
1520   MachineFrameInfo *MFI = MF.getFrameInfo();
1521   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1522   uint64_t StackSize;
1523   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1524   bool Is64Bit = STI.is64Bit();
1525   const bool IsLP64 = STI.isTarget64BitLP64();
1526   unsigned TlsReg, TlsOffset;
1527   DebugLoc DL;
1528
1529   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1530   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1531          "Scratch register is live-in");
1532
1533   if (MF.getFunction()->isVarArg())
1534     report_fatal_error("Segmented stacks do not support vararg functions.");
1535   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1536       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1537       !STI.isTargetDragonFly())
1538     report_fatal_error("Segmented stacks not supported on this platform.");
1539
1540   // Eventually StackSize will be calculated by a link-time pass; which will
1541   // also decide whether checking code needs to be injected into this particular
1542   // prologue.
1543   StackSize = MFI->getStackSize();
1544
1545   // Do not generate a prologue for functions with a stack of size zero
1546   if (StackSize == 0)
1547     return;
1548
1549   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1550   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1551   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1552   bool IsNested = false;
1553
1554   // We need to know if the function has a nest argument only in 64 bit mode.
1555   if (Is64Bit)
1556     IsNested = HasNestArgument(&MF);
1557
1558   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1559   // allocMBB needs to be last (terminating) instruction.
1560
1561   for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1562          e = prologueMBB.livein_end(); i != e; i++) {
1563     allocMBB->addLiveIn(*i);
1564     checkMBB->addLiveIn(*i);
1565   }
1566
1567   if (IsNested)
1568     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1569
1570   MF.push_front(allocMBB);
1571   MF.push_front(checkMBB);
1572
1573   // When the frame size is less than 256 we just compare the stack
1574   // boundary directly to the value of the stack pointer, per gcc.
1575   bool CompareStackPointer = StackSize < kSplitStackAvailable;
1576
1577   // Read the limit off the current stacklet off the stack_guard location.
1578   if (Is64Bit) {
1579     if (STI.isTargetLinux()) {
1580       TlsReg = X86::FS;
1581       TlsOffset = IsLP64 ? 0x70 : 0x40;
1582     } else if (STI.isTargetDarwin()) {
1583       TlsReg = X86::GS;
1584       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1585     } else if (STI.isTargetWin64()) {
1586       TlsReg = X86::GS;
1587       TlsOffset = 0x28; // pvArbitrary, reserved for application use
1588     } else if (STI.isTargetFreeBSD()) {
1589       TlsReg = X86::FS;
1590       TlsOffset = 0x18;
1591     } else if (STI.isTargetDragonFly()) {
1592       TlsReg = X86::FS;
1593       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1594     } else {
1595       report_fatal_error("Segmented stacks not supported on this platform.");
1596     }
1597
1598     if (CompareStackPointer)
1599       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1600     else
1601       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1602         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1603
1604     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1605       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1606   } else {
1607     if (STI.isTargetLinux()) {
1608       TlsReg = X86::GS;
1609       TlsOffset = 0x30;
1610     } else if (STI.isTargetDarwin()) {
1611       TlsReg = X86::GS;
1612       TlsOffset = 0x48 + 90*4;
1613     } else if (STI.isTargetWin32()) {
1614       TlsReg = X86::FS;
1615       TlsOffset = 0x14; // pvArbitrary, reserved for application use
1616     } else if (STI.isTargetDragonFly()) {
1617       TlsReg = X86::FS;
1618       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1619     } else if (STI.isTargetFreeBSD()) {
1620       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1621     } else {
1622       report_fatal_error("Segmented stacks not supported on this platform.");
1623     }
1624
1625     if (CompareStackPointer)
1626       ScratchReg = X86::ESP;
1627     else
1628       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1629         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1630
1631     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1632         STI.isTargetDragonFly()) {
1633       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1634         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1635     } else if (STI.isTargetDarwin()) {
1636
1637       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1638       unsigned ScratchReg2;
1639       bool SaveScratch2;
1640       if (CompareStackPointer) {
1641         // The primary scratch register is available for holding the TLS offset.
1642         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1643         SaveScratch2 = false;
1644       } else {
1645         // Need to use a second register to hold the TLS offset
1646         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1647
1648         // Unfortunately, with fastcc the second scratch register may hold an
1649         // argument.
1650         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1651       }
1652
1653       // If Scratch2 is live-in then it needs to be saved.
1654       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1655              "Scratch register is live-in and not saved");
1656
1657       if (SaveScratch2)
1658         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1659           .addReg(ScratchReg2, RegState::Kill);
1660
1661       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1662         .addImm(TlsOffset);
1663       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1664         .addReg(ScratchReg)
1665         .addReg(ScratchReg2).addImm(1).addReg(0)
1666         .addImm(0)
1667         .addReg(TlsReg);
1668
1669       if (SaveScratch2)
1670         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1671     }
1672   }
1673
1674   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1675   // It jumps to normal execution of the function body.
1676   BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&prologueMBB);
1677
1678   // On 32 bit we first push the arguments size and then the frame size. On 64
1679   // bit, we pass the stack frame size in r10 and the argument size in r11.
1680   if (Is64Bit) {
1681     // Functions with nested arguments use R10, so it needs to be saved across
1682     // the call to _morestack
1683
1684     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1685     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1686     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1687     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1688     const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1689
1690     if (IsNested)
1691       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1692
1693     BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1694       .addImm(StackSize);
1695     BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1696       .addImm(X86FI->getArgumentStackSize());
1697     MF.getRegInfo().setPhysRegUsed(Reg10);
1698     MF.getRegInfo().setPhysRegUsed(Reg11);
1699   } else {
1700     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1701       .addImm(X86FI->getArgumentStackSize());
1702     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1703       .addImm(StackSize);
1704   }
1705
1706   // __morestack is in libgcc
1707   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1708     // Under the large code model, we cannot assume that __morestack lives
1709     // within 2^31 bytes of the call site, so we cannot use pc-relative
1710     // addressing. We cannot perform the call via a temporary register,
1711     // as the rax register may be used to store the static chain, and all
1712     // other suitable registers may be either callee-save or used for
1713     // parameter passing. We cannot use the stack at this point either
1714     // because __morestack manipulates the stack directly.
1715     //
1716     // To avoid these issues, perform an indirect call via a read-only memory
1717     // location containing the address.
1718     //
1719     // This solution is not perfect, as it assumes that the .rodata section
1720     // is laid out within 2^31 bytes of each function body, but this seems
1721     // to be sufficient for JIT.
1722     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1723         .addReg(X86::RIP)
1724         .addImm(0)
1725         .addReg(0)
1726         .addExternalSymbol("__morestack_addr")
1727         .addReg(0);
1728     MF.getMMI().setUsesMorestackAddr(true);
1729   } else {
1730     if (Is64Bit)
1731       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1732         .addExternalSymbol("__morestack");
1733     else
1734       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1735         .addExternalSymbol("__morestack");
1736   }
1737
1738   if (IsNested)
1739     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1740   else
1741     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1742
1743   allocMBB->addSuccessor(&prologueMBB);
1744
1745   checkMBB->addSuccessor(allocMBB);
1746   checkMBB->addSuccessor(&prologueMBB);
1747
1748 #ifdef XDEBUG
1749   MF.verify();
1750 #endif
1751 }
1752
1753 /// Erlang programs may need a special prologue to handle the stack size they
1754 /// might need at runtime. That is because Erlang/OTP does not implement a C
1755 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1756 /// (for more information see Eric Stenman's Ph.D. thesis:
1757 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1758 ///
1759 /// CheckStack:
1760 ///       temp0 = sp - MaxStack
1761 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1762 /// OldStart:
1763 ///       ...
1764 /// IncStack:
1765 ///       call inc_stack   # doubles the stack space
1766 ///       temp0 = sp - MaxStack
1767 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1768 void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
1769   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1770   MachineFrameInfo *MFI = MF.getFrameInfo();
1771   const unsigned SlotSize =
1772       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo())
1773           ->getSlotSize();
1774   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1775   const bool Is64Bit = STI.is64Bit();
1776   const bool IsLP64 = STI.isTarget64BitLP64();
1777   DebugLoc DL;
1778   // HiPE-specific values
1779   const unsigned HipeLeafWords = 24;
1780   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1781   const unsigned Guaranteed = HipeLeafWords * SlotSize;
1782   unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1783                             MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1784   unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1785
1786   assert(STI.isTargetLinux() &&
1787          "HiPE prologue is only supported on Linux operating systems.");
1788
1789   // Compute the largest caller's frame that is needed to fit the callees'
1790   // frames. This 'MaxStack' is computed from:
1791   //
1792   // a) the fixed frame size, which is the space needed for all spilled temps,
1793   // b) outgoing on-stack parameter areas, and
1794   // c) the minimum stack space this function needs to make available for the
1795   //    functions it calls (a tunable ABI property).
1796   if (MFI->hasCalls()) {
1797     unsigned MoreStackForCalls = 0;
1798
1799     for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1800          MBBI != MBBE; ++MBBI)
1801       for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1802            MI != ME; ++MI) {
1803         if (!MI->isCall())
1804           continue;
1805
1806         // Get callee operand.
1807         const MachineOperand &MO = MI->getOperand(0);
1808
1809         // Only take account of global function calls (no closures etc.).
1810         if (!MO.isGlobal())
1811           continue;
1812
1813         const Function *F = dyn_cast<Function>(MO.getGlobal());
1814         if (!F)
1815           continue;
1816
1817         // Do not update 'MaxStack' for primitive and built-in functions
1818         // (encoded with names either starting with "erlang."/"bif_" or not
1819         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1820         // "_", such as the BIF "suspend_0") as they are executed on another
1821         // stack.
1822         if (F->getName().find("erlang.") != StringRef::npos ||
1823             F->getName().find("bif_") != StringRef::npos ||
1824             F->getName().find_first_of("._") == StringRef::npos)
1825           continue;
1826
1827         unsigned CalleeStkArity =
1828           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1829         if (HipeLeafWords - 1 > CalleeStkArity)
1830           MoreStackForCalls = std::max(MoreStackForCalls,
1831                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1832       }
1833     MaxStack += MoreStackForCalls;
1834   }
1835
1836   // If the stack frame needed is larger than the guaranteed then runtime checks
1837   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1838   if (MaxStack > Guaranteed) {
1839     MachineBasicBlock &prologueMBB = MF.front();
1840     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1841     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1842
1843     for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
1844            E = prologueMBB.livein_end(); I != E; I++) {
1845       stackCheckMBB->addLiveIn(*I);
1846       incStackMBB->addLiveIn(*I);
1847     }
1848
1849     MF.push_front(incStackMBB);
1850     MF.push_front(stackCheckMBB);
1851
1852     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1853     unsigned LEAop, CMPop, CALLop;
1854     if (Is64Bit) {
1855       SPReg = X86::RSP;
1856       PReg  = X86::RBP;
1857       LEAop = X86::LEA64r;
1858       CMPop = X86::CMP64rm;
1859       CALLop = X86::CALL64pcrel32;
1860       SPLimitOffset = 0x90;
1861     } else {
1862       SPReg = X86::ESP;
1863       PReg  = X86::EBP;
1864       LEAop = X86::LEA32r;
1865       CMPop = X86::CMP32rm;
1866       CALLop = X86::CALLpcrel32;
1867       SPLimitOffset = 0x4c;
1868     }
1869
1870     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1871     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1872            "HiPE prologue scratch register is live-in");
1873
1874     // Create new MBB for StackCheck:
1875     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1876                  SPReg, false, -MaxStack);
1877     // SPLimitOffset is in a fixed heap location (pointed by BP).
1878     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1879                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
1880     BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&prologueMBB);
1881
1882     // Create new MBB for IncStack:
1883     BuildMI(incStackMBB, DL, TII.get(CALLop)).
1884       addExternalSymbol("inc_stack_0");
1885     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1886                  SPReg, false, -MaxStack);
1887     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1888                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
1889     BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1890
1891     stackCheckMBB->addSuccessor(&prologueMBB, 99);
1892     stackCheckMBB->addSuccessor(incStackMBB, 1);
1893     incStackMBB->addSuccessor(&prologueMBB, 99);
1894     incStackMBB->addSuccessor(incStackMBB, 1);
1895   }
1896 #ifdef XDEBUG
1897   MF.verify();
1898 #endif
1899 }
1900
1901 bool X86FrameLowering::
1902 convertArgMovsToPushes(MachineFunction &MF, MachineBasicBlock &MBB,
1903                        MachineBasicBlock::iterator I, uint64_t Amount) const {
1904   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1905   const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
1906     MF.getSubtarget().getRegisterInfo());
1907   unsigned StackPtr = RegInfo.getStackRegister();
1908
1909   // Scan the call setup sequence for the pattern we're looking for.
1910   // We only handle a simple case now - a sequence of MOV32mi or MOV32mr
1911   // instructions, that push a sequence of 32-bit values onto the stack, with
1912   // no gaps.  
1913   std::map<int64_t, MachineBasicBlock::iterator> MovMap;
1914   do {
1915     int Opcode = I->getOpcode();
1916     if (Opcode != X86::MOV32mi && Opcode != X86::MOV32mr)
1917       break;
1918  
1919     // We only want movs of the form:
1920     // movl imm/r32, k(%ecx)
1921     // If we run into something else, bail
1922     // Note that AddrBaseReg may, counterintuitively, not be a register...
1923     if (!I->getOperand(X86::AddrBaseReg).isReg() || 
1924         (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
1925         !I->getOperand(X86::AddrScaleAmt).isImm() ||
1926         (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
1927         (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
1928         (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
1929         !I->getOperand(X86::AddrDisp).isImm())
1930       return false;
1931
1932     int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
1933     
1934     // We don't want to consider the unaligned case.
1935     if (StackDisp % 4)
1936       return false;
1937
1938     // If the same stack slot is being filled twice, something's fishy.
1939     if (!MovMap.insert(std::pair<int64_t, MachineInstr*>(StackDisp, I)).second)
1940       return false;
1941
1942     ++I;
1943   } while (I != MBB.end());
1944
1945   // We now expect the end of the sequence - a call and a stack adjust.
1946   if (I == MBB.end())
1947     return false;
1948   if (!I->isCall())
1949     return false;
1950   MachineBasicBlock::iterator Call = I;
1951   if ((++I)->getOpcode() != TII.getCallFrameDestroyOpcode())
1952     return false;
1953
1954   // Now, go through the map, and see that we don't have any gaps,
1955   // but only a series of 32-bit MOVs.
1956   // Since std::map provides ordered iteration, the original order
1957   // of the MOVs doesn't matter.
1958   int64_t ExpectedDist = 0;
1959   for (auto MMI = MovMap.begin(), MME = MovMap.end(); MMI != MME; 
1960        ++MMI, ExpectedDist += 4)
1961     if (MMI->first != ExpectedDist)
1962       return false;
1963
1964   // Ok, everything looks fine. Do the transformation.
1965   DebugLoc DL = I->getDebugLoc();
1966
1967   // It's possible the original stack adjustment amount was larger than
1968   // that done by the pushes. If so, we still need a SUB.
1969   Amount -= ExpectedDist;
1970   if (Amount) {
1971     MachineInstr* Sub = BuildMI(MBB, Call, DL,
1972                           TII.get(getSUBriOpcode(false, Amount)), StackPtr)
1973                   .addReg(StackPtr).addImm(Amount);
1974     Sub->getOperand(3).setIsDead();
1975   }
1976
1977   // Now, iterate through the map in reverse order, and replace the movs
1978   // with pushes. MOVmi/MOVmr doesn't have any defs, so need to replace uses.
1979   for (auto MMI = MovMap.rbegin(), MME = MovMap.rend(); MMI != MME; ++MMI) {
1980     MachineBasicBlock::iterator MOV = MMI->second;
1981     MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
1982
1983     // Replace MOVmr with PUSH32r, and MOVmi with PUSHi of appropriate size
1984     int PushOpcode = X86::PUSH32r;
1985     if (MOV->getOpcode() == X86::MOV32mi)
1986       PushOpcode = getPUSHiOpcode(false, PushOp);
1987
1988     BuildMI(MBB, Call, DL, TII.get(PushOpcode)).addOperand(PushOp);
1989     MBB.erase(MOV);
1990   }
1991
1992   return true;
1993 }
1994
1995 void X86FrameLowering::
1996 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1997                               MachineBasicBlock::iterator I) const {
1998   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1999   const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
2000                                        MF.getSubtarget().getRegisterInfo());
2001   unsigned StackPtr = RegInfo.getStackRegister();
2002   bool reserveCallFrame = hasReservedCallFrame(MF);
2003   int Opcode = I->getOpcode();
2004   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
2005   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
2006   bool IsLP64 = STI.isTarget64BitLP64();
2007   DebugLoc DL = I->getDebugLoc();
2008   uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
2009   uint64_t CalleeAmt = isDestroy ? I->getOperand(1).getImm() : 0;
2010   I = MBB.erase(I);
2011
2012   if (!reserveCallFrame) {
2013     // If the stack pointer can be changed after prologue, turn the
2014     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
2015     // adjcallstackdown instruction into 'add ESP, <amt>'
2016     if (Amount == 0)
2017       return;
2018
2019     // We need to keep the stack aligned properly.  To do this, we round the
2020     // amount of space needed for the outgoing arguments up to the next
2021     // alignment boundary.
2022     unsigned StackAlign = MF.getTarget()
2023                               .getSubtargetImpl()
2024                               ->getFrameLowering()
2025                               ->getStackAlignment();
2026     Amount = (Amount + StackAlign - 1) / StackAlign * StackAlign;
2027
2028     MachineInstr *New = nullptr;
2029     if (Opcode == TII.getCallFrameSetupOpcode()) {
2030       // Try to convert movs to the stack into pushes.
2031       // We currently only look for a pattern that appears in 32-bit
2032       // calling conventions.
2033       if (!IsLP64 && convertArgMovsToPushes(MF, MBB, I, Amount))
2034         return;
2035
2036       New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)),
2037                     StackPtr)
2038         .addReg(StackPtr)
2039         .addImm(Amount);
2040     } else {
2041       assert(Opcode == TII.getCallFrameDestroyOpcode());
2042
2043       // Factor out the amount the callee already popped.
2044       Amount -= CalleeAmt;
2045
2046       if (Amount) {
2047         unsigned Opc = getADDriOpcode(IsLP64, Amount);
2048         New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
2049           .addReg(StackPtr).addImm(Amount);
2050       }
2051     }
2052
2053     if (New) {
2054       // The EFLAGS implicit def is dead.
2055       New->getOperand(3).setIsDead();
2056
2057       // Replace the pseudo instruction with a new instruction.
2058       MBB.insert(I, New);
2059     }
2060
2061     return;
2062   }
2063
2064   if (Opcode == TII.getCallFrameDestroyOpcode() && CalleeAmt) {
2065     // If we are performing frame pointer elimination and if the callee pops
2066     // something off the stack pointer, add it back.  We do this until we have
2067     // more advanced stack pointer tracking ability.
2068     unsigned Opc = getSUBriOpcode(IsLP64, CalleeAmt);
2069     MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
2070       .addReg(StackPtr).addImm(CalleeAmt);
2071
2072     // The EFLAGS implicit def is dead.
2073     New->getOperand(3).setIsDead();
2074
2075     // We are not tracking the stack pointer adjustment by the callee, so make
2076     // sure we restore the stack pointer immediately after the call, there may
2077     // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
2078     MachineBasicBlock::iterator B = MBB.begin();
2079     while (I != B && !std::prev(I)->isCall())
2080       --I;
2081     MBB.insert(I, New);
2082   }
2083 }
2084