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