LLVM API Documentation

X86FrameLowering.cpp
Go to the documentation of this file.
00001 //===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the X86 implementation of TargetFrameLowering class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "X86FrameLowering.h"
00015 #include "X86InstrBuilder.h"
00016 #include "X86InstrInfo.h"
00017 #include "X86MachineFunctionInfo.h"
00018 #include "X86Subtarget.h"
00019 #include "X86TargetMachine.h"
00020 #include "llvm/ADT/SmallSet.h"
00021 #include "llvm/CodeGen/MachineFrameInfo.h"
00022 #include "llvm/CodeGen/MachineFunction.h"
00023 #include "llvm/CodeGen/MachineInstrBuilder.h"
00024 #include "llvm/CodeGen/MachineModuleInfo.h"
00025 #include "llvm/CodeGen/MachineRegisterInfo.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/Function.h"
00028 #include "llvm/MC/MCAsmInfo.h"
00029 #include "llvm/MC/MCSymbol.h"
00030 #include "llvm/Support/CommandLine.h"
00031 #include "llvm/Target/TargetOptions.h"
00032 #include "llvm/Support/Debug.h"
00033 #include <cstdlib>
00034 
00035 using namespace llvm;
00036 
00037 // FIXME: completely move here.
00038 extern cl::opt<bool> ForceStackAlign;
00039 
00040 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
00041   return !MF.getFrameInfo()->hasVarSizedObjects();
00042 }
00043 
00044 /// hasFP - Return true if the specified function should have a dedicated frame
00045 /// pointer register.  This is true if the function has variable sized allocas
00046 /// or if frame pointer elimination is disabled.
00047 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
00048   const MachineFrameInfo *MFI = MF.getFrameInfo();
00049   const MachineModuleInfo &MMI = MF.getMMI();
00050   const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
00051 
00052   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
00053           RegInfo->needsStackRealignment(MF) ||
00054           MFI->hasVarSizedObjects() ||
00055           MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
00056           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
00057           MMI.callsUnwindInit() || MMI.callsEHReturn() ||
00058           MFI->hasStackMap() || MFI->hasPatchPoint());
00059 }
00060 
00061 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
00062   if (IsLP64) {
00063     if (isInt<8>(Imm))
00064       return X86::SUB64ri8;
00065     return X86::SUB64ri32;
00066   } else {
00067     if (isInt<8>(Imm))
00068       return X86::SUB32ri8;
00069     return X86::SUB32ri;
00070   }
00071 }
00072 
00073 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
00074   if (IsLP64) {
00075     if (isInt<8>(Imm))
00076       return X86::ADD64ri8;
00077     return X86::ADD64ri32;
00078   } else {
00079     if (isInt<8>(Imm))
00080       return X86::ADD32ri8;
00081     return X86::ADD32ri;
00082   }
00083 }
00084 
00085 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
00086   if (IsLP64) {
00087     if (isInt<8>(Imm))
00088       return X86::AND64ri8;
00089     return X86::AND64ri32;
00090   }
00091   if (isInt<8>(Imm))
00092     return X86::AND32ri8;
00093   return X86::AND32ri;
00094 }
00095 
00096 static unsigned getPUSHiOpcode(bool IsLP64, MachineOperand MO) {
00097   // We don't support LP64 for now.
00098   assert(!IsLP64);
00099 
00100   if (MO.isImm() && isInt<8>(MO.getImm()))
00101     return X86::PUSH32i8;
00102 
00103   return X86::PUSHi32;;
00104 }
00105 
00106 static unsigned getLEArOpcode(unsigned IsLP64) {
00107   return IsLP64 ? X86::LEA64r : X86::LEA32r;
00108 }
00109 
00110 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
00111 /// when it reaches the "return" instruction. We can then pop a stack object
00112 /// to this register without worry about clobbering it.
00113 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
00114                                        MachineBasicBlock::iterator &MBBI,
00115                                        const TargetRegisterInfo &TRI,
00116                                        bool Is64Bit) {
00117   const MachineFunction *MF = MBB.getParent();
00118   const Function *F = MF->getFunction();
00119   if (!F || MF->getMMI().callsEHReturn())
00120     return 0;
00121 
00122   static const uint16_t CallerSavedRegs32Bit[] = {
00123     X86::EAX, X86::EDX, X86::ECX, 0
00124   };
00125 
00126   static const uint16_t CallerSavedRegs64Bit[] = {
00127     X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
00128     X86::R8,  X86::R9,  X86::R10, X86::R11, 0
00129   };
00130 
00131   unsigned Opc = MBBI->getOpcode();
00132   switch (Opc) {
00133   default: return 0;
00134   case X86::RETL:
00135   case X86::RETQ:
00136   case X86::RETIL:
00137   case X86::RETIQ:
00138   case X86::TCRETURNdi:
00139   case X86::TCRETURNri:
00140   case X86::TCRETURNmi:
00141   case X86::TCRETURNdi64:
00142   case X86::TCRETURNri64:
00143   case X86::TCRETURNmi64:
00144   case X86::EH_RETURN:
00145   case X86::EH_RETURN64: {
00146     SmallSet<uint16_t, 8> Uses;
00147     for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
00148       MachineOperand &MO = MBBI->getOperand(i);
00149       if (!MO.isReg() || MO.isDef())
00150         continue;
00151       unsigned Reg = MO.getReg();
00152       if (!Reg)
00153         continue;
00154       for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
00155         Uses.insert(*AI);
00156     }
00157 
00158     const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
00159     for (; *CS; ++CS)
00160       if (!Uses.count(*CS))
00161         return *CS;
00162   }
00163   }
00164 
00165   return 0;
00166 }
00167 
00168 
00169 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
00170 /// stack pointer by a constant value.
00171 static
00172 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
00173                   unsigned StackPtr, int64_t NumBytes,
00174                   bool Is64BitTarget, bool Is64BitStackPtr, bool UseLEA,
00175                   const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
00176   bool isSub = NumBytes < 0;
00177   uint64_t Offset = isSub ? -NumBytes : NumBytes;
00178   unsigned Opc;
00179   if (UseLEA)
00180     Opc = getLEArOpcode(Is64BitStackPtr);
00181   else
00182     Opc = isSub
00183       ? getSUBriOpcode(Is64BitStackPtr, Offset)
00184       : getADDriOpcode(Is64BitStackPtr, Offset);
00185 
00186   uint64_t Chunk = (1LL << 31) - 1;
00187   DebugLoc DL = MBB.findDebugLoc(MBBI);
00188 
00189   while (Offset) {
00190     uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
00191     if (ThisVal == (Is64BitTarget ? 8 : 4)) {
00192       // Use push / pop instead.
00193       unsigned Reg = isSub
00194         ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
00195         : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
00196       if (Reg) {
00197         Opc = isSub
00198           ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
00199           : (Is64BitTarget ? X86::POP64r  : X86::POP32r);
00200         MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
00201           .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
00202         if (isSub)
00203           MI->setFlag(MachineInstr::FrameSetup);
00204         Offset -= ThisVal;
00205         continue;
00206       }
00207     }
00208 
00209     MachineInstr *MI = nullptr;
00210 
00211     if (UseLEA) {
00212       MI =  addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
00213                           StackPtr, false, isSub ? -ThisVal : ThisVal);
00214     } else {
00215       MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
00216             .addReg(StackPtr)
00217             .addImm(ThisVal);
00218       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
00219     }
00220 
00221     if (isSub)
00222       MI->setFlag(MachineInstr::FrameSetup);
00223 
00224     Offset -= ThisVal;
00225   }
00226 }
00227 
00228 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
00229 static
00230 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
00231                       unsigned StackPtr, uint64_t *NumBytes = nullptr) {
00232   if (MBBI == MBB.begin()) return;
00233 
00234   MachineBasicBlock::iterator PI = std::prev(MBBI);
00235   unsigned Opc = PI->getOpcode();
00236   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
00237        Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
00238        Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
00239       PI->getOperand(0).getReg() == StackPtr) {
00240     if (NumBytes)
00241       *NumBytes += PI->getOperand(2).getImm();
00242     MBB.erase(PI);
00243   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
00244               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
00245              PI->getOperand(0).getReg() == StackPtr) {
00246     if (NumBytes)
00247       *NumBytes -= PI->getOperand(2).getImm();
00248     MBB.erase(PI);
00249   }
00250 }
00251 
00252 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
00253 /// iterator.
00254 static
00255 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
00256                         MachineBasicBlock::iterator &MBBI,
00257                         unsigned StackPtr, uint64_t *NumBytes = nullptr) {
00258   // FIXME:  THIS ISN'T RUN!!!
00259   return;
00260 
00261   if (MBBI == MBB.end()) return;
00262 
00263   MachineBasicBlock::iterator NI = std::next(MBBI);
00264   if (NI == MBB.end()) return;
00265 
00266   unsigned Opc = NI->getOpcode();
00267   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
00268        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
00269       NI->getOperand(0).getReg() == StackPtr) {
00270     if (NumBytes)
00271       *NumBytes -= NI->getOperand(2).getImm();
00272     MBB.erase(NI);
00273     MBBI = NI;
00274   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
00275               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
00276              NI->getOperand(0).getReg() == StackPtr) {
00277     if (NumBytes)
00278       *NumBytes += NI->getOperand(2).getImm();
00279     MBB.erase(NI);
00280     MBBI = NI;
00281   }
00282 }
00283 
00284 /// mergeSPUpdates - Checks the instruction before/after the passed
00285 /// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
00286 /// the stack adjustment is returned as a positive value for ADD/LEA and a
00287 /// negative for SUB.
00288 static int mergeSPUpdates(MachineBasicBlock &MBB,
00289                           MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
00290                           bool doMergeWithPrevious) {
00291   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
00292       (!doMergeWithPrevious && MBBI == MBB.end()))
00293     return 0;
00294 
00295   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
00296   MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
00297                                                        : std::next(MBBI);
00298   unsigned Opc = PI->getOpcode();
00299   int Offset = 0;
00300 
00301   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
00302        Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
00303        Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
00304       PI->getOperand(0).getReg() == StackPtr){
00305     Offset += PI->getOperand(2).getImm();
00306     MBB.erase(PI);
00307     if (!doMergeWithPrevious) MBBI = NI;
00308   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
00309               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
00310              PI->getOperand(0).getReg() == StackPtr) {
00311     Offset -= PI->getOperand(2).getImm();
00312     MBB.erase(PI);
00313     if (!doMergeWithPrevious) MBBI = NI;
00314   }
00315 
00316   return Offset;
00317 }
00318 
00319 static bool isEAXLiveIn(MachineFunction &MF) {
00320   for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
00321        EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
00322     unsigned Reg = II->first;
00323 
00324     if (Reg == X86::EAX || Reg == X86::AX ||
00325         Reg == X86::AH || Reg == X86::AL)
00326       return true;
00327   }
00328 
00329   return false;
00330 }
00331 
00332 void
00333 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
00334                                             MachineBasicBlock::iterator MBBI,
00335                                             DebugLoc DL) const {
00336   MachineFunction &MF = *MBB.getParent();
00337   MachineFrameInfo *MFI = MF.getFrameInfo();
00338   MachineModuleInfo &MMI = MF.getMMI();
00339   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
00340   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
00341 
00342   // Add callee saved registers to move list.
00343   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
00344   if (CSI.empty()) return;
00345 
00346   // Calculate offsets.
00347   for (std::vector<CalleeSavedInfo>::const_iterator
00348          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
00349     int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
00350     unsigned Reg = I->getReg();
00351 
00352     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
00353     unsigned CFIIndex =
00354         MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
00355                                                         Offset));
00356     BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00357         .addCFIIndex(CFIIndex);
00358   }
00359 }
00360 
00361 /// usesTheStack - This function checks if any of the users of EFLAGS
00362 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
00363 /// to use the stack, and if we don't adjust the stack we clobber the first
00364 /// frame index.
00365 /// See X86InstrInfo::copyPhysReg.
00366 static bool usesTheStack(const MachineFunction &MF) {
00367   const MachineRegisterInfo &MRI = MF.getRegInfo();
00368 
00369   for (MachineRegisterInfo::reg_instr_iterator
00370        ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
00371        ri != re; ++ri)
00372     if (ri->isCopy())
00373       return true;
00374 
00375   return false;
00376 }
00377 
00378 void X86FrameLowering::getStackProbeFunction(const X86Subtarget &STI,
00379                                              unsigned &CallOp,
00380                                              const char *&Symbol) {
00381   CallOp = STI.is64Bit() ? X86::W64ALLOCA : X86::CALLpcrel32;
00382 
00383   if (STI.is64Bit()) {
00384     if (STI.isTargetCygMing()) {
00385       Symbol = "___chkstk_ms";
00386     } else {
00387       Symbol = "__chkstk";
00388     }
00389   } else if (STI.isTargetCygMing())
00390     Symbol = "_alloca";
00391   else
00392     Symbol = "_chkstk";
00393 }
00394 
00395 /// emitPrologue - Push callee-saved registers onto the stack, which
00396 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
00397 /// space for local variables. Also emit labels used by the exception handler to
00398 /// generate the exception handling frames.
00399 
00400 /*
00401   Here's a gist of what gets emitted:
00402 
00403   ; Establish frame pointer, if needed
00404   [if needs FP]
00405       push  %rbp
00406       .cfi_def_cfa_offset 16
00407       .cfi_offset %rbp, -16
00408       .seh_pushreg %rpb
00409       mov  %rsp, %rbp
00410       .cfi_def_cfa_register %rbp
00411 
00412   ; Spill general-purpose registers
00413   [for all callee-saved GPRs]
00414       pushq %<reg>
00415       [if not needs FP]
00416          .cfi_def_cfa_offset (offset from RETADDR)
00417       .seh_pushreg %<reg>
00418 
00419   ; If the required stack alignment > default stack alignment
00420   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
00421   ; of unknown size in the stack frame.
00422   [if stack needs re-alignment]
00423       and  $MASK, %rsp
00424 
00425   ; Allocate space for locals
00426   [if target is Windows and allocated space > 4096 bytes]
00427       ; Windows needs special care for allocations larger
00428       ; than one page.
00429       mov $NNN, %rax
00430       call ___chkstk_ms/___chkstk
00431       sub  %rax, %rsp
00432   [else]
00433       sub  $NNN, %rsp
00434 
00435   [if needs FP]
00436       .seh_stackalloc (size of XMM spill slots)
00437       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
00438   [else]
00439       .seh_stackalloc NNN
00440 
00441   ; Spill XMMs
00442   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
00443   ; they may get spilled on any platform, if the current function
00444   ; calls @llvm.eh.unwind.init
00445   [if needs FP]
00446       [for all callee-saved XMM registers]
00447           movaps  %<xmm reg>, -MMM(%rbp)
00448       [for all callee-saved XMM registers]
00449           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
00450               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
00451   [else]
00452       [for all callee-saved XMM registers]
00453           movaps  %<xmm reg>, KKK(%rsp)
00454       [for all callee-saved XMM registers]
00455           .seh_savexmm %<xmm reg>, KKK
00456 
00457   .seh_endprologue
00458 
00459   [if needs base pointer]
00460       mov  %rsp, %rbx
00461       [if needs to restore base pointer]
00462           mov %rsp, -MMM(%rbp)
00463 
00464   ; Emit CFI info
00465   [if needs FP]
00466       [for all callee-saved registers]
00467           .cfi_offset %<reg>, (offset from %rbp)
00468   [else]
00469        .cfi_def_cfa_offset (offset from RETADDR)
00470       [for all callee-saved registers]
00471           .cfi_offset %<reg>, (offset from %rsp)
00472 
00473   Notes:
00474   - .seh directives are emitted only for Windows 64 ABI
00475   - .cfi directives are emitted for all other ABIs
00476   - for 32-bit code, substitute %e?? registers for %r??
00477 */
00478 
00479 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
00480   MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
00481   MachineBasicBlock::iterator MBBI = MBB.begin();
00482   MachineFrameInfo *MFI = MF.getFrameInfo();
00483   const Function *Fn = MF.getFunction();
00484   const X86RegisterInfo *RegInfo =
00485       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
00486   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
00487   MachineModuleInfo &MMI = MF.getMMI();
00488   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
00489   uint64_t MaxAlign  = MFI->getMaxAlignment(); // Desired stack alignment.
00490   uint64_t StackSize = MFI->getStackSize();    // Number of bytes to allocate.
00491   bool HasFP = hasFP(MF);
00492   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
00493   bool Is64Bit = STI.is64Bit();
00494   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
00495   const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
00496   bool IsWin64 = STI.isTargetWin64();
00497   // Not necessarily synonymous with IsWin64.
00498   bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
00499   bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
00500   bool NeedsDwarfCFI =
00501       !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
00502   bool UseLEA = STI.useLeaForSP();
00503   unsigned StackAlign = getStackAlignment();
00504   unsigned SlotSize = RegInfo->getSlotSize();
00505   unsigned FramePtr = RegInfo->getFrameRegister(MF);
00506   const unsigned MachineFramePtr = STI.isTarget64BitILP32() ?
00507                  getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
00508   unsigned StackPtr = RegInfo->getStackRegister();
00509   unsigned BasePtr = RegInfo->getBaseRegister();
00510   DebugLoc DL;
00511 
00512   // If we're forcing a stack realignment we can't rely on just the frame
00513   // info, we need to know the ABI stack alignment as well in case we
00514   // have a call out.  Otherwise just make sure we have some alignment - we'll
00515   // go with the minimum SlotSize.
00516   if (ForceStackAlign) {
00517     if (MFI->hasCalls())
00518       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
00519     else if (MaxAlign < SlotSize)
00520       MaxAlign = SlotSize;
00521   }
00522 
00523   // Add RETADDR move area to callee saved frame size.
00524   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
00525   if (TailCallReturnAddrDelta < 0)
00526     X86FI->setCalleeSavedFrameSize(
00527       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
00528 
00529   bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
00530 
00531   // The default stack probe size is 4096 if the function has no stackprobesize
00532   // attribute.
00533   unsigned StackProbeSize = 4096;
00534   if (Fn->hasFnAttribute("stack-probe-size"))
00535     Fn->getFnAttribute("stack-probe-size")
00536         .getValueAsString()
00537         .getAsInteger(0, StackProbeSize);
00538 
00539   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
00540   // function, and use up to 128 bytes of stack space, don't have a frame
00541   // pointer, calls, or dynamic alloca then we do not need to adjust the
00542   // stack pointer (we fit in the Red Zone). We also check that we don't
00543   // push and pop from the stack.
00544   if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00545                                                    Attribute::NoRedZone) &&
00546       !RegInfo->needsStackRealignment(MF) &&
00547       !MFI->hasVarSizedObjects() &&                     // No dynamic alloca.
00548       !MFI->adjustsStack() &&                           // No calls.
00549       !IsWin64 &&                                       // Win64 has no Red Zone
00550       !usesTheStack(MF) &&                              // Don't push and pop.
00551       !MF.shouldSplitStack()) {                         // Regular stack
00552     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
00553     if (HasFP) MinSize += SlotSize;
00554     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
00555     MFI->setStackSize(StackSize);
00556   }
00557 
00558   // Insert stack pointer adjustment for later moving of return addr.  Only
00559   // applies to tail call optimized functions where the callee argument stack
00560   // size is bigger than the callers.
00561   if (TailCallReturnAddrDelta < 0) {
00562     MachineInstr *MI =
00563       BuildMI(MBB, MBBI, DL,
00564               TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
00565               StackPtr)
00566         .addReg(StackPtr)
00567         .addImm(-TailCallReturnAddrDelta)
00568         .setMIFlag(MachineInstr::FrameSetup);
00569     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
00570   }
00571 
00572   // Mapping for machine moves:
00573   //
00574   //   DST: VirtualFP AND
00575   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
00576   //        ELSE                        => DW_CFA_def_cfa
00577   //
00578   //   SRC: VirtualFP AND
00579   //        DST: Register               => DW_CFA_def_cfa_register
00580   //
00581   //   ELSE
00582   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
00583   //        REG < 64                    => DW_CFA_offset + Reg
00584   //        ELSE                        => DW_CFA_offset_extended
00585 
00586   uint64_t NumBytes = 0;
00587   int stackGrowth = -SlotSize;
00588 
00589   if (HasFP) {
00590     // Calculate required stack adjustment.
00591     uint64_t FrameSize = StackSize - SlotSize;
00592     // If required, include space for extra hidden slot for stashing base pointer.
00593     if (X86FI->getRestoreBasePointer())
00594       FrameSize += SlotSize;
00595     if (RegInfo->needsStackRealignment(MF)) {
00596       // Callee-saved registers are pushed on stack before the stack
00597       // is realigned.
00598       FrameSize -= X86FI->getCalleeSavedFrameSize();
00599       NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
00600     } else {
00601       NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
00602     }
00603 
00604     // Get the offset of the stack slot for the EBP register, which is
00605     // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
00606     // Update the frame offset adjustment.
00607     MFI->setOffsetAdjustment(-NumBytes);
00608 
00609     // Save EBP/RBP into the appropriate stack slot.
00610     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
00611       .addReg(MachineFramePtr, RegState::Kill)
00612       .setMIFlag(MachineInstr::FrameSetup);
00613 
00614     if (NeedsDwarfCFI) {
00615       // Mark the place where EBP/RBP was saved.
00616       // Define the current CFA rule to use the provided offset.
00617       assert(StackSize);
00618       unsigned CFIIndex = MMI.addFrameInst(
00619           MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
00620       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00621           .addCFIIndex(CFIIndex);
00622 
00623       // Change the rule for the FramePtr to be an "offset" rule.
00624       unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
00625       CFIIndex = MMI.addFrameInst(
00626           MCCFIInstruction::createOffset(nullptr,
00627                                          DwarfFramePtr, 2 * stackGrowth));
00628       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00629           .addCFIIndex(CFIIndex);
00630     }
00631 
00632     if (NeedsWinEH) {
00633       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
00634           .addImm(FramePtr)
00635           .setMIFlag(MachineInstr::FrameSetup);
00636     }
00637 
00638     // Update EBP with the new base value.
00639     BuildMI(MBB, MBBI, DL,
00640             TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), FramePtr)
00641         .addReg(StackPtr)
00642         .setMIFlag(MachineInstr::FrameSetup);
00643 
00644     if (NeedsDwarfCFI) {
00645       // Mark effective beginning of when frame pointer becomes valid.
00646       // Define the current CFA to use the EBP/RBP register.
00647       unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
00648       unsigned CFIIndex = MMI.addFrameInst(
00649           MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
00650       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00651           .addCFIIndex(CFIIndex);
00652     }
00653 
00654     // Mark the FramePtr as live-in in every block.
00655     for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
00656       I->addLiveIn(MachineFramePtr);
00657   } else {
00658     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
00659   }
00660 
00661   // Skip the callee-saved push instructions.
00662   bool PushedRegs = false;
00663   int StackOffset = 2 * stackGrowth;
00664 
00665   while (MBBI != MBB.end() &&
00666          (MBBI->getOpcode() == X86::PUSH32r ||
00667           MBBI->getOpcode() == X86::PUSH64r)) {
00668     PushedRegs = true;
00669     unsigned Reg = MBBI->getOperand(0).getReg();
00670     ++MBBI;
00671 
00672     if (!HasFP && NeedsDwarfCFI) {
00673       // Mark callee-saved push instruction.
00674       // Define the current CFA rule to use the provided offset.
00675       assert(StackSize);
00676       unsigned CFIIndex = MMI.addFrameInst(
00677           MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
00678       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00679           .addCFIIndex(CFIIndex);
00680       StackOffset += stackGrowth;
00681     }
00682 
00683     if (NeedsWinEH) {
00684       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
00685           MachineInstr::FrameSetup);
00686     }
00687   }
00688 
00689   // Realign stack after we pushed callee-saved registers (so that we'll be
00690   // able to calculate their offsets from the frame pointer).
00691   if (RegInfo->needsStackRealignment(MF)) {
00692     assert(HasFP && "There should be a frame pointer if stack is realigned.");
00693     uint64_t Val = -MaxAlign;
00694     MachineInstr *MI =
00695       BuildMI(MBB, MBBI, DL,
00696               TII.get(getANDriOpcode(Uses64BitFramePtr, Val)), StackPtr)
00697       .addReg(StackPtr)
00698       .addImm(Val)
00699       .setMIFlag(MachineInstr::FrameSetup);
00700 
00701     // The EFLAGS implicit def is dead.
00702     MI->getOperand(3).setIsDead();
00703   }
00704 
00705   // If there is an SUB32ri of ESP immediately before this instruction, merge
00706   // the two. This can be the case when tail call elimination is enabled and
00707   // the callee has more arguments then the caller.
00708   NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
00709 
00710   // If there is an ADD32ri or SUB32ri of ESP immediately after this
00711   // instruction, merge the two instructions.
00712   mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
00713 
00714   // Adjust stack pointer: ESP -= numbytes.
00715 
00716   // Windows and cygwin/mingw require a prologue helper routine when allocating
00717   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
00718   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
00719   // stack and adjust the stack pointer in one go.  The 64-bit version of
00720   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
00721   // responsible for adjusting the stack pointer.  Touching the stack at 4K
00722   // increments is necessary to ensure that the guard pages used by the OS
00723   // virtual memory manager are allocated in correct sequence.
00724   if (NumBytes >= StackProbeSize && UseStackProbe) {
00725     const char *StackProbeSymbol;
00726     unsigned CallOp;
00727 
00728     getStackProbeFunction(STI, CallOp, StackProbeSymbol);
00729 
00730     // Check whether EAX is livein for this function.
00731     bool isEAXAlive = isEAXLiveIn(MF);
00732 
00733     if (isEAXAlive) {
00734       // Sanity check that EAX is not livein for this function.
00735       // It should not be, so throw an assert.
00736       assert(!Is64Bit && "EAX is livein in x64 case!");
00737 
00738       // Save EAX
00739       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
00740         .addReg(X86::EAX, RegState::Kill)
00741         .setMIFlag(MachineInstr::FrameSetup);
00742     }
00743 
00744     if (Is64Bit) {
00745       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
00746       // Function prologue is responsible for adjusting the stack pointer.
00747       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
00748         .addImm(NumBytes)
00749         .setMIFlag(MachineInstr::FrameSetup);
00750     } else {
00751       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
00752       // We'll also use 4 already allocated bytes for EAX.
00753       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
00754         .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
00755         .setMIFlag(MachineInstr::FrameSetup);
00756     }
00757 
00758     BuildMI(MBB, MBBI, DL,
00759             TII.get(CallOp))
00760       .addExternalSymbol(StackProbeSymbol)
00761       .addReg(StackPtr,    RegState::Define | RegState::Implicit)
00762       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
00763       .setMIFlag(MachineInstr::FrameSetup);
00764 
00765     if (Is64Bit) {
00766       // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
00767       // themself. It also does not clobber %rax so we can reuse it when
00768       // adjusting %rsp.
00769       BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), StackPtr)
00770         .addReg(StackPtr)
00771         .addReg(X86::RAX)
00772         .setMIFlag(MachineInstr::FrameSetup);
00773     }
00774     if (isEAXAlive) {
00775       // Restore EAX
00776       MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
00777                                               X86::EAX),
00778                                       StackPtr, false, NumBytes - 4);
00779       MI->setFlag(MachineInstr::FrameSetup);
00780       MBB.insert(MBBI, MI);
00781     }
00782   } else if (NumBytes) {
00783     emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
00784                  UseLEA, TII, *RegInfo);
00785   }
00786 
00787   int SEHFrameOffset = 0;
00788   if (NeedsWinEH) {
00789     if (HasFP) {
00790       // We need to set frame base offset low enough such that all saved
00791       // register offsets would be positive relative to it, but we can't
00792       // just use NumBytes, because .seh_setframe offset must be <=240.
00793       // So we pretend to have only allocated enough space to spill the
00794       // non-volatile registers.
00795       // We don't care about the rest of stack allocation, because unwinder
00796       // will restore SP to (BP - SEHFrameOffset)
00797       for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
00798         int offset = MFI->getObjectOffset(Info.getFrameIdx());
00799         SEHFrameOffset = std::max(SEHFrameOffset, std::abs(offset));
00800       }
00801       SEHFrameOffset += SEHFrameOffset % 16; // ensure alignmant
00802 
00803       // This only needs to account for XMM spill slots, GPR slots
00804       // are covered by the .seh_pushreg's emitted above.
00805       unsigned Size = SEHFrameOffset - X86FI->getCalleeSavedFrameSize();
00806       if (Size) {
00807         BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
00808             .addImm(Size)
00809             .setMIFlag(MachineInstr::FrameSetup);
00810       }
00811 
00812       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
00813           .addImm(FramePtr)
00814           .addImm(SEHFrameOffset)
00815           .setMIFlag(MachineInstr::FrameSetup);
00816     } else {
00817       // SP will be the base register for restoring XMMs
00818       if (NumBytes) {
00819         BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
00820             .addImm(NumBytes)
00821             .setMIFlag(MachineInstr::FrameSetup);
00822       }
00823     }
00824   }
00825 
00826   // Skip the rest of register spilling code
00827   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
00828     ++MBBI;
00829 
00830   // Emit SEH info for non-GPRs
00831   if (NeedsWinEH) {
00832     for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
00833       unsigned Reg = Info.getReg();
00834       if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
00835         continue;
00836       assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
00837 
00838       int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
00839       Offset += SEHFrameOffset;
00840 
00841       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
00842           .addImm(Reg)
00843           .addImm(Offset)
00844           .setMIFlag(MachineInstr::FrameSetup);
00845     }
00846 
00847     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
00848         .setMIFlag(MachineInstr::FrameSetup);
00849   }
00850 
00851   // If we need a base pointer, set it up here. It's whatever the value
00852   // of the stack pointer is at this point. Any variable size objects
00853   // will be allocated after this, so we can still use the base pointer
00854   // to reference locals.
00855   if (RegInfo->hasBasePointer(MF)) {
00856     // Update the base pointer with the current stack pointer.
00857     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
00858     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
00859       .addReg(StackPtr)
00860       .setMIFlag(MachineInstr::FrameSetup);
00861     if (X86FI->getRestoreBasePointer()) {
00862       // Stash value of base pointer.  Saving RSP instead of EBP shortens dependence chain.
00863       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
00864       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
00865                    FramePtr, true, X86FI->getRestoreBasePointerOffset())
00866         .addReg(StackPtr)
00867         .setMIFlag(MachineInstr::FrameSetup);
00868     }
00869   }
00870 
00871   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
00872     // Mark end of stack pointer adjustment.
00873     if (!HasFP && NumBytes) {
00874       // Define the current CFA rule to use the provided offset.
00875       assert(StackSize);
00876       unsigned CFIIndex = MMI.addFrameInst(
00877           MCCFIInstruction::createDefCfaOffset(nullptr,
00878                                                -StackSize + stackGrowth));
00879 
00880       BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00881           .addCFIIndex(CFIIndex);
00882     }
00883 
00884     // Emit DWARF info specifying the offsets of the callee-saved registers.
00885     if (PushedRegs)
00886       emitCalleeSavedFrameMoves(MBB, MBBI, DL);
00887   }
00888 }
00889 
00890 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
00891                                     MachineBasicBlock &MBB) const {
00892   const MachineFrameInfo *MFI = MF.getFrameInfo();
00893   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
00894   const X86RegisterInfo *RegInfo =
00895       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
00896   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
00897   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
00898   assert(MBBI != MBB.end() && "Returning block has no instructions");
00899   unsigned RetOpcode = MBBI->getOpcode();
00900   DebugLoc DL = MBBI->getDebugLoc();
00901   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
00902   bool Is64Bit = STI.is64Bit();
00903   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
00904   const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
00905   const bool Is64BitILP32 = STI.isTarget64BitILP32();
00906   bool UseLEA = STI.useLeaForSP();
00907   unsigned StackAlign = getStackAlignment();
00908   unsigned SlotSize = RegInfo->getSlotSize();
00909   unsigned FramePtr = RegInfo->getFrameRegister(MF);
00910   unsigned MachineFramePtr = Is64BitILP32 ?
00911              getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
00912   unsigned StackPtr = RegInfo->getStackRegister();
00913 
00914   bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
00915   bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
00916 
00917   switch (RetOpcode) {
00918   default:
00919     llvm_unreachable("Can only insert epilog into returning blocks");
00920   case X86::RETQ:
00921   case X86::RETL:
00922   case X86::RETIL:
00923   case X86::RETIQ:
00924   case X86::TCRETURNdi:
00925   case X86::TCRETURNri:
00926   case X86::TCRETURNmi:
00927   case X86::TCRETURNdi64:
00928   case X86::TCRETURNri64:
00929   case X86::TCRETURNmi64:
00930   case X86::EH_RETURN:
00931   case X86::EH_RETURN64:
00932     break;  // These are ok
00933   }
00934 
00935   // Get the number of bytes to allocate from the FrameInfo.
00936   uint64_t StackSize = MFI->getStackSize();
00937   uint64_t MaxAlign  = MFI->getMaxAlignment();
00938   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
00939   uint64_t NumBytes = 0;
00940 
00941   // If we're forcing a stack realignment we can't rely on just the frame
00942   // info, we need to know the ABI stack alignment as well in case we
00943   // have a call out.  Otherwise just make sure we have some alignment - we'll
00944   // go with the minimum.
00945   if (ForceStackAlign) {
00946     if (MFI->hasCalls())
00947       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
00948     else
00949       MaxAlign = MaxAlign ? MaxAlign : 4;
00950   }
00951 
00952   if (hasFP(MF)) {
00953     // Calculate required stack adjustment.
00954     uint64_t FrameSize = StackSize - SlotSize;
00955     if (RegInfo->needsStackRealignment(MF)) {
00956       // Callee-saved registers were pushed on stack before the stack
00957       // was realigned.
00958       FrameSize -= CSSize;
00959       NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
00960     } else {
00961       NumBytes = FrameSize - CSSize;
00962     }
00963 
00964     // Pop EBP.
00965     BuildMI(MBB, MBBI, DL,
00966             TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
00967   } else {
00968     NumBytes = StackSize - CSSize;
00969   }
00970 
00971   // Skip the callee-saved pop instructions.
00972   while (MBBI != MBB.begin()) {
00973     MachineBasicBlock::iterator PI = std::prev(MBBI);
00974     unsigned Opc = PI->getOpcode();
00975 
00976     if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
00977         !PI->isTerminator())
00978       break;
00979 
00980     --MBBI;
00981   }
00982   MachineBasicBlock::iterator FirstCSPop = MBBI;
00983 
00984   DL = MBBI->getDebugLoc();
00985 
00986   // If there is an ADD32ri or SUB32ri of ESP immediately before this
00987   // instruction, merge the two instructions.
00988   if (NumBytes || MFI->hasVarSizedObjects())
00989     mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
00990 
00991   // If dynamic alloca is used, then reset esp to point to the last callee-saved
00992   // slot before popping them off! Same applies for the case, when stack was
00993   // realigned.
00994   if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
00995     if (RegInfo->needsStackRealignment(MF))
00996       MBBI = FirstCSPop;
00997     if (CSSize != 0) {
00998       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
00999       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
01000                    FramePtr, false, -CSSize);
01001       --MBBI;
01002     } else {
01003       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
01004       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
01005         .addReg(FramePtr);
01006       --MBBI;
01007     }
01008   } else if (NumBytes) {
01009     // Adjust stack pointer back: ESP += numbytes.
01010     emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr, UseLEA,
01011                  TII, *RegInfo);
01012     --MBBI;
01013   }
01014 
01015   // Windows unwinder will not invoke function's exception handler if IP is
01016   // either in prologue or in epilogue.  This behavior causes a problem when a
01017   // call immediately precedes an epilogue, because the return address points
01018   // into the epilogue.  To cope with that, we insert an epilogue marker here,
01019   // then replace it with a 'nop' if it ends up immediately after a CALL in the
01020   // final emitted code.
01021   if (NeedsWinEH)
01022     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
01023 
01024   // We're returning from function via eh_return.
01025   if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
01026     MBBI = MBB.getLastNonDebugInstr();
01027     MachineOperand &DestAddr  = MBBI->getOperand(0);
01028     assert(DestAddr.isReg() && "Offset should be in register!");
01029     BuildMI(MBB, MBBI, DL,
01030             TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
01031             StackPtr).addReg(DestAddr.getReg());
01032   } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
01033              RetOpcode == X86::TCRETURNmi ||
01034              RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
01035              RetOpcode == X86::TCRETURNmi64) {
01036     bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
01037     // Tail call return: adjust the stack pointer and jump to callee.
01038     MBBI = MBB.getLastNonDebugInstr();
01039     MachineOperand &JumpTarget = MBBI->getOperand(0);
01040     MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
01041     assert(StackAdjust.isImm() && "Expecting immediate value.");
01042 
01043     // Adjust stack pointer.
01044     int StackAdj = StackAdjust.getImm();
01045     int MaxTCDelta = X86FI->getTCReturnAddrDelta();
01046     int Offset = 0;
01047     assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
01048 
01049     // Incoporate the retaddr area.
01050     Offset = StackAdj-MaxTCDelta;
01051     assert(Offset >= 0 && "Offset should never be negative");
01052 
01053     if (Offset) {
01054       // Check for possible merge with preceding ADD instruction.
01055       Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
01056       emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
01057                    UseLEA, TII, *RegInfo);
01058     }
01059 
01060     // Jump to label or value in register.
01061     if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
01062       MachineInstrBuilder MIB =
01063         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
01064                                        ? X86::TAILJMPd : X86::TAILJMPd64));
01065       if (JumpTarget.isGlobal())
01066         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
01067                              JumpTarget.getTargetFlags());
01068       else {
01069         assert(JumpTarget.isSymbol());
01070         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
01071                               JumpTarget.getTargetFlags());
01072       }
01073     } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
01074       MachineInstrBuilder MIB =
01075         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
01076                                        ? X86::TAILJMPm : X86::TAILJMPm64));
01077       for (unsigned i = 0; i != 5; ++i)
01078         MIB.addOperand(MBBI->getOperand(i));
01079     } else if (RetOpcode == X86::TCRETURNri64) {
01080       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
01081         addReg(JumpTarget.getReg(), RegState::Kill);
01082     } else {
01083       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
01084         addReg(JumpTarget.getReg(), RegState::Kill);
01085     }
01086 
01087     MachineInstr *NewMI = std::prev(MBBI);
01088     NewMI->copyImplicitOps(MF, MBBI);
01089 
01090     // Delete the pseudo instruction TCRETURN.
01091     MBB.erase(MBBI);
01092   } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
01093               RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
01094              (X86FI->getTCReturnAddrDelta() < 0)) {
01095     // Add the return addr area delta back since we are not tail calling.
01096     int delta = -1*X86FI->getTCReturnAddrDelta();
01097     MBBI = MBB.getLastNonDebugInstr();
01098 
01099     // Check for possible merge with preceding ADD instruction.
01100     delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
01101     emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, Uses64BitFramePtr, UseLEA, TII,
01102                  *RegInfo);
01103   }
01104 }
01105 
01106 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
01107                                           int FI) const {
01108   const X86RegisterInfo *RegInfo =
01109       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
01110   const MachineFrameInfo *MFI = MF.getFrameInfo();
01111   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
01112   uint64_t StackSize = MFI->getStackSize();
01113 
01114   if (RegInfo->hasBasePointer(MF)) {
01115     assert (hasFP(MF) && "VLAs and dynamic stack realign, but no FP?!");
01116     if (FI < 0) {
01117       // Skip the saved EBP.
01118       return Offset + RegInfo->getSlotSize();
01119     } else {
01120       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
01121       return Offset + StackSize;
01122     }
01123   } else if (RegInfo->needsStackRealignment(MF)) {
01124     if (FI < 0) {
01125       // Skip the saved EBP.
01126       return Offset + RegInfo->getSlotSize();
01127     } else {
01128       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
01129       return Offset + StackSize;
01130     }
01131     // FIXME: Support tail calls
01132   } else {
01133     if (!hasFP(MF))
01134       return Offset + StackSize;
01135 
01136     // Skip the saved EBP.
01137     Offset += RegInfo->getSlotSize();
01138 
01139     // Skip the RETADDR move area
01140     const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
01141     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
01142     if (TailCallReturnAddrDelta < 0)
01143       Offset -= TailCallReturnAddrDelta;
01144   }
01145 
01146   return Offset;
01147 }
01148 
01149 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
01150                                              unsigned &FrameReg) const {
01151   const X86RegisterInfo *RegInfo =
01152       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
01153   // We can't calculate offset from frame pointer if the stack is realigned,
01154   // so enforce usage of stack/base pointer.  The base pointer is used when we
01155   // have dynamic allocas in addition to dynamic realignment.
01156   if (RegInfo->hasBasePointer(MF))
01157     FrameReg = RegInfo->getBaseRegister();
01158   else if (RegInfo->needsStackRealignment(MF))
01159     FrameReg = RegInfo->getStackRegister();
01160   else
01161     FrameReg = RegInfo->getFrameRegister(MF);
01162   return getFrameIndexOffset(MF, FI);
01163 }
01164 
01165 // Simplified from getFrameIndexOffset keeping only StackPointer cases
01166 int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
01167   const MachineFrameInfo *MFI = MF.getFrameInfo();
01168   // Does not include any dynamic realign.
01169   const uint64_t StackSize = MFI->getStackSize();
01170   {
01171 #ifndef NDEBUG
01172     const X86RegisterInfo *RegInfo =
01173       static_cast<const X86RegisterInfo*>(MF.getSubtarget().getRegisterInfo());
01174     // Note: LLVM arranges the stack as:
01175     // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
01176     //      > "Stack Slots" (<--SP)
01177     // We can always address StackSlots from RSP.  We can usually (unless
01178     // needsStackRealignment) address CSRs from RSP, but sometimes need to
01179     // address them from RBP.  FixedObjects can be placed anywhere in the stack
01180     // frame depending on their specific requirements (i.e. we can actually
01181     // refer to arguments to the function which are stored in the *callers*
01182     // frame).  As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
01183     // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
01184 
01185     assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
01186 
01187     // We don't handle tail calls, and shouldn't be seeing them
01188     // either.
01189     int TailCallReturnAddrDelta =
01190         MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
01191     assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
01192 #endif
01193   }
01194 
01195   // This is how the math works out:
01196   //
01197   //  %rsp grows (i.e. gets lower) left to right. Each box below is
01198   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
01199   //  get to.
01200   //
01201   //    ----------------------------------
01202   //    | BP | Obj0 | Obj1 | ... | ObjN |
01203   //    ----------------------------------
01204   //    ^    ^      ^                   ^
01205   //    A    B      C                   E
01206   //
01207   // A is the incoming stack pointer.
01208   // (B - A) is the local area offset (-8 for x86-64) [1]
01209   // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
01210   //
01211   // |(E - B)| is the StackSize (absolute value, positive).  For a
01212   // stack that grown down, this works out to be (B - E). [3]
01213   //
01214   // E is also the value of %rsp after stack has been set up, and we
01215   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
01216   // (C - E) == (C - A) - (B - A) + (B - E)
01217   //            { Using [1], [2] and [3] above }
01218   //         == getObjectOffset - LocalAreaOffset + StackSize
01219   //
01220 
01221   // Get the Offset from the StackPointer
01222   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
01223 
01224   return Offset + StackSize;
01225 }
01226 // Simplified from getFrameIndexReference keeping only StackPointer cases
01227 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF, int FI,
01228                                                   unsigned &FrameReg) const {
01229   const X86RegisterInfo *RegInfo =
01230     static_cast<const X86RegisterInfo*>(MF.getSubtarget().getRegisterInfo());
01231 
01232   assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
01233 
01234   FrameReg = RegInfo->getStackRegister();
01235   return getFrameIndexOffsetFromSP(MF, FI);
01236 }
01237 
01238 bool X86FrameLowering::assignCalleeSavedSpillSlots(
01239     MachineFunction &MF, const TargetRegisterInfo *TRI,
01240     std::vector<CalleeSavedInfo> &CSI) const {
01241   MachineFrameInfo *MFI = MF.getFrameInfo();
01242   const X86RegisterInfo *RegInfo =
01243       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
01244   unsigned SlotSize = RegInfo->getSlotSize();
01245   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
01246 
01247   unsigned CalleeSavedFrameSize = 0;
01248   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
01249 
01250   if (hasFP(MF)) {
01251     // emitPrologue always spills frame register the first thing.
01252     SpillSlotOffset -= SlotSize;
01253     MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
01254 
01255     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
01256     // the frame register, we can delete it from CSI list and not have to worry
01257     // about avoiding it later.
01258     unsigned FPReg = RegInfo->getFrameRegister(MF);
01259     for (unsigned i = 0; i < CSI.size(); ++i) {
01260       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
01261         CSI.erase(CSI.begin() + i);
01262         break;
01263       }
01264     }
01265   }
01266 
01267   // Assign slots for GPRs. It increases frame size.
01268   for (unsigned i = CSI.size(); i != 0; --i) {
01269     unsigned Reg = CSI[i - 1].getReg();
01270 
01271     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
01272       continue;
01273 
01274     SpillSlotOffset -= SlotSize;
01275     CalleeSavedFrameSize += SlotSize;
01276 
01277     int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
01278     CSI[i - 1].setFrameIdx(SlotIndex);
01279   }
01280 
01281   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
01282 
01283   // Assign slots for XMMs.
01284   for (unsigned i = CSI.size(); i != 0; --i) {
01285     unsigned Reg = CSI[i - 1].getReg();
01286     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
01287       continue;
01288 
01289     const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
01290     // ensure alignment
01291     SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
01292     // spill into slot
01293     SpillSlotOffset -= RC->getSize();
01294     int SlotIndex =
01295         MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
01296     CSI[i - 1].setFrameIdx(SlotIndex);
01297     MFI->ensureMaxAlignment(RC->getAlignment());
01298   }
01299 
01300   return true;
01301 }
01302 
01303 bool X86FrameLowering::spillCalleeSavedRegisters(
01304     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
01305     const std::vector<CalleeSavedInfo> &CSI,
01306     const TargetRegisterInfo *TRI) const {
01307   DebugLoc DL = MBB.findDebugLoc(MI);
01308 
01309   MachineFunction &MF = *MBB.getParent();
01310   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
01311   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
01312 
01313   // Push GPRs. It increases frame size.
01314   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
01315   for (unsigned i = CSI.size(); i != 0; --i) {
01316     unsigned Reg = CSI[i - 1].getReg();
01317 
01318     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
01319       continue;
01320     // Add the callee-saved register as live-in. It's killed at the spill.
01321     MBB.addLiveIn(Reg);
01322 
01323     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
01324       .setMIFlag(MachineInstr::FrameSetup);
01325   }
01326 
01327   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
01328   // It can be done by spilling XMMs to stack frame.
01329   for (unsigned i = CSI.size(); i != 0; --i) {
01330     unsigned Reg = CSI[i-1].getReg();
01331     if (X86::GR64RegClass.contains(Reg) ||
01332         X86::GR32RegClass.contains(Reg))
01333       continue;
01334     // Add the callee-saved register as live-in. It's killed at the spill.
01335     MBB.addLiveIn(Reg);
01336     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01337 
01338     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
01339                             TRI);
01340     --MI;
01341     MI->setFlag(MachineInstr::FrameSetup);
01342     ++MI;
01343   }
01344 
01345   return true;
01346 }
01347 
01348 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
01349                                                MachineBasicBlock::iterator MI,
01350                                         const std::vector<CalleeSavedInfo> &CSI,
01351                                           const TargetRegisterInfo *TRI) const {
01352   if (CSI.empty())
01353     return false;
01354 
01355   DebugLoc DL = MBB.findDebugLoc(MI);
01356 
01357   MachineFunction &MF = *MBB.getParent();
01358   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
01359   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
01360 
01361   // Reload XMMs from stack frame.
01362   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01363     unsigned Reg = CSI[i].getReg();
01364     if (X86::GR64RegClass.contains(Reg) ||
01365         X86::GR32RegClass.contains(Reg))
01366       continue;
01367 
01368     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01369     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
01370   }
01371 
01372   // POP GPRs.
01373   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
01374   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01375     unsigned Reg = CSI[i].getReg();
01376     if (!X86::GR64RegClass.contains(Reg) &&
01377         !X86::GR32RegClass.contains(Reg))
01378       continue;
01379 
01380     BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
01381   }
01382   return true;
01383 }
01384 
01385 void
01386 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
01387                                                        RegScavenger *RS) const {
01388   MachineFrameInfo *MFI = MF.getFrameInfo();
01389   const X86RegisterInfo *RegInfo =
01390       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
01391   unsigned SlotSize = RegInfo->getSlotSize();
01392 
01393   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
01394   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
01395 
01396   if (TailCallReturnAddrDelta < 0) {
01397     // create RETURNADDR area
01398     //   arg
01399     //   arg
01400     //   RETADDR
01401     //   { ...
01402     //     RETADDR area
01403     //     ...
01404     //   }
01405     //   [EBP]
01406     MFI->CreateFixedObject(-TailCallReturnAddrDelta,
01407                            TailCallReturnAddrDelta - SlotSize, true);
01408   }
01409 
01410   // Spill the BasePtr if it's used.
01411   if (RegInfo->hasBasePointer(MF))
01412     MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
01413 }
01414 
01415 static bool
01416 HasNestArgument(const MachineFunction *MF) {
01417   const Function *F = MF->getFunction();
01418   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
01419        I != E; I++) {
01420     if (I->hasNestAttr())
01421       return true;
01422   }
01423   return false;
01424 }
01425 
01426 /// GetScratchRegister - Get a temp register for performing work in the
01427 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
01428 /// and the properties of the function either one or two registers will be
01429 /// needed. Set primary to true for the first register, false for the second.
01430 static unsigned
01431 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
01432   CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
01433 
01434   // Erlang stuff.
01435   if (CallingConvention == CallingConv::HiPE) {
01436     if (Is64Bit)
01437       return Primary ? X86::R14 : X86::R13;
01438     else
01439       return Primary ? X86::EBX : X86::EDI;
01440   }
01441 
01442   if (Is64Bit) {
01443     if (IsLP64)
01444       return Primary ? X86::R11 : X86::R12;
01445     else
01446       return Primary ? X86::R11D : X86::R12D;
01447   }
01448 
01449   bool IsNested = HasNestArgument(&MF);
01450 
01451   if (CallingConvention == CallingConv::X86_FastCall ||
01452       CallingConvention == CallingConv::Fast) {
01453     if (IsNested)
01454       report_fatal_error("Segmented stacks does not support fastcall with "
01455                          "nested function.");
01456     return Primary ? X86::EAX : X86::ECX;
01457   }
01458   if (IsNested)
01459     return Primary ? X86::EDX : X86::EAX;
01460   return Primary ? X86::ECX : X86::EAX;
01461 }
01462 
01463 // The stack limit in the TCB is set to this many bytes above the actual stack
01464 // limit.
01465 static const uint64_t kSplitStackAvailable = 256;
01466 
01467 void
01468 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
01469   MachineBasicBlock &prologueMBB = MF.front();
01470   MachineFrameInfo *MFI = MF.getFrameInfo();
01471   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
01472   uint64_t StackSize;
01473   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
01474   bool Is64Bit = STI.is64Bit();
01475   const bool IsLP64 = STI.isTarget64BitLP64();
01476   unsigned TlsReg, TlsOffset;
01477   DebugLoc DL;
01478 
01479   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
01480   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
01481          "Scratch register is live-in");
01482 
01483   if (MF.getFunction()->isVarArg())
01484     report_fatal_error("Segmented stacks do not support vararg functions.");
01485   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
01486       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
01487       !STI.isTargetDragonFly())
01488     report_fatal_error("Segmented stacks not supported on this platform.");
01489 
01490   // Eventually StackSize will be calculated by a link-time pass; which will
01491   // also decide whether checking code needs to be injected into this particular
01492   // prologue.
01493   StackSize = MFI->getStackSize();
01494 
01495   // Do not generate a prologue for functions with a stack of size zero
01496   if (StackSize == 0)
01497     return;
01498 
01499   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
01500   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
01501   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
01502   bool IsNested = false;
01503 
01504   // We need to know if the function has a nest argument only in 64 bit mode.
01505   if (Is64Bit)
01506     IsNested = HasNestArgument(&MF);
01507 
01508   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
01509   // allocMBB needs to be last (terminating) instruction.
01510 
01511   for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
01512          e = prologueMBB.livein_end(); i != e; i++) {
01513     allocMBB->addLiveIn(*i);
01514     checkMBB->addLiveIn(*i);
01515   }
01516 
01517   if (IsNested)
01518     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
01519 
01520   MF.push_front(allocMBB);
01521   MF.push_front(checkMBB);
01522 
01523   // When the frame size is less than 256 we just compare the stack
01524   // boundary directly to the value of the stack pointer, per gcc.
01525   bool CompareStackPointer = StackSize < kSplitStackAvailable;
01526 
01527   // Read the limit off the current stacklet off the stack_guard location.
01528   if (Is64Bit) {
01529     if (STI.isTargetLinux()) {
01530       TlsReg = X86::FS;
01531       TlsOffset = IsLP64 ? 0x70 : 0x40;
01532     } else if (STI.isTargetDarwin()) {
01533       TlsReg = X86::GS;
01534       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
01535     } else if (STI.isTargetWin64()) {
01536       TlsReg = X86::GS;
01537       TlsOffset = 0x28; // pvArbitrary, reserved for application use
01538     } else if (STI.isTargetFreeBSD()) {
01539       TlsReg = X86::FS;
01540       TlsOffset = 0x18;
01541     } else if (STI.isTargetDragonFly()) {
01542       TlsReg = X86::FS;
01543       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
01544     } else {
01545       report_fatal_error("Segmented stacks not supported on this platform.");
01546     }
01547 
01548     if (CompareStackPointer)
01549       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
01550     else
01551       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
01552         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
01553 
01554     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
01555       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
01556   } else {
01557     if (STI.isTargetLinux()) {
01558       TlsReg = X86::GS;
01559       TlsOffset = 0x30;
01560     } else if (STI.isTargetDarwin()) {
01561       TlsReg = X86::GS;
01562       TlsOffset = 0x48 + 90*4;
01563     } else if (STI.isTargetWin32()) {
01564       TlsReg = X86::FS;
01565       TlsOffset = 0x14; // pvArbitrary, reserved for application use
01566     } else if (STI.isTargetDragonFly()) {
01567       TlsReg = X86::FS;
01568       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
01569     } else if (STI.isTargetFreeBSD()) {
01570       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
01571     } else {
01572       report_fatal_error("Segmented stacks not supported on this platform.");
01573     }
01574 
01575     if (CompareStackPointer)
01576       ScratchReg = X86::ESP;
01577     else
01578       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
01579         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
01580 
01581     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
01582         STI.isTargetDragonFly()) {
01583       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
01584         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
01585     } else if (STI.isTargetDarwin()) {
01586 
01587       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
01588       unsigned ScratchReg2;
01589       bool SaveScratch2;
01590       if (CompareStackPointer) {
01591         // The primary scratch register is available for holding the TLS offset.
01592         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
01593         SaveScratch2 = false;
01594       } else {
01595         // Need to use a second register to hold the TLS offset
01596         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
01597 
01598         // Unfortunately, with fastcc the second scratch register may hold an
01599         // argument.
01600         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
01601       }
01602 
01603       // If Scratch2 is live-in then it needs to be saved.
01604       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
01605              "Scratch register is live-in and not saved");
01606 
01607       if (SaveScratch2)
01608         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
01609           .addReg(ScratchReg2, RegState::Kill);
01610 
01611       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
01612         .addImm(TlsOffset);
01613       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
01614         .addReg(ScratchReg)
01615         .addReg(ScratchReg2).addImm(1).addReg(0)
01616         .addImm(0)
01617         .addReg(TlsReg);
01618 
01619       if (SaveScratch2)
01620         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
01621     }
01622   }
01623 
01624   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
01625   // It jumps to normal execution of the function body.
01626   BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&prologueMBB);
01627 
01628   // On 32 bit we first push the arguments size and then the frame size. On 64
01629   // bit, we pass the stack frame size in r10 and the argument size in r11.
01630   if (Is64Bit) {
01631     // Functions with nested arguments use R10, so it needs to be saved across
01632     // the call to _morestack
01633 
01634     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
01635     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
01636     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
01637     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
01638     const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
01639 
01640     if (IsNested)
01641       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
01642 
01643     BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
01644       .addImm(StackSize);
01645     BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
01646       .addImm(X86FI->getArgumentStackSize());
01647     MF.getRegInfo().setPhysRegUsed(Reg10);
01648     MF.getRegInfo().setPhysRegUsed(Reg11);
01649   } else {
01650     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
01651       .addImm(X86FI->getArgumentStackSize());
01652     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
01653       .addImm(StackSize);
01654   }
01655 
01656   // __morestack is in libgcc
01657   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
01658     // Under the large code model, we cannot assume that __morestack lives
01659     // within 2^31 bytes of the call site, so we cannot use pc-relative
01660     // addressing. We cannot perform the call via a temporary register,
01661     // as the rax register may be used to store the static chain, and all
01662     // other suitable registers may be either callee-save or used for
01663     // parameter passing. We cannot use the stack at this point either
01664     // because __morestack manipulates the stack directly.
01665     //
01666     // To avoid these issues, perform an indirect call via a read-only memory
01667     // location containing the address.
01668     //
01669     // This solution is not perfect, as it assumes that the .rodata section
01670     // is laid out within 2^31 bytes of each function body, but this seems
01671     // to be sufficient for JIT.
01672     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
01673         .addReg(X86::RIP)
01674         .addImm(0)
01675         .addReg(0)
01676         .addExternalSymbol("__morestack_addr")
01677         .addReg(0);
01678     MF.getMMI().setUsesMorestackAddr(true);
01679   } else {
01680     if (Is64Bit)
01681       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
01682         .addExternalSymbol("__morestack");
01683     else
01684       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
01685         .addExternalSymbol("__morestack");
01686   }
01687 
01688   if (IsNested)
01689     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
01690   else
01691     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
01692 
01693   allocMBB->addSuccessor(&prologueMBB);
01694 
01695   checkMBB->addSuccessor(allocMBB);
01696   checkMBB->addSuccessor(&prologueMBB);
01697 
01698 #ifdef XDEBUG
01699   MF.verify();
01700 #endif
01701 }
01702 
01703 /// Erlang programs may need a special prologue to handle the stack size they
01704 /// might need at runtime. That is because Erlang/OTP does not implement a C
01705 /// stack but uses a custom implementation of hybrid stack/heap architecture.
01706 /// (for more information see Eric Stenman's Ph.D. thesis:
01707 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
01708 ///
01709 /// CheckStack:
01710 ///       temp0 = sp - MaxStack
01711 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
01712 /// OldStart:
01713 ///       ...
01714 /// IncStack:
01715 ///       call inc_stack   # doubles the stack space
01716 ///       temp0 = sp - MaxStack
01717 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
01718 void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
01719   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
01720   MachineFrameInfo *MFI = MF.getFrameInfo();
01721   const unsigned SlotSize =
01722       static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo())
01723           ->getSlotSize();
01724   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
01725   const bool Is64Bit = STI.is64Bit();
01726   const bool IsLP64 = STI.isTarget64BitLP64();
01727   DebugLoc DL;
01728   // HiPE-specific values
01729   const unsigned HipeLeafWords = 24;
01730   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
01731   const unsigned Guaranteed = HipeLeafWords * SlotSize;
01732   unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
01733                             MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
01734   unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
01735 
01736   assert(STI.isTargetLinux() &&
01737          "HiPE prologue is only supported on Linux operating systems.");
01738 
01739   // Compute the largest caller's frame that is needed to fit the callees'
01740   // frames. This 'MaxStack' is computed from:
01741   //
01742   // a) the fixed frame size, which is the space needed for all spilled temps,
01743   // b) outgoing on-stack parameter areas, and
01744   // c) the minimum stack space this function needs to make available for the
01745   //    functions it calls (a tunable ABI property).
01746   if (MFI->hasCalls()) {
01747     unsigned MoreStackForCalls = 0;
01748 
01749     for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
01750          MBBI != MBBE; ++MBBI)
01751       for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
01752            MI != ME; ++MI) {
01753         if (!MI->isCall())
01754           continue;
01755 
01756         // Get callee operand.
01757         const MachineOperand &MO = MI->getOperand(0);
01758 
01759         // Only take account of global function calls (no closures etc.).
01760         if (!MO.isGlobal())
01761           continue;
01762 
01763         const Function *F = dyn_cast<Function>(MO.getGlobal());
01764         if (!F)
01765           continue;
01766 
01767         // Do not update 'MaxStack' for primitive and built-in functions
01768         // (encoded with names either starting with "erlang."/"bif_" or not
01769         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
01770         // "_", such as the BIF "suspend_0") as they are executed on another
01771         // stack.
01772         if (F->getName().find("erlang.") != StringRef::npos ||
01773             F->getName().find("bif_") != StringRef::npos ||
01774             F->getName().find_first_of("._") == StringRef::npos)
01775           continue;
01776 
01777         unsigned CalleeStkArity =
01778           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
01779         if (HipeLeafWords - 1 > CalleeStkArity)
01780           MoreStackForCalls = std::max(MoreStackForCalls,
01781                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
01782       }
01783     MaxStack += MoreStackForCalls;
01784   }
01785 
01786   // If the stack frame needed is larger than the guaranteed then runtime checks
01787   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
01788   if (MaxStack > Guaranteed) {
01789     MachineBasicBlock &prologueMBB = MF.front();
01790     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
01791     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
01792 
01793     for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
01794            E = prologueMBB.livein_end(); I != E; I++) {
01795       stackCheckMBB->addLiveIn(*I);
01796       incStackMBB->addLiveIn(*I);
01797     }
01798 
01799     MF.push_front(incStackMBB);
01800     MF.push_front(stackCheckMBB);
01801 
01802     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
01803     unsigned LEAop, CMPop, CALLop;
01804     if (Is64Bit) {
01805       SPReg = X86::RSP;
01806       PReg  = X86::RBP;
01807       LEAop = X86::LEA64r;
01808       CMPop = X86::CMP64rm;
01809       CALLop = X86::CALL64pcrel32;
01810       SPLimitOffset = 0x90;
01811     } else {
01812       SPReg = X86::ESP;
01813       PReg  = X86::EBP;
01814       LEAop = X86::LEA32r;
01815       CMPop = X86::CMP32rm;
01816       CALLop = X86::CALLpcrel32;
01817       SPLimitOffset = 0x4c;
01818     }
01819 
01820     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
01821     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
01822            "HiPE prologue scratch register is live-in");
01823 
01824     // Create new MBB for StackCheck:
01825     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
01826                  SPReg, false, -MaxStack);
01827     // SPLimitOffset is in a fixed heap location (pointed by BP).
01828     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
01829                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
01830     BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&prologueMBB);
01831 
01832     // Create new MBB for IncStack:
01833     BuildMI(incStackMBB, DL, TII.get(CALLop)).
01834       addExternalSymbol("inc_stack_0");
01835     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
01836                  SPReg, false, -MaxStack);
01837     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
01838                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
01839     BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
01840 
01841     stackCheckMBB->addSuccessor(&prologueMBB, 99);
01842     stackCheckMBB->addSuccessor(incStackMBB, 1);
01843     incStackMBB->addSuccessor(&prologueMBB, 99);
01844     incStackMBB->addSuccessor(incStackMBB, 1);
01845   }
01846 #ifdef XDEBUG
01847   MF.verify();
01848 #endif
01849 }
01850 
01851 bool X86FrameLowering::
01852 convertArgMovsToPushes(MachineFunction &MF, MachineBasicBlock &MBB,
01853                        MachineBasicBlock::iterator I, uint64_t Amount) const {
01854   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
01855   const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
01856     MF.getSubtarget().getRegisterInfo());
01857   unsigned StackPtr = RegInfo.getStackRegister();
01858 
01859   // Scan the call setup sequence for the pattern we're looking for.
01860   // We only handle a simple case now - a sequence of MOV32mi or MOV32mr
01861   // instructions, that push a sequence of 32-bit values onto the stack, with
01862   // no gaps.  
01863   std::map<int64_t, MachineBasicBlock::iterator> MovMap;
01864   do {
01865     int Opcode = I->getOpcode();
01866     if (Opcode != X86::MOV32mi && Opcode != X86::MOV32mr)
01867       break;
01868  
01869     // We only want movs of the form:
01870     // movl imm/r32, k(%ecx)
01871     // If we run into something else, bail
01872     // Note that AddrBaseReg may, counterintuitively, not be a register...
01873     if (!I->getOperand(X86::AddrBaseReg).isReg() || 
01874         (I->getOperand(X86::AddrBaseReg).getReg() != StackPtr) ||
01875         !I->getOperand(X86::AddrScaleAmt).isImm() ||
01876         (I->getOperand(X86::AddrScaleAmt).getImm() != 1) ||
01877         (I->getOperand(X86::AddrIndexReg).getReg() != X86::NoRegister) ||
01878         (I->getOperand(X86::AddrSegmentReg).getReg() != X86::NoRegister) ||
01879         !I->getOperand(X86::AddrDisp).isImm())
01880       return false;
01881 
01882     int64_t StackDisp = I->getOperand(X86::AddrDisp).getImm();
01883     
01884     // We don't want to consider the unaligned case.
01885     if (StackDisp % 4)
01886       return false;
01887 
01888     // If the same stack slot is being filled twice, something's fishy.
01889     if (!MovMap.insert(std::pair<int64_t, MachineInstr*>(StackDisp, I)).second)
01890       return false;
01891 
01892     ++I;
01893   } while (I != MBB.end());
01894 
01895   // We now expect the end of the sequence - a call and a stack adjust.
01896   if (I == MBB.end())
01897     return false;
01898   if (!I->isCall())
01899     return false;
01900   MachineBasicBlock::iterator Call = I;
01901   if ((++I)->getOpcode() != TII.getCallFrameDestroyOpcode())
01902     return false;
01903 
01904   // Now, go through the map, and see that we don't have any gaps,
01905   // but only a series of 32-bit MOVs.
01906   // Since std::map provides ordered iteration, the original order
01907   // of the MOVs doesn't matter.
01908   int64_t ExpectedDist = 0;
01909   for (auto MMI = MovMap.begin(), MME = MovMap.end(); MMI != MME; 
01910        ++MMI, ExpectedDist += 4)
01911     if (MMI->first != ExpectedDist)
01912       return false;
01913 
01914   // Ok, everything looks fine. Do the transformation.
01915   DebugLoc DL = I->getDebugLoc();
01916 
01917   // It's possible the original stack adjustment amount was larger than
01918   // that done by the pushes. If so, we still need a SUB.
01919   Amount -= ExpectedDist;
01920   if (Amount) {
01921     MachineInstr* Sub = BuildMI(MBB, Call, DL,
01922                           TII.get(getSUBriOpcode(false, Amount)), StackPtr)
01923                   .addReg(StackPtr).addImm(Amount);
01924     Sub->getOperand(3).setIsDead();
01925   }
01926 
01927   // Now, iterate through the map in reverse order, and replace the movs
01928   // with pushes. MOVmi/MOVmr doesn't have any defs, so need to replace uses.
01929   for (auto MMI = MovMap.rbegin(), MME = MovMap.rend(); MMI != MME; ++MMI) {
01930     MachineBasicBlock::iterator MOV = MMI->second;
01931     MachineOperand PushOp = MOV->getOperand(X86::AddrNumOperands);
01932 
01933     // Replace MOVmr with PUSH32r, and MOVmi with PUSHi of appropriate size
01934     int PushOpcode = X86::PUSH32r;
01935     if (MOV->getOpcode() == X86::MOV32mi)
01936       PushOpcode = getPUSHiOpcode(false, PushOp);
01937 
01938     BuildMI(MBB, Call, DL, TII.get(PushOpcode)).addOperand(PushOp);
01939     MBB.erase(MOV);
01940   }
01941 
01942   return true;
01943 }
01944 
01945 void X86FrameLowering::
01946 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
01947                               MachineBasicBlock::iterator I) const {
01948   const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
01949   const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
01950                                        MF.getSubtarget().getRegisterInfo());
01951   unsigned StackPtr = RegInfo.getStackRegister();
01952   bool reserveCallFrame = hasReservedCallFrame(MF);
01953   int Opcode = I->getOpcode();
01954   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
01955   const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
01956   bool IsLP64 = STI.isTarget64BitLP64();
01957   DebugLoc DL = I->getDebugLoc();
01958   uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
01959   uint64_t CalleeAmt = isDestroy ? I->getOperand(1).getImm() : 0;
01960   I = MBB.erase(I);
01961 
01962   if (!reserveCallFrame) {
01963     // If the stack pointer can be changed after prologue, turn the
01964     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
01965     // adjcallstackdown instruction into 'add ESP, <amt>'
01966     if (Amount == 0)
01967       return;
01968 
01969     // We need to keep the stack aligned properly.  To do this, we round the
01970     // amount of space needed for the outgoing arguments up to the next
01971     // alignment boundary.
01972     unsigned StackAlign = MF.getTarget()
01973                               .getSubtargetImpl()
01974                               ->getFrameLowering()
01975                               ->getStackAlignment();
01976     Amount = (Amount + StackAlign - 1) / StackAlign * StackAlign;
01977 
01978     MachineInstr *New = nullptr;
01979     if (Opcode == TII.getCallFrameSetupOpcode()) {
01980       // Try to convert movs to the stack into pushes.
01981       // We currently only look for a pattern that appears in 32-bit
01982       // calling conventions.
01983       if (!IsLP64 && convertArgMovsToPushes(MF, MBB, I, Amount))
01984         return;
01985 
01986       New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)),
01987                     StackPtr)
01988         .addReg(StackPtr)
01989         .addImm(Amount);
01990     } else {
01991       assert(Opcode == TII.getCallFrameDestroyOpcode());
01992 
01993       // Factor out the amount the callee already popped.
01994       Amount -= CalleeAmt;
01995 
01996       if (Amount) {
01997         unsigned Opc = getADDriOpcode(IsLP64, Amount);
01998         New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
01999           .addReg(StackPtr).addImm(Amount);
02000       }
02001     }
02002 
02003     if (New) {
02004       // The EFLAGS implicit def is dead.
02005       New->getOperand(3).setIsDead();
02006 
02007       // Replace the pseudo instruction with a new instruction.
02008       MBB.insert(I, New);
02009     }
02010 
02011     return;
02012   }
02013 
02014   if (Opcode == TII.getCallFrameDestroyOpcode() && CalleeAmt) {
02015     // If we are performing frame pointer elimination and if the callee pops
02016     // something off the stack pointer, add it back.  We do this until we have
02017     // more advanced stack pointer tracking ability.
02018     unsigned Opc = getSUBriOpcode(IsLP64, CalleeAmt);
02019     MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
02020       .addReg(StackPtr).addImm(CalleeAmt);
02021 
02022     // The EFLAGS implicit def is dead.
02023     New->getOperand(3).setIsDead();
02024 
02025     // We are not tracking the stack pointer adjustment by the callee, so make
02026     // sure we restore the stack pointer immediately after the call, there may
02027     // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
02028     MachineBasicBlock::iterator B = MBB.begin();
02029     while (I != B && !std::prev(I)->isCall())
02030       --I;
02031     MBB.insert(I, New);
02032   }
02033 }
02034