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/Analysis/EHPersonalities.h"
00022 #include "llvm/CodeGen/MachineFrameInfo.h"
00023 #include "llvm/CodeGen/MachineFunction.h"
00024 #include "llvm/CodeGen/MachineInstrBuilder.h"
00025 #include "llvm/CodeGen/MachineModuleInfo.h"
00026 #include "llvm/CodeGen/MachineRegisterInfo.h"
00027 #include "llvm/CodeGen/WinEHFuncInfo.h"
00028 #include "llvm/IR/DataLayout.h"
00029 #include "llvm/IR/Function.h"
00030 #include "llvm/MC/MCAsmInfo.h"
00031 #include "llvm/MC/MCSymbol.h"
00032 #include "llvm/Target/TargetOptions.h"
00033 #include "llvm/Support/Debug.h"
00034 #include <cstdlib>
00035 
00036 using namespace llvm;
00037 
00038 X86FrameLowering::X86FrameLowering(const X86Subtarget &STI,
00039                                    unsigned StackAlignOverride)
00040     : TargetFrameLowering(StackGrowsDown, StackAlignOverride,
00041                           STI.is64Bit() ? -8 : -4),
00042       STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {
00043   // Cache a bunch of frame-related predicates for this subtarget.
00044   SlotSize = TRI->getSlotSize();
00045   Is64Bit = STI.is64Bit();
00046   IsLP64 = STI.isTarget64BitLP64();
00047   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
00048   Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
00049   StackPtr = TRI->getStackRegister();
00050 }
00051 
00052 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
00053   return !MF.getFrameInfo()->hasVarSizedObjects() &&
00054          !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
00055 }
00056 
00057 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
00058 /// call frame pseudos can be simplified.  Having a FP, as in the default
00059 /// implementation, is not sufficient here since we can't always use it.
00060 /// Use a more nuanced condition.
00061 bool
00062 X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
00063   return hasReservedCallFrame(MF) ||
00064          (hasFP(MF) && !TRI->needsStackRealignment(MF)) ||
00065          TRI->hasBasePointer(MF);
00066 }
00067 
00068 // needsFrameIndexResolution - Do we need to perform FI resolution for
00069 // this function. Normally, this is required only when the function
00070 // has any stack objects. However, FI resolution actually has another job,
00071 // not apparent from the title - it resolves callframesetup/destroy 
00072 // that were not simplified earlier.
00073 // So, this is required for x86 functions that have push sequences even
00074 // when there are no stack objects.
00075 bool
00076 X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
00077   return MF.getFrameInfo()->hasStackObjects() ||
00078          MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
00079 }
00080 
00081 /// hasFP - Return true if the specified function should have a dedicated frame
00082 /// pointer register.  This is true if the function has variable sized allocas
00083 /// or if frame pointer elimination is disabled.
00084 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
00085   const MachineFrameInfo *MFI = MF.getFrameInfo();
00086   const MachineModuleInfo &MMI = MF.getMMI();
00087 
00088   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
00089           TRI->needsStackRealignment(MF) ||
00090           MFI->hasVarSizedObjects() ||
00091           MFI->isFrameAddressTaken() || MFI->hasOpaqueSPAdjustment() ||
00092           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
00093           MMI.callsUnwindInit() || MMI.hasEHFunclets() || MMI.callsEHReturn() ||
00094           MFI->hasStackMap() || MFI->hasPatchPoint() ||
00095           MFI->hasCopyImplyingStackAdjustment());
00096 }
00097 
00098 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
00099   if (IsLP64) {
00100     if (isInt<8>(Imm))
00101       return X86::SUB64ri8;
00102     return X86::SUB64ri32;
00103   } else {
00104     if (isInt<8>(Imm))
00105       return X86::SUB32ri8;
00106     return X86::SUB32ri;
00107   }
00108 }
00109 
00110 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
00111   if (IsLP64) {
00112     if (isInt<8>(Imm))
00113       return X86::ADD64ri8;
00114     return X86::ADD64ri32;
00115   } else {
00116     if (isInt<8>(Imm))
00117       return X86::ADD32ri8;
00118     return X86::ADD32ri;
00119   }
00120 }
00121 
00122 static unsigned getSUBrrOpcode(unsigned isLP64) {
00123   return isLP64 ? X86::SUB64rr : X86::SUB32rr;
00124 }
00125 
00126 static unsigned getADDrrOpcode(unsigned isLP64) {
00127   return isLP64 ? X86::ADD64rr : X86::ADD32rr;
00128 }
00129 
00130 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
00131   if (IsLP64) {
00132     if (isInt<8>(Imm))
00133       return X86::AND64ri8;
00134     return X86::AND64ri32;
00135   }
00136   if (isInt<8>(Imm))
00137     return X86::AND32ri8;
00138   return X86::AND32ri;
00139 }
00140 
00141 static unsigned getLEArOpcode(unsigned IsLP64) {
00142   return IsLP64 ? X86::LEA64r : X86::LEA32r;
00143 }
00144 
00145 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
00146 /// when it reaches the "return" instruction. We can then pop a stack object
00147 /// to this register without worry about clobbering it.
00148 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
00149                                        MachineBasicBlock::iterator &MBBI,
00150                                        const X86RegisterInfo *TRI,
00151                                        bool Is64Bit) {
00152   const MachineFunction *MF = MBB.getParent();
00153   const Function *F = MF->getFunction();
00154   if (!F || MF->getMMI().callsEHReturn())
00155     return 0;
00156 
00157   const TargetRegisterClass &AvailableRegs = *TRI->getGPRsForTailCall(*MF);
00158 
00159   unsigned Opc = MBBI->getOpcode();
00160   switch (Opc) {
00161   default: return 0;
00162   case X86::RETL:
00163   case X86::RETQ:
00164   case X86::RETIL:
00165   case X86::RETIQ:
00166   case X86::TCRETURNdi:
00167   case X86::TCRETURNri:
00168   case X86::TCRETURNmi:
00169   case X86::TCRETURNdi64:
00170   case X86::TCRETURNri64:
00171   case X86::TCRETURNmi64:
00172   case X86::EH_RETURN:
00173   case X86::EH_RETURN64: {
00174     SmallSet<uint16_t, 8> Uses;
00175     for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
00176       MachineOperand &MO = MBBI->getOperand(i);
00177       if (!MO.isReg() || MO.isDef())
00178         continue;
00179       unsigned Reg = MO.getReg();
00180       if (!Reg)
00181         continue;
00182       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
00183         Uses.insert(*AI);
00184     }
00185 
00186     for (auto CS : AvailableRegs)
00187       if (!Uses.count(CS) && CS != X86::RIP)
00188         return CS;
00189   }
00190   }
00191 
00192   return 0;
00193 }
00194 
00195 static bool isEAXLiveIn(MachineFunction &MF) {
00196   for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
00197        EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
00198     unsigned Reg = II->first;
00199 
00200     if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
00201         Reg == X86::AH || Reg == X86::AL)
00202       return true;
00203   }
00204 
00205   return false;
00206 }
00207 
00208 /// Check if the flags need to be preserved before the terminators.
00209 /// This would be the case, if the eflags is live-in of the region
00210 /// composed by the terminators or live-out of that region, without
00211 /// being defined by a terminator.
00212 static bool
00213 flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) {
00214   for (const MachineInstr &MI : MBB.terminators()) {
00215     bool BreakNext = false;
00216     for (const MachineOperand &MO : MI.operands()) {
00217       if (!MO.isReg())
00218         continue;
00219       unsigned Reg = MO.getReg();
00220       if (Reg != X86::EFLAGS)
00221         continue;
00222 
00223       // This terminator needs an eflags that is not defined
00224       // by a previous another terminator:
00225       // EFLAGS is live-in of the region composed by the terminators.
00226       if (!MO.isDef())
00227         return true;
00228       // This terminator defines the eflags, i.e., we don't need to preserve it.
00229       // However, we still need to check this specific terminator does not
00230       // read a live-in value.
00231       BreakNext = true;
00232     }
00233     // We found a definition of the eflags, no need to preserve them.
00234     if (BreakNext)
00235       return false;
00236   }
00237 
00238   // None of the terminators use or define the eflags.
00239   // Check if they are live-out, that would imply we need to preserve them.
00240   for (const MachineBasicBlock *Succ : MBB.successors())
00241     if (Succ->isLiveIn(X86::EFLAGS))
00242       return true;
00243 
00244   return false;
00245 }
00246 
00247 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
00248 /// stack pointer by a constant value.
00249 void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
00250                                     MachineBasicBlock::iterator &MBBI,
00251                                     int64_t NumBytes, bool InEpilogue) const {
00252   bool isSub = NumBytes < 0;
00253   uint64_t Offset = isSub ? -NumBytes : NumBytes;
00254 
00255   uint64_t Chunk = (1LL << 31) - 1;
00256   DebugLoc DL = MBB.findDebugLoc(MBBI);
00257 
00258   while (Offset) {
00259     if (Offset > Chunk) {
00260       // Rather than emit a long series of instructions for large offsets,
00261       // load the offset into a register and do one sub/add
00262       unsigned Reg = 0;
00263 
00264       if (isSub && !isEAXLiveIn(*MBB.getParent()))
00265         Reg = (unsigned)(Is64Bit ? X86::RAX : X86::EAX);
00266       else
00267         Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
00268 
00269       if (Reg) {
00270         unsigned Opc = Is64Bit ? X86::MOV64ri : X86::MOV32ri;
00271         BuildMI(MBB, MBBI, DL, TII.get(Opc), Reg)
00272           .addImm(Offset);
00273         Opc = isSub
00274           ? getSUBrrOpcode(Is64Bit)
00275           : getADDrrOpcode(Is64Bit);
00276         MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
00277           .addReg(StackPtr)
00278           .addReg(Reg);
00279         MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
00280         Offset = 0;
00281         continue;
00282       }
00283     }
00284 
00285     uint64_t ThisVal = std::min(Offset, Chunk);
00286     if (ThisVal == (Is64Bit ? 8 : 4)) {
00287       // Use push / pop instead.
00288       unsigned Reg = isSub
00289         ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
00290         : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
00291       if (Reg) {
00292         unsigned Opc = isSub
00293           ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
00294           : (Is64Bit ? X86::POP64r  : X86::POP32r);
00295         MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
00296           .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
00297         if (isSub)
00298           MI->setFlag(MachineInstr::FrameSetup);
00299         else
00300           MI->setFlag(MachineInstr::FrameDestroy);
00301         Offset -= ThisVal;
00302         continue;
00303       }
00304     }
00305 
00306     MachineInstrBuilder MI = BuildStackAdjustment(
00307         MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue);
00308     if (isSub)
00309       MI.setMIFlag(MachineInstr::FrameSetup);
00310     else
00311       MI.setMIFlag(MachineInstr::FrameDestroy);
00312 
00313     Offset -= ThisVal;
00314   }
00315 }
00316 
00317 MachineInstrBuilder X86FrameLowering::BuildStackAdjustment(
00318     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, DebugLoc DL,
00319     int64_t Offset, bool InEpilogue) const {
00320   assert(Offset != 0 && "zero offset stack adjustment requested");
00321 
00322   // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue
00323   // is tricky.
00324   bool UseLEA;
00325   if (!InEpilogue) {
00326     // Check if inserting the prologue at the beginning
00327     // of MBB would require to use LEA operations.
00328     // We need to use LEA operations if EFLAGS is live in, because
00329     // it means an instruction will read it before it gets defined.
00330     UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS);
00331   } else {
00332     // If we can use LEA for SP but we shouldn't, check that none
00333     // of the terminators uses the eflags. Otherwise we will insert
00334     // a ADD that will redefine the eflags and break the condition.
00335     // Alternatively, we could move the ADD, but this may not be possible
00336     // and is an optimization anyway.
00337     UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent());
00338     if (UseLEA && !STI.useLeaForSP())
00339       UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB);
00340     // If that assert breaks, that means we do not do the right thing
00341     // in canUseAsEpilogue.
00342     assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) &&
00343            "We shouldn't have allowed this insertion point");
00344   }
00345 
00346   MachineInstrBuilder MI;
00347   if (UseLEA) {
00348     MI = addRegOffset(BuildMI(MBB, MBBI, DL,
00349                               TII.get(getLEArOpcode(Uses64BitFramePtr)),
00350                               StackPtr),
00351                       StackPtr, false, Offset);
00352   } else {
00353     bool IsSub = Offset < 0;
00354     uint64_t AbsOffset = IsSub ? -Offset : Offset;
00355     unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr, AbsOffset)
00356                          : getADDriOpcode(Uses64BitFramePtr, AbsOffset);
00357     MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
00358              .addReg(StackPtr)
00359              .addImm(AbsOffset);
00360     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
00361   }
00362   return MI;
00363 }
00364 
00365 int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
00366                                      MachineBasicBlock::iterator &MBBI,
00367                                      bool doMergeWithPrevious) const {
00368   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
00369       (!doMergeWithPrevious && MBBI == MBB.end()))
00370     return 0;
00371 
00372   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
00373   MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
00374                                                        : std::next(MBBI);
00375   unsigned Opc = PI->getOpcode();
00376   int Offset = 0;
00377 
00378   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
00379        Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
00380        Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
00381       PI->getOperand(0).getReg() == StackPtr){
00382     Offset += PI->getOperand(2).getImm();
00383     MBB.erase(PI);
00384     if (!doMergeWithPrevious) MBBI = NI;
00385   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
00386               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
00387              PI->getOperand(0).getReg() == StackPtr) {
00388     Offset -= PI->getOperand(2).getImm();
00389     MBB.erase(PI);
00390     if (!doMergeWithPrevious) MBBI = NI;
00391   }
00392 
00393   return Offset;
00394 }
00395 
00396 void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB,
00397                                 MachineBasicBlock::iterator MBBI, DebugLoc DL,
00398                                 MCCFIInstruction CFIInst) const {
00399   MachineFunction &MF = *MBB.getParent();
00400   unsigned CFIIndex = MF.getMMI().addFrameInst(CFIInst);
00401   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
00402       .addCFIIndex(CFIIndex);
00403 }
00404 
00405 void
00406 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
00407                                             MachineBasicBlock::iterator MBBI,
00408                                             DebugLoc DL) const {
00409   MachineFunction &MF = *MBB.getParent();
00410   MachineFrameInfo *MFI = MF.getFrameInfo();
00411   MachineModuleInfo &MMI = MF.getMMI();
00412   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
00413 
00414   // Add callee saved registers to move list.
00415   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
00416   if (CSI.empty()) return;
00417 
00418   // Calculate offsets.
00419   for (std::vector<CalleeSavedInfo>::const_iterator
00420          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
00421     int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
00422     unsigned Reg = I->getReg();
00423 
00424     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
00425     BuildCFI(MBB, MBBI, DL,
00426              MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
00427   }
00428 }
00429 
00430 MachineInstr *X86FrameLowering::emitStackProbe(MachineFunction &MF,
00431                                                MachineBasicBlock &MBB,
00432                                                MachineBasicBlock::iterator MBBI,
00433                                                DebugLoc DL,
00434                                                bool InProlog) const {
00435   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
00436   if (STI.isTargetWindowsCoreCLR()) {
00437     if (InProlog) {
00438       return emitStackProbeInlineStub(MF, MBB, MBBI, DL, true);
00439     } else {
00440       return emitStackProbeInline(MF, MBB, MBBI, DL, false);
00441     }
00442   } else {
00443     return emitStackProbeCall(MF, MBB, MBBI, DL, InProlog);
00444   }
00445 }
00446 
00447 void X86FrameLowering::inlineStackProbe(MachineFunction &MF,
00448                                         MachineBasicBlock &PrologMBB) const {
00449   const StringRef ChkStkStubSymbol = "__chkstk_stub";
00450   MachineInstr *ChkStkStub = nullptr;
00451 
00452   for (MachineInstr &MI : PrologMBB) {
00453     if (MI.isCall() && MI.getOperand(0).isSymbol() &&
00454         ChkStkStubSymbol == MI.getOperand(0).getSymbolName()) {
00455       ChkStkStub = &MI;
00456       break;
00457     }
00458   }
00459 
00460   if (ChkStkStub != nullptr) {
00461     MachineBasicBlock::iterator MBBI = std::next(ChkStkStub->getIterator());
00462     assert(std::prev(MBBI).operator==(ChkStkStub) &&
00463       "MBBI expected after __chkstk_stub.");
00464     DebugLoc DL = PrologMBB.findDebugLoc(MBBI);
00465     emitStackProbeInline(MF, PrologMBB, MBBI, DL, true);
00466     ChkStkStub->eraseFromParent();
00467   }
00468 }
00469 
00470 MachineInstr *X86FrameLowering::emitStackProbeInline(
00471   MachineFunction &MF, MachineBasicBlock &MBB,
00472   MachineBasicBlock::iterator MBBI, DebugLoc DL, bool InProlog) const {
00473   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
00474   assert(STI.is64Bit() && "different expansion needed for 32 bit");
00475   assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
00476   const TargetInstrInfo &TII = *STI.getInstrInfo();
00477   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
00478 
00479   // RAX contains the number of bytes of desired stack adjustment.
00480   // The handling here assumes this value has already been updated so as to
00481   // maintain stack alignment.
00482   //
00483   // We need to exit with RSP modified by this amount and execute suitable
00484   // page touches to notify the OS that we're growing the stack responsibly.
00485   // All stack probing must be done without modifying RSP.
00486   //
00487   // MBB:
00488   //    SizeReg = RAX;
00489   //    ZeroReg = 0
00490   //    CopyReg = RSP
00491   //    Flags, TestReg = CopyReg - SizeReg
00492   //    FinalReg = !Flags.Ovf ? TestReg : ZeroReg
00493   //    LimitReg = gs magic thread env access
00494   //    if FinalReg >= LimitReg goto ContinueMBB
00495   // RoundBB:
00496   //    RoundReg = page address of FinalReg
00497   // LoopMBB:
00498   //    LoopReg = PHI(LimitReg,ProbeReg)
00499   //    ProbeReg = LoopReg - PageSize
00500   //    [ProbeReg] = 0
00501   //    if (ProbeReg > RoundReg) goto LoopMBB
00502   // ContinueMBB:
00503   //    RSP = RSP - RAX
00504   //    [rest of original MBB]
00505 
00506   // Set up the new basic blocks
00507   MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB);
00508   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
00509   MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB);
00510 
00511   MachineFunction::iterator MBBIter = std::next(MBB.getIterator());
00512   MF.insert(MBBIter, RoundMBB);
00513   MF.insert(MBBIter, LoopMBB);
00514   MF.insert(MBBIter, ContinueMBB);
00515 
00516   // Split MBB and move the tail portion down to ContinueMBB.
00517   MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI);
00518   ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end());
00519   ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB);
00520 
00521   // Some useful constants
00522   const int64_t ThreadEnvironmentStackLimit = 0x10;
00523   const int64_t PageSize = 0x1000;
00524   const int64_t PageMask = ~(PageSize - 1);
00525 
00526   // Registers we need. For the normal case we use virtual
00527   // registers. For the prolog expansion we use RAX, RCX and RDX.
00528   MachineRegisterInfo &MRI = MF.getRegInfo();
00529   const TargetRegisterClass *RegClass = &X86::GR64RegClass;
00530   const unsigned SizeReg = InProlog ? (unsigned)X86::RAX
00531                                     : MRI.createVirtualRegister(RegClass),
00532                  ZeroReg = InProlog ? (unsigned)X86::RCX
00533                                     : MRI.createVirtualRegister(RegClass),
00534                  CopyReg = InProlog ? (unsigned)X86::RDX
00535                                     : MRI.createVirtualRegister(RegClass),
00536                  TestReg = InProlog ? (unsigned)X86::RDX
00537                                     : MRI.createVirtualRegister(RegClass),
00538                  FinalReg = InProlog ? (unsigned)X86::RDX
00539                                      : MRI.createVirtualRegister(RegClass),
00540                  RoundedReg = InProlog ? (unsigned)X86::RDX
00541                                        : MRI.createVirtualRegister(RegClass),
00542                  LimitReg = InProlog ? (unsigned)X86::RCX
00543                                      : MRI.createVirtualRegister(RegClass),
00544                  JoinReg = InProlog ? (unsigned)X86::RCX
00545                                     : MRI.createVirtualRegister(RegClass),
00546                  ProbeReg = InProlog ? (unsigned)X86::RCX
00547                                      : MRI.createVirtualRegister(RegClass);
00548 
00549   // SP-relative offsets where we can save RCX and RDX.
00550   int64_t RCXShadowSlot = 0;
00551   int64_t RDXShadowSlot = 0;
00552 
00553   // If inlining in the prolog, save RCX and RDX.     
00554   // Future optimization: don't save or restore if not live in.
00555   if (InProlog) {
00556     // Compute the offsets. We need to account for things already
00557     // pushed onto the stack at this point: return address, frame
00558     // pointer (if used), and callee saves.
00559     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
00560     const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
00561     const bool HasFP = hasFP(MF);
00562     RCXShadowSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
00563     RDXShadowSlot = RCXShadowSlot + 8;
00564     // Emit the saves.
00565     addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
00566                  RCXShadowSlot)
00567         .addReg(X86::RCX);
00568     addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
00569                  RDXShadowSlot)
00570         .addReg(X86::RDX);
00571   } else {
00572     // Not in the prolog. Copy RAX to a virtual reg.
00573     BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX);
00574   }
00575 
00576   // Add code to MBB to check for overflow and set the new target stack pointer
00577   // to zero if so.
00578   BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg)
00579       .addReg(ZeroReg, RegState::Undef)
00580       .addReg(ZeroReg, RegState::Undef);
00581   BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP);
00582   BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg)
00583       .addReg(CopyReg)
00584       .addReg(SizeReg);
00585   BuildMI(&MBB, DL, TII.get(X86::CMOVB64rr), FinalReg)
00586       .addReg(TestReg)
00587       .addReg(ZeroReg);
00588 
00589   // FinalReg now holds final stack pointer value, or zero if
00590   // allocation would overflow. Compare against the current stack
00591   // limit from the thread environment block. Note this limit is the
00592   // lowest touched page on the stack, not the point at which the OS
00593   // will cause an overflow exception, so this is just an optimization
00594   // to avoid unnecessarily touching pages that are below the current
00595   // SP but already commited to the stack by the OS.
00596   BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg)
00597       .addReg(0)
00598       .addImm(1)
00599       .addReg(0)
00600       .addImm(ThreadEnvironmentStackLimit)
00601       .addReg(X86::GS);
00602   BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg);
00603   // Jump if the desired stack pointer is at or above the stack limit.
00604   BuildMI(&MBB, DL, TII.get(X86::JAE_1)).addMBB(ContinueMBB);
00605 
00606   // Add code to roundMBB to round the final stack pointer to a page boundary.
00607   BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg)
00608       .addReg(FinalReg)
00609       .addImm(PageMask);
00610   BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB);
00611 
00612   // LimitReg now holds the current stack limit, RoundedReg page-rounded
00613   // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
00614   // and probe until we reach RoundedReg.
00615   if (!InProlog) {
00616     BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg)
00617         .addReg(LimitReg)
00618         .addMBB(RoundMBB)
00619         .addReg(ProbeReg)
00620         .addMBB(LoopMBB);
00621   }
00622 
00623   addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg,
00624                false, -PageSize);
00625 
00626   // Probe by storing a byte onto the stack.
00627   BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi))
00628       .addReg(ProbeReg)
00629       .addImm(1)
00630       .addReg(0)
00631       .addImm(0)
00632       .addReg(0)
00633       .addImm(0);
00634   BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr))
00635       .addReg(RoundedReg)
00636       .addReg(ProbeReg);
00637   BuildMI(LoopMBB, DL, TII.get(X86::JNE_1)).addMBB(LoopMBB);
00638 
00639   MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
00640 
00641   // If in prolog, restore RDX and RCX.
00642   if (InProlog) {
00643     addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::MOV64rm),
00644                          X86::RCX),
00645                  X86::RSP, false, RCXShadowSlot);
00646     addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::MOV64rm),
00647                          X86::RDX),
00648                  X86::RSP, false, RDXShadowSlot);
00649   }
00650 
00651   // Now that the probing is done, add code to continueMBB to update
00652   // the stack pointer for real.
00653   BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
00654       .addReg(X86::RSP)
00655       .addReg(SizeReg);
00656 
00657   // Add the control flow edges we need.
00658   MBB.addSuccessor(ContinueMBB);
00659   MBB.addSuccessor(RoundMBB);
00660   RoundMBB->addSuccessor(LoopMBB);
00661   LoopMBB->addSuccessor(ContinueMBB);
00662   LoopMBB->addSuccessor(LoopMBB);
00663 
00664   // Mark all the instructions added to the prolog as frame setup.
00665   if (InProlog) {
00666     for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
00667       BeforeMBBI->setFlag(MachineInstr::FrameSetup);
00668     }
00669     for (MachineInstr &MI : *RoundMBB) {
00670       MI.setFlag(MachineInstr::FrameSetup);
00671     }
00672     for (MachineInstr &MI : *LoopMBB) {
00673       MI.setFlag(MachineInstr::FrameSetup);
00674     }
00675     for (MachineBasicBlock::iterator CMBBI = ContinueMBB->begin();
00676          CMBBI != ContinueMBBI; ++CMBBI) {
00677       CMBBI->setFlag(MachineInstr::FrameSetup);
00678     }
00679   }
00680 
00681   // Possible TODO: physreg liveness for InProlog case.
00682 
00683   return ContinueMBBI;
00684 }
00685 
00686 MachineInstr *X86FrameLowering::emitStackProbeCall(
00687     MachineFunction &MF, MachineBasicBlock &MBB,
00688     MachineBasicBlock::iterator MBBI, DebugLoc DL, bool InProlog) const {
00689   bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
00690 
00691   unsigned CallOp;
00692   if (Is64Bit)
00693     CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
00694   else
00695     CallOp = X86::CALLpcrel32;
00696 
00697   const char *Symbol;
00698   if (Is64Bit) {
00699     if (STI.isTargetCygMing()) {
00700       Symbol = "___chkstk_ms";
00701     } else {
00702       Symbol = "__chkstk";
00703     }
00704   } else if (STI.isTargetCygMing())
00705     Symbol = "_alloca";
00706   else
00707     Symbol = "_chkstk";
00708 
00709   MachineInstrBuilder CI;
00710   MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI);
00711 
00712   // All current stack probes take AX and SP as input, clobber flags, and
00713   // preserve all registers. x86_64 probes leave RSP unmodified.
00714   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
00715     // For the large code model, we have to call through a register. Use R11,
00716     // as it is scratch in all supported calling conventions.
00717     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
00718         .addExternalSymbol(Symbol);
00719     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
00720   } else {
00721     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addExternalSymbol(Symbol);
00722   }
00723 
00724   unsigned AX = Is64Bit ? X86::RAX : X86::EAX;
00725   unsigned SP = Is64Bit ? X86::RSP : X86::ESP;
00726   CI.addReg(AX, RegState::Implicit)
00727       .addReg(SP, RegState::Implicit)
00728       .addReg(AX, RegState::Define | RegState::Implicit)
00729       .addReg(SP, RegState::Define | RegState::Implicit)
00730       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
00731 
00732   if (Is64Bit) {
00733     // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
00734     // themselves. It also does not clobber %rax so we can reuse it when
00735     // adjusting %rsp.
00736     BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
00737         .addReg(X86::RSP)
00738         .addReg(X86::RAX);
00739   }
00740 
00741   if (InProlog) {
00742     // Apply the frame setup flag to all inserted instrs.
00743     for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
00744       ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
00745   }
00746 
00747   return MBBI;
00748 }
00749 
00750 MachineInstr *X86FrameLowering::emitStackProbeInlineStub(
00751     MachineFunction &MF, MachineBasicBlock &MBB,
00752     MachineBasicBlock::iterator MBBI, DebugLoc DL, bool InProlog) const {
00753 
00754   assert(InProlog && "ChkStkStub called outside prolog!");
00755 
00756   BuildMI(MBB, MBBI, DL, TII.get(X86::CALLpcrel32))
00757       .addExternalSymbol("__chkstk_stub");
00758 
00759   return MBBI;
00760 }
00761 
00762 static unsigned calculateSetFPREG(uint64_t SPAdjust) {
00763   // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
00764   // and might require smaller successive adjustments.
00765   const uint64_t Win64MaxSEHOffset = 128;
00766   uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
00767   // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
00768   return SEHFrameOffset & -16;
00769 }
00770 
00771 // If we're forcing a stack realignment we can't rely on just the frame
00772 // info, we need to know the ABI stack alignment as well in case we
00773 // have a call out.  Otherwise just make sure we have some alignment - we'll
00774 // go with the minimum SlotSize.
00775 uint64_t X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
00776   const MachineFrameInfo *MFI = MF.getFrameInfo();
00777   uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
00778   unsigned StackAlign = getStackAlignment();
00779   if (MF.getFunction()->hasFnAttribute("stackrealign")) {
00780     if (MFI->hasCalls())
00781       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
00782     else if (MaxAlign < SlotSize)
00783       MaxAlign = SlotSize;
00784   }
00785   return MaxAlign;
00786 }
00787 
00788 void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
00789                                           MachineBasicBlock::iterator MBBI,
00790                                           DebugLoc DL, unsigned Reg,
00791                                           uint64_t MaxAlign) const {
00792   uint64_t Val = -MaxAlign;
00793   unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val);
00794   MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg)
00795                          .addReg(Reg)
00796                          .addImm(Val)
00797                          .setMIFlag(MachineInstr::FrameSetup);
00798 
00799   // The EFLAGS implicit def is dead.
00800   MI->getOperand(3).setIsDead();
00801 }
00802 
00803 /// emitPrologue - Push callee-saved registers onto the stack, which
00804 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
00805 /// space for local variables. Also emit labels used by the exception handler to
00806 /// generate the exception handling frames.
00807 
00808 /*
00809   Here's a gist of what gets emitted:
00810 
00811   ; Establish frame pointer, if needed
00812   [if needs FP]
00813       push  %rbp
00814       .cfi_def_cfa_offset 16
00815       .cfi_offset %rbp, -16
00816       .seh_pushreg %rpb
00817       mov  %rsp, %rbp
00818       .cfi_def_cfa_register %rbp
00819 
00820   ; Spill general-purpose registers
00821   [for all callee-saved GPRs]
00822       pushq %<reg>
00823       [if not needs FP]
00824          .cfi_def_cfa_offset (offset from RETADDR)
00825       .seh_pushreg %<reg>
00826 
00827   ; If the required stack alignment > default stack alignment
00828   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
00829   ; of unknown size in the stack frame.
00830   [if stack needs re-alignment]
00831       and  $MASK, %rsp
00832 
00833   ; Allocate space for locals
00834   [if target is Windows and allocated space > 4096 bytes]
00835       ; Windows needs special care for allocations larger
00836       ; than one page.
00837       mov $NNN, %rax
00838       call ___chkstk_ms/___chkstk
00839       sub  %rax, %rsp
00840   [else]
00841       sub  $NNN, %rsp
00842 
00843   [if needs FP]
00844       .seh_stackalloc (size of XMM spill slots)
00845       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
00846   [else]
00847       .seh_stackalloc NNN
00848 
00849   ; Spill XMMs
00850   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
00851   ; they may get spilled on any platform, if the current function
00852   ; calls @llvm.eh.unwind.init
00853   [if needs FP]
00854       [for all callee-saved XMM registers]
00855           movaps  %<xmm reg>, -MMM(%rbp)
00856       [for all callee-saved XMM registers]
00857           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
00858               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
00859   [else]
00860       [for all callee-saved XMM registers]
00861           movaps  %<xmm reg>, KKK(%rsp)
00862       [for all callee-saved XMM registers]
00863           .seh_savexmm %<xmm reg>, KKK
00864 
00865   .seh_endprologue
00866 
00867   [if needs base pointer]
00868       mov  %rsp, %rbx
00869       [if needs to restore base pointer]
00870           mov %rsp, -MMM(%rbp)
00871 
00872   ; Emit CFI info
00873   [if needs FP]
00874       [for all callee-saved registers]
00875           .cfi_offset %<reg>, (offset from %rbp)
00876   [else]
00877        .cfi_def_cfa_offset (offset from RETADDR)
00878       [for all callee-saved registers]
00879           .cfi_offset %<reg>, (offset from %rsp)
00880 
00881   Notes:
00882   - .seh directives are emitted only for Windows 64 ABI
00883   - .cfi directives are emitted for all other ABIs
00884   - for 32-bit code, substitute %e?? registers for %r??
00885 */
00886 
00887 void X86FrameLowering::emitPrologue(MachineFunction &MF,
00888                                     MachineBasicBlock &MBB) const {
00889   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
00890          "MF used frame lowering for wrong subtarget");
00891   MachineBasicBlock::iterator MBBI = MBB.begin();
00892   MachineFrameInfo *MFI = MF.getFrameInfo();
00893   const Function *Fn = MF.getFunction();
00894   MachineModuleInfo &MMI = MF.getMMI();
00895   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
00896   uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
00897   uint64_t StackSize = MFI->getStackSize();    // Number of bytes to allocate.
00898   bool IsFunclet = MBB.isEHFuncletEntry();
00899   EHPersonality Personality = EHPersonality::Unknown;
00900   if (Fn->hasPersonalityFn())
00901     Personality = classifyEHPersonality(Fn->getPersonalityFn());
00902   bool FnHasClrFunclet =
00903       MMI.hasEHFunclets() && Personality == EHPersonality::CoreCLR;
00904   bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
00905   bool HasFP = hasFP(MF);
00906   bool IsWin64CC = STI.isCallingConvWin64(Fn->getCallingConv());
00907   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
00908   bool NeedsWinCFI = IsWin64Prologue && Fn->needsUnwindTableEntry();
00909   bool NeedsDwarfCFI =
00910       !IsWin64Prologue && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
00911   unsigned FramePtr = TRI->getFrameRegister(MF);
00912   const unsigned MachineFramePtr =
00913       STI.isTarget64BitILP32()
00914           ? getX86SubSuperRegister(FramePtr, 64) : FramePtr;
00915   unsigned BasePtr = TRI->getBaseRegister();
00916   
00917   // Debug location must be unknown since the first debug location is used
00918   // to determine the end of the prologue.
00919   DebugLoc DL;
00920 
00921   // Add RETADDR move area to callee saved frame size.
00922   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
00923   if (TailCallReturnAddrDelta && IsWin64Prologue)
00924     report_fatal_error("Can't handle guaranteed tail call under win64 yet");
00925 
00926   if (TailCallReturnAddrDelta < 0)
00927     X86FI->setCalleeSavedFrameSize(
00928       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
00929 
00930   bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
00931 
00932   // The default stack probe size is 4096 if the function has no stackprobesize
00933   // attribute.
00934   unsigned StackProbeSize = 4096;
00935   if (Fn->hasFnAttribute("stack-probe-size"))
00936     Fn->getFnAttribute("stack-probe-size")
00937         .getValueAsString()
00938         .getAsInteger(0, StackProbeSize);
00939 
00940   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
00941   // function, and use up to 128 bytes of stack space, don't have a frame
00942   // pointer, calls, or dynamic alloca then we do not need to adjust the
00943   // stack pointer (we fit in the Red Zone). We also check that we don't
00944   // push and pop from the stack.
00945   if (Is64Bit && !Fn->hasFnAttribute(Attribute::NoRedZone) &&
00946       !TRI->needsStackRealignment(MF) &&
00947       !MFI->hasVarSizedObjects() &&             // No dynamic alloca.
00948       !MFI->adjustsStack() &&                   // No calls.
00949       !IsWin64CC &&                             // Win64 has no Red Zone
00950       !MFI->hasCopyImplyingStackAdjustment() && // Don't push and pop.
00951       !MF.shouldSplitStack()) {                 // Regular stack
00952     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
00953     if (HasFP) MinSize += SlotSize;
00954     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
00955     MFI->setStackSize(StackSize);
00956   }
00957 
00958   // Insert stack pointer adjustment for later moving of return addr.  Only
00959   // applies to tail call optimized functions where the callee argument stack
00960   // size is bigger than the callers.
00961   if (TailCallReturnAddrDelta < 0) {
00962     BuildStackAdjustment(MBB, MBBI, DL, TailCallReturnAddrDelta,
00963                          /*InEpilogue=*/false)
00964         .setMIFlag(MachineInstr::FrameSetup);
00965   }
00966 
00967   // Mapping for machine moves:
00968   //
00969   //   DST: VirtualFP AND
00970   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
00971   //        ELSE                        => DW_CFA_def_cfa
00972   //
00973   //   SRC: VirtualFP AND
00974   //        DST: Register               => DW_CFA_def_cfa_register
00975   //
00976   //   ELSE
00977   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
00978   //        REG < 64                    => DW_CFA_offset + Reg
00979   //        ELSE                        => DW_CFA_offset_extended
00980 
00981   uint64_t NumBytes = 0;
00982   int stackGrowth = -SlotSize;
00983 
00984   // Find the funclet establisher parameter
00985   unsigned Establisher = X86::NoRegister;
00986   if (IsClrFunclet)
00987     Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
00988   else if (IsFunclet)
00989     Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
00990 
00991   if (IsWin64Prologue && IsFunclet && !IsClrFunclet) {
00992     // Immediately spill establisher into the home slot.
00993     // The runtime cares about this.
00994     // MOV64mr %rdx, 16(%rsp)
00995     unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
00996     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16)
00997         .addReg(Establisher)
00998         .setMIFlag(MachineInstr::FrameSetup);
00999     MBB.addLiveIn(Establisher);
01000   }
01001 
01002   if (HasFP) {
01003     // Calculate required stack adjustment.
01004     uint64_t FrameSize = StackSize - SlotSize;
01005     // If required, include space for extra hidden slot for stashing base pointer.
01006     if (X86FI->getRestoreBasePointer())
01007       FrameSize += SlotSize;
01008 
01009     NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
01010 
01011     // Callee-saved registers are pushed on stack before the stack is realigned.
01012     if (TRI->needsStackRealignment(MF) && !IsWin64Prologue)
01013       NumBytes = alignTo(NumBytes, MaxAlign);
01014 
01015     // Get the offset of the stack slot for the EBP register, which is
01016     // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
01017     // Update the frame offset adjustment.
01018     if (!IsFunclet)
01019       MFI->setOffsetAdjustment(-NumBytes);
01020     else
01021       assert(MFI->getOffsetAdjustment() == -(int)NumBytes &&
01022              "should calculate same local variable offset for funclets");
01023 
01024     // Save EBP/RBP into the appropriate stack slot.
01025     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
01026       .addReg(MachineFramePtr, RegState::Kill)
01027       .setMIFlag(MachineInstr::FrameSetup);
01028 
01029     if (NeedsDwarfCFI) {
01030       // Mark the place where EBP/RBP was saved.
01031       // Define the current CFA rule to use the provided offset.
01032       assert(StackSize);
01033       BuildCFI(MBB, MBBI, DL,
01034                MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
01035 
01036       // Change the rule for the FramePtr to be an "offset" rule.
01037       unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
01038       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createOffset(
01039                                   nullptr, DwarfFramePtr, 2 * stackGrowth));
01040     }
01041 
01042     if (NeedsWinCFI) {
01043       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
01044           .addImm(FramePtr)
01045           .setMIFlag(MachineInstr::FrameSetup);
01046     }
01047 
01048     if (!IsWin64Prologue && !IsFunclet) {
01049       // Update EBP with the new base value.
01050       BuildMI(MBB, MBBI, DL,
01051               TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
01052               FramePtr)
01053           .addReg(StackPtr)
01054           .setMIFlag(MachineInstr::FrameSetup);
01055 
01056       if (NeedsDwarfCFI) {
01057         // Mark effective beginning of when frame pointer becomes valid.
01058         // Define the current CFA to use the EBP/RBP register.
01059         unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
01060         BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaRegister(
01061                                     nullptr, DwarfFramePtr));
01062       }
01063     }
01064 
01065     // Mark the FramePtr as live-in in every block. Don't do this again for
01066     // funclet prologues.
01067     if (!IsFunclet) {
01068       for (MachineBasicBlock &EveryMBB : MF)
01069         EveryMBB.addLiveIn(MachineFramePtr);
01070     }
01071   } else {
01072     assert(!IsFunclet && "funclets without FPs not yet implemented");
01073     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
01074   }
01075 
01076   // For EH funclets, only allocate enough space for outgoing calls. Save the
01077   // NumBytes value that we would've used for the parent frame.
01078   unsigned ParentFrameNumBytes = NumBytes;
01079   if (IsFunclet)
01080     NumBytes = getWinEHFuncletFrameSize(MF);
01081 
01082   // Skip the callee-saved push instructions.
01083   bool PushedRegs = false;
01084   int StackOffset = 2 * stackGrowth;
01085 
01086   while (MBBI != MBB.end() &&
01087          MBBI->getFlag(MachineInstr::FrameSetup) &&
01088          (MBBI->getOpcode() == X86::PUSH32r ||
01089           MBBI->getOpcode() == X86::PUSH64r)) {
01090     PushedRegs = true;
01091     unsigned Reg = MBBI->getOperand(0).getReg();
01092     ++MBBI;
01093 
01094     if (!HasFP && NeedsDwarfCFI) {
01095       // Mark callee-saved push instruction.
01096       // Define the current CFA rule to use the provided offset.
01097       assert(StackSize);
01098       BuildCFI(MBB, MBBI, DL,
01099                MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
01100       StackOffset += stackGrowth;
01101     }
01102 
01103     if (NeedsWinCFI) {
01104       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
01105           MachineInstr::FrameSetup);
01106     }
01107   }
01108 
01109   // Realign stack after we pushed callee-saved registers (so that we'll be
01110   // able to calculate their offsets from the frame pointer).
01111   // Don't do this for Win64, it needs to realign the stack after the prologue.
01112   if (!IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF)) {
01113     assert(HasFP && "There should be a frame pointer if stack is realigned.");
01114     BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
01115   }
01116 
01117   // If there is an SUB32ri of ESP immediately before this instruction, merge
01118   // the two. This can be the case when tail call elimination is enabled and
01119   // the callee has more arguments then the caller.
01120   NumBytes -= mergeSPUpdates(MBB, MBBI, true);
01121 
01122   // Adjust stack pointer: ESP -= numbytes.
01123 
01124   // Windows and cygwin/mingw require a prologue helper routine when allocating
01125   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
01126   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
01127   // stack and adjust the stack pointer in one go.  The 64-bit version of
01128   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
01129   // responsible for adjusting the stack pointer.  Touching the stack at 4K
01130   // increments is necessary to ensure that the guard pages used by the OS
01131   // virtual memory manager are allocated in correct sequence.
01132   uint64_t AlignedNumBytes = NumBytes;
01133   if (IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF))
01134     AlignedNumBytes = alignTo(AlignedNumBytes, MaxAlign);
01135   if (AlignedNumBytes >= StackProbeSize && UseStackProbe) {
01136     // Check whether EAX is livein for this function.
01137     bool isEAXAlive = isEAXLiveIn(MF);
01138 
01139     if (isEAXAlive) {
01140       // Sanity check that EAX is not livein for this function.
01141       // It should not be, so throw an assert.
01142       assert(!Is64Bit && "EAX is livein in x64 case!");
01143 
01144       // Save EAX
01145       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
01146         .addReg(X86::EAX, RegState::Kill)
01147         .setMIFlag(MachineInstr::FrameSetup);
01148     }
01149 
01150     if (Is64Bit) {
01151       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
01152       // Function prologue is responsible for adjusting the stack pointer.
01153       if (isUInt<32>(NumBytes)) {
01154         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
01155             .addImm(NumBytes)
01156             .setMIFlag(MachineInstr::FrameSetup);
01157       } else if (isInt<32>(NumBytes)) {
01158         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
01159             .addImm(NumBytes)
01160             .setMIFlag(MachineInstr::FrameSetup);
01161       } else {
01162         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
01163             .addImm(NumBytes)
01164             .setMIFlag(MachineInstr::FrameSetup);
01165       }
01166     } else {
01167       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
01168       // We'll also use 4 already allocated bytes for EAX.
01169       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
01170           .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
01171           .setMIFlag(MachineInstr::FrameSetup);
01172     }
01173 
01174     // Call __chkstk, __chkstk_ms, or __alloca.
01175     emitStackProbe(MF, MBB, MBBI, DL, true);
01176 
01177     if (isEAXAlive) {
01178       // Restore EAX
01179       MachineInstr *MI =
01180           addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX),
01181                        StackPtr, false, NumBytes - 4);
01182       MI->setFlag(MachineInstr::FrameSetup);
01183       MBB.insert(MBBI, MI);
01184     }
01185   } else if (NumBytes) {
01186     emitSPUpdate(MBB, MBBI, -(int64_t)NumBytes, /*InEpilogue=*/false);
01187   }
01188 
01189   if (NeedsWinCFI && NumBytes)
01190     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
01191         .addImm(NumBytes)
01192         .setMIFlag(MachineInstr::FrameSetup);
01193 
01194   int SEHFrameOffset = 0;
01195   unsigned SPOrEstablisher;
01196   if (IsFunclet) {
01197     if (IsClrFunclet) {
01198       // The establisher parameter passed to a CLR funclet is actually a pointer
01199       // to the (mostly empty) frame of its nearest enclosing funclet; we have
01200       // to find the root function establisher frame by loading the PSPSym from
01201       // the intermediate frame.
01202       unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
01203       MachinePointerInfo NoInfo;
01204       MBB.addLiveIn(Establisher);
01205       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher),
01206                    Establisher, false, PSPSlotOffset)
01207           .addMemOperand(MF.getMachineMemOperand(
01208               NoInfo, MachineMemOperand::MOLoad, SlotSize, SlotSize));
01209       ;
01210       // Save the root establisher back into the current funclet's (mostly
01211       // empty) frame, in case a sub-funclet or the GC needs it.
01212       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
01213                    false, PSPSlotOffset)
01214           .addReg(Establisher)
01215           .addMemOperand(
01216               MF.getMachineMemOperand(NoInfo, MachineMemOperand::MOStore |
01217                                                   MachineMemOperand::MOVolatile,
01218                                       SlotSize, SlotSize));
01219     }
01220     SPOrEstablisher = Establisher;
01221   } else {
01222     SPOrEstablisher = StackPtr;
01223   }
01224 
01225   if (IsWin64Prologue && HasFP) {
01226     // Set RBP to a small fixed offset from RSP. In the funclet case, we base
01227     // this calculation on the incoming establisher, which holds the value of
01228     // RSP from the parent frame at the end of the prologue.
01229     SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes);
01230     if (SEHFrameOffset)
01231       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
01232                    SPOrEstablisher, false, SEHFrameOffset);
01233     else
01234       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr)
01235           .addReg(SPOrEstablisher);
01236 
01237     // If this is not a funclet, emit the CFI describing our frame pointer.
01238     if (NeedsWinCFI && !IsFunclet) {
01239       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
01240           .addImm(FramePtr)
01241           .addImm(SEHFrameOffset)
01242           .setMIFlag(MachineInstr::FrameSetup);
01243       if (isAsynchronousEHPersonality(Personality))
01244         MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset;
01245     }
01246   } else if (IsFunclet && STI.is32Bit()) {
01247     // Reset EBP / ESI to something good for funclets.
01248     MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL);
01249     // If we're a catch funclet, we can be returned to via catchret. Save ESP
01250     // into the registration node so that the runtime will restore it for us.
01251     if (!MBB.isCleanupFuncletEntry()) {
01252       assert(Personality == EHPersonality::MSVC_CXX);
01253       unsigned FrameReg;
01254       int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex;
01255       int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg);
01256       // ESP is the first field, so no extra displacement is needed.
01257       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg,
01258                    false, EHRegOffset)
01259           .addReg(X86::ESP);
01260     }
01261   }
01262 
01263   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
01264     const MachineInstr *FrameInstr = &*MBBI;
01265     ++MBBI;
01266 
01267     if (NeedsWinCFI) {
01268       int FI;
01269       if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
01270         if (X86::FR64RegClass.contains(Reg)) {
01271           unsigned IgnoredFrameReg;
01272           int Offset = getFrameIndexReference(MF, FI, IgnoredFrameReg);
01273           Offset += SEHFrameOffset;
01274 
01275           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
01276               .addImm(Reg)
01277               .addImm(Offset)
01278               .setMIFlag(MachineInstr::FrameSetup);
01279         }
01280       }
01281     }
01282   }
01283 
01284   if (NeedsWinCFI)
01285     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
01286         .setMIFlag(MachineInstr::FrameSetup);
01287 
01288   if (FnHasClrFunclet && !IsFunclet) {
01289     // Save the so-called Initial-SP (i.e. the value of the stack pointer
01290     // immediately after the prolog)  into the PSPSlot so that funclets
01291     // and the GC can recover it.
01292     unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
01293     auto PSPInfo = MachinePointerInfo::getFixedStack(
01294         MF, MF.getWinEHFuncInfo()->PSPSymFrameIdx);
01295     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false,
01296                  PSPSlotOffset)
01297         .addReg(StackPtr)
01298         .addMemOperand(MF.getMachineMemOperand(
01299             PSPInfo, MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
01300             SlotSize, SlotSize));
01301   }
01302 
01303   // Realign stack after we spilled callee-saved registers (so that we'll be
01304   // able to calculate their offsets from the frame pointer).
01305   // Win64 requires aligning the stack after the prologue.
01306   if (IsWin64Prologue && TRI->needsStackRealignment(MF)) {
01307     assert(HasFP && "There should be a frame pointer if stack is realigned.");
01308     BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign);
01309   }
01310 
01311   // We already dealt with stack realignment and funclets above.
01312   if (IsFunclet && STI.is32Bit())
01313     return;
01314 
01315   // If we need a base pointer, set it up here. It's whatever the value
01316   // of the stack pointer is at this point. Any variable size objects
01317   // will be allocated after this, so we can still use the base pointer
01318   // to reference locals.
01319   if (TRI->hasBasePointer(MF)) {
01320     // Update the base pointer with the current stack pointer.
01321     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
01322     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
01323       .addReg(SPOrEstablisher)
01324       .setMIFlag(MachineInstr::FrameSetup);
01325     if (X86FI->getRestoreBasePointer()) {
01326       // Stash value of base pointer.  Saving RSP instead of EBP shortens
01327       // dependence chain. Used by SjLj EH.
01328       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
01329       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
01330                    FramePtr, true, X86FI->getRestoreBasePointerOffset())
01331         .addReg(SPOrEstablisher)
01332         .setMIFlag(MachineInstr::FrameSetup);
01333     }
01334 
01335     if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
01336       // Stash the value of the frame pointer relative to the base pointer for
01337       // Win32 EH. This supports Win32 EH, which does the inverse of the above:
01338       // it recovers the frame pointer from the base pointer rather than the
01339       // other way around.
01340       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
01341       unsigned UsedReg;
01342       int Offset =
01343           getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg);
01344       assert(UsedReg == BasePtr);
01345       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset)
01346           .addReg(FramePtr)
01347           .setMIFlag(MachineInstr::FrameSetup);
01348     }
01349   }
01350 
01351   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
01352     // Mark end of stack pointer adjustment.
01353     if (!HasFP && NumBytes) {
01354       // Define the current CFA rule to use the provided offset.
01355       assert(StackSize);
01356       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaOffset(
01357                                   nullptr, -StackSize + stackGrowth));
01358     }
01359 
01360     // Emit DWARF info specifying the offsets of the callee-saved registers.
01361     if (PushedRegs)
01362       emitCalleeSavedFrameMoves(MBB, MBBI, DL);
01363   }
01364 }
01365 
01366 bool X86FrameLowering::canUseLEAForSPInEpilogue(
01367     const MachineFunction &MF) const {
01368   // We can't use LEA instructions for adjusting the stack pointer if this is a
01369   // leaf function in the Win64 ABI.  Only ADD instructions may be used to
01370   // deallocate the stack.
01371   // This means that we can use LEA for SP in two situations:
01372   // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
01373   // 2. We *have* a frame pointer which means we are permitted to use LEA.
01374   return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
01375 }
01376 
01377 static bool isFuncletReturnInstr(MachineInstr *MI) {
01378   switch (MI->getOpcode()) {
01379   case X86::CATCHRET:
01380   case X86::CLEANUPRET:
01381     return true;
01382   default:
01383     return false;
01384   }
01385   llvm_unreachable("impossible");
01386 }
01387 
01388 // CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
01389 // stack. It holds a pointer to the bottom of the root function frame.  The
01390 // establisher frame pointer passed to a nested funclet may point to the
01391 // (mostly empty) frame of its parent funclet, but it will need to find
01392 // the frame of the root function to access locals.  To facilitate this,
01393 // every funclet copies the pointer to the bottom of the root function
01394 // frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
01395 // same offset for the PSPSym in the root function frame that's used in the
01396 // funclets' frames allows each funclet to dynamically accept any ancestor
01397 // frame as its establisher argument (the runtime doesn't guarantee the
01398 // immediate parent for some reason lost to history), and also allows the GC,
01399 // which uses the PSPSym for some bookkeeping, to find it in any funclet's
01400 // frame with only a single offset reported for the entire method.
01401 unsigned
01402 X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
01403   const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
01404   // getFrameIndexReferenceFromSP has an out ref parameter for the stack
01405   // pointer register; pass a dummy that we ignore
01406   unsigned SPReg;
01407   int Offset = getFrameIndexReferenceFromSP(MF, Info.PSPSymFrameIdx, SPReg);
01408   assert(Offset >= 0);
01409   return static_cast<unsigned>(Offset);
01410 }
01411 
01412 unsigned
01413 X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
01414   // This is the size of the pushed CSRs.
01415   unsigned CSSize =
01416       MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
01417   // This is the amount of stack a funclet needs to allocate.
01418   unsigned UsedSize;
01419   EHPersonality Personality =
01420       classifyEHPersonality(MF.getFunction()->getPersonalityFn());
01421   if (Personality == EHPersonality::CoreCLR) {
01422     // CLR funclets need to hold enough space to include the PSPSym, at the
01423     // same offset from the stack pointer (immediately after the prolog) as it
01424     // resides at in the main function.
01425     UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
01426   } else {
01427     // Other funclets just need enough stack for outgoing call arguments.
01428     UsedSize = MF.getFrameInfo()->getMaxCallFrameSize();
01429   }
01430   // RBP is not included in the callee saved register block. After pushing RBP,
01431   // everything is 16 byte aligned. Everything we allocate before an outgoing
01432   // call must also be 16 byte aligned.
01433   unsigned FrameSizeMinusRBP = alignTo(CSSize + UsedSize, getStackAlignment());
01434   // Subtract out the size of the callee saved registers. This is how much stack
01435   // each funclet will allocate.
01436   return FrameSizeMinusRBP - CSSize;
01437 }
01438 
01439 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
01440                                     MachineBasicBlock &MBB) const {
01441   const MachineFrameInfo *MFI = MF.getFrameInfo();
01442   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
01443   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
01444   DebugLoc DL;
01445   if (MBBI != MBB.end())
01446     DL = MBBI->getDebugLoc();
01447   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
01448   const bool Is64BitILP32 = STI.isTarget64BitILP32();
01449   unsigned FramePtr = TRI->getFrameRegister(MF);
01450   unsigned MachineFramePtr =
01451       Is64BitILP32 ? getX86SubSuperRegister(FramePtr, 64) : FramePtr;
01452 
01453   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
01454   bool NeedsWinCFI =
01455       IsWin64Prologue && MF.getFunction()->needsUnwindTableEntry();
01456   bool IsFunclet = isFuncletReturnInstr(MBBI);
01457   MachineBasicBlock *TargetMBB = nullptr;
01458 
01459   // Get the number of bytes to allocate from the FrameInfo.
01460   uint64_t StackSize = MFI->getStackSize();
01461   uint64_t MaxAlign = calculateMaxStackAlign(MF);
01462   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
01463   uint64_t NumBytes = 0;
01464 
01465   if (MBBI->getOpcode() == X86::CATCHRET) {
01466     // SEH shouldn't use catchret.
01467     assert(!isAsynchronousEHPersonality(
01468                classifyEHPersonality(MF.getFunction()->getPersonalityFn())) &&
01469            "SEH should not use CATCHRET");
01470 
01471     NumBytes = getWinEHFuncletFrameSize(MF);
01472     assert(hasFP(MF) && "EH funclets without FP not yet implemented");
01473     TargetMBB = MBBI->getOperand(0).getMBB();
01474 
01475     // Pop EBP.
01476     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r),
01477             MachineFramePtr)
01478         .setMIFlag(MachineInstr::FrameDestroy);
01479   } else if (MBBI->getOpcode() == X86::CLEANUPRET) {
01480     NumBytes = getWinEHFuncletFrameSize(MF);
01481     assert(hasFP(MF) && "EH funclets without FP not yet implemented");
01482     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r),
01483             MachineFramePtr)
01484         .setMIFlag(MachineInstr::FrameDestroy);
01485   } else if (hasFP(MF)) {
01486     // Calculate required stack adjustment.
01487     uint64_t FrameSize = StackSize - SlotSize;
01488     NumBytes = FrameSize - CSSize;
01489 
01490     // Callee-saved registers were pushed on stack before the stack was
01491     // realigned.
01492     if (TRI->needsStackRealignment(MF) && !IsWin64Prologue)
01493       NumBytes = alignTo(FrameSize, MaxAlign);
01494 
01495     // Pop EBP.
01496     BuildMI(MBB, MBBI, DL,
01497             TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr)
01498         .setMIFlag(MachineInstr::FrameDestroy);
01499   } else {
01500     NumBytes = StackSize - CSSize;
01501   }
01502   uint64_t SEHStackAllocAmt = NumBytes;
01503 
01504   // Skip the callee-saved pop instructions.
01505   while (MBBI != MBB.begin()) {
01506     MachineBasicBlock::iterator PI = std::prev(MBBI);
01507     unsigned Opc = PI->getOpcode();
01508 
01509     if ((Opc != X86::POP32r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
01510         (Opc != X86::POP64r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
01511         Opc != X86::DBG_VALUE && !PI->isTerminator())
01512       break;
01513 
01514     --MBBI;
01515   }
01516   MachineBasicBlock::iterator FirstCSPop = MBBI;
01517 
01518   if (TargetMBB) {
01519     // Fill EAX/RAX with the address of the target block.
01520     unsigned ReturnReg = STI.is64Bit() ? X86::RAX : X86::EAX;
01521     if (STI.is64Bit()) {
01522       // LEA64r TargetMBB(%rip), %rax
01523       BuildMI(MBB, FirstCSPop, DL, TII.get(X86::LEA64r), ReturnReg)
01524           .addReg(X86::RIP)
01525           .addImm(0)
01526           .addReg(0)
01527           .addMBB(TargetMBB)
01528           .addReg(0);
01529     } else {
01530       // MOV32ri $TargetMBB, %eax
01531       BuildMI(MBB, FirstCSPop, DL, TII.get(X86::MOV32ri), ReturnReg)
01532           .addMBB(TargetMBB);
01533     }
01534     // Record that we've taken the address of TargetMBB and no longer just
01535     // reference it in a terminator.
01536     TargetMBB->setHasAddressTaken();
01537   }
01538 
01539   if (MBBI != MBB.end())
01540     DL = MBBI->getDebugLoc();
01541 
01542   // If there is an ADD32ri or SUB32ri of ESP immediately before this
01543   // instruction, merge the two instructions.
01544   if (NumBytes || MFI->hasVarSizedObjects())
01545     NumBytes += mergeSPUpdates(MBB, MBBI, true);
01546 
01547   // If dynamic alloca is used, then reset esp to point to the last callee-saved
01548   // slot before popping them off! Same applies for the case, when stack was
01549   // realigned. Don't do this if this was a funclet epilogue, since the funclets
01550   // will not do realignment or dynamic stack allocation.
01551   if ((TRI->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) &&
01552       !IsFunclet) {
01553     if (TRI->needsStackRealignment(MF))
01554       MBBI = FirstCSPop;
01555     unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
01556     uint64_t LEAAmount =
01557         IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
01558 
01559     // There are only two legal forms of epilogue:
01560     // - add SEHAllocationSize, %rsp
01561     // - lea SEHAllocationSize(%FramePtr), %rsp
01562     //
01563     // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
01564     // However, we may use this sequence if we have a frame pointer because the
01565     // effects of the prologue can safely be undone.
01566     if (LEAAmount != 0) {
01567       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
01568       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
01569                    FramePtr, false, LEAAmount);
01570       --MBBI;
01571     } else {
01572       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
01573       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
01574         .addReg(FramePtr);
01575       --MBBI;
01576     }
01577   } else if (NumBytes) {
01578     // Adjust stack pointer back: ESP += numbytes.
01579     emitSPUpdate(MBB, MBBI, NumBytes, /*InEpilogue=*/true);
01580     --MBBI;
01581   }
01582 
01583   // Windows unwinder will not invoke function's exception handler if IP is
01584   // either in prologue or in epilogue.  This behavior causes a problem when a
01585   // call immediately precedes an epilogue, because the return address points
01586   // into the epilogue.  To cope with that, we insert an epilogue marker here,
01587   // then replace it with a 'nop' if it ends up immediately after a CALL in the
01588   // final emitted code.
01589   if (NeedsWinCFI)
01590     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
01591 
01592   // Add the return addr area delta back since we are not tail calling.
01593   int Offset = -1 * X86FI->getTCReturnAddrDelta();
01594   assert(Offset >= 0 && "TCDelta should never be positive");
01595   if (Offset) {
01596     MBBI = MBB.getFirstTerminator();
01597 
01598     // Check for possible merge with preceding ADD instruction.
01599     Offset += mergeSPUpdates(MBB, MBBI, true);
01600     emitSPUpdate(MBB, MBBI, Offset, /*InEpilogue=*/true);
01601   }
01602 }
01603 
01604 // NOTE: this only has a subset of the full frame index logic. In
01605 // particular, the FI < 0 and AfterFPPop logic is handled in
01606 // X86RegisterInfo::eliminateFrameIndex, but not here. Possibly
01607 // (probably?) it should be moved into here.
01608 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
01609                                              unsigned &FrameReg) const {
01610   const MachineFrameInfo *MFI = MF.getFrameInfo();
01611 
01612   // We can't calculate offset from frame pointer if the stack is realigned,
01613   // so enforce usage of stack/base pointer.  The base pointer is used when we
01614   // have dynamic allocas in addition to dynamic realignment.
01615   if (TRI->hasBasePointer(MF))
01616     FrameReg = TRI->getBaseRegister();
01617   else if (TRI->needsStackRealignment(MF))
01618     FrameReg = TRI->getStackRegister();
01619   else
01620     FrameReg = TRI->getFrameRegister(MF);
01621 
01622   // Offset will hold the offset from the stack pointer at function entry to the
01623   // object.
01624   // We need to factor in additional offsets applied during the prologue to the
01625   // frame, base, and stack pointer depending on which is used.
01626   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
01627   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
01628   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
01629   uint64_t StackSize = MFI->getStackSize();
01630   bool HasFP = hasFP(MF);
01631   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
01632   int64_t FPDelta = 0;
01633 
01634   if (IsWin64Prologue) {
01635     assert(!MFI->hasCalls() || (StackSize % 16) == 8);
01636 
01637     // Calculate required stack adjustment.
01638     uint64_t FrameSize = StackSize - SlotSize;
01639     // If required, include space for extra hidden slot for stashing base pointer.
01640     if (X86FI->getRestoreBasePointer())
01641       FrameSize += SlotSize;
01642     uint64_t NumBytes = FrameSize - CSSize;
01643 
01644     uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
01645     if (FI && FI == X86FI->getFAIndex())
01646       return -SEHFrameOffset;
01647 
01648     // FPDelta is the offset from the "traditional" FP location of the old base
01649     // pointer followed by return address and the location required by the
01650     // restricted Win64 prologue.
01651     // Add FPDelta to all offsets below that go through the frame pointer.
01652     FPDelta = FrameSize - SEHFrameOffset;
01653     assert((!MFI->hasCalls() || (FPDelta % 16) == 0) &&
01654            "FPDelta isn't aligned per the Win64 ABI!");
01655   }
01656 
01657 
01658   if (TRI->hasBasePointer(MF)) {
01659     assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
01660     if (FI < 0) {
01661       // Skip the saved EBP.
01662       return Offset + SlotSize + FPDelta;
01663     } else {
01664       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
01665       return Offset + StackSize;
01666     }
01667   } else if (TRI->needsStackRealignment(MF)) {
01668     if (FI < 0) {
01669       // Skip the saved EBP.
01670       return Offset + SlotSize + FPDelta;
01671     } else {
01672       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
01673       return Offset + StackSize;
01674     }
01675     // FIXME: Support tail calls
01676   } else {
01677     if (!HasFP)
01678       return Offset + StackSize;
01679 
01680     // Skip the saved EBP.
01681     Offset += SlotSize;
01682 
01683     // Skip the RETADDR move area
01684     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
01685     if (TailCallReturnAddrDelta < 0)
01686       Offset -= TailCallReturnAddrDelta;
01687   }
01688 
01689   return Offset + FPDelta;
01690 }
01691 
01692 // Simplified from getFrameIndexReference keeping only StackPointer cases
01693 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
01694                                                    int FI,
01695                                                    unsigned &FrameReg) const {
01696   const MachineFrameInfo *MFI = MF.getFrameInfo();
01697   // Does not include any dynamic realign.
01698   const uint64_t StackSize = MFI->getStackSize();
01699   {
01700 #ifndef NDEBUG
01701     // LLVM arranges the stack as follows:
01702     //   ...
01703     //   ARG2
01704     //   ARG1
01705     //   RETADDR
01706     //   PUSH RBP   <-- RBP points here
01707     //   PUSH CSRs
01708     //   ~~~~~~~    <-- possible stack realignment (non-win64)
01709     //   ...
01710     //   STACK OBJECTS
01711     //   ...        <-- RSP after prologue points here
01712     //   ~~~~~~~    <-- possible stack realignment (win64)
01713     //
01714     // if (hasVarSizedObjects()):
01715     //   ...        <-- "base pointer" (ESI/RBX) points here
01716     //   DYNAMIC ALLOCAS
01717     //   ...        <-- RSP points here
01718     //
01719     // Case 1: In the simple case of no stack realignment and no dynamic
01720     // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
01721     // with fixed offsets from RSP.
01722     //
01723     // Case 2: In the case of stack realignment with no dynamic allocas, fixed
01724     // stack objects are addressed with RBP and regular stack objects with RSP.
01725     //
01726     // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
01727     // to address stack arguments for outgoing calls and nothing else. The "base
01728     // pointer" points to local variables, and RBP points to fixed objects.
01729     //
01730     // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
01731     // answer we give is relative to the SP after the prologue, and not the
01732     // SP in the middle of the function.
01733 
01734     assert((!MFI->isFixedObjectIndex(FI) || !TRI->needsStackRealignment(MF) ||
01735             STI.isTargetWin64()) &&
01736            "offset from fixed object to SP is not static");
01737 
01738     // We don't handle tail calls, and shouldn't be seeing them either.
01739     int TailCallReturnAddrDelta =
01740         MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
01741     assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
01742 #endif
01743   }
01744 
01745   // Fill in FrameReg output argument.
01746   FrameReg = TRI->getStackRegister();
01747 
01748   // This is how the math works out:
01749   //
01750   //  %rsp grows (i.e. gets lower) left to right. Each box below is
01751   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
01752   //  get to.
01753   //
01754   //    ----------------------------------
01755   //    | BP | Obj0 | Obj1 | ... | ObjN |
01756   //    ----------------------------------
01757   //    ^    ^      ^                   ^
01758   //    A    B      C                   E
01759   //
01760   // A is the incoming stack pointer.
01761   // (B - A) is the local area offset (-8 for x86-64) [1]
01762   // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
01763   //
01764   // |(E - B)| is the StackSize (absolute value, positive).  For a
01765   // stack that grown down, this works out to be (B - E). [3]
01766   //
01767   // E is also the value of %rsp after stack has been set up, and we
01768   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
01769   // (C - E) == (C - A) - (B - A) + (B - E)
01770   //            { Using [1], [2] and [3] above }
01771   //         == getObjectOffset - LocalAreaOffset + StackSize
01772   //
01773 
01774   // Get the Offset from the StackPointer
01775   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
01776 
01777   return Offset + StackSize;
01778 }
01779 
01780 bool X86FrameLowering::assignCalleeSavedSpillSlots(
01781     MachineFunction &MF, const TargetRegisterInfo *TRI,
01782     std::vector<CalleeSavedInfo> &CSI) const {
01783   MachineFrameInfo *MFI = MF.getFrameInfo();
01784   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
01785 
01786   unsigned CalleeSavedFrameSize = 0;
01787   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
01788 
01789   if (hasFP(MF)) {
01790     // emitPrologue always spills frame register the first thing.
01791     SpillSlotOffset -= SlotSize;
01792     MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
01793 
01794     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
01795     // the frame register, we can delete it from CSI list and not have to worry
01796     // about avoiding it later.
01797     unsigned FPReg = TRI->getFrameRegister(MF);
01798     for (unsigned i = 0; i < CSI.size(); ++i) {
01799       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
01800         CSI.erase(CSI.begin() + i);
01801         break;
01802       }
01803     }
01804   }
01805 
01806   // Assign slots for GPRs. It increases frame size.
01807   for (unsigned i = CSI.size(); i != 0; --i) {
01808     unsigned Reg = CSI[i - 1].getReg();
01809 
01810     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
01811       continue;
01812 
01813     SpillSlotOffset -= SlotSize;
01814     CalleeSavedFrameSize += SlotSize;
01815 
01816     int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
01817     CSI[i - 1].setFrameIdx(SlotIndex);
01818   }
01819 
01820   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
01821 
01822   // Assign slots for XMMs.
01823   for (unsigned i = CSI.size(); i != 0; --i) {
01824     unsigned Reg = CSI[i - 1].getReg();
01825     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
01826       continue;
01827 
01828     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01829     // ensure alignment
01830     SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
01831     // spill into slot
01832     SpillSlotOffset -= RC->getSize();
01833     int SlotIndex =
01834         MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
01835     CSI[i - 1].setFrameIdx(SlotIndex);
01836     MFI->ensureMaxAlignment(RC->getAlignment());
01837   }
01838 
01839   return true;
01840 }
01841 
01842 bool X86FrameLowering::spillCalleeSavedRegisters(
01843     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
01844     const std::vector<CalleeSavedInfo> &CSI,
01845     const TargetRegisterInfo *TRI) const {
01846   DebugLoc DL = MBB.findDebugLoc(MI);
01847 
01848   // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
01849   // for us, and there are no XMM CSRs on Win32.
01850   if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
01851     return true;
01852 
01853   // Push GPRs. It increases frame size.
01854   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
01855   for (unsigned i = CSI.size(); i != 0; --i) {
01856     unsigned Reg = CSI[i - 1].getReg();
01857 
01858     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
01859       continue;
01860     // Add the callee-saved register as live-in. It's killed at the spill.
01861     MBB.addLiveIn(Reg);
01862 
01863     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
01864       .setMIFlag(MachineInstr::FrameSetup);
01865   }
01866 
01867   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
01868   // It can be done by spilling XMMs to stack frame.
01869   for (unsigned i = CSI.size(); i != 0; --i) {
01870     unsigned Reg = CSI[i-1].getReg();
01871     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
01872       continue;
01873     // Add the callee-saved register as live-in. It's killed at the spill.
01874     MBB.addLiveIn(Reg);
01875     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01876 
01877     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
01878                             TRI);
01879     --MI;
01880     MI->setFlag(MachineInstr::FrameSetup);
01881     ++MI;
01882   }
01883 
01884   return true;
01885 }
01886 
01887 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
01888                                                MachineBasicBlock::iterator MI,
01889                                         const std::vector<CalleeSavedInfo> &CSI,
01890                                           const TargetRegisterInfo *TRI) const {
01891   if (CSI.empty())
01892     return false;
01893 
01894   if (isFuncletReturnInstr(MI) && STI.isOSWindows()) {
01895     // Don't restore CSRs in 32-bit EH funclets. Matches
01896     // spillCalleeSavedRegisters.
01897     if (STI.is32Bit())
01898       return true;
01899     // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
01900     // funclets. emitEpilogue transforms these to normal jumps.
01901     if (MI->getOpcode() == X86::CATCHRET) {
01902       const Function *Func = MBB.getParent()->getFunction();
01903       bool IsSEH = isAsynchronousEHPersonality(
01904           classifyEHPersonality(Func->getPersonalityFn()));
01905       if (IsSEH)
01906         return true;
01907     }
01908   }
01909 
01910   DebugLoc DL = MBB.findDebugLoc(MI);
01911 
01912   // Reload XMMs from stack frame.
01913   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01914     unsigned Reg = CSI[i].getReg();
01915     if (X86::GR64RegClass.contains(Reg) ||
01916         X86::GR32RegClass.contains(Reg))
01917       continue;
01918 
01919     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
01920     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
01921   }
01922 
01923   // POP GPRs.
01924   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
01925   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
01926     unsigned Reg = CSI[i].getReg();
01927     if (!X86::GR64RegClass.contains(Reg) &&
01928         !X86::GR32RegClass.contains(Reg))
01929       continue;
01930 
01931     BuildMI(MBB, MI, DL, TII.get(Opc), Reg)
01932         .setMIFlag(MachineInstr::FrameDestroy);
01933   }
01934   return true;
01935 }
01936 
01937 void X86FrameLowering::determineCalleeSaves(MachineFunction &MF,
01938                                             BitVector &SavedRegs,
01939                                             RegScavenger *RS) const {
01940   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
01941 
01942   MachineFrameInfo *MFI = MF.getFrameInfo();
01943 
01944   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
01945   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
01946 
01947   if (TailCallReturnAddrDelta < 0) {
01948     // create RETURNADDR area
01949     //   arg
01950     //   arg
01951     //   RETADDR
01952     //   { ...
01953     //     RETADDR area
01954     //     ...
01955     //   }
01956     //   [EBP]
01957     MFI->CreateFixedObject(-TailCallReturnAddrDelta,
01958                            TailCallReturnAddrDelta - SlotSize, true);
01959   }
01960 
01961   // Spill the BasePtr if it's used.
01962   if (TRI->hasBasePointer(MF)) {
01963     SavedRegs.set(TRI->getBaseRegister());
01964 
01965     // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
01966     if (MF.getMMI().hasEHFunclets()) {
01967       int FI = MFI->CreateSpillStackObject(SlotSize, SlotSize);
01968       X86FI->setHasSEHFramePtrSave(true);
01969       X86FI->setSEHFramePtrSaveIndex(FI);
01970     }
01971   }
01972 }
01973 
01974 static bool
01975 HasNestArgument(const MachineFunction *MF) {
01976   const Function *F = MF->getFunction();
01977   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
01978        I != E; I++) {
01979     if (I->hasNestAttr())
01980       return true;
01981   }
01982   return false;
01983 }
01984 
01985 /// GetScratchRegister - Get a temp register for performing work in the
01986 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
01987 /// and the properties of the function either one or two registers will be
01988 /// needed. Set primary to true for the first register, false for the second.
01989 static unsigned
01990 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
01991   CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
01992 
01993   // Erlang stuff.
01994   if (CallingConvention == CallingConv::HiPE) {
01995     if (Is64Bit)
01996       return Primary ? X86::R14 : X86::R13;
01997     else
01998       return Primary ? X86::EBX : X86::EDI;
01999   }
02000 
02001   if (Is64Bit) {
02002     if (IsLP64)
02003       return Primary ? X86::R11 : X86::R12;
02004     else
02005       return Primary ? X86::R11D : X86::R12D;
02006   }
02007 
02008   bool IsNested = HasNestArgument(&MF);
02009 
02010   if (CallingConvention == CallingConv::X86_FastCall ||
02011       CallingConvention == CallingConv::Fast) {
02012     if (IsNested)
02013       report_fatal_error("Segmented stacks does not support fastcall with "
02014                          "nested function.");
02015     return Primary ? X86::EAX : X86::ECX;
02016   }
02017   if (IsNested)
02018     return Primary ? X86::EDX : X86::EAX;
02019   return Primary ? X86::ECX : X86::EAX;
02020 }
02021 
02022 // The stack limit in the TCB is set to this many bytes above the actual stack
02023 // limit.
02024 static const uint64_t kSplitStackAvailable = 256;
02025 
02026 void X86FrameLowering::adjustForSegmentedStacks(
02027     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
02028   MachineFrameInfo *MFI = MF.getFrameInfo();
02029   uint64_t StackSize;
02030   unsigned TlsReg, TlsOffset;
02031   DebugLoc DL;
02032 
02033   // To support shrink-wrapping we would need to insert the new blocks
02034   // at the right place and update the branches to PrologueMBB.
02035   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
02036 
02037   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
02038   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
02039          "Scratch register is live-in");
02040 
02041   if (MF.getFunction()->isVarArg())
02042     report_fatal_error("Segmented stacks do not support vararg functions.");
02043   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
02044       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
02045       !STI.isTargetDragonFly())
02046     report_fatal_error("Segmented stacks not supported on this platform.");
02047 
02048   // Eventually StackSize will be calculated by a link-time pass; which will
02049   // also decide whether checking code needs to be injected into this particular
02050   // prologue.
02051   StackSize = MFI->getStackSize();
02052 
02053   // Do not generate a prologue for functions with a stack of size zero
02054   if (StackSize == 0)
02055     return;
02056 
02057   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
02058   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
02059   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
02060   bool IsNested = false;
02061 
02062   // We need to know if the function has a nest argument only in 64 bit mode.
02063   if (Is64Bit)
02064     IsNested = HasNestArgument(&MF);
02065 
02066   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
02067   // allocMBB needs to be last (terminating) instruction.
02068 
02069   for (const auto &LI : PrologueMBB.liveins()) {
02070     allocMBB->addLiveIn(LI);
02071     checkMBB->addLiveIn(LI);
02072   }
02073 
02074   if (IsNested)
02075     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
02076 
02077   MF.push_front(allocMBB);
02078   MF.push_front(checkMBB);
02079 
02080   // When the frame size is less than 256 we just compare the stack
02081   // boundary directly to the value of the stack pointer, per gcc.
02082   bool CompareStackPointer = StackSize < kSplitStackAvailable;
02083 
02084   // Read the limit off the current stacklet off the stack_guard location.
02085   if (Is64Bit) {
02086     if (STI.isTargetLinux()) {
02087       TlsReg = X86::FS;
02088       TlsOffset = IsLP64 ? 0x70 : 0x40;
02089     } else if (STI.isTargetDarwin()) {
02090       TlsReg = X86::GS;
02091       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
02092     } else if (STI.isTargetWin64()) {
02093       TlsReg = X86::GS;
02094       TlsOffset = 0x28; // pvArbitrary, reserved for application use
02095     } else if (STI.isTargetFreeBSD()) {
02096       TlsReg = X86::FS;
02097       TlsOffset = 0x18;
02098     } else if (STI.isTargetDragonFly()) {
02099       TlsReg = X86::FS;
02100       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
02101     } else {
02102       report_fatal_error("Segmented stacks not supported on this platform.");
02103     }
02104 
02105     if (CompareStackPointer)
02106       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
02107     else
02108       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
02109         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
02110 
02111     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
02112       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
02113   } else {
02114     if (STI.isTargetLinux()) {
02115       TlsReg = X86::GS;
02116       TlsOffset = 0x30;
02117     } else if (STI.isTargetDarwin()) {
02118       TlsReg = X86::GS;
02119       TlsOffset = 0x48 + 90*4;
02120     } else if (STI.isTargetWin32()) {
02121       TlsReg = X86::FS;
02122       TlsOffset = 0x14; // pvArbitrary, reserved for application use
02123     } else if (STI.isTargetDragonFly()) {
02124       TlsReg = X86::FS;
02125       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
02126     } else if (STI.isTargetFreeBSD()) {
02127       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
02128     } else {
02129       report_fatal_error("Segmented stacks not supported on this platform.");
02130     }
02131 
02132     if (CompareStackPointer)
02133       ScratchReg = X86::ESP;
02134     else
02135       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
02136         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
02137 
02138     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
02139         STI.isTargetDragonFly()) {
02140       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
02141         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
02142     } else if (STI.isTargetDarwin()) {
02143 
02144       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
02145       unsigned ScratchReg2;
02146       bool SaveScratch2;
02147       if (CompareStackPointer) {
02148         // The primary scratch register is available for holding the TLS offset.
02149         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
02150         SaveScratch2 = false;
02151       } else {
02152         // Need to use a second register to hold the TLS offset
02153         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
02154 
02155         // Unfortunately, with fastcc the second scratch register may hold an
02156         // argument.
02157         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
02158       }
02159 
02160       // If Scratch2 is live-in then it needs to be saved.
02161       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
02162              "Scratch register is live-in and not saved");
02163 
02164       if (SaveScratch2)
02165         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
02166           .addReg(ScratchReg2, RegState::Kill);
02167 
02168       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
02169         .addImm(TlsOffset);
02170       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
02171         .addReg(ScratchReg)
02172         .addReg(ScratchReg2).addImm(1).addReg(0)
02173         .addImm(0)
02174         .addReg(TlsReg);
02175 
02176       if (SaveScratch2)
02177         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
02178     }
02179   }
02180 
02181   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
02182   // It jumps to normal execution of the function body.
02183   BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&PrologueMBB);
02184 
02185   // On 32 bit we first push the arguments size and then the frame size. On 64
02186   // bit, we pass the stack frame size in r10 and the argument size in r11.
02187   if (Is64Bit) {
02188     // Functions with nested arguments use R10, so it needs to be saved across
02189     // the call to _morestack
02190 
02191     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
02192     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
02193     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
02194     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
02195     const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
02196 
02197     if (IsNested)
02198       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
02199 
02200     BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
02201       .addImm(StackSize);
02202     BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
02203       .addImm(X86FI->getArgumentStackSize());
02204   } else {
02205     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
02206       .addImm(X86FI->getArgumentStackSize());
02207     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
02208       .addImm(StackSize);
02209   }
02210 
02211   // __morestack is in libgcc
02212   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
02213     // Under the large code model, we cannot assume that __morestack lives
02214     // within 2^31 bytes of the call site, so we cannot use pc-relative
02215     // addressing. We cannot perform the call via a temporary register,
02216     // as the rax register may be used to store the static chain, and all
02217     // other suitable registers may be either callee-save or used for
02218     // parameter passing. We cannot use the stack at this point either
02219     // because __morestack manipulates the stack directly.
02220     //
02221     // To avoid these issues, perform an indirect call via a read-only memory
02222     // location containing the address.
02223     //
02224     // This solution is not perfect, as it assumes that the .rodata section
02225     // is laid out within 2^31 bytes of each function body, but this seems
02226     // to be sufficient for JIT.
02227     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
02228         .addReg(X86::RIP)
02229         .addImm(0)
02230         .addReg(0)
02231         .addExternalSymbol("__morestack_addr")
02232         .addReg(0);
02233     MF.getMMI().setUsesMorestackAddr(true);
02234   } else {
02235     if (Is64Bit)
02236       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
02237         .addExternalSymbol("__morestack");
02238     else
02239       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
02240         .addExternalSymbol("__morestack");
02241   }
02242 
02243   if (IsNested)
02244     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
02245   else
02246     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
02247 
02248   allocMBB->addSuccessor(&PrologueMBB);
02249 
02250   checkMBB->addSuccessor(allocMBB);
02251   checkMBB->addSuccessor(&PrologueMBB);
02252 
02253 #ifdef XDEBUG
02254   MF.verify();
02255 #endif
02256 }
02257 
02258 /// Erlang programs may need a special prologue to handle the stack size they
02259 /// might need at runtime. That is because Erlang/OTP does not implement a C
02260 /// stack but uses a custom implementation of hybrid stack/heap architecture.
02261 /// (for more information see Eric Stenman's Ph.D. thesis:
02262 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
02263 ///
02264 /// CheckStack:
02265 ///       temp0 = sp - MaxStack
02266 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
02267 /// OldStart:
02268 ///       ...
02269 /// IncStack:
02270 ///       call inc_stack   # doubles the stack space
02271 ///       temp0 = sp - MaxStack
02272 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
02273 void X86FrameLowering::adjustForHiPEPrologue(
02274     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
02275   MachineFrameInfo *MFI = MF.getFrameInfo();
02276   DebugLoc DL;
02277 
02278   // To support shrink-wrapping we would need to insert the new blocks
02279   // at the right place and update the branches to PrologueMBB.
02280   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
02281 
02282   // HiPE-specific values
02283   const unsigned HipeLeafWords = 24;
02284   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
02285   const unsigned Guaranteed = HipeLeafWords * SlotSize;
02286   unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
02287                             MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
02288   unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
02289 
02290   assert(STI.isTargetLinux() &&
02291          "HiPE prologue is only supported on Linux operating systems.");
02292 
02293   // Compute the largest caller's frame that is needed to fit the callees'
02294   // frames. This 'MaxStack' is computed from:
02295   //
02296   // a) the fixed frame size, which is the space needed for all spilled temps,
02297   // b) outgoing on-stack parameter areas, and
02298   // c) the minimum stack space this function needs to make available for the
02299   //    functions it calls (a tunable ABI property).
02300   if (MFI->hasCalls()) {
02301     unsigned MoreStackForCalls = 0;
02302 
02303     for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
02304          MBBI != MBBE; ++MBBI)
02305       for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
02306            MI != ME; ++MI) {
02307         if (!MI->isCall())
02308           continue;
02309 
02310         // Get callee operand.
02311         const MachineOperand &MO = MI->getOperand(0);
02312 
02313         // Only take account of global function calls (no closures etc.).
02314         if (!MO.isGlobal())
02315           continue;
02316 
02317         const Function *F = dyn_cast<Function>(MO.getGlobal());
02318         if (!F)
02319           continue;
02320 
02321         // Do not update 'MaxStack' for primitive and built-in functions
02322         // (encoded with names either starting with "erlang."/"bif_" or not
02323         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
02324         // "_", such as the BIF "suspend_0") as they are executed on another
02325         // stack.
02326         if (F->getName().find("erlang.") != StringRef::npos ||
02327             F->getName().find("bif_") != StringRef::npos ||
02328             F->getName().find_first_of("._") == StringRef::npos)
02329           continue;
02330 
02331         unsigned CalleeStkArity =
02332           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
02333         if (HipeLeafWords - 1 > CalleeStkArity)
02334           MoreStackForCalls = std::max(MoreStackForCalls,
02335                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
02336       }
02337     MaxStack += MoreStackForCalls;
02338   }
02339 
02340   // If the stack frame needed is larger than the guaranteed then runtime checks
02341   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
02342   if (MaxStack > Guaranteed) {
02343     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
02344     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
02345 
02346     for (const auto &LI : PrologueMBB.liveins()) {
02347       stackCheckMBB->addLiveIn(LI);
02348       incStackMBB->addLiveIn(LI);
02349     }
02350 
02351     MF.push_front(incStackMBB);
02352     MF.push_front(stackCheckMBB);
02353 
02354     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
02355     unsigned LEAop, CMPop, CALLop;
02356     if (Is64Bit) {
02357       SPReg = X86::RSP;
02358       PReg  = X86::RBP;
02359       LEAop = X86::LEA64r;
02360       CMPop = X86::CMP64rm;
02361       CALLop = X86::CALL64pcrel32;
02362       SPLimitOffset = 0x90;
02363     } else {
02364       SPReg = X86::ESP;
02365       PReg  = X86::EBP;
02366       LEAop = X86::LEA32r;
02367       CMPop = X86::CMP32rm;
02368       CALLop = X86::CALLpcrel32;
02369       SPLimitOffset = 0x4c;
02370     }
02371 
02372     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
02373     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
02374            "HiPE prologue scratch register is live-in");
02375 
02376     // Create new MBB for StackCheck:
02377     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
02378                  SPReg, false, -MaxStack);
02379     // SPLimitOffset is in a fixed heap location (pointed by BP).
02380     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
02381                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
02382     BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&PrologueMBB);
02383 
02384     // Create new MBB for IncStack:
02385     BuildMI(incStackMBB, DL, TII.get(CALLop)).
02386       addExternalSymbol("inc_stack_0");
02387     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
02388                  SPReg, false, -MaxStack);
02389     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
02390                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
02391     BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
02392 
02393     stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100});
02394     stackCheckMBB->addSuccessor(incStackMBB, {1, 100});
02395     incStackMBB->addSuccessor(&PrologueMBB, {99, 100});
02396     incStackMBB->addSuccessor(incStackMBB, {1, 100});
02397   }
02398 #ifdef XDEBUG
02399   MF.verify();
02400 #endif
02401 }
02402 
02403 bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
02404     MachineBasicBlock::iterator MBBI, DebugLoc DL, int Offset) const {
02405 
02406   if (Offset <= 0)
02407     return false;
02408 
02409   if (Offset % SlotSize)
02410     return false;
02411 
02412   int NumPops = Offset / SlotSize;
02413   // This is only worth it if we have at most 2 pops.
02414   if (NumPops != 1 && NumPops != 2)
02415     return false;
02416 
02417   // Handle only the trivial case where the adjustment directly follows
02418   // a call. This is the most common one, anyway.
02419   if (MBBI == MBB.begin())
02420     return false;
02421   MachineBasicBlock::iterator Prev = std::prev(MBBI);
02422   if (!Prev->isCall() || !Prev->getOperand(1).isRegMask())
02423     return false;
02424 
02425   unsigned Regs[2];
02426   unsigned FoundRegs = 0;
02427 
02428   auto RegMask = Prev->getOperand(1);
02429 
02430   auto &RegClass =
02431       Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
02432   // Try to find up to NumPops free registers.
02433   for (auto Candidate : RegClass) {
02434 
02435     // Poor man's liveness:
02436     // Since we're immediately after a call, any register that is clobbered
02437     // by the call and not defined by it can be considered dead.
02438     if (!RegMask.clobbersPhysReg(Candidate))
02439       continue;
02440 
02441     bool IsDef = false;
02442     for (const MachineOperand &MO : Prev->implicit_operands()) {
02443       if (MO.isReg() && MO.isDef() && MO.getReg() == Candidate) {
02444         IsDef = true;
02445         break;
02446       }
02447     }
02448 
02449     if (IsDef)
02450       continue;
02451 
02452     Regs[FoundRegs++] = Candidate;
02453     if (FoundRegs == (unsigned)NumPops)
02454       break;
02455   }
02456 
02457   if (FoundRegs == 0)
02458     return false;
02459 
02460   // If we found only one free register, but need two, reuse the same one twice.
02461   while (FoundRegs < (unsigned)NumPops)
02462     Regs[FoundRegs++] = Regs[0];
02463 
02464   for (int i = 0; i < NumPops; ++i)
02465     BuildMI(MBB, MBBI, DL, 
02466             TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r), Regs[i]);
02467 
02468   return true;
02469 }
02470 
02471 void X86FrameLowering::
02472 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
02473                               MachineBasicBlock::iterator I) const {
02474   bool reserveCallFrame = hasReservedCallFrame(MF);
02475   unsigned Opcode = I->getOpcode();
02476   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
02477   DebugLoc DL = I->getDebugLoc();
02478   uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
02479   uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
02480   I = MBB.erase(I);
02481 
02482   if (!reserveCallFrame) {
02483     // If the stack pointer can be changed after prologue, turn the
02484     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
02485     // adjcallstackdown instruction into 'add ESP, <amt>'
02486 
02487     // We need to keep the stack aligned properly.  To do this, we round the
02488     // amount of space needed for the outgoing arguments up to the next
02489     // alignment boundary.
02490     unsigned StackAlign = getStackAlignment();
02491     Amount = alignTo(Amount, StackAlign);
02492 
02493     MachineModuleInfo &MMI = MF.getMMI();
02494     const Function *Fn = MF.getFunction();
02495     bool WindowsCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
02496     bool DwarfCFI = !WindowsCFI && 
02497                     (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
02498 
02499     // If we have any exception handlers in this function, and we adjust
02500     // the SP before calls, we may need to indicate this to the unwinder
02501     // using GNU_ARGS_SIZE. Note that this may be necessary even when
02502     // Amount == 0, because the preceding function may have set a non-0
02503     // GNU_ARGS_SIZE.
02504     // TODO: We don't need to reset this between subsequent functions,
02505     // if it didn't change.
02506     bool HasDwarfEHHandlers = !WindowsCFI &&
02507                               !MF.getMMI().getLandingPads().empty();
02508 
02509     if (HasDwarfEHHandlers && !isDestroy &&
02510         MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences())
02511       BuildCFI(MBB, I, DL,
02512                MCCFIInstruction::createGnuArgsSize(nullptr, Amount));
02513 
02514     if (Amount == 0)
02515       return;
02516 
02517     // Factor out the amount that gets handled inside the sequence
02518     // (Pushes of argument for frame setup, callee pops for frame destroy)
02519     Amount -= InternalAmt;
02520 
02521     // TODO: This is needed only if we require precise CFA.
02522     // If this is a callee-pop calling convention, emit a CFA adjust for
02523     // the amount the callee popped.
02524     if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF))
02525       BuildCFI(MBB, I, DL, 
02526                MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt));
02527 
02528     if (Amount) {
02529       // Add Amount to SP to destroy a frame, and subtract to setup.
02530       int Offset = isDestroy ? Amount : -Amount;
02531 
02532       if (!(Fn->optForMinSize() && 
02533             adjustStackWithPops(MBB, I, DL, Offset)))
02534         BuildStackAdjustment(MBB, I, DL, Offset, /*InEpilogue=*/false);
02535     }
02536 
02537     if (DwarfCFI && !hasFP(MF)) {
02538       // If we don't have FP, but need to generate unwind information,
02539       // we need to set the correct CFA offset after the stack adjustment.
02540       // How much we adjust the CFA offset depends on whether we're emitting
02541       // CFI only for EH purposes or for debugging. EH only requires the CFA
02542       // offset to be correct at each call site, while for debugging we want
02543       // it to be more precise.
02544       int CFAOffset = Amount;
02545       // TODO: When not using precise CFA, we also need to adjust for the
02546       // InternalAmt here.
02547 
02548       if (CFAOffset) {
02549         CFAOffset = isDestroy ? -CFAOffset : CFAOffset;
02550         BuildCFI(MBB, I, DL, 
02551                  MCCFIInstruction::createAdjustCfaOffset(nullptr, CFAOffset));
02552       }
02553     }
02554 
02555     return;
02556   }
02557 
02558   if (isDestroy && InternalAmt) {
02559     // If we are performing frame pointer elimination and if the callee pops
02560     // something off the stack pointer, add it back.  We do this until we have
02561     // more advanced stack pointer tracking ability.
02562     // We are not tracking the stack pointer adjustment by the callee, so make
02563     // sure we restore the stack pointer immediately after the call, there may
02564     // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
02565     MachineBasicBlock::iterator B = MBB.begin();
02566     while (I != B && !std::prev(I)->isCall())
02567       --I;
02568     BuildStackAdjustment(MBB, I, DL, -InternalAmt, /*InEpilogue=*/false);
02569   }
02570 }
02571 
02572 bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
02573   assert(MBB.getParent() && "Block is not attached to a function!");
02574 
02575   // Win64 has strict requirements in terms of epilogue and we are
02576   // not taking a chance at messing with them.
02577   // I.e., unless this block is already an exit block, we can't use
02578   // it as an epilogue.
02579   if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
02580     return false;
02581 
02582   if (canUseLEAForSPInEpilogue(*MBB.getParent()))
02583     return true;
02584 
02585   // If we cannot use LEA to adjust SP, we may need to use ADD, which
02586   // clobbers the EFLAGS. Check that we do not need to preserve it,
02587   // otherwise, conservatively assume this is not
02588   // safe to insert the epilogue here.
02589   return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
02590 }
02591 
02592 bool X86FrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
02593   // If we may need to emit frameless compact unwind information, give
02594   // up as this is currently broken: PR25614.
02595   return (MF.getFunction()->hasFnAttribute(Attribute::NoUnwind) || hasFP(MF)) &&
02596          // The lowering of segmented stack and HiPE only support entry blocks
02597          // as prologue blocks: PR26107.
02598          // This limitation may be lifted if we fix:
02599          // - adjustForSegmentedStacks
02600          // - adjustForHiPEPrologue
02601          MF.getFunction()->getCallingConv() != CallingConv::HiPE &&
02602          !MF.shouldSplitStack();
02603 }
02604 
02605 MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers(
02606     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
02607     DebugLoc DL, bool RestoreSP) const {
02608   assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
02609   assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
02610   assert(STI.is32Bit() && !Uses64BitFramePtr &&
02611          "restoring EBP/ESI on non-32-bit target");
02612 
02613   MachineFunction &MF = *MBB.getParent();
02614   unsigned FramePtr = TRI->getFrameRegister(MF);
02615   unsigned BasePtr = TRI->getBaseRegister();
02616   WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
02617   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
02618   MachineFrameInfo *MFI = MF.getFrameInfo();
02619 
02620   // FIXME: Don't set FrameSetup flag in catchret case.
02621 
02622   int FI = FuncInfo.EHRegNodeFrameIndex;
02623   int EHRegSize = MFI->getObjectSize(FI);
02624 
02625   if (RestoreSP) {
02626     // MOV32rm -EHRegSize(%ebp), %esp
02627     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP),
02628                  X86::EBP, true, -EHRegSize)
02629         .setMIFlag(MachineInstr::FrameSetup);
02630   }
02631 
02632   unsigned UsedReg;
02633   int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg);
02634   int EndOffset = -EHRegOffset - EHRegSize;
02635   FuncInfo.EHRegNodeEndOffset = EndOffset;
02636 
02637   if (UsedReg == FramePtr) {
02638     // ADD $offset, %ebp
02639     unsigned ADDri = getADDriOpcode(false, EndOffset);
02640     BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr)
02641         .addReg(FramePtr)
02642         .addImm(EndOffset)
02643         .setMIFlag(MachineInstr::FrameSetup)
02644         ->getOperand(3)
02645         .setIsDead();
02646     assert(EndOffset >= 0 &&
02647            "end of registration object above normal EBP position!");
02648   } else if (UsedReg == BasePtr) {
02649     // LEA offset(%ebp), %esi
02650     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr),
02651                  FramePtr, false, EndOffset)
02652         .setMIFlag(MachineInstr::FrameSetup);
02653     // MOV32rm SavedEBPOffset(%esi), %ebp
02654     assert(X86FI->getHasSEHFramePtrSave());
02655     int Offset =
02656         getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg);
02657     assert(UsedReg == BasePtr);
02658     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr),
02659                  UsedReg, true, Offset)
02660         .setMIFlag(MachineInstr::FrameSetup);
02661   } else {
02662     llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
02663   }
02664   return MBBI;
02665 }
02666 
02667 unsigned X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const {
02668   // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
02669   unsigned Offset = 16;
02670   // RBP is immediately pushed.
02671   Offset += SlotSize;
02672   // All callee-saved registers are then pushed.
02673   Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
02674   // Every funclet allocates enough stack space for the largest outgoing call.
02675   Offset += getWinEHFuncletFrameSize(MF);
02676   return Offset;
02677 }
02678 
02679 void X86FrameLowering::processFunctionBeforeFrameFinalized(
02680     MachineFunction &MF, RegScavenger *RS) const {
02681   // If this function isn't doing Win64-style C++ EH, we don't need to do
02682   // anything.
02683   const Function *Fn = MF.getFunction();
02684   if (!STI.is64Bit() || !MF.getMMI().hasEHFunclets() ||
02685       classifyEHPersonality(Fn->getPersonalityFn()) != EHPersonality::MSVC_CXX)
02686     return;
02687 
02688   // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
02689   // relative to RSP after the prologue.  Find the offset of the last fixed
02690   // object, so that we can allocate a slot immediately following it. If there
02691   // were no fixed objects, use offset -SlotSize, which is immediately after the
02692   // return address. Fixed objects have negative frame indices.
02693   MachineFrameInfo *MFI = MF.getFrameInfo();
02694   int64_t MinFixedObjOffset = -SlotSize;
02695   for (int I = MFI->getObjectIndexBegin(); I < 0; ++I)
02696     MinFixedObjOffset = std::min(MinFixedObjOffset, MFI->getObjectOffset(I));
02697 
02698   int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
02699   int UnwindHelpFI =
02700       MFI->CreateFixedObject(SlotSize, UnwindHelpOffset, /*Immutable=*/false);
02701   MF.getWinEHFuncInfo()->UnwindHelpFrameIdx = UnwindHelpFI;
02702 
02703   // Store -2 into UnwindHelp on function entry. We have to scan forwards past
02704   // other frame setup instructions.
02705   MachineBasicBlock &MBB = MF.front();
02706   auto MBBI = MBB.begin();
02707   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
02708     ++MBBI;
02709 
02710   DebugLoc DL = MBB.findDebugLoc(MBBI);
02711   addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),
02712                     UnwindHelpFI)
02713       .addImm(-2);
02714 }