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