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