f049635a5fee3a806ab056b28e0cd3303fc676ab
[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/Analysis/EHPersonalities.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/WinEHFuncInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/Debug.h"
34 #include <cstdlib>
35
36 using namespace llvm;
37
38 X86FrameLowering::X86FrameLowering(const X86Subtarget &STI,
39                                    unsigned StackAlignOverride)
40     : TargetFrameLowering(StackGrowsDown, StackAlignOverride,
41                           STI.is64Bit() ? -8 : -4),
42       STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {
43   // Cache a bunch of frame-related predicates for this subtarget.
44   SlotSize = TRI->getSlotSize();
45   Is64Bit = STI.is64Bit();
46   IsLP64 = STI.isTarget64BitLP64();
47   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
48   Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
49   StackPtr = TRI->getStackRegister();
50 }
51
52 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
53   return !MF.getFrameInfo()->hasVarSizedObjects() &&
54          !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
55 }
56
57 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
58 /// call frame pseudos can be simplified.  Having a FP, as in the default
59 /// implementation, is not sufficient here since we can't always use it.
60 /// Use a more nuanced condition.
61 bool
62 X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
63   return hasReservedCallFrame(MF) ||
64          (hasFP(MF) && !TRI->needsStackRealignment(MF)) ||
65          TRI->hasBasePointer(MF);
66 }
67
68 // needsFrameIndexResolution - Do we need to perform FI resolution for
69 // this function. Normally, this is required only when the function
70 // has any stack objects. However, FI resolution actually has another job,
71 // not apparent from the title - it resolves callframesetup/destroy 
72 // that were not simplified earlier.
73 // So, this is required for x86 functions that have push sequences even
74 // when there are no stack objects.
75 bool
76 X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
77   return MF.getFrameInfo()->hasStackObjects() ||
78          MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
79 }
80
81 /// hasFP - Return true if the specified function should have a dedicated frame
82 /// pointer register.  This is true if the function has variable sized allocas
83 /// or if frame pointer elimination is disabled.
84 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
85   const MachineFrameInfo *MFI = MF.getFrameInfo();
86   const MachineModuleInfo &MMI = MF.getMMI();
87
88   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
89           TRI->needsStackRealignment(MF) ||
90           MFI->hasVarSizedObjects() ||
91           MFI->isFrameAddressTaken() || MFI->hasOpaqueSPAdjustment() ||
92           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
93           MMI.callsUnwindInit() || MMI.hasEHFunclets() || MMI.callsEHReturn() ||
94           MFI->hasStackMap() || MFI->hasPatchPoint());
95 }
96
97 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
98   if (IsLP64) {
99     if (isInt<8>(Imm))
100       return X86::SUB64ri8;
101     return X86::SUB64ri32;
102   } else {
103     if (isInt<8>(Imm))
104       return X86::SUB32ri8;
105     return X86::SUB32ri;
106   }
107 }
108
109 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
110   if (IsLP64) {
111     if (isInt<8>(Imm))
112       return X86::ADD64ri8;
113     return X86::ADD64ri32;
114   } else {
115     if (isInt<8>(Imm))
116       return X86::ADD32ri8;
117     return X86::ADD32ri;
118   }
119 }
120
121 static unsigned getSUBrrOpcode(unsigned isLP64) {
122   return isLP64 ? X86::SUB64rr : X86::SUB32rr;
123 }
124
125 static unsigned getADDrrOpcode(unsigned isLP64) {
126   return isLP64 ? X86::ADD64rr : X86::ADD32rr;
127 }
128
129 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
130   if (IsLP64) {
131     if (isInt<8>(Imm))
132       return X86::AND64ri8;
133     return X86::AND64ri32;
134   }
135   if (isInt<8>(Imm))
136     return X86::AND32ri8;
137   return X86::AND32ri;
138 }
139
140 static unsigned getLEArOpcode(unsigned IsLP64) {
141   return IsLP64 ? X86::LEA64r : X86::LEA32r;
142 }
143
144 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
145 /// when it reaches the "return" instruction. We can then pop a stack object
146 /// to this register without worry about clobbering it.
147 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
148                                        MachineBasicBlock::iterator &MBBI,
149                                        const X86RegisterInfo *TRI,
150                                        bool Is64Bit) {
151   const MachineFunction *MF = MBB.getParent();
152   const Function *F = MF->getFunction();
153   if (!F || MF->getMMI().callsEHReturn())
154     return 0;
155
156   const TargetRegisterClass &AvailableRegs = *TRI->getGPRsForTailCall(*MF);
157
158   unsigned Opc = MBBI->getOpcode();
159   switch (Opc) {
160   default: return 0;
161   case X86::RETL:
162   case X86::RETQ:
163   case X86::RETIL:
164   case X86::RETIQ:
165   case X86::TCRETURNdi:
166   case X86::TCRETURNri:
167   case X86::TCRETURNmi:
168   case X86::TCRETURNdi64:
169   case X86::TCRETURNri64:
170   case X86::TCRETURNmi64:
171   case X86::EH_RETURN:
172   case X86::EH_RETURN64: {
173     SmallSet<uint16_t, 8> Uses;
174     for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
175       MachineOperand &MO = MBBI->getOperand(i);
176       if (!MO.isReg() || MO.isDef())
177         continue;
178       unsigned Reg = MO.getReg();
179       if (!Reg)
180         continue;
181       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
182         Uses.insert(*AI);
183     }
184
185     for (auto CS : AvailableRegs)
186       if (!Uses.count(CS) && CS != X86::RIP)
187         return CS;
188   }
189   }
190
191   return 0;
192 }
193
194 static bool isEAXLiveIn(MachineFunction &MF) {
195   for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
196        EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
197     unsigned Reg = II->first;
198
199     if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
200         Reg == X86::AH || Reg == X86::AL)
201       return true;
202   }
203
204   return false;
205 }
206
207 /// Check if the flags need to be preserved before the terminators.
208 /// This would be the case, if the eflags is live-in of the region
209 /// composed by the terminators or live-out of that region, without
210 /// being defined by a terminator.
211 static bool
212 flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) {
213   for (const MachineInstr &MI : MBB.terminators()) {
214     bool BreakNext = false;
215     for (const MachineOperand &MO : MI.operands()) {
216       if (!MO.isReg())
217         continue;
218       unsigned Reg = MO.getReg();
219       if (Reg != X86::EFLAGS)
220         continue;
221
222       // This terminator needs an eflags that is not defined
223       // by a previous another terminator:
224       // EFLAGS is live-in of the region composed by the terminators.
225       if (!MO.isDef())
226         return true;
227       // This terminator defines the eflags, i.e., we don't need to preserve it.
228       // However, we still need to check this specific terminator does not
229       // read a live-in value.
230       BreakNext = true;
231     }
232     // We found a definition of the eflags, no need to preserve them.
233     if (BreakNext)
234       return false;
235   }
236
237   // None of the terminators use or define the eflags.
238   // Check if they are live-out, that would imply we need to preserve them.
239   for (const MachineBasicBlock *Succ : MBB.successors())
240     if (Succ->isLiveIn(X86::EFLAGS))
241       return true;
242
243   return false;
244 }
245
246 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
247 /// stack pointer by a constant value.
248 void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
249                                     MachineBasicBlock::iterator &MBBI,
250                                     int64_t NumBytes, bool InEpilogue) const {
251   bool isSub = NumBytes < 0;
252   uint64_t Offset = isSub ? -NumBytes : NumBytes;
253
254   uint64_t Chunk = (1LL << 31) - 1;
255   DebugLoc DL = MBB.findDebugLoc(MBBI);
256
257   while (Offset) {
258     if (Offset > Chunk) {
259       // Rather than emit a long series of instructions for large offsets,
260       // load the offset into a register and do one sub/add
261       unsigned Reg = 0;
262
263       if (isSub && !isEAXLiveIn(*MBB.getParent()))
264         Reg = (unsigned)(Is64Bit ? X86::RAX : X86::EAX);
265       else
266         Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
267
268       if (Reg) {
269         unsigned Opc = Is64Bit ? X86::MOV64ri : X86::MOV32ri;
270         BuildMI(MBB, MBBI, DL, TII.get(Opc), Reg)
271           .addImm(Offset);
272         Opc = isSub
273           ? getSUBrrOpcode(Is64Bit)
274           : getADDrrOpcode(Is64Bit);
275         MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
276           .addReg(StackPtr)
277           .addReg(Reg);
278         MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
279         Offset = 0;
280         continue;
281       }
282     }
283
284     uint64_t ThisVal = std::min(Offset, Chunk);
285     if (ThisVal == (Is64Bit ? 8 : 4)) {
286       // Use push / pop instead.
287       unsigned Reg = isSub
288         ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
289         : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
290       if (Reg) {
291         unsigned Opc = isSub
292           ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
293           : (Is64Bit ? X86::POP64r  : X86::POP32r);
294         MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
295           .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
296         if (isSub)
297           MI->setFlag(MachineInstr::FrameSetup);
298         else
299           MI->setFlag(MachineInstr::FrameDestroy);
300         Offset -= ThisVal;
301         continue;
302       }
303     }
304
305     MachineInstrBuilder MI = BuildStackAdjustment(
306         MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue);
307     if (isSub)
308       MI.setMIFlag(MachineInstr::FrameSetup);
309     else
310       MI.setMIFlag(MachineInstr::FrameDestroy);
311
312     Offset -= ThisVal;
313   }
314 }
315
316 MachineInstrBuilder X86FrameLowering::BuildStackAdjustment(
317     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, DebugLoc DL,
318     int64_t Offset, bool InEpilogue) const {
319   assert(Offset != 0 && "zero offset stack adjustment requested");
320
321   // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue
322   // is tricky.
323   bool UseLEA;
324   if (!InEpilogue) {
325     // Check if inserting the prologue at the beginning
326     // of MBB would require to use LEA operations.
327     // We need to use LEA operations if EFLAGS is live in, because
328     // it means an instruction will read it before it gets defined.
329     UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS);
330   } else {
331     // If we can use LEA for SP but we shouldn't, check that none
332     // of the terminators uses the eflags. Otherwise we will insert
333     // a ADD that will redefine the eflags and break the condition.
334     // Alternatively, we could move the ADD, but this may not be possible
335     // and is an optimization anyway.
336     UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent());
337     if (UseLEA && !STI.useLeaForSP())
338       UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB);
339     // If that assert breaks, that means we do not do the right thing
340     // in canUseAsEpilogue.
341     assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) &&
342            "We shouldn't have allowed this insertion point");
343   }
344
345   MachineInstrBuilder MI;
346   if (UseLEA) {
347     MI = addRegOffset(BuildMI(MBB, MBBI, DL,
348                               TII.get(getLEArOpcode(Uses64BitFramePtr)),
349                               StackPtr),
350                       StackPtr, false, Offset);
351   } else {
352     bool IsSub = Offset < 0;
353     uint64_t AbsOffset = IsSub ? -Offset : Offset;
354     unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr, AbsOffset)
355                          : getADDriOpcode(Uses64BitFramePtr, AbsOffset);
356     MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
357              .addReg(StackPtr)
358              .addImm(AbsOffset);
359     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
360   }
361   return MI;
362 }
363
364 int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
365                                      MachineBasicBlock::iterator &MBBI,
366                                      bool doMergeWithPrevious) const {
367   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
368       (!doMergeWithPrevious && MBBI == MBB.end()))
369     return 0;
370
371   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
372   MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
373                                                        : std::next(MBBI);
374   unsigned Opc = PI->getOpcode();
375   int Offset = 0;
376
377   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
378        Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
379        Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
380       PI->getOperand(0).getReg() == StackPtr){
381     Offset += PI->getOperand(2).getImm();
382     MBB.erase(PI);
383     if (!doMergeWithPrevious) MBBI = NI;
384   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
385               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
386              PI->getOperand(0).getReg() == StackPtr) {
387     Offset -= PI->getOperand(2).getImm();
388     MBB.erase(PI);
389     if (!doMergeWithPrevious) MBBI = NI;
390   }
391
392   return Offset;
393 }
394
395 void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB,
396                                 MachineBasicBlock::iterator MBBI, DebugLoc DL,
397                                 MCCFIInstruction CFIInst) const {
398   MachineFunction &MF = *MBB.getParent();
399   unsigned CFIIndex = MF.getMMI().addFrameInst(CFIInst);
400   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
401       .addCFIIndex(CFIIndex);
402 }
403
404 void
405 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
406                                             MachineBasicBlock::iterator MBBI,
407                                             DebugLoc DL) const {
408   MachineFunction &MF = *MBB.getParent();
409   MachineFrameInfo *MFI = MF.getFrameInfo();
410   MachineModuleInfo &MMI = MF.getMMI();
411   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
412
413   // Add callee saved registers to move list.
414   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
415   if (CSI.empty()) return;
416
417   // Calculate offsets.
418   for (std::vector<CalleeSavedInfo>::const_iterator
419          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
420     int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
421     unsigned Reg = I->getReg();
422
423     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
424     BuildCFI(MBB, MBBI, DL,
425              MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
426   }
427 }
428
429 /// usesTheStack - This function checks if any of the users of EFLAGS
430 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
431 /// to use the stack, and if we don't adjust the stack we clobber the first
432 /// frame index.
433 /// See X86InstrInfo::copyPhysReg.
434 static bool usesTheStack(const MachineFunction &MF) {
435   const MachineRegisterInfo &MRI = MF.getRegInfo();
436
437   for (MachineRegisterInfo::reg_instr_iterator
438        ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
439        ri != re; ++ri)
440     if (ri->isCopy())
441       return true;
442
443   return false;
444 }
445
446 MachineInstr *X86FrameLowering::emitStackProbe(MachineFunction &MF,
447                                                MachineBasicBlock &MBB,
448                                                MachineBasicBlock::iterator MBBI,
449                                                DebugLoc DL,
450                                                bool InProlog) const {
451   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
452   if (STI.isTargetWindowsCoreCLR()) {
453     if (InProlog) {
454       return emitStackProbeInlineStub(MF, MBB, MBBI, DL, true);
455     } else {
456       return emitStackProbeInline(MF, MBB, MBBI, DL, false);
457     }
458   } else {
459     return emitStackProbeCall(MF, MBB, MBBI, DL, InProlog);
460   }
461 }
462
463 void X86FrameLowering::inlineStackProbe(MachineFunction &MF,
464                                         MachineBasicBlock &PrologMBB) const {
465   const StringRef ChkStkStubSymbol = "__chkstk_stub";
466   MachineInstr *ChkStkStub = nullptr;
467
468   for (MachineInstr &MI : PrologMBB) {
469     if (MI.isCall() && MI.getOperand(0).isSymbol() &&
470         ChkStkStubSymbol == MI.getOperand(0).getSymbolName()) {
471       ChkStkStub = &MI;
472       break;
473     }
474   }
475
476   if (ChkStkStub != nullptr) {
477     MachineBasicBlock::iterator MBBI = std::next(ChkStkStub->getIterator());
478     assert(std::prev(MBBI).operator==(ChkStkStub) &&
479       "MBBI expected after __chkstk_stub.");
480     DebugLoc DL = PrologMBB.findDebugLoc(MBBI);
481     emitStackProbeInline(MF, PrologMBB, MBBI, DL, true);
482     ChkStkStub->eraseFromParent();
483   }
484 }
485
486 MachineInstr *X86FrameLowering::emitStackProbeInline(
487   MachineFunction &MF, MachineBasicBlock &MBB,
488   MachineBasicBlock::iterator MBBI, DebugLoc DL, bool InProlog) const {
489   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
490   assert(STI.is64Bit() && "different expansion needed for 32 bit");
491   assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
492   const TargetInstrInfo &TII = *STI.getInstrInfo();
493   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
494
495   // RAX contains the number of bytes of desired stack adjustment.
496   // The handling here assumes this value has already been updated so as to
497   // maintain stack alignment.
498   //
499   // We need to exit with RSP modified by this amount and execute suitable
500   // page touches to notify the OS that we're growing the stack responsibly.
501   // All stack probing must be done without modifying RSP.
502   //
503   // MBB:
504   //    SizeReg = RAX;
505   //    ZeroReg = 0
506   //    CopyReg = RSP
507   //    Flags, TestReg = CopyReg - SizeReg
508   //    FinalReg = !Flags.Ovf ? TestReg : ZeroReg
509   //    LimitReg = gs magic thread env access
510   //    if FinalReg >= LimitReg goto ContinueMBB
511   // RoundBB:
512   //    RoundReg = page address of FinalReg
513   // LoopMBB:
514   //    LoopReg = PHI(LimitReg,ProbeReg)
515   //    ProbeReg = LoopReg - PageSize
516   //    [ProbeReg] = 0
517   //    if (ProbeReg > RoundReg) goto LoopMBB
518   // ContinueMBB:
519   //    RSP = RSP - RAX
520   //    [rest of original MBB]
521
522   // Set up the new basic blocks
523   MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB);
524   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
525   MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB);
526
527   MachineFunction::iterator MBBIter = std::next(MBB.getIterator());
528   MF.insert(MBBIter, RoundMBB);
529   MF.insert(MBBIter, LoopMBB);
530   MF.insert(MBBIter, ContinueMBB);
531
532   // Split MBB and move the tail portion down to ContinueMBB.
533   MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI);
534   ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end());
535   ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB);
536
537   // Some useful constants
538   const int64_t ThreadEnvironmentStackLimit = 0x10;
539   const int64_t PageSize = 0x1000;
540   const int64_t PageMask = ~(PageSize - 1);
541
542   // Registers we need. For the normal case we use virtual
543   // registers. For the prolog expansion we use RAX, RCX and RDX.
544   MachineRegisterInfo &MRI = MF.getRegInfo();
545   const TargetRegisterClass *RegClass = &X86::GR64RegClass;
546   const unsigned SizeReg = InProlog ? (unsigned)X86::RAX
547                                     : MRI.createVirtualRegister(RegClass),
548                  ZeroReg = InProlog ? (unsigned)X86::RCX
549                                     : MRI.createVirtualRegister(RegClass),
550                  CopyReg = InProlog ? (unsigned)X86::RDX
551                                     : MRI.createVirtualRegister(RegClass),
552                  TestReg = InProlog ? (unsigned)X86::RDX
553                                     : MRI.createVirtualRegister(RegClass),
554                  FinalReg = InProlog ? (unsigned)X86::RDX
555                                      : MRI.createVirtualRegister(RegClass),
556                  RoundedReg = InProlog ? (unsigned)X86::RDX
557                                        : MRI.createVirtualRegister(RegClass),
558                  LimitReg = InProlog ? (unsigned)X86::RCX
559                                      : MRI.createVirtualRegister(RegClass),
560                  JoinReg = InProlog ? (unsigned)X86::RCX
561                                     : MRI.createVirtualRegister(RegClass),
562                  ProbeReg = InProlog ? (unsigned)X86::RCX
563                                      : MRI.createVirtualRegister(RegClass);
564
565   // SP-relative offsets where we can save RCX and RDX.
566   int64_t RCXShadowSlot = 0;
567   int64_t RDXShadowSlot = 0;
568
569   // If inlining in the prolog, save RCX and RDX.     
570   // Future optimization: don't save or restore if not live in.
571   if (InProlog) {
572     // Compute the offsets. We need to account for things already
573     // pushed onto the stack at this point: return address, frame
574     // pointer (if used), and callee saves.
575     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
576     const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
577     const bool HasFP = hasFP(MF);
578     RCXShadowSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
579     RDXShadowSlot = RCXShadowSlot + 8;
580     // Emit the saves.
581     addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
582                  RCXShadowSlot)
583         .addReg(X86::RCX);
584     addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
585                  RDXShadowSlot)
586         .addReg(X86::RDX);
587   } else {
588     // Not in the prolog. Copy RAX to a virtual reg.
589     BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX);
590   }
591
592   // Add code to MBB to check for overflow and set the new target stack pointer
593   // to zero if so.
594   BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg)
595       .addReg(ZeroReg, RegState::Undef)
596       .addReg(ZeroReg, RegState::Undef);
597   BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP);
598   BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg)
599       .addReg(CopyReg)
600       .addReg(SizeReg);
601   BuildMI(&MBB, DL, TII.get(X86::CMOVB64rr), FinalReg)
602       .addReg(TestReg)
603       .addReg(ZeroReg);
604
605   // FinalReg now holds final stack pointer value, or zero if
606   // allocation would overflow. Compare against the current stack
607   // limit from the thread environment block. Note this limit is the
608   // lowest touched page on the stack, not the point at which the OS
609   // will cause an overflow exception, so this is just an optimization
610   // to avoid unnecessarily touching pages that are below the current
611   // SP but already commited to the stack by the OS.
612   BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg)
613       .addReg(0)
614       .addImm(1)
615       .addReg(0)
616       .addImm(ThreadEnvironmentStackLimit)
617       .addReg(X86::GS);
618   BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg);
619   // Jump if the desired stack pointer is at or above the stack limit.
620   BuildMI(&MBB, DL, TII.get(X86::JAE_1)).addMBB(ContinueMBB);
621
622   // Add code to roundMBB to round the final stack pointer to a page boundary.
623   BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg)
624       .addReg(FinalReg)
625       .addImm(PageMask);
626   BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB);
627
628   // LimitReg now holds the current stack limit, RoundedReg page-rounded
629   // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
630   // and probe until we reach RoundedReg.
631   if (!InProlog) {
632     BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg)
633         .addReg(LimitReg)
634         .addMBB(RoundMBB)
635         .addReg(ProbeReg)
636         .addMBB(LoopMBB);
637   }
638
639   addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg,
640                false, -PageSize);
641
642   // Probe by storing a byte onto the stack.
643   BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi))
644       .addReg(ProbeReg)
645       .addImm(1)
646       .addReg(0)
647       .addImm(0)
648       .addReg(0)
649       .addImm(0);
650   BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr))
651       .addReg(RoundedReg)
652       .addReg(ProbeReg);
653   BuildMI(LoopMBB, DL, TII.get(X86::JNE_1)).addMBB(LoopMBB);
654
655   MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
656
657   // If in prolog, restore RDX and RCX.
658   if (InProlog) {
659     addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::MOV64rm),
660                          X86::RCX),
661                  X86::RSP, false, RCXShadowSlot);
662     addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::MOV64rm),
663                          X86::RDX),
664                  X86::RSP, false, RDXShadowSlot);
665   }
666
667   // Now that the probing is done, add code to continueMBB to update
668   // the stack pointer for real.
669   BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
670       .addReg(X86::RSP)
671       .addReg(SizeReg);
672
673   // Add the control flow edges we need.
674   MBB.addSuccessor(ContinueMBB);
675   MBB.addSuccessor(RoundMBB);
676   RoundMBB->addSuccessor(LoopMBB);
677   LoopMBB->addSuccessor(ContinueMBB);
678   LoopMBB->addSuccessor(LoopMBB);
679
680   // Mark all the instructions added to the prolog as frame setup.
681   if (InProlog) {
682     for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
683       BeforeMBBI->setFlag(MachineInstr::FrameSetup);
684     }
685     for (MachineInstr &MI : *RoundMBB) {
686       MI.setFlag(MachineInstr::FrameSetup);
687     }
688     for (MachineInstr &MI : *LoopMBB) {
689       MI.setFlag(MachineInstr::FrameSetup);
690     }
691     for (MachineBasicBlock::iterator CMBBI = ContinueMBB->begin();
692          CMBBI != ContinueMBBI; ++CMBBI) {
693       CMBBI->setFlag(MachineInstr::FrameSetup);
694     }
695   }
696
697   // Possible TODO: physreg liveness for InProlog case.
698
699   return ContinueMBBI;
700 }
701
702 MachineInstr *X86FrameLowering::emitStackProbeCall(
703     MachineFunction &MF, MachineBasicBlock &MBB,
704     MachineBasicBlock::iterator MBBI, DebugLoc DL, bool InProlog) const {
705   bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
706
707   unsigned CallOp;
708   if (Is64Bit)
709     CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
710   else
711     CallOp = X86::CALLpcrel32;
712
713   const char *Symbol;
714   if (Is64Bit) {
715     if (STI.isTargetCygMing()) {
716       Symbol = "___chkstk_ms";
717     } else {
718       Symbol = "__chkstk";
719     }
720   } else if (STI.isTargetCygMing())
721     Symbol = "_alloca";
722   else
723     Symbol = "_chkstk";
724
725   MachineInstrBuilder CI;
726   MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI);
727
728   // All current stack probes take AX and SP as input, clobber flags, and
729   // preserve all registers. x86_64 probes leave RSP unmodified.
730   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
731     // For the large code model, we have to call through a register. Use R11,
732     // as it is scratch in all supported calling conventions.
733     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
734         .addExternalSymbol(Symbol);
735     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
736   } else {
737     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addExternalSymbol(Symbol);
738   }
739
740   unsigned AX = Is64Bit ? X86::RAX : X86::EAX;
741   unsigned SP = Is64Bit ? X86::RSP : X86::ESP;
742   CI.addReg(AX, RegState::Implicit)
743       .addReg(SP, RegState::Implicit)
744       .addReg(AX, RegState::Define | RegState::Implicit)
745       .addReg(SP, RegState::Define | RegState::Implicit)
746       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
747
748   if (Is64Bit) {
749     // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
750     // themselves. It also does not clobber %rax so we can reuse it when
751     // adjusting %rsp.
752     BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
753         .addReg(X86::RSP)
754         .addReg(X86::RAX);
755   }
756
757   if (InProlog) {
758     // Apply the frame setup flag to all inserted instrs.
759     for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
760       ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
761   }
762
763   return MBBI;
764 }
765
766 MachineInstr *X86FrameLowering::emitStackProbeInlineStub(
767     MachineFunction &MF, MachineBasicBlock &MBB,
768     MachineBasicBlock::iterator MBBI, DebugLoc DL, bool InProlog) const {
769
770   assert(InProlog && "ChkStkStub called outside prolog!");
771
772   BuildMI(MBB, MBBI, DL, TII.get(X86::CALLpcrel32))
773       .addExternalSymbol("__chkstk_stub");
774
775   return MBBI;
776 }
777
778 static unsigned calculateSetFPREG(uint64_t SPAdjust) {
779   // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
780   // and might require smaller successive adjustments.
781   const uint64_t Win64MaxSEHOffset = 128;
782   uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
783   // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
784   return SEHFrameOffset & -16;
785 }
786
787 // If we're forcing a stack realignment we can't rely on just the frame
788 // info, we need to know the ABI stack alignment as well in case we
789 // have a call out.  Otherwise just make sure we have some alignment - we'll
790 // go with the minimum SlotSize.
791 uint64_t X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
792   const MachineFrameInfo *MFI = MF.getFrameInfo();
793   uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
794   unsigned StackAlign = getStackAlignment();
795   if (MF.getFunction()->hasFnAttribute("stackrealign")) {
796     if (MFI->hasCalls())
797       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
798     else if (MaxAlign < SlotSize)
799       MaxAlign = SlotSize;
800   }
801   return MaxAlign;
802 }
803
804 void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
805                                           MachineBasicBlock::iterator MBBI,
806                                           DebugLoc DL, unsigned Reg,
807                                           uint64_t MaxAlign) const {
808   uint64_t Val = -MaxAlign;
809   unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val);
810   MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg)
811                          .addReg(Reg)
812                          .addImm(Val)
813                          .setMIFlag(MachineInstr::FrameSetup);
814
815   // The EFLAGS implicit def is dead.
816   MI->getOperand(3).setIsDead();
817 }
818
819 /// emitPrologue - Push callee-saved registers onto the stack, which
820 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
821 /// space for local variables. Also emit labels used by the exception handler to
822 /// generate the exception handling frames.
823
824 /*
825   Here's a gist of what gets emitted:
826
827   ; Establish frame pointer, if needed
828   [if needs FP]
829       push  %rbp
830       .cfi_def_cfa_offset 16
831       .cfi_offset %rbp, -16
832       .seh_pushreg %rpb
833       mov  %rsp, %rbp
834       .cfi_def_cfa_register %rbp
835
836   ; Spill general-purpose registers
837   [for all callee-saved GPRs]
838       pushq %<reg>
839       [if not needs FP]
840          .cfi_def_cfa_offset (offset from RETADDR)
841       .seh_pushreg %<reg>
842
843   ; If the required stack alignment > default stack alignment
844   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
845   ; of unknown size in the stack frame.
846   [if stack needs re-alignment]
847       and  $MASK, %rsp
848
849   ; Allocate space for locals
850   [if target is Windows and allocated space > 4096 bytes]
851       ; Windows needs special care for allocations larger
852       ; than one page.
853       mov $NNN, %rax
854       call ___chkstk_ms/___chkstk
855       sub  %rax, %rsp
856   [else]
857       sub  $NNN, %rsp
858
859   [if needs FP]
860       .seh_stackalloc (size of XMM spill slots)
861       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
862   [else]
863       .seh_stackalloc NNN
864
865   ; Spill XMMs
866   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
867   ; they may get spilled on any platform, if the current function
868   ; calls @llvm.eh.unwind.init
869   [if needs FP]
870       [for all callee-saved XMM registers]
871           movaps  %<xmm reg>, -MMM(%rbp)
872       [for all callee-saved XMM registers]
873           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
874               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
875   [else]
876       [for all callee-saved XMM registers]
877           movaps  %<xmm reg>, KKK(%rsp)
878       [for all callee-saved XMM registers]
879           .seh_savexmm %<xmm reg>, KKK
880
881   .seh_endprologue
882
883   [if needs base pointer]
884       mov  %rsp, %rbx
885       [if needs to restore base pointer]
886           mov %rsp, -MMM(%rbp)
887
888   ; Emit CFI info
889   [if needs FP]
890       [for all callee-saved registers]
891           .cfi_offset %<reg>, (offset from %rbp)
892   [else]
893        .cfi_def_cfa_offset (offset from RETADDR)
894       [for all callee-saved registers]
895           .cfi_offset %<reg>, (offset from %rsp)
896
897   Notes:
898   - .seh directives are emitted only for Windows 64 ABI
899   - .cfi directives are emitted for all other ABIs
900   - for 32-bit code, substitute %e?? registers for %r??
901 */
902
903 void X86FrameLowering::emitPrologue(MachineFunction &MF,
904                                     MachineBasicBlock &MBB) const {
905   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
906          "MF used frame lowering for wrong subtarget");
907   MachineBasicBlock::iterator MBBI = MBB.begin();
908   MachineFrameInfo *MFI = MF.getFrameInfo();
909   const Function *Fn = MF.getFunction();
910   MachineModuleInfo &MMI = MF.getMMI();
911   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
912   uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
913   uint64_t StackSize = MFI->getStackSize();    // Number of bytes to allocate.
914   bool IsFunclet = MBB.isEHFuncletEntry();
915   EHPersonality Personality = EHPersonality::Unknown;
916   if (Fn->hasPersonalityFn())
917     Personality = classifyEHPersonality(Fn->getPersonalityFn());
918   bool FnHasClrFunclet =
919       MMI.hasEHFunclets() && Personality == EHPersonality::CoreCLR;
920   bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
921   bool HasFP = hasFP(MF);
922   bool IsWin64CC = STI.isCallingConvWin64(Fn->getCallingConv());
923   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
924   bool NeedsWinCFI = IsWin64Prologue && Fn->needsUnwindTableEntry();
925   bool NeedsDwarfCFI =
926       !IsWin64Prologue && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
927   unsigned FramePtr = TRI->getFrameRegister(MF);
928   const unsigned MachineFramePtr =
929       STI.isTarget64BitILP32()
930           ? getX86SubSuperRegister(FramePtr, MVT::i64) : FramePtr;
931   unsigned BasePtr = TRI->getBaseRegister();
932   
933   // Debug location must be unknown since the first debug location is used
934   // to determine the end of the prologue.
935   DebugLoc DL;
936
937   // Add RETADDR move area to callee saved frame size.
938   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
939   if (TailCallReturnAddrDelta && IsWin64Prologue)
940     report_fatal_error("Can't handle guaranteed tail call under win64 yet");
941
942   if (TailCallReturnAddrDelta < 0)
943     X86FI->setCalleeSavedFrameSize(
944       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
945
946   bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
947
948   // The default stack probe size is 4096 if the function has no stackprobesize
949   // attribute.
950   unsigned StackProbeSize = 4096;
951   if (Fn->hasFnAttribute("stack-probe-size"))
952     Fn->getFnAttribute("stack-probe-size")
953         .getValueAsString()
954         .getAsInteger(0, StackProbeSize);
955
956   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
957   // function, and use up to 128 bytes of stack space, don't have a frame
958   // pointer, calls, or dynamic alloca then we do not need to adjust the
959   // stack pointer (we fit in the Red Zone). We also check that we don't
960   // push and pop from the stack.
961   if (Is64Bit && !Fn->hasFnAttribute(Attribute::NoRedZone) &&
962       !TRI->needsStackRealignment(MF) &&
963       !MFI->hasVarSizedObjects() && // No dynamic alloca.
964       !MFI->adjustsStack() &&       // No calls.
965       !IsWin64CC &&                 // Win64 has no Red Zone
966       !usesTheStack(MF) &&          // Don't push and pop.
967       !MF.shouldSplitStack()) {     // Regular stack
968     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
969     if (HasFP) MinSize += SlotSize;
970     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
971     MFI->setStackSize(StackSize);
972   }
973
974   // Insert stack pointer adjustment for later moving of return addr.  Only
975   // applies to tail call optimized functions where the callee argument stack
976   // size is bigger than the callers.
977   if (TailCallReturnAddrDelta < 0) {
978     BuildStackAdjustment(MBB, MBBI, DL, TailCallReturnAddrDelta,
979                          /*InEpilogue=*/false)
980         .setMIFlag(MachineInstr::FrameSetup);
981   }
982
983   // Mapping for machine moves:
984   //
985   //   DST: VirtualFP AND
986   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
987   //        ELSE                        => DW_CFA_def_cfa
988   //
989   //   SRC: VirtualFP AND
990   //        DST: Register               => DW_CFA_def_cfa_register
991   //
992   //   ELSE
993   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
994   //        REG < 64                    => DW_CFA_offset + Reg
995   //        ELSE                        => DW_CFA_offset_extended
996
997   uint64_t NumBytes = 0;
998   int stackGrowth = -SlotSize;
999
1000   // Find the funclet establisher parameter
1001   unsigned Establisher = X86::NoRegister;
1002   if (IsClrFunclet)
1003     Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
1004   else if (IsFunclet)
1005     Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
1006
1007   if (IsWin64Prologue && IsFunclet && !IsClrFunclet) {
1008     // Immediately spill establisher into the home slot.
1009     // The runtime cares about this.
1010     // MOV64mr %rdx, 16(%rsp)
1011     unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1012     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16)
1013         .addReg(Establisher)
1014         .setMIFlag(MachineInstr::FrameSetup);
1015     MBB.addLiveIn(Establisher);
1016   }
1017
1018   if (HasFP) {
1019     // Calculate required stack adjustment.
1020     uint64_t FrameSize = StackSize - SlotSize;
1021     // If required, include space for extra hidden slot for stashing base pointer.
1022     if (X86FI->getRestoreBasePointer())
1023       FrameSize += SlotSize;
1024
1025     NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
1026
1027     // Callee-saved registers are pushed on stack before the stack is realigned.
1028     if (TRI->needsStackRealignment(MF) && !IsWin64Prologue)
1029       NumBytes = RoundUpToAlignment(NumBytes, MaxAlign);
1030
1031     // Get the offset of the stack slot for the EBP register, which is
1032     // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
1033     // Update the frame offset adjustment.
1034     if (!IsFunclet)
1035       MFI->setOffsetAdjustment(-NumBytes);
1036     else
1037       assert(MFI->getOffsetAdjustment() == -(int)NumBytes &&
1038              "should calculate same local variable offset for funclets");
1039
1040     // Save EBP/RBP into the appropriate stack slot.
1041     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
1042       .addReg(MachineFramePtr, RegState::Kill)
1043       .setMIFlag(MachineInstr::FrameSetup);
1044
1045     if (NeedsDwarfCFI) {
1046       // Mark the place where EBP/RBP was saved.
1047       // Define the current CFA rule to use the provided offset.
1048       assert(StackSize);
1049       BuildCFI(MBB, MBBI, DL,
1050                MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
1051
1052       // Change the rule for the FramePtr to be an "offset" rule.
1053       unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1054       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createOffset(
1055                                   nullptr, DwarfFramePtr, 2 * stackGrowth));
1056     }
1057
1058     if (NeedsWinCFI) {
1059       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1060           .addImm(FramePtr)
1061           .setMIFlag(MachineInstr::FrameSetup);
1062     }
1063
1064     if (!IsWin64Prologue && !IsFunclet) {
1065       // Update EBP with the new base value.
1066       BuildMI(MBB, MBBI, DL,
1067               TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
1068               FramePtr)
1069           .addReg(StackPtr)
1070           .setMIFlag(MachineInstr::FrameSetup);
1071
1072       if (NeedsDwarfCFI) {
1073         // Mark effective beginning of when frame pointer becomes valid.
1074         // Define the current CFA to use the EBP/RBP register.
1075         unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1076         BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaRegister(
1077                                     nullptr, DwarfFramePtr));
1078       }
1079     }
1080
1081     // Mark the FramePtr as live-in in every block. Don't do this again for
1082     // funclet prologues.
1083     if (!IsFunclet) {
1084       for (MachineBasicBlock &EveryMBB : MF)
1085         EveryMBB.addLiveIn(MachineFramePtr);
1086     }
1087   } else {
1088     assert(!IsFunclet && "funclets without FPs not yet implemented");
1089     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
1090   }
1091
1092   // For EH funclets, only allocate enough space for outgoing calls. Save the
1093   // NumBytes value that we would've used for the parent frame.
1094   unsigned ParentFrameNumBytes = NumBytes;
1095   if (IsFunclet)
1096     NumBytes = getWinEHFuncletFrameSize(MF);
1097
1098   // Skip the callee-saved push instructions.
1099   bool PushedRegs = false;
1100   int StackOffset = 2 * stackGrowth;
1101
1102   while (MBBI != MBB.end() &&
1103          MBBI->getFlag(MachineInstr::FrameSetup) &&
1104          (MBBI->getOpcode() == X86::PUSH32r ||
1105           MBBI->getOpcode() == X86::PUSH64r)) {
1106     PushedRegs = true;
1107     unsigned Reg = MBBI->getOperand(0).getReg();
1108     ++MBBI;
1109
1110     if (!HasFP && NeedsDwarfCFI) {
1111       // Mark callee-saved push instruction.
1112       // Define the current CFA rule to use the provided offset.
1113       assert(StackSize);
1114       BuildCFI(MBB, MBBI, DL,
1115                MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
1116       StackOffset += stackGrowth;
1117     }
1118
1119     if (NeedsWinCFI) {
1120       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
1121           MachineInstr::FrameSetup);
1122     }
1123   }
1124
1125   // Realign stack after we pushed callee-saved registers (so that we'll be
1126   // able to calculate their offsets from the frame pointer).
1127   // Don't do this for Win64, it needs to realign the stack after the prologue.
1128   if (!IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF)) {
1129     assert(HasFP && "There should be a frame pointer if stack is realigned.");
1130     BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
1131   }
1132
1133   // If there is an SUB32ri of ESP immediately before this instruction, merge
1134   // the two. This can be the case when tail call elimination is enabled and
1135   // the callee has more arguments then the caller.
1136   NumBytes -= mergeSPUpdates(MBB, MBBI, true);
1137
1138   // Adjust stack pointer: ESP -= numbytes.
1139
1140   // Windows and cygwin/mingw require a prologue helper routine when allocating
1141   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
1142   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
1143   // stack and adjust the stack pointer in one go.  The 64-bit version of
1144   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
1145   // responsible for adjusting the stack pointer.  Touching the stack at 4K
1146   // increments is necessary to ensure that the guard pages used by the OS
1147   // virtual memory manager are allocated in correct sequence.
1148   uint64_t AlignedNumBytes = NumBytes;
1149   if (IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF))
1150     AlignedNumBytes = RoundUpToAlignment(AlignedNumBytes, MaxAlign);
1151   if (AlignedNumBytes >= StackProbeSize && UseStackProbe) {
1152     // Check whether EAX is livein for this function.
1153     bool isEAXAlive = isEAXLiveIn(MF);
1154
1155     if (isEAXAlive) {
1156       // Sanity check that EAX is not livein for this function.
1157       // It should not be, so throw an assert.
1158       assert(!Is64Bit && "EAX is livein in x64 case!");
1159
1160       // Save EAX
1161       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
1162         .addReg(X86::EAX, RegState::Kill)
1163         .setMIFlag(MachineInstr::FrameSetup);
1164     }
1165
1166     if (Is64Bit) {
1167       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
1168       // Function prologue is responsible for adjusting the stack pointer.
1169       if (isUInt<32>(NumBytes)) {
1170         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
1171             .addImm(NumBytes)
1172             .setMIFlag(MachineInstr::FrameSetup);
1173       } else if (isInt<32>(NumBytes)) {
1174         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
1175             .addImm(NumBytes)
1176             .setMIFlag(MachineInstr::FrameSetup);
1177       } else {
1178         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
1179             .addImm(NumBytes)
1180             .setMIFlag(MachineInstr::FrameSetup);
1181       }
1182     } else {
1183       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
1184       // We'll also use 4 already allocated bytes for EAX.
1185       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
1186           .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
1187           .setMIFlag(MachineInstr::FrameSetup);
1188     }
1189
1190     // Call __chkstk, __chkstk_ms, or __alloca.
1191     emitStackProbe(MF, MBB, MBBI, DL, true);
1192
1193     if (isEAXAlive) {
1194       // Restore EAX
1195       MachineInstr *MI =
1196           addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX),
1197                        StackPtr, false, NumBytes - 4);
1198       MI->setFlag(MachineInstr::FrameSetup);
1199       MBB.insert(MBBI, MI);
1200     }
1201   } else if (NumBytes) {
1202     emitSPUpdate(MBB, MBBI, -(int64_t)NumBytes, /*InEpilogue=*/false);
1203   }
1204
1205   if (NeedsWinCFI && NumBytes)
1206     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
1207         .addImm(NumBytes)
1208         .setMIFlag(MachineInstr::FrameSetup);
1209
1210   int SEHFrameOffset = 0;
1211   unsigned SPOrEstablisher;
1212   if (IsFunclet) {
1213     if (IsClrFunclet) {
1214       // The establisher parameter passed to a CLR funclet is actually a pointer
1215       // to the (mostly empty) frame of its nearest enclosing funclet; we have
1216       // to find the root function establisher frame by loading the PSPSym from
1217       // the intermediate frame.
1218       unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
1219       MachinePointerInfo NoInfo;
1220       MBB.addLiveIn(Establisher);
1221       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher),
1222                    Establisher, false, PSPSlotOffset)
1223           .addMemOperand(MF.getMachineMemOperand(
1224               NoInfo, MachineMemOperand::MOLoad, SlotSize, SlotSize));
1225       ;
1226       // Save the root establisher back into the current funclet's (mostly
1227       // empty) frame, in case a sub-funclet or the GC needs it.
1228       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
1229                    false, PSPSlotOffset)
1230           .addReg(Establisher)
1231           .addMemOperand(
1232               MF.getMachineMemOperand(NoInfo, MachineMemOperand::MOStore |
1233                                                   MachineMemOperand::MOVolatile,
1234                                       SlotSize, SlotSize));
1235     }
1236     SPOrEstablisher = Establisher;
1237   } else {
1238     SPOrEstablisher = StackPtr;
1239   }
1240
1241   if (IsWin64Prologue && HasFP) {
1242     // Set RBP to a small fixed offset from RSP. In the funclet case, we base
1243     // this calculation on the incoming establisher, which holds the value of
1244     // RSP from the parent frame at the end of the prologue.
1245     SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes);
1246     if (SEHFrameOffset)
1247       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
1248                    SPOrEstablisher, false, SEHFrameOffset);
1249     else
1250       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr)
1251           .addReg(SPOrEstablisher);
1252
1253     // If this is not a funclet, emit the CFI describing our frame pointer.
1254     if (NeedsWinCFI && !IsFunclet) {
1255       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
1256           .addImm(FramePtr)
1257           .addImm(SEHFrameOffset)
1258           .setMIFlag(MachineInstr::FrameSetup);
1259       if (isAsynchronousEHPersonality(Personality))
1260         MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset;
1261     }
1262   } else if (IsFunclet && STI.is32Bit()) {
1263     // Reset EBP / ESI to something good for funclets.
1264     MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL);
1265     // If we're a catch funclet, we can be returned to via catchret. Save ESP
1266     // into the registration node so that the runtime will restore it for us.
1267     if (!MBB.isCleanupFuncletEntry()) {
1268       assert(Personality == EHPersonality::MSVC_CXX);
1269       unsigned FrameReg;
1270       int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex;
1271       int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg);
1272       // ESP is the first field, so no extra displacement is needed.
1273       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg,
1274                    false, EHRegOffset)
1275           .addReg(X86::ESP);
1276     }
1277   }
1278
1279   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
1280     const MachineInstr *FrameInstr = &*MBBI;
1281     ++MBBI;
1282
1283     if (NeedsWinCFI) {
1284       int FI;
1285       if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
1286         if (X86::FR64RegClass.contains(Reg)) {
1287           unsigned IgnoredFrameReg;
1288           int Offset = getFrameIndexReference(MF, FI, IgnoredFrameReg);
1289           Offset += SEHFrameOffset;
1290
1291           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
1292               .addImm(Reg)
1293               .addImm(Offset)
1294               .setMIFlag(MachineInstr::FrameSetup);
1295         }
1296       }
1297     }
1298   }
1299
1300   if (NeedsWinCFI)
1301     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
1302         .setMIFlag(MachineInstr::FrameSetup);
1303
1304   if (FnHasClrFunclet && !IsFunclet) {
1305     // Save the so-called Initial-SP (i.e. the value of the stack pointer
1306     // immediately after the prolog)  into the PSPSlot so that funclets
1307     // and the GC can recover it.
1308     unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
1309     auto PSPInfo = MachinePointerInfo::getFixedStack(
1310         MF, MF.getWinEHFuncInfo()->PSPSymFrameIdx);
1311     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false,
1312                  PSPSlotOffset)
1313         .addReg(StackPtr)
1314         .addMemOperand(MF.getMachineMemOperand(
1315             PSPInfo, MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
1316             SlotSize, SlotSize));
1317   }
1318
1319   // Realign stack after we spilled callee-saved registers (so that we'll be
1320   // able to calculate their offsets from the frame pointer).
1321   // Win64 requires aligning the stack after the prologue.
1322   if (IsWin64Prologue && TRI->needsStackRealignment(MF)) {
1323     assert(HasFP && "There should be a frame pointer if stack is realigned.");
1324     BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign);
1325   }
1326
1327   // We already dealt with stack realignment and funclets above.
1328   if (IsFunclet && STI.is32Bit())
1329     return;
1330
1331   // If we need a base pointer, set it up here. It's whatever the value
1332   // of the stack pointer is at this point. Any variable size objects
1333   // will be allocated after this, so we can still use the base pointer
1334   // to reference locals.
1335   if (TRI->hasBasePointer(MF)) {
1336     // Update the base pointer with the current stack pointer.
1337     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
1338     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
1339       .addReg(SPOrEstablisher)
1340       .setMIFlag(MachineInstr::FrameSetup);
1341     if (X86FI->getRestoreBasePointer()) {
1342       // Stash value of base pointer.  Saving RSP instead of EBP shortens
1343       // dependence chain. Used by SjLj EH.
1344       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1345       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
1346                    FramePtr, true, X86FI->getRestoreBasePointerOffset())
1347         .addReg(SPOrEstablisher)
1348         .setMIFlag(MachineInstr::FrameSetup);
1349     }
1350
1351     if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
1352       // Stash the value of the frame pointer relative to the base pointer for
1353       // Win32 EH. This supports Win32 EH, which does the inverse of the above:
1354       // it recovers the frame pointer from the base pointer rather than the
1355       // other way around.
1356       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1357       unsigned UsedReg;
1358       int Offset =
1359           getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg);
1360       assert(UsedReg == BasePtr);
1361       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset)
1362           .addReg(FramePtr)
1363           .setMIFlag(MachineInstr::FrameSetup);
1364     }
1365   }
1366
1367   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
1368     // Mark end of stack pointer adjustment.
1369     if (!HasFP && NumBytes) {
1370       // Define the current CFA rule to use the provided offset.
1371       assert(StackSize);
1372       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaOffset(
1373                                   nullptr, -StackSize + stackGrowth));
1374     }
1375
1376     // Emit DWARF info specifying the offsets of the callee-saved registers.
1377     if (PushedRegs)
1378       emitCalleeSavedFrameMoves(MBB, MBBI, DL);
1379   }
1380 }
1381
1382 bool X86FrameLowering::canUseLEAForSPInEpilogue(
1383     const MachineFunction &MF) const {
1384   // We can't use LEA instructions for adjusting the stack pointer if this is a
1385   // leaf function in the Win64 ABI.  Only ADD instructions may be used to
1386   // deallocate the stack.
1387   // This means that we can use LEA for SP in two situations:
1388   // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
1389   // 2. We *have* a frame pointer which means we are permitted to use LEA.
1390   return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
1391 }
1392
1393 static bool isFuncletReturnInstr(MachineInstr *MI) {
1394   switch (MI->getOpcode()) {
1395   case X86::CATCHRET:
1396   case X86::CLEANUPRET:
1397     return true;
1398   default:
1399     return false;
1400   }
1401   llvm_unreachable("impossible");
1402 }
1403
1404 // CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
1405 // stack. It holds a pointer to the bottom of the root function frame.  The
1406 // establisher frame pointer passed to a nested funclet may point to the
1407 // (mostly empty) frame of its parent funclet, but it will need to find
1408 // the frame of the root function to access locals.  To facilitate this,
1409 // every funclet copies the pointer to the bottom of the root function
1410 // frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
1411 // same offset for the PSPSym in the root function frame that's used in the
1412 // funclets' frames allows each funclet to dynamically accept any ancestor
1413 // frame as its establisher argument (the runtime doesn't guarantee the
1414 // immediate parent for some reason lost to history), and also allows the GC,
1415 // which uses the PSPSym for some bookkeeping, to find it in any funclet's
1416 // frame with only a single offset reported for the entire method.
1417 unsigned
1418 X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
1419   const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
1420   // getFrameIndexReferenceFromSP has an out ref parameter for the stack
1421   // pointer register; pass a dummy that we ignore
1422   unsigned SPReg;
1423   int Offset = getFrameIndexReferenceFromSP(MF, Info.PSPSymFrameIdx, SPReg);
1424   assert(Offset >= 0);
1425   return static_cast<unsigned>(Offset);
1426 }
1427
1428 unsigned
1429 X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
1430   // This is the size of the pushed CSRs.
1431   unsigned CSSize =
1432       MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
1433   // This is the amount of stack a funclet needs to allocate.
1434   unsigned UsedSize;
1435   EHPersonality Personality =
1436       classifyEHPersonality(MF.getFunction()->getPersonalityFn());
1437   if (Personality == EHPersonality::CoreCLR) {
1438     // CLR funclets need to hold enough space to include the PSPSym, at the
1439     // same offset from the stack pointer (immediately after the prolog) as it
1440     // resides at in the main function.
1441     UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
1442   } else {
1443     // Other funclets just need enough stack for outgoing call arguments.
1444     UsedSize = MF.getFrameInfo()->getMaxCallFrameSize();
1445   }
1446   // RBP is not included in the callee saved register block. After pushing RBP,
1447   // everything is 16 byte aligned. Everything we allocate before an outgoing
1448   // call must also be 16 byte aligned.
1449   unsigned FrameSizeMinusRBP =
1450       RoundUpToAlignment(CSSize + UsedSize, getStackAlignment());
1451   // Subtract out the size of the callee saved registers. This is how much stack
1452   // each funclet will allocate.
1453   return FrameSizeMinusRBP - CSSize;
1454 }
1455
1456 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
1457                                     MachineBasicBlock &MBB) const {
1458   const MachineFrameInfo *MFI = MF.getFrameInfo();
1459   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1460   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1461   DebugLoc DL;
1462   if (MBBI != MBB.end())
1463     DL = MBBI->getDebugLoc();
1464   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
1465   const bool Is64BitILP32 = STI.isTarget64BitILP32();
1466   unsigned FramePtr = TRI->getFrameRegister(MF);
1467   unsigned MachineFramePtr =
1468       Is64BitILP32 ? getX86SubSuperRegister(FramePtr, MVT::i64) : FramePtr;
1469
1470   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1471   bool NeedsWinCFI =
1472       IsWin64Prologue && MF.getFunction()->needsUnwindTableEntry();
1473   bool IsFunclet = isFuncletReturnInstr(MBBI);
1474   MachineBasicBlock *TargetMBB = nullptr;
1475
1476   // Get the number of bytes to allocate from the FrameInfo.
1477   uint64_t StackSize = MFI->getStackSize();
1478   uint64_t MaxAlign = calculateMaxStackAlign(MF);
1479   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1480   uint64_t NumBytes = 0;
1481
1482   if (MBBI->getOpcode() == X86::CATCHRET) {
1483     // SEH shouldn't use catchret.
1484     assert(!isAsynchronousEHPersonality(
1485                classifyEHPersonality(MF.getFunction()->getPersonalityFn())) &&
1486            "SEH should not use CATCHRET");
1487
1488     NumBytes = getWinEHFuncletFrameSize(MF);
1489     assert(hasFP(MF) && "EH funclets without FP not yet implemented");
1490     TargetMBB = MBBI->getOperand(0).getMBB();
1491
1492     // Pop EBP.
1493     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r),
1494             MachineFramePtr)
1495         .setMIFlag(MachineInstr::FrameDestroy);
1496   } else if (MBBI->getOpcode() == X86::CLEANUPRET) {
1497     NumBytes = getWinEHFuncletFrameSize(MF);
1498     assert(hasFP(MF) && "EH funclets without FP not yet implemented");
1499     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r),
1500             MachineFramePtr)
1501         .setMIFlag(MachineInstr::FrameDestroy);
1502   } else if (hasFP(MF)) {
1503     // Calculate required stack adjustment.
1504     uint64_t FrameSize = StackSize - SlotSize;
1505     NumBytes = FrameSize - CSSize;
1506
1507     // Callee-saved registers were pushed on stack before the stack was
1508     // realigned.
1509     if (TRI->needsStackRealignment(MF) && !IsWin64Prologue)
1510       NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
1511
1512     // Pop EBP.
1513     BuildMI(MBB, MBBI, DL,
1514             TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr)
1515         .setMIFlag(MachineInstr::FrameDestroy);
1516   } else {
1517     NumBytes = StackSize - CSSize;
1518   }
1519   uint64_t SEHStackAllocAmt = NumBytes;
1520
1521   // Skip the callee-saved pop instructions.
1522   while (MBBI != MBB.begin()) {
1523     MachineBasicBlock::iterator PI = std::prev(MBBI);
1524     unsigned Opc = PI->getOpcode();
1525
1526     if ((Opc != X86::POP32r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
1527         (Opc != X86::POP64r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
1528         Opc != X86::DBG_VALUE && !PI->isTerminator())
1529       break;
1530
1531     --MBBI;
1532   }
1533   MachineBasicBlock::iterator FirstCSPop = MBBI;
1534
1535   if (TargetMBB) {
1536     // Fill EAX/RAX with the address of the target block.
1537     unsigned ReturnReg = STI.is64Bit() ? X86::RAX : X86::EAX;
1538     if (STI.is64Bit()) {
1539       // LEA64r TargetMBB(%rip), %rax
1540       BuildMI(MBB, FirstCSPop, DL, TII.get(X86::LEA64r), ReturnReg)
1541           .addReg(X86::RIP)
1542           .addImm(0)
1543           .addReg(0)
1544           .addMBB(TargetMBB)
1545           .addReg(0);
1546     } else {
1547       // MOV32ri $TargetMBB, %eax
1548       BuildMI(MBB, FirstCSPop, DL, TII.get(X86::MOV32ri), ReturnReg)
1549           .addMBB(TargetMBB);
1550     }
1551     // Record that we've taken the address of TargetMBB and no longer just
1552     // reference it in a terminator.
1553     TargetMBB->setHasAddressTaken();
1554   }
1555
1556   if (MBBI != MBB.end())
1557     DL = MBBI->getDebugLoc();
1558
1559   // If there is an ADD32ri or SUB32ri of ESP immediately before this
1560   // instruction, merge the two instructions.
1561   if (NumBytes || MFI->hasVarSizedObjects())
1562     NumBytes += mergeSPUpdates(MBB, MBBI, true);
1563
1564   // If dynamic alloca is used, then reset esp to point to the last callee-saved
1565   // slot before popping them off! Same applies for the case, when stack was
1566   // realigned. Don't do this if this was a funclet epilogue, since the funclets
1567   // will not do realignment or dynamic stack allocation.
1568   if ((TRI->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) &&
1569       !IsFunclet) {
1570     if (TRI->needsStackRealignment(MF))
1571       MBBI = FirstCSPop;
1572     unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1573     uint64_t LEAAmount =
1574         IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
1575
1576     // There are only two legal forms of epilogue:
1577     // - add SEHAllocationSize, %rsp
1578     // - lea SEHAllocationSize(%FramePtr), %rsp
1579     //
1580     // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1581     // However, we may use this sequence if we have a frame pointer because the
1582     // effects of the prologue can safely be undone.
1583     if (LEAAmount != 0) {
1584       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1585       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1586                    FramePtr, false, LEAAmount);
1587       --MBBI;
1588     } else {
1589       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1590       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1591         .addReg(FramePtr);
1592       --MBBI;
1593     }
1594   } else if (NumBytes) {
1595     // Adjust stack pointer back: ESP += numbytes.
1596     emitSPUpdate(MBB, MBBI, NumBytes, /*InEpilogue=*/true);
1597     --MBBI;
1598   }
1599
1600   // Windows unwinder will not invoke function's exception handler if IP is
1601   // either in prologue or in epilogue.  This behavior causes a problem when a
1602   // call immediately precedes an epilogue, because the return address points
1603   // into the epilogue.  To cope with that, we insert an epilogue marker here,
1604   // then replace it with a 'nop' if it ends up immediately after a CALL in the
1605   // final emitted code.
1606   if (NeedsWinCFI)
1607     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1608
1609   // Add the return addr area delta back since we are not tail calling.
1610   int Offset = -1 * X86FI->getTCReturnAddrDelta();
1611   assert(Offset >= 0 && "TCDelta should never be positive");
1612   if (Offset) {
1613     MBBI = MBB.getFirstTerminator();
1614
1615     // Check for possible merge with preceding ADD instruction.
1616     Offset += mergeSPUpdates(MBB, MBBI, true);
1617     emitSPUpdate(MBB, MBBI, Offset, /*InEpilogue=*/true);
1618   }
1619 }
1620
1621 // NOTE: this only has a subset of the full frame index logic. In
1622 // particular, the FI < 0 and AfterFPPop logic is handled in
1623 // X86RegisterInfo::eliminateFrameIndex, but not here. Possibly
1624 // (probably?) it should be moved into here.
1625 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1626                                              unsigned &FrameReg) const {
1627   const MachineFrameInfo *MFI = MF.getFrameInfo();
1628
1629   // We can't calculate offset from frame pointer if the stack is realigned,
1630   // so enforce usage of stack/base pointer.  The base pointer is used when we
1631   // have dynamic allocas in addition to dynamic realignment.
1632   if (TRI->hasBasePointer(MF))
1633     FrameReg = TRI->getBaseRegister();
1634   else if (TRI->needsStackRealignment(MF))
1635     FrameReg = TRI->getStackRegister();
1636   else
1637     FrameReg = TRI->getFrameRegister(MF);
1638
1639   // Offset will hold the offset from the stack pointer at function entry to the
1640   // object.
1641   // We need to factor in additional offsets applied during the prologue to the
1642   // frame, base, and stack pointer depending on which is used.
1643   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1644   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1645   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1646   uint64_t StackSize = MFI->getStackSize();
1647   bool HasFP = hasFP(MF);
1648   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1649   int64_t FPDelta = 0;
1650
1651   if (IsWin64Prologue) {
1652     assert(!MFI->hasCalls() || (StackSize % 16) == 8);
1653
1654     // Calculate required stack adjustment.
1655     uint64_t FrameSize = StackSize - SlotSize;
1656     // If required, include space for extra hidden slot for stashing base pointer.
1657     if (X86FI->getRestoreBasePointer())
1658       FrameSize += SlotSize;
1659     uint64_t NumBytes = FrameSize - CSSize;
1660
1661     uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
1662     if (FI && FI == X86FI->getFAIndex())
1663       return -SEHFrameOffset;
1664
1665     // FPDelta is the offset from the "traditional" FP location of the old base
1666     // pointer followed by return address and the location required by the
1667     // restricted Win64 prologue.
1668     // Add FPDelta to all offsets below that go through the frame pointer.
1669     FPDelta = FrameSize - SEHFrameOffset;
1670     assert((!MFI->hasCalls() || (FPDelta % 16) == 0) &&
1671            "FPDelta isn't aligned per the Win64 ABI!");
1672   }
1673
1674
1675   if (TRI->hasBasePointer(MF)) {
1676     assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
1677     if (FI < 0) {
1678       // Skip the saved EBP.
1679       return Offset + SlotSize + FPDelta;
1680     } else {
1681       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1682       return Offset + StackSize;
1683     }
1684   } else if (TRI->needsStackRealignment(MF)) {
1685     if (FI < 0) {
1686       // Skip the saved EBP.
1687       return Offset + SlotSize + FPDelta;
1688     } else {
1689       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1690       return Offset + StackSize;
1691     }
1692     // FIXME: Support tail calls
1693   } else {
1694     if (!HasFP)
1695       return Offset + StackSize;
1696
1697     // Skip the saved EBP.
1698     Offset += SlotSize;
1699
1700     // Skip the RETADDR move area
1701     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1702     if (TailCallReturnAddrDelta < 0)
1703       Offset -= TailCallReturnAddrDelta;
1704   }
1705
1706   return Offset + FPDelta;
1707 }
1708
1709 // Simplified from getFrameIndexReference keeping only StackPointer cases
1710 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
1711                                                    int FI,
1712                                                    unsigned &FrameReg) const {
1713   const MachineFrameInfo *MFI = MF.getFrameInfo();
1714   // Does not include any dynamic realign.
1715   const uint64_t StackSize = MFI->getStackSize();
1716   {
1717 #ifndef NDEBUG
1718     // LLVM arranges the stack as follows:
1719     //   ...
1720     //   ARG2
1721     //   ARG1
1722     //   RETADDR
1723     //   PUSH RBP   <-- RBP points here
1724     //   PUSH CSRs
1725     //   ~~~~~~~    <-- possible stack realignment (non-win64)
1726     //   ...
1727     //   STACK OBJECTS
1728     //   ...        <-- RSP after prologue points here
1729     //   ~~~~~~~    <-- possible stack realignment (win64)
1730     //
1731     // if (hasVarSizedObjects()):
1732     //   ...        <-- "base pointer" (ESI/RBX) points here
1733     //   DYNAMIC ALLOCAS
1734     //   ...        <-- RSP points here
1735     //
1736     // Case 1: In the simple case of no stack realignment and no dynamic
1737     // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
1738     // with fixed offsets from RSP.
1739     //
1740     // Case 2: In the case of stack realignment with no dynamic allocas, fixed
1741     // stack objects are addressed with RBP and regular stack objects with RSP.
1742     //
1743     // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
1744     // to address stack arguments for outgoing calls and nothing else. The "base
1745     // pointer" points to local variables, and RBP points to fixed objects.
1746     //
1747     // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
1748     // answer we give is relative to the SP after the prologue, and not the
1749     // SP in the middle of the function.
1750
1751     assert((!MFI->isFixedObjectIndex(FI) || !TRI->needsStackRealignment(MF) ||
1752             STI.isTargetWin64()) &&
1753            "offset from fixed object to SP is not static");
1754
1755     // We don't handle tail calls, and shouldn't be seeing them either.
1756     int TailCallReturnAddrDelta =
1757         MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1758     assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1759 #endif
1760   }
1761
1762   // Fill in FrameReg output argument.
1763   FrameReg = TRI->getStackRegister();
1764
1765   // This is how the math works out:
1766   //
1767   //  %rsp grows (i.e. gets lower) left to right. Each box below is
1768   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
1769   //  get to.
1770   //
1771   //    ----------------------------------
1772   //    | BP | Obj0 | Obj1 | ... | ObjN |
1773   //    ----------------------------------
1774   //    ^    ^      ^                   ^
1775   //    A    B      C                   E
1776   //
1777   // A is the incoming stack pointer.
1778   // (B - A) is the local area offset (-8 for x86-64) [1]
1779   // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1780   //
1781   // |(E - B)| is the StackSize (absolute value, positive).  For a
1782   // stack that grown down, this works out to be (B - E). [3]
1783   //
1784   // E is also the value of %rsp after stack has been set up, and we
1785   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
1786   // (C - E) == (C - A) - (B - A) + (B - E)
1787   //            { Using [1], [2] and [3] above }
1788   //         == getObjectOffset - LocalAreaOffset + StackSize
1789   //
1790
1791   // Get the Offset from the StackPointer
1792   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1793
1794   return Offset + StackSize;
1795 }
1796
1797 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1798     MachineFunction &MF, const TargetRegisterInfo *TRI,
1799     std::vector<CalleeSavedInfo> &CSI) const {
1800   MachineFrameInfo *MFI = MF.getFrameInfo();
1801   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1802
1803   unsigned CalleeSavedFrameSize = 0;
1804   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1805
1806   if (hasFP(MF)) {
1807     // emitPrologue always spills frame register the first thing.
1808     SpillSlotOffset -= SlotSize;
1809     MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1810
1811     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1812     // the frame register, we can delete it from CSI list and not have to worry
1813     // about avoiding it later.
1814     unsigned FPReg = TRI->getFrameRegister(MF);
1815     for (unsigned i = 0; i < CSI.size(); ++i) {
1816       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1817         CSI.erase(CSI.begin() + i);
1818         break;
1819       }
1820     }
1821   }
1822
1823   // Assign slots for GPRs. It increases frame size.
1824   for (unsigned i = CSI.size(); i != 0; --i) {
1825     unsigned Reg = CSI[i - 1].getReg();
1826
1827     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1828       continue;
1829
1830     SpillSlotOffset -= SlotSize;
1831     CalleeSavedFrameSize += SlotSize;
1832
1833     int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1834     CSI[i - 1].setFrameIdx(SlotIndex);
1835   }
1836
1837   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1838
1839   // Assign slots for XMMs.
1840   for (unsigned i = CSI.size(); i != 0; --i) {
1841     unsigned Reg = CSI[i - 1].getReg();
1842     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1843       continue;
1844
1845     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1846     // ensure alignment
1847     SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1848     // spill into slot
1849     SpillSlotOffset -= RC->getSize();
1850     int SlotIndex =
1851         MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1852     CSI[i - 1].setFrameIdx(SlotIndex);
1853     MFI->ensureMaxAlignment(RC->getAlignment());
1854   }
1855
1856   return true;
1857 }
1858
1859 bool X86FrameLowering::spillCalleeSavedRegisters(
1860     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1861     const std::vector<CalleeSavedInfo> &CSI,
1862     const TargetRegisterInfo *TRI) const {
1863   DebugLoc DL = MBB.findDebugLoc(MI);
1864
1865   // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
1866   // for us, and there are no XMM CSRs on Win32.
1867   if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
1868     return true;
1869
1870   // Push GPRs. It increases frame size.
1871   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1872   for (unsigned i = CSI.size(); i != 0; --i) {
1873     unsigned Reg = CSI[i - 1].getReg();
1874
1875     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1876       continue;
1877     // Add the callee-saved register as live-in. It's killed at the spill.
1878     MBB.addLiveIn(Reg);
1879
1880     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1881       .setMIFlag(MachineInstr::FrameSetup);
1882   }
1883
1884   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1885   // It can be done by spilling XMMs to stack frame.
1886   for (unsigned i = CSI.size(); i != 0; --i) {
1887     unsigned Reg = CSI[i-1].getReg();
1888     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1889       continue;
1890     // Add the callee-saved register as live-in. It's killed at the spill.
1891     MBB.addLiveIn(Reg);
1892     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1893
1894     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1895                             TRI);
1896     --MI;
1897     MI->setFlag(MachineInstr::FrameSetup);
1898     ++MI;
1899   }
1900
1901   return true;
1902 }
1903
1904 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1905                                                MachineBasicBlock::iterator MI,
1906                                         const std::vector<CalleeSavedInfo> &CSI,
1907                                           const TargetRegisterInfo *TRI) const {
1908   if (CSI.empty())
1909     return false;
1910
1911   if (isFuncletReturnInstr(MI) && STI.isOSWindows()) {
1912     // Don't restore CSRs in 32-bit EH funclets. Matches
1913     // spillCalleeSavedRegisters.
1914     if (STI.is32Bit())
1915       return true;
1916     // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
1917     // funclets. emitEpilogue transforms these to normal jumps.
1918     if (MI->getOpcode() == X86::CATCHRET) {
1919       const Function *Func = MBB.getParent()->getFunction();
1920       bool IsSEH = isAsynchronousEHPersonality(
1921           classifyEHPersonality(Func->getPersonalityFn()));
1922       if (IsSEH)
1923         return true;
1924     }
1925   }
1926
1927   DebugLoc DL = MBB.findDebugLoc(MI);
1928
1929   // Reload XMMs from stack frame.
1930   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1931     unsigned Reg = CSI[i].getReg();
1932     if (X86::GR64RegClass.contains(Reg) ||
1933         X86::GR32RegClass.contains(Reg))
1934       continue;
1935
1936     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1937     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1938   }
1939
1940   // POP GPRs.
1941   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1942   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1943     unsigned Reg = CSI[i].getReg();
1944     if (!X86::GR64RegClass.contains(Reg) &&
1945         !X86::GR32RegClass.contains(Reg))
1946       continue;
1947
1948     BuildMI(MBB, MI, DL, TII.get(Opc), Reg)
1949         .setMIFlag(MachineInstr::FrameDestroy);
1950   }
1951   return true;
1952 }
1953
1954 void X86FrameLowering::determineCalleeSaves(MachineFunction &MF,
1955                                             BitVector &SavedRegs,
1956                                             RegScavenger *RS) const {
1957   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1958
1959   MachineFrameInfo *MFI = MF.getFrameInfo();
1960
1961   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1962   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1963
1964   if (TailCallReturnAddrDelta < 0) {
1965     // create RETURNADDR area
1966     //   arg
1967     //   arg
1968     //   RETADDR
1969     //   { ...
1970     //     RETADDR area
1971     //     ...
1972     //   }
1973     //   [EBP]
1974     MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1975                            TailCallReturnAddrDelta - SlotSize, true);
1976   }
1977
1978   // Spill the BasePtr if it's used.
1979   if (TRI->hasBasePointer(MF)) {
1980     SavedRegs.set(TRI->getBaseRegister());
1981
1982     // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
1983     if (MF.getMMI().hasEHFunclets()) {
1984       int FI = MFI->CreateSpillStackObject(SlotSize, SlotSize);
1985       X86FI->setHasSEHFramePtrSave(true);
1986       X86FI->setSEHFramePtrSaveIndex(FI);
1987     }
1988   }
1989 }
1990
1991 static bool
1992 HasNestArgument(const MachineFunction *MF) {
1993   const Function *F = MF->getFunction();
1994   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1995        I != E; I++) {
1996     if (I->hasNestAttr())
1997       return true;
1998   }
1999   return false;
2000 }
2001
2002 /// GetScratchRegister - Get a temp register for performing work in the
2003 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
2004 /// and the properties of the function either one or two registers will be
2005 /// needed. Set primary to true for the first register, false for the second.
2006 static unsigned
2007 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
2008   CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
2009
2010   // Erlang stuff.
2011   if (CallingConvention == CallingConv::HiPE) {
2012     if (Is64Bit)
2013       return Primary ? X86::R14 : X86::R13;
2014     else
2015       return Primary ? X86::EBX : X86::EDI;
2016   }
2017
2018   if (Is64Bit) {
2019     if (IsLP64)
2020       return Primary ? X86::R11 : X86::R12;
2021     else
2022       return Primary ? X86::R11D : X86::R12D;
2023   }
2024
2025   bool IsNested = HasNestArgument(&MF);
2026
2027   if (CallingConvention == CallingConv::X86_FastCall ||
2028       CallingConvention == CallingConv::Fast) {
2029     if (IsNested)
2030       report_fatal_error("Segmented stacks does not support fastcall with "
2031                          "nested function.");
2032     return Primary ? X86::EAX : X86::ECX;
2033   }
2034   if (IsNested)
2035     return Primary ? X86::EDX : X86::EAX;
2036   return Primary ? X86::ECX : X86::EAX;
2037 }
2038
2039 // The stack limit in the TCB is set to this many bytes above the actual stack
2040 // limit.
2041 static const uint64_t kSplitStackAvailable = 256;
2042
2043 void X86FrameLowering::adjustForSegmentedStacks(
2044     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
2045   MachineFrameInfo *MFI = MF.getFrameInfo();
2046   uint64_t StackSize;
2047   unsigned TlsReg, TlsOffset;
2048   DebugLoc DL;
2049
2050   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
2051   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
2052          "Scratch register is live-in");
2053
2054   if (MF.getFunction()->isVarArg())
2055     report_fatal_error("Segmented stacks do not support vararg functions.");
2056   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
2057       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
2058       !STI.isTargetDragonFly())
2059     report_fatal_error("Segmented stacks not supported on this platform.");
2060
2061   // Eventually StackSize will be calculated by a link-time pass; which will
2062   // also decide whether checking code needs to be injected into this particular
2063   // prologue.
2064   StackSize = MFI->getStackSize();
2065
2066   // Do not generate a prologue for functions with a stack of size zero
2067   if (StackSize == 0)
2068     return;
2069
2070   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
2071   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
2072   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2073   bool IsNested = false;
2074
2075   // We need to know if the function has a nest argument only in 64 bit mode.
2076   if (Is64Bit)
2077     IsNested = HasNestArgument(&MF);
2078
2079   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
2080   // allocMBB needs to be last (terminating) instruction.
2081
2082   for (const auto &LI : PrologueMBB.liveins()) {
2083     allocMBB->addLiveIn(LI);
2084     checkMBB->addLiveIn(LI);
2085   }
2086
2087   if (IsNested)
2088     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
2089
2090   MF.push_front(allocMBB);
2091   MF.push_front(checkMBB);
2092
2093   // When the frame size is less than 256 we just compare the stack
2094   // boundary directly to the value of the stack pointer, per gcc.
2095   bool CompareStackPointer = StackSize < kSplitStackAvailable;
2096
2097   // Read the limit off the current stacklet off the stack_guard location.
2098   if (Is64Bit) {
2099     if (STI.isTargetLinux()) {
2100       TlsReg = X86::FS;
2101       TlsOffset = IsLP64 ? 0x70 : 0x40;
2102     } else if (STI.isTargetDarwin()) {
2103       TlsReg = X86::GS;
2104       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
2105     } else if (STI.isTargetWin64()) {
2106       TlsReg = X86::GS;
2107       TlsOffset = 0x28; // pvArbitrary, reserved for application use
2108     } else if (STI.isTargetFreeBSD()) {
2109       TlsReg = X86::FS;
2110       TlsOffset = 0x18;
2111     } else if (STI.isTargetDragonFly()) {
2112       TlsReg = X86::FS;
2113       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
2114     } else {
2115       report_fatal_error("Segmented stacks not supported on this platform.");
2116     }
2117
2118     if (CompareStackPointer)
2119       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
2120     else
2121       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
2122         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
2123
2124     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
2125       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
2126   } else {
2127     if (STI.isTargetLinux()) {
2128       TlsReg = X86::GS;
2129       TlsOffset = 0x30;
2130     } else if (STI.isTargetDarwin()) {
2131       TlsReg = X86::GS;
2132       TlsOffset = 0x48 + 90*4;
2133     } else if (STI.isTargetWin32()) {
2134       TlsReg = X86::FS;
2135       TlsOffset = 0x14; // pvArbitrary, reserved for application use
2136     } else if (STI.isTargetDragonFly()) {
2137       TlsReg = X86::FS;
2138       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
2139     } else if (STI.isTargetFreeBSD()) {
2140       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
2141     } else {
2142       report_fatal_error("Segmented stacks not supported on this platform.");
2143     }
2144
2145     if (CompareStackPointer)
2146       ScratchReg = X86::ESP;
2147     else
2148       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
2149         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
2150
2151     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
2152         STI.isTargetDragonFly()) {
2153       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
2154         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
2155     } else if (STI.isTargetDarwin()) {
2156
2157       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
2158       unsigned ScratchReg2;
2159       bool SaveScratch2;
2160       if (CompareStackPointer) {
2161         // The primary scratch register is available for holding the TLS offset.
2162         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
2163         SaveScratch2 = false;
2164       } else {
2165         // Need to use a second register to hold the TLS offset
2166         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
2167
2168         // Unfortunately, with fastcc the second scratch register may hold an
2169         // argument.
2170         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
2171       }
2172
2173       // If Scratch2 is live-in then it needs to be saved.
2174       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
2175              "Scratch register is live-in and not saved");
2176
2177       if (SaveScratch2)
2178         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
2179           .addReg(ScratchReg2, RegState::Kill);
2180
2181       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
2182         .addImm(TlsOffset);
2183       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
2184         .addReg(ScratchReg)
2185         .addReg(ScratchReg2).addImm(1).addReg(0)
2186         .addImm(0)
2187         .addReg(TlsReg);
2188
2189       if (SaveScratch2)
2190         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
2191     }
2192   }
2193
2194   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
2195   // It jumps to normal execution of the function body.
2196   BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&PrologueMBB);
2197
2198   // On 32 bit we first push the arguments size and then the frame size. On 64
2199   // bit, we pass the stack frame size in r10 and the argument size in r11.
2200   if (Is64Bit) {
2201     // Functions with nested arguments use R10, so it needs to be saved across
2202     // the call to _morestack
2203
2204     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
2205     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
2206     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
2207     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
2208     const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
2209
2210     if (IsNested)
2211       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
2212
2213     BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
2214       .addImm(StackSize);
2215     BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
2216       .addImm(X86FI->getArgumentStackSize());
2217   } else {
2218     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
2219       .addImm(X86FI->getArgumentStackSize());
2220     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
2221       .addImm(StackSize);
2222   }
2223
2224   // __morestack is in libgcc
2225   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
2226     // Under the large code model, we cannot assume that __morestack lives
2227     // within 2^31 bytes of the call site, so we cannot use pc-relative
2228     // addressing. We cannot perform the call via a temporary register,
2229     // as the rax register may be used to store the static chain, and all
2230     // other suitable registers may be either callee-save or used for
2231     // parameter passing. We cannot use the stack at this point either
2232     // because __morestack manipulates the stack directly.
2233     //
2234     // To avoid these issues, perform an indirect call via a read-only memory
2235     // location containing the address.
2236     //
2237     // This solution is not perfect, as it assumes that the .rodata section
2238     // is laid out within 2^31 bytes of each function body, but this seems
2239     // to be sufficient for JIT.
2240     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
2241         .addReg(X86::RIP)
2242         .addImm(0)
2243         .addReg(0)
2244         .addExternalSymbol("__morestack_addr")
2245         .addReg(0);
2246     MF.getMMI().setUsesMorestackAddr(true);
2247   } else {
2248     if (Is64Bit)
2249       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
2250         .addExternalSymbol("__morestack");
2251     else
2252       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
2253         .addExternalSymbol("__morestack");
2254   }
2255
2256   if (IsNested)
2257     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
2258   else
2259     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
2260
2261   allocMBB->addSuccessor(&PrologueMBB);
2262
2263   checkMBB->addSuccessor(allocMBB);
2264   checkMBB->addSuccessor(&PrologueMBB);
2265
2266 #ifdef XDEBUG
2267   MF.verify();
2268 #endif
2269 }
2270
2271 /// Erlang programs may need a special prologue to handle the stack size they
2272 /// might need at runtime. That is because Erlang/OTP does not implement a C
2273 /// stack but uses a custom implementation of hybrid stack/heap architecture.
2274 /// (for more information see Eric Stenman's Ph.D. thesis:
2275 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
2276 ///
2277 /// CheckStack:
2278 ///       temp0 = sp - MaxStack
2279 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
2280 /// OldStart:
2281 ///       ...
2282 /// IncStack:
2283 ///       call inc_stack   # doubles the stack space
2284 ///       temp0 = sp - MaxStack
2285 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
2286 void X86FrameLowering::adjustForHiPEPrologue(
2287     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
2288   MachineFrameInfo *MFI = MF.getFrameInfo();
2289   DebugLoc DL;
2290   // HiPE-specific values
2291   const unsigned HipeLeafWords = 24;
2292   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
2293   const unsigned Guaranteed = HipeLeafWords * SlotSize;
2294   unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
2295                             MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
2296   unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
2297
2298   assert(STI.isTargetLinux() &&
2299          "HiPE prologue is only supported on Linux operating systems.");
2300
2301   // Compute the largest caller's frame that is needed to fit the callees'
2302   // frames. This 'MaxStack' is computed from:
2303   //
2304   // a) the fixed frame size, which is the space needed for all spilled temps,
2305   // b) outgoing on-stack parameter areas, and
2306   // c) the minimum stack space this function needs to make available for the
2307   //    functions it calls (a tunable ABI property).
2308   if (MFI->hasCalls()) {
2309     unsigned MoreStackForCalls = 0;
2310
2311     for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
2312          MBBI != MBBE; ++MBBI)
2313       for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
2314            MI != ME; ++MI) {
2315         if (!MI->isCall())
2316           continue;
2317
2318         // Get callee operand.
2319         const MachineOperand &MO = MI->getOperand(0);
2320
2321         // Only take account of global function calls (no closures etc.).
2322         if (!MO.isGlobal())
2323           continue;
2324
2325         const Function *F = dyn_cast<Function>(MO.getGlobal());
2326         if (!F)
2327           continue;
2328
2329         // Do not update 'MaxStack' for primitive and built-in functions
2330         // (encoded with names either starting with "erlang."/"bif_" or not
2331         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
2332         // "_", such as the BIF "suspend_0") as they are executed on another
2333         // stack.
2334         if (F->getName().find("erlang.") != StringRef::npos ||
2335             F->getName().find("bif_") != StringRef::npos ||
2336             F->getName().find_first_of("._") == StringRef::npos)
2337           continue;
2338
2339         unsigned CalleeStkArity =
2340           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
2341         if (HipeLeafWords - 1 > CalleeStkArity)
2342           MoreStackForCalls = std::max(MoreStackForCalls,
2343                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
2344       }
2345     MaxStack += MoreStackForCalls;
2346   }
2347
2348   // If the stack frame needed is larger than the guaranteed then runtime checks
2349   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
2350   if (MaxStack > Guaranteed) {
2351     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
2352     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
2353
2354     for (const auto &LI : PrologueMBB.liveins()) {
2355       stackCheckMBB->addLiveIn(LI);
2356       incStackMBB->addLiveIn(LI);
2357     }
2358
2359     MF.push_front(incStackMBB);
2360     MF.push_front(stackCheckMBB);
2361
2362     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
2363     unsigned LEAop, CMPop, CALLop;
2364     if (Is64Bit) {
2365       SPReg = X86::RSP;
2366       PReg  = X86::RBP;
2367       LEAop = X86::LEA64r;
2368       CMPop = X86::CMP64rm;
2369       CALLop = X86::CALL64pcrel32;
2370       SPLimitOffset = 0x90;
2371     } else {
2372       SPReg = X86::ESP;
2373       PReg  = X86::EBP;
2374       LEAop = X86::LEA32r;
2375       CMPop = X86::CMP32rm;
2376       CALLop = X86::CALLpcrel32;
2377       SPLimitOffset = 0x4c;
2378     }
2379
2380     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
2381     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
2382            "HiPE prologue scratch register is live-in");
2383
2384     // Create new MBB for StackCheck:
2385     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
2386                  SPReg, false, -MaxStack);
2387     // SPLimitOffset is in a fixed heap location (pointed by BP).
2388     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
2389                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
2390     BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&PrologueMBB);
2391
2392     // Create new MBB for IncStack:
2393     BuildMI(incStackMBB, DL, TII.get(CALLop)).
2394       addExternalSymbol("inc_stack_0");
2395     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
2396                  SPReg, false, -MaxStack);
2397     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
2398                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
2399     BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
2400
2401     stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100});
2402     stackCheckMBB->addSuccessor(incStackMBB, {1, 100});
2403     incStackMBB->addSuccessor(&PrologueMBB, {99, 100});
2404     incStackMBB->addSuccessor(incStackMBB, {1, 100});
2405   }
2406 #ifdef XDEBUG
2407   MF.verify();
2408 #endif
2409 }
2410
2411 bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
2412     MachineBasicBlock::iterator MBBI, DebugLoc DL, int Offset) const {
2413
2414   if (Offset <= 0)
2415     return false;
2416
2417   if (Offset % SlotSize)
2418     return false;
2419
2420   int NumPops = Offset / SlotSize;
2421   // This is only worth it if we have at most 2 pops.
2422   if (NumPops != 1 && NumPops != 2)
2423     return false;
2424
2425   // Handle only the trivial case where the adjustment directly follows
2426   // a call. This is the most common one, anyway.
2427   if (MBBI == MBB.begin())
2428     return false;
2429   MachineBasicBlock::iterator Prev = std::prev(MBBI);
2430   if (!Prev->isCall() || !Prev->getOperand(1).isRegMask())
2431     return false;
2432
2433   unsigned Regs[2];
2434   unsigned FoundRegs = 0;
2435
2436   auto RegMask = Prev->getOperand(1);
2437
2438   auto &RegClass =
2439       Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
2440   // Try to find up to NumPops free registers.
2441   for (auto Candidate : RegClass) {
2442
2443     // Poor man's liveness:
2444     // Since we're immediately after a call, any register that is clobbered
2445     // by the call and not defined by it can be considered dead.
2446     if (!RegMask.clobbersPhysReg(Candidate))
2447       continue;
2448
2449     bool IsDef = false;
2450     for (const MachineOperand &MO : Prev->implicit_operands()) {
2451       if (MO.isReg() && MO.isDef() && MO.getReg() == Candidate) {
2452         IsDef = true;
2453         break;
2454       }
2455     }
2456
2457     if (IsDef)
2458       continue;
2459
2460     Regs[FoundRegs++] = Candidate;
2461     if (FoundRegs == (unsigned)NumPops)
2462       break;
2463   }
2464
2465   if (FoundRegs == 0)
2466     return false;
2467
2468   // If we found only one free register, but need two, reuse the same one twice.
2469   while (FoundRegs < (unsigned)NumPops)
2470     Regs[FoundRegs++] = Regs[0];
2471
2472   for (int i = 0; i < NumPops; ++i)
2473     BuildMI(MBB, MBBI, DL, 
2474             TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r), Regs[i]);
2475
2476   return true;
2477 }
2478
2479 void X86FrameLowering::
2480 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
2481                               MachineBasicBlock::iterator I) const {
2482   bool reserveCallFrame = hasReservedCallFrame(MF);
2483   unsigned Opcode = I->getOpcode();
2484   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
2485   DebugLoc DL = I->getDebugLoc();
2486   uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
2487   uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
2488   I = MBB.erase(I);
2489
2490   if (!reserveCallFrame) {
2491     // If the stack pointer can be changed after prologue, turn the
2492     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
2493     // adjcallstackdown instruction into 'add ESP, <amt>'
2494
2495     // We need to keep the stack aligned properly.  To do this, we round the
2496     // amount of space needed for the outgoing arguments up to the next
2497     // alignment boundary.
2498     unsigned StackAlign = getStackAlignment();
2499     Amount = RoundUpToAlignment(Amount, StackAlign);
2500
2501     MachineModuleInfo &MMI = MF.getMMI();
2502     const Function *Fn = MF.getFunction();
2503     bool WindowsCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
2504     bool DwarfCFI = !WindowsCFI && 
2505                     (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
2506
2507     // If we have any exception handlers in this function, and we adjust
2508     // the SP before calls, we may need to indicate this to the unwinder
2509     // using GNU_ARGS_SIZE. Note that this may be necessary even when
2510     // Amount == 0, because the preceding function may have set a non-0
2511     // GNU_ARGS_SIZE.
2512     // TODO: We don't need to reset this between subsequent functions,
2513     // if it didn't change.
2514     bool HasDwarfEHHandlers = !WindowsCFI &&
2515                               !MF.getMMI().getLandingPads().empty();
2516
2517     if (HasDwarfEHHandlers && !isDestroy &&
2518         MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences())
2519       BuildCFI(MBB, I, DL,
2520                MCCFIInstruction::createGnuArgsSize(nullptr, Amount));
2521
2522     if (Amount == 0)
2523       return;
2524
2525     // Factor out the amount that gets handled inside the sequence
2526     // (Pushes of argument for frame setup, callee pops for frame destroy)
2527     Amount -= InternalAmt;
2528
2529     // TODO: This is needed only if we require precise CFA.
2530     // If this is a callee-pop calling convention, emit a CFA adjust for
2531     // the amount the callee popped.
2532     if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF))
2533       BuildCFI(MBB, I, DL, 
2534                MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt));
2535
2536     if (Amount) {
2537       // Add Amount to SP to destroy a frame, and subtract to setup.
2538       int Offset = isDestroy ? Amount : -Amount;
2539
2540       if (!(Fn->optForMinSize() && 
2541             adjustStackWithPops(MBB, I, DL, Offset)))
2542         BuildStackAdjustment(MBB, I, DL, Offset, /*InEpilogue=*/false);
2543     }
2544
2545     if (DwarfCFI && !hasFP(MF)) {
2546       // If we don't have FP, but need to generate unwind information,
2547       // we need to set the correct CFA offset after the stack adjustment.
2548       // How much we adjust the CFA offset depends on whether we're emitting
2549       // CFI only for EH purposes or for debugging. EH only requires the CFA
2550       // offset to be correct at each call site, while for debugging we want
2551       // it to be more precise.
2552       int CFAOffset = Amount;
2553       // TODO: When not using precise CFA, we also need to adjust for the
2554       // InternalAmt here.
2555
2556       if (CFAOffset) {
2557         CFAOffset = isDestroy ? -CFAOffset : CFAOffset;
2558         BuildCFI(MBB, I, DL, 
2559                  MCCFIInstruction::createAdjustCfaOffset(nullptr, CFAOffset));
2560       }
2561     }
2562
2563     return;
2564   }
2565
2566   if (isDestroy && InternalAmt) {
2567     // If we are performing frame pointer elimination and if the callee pops
2568     // something off the stack pointer, add it back.  We do this until we have
2569     // more advanced stack pointer tracking ability.
2570     // We are not tracking the stack pointer adjustment by the callee, so make
2571     // sure we restore the stack pointer immediately after the call, there may
2572     // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
2573     MachineBasicBlock::iterator B = MBB.begin();
2574     while (I != B && !std::prev(I)->isCall())
2575       --I;
2576     BuildStackAdjustment(MBB, I, DL, -InternalAmt, /*InEpilogue=*/false);
2577   }
2578 }
2579
2580 bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
2581   assert(MBB.getParent() && "Block is not attached to a function!");
2582
2583   // Win64 has strict requirements in terms of epilogue and we are
2584   // not taking a chance at messing with them.
2585   // I.e., unless this block is already an exit block, we can't use
2586   // it as an epilogue.
2587   if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
2588     return false;
2589
2590   if (canUseLEAForSPInEpilogue(*MBB.getParent()))
2591     return true;
2592
2593   // If we cannot use LEA to adjust SP, we may need to use ADD, which
2594   // clobbers the EFLAGS. Check that we do not need to preserve it,
2595   // otherwise, conservatively assume this is not
2596   // safe to insert the epilogue here.
2597   return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
2598 }
2599
2600 bool X86FrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
2601   // If we may need to emit frameless compact unwind information, give
2602   // up as this is currently broken: PR25614.
2603   return MF.getFunction()->hasFnAttribute(Attribute::NoUnwind) || hasFP(MF);
2604 }
2605
2606 MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers(
2607     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
2608     DebugLoc DL, bool RestoreSP) const {
2609   assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
2610   assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
2611   assert(STI.is32Bit() && !Uses64BitFramePtr &&
2612          "restoring EBP/ESI on non-32-bit target");
2613
2614   MachineFunction &MF = *MBB.getParent();
2615   unsigned FramePtr = TRI->getFrameRegister(MF);
2616   unsigned BasePtr = TRI->getBaseRegister();
2617   WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
2618   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2619   MachineFrameInfo *MFI = MF.getFrameInfo();
2620
2621   // FIXME: Don't set FrameSetup flag in catchret case.
2622
2623   int FI = FuncInfo.EHRegNodeFrameIndex;
2624   int EHRegSize = MFI->getObjectSize(FI);
2625
2626   if (RestoreSP) {
2627     // MOV32rm -EHRegSize(%ebp), %esp
2628     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP),
2629                  X86::EBP, true, -EHRegSize)
2630         .setMIFlag(MachineInstr::FrameSetup);
2631   }
2632
2633   unsigned UsedReg;
2634   int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg);
2635   int EndOffset = -EHRegOffset - EHRegSize;
2636   FuncInfo.EHRegNodeEndOffset = EndOffset;
2637
2638   if (UsedReg == FramePtr) {
2639     // ADD $offset, %ebp
2640     unsigned ADDri = getADDriOpcode(false, EndOffset);
2641     BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr)
2642         .addReg(FramePtr)
2643         .addImm(EndOffset)
2644         .setMIFlag(MachineInstr::FrameSetup)
2645         ->getOperand(3)
2646         .setIsDead();
2647     assert(EndOffset >= 0 &&
2648            "end of registration object above normal EBP position!");
2649   } else if (UsedReg == BasePtr) {
2650     // LEA offset(%ebp), %esi
2651     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr),
2652                  FramePtr, false, EndOffset)
2653         .setMIFlag(MachineInstr::FrameSetup);
2654     // MOV32rm SavedEBPOffset(%esi), %ebp
2655     assert(X86FI->getHasSEHFramePtrSave());
2656     int Offset =
2657         getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg);
2658     assert(UsedReg == BasePtr);
2659     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr),
2660                  UsedReg, true, Offset)
2661         .setMIFlag(MachineInstr::FrameSetup);
2662   } else {
2663     llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
2664   }
2665   return MBBI;
2666 }
2667
2668 unsigned X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const {
2669   // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
2670   unsigned Offset = 16;
2671   // RBP is immediately pushed.
2672   Offset += SlotSize;
2673   // All callee-saved registers are then pushed.
2674   Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
2675   // Every funclet allocates enough stack space for the largest outgoing call.
2676   Offset += getWinEHFuncletFrameSize(MF);
2677   return Offset;
2678 }
2679
2680 void X86FrameLowering::processFunctionBeforeFrameFinalized(
2681     MachineFunction &MF, RegScavenger *RS) const {
2682   // If this function isn't doing Win64-style C++ EH, we don't need to do
2683   // anything.
2684   const Function *Fn = MF.getFunction();
2685   if (!STI.is64Bit() || !MF.getMMI().hasEHFunclets() ||
2686       classifyEHPersonality(Fn->getPersonalityFn()) != EHPersonality::MSVC_CXX)
2687     return;
2688
2689   // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
2690   // relative to RSP after the prologue.  Find the offset of the last fixed
2691   // object, so that we can allocate a slot immediately following it. If there
2692   // were no fixed objects, use offset -SlotSize, which is immediately after the
2693   // return address. Fixed objects have negative frame indices.
2694   MachineFrameInfo *MFI = MF.getFrameInfo();
2695   int64_t MinFixedObjOffset = -SlotSize;
2696   for (int I = MFI->getObjectIndexBegin(); I < 0; ++I)
2697     MinFixedObjOffset = std::min(MinFixedObjOffset, MFI->getObjectOffset(I));
2698
2699   int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
2700   int UnwindHelpFI =
2701       MFI->CreateFixedObject(SlotSize, UnwindHelpOffset, /*Immutable=*/false);
2702   MF.getWinEHFuncInfo()->UnwindHelpFrameIdx = UnwindHelpFI;
2703
2704   // Store -2 into UnwindHelp on function entry. We have to scan forwards past
2705   // other frame setup instructions.
2706   MachineBasicBlock &MBB = MF.front();
2707   auto MBBI = MBB.begin();
2708   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
2709     ++MBBI;
2710
2711   DebugLoc DL = MBB.findDebugLoc(MBBI);
2712   addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),
2713                     UnwindHelpFI)
2714       .addImm(-2);
2715 }