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