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