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