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