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