1 //===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the X86 implementation of TargetFrameLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "X86FrameLowering.h"
14 #include "X86InstrBuilder.h"
15 #include "X86InstrInfo.h"
16 #include "X86MachineFunctionInfo.h"
17 #include "X86Subtarget.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.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/Support/Debug.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include <cstdlib>
35 
36 #define DEBUG_TYPE "x86-fl"
37 
38 STATISTIC(NumFrameLoopProbe, "Number of loop stack probes used in prologue");
39 STATISTIC(NumFrameExtraProbe,
40           "Number of extra stack probes generated in prologue");
41 
42 using namespace llvm;
43 
44 X86FrameLowering::X86FrameLowering(const X86Subtarget &STI,
45                                    MaybeAlign StackAlignOverride)
46     : TargetFrameLowering(StackGrowsDown, StackAlignOverride.valueOrOne(),
47                           STI.is64Bit() ? -8 : -4),
48       STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {
49   // Cache a bunch of frame-related predicates for this subtarget.
50   SlotSize = TRI->getSlotSize();
51   Is64Bit = STI.is64Bit();
52   IsLP64 = STI.isTarget64BitLP64();
53   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
54   Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
55   StackPtr = TRI->getStackRegister();
56 }
57 
58 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
59   return !MF.getFrameInfo().hasVarSizedObjects() &&
60          !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
61 }
62 
63 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
64 /// call frame pseudos can be simplified.  Having a FP, as in the default
65 /// implementation, is not sufficient here since we can't always use it.
66 /// Use a more nuanced condition.
67 bool
68 X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
69   return hasReservedCallFrame(MF) ||
70          (hasFP(MF) && !TRI->needsStackRealignment(MF)) ||
71          TRI->hasBasePointer(MF);
72 }
73 
74 // needsFrameIndexResolution - Do we need to perform FI resolution for
75 // this function. Normally, this is required only when the function
76 // has any stack objects. However, FI resolution actually has another job,
77 // not apparent from the title - it resolves callframesetup/destroy
78 // that were not simplified earlier.
79 // So, this is required for x86 functions that have push sequences even
80 // when there are no stack objects.
81 bool
82 X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
83   return MF.getFrameInfo().hasStackObjects() ||
84          MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
85 }
86 
87 /// hasFP - Return true if the specified function should have a dedicated frame
88 /// pointer register.  This is true if the function has variable sized allocas
89 /// or if frame pointer elimination is disabled.
90 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
91   const MachineFrameInfo &MFI = MF.getFrameInfo();
92   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
93           TRI->needsStackRealignment(MF) ||
94           MFI.hasVarSizedObjects() ||
95           MFI.isFrameAddressTaken() || MFI.hasOpaqueSPAdjustment() ||
96           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
97           MF.callsUnwindInit() || MF.hasEHFunclets() || MF.callsEHReturn() ||
98           MFI.hasStackMap() || MFI.hasPatchPoint() ||
99           MFI.hasCopyImplyingStackAdjustment());
100 }
101 
102 static unsigned getSUBriOpcode(bool IsLP64, int64_t Imm) {
103   if (IsLP64) {
104     if (isInt<8>(Imm))
105       return X86::SUB64ri8;
106     return X86::SUB64ri32;
107   } else {
108     if (isInt<8>(Imm))
109       return X86::SUB32ri8;
110     return X86::SUB32ri;
111   }
112 }
113 
114 static unsigned getADDriOpcode(bool IsLP64, int64_t Imm) {
115   if (IsLP64) {
116     if (isInt<8>(Imm))
117       return X86::ADD64ri8;
118     return X86::ADD64ri32;
119   } else {
120     if (isInt<8>(Imm))
121       return X86::ADD32ri8;
122     return X86::ADD32ri;
123   }
124 }
125 
126 static unsigned getSUBrrOpcode(bool IsLP64) {
127   return IsLP64 ? X86::SUB64rr : X86::SUB32rr;
128 }
129 
130 static unsigned getADDrrOpcode(bool IsLP64) {
131   return IsLP64 ? X86::ADD64rr : X86::ADD32rr;
132 }
133 
134 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
135   if (IsLP64) {
136     if (isInt<8>(Imm))
137       return X86::AND64ri8;
138     return X86::AND64ri32;
139   }
140   if (isInt<8>(Imm))
141     return X86::AND32ri8;
142   return X86::AND32ri;
143 }
144 
145 static unsigned getLEArOpcode(bool IsLP64) {
146   return IsLP64 ? X86::LEA64r : X86::LEA32r;
147 }
148 
149 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
150 /// when it reaches the "return" instruction. We can then pop a stack object
151 /// to this register without worry about clobbering it.
152 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
153                                        MachineBasicBlock::iterator &MBBI,
154                                        const X86RegisterInfo *TRI,
155                                        bool Is64Bit) {
156   const MachineFunction *MF = MBB.getParent();
157   if (MF->callsEHReturn())
158     return 0;
159 
160   const TargetRegisterClass &AvailableRegs = *TRI->getGPRsForTailCall(*MF);
161 
162   if (MBBI == MBB.end())
163     return 0;
164 
165   switch (MBBI->getOpcode()) {
166   default: return 0;
167   case TargetOpcode::PATCHABLE_RET:
168   case X86::RET:
169   case X86::RETL:
170   case X86::RETQ:
171   case X86::RETIL:
172   case X86::RETIQ:
173   case X86::TCRETURNdi:
174   case X86::TCRETURNri:
175   case X86::TCRETURNmi:
176   case X86::TCRETURNdi64:
177   case X86::TCRETURNri64:
178   case X86::TCRETURNmi64:
179   case X86::EH_RETURN:
180   case X86::EH_RETURN64: {
181     SmallSet<uint16_t, 8> Uses;
182     for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
183       MachineOperand &MO = MBBI->getOperand(i);
184       if (!MO.isReg() || MO.isDef())
185         continue;
186       Register Reg = MO.getReg();
187       if (!Reg)
188         continue;
189       for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
190         Uses.insert(*AI);
191     }
192 
193     for (auto CS : AvailableRegs)
194       if (!Uses.count(CS) && CS != X86::RIP && CS != X86::RSP &&
195           CS != X86::ESP)
196         return CS;
197   }
198   }
199 
200   return 0;
201 }
202 
203 static bool isEAXLiveIn(MachineBasicBlock &MBB) {
204   for (MachineBasicBlock::RegisterMaskPair RegMask : MBB.liveins()) {
205     unsigned Reg = RegMask.PhysReg;
206 
207     if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
208         Reg == X86::AH || Reg == X86::AL)
209       return true;
210   }
211 
212   return false;
213 }
214 
215 /// Check if the flags need to be preserved before the terminators.
216 /// This would be the case, if the eflags is live-in of the region
217 /// composed by the terminators or live-out of that region, without
218 /// being defined by a terminator.
219 static bool
220 flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) {
221   for (const MachineInstr &MI : MBB.terminators()) {
222     bool BreakNext = false;
223     for (const MachineOperand &MO : MI.operands()) {
224       if (!MO.isReg())
225         continue;
226       Register Reg = MO.getReg();
227       if (Reg != X86::EFLAGS)
228         continue;
229 
230       // This terminator needs an eflags that is not defined
231       // by a previous another terminator:
232       // EFLAGS is live-in of the region composed by the terminators.
233       if (!MO.isDef())
234         return true;
235       // This terminator defines the eflags, i.e., we don't need to preserve it.
236       // However, we still need to check this specific terminator does not
237       // read a live-in value.
238       BreakNext = true;
239     }
240     // We found a definition of the eflags, no need to preserve them.
241     if (BreakNext)
242       return false;
243   }
244 
245   // None of the terminators use or define the eflags.
246   // Check if they are live-out, that would imply we need to preserve them.
247   for (const MachineBasicBlock *Succ : MBB.successors())
248     if (Succ->isLiveIn(X86::EFLAGS))
249       return true;
250 
251   return false;
252 }
253 
254 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
255 /// stack pointer by a constant value.
256 void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
257                                     MachineBasicBlock::iterator &MBBI,
258                                     const DebugLoc &DL,
259                                     int64_t NumBytes, bool InEpilogue) const {
260   bool isSub = NumBytes < 0;
261   uint64_t Offset = isSub ? -NumBytes : NumBytes;
262   MachineInstr::MIFlag Flag =
263       isSub ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy;
264 
265   uint64_t Chunk = (1LL << 31) - 1;
266 
267   MachineFunction &MF = *MBB.getParent();
268   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
269   const X86TargetLowering &TLI = *STI.getTargetLowering();
270   const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
271 
272   // It's ok to not take into account large chunks when probing, as the
273   // allocation is split in smaller chunks anyway.
274   if (EmitInlineStackProbe && !InEpilogue) {
275 
276     // stack probing may involve looping, and control flow generations is
277     // disallowed at this point. Rely to later processing through
278     // `inlineStackProbe`.
279     MachineInstr *Stub = emitStackProbeInlineStub(MF, MBB, MBBI, DL, true);
280 
281     // Encode the static offset as a metadata attached to the stub.
282     LLVMContext &Context = MF.getFunction().getContext();
283     MachineInstrBuilder(MF, Stub).addMetadata(
284         MDTuple::get(Context, {ConstantAsMetadata::get(ConstantInt::get(
285                                   IntegerType::get(Context, 64), Offset))}));
286     return;
287   } else if (Offset > Chunk) {
288     // Rather than emit a long series of instructions for large offsets,
289     // load the offset into a register and do one sub/add
290     unsigned Reg = 0;
291     unsigned Rax = (unsigned)(Is64Bit ? X86::RAX : X86::EAX);
292 
293     if (isSub && !isEAXLiveIn(MBB))
294       Reg = Rax;
295     else
296       Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
297 
298     unsigned MovRIOpc = Is64Bit ? X86::MOV64ri : X86::MOV32ri;
299     unsigned AddSubRROpc =
300         isSub ? getSUBrrOpcode(Is64Bit) : getADDrrOpcode(Is64Bit);
301     if (Reg) {
302       BuildMI(MBB, MBBI, DL, TII.get(MovRIOpc), Reg)
303           .addImm(Offset)
304           .setMIFlag(Flag);
305       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AddSubRROpc), StackPtr)
306                              .addReg(StackPtr)
307                              .addReg(Reg);
308       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
309       return;
310     } else if (Offset > 8 * Chunk) {
311       // If we would need more than 8 add or sub instructions (a >16GB stack
312       // frame), it's worth spilling RAX to materialize this immediate.
313       //   pushq %rax
314       //   movabsq +-$Offset+-SlotSize, %rax
315       //   addq %rsp, %rax
316       //   xchg %rax, (%rsp)
317       //   movq (%rsp), %rsp
318       assert(Is64Bit && "can't have 32-bit 16GB stack frame");
319       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
320           .addReg(Rax, RegState::Kill)
321           .setMIFlag(Flag);
322       // Subtract is not commutative, so negate the offset and always use add.
323       // Subtract 8 less and add 8 more to account for the PUSH we just did.
324       if (isSub)
325         Offset = -(Offset - SlotSize);
326       else
327         Offset = Offset + SlotSize;
328       BuildMI(MBB, MBBI, DL, TII.get(MovRIOpc), Rax)
329           .addImm(Offset)
330           .setMIFlag(Flag);
331       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(X86::ADD64rr), Rax)
332                              .addReg(Rax)
333                              .addReg(StackPtr);
334       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
335       // Exchange the new SP in RAX with the top of the stack.
336       addRegOffset(
337           BuildMI(MBB, MBBI, DL, TII.get(X86::XCHG64rm), Rax).addReg(Rax),
338           StackPtr, false, 0);
339       // Load new SP from the top of the stack into RSP.
340       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), StackPtr),
341                    StackPtr, false, 0);
342       return;
343     }
344   }
345 
346   while (Offset) {
347     uint64_t ThisVal = std::min(Offset, Chunk);
348     if (ThisVal == SlotSize) {
349       // Use push / pop for slot sized adjustments as a size optimization. We
350       // need to find a dead register when using pop.
351       unsigned Reg = isSub
352         ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
353         : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
354       if (Reg) {
355         unsigned Opc = isSub
356           ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
357           : (Is64Bit ? X86::POP64r  : X86::POP32r);
358         BuildMI(MBB, MBBI, DL, TII.get(Opc))
359             .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub))
360             .setMIFlag(Flag);
361         Offset -= ThisVal;
362         continue;
363       }
364     }
365 
366     BuildStackAdjustment(MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue)
367         .setMIFlag(Flag);
368 
369     Offset -= ThisVal;
370   }
371 }
372 
373 MachineInstrBuilder X86FrameLowering::BuildStackAdjustment(
374     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
375     const DebugLoc &DL, int64_t Offset, bool InEpilogue) const {
376   assert(Offset != 0 && "zero offset stack adjustment requested");
377 
378   // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue
379   // is tricky.
380   bool UseLEA;
381   if (!InEpilogue) {
382     // Check if inserting the prologue at the beginning
383     // of MBB would require to use LEA operations.
384     // We need to use LEA operations if EFLAGS is live in, because
385     // it means an instruction will read it before it gets defined.
386     UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS);
387   } else {
388     // If we can use LEA for SP but we shouldn't, check that none
389     // of the terminators uses the eflags. Otherwise we will insert
390     // a ADD that will redefine the eflags and break the condition.
391     // Alternatively, we could move the ADD, but this may not be possible
392     // and is an optimization anyway.
393     UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent());
394     if (UseLEA && !STI.useLeaForSP())
395       UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB);
396     // If that assert breaks, that means we do not do the right thing
397     // in canUseAsEpilogue.
398     assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) &&
399            "We shouldn't have allowed this insertion point");
400   }
401 
402   MachineInstrBuilder MI;
403   if (UseLEA) {
404     MI = addRegOffset(BuildMI(MBB, MBBI, DL,
405                               TII.get(getLEArOpcode(Uses64BitFramePtr)),
406                               StackPtr),
407                       StackPtr, false, Offset);
408   } else {
409     bool IsSub = Offset < 0;
410     uint64_t AbsOffset = IsSub ? -Offset : Offset;
411     const unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr, AbsOffset)
412                                : getADDriOpcode(Uses64BitFramePtr, AbsOffset);
413     MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
414              .addReg(StackPtr)
415              .addImm(AbsOffset);
416     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
417   }
418   return MI;
419 }
420 
421 int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
422                                      MachineBasicBlock::iterator &MBBI,
423                                      bool doMergeWithPrevious) const {
424   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
425       (!doMergeWithPrevious && MBBI == MBB.end()))
426     return 0;
427 
428   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
429 
430   PI = skipDebugInstructionsBackward(PI, MBB.begin());
431   // It is assumed that ADD/SUB/LEA instruction is succeded by one CFI
432   // instruction, and that there are no DBG_VALUE or other instructions between
433   // ADD/SUB/LEA and its corresponding CFI instruction.
434   /* TODO: Add support for the case where there are multiple CFI instructions
435     below the ADD/SUB/LEA, e.g.:
436     ...
437     add
438     cfi_def_cfa_offset
439     cfi_offset
440     ...
441   */
442   if (doMergeWithPrevious && PI != MBB.begin() && PI->isCFIInstruction())
443     PI = std::prev(PI);
444 
445   unsigned Opc = PI->getOpcode();
446   int Offset = 0;
447 
448   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
449        Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
450       PI->getOperand(0).getReg() == StackPtr){
451     assert(PI->getOperand(1).getReg() == StackPtr);
452     Offset = PI->getOperand(2).getImm();
453   } else if ((Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
454              PI->getOperand(0).getReg() == StackPtr &&
455              PI->getOperand(1).getReg() == StackPtr &&
456              PI->getOperand(2).getImm() == 1 &&
457              PI->getOperand(3).getReg() == X86::NoRegister &&
458              PI->getOperand(5).getReg() == X86::NoRegister) {
459     // For LEAs we have: def = lea SP, FI, noreg, Offset, noreg.
460     Offset = PI->getOperand(4).getImm();
461   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
462               Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
463              PI->getOperand(0).getReg() == StackPtr) {
464     assert(PI->getOperand(1).getReg() == StackPtr);
465     Offset = -PI->getOperand(2).getImm();
466   } else
467     return 0;
468 
469   PI = MBB.erase(PI);
470   if (PI != MBB.end() && PI->isCFIInstruction()) PI = MBB.erase(PI);
471   if (!doMergeWithPrevious)
472     MBBI = skipDebugInstructionsForward(PI, MBB.end());
473 
474   return Offset;
475 }
476 
477 void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB,
478                                 MachineBasicBlock::iterator MBBI,
479                                 const DebugLoc &DL,
480                                 const MCCFIInstruction &CFIInst) const {
481   MachineFunction &MF = *MBB.getParent();
482   unsigned CFIIndex = MF.addFrameInst(CFIInst);
483   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
484       .addCFIIndex(CFIIndex);
485 }
486 
487 void X86FrameLowering::emitCalleeSavedFrameMoves(
488     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
489     const DebugLoc &DL) const {
490   MachineFunction &MF = *MBB.getParent();
491   MachineFrameInfo &MFI = MF.getFrameInfo();
492   MachineModuleInfo &MMI = MF.getMMI();
493   const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
494 
495   // Add callee saved registers to move list.
496   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
497   if (CSI.empty()) return;
498 
499   // Calculate offsets.
500   for (std::vector<CalleeSavedInfo>::const_iterator
501          I = CSI.begin(), E = CSI.end(); I != E; ++I) {
502     int64_t Offset = MFI.getObjectOffset(I->getFrameIdx());
503     unsigned Reg = I->getReg();
504 
505     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
506     BuildCFI(MBB, MBBI, DL,
507              MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
508   }
509 }
510 
511 void X86FrameLowering::emitStackProbe(MachineFunction &MF,
512                                       MachineBasicBlock &MBB,
513                                       MachineBasicBlock::iterator MBBI,
514                                       const DebugLoc &DL, bool InProlog) const {
515   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
516   if (STI.isTargetWindowsCoreCLR()) {
517     if (InProlog) {
518       emitStackProbeInlineStub(MF, MBB, MBBI, DL, true);
519     } else {
520       emitStackProbeInline(MF, MBB, MBBI, DL, false);
521     }
522   } else {
523     emitStackProbeCall(MF, MBB, MBBI, DL, InProlog);
524   }
525 }
526 
527 void X86FrameLowering::inlineStackProbe(MachineFunction &MF,
528                                         MachineBasicBlock &PrologMBB) const {
529   const StringRef ChkStkStubSymbol = "__chkstk_stub";
530   MachineInstr *ChkStkStub = nullptr;
531 
532   for (MachineInstr &MI : PrologMBB) {
533     if (MI.isCall() && MI.getOperand(0).isSymbol() &&
534         ChkStkStubSymbol == MI.getOperand(0).getSymbolName()) {
535       ChkStkStub = &MI;
536       break;
537     }
538   }
539 
540   if (ChkStkStub != nullptr) {
541     assert(!ChkStkStub->isBundled() &&
542            "Not expecting bundled instructions here");
543     MachineBasicBlock::iterator MBBI = std::next(ChkStkStub->getIterator());
544     assert(std::prev(MBBI) == ChkStkStub &&
545            "MBBI expected after __chkstk_stub.");
546     DebugLoc DL = PrologMBB.findDebugLoc(MBBI);
547     emitStackProbeInline(MF, PrologMBB, MBBI, DL, true);
548     ChkStkStub->eraseFromParent();
549   }
550 }
551 
552 void X86FrameLowering::emitStackProbeInline(MachineFunction &MF,
553                                             MachineBasicBlock &MBB,
554                                             MachineBasicBlock::iterator MBBI,
555                                             const DebugLoc &DL,
556                                             bool InProlog) const {
557   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
558   if (STI.isTargetWindowsCoreCLR() && STI.is64Bit())
559     emitStackProbeInlineWindowsCoreCLR64(MF, MBB, MBBI, DL, InProlog);
560   else
561     emitStackProbeInlineGeneric(MF, MBB, MBBI, DL, InProlog);
562 }
563 
564 void X86FrameLowering::emitStackProbeInlineGeneric(
565     MachineFunction &MF, MachineBasicBlock &MBB,
566     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
567   MachineInstr &CallToInline = *std::prev(MBBI);
568   assert(CallToInline.getOperand(1).isMetadata() &&
569          "no metadata attached to that probe");
570   uint64_t Offset =
571       cast<ConstantInt>(
572           cast<ConstantAsMetadata>(
573               cast<MDTuple>(CallToInline.getOperand(1).getMetadata())
574                   ->getOperand(0))
575               ->getValue())
576           ->getZExtValue();
577 
578   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
579   const X86TargetLowering &TLI = *STI.getTargetLowering();
580   assert(!(STI.is64Bit() && STI.isTargetWindowsCoreCLR()) &&
581          "different expansion expected for CoreCLR 64 bit");
582 
583   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
584   uint64_t ProbeChunk = StackProbeSize * 8;
585 
586   // Synthesize a loop or unroll it, depending on the number of iterations.
587   if (Offset > ProbeChunk) {
588     emitStackProbeInlineGenericLoop(MF, MBB, MBBI, DL, Offset);
589   } else {
590     emitStackProbeInlineGenericBlock(MF, MBB, MBBI, DL, Offset);
591   }
592 }
593 
594 void X86FrameLowering::emitStackProbeInlineGenericBlock(
595     MachineFunction &MF, MachineBasicBlock &MBB,
596     MachineBasicBlock::iterator MBBI, const DebugLoc &DL,
597     uint64_t Offset) const {
598 
599   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
600   const X86TargetLowering &TLI = *STI.getTargetLowering();
601   const unsigned Opc = getSUBriOpcode(Uses64BitFramePtr, Offset);
602   const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
603   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
604   uint64_t CurrentOffset = 0;
605   // 0 Thanks to return address being saved on the stack
606   uint64_t CurrentProbeOffset = 0;
607 
608   // For the first N - 1 pages, just probe. I tried to take advantage of
609   // natural probes but it implies much more logic and there was very few
610   // interesting natural probes to interleave.
611   while (CurrentOffset + StackProbeSize < Offset) {
612     MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
613                            .addReg(StackPtr)
614                            .addImm(StackProbeSize)
615                            .setMIFlag(MachineInstr::FrameSetup);
616     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
617 
618 
619     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
620                      .setMIFlag(MachineInstr::FrameSetup),
621                  StackPtr, false, 0)
622         .addImm(0)
623         .setMIFlag(MachineInstr::FrameSetup);
624     NumFrameExtraProbe++;
625     CurrentOffset += StackProbeSize;
626     CurrentProbeOffset += StackProbeSize;
627   }
628 
629   uint64_t ChunkSize = Offset - CurrentOffset;
630   MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
631                          .addReg(StackPtr)
632                          .addImm(ChunkSize)
633                          .setMIFlag(MachineInstr::FrameSetup);
634   MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
635 }
636 
637 void X86FrameLowering::emitStackProbeInlineGenericLoop(
638     MachineFunction &MF, MachineBasicBlock &MBB,
639     MachineBasicBlock::iterator MBBI, const DebugLoc &DL,
640     uint64_t Offset) const {
641 
642   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
643   const X86TargetLowering &TLI = *STI.getTargetLowering();
644   const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
645   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
646 
647   // Synthesize a loop
648   NumFrameLoopProbe++;
649   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
650 
651   MachineBasicBlock *testMBB = MF.CreateMachineBasicBlock(LLVM_BB);
652   MachineBasicBlock *tailMBB = MF.CreateMachineBasicBlock(LLVM_BB);
653 
654   MachineFunction::iterator MBBIter = ++MBB.getIterator();
655   MF.insert(MBBIter, testMBB);
656   MF.insert(MBBIter, tailMBB);
657 
658   unsigned FinalStackPtr = Uses64BitFramePtr ? X86::R11 : X86::R11D;
659   BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FinalStackPtr)
660       .addReg(StackPtr)
661       .setMIFlag(MachineInstr::FrameSetup);
662 
663   // save loop bound
664   {
665     const unsigned Opc = getSUBriOpcode(Uses64BitFramePtr, Offset);
666     BuildMI(MBB, MBBI, DL, TII.get(Opc), FinalStackPtr)
667         .addReg(FinalStackPtr)
668         .addImm(Offset / StackProbeSize * StackProbeSize)
669         .setMIFlag(MachineInstr::FrameSetup);
670   }
671 
672   // allocate a page
673   {
674     const unsigned Opc = getSUBriOpcode(Uses64BitFramePtr, StackProbeSize);
675     BuildMI(testMBB, DL, TII.get(Opc), StackPtr)
676         .addReg(StackPtr)
677         .addImm(StackProbeSize)
678         .setMIFlag(MachineInstr::FrameSetup);
679   }
680 
681   // touch the page
682   addRegOffset(BuildMI(testMBB, DL, TII.get(MovMIOpc))
683                    .setMIFlag(MachineInstr::FrameSetup),
684                StackPtr, false, 0)
685       .addImm(0)
686       .setMIFlag(MachineInstr::FrameSetup);
687 
688   // cmp with stack pointer bound
689   BuildMI(testMBB, DL, TII.get(IsLP64 ? X86::CMP64rr : X86::CMP32rr))
690       .addReg(StackPtr)
691       .addReg(FinalStackPtr)
692       .setMIFlag(MachineInstr::FrameSetup);
693 
694   // jump
695   BuildMI(testMBB, DL, TII.get(X86::JCC_1))
696       .addMBB(testMBB)
697       .addImm(X86::COND_NE)
698       .setMIFlag(MachineInstr::FrameSetup);
699   testMBB->addSuccessor(testMBB);
700   testMBB->addSuccessor(tailMBB);
701   testMBB->addLiveIn(FinalStackPtr);
702 
703   // allocate a block and touch it
704 
705   tailMBB->splice(tailMBB->end(), &MBB, MBBI, MBB.end());
706   tailMBB->transferSuccessorsAndUpdatePHIs(&MBB);
707   MBB.addSuccessor(testMBB);
708 
709   if (Offset % StackProbeSize) {
710     const unsigned Opc = getSUBriOpcode(Uses64BitFramePtr, Offset);
711     BuildMI(*tailMBB, tailMBB->begin(), DL, TII.get(Opc), StackPtr)
712         .addReg(StackPtr)
713         .addImm(Offset % StackProbeSize)
714         .setMIFlag(MachineInstr::FrameSetup);
715   }
716 }
717 
718 void X86FrameLowering::emitStackProbeInlineWindowsCoreCLR64(
719     MachineFunction &MF, MachineBasicBlock &MBB,
720     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
721   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
722   assert(STI.is64Bit() && "different expansion needed for 32 bit");
723   assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
724   const TargetInstrInfo &TII = *STI.getInstrInfo();
725   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
726 
727   // RAX contains the number of bytes of desired stack adjustment.
728   // The handling here assumes this value has already been updated so as to
729   // maintain stack alignment.
730   //
731   // We need to exit with RSP modified by this amount and execute suitable
732   // page touches to notify the OS that we're growing the stack responsibly.
733   // All stack probing must be done without modifying RSP.
734   //
735   // MBB:
736   //    SizeReg = RAX;
737   //    ZeroReg = 0
738   //    CopyReg = RSP
739   //    Flags, TestReg = CopyReg - SizeReg
740   //    FinalReg = !Flags.Ovf ? TestReg : ZeroReg
741   //    LimitReg = gs magic thread env access
742   //    if FinalReg >= LimitReg goto ContinueMBB
743   // RoundBB:
744   //    RoundReg = page address of FinalReg
745   // LoopMBB:
746   //    LoopReg = PHI(LimitReg,ProbeReg)
747   //    ProbeReg = LoopReg - PageSize
748   //    [ProbeReg] = 0
749   //    if (ProbeReg > RoundReg) goto LoopMBB
750   // ContinueMBB:
751   //    RSP = RSP - RAX
752   //    [rest of original MBB]
753 
754   // Set up the new basic blocks
755   MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB);
756   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
757   MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB);
758 
759   MachineFunction::iterator MBBIter = std::next(MBB.getIterator());
760   MF.insert(MBBIter, RoundMBB);
761   MF.insert(MBBIter, LoopMBB);
762   MF.insert(MBBIter, ContinueMBB);
763 
764   // Split MBB and move the tail portion down to ContinueMBB.
765   MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI);
766   ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end());
767   ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB);
768 
769   // Some useful constants
770   const int64_t ThreadEnvironmentStackLimit = 0x10;
771   const int64_t PageSize = 0x1000;
772   const int64_t PageMask = ~(PageSize - 1);
773 
774   // Registers we need. For the normal case we use virtual
775   // registers. For the prolog expansion we use RAX, RCX and RDX.
776   MachineRegisterInfo &MRI = MF.getRegInfo();
777   const TargetRegisterClass *RegClass = &X86::GR64RegClass;
778   const Register SizeReg = InProlog ? X86::RAX
779                                     : MRI.createVirtualRegister(RegClass),
780                  ZeroReg = InProlog ? X86::RCX
781                                     : MRI.createVirtualRegister(RegClass),
782                  CopyReg = InProlog ? X86::RDX
783                                     : MRI.createVirtualRegister(RegClass),
784                  TestReg = InProlog ? X86::RDX
785                                     : MRI.createVirtualRegister(RegClass),
786                  FinalReg = InProlog ? X86::RDX
787                                      : MRI.createVirtualRegister(RegClass),
788                  RoundedReg = InProlog ? X86::RDX
789                                        : MRI.createVirtualRegister(RegClass),
790                  LimitReg = InProlog ? X86::RCX
791                                      : MRI.createVirtualRegister(RegClass),
792                  JoinReg = InProlog ? X86::RCX
793                                     : MRI.createVirtualRegister(RegClass),
794                  ProbeReg = InProlog ? X86::RCX
795                                      : MRI.createVirtualRegister(RegClass);
796 
797   // SP-relative offsets where we can save RCX and RDX.
798   int64_t RCXShadowSlot = 0;
799   int64_t RDXShadowSlot = 0;
800 
801   // If inlining in the prolog, save RCX and RDX.
802   if (InProlog) {
803     // Compute the offsets. We need to account for things already
804     // pushed onto the stack at this point: return address, frame
805     // pointer (if used), and callee saves.
806     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
807     const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
808     const bool HasFP = hasFP(MF);
809 
810     // Check if we need to spill RCX and/or RDX.
811     // Here we assume that no earlier prologue instruction changes RCX and/or
812     // RDX, so checking the block live-ins is enough.
813     const bool IsRCXLiveIn = MBB.isLiveIn(X86::RCX);
814     const bool IsRDXLiveIn = MBB.isLiveIn(X86::RDX);
815     int64_t InitSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
816     // Assign the initial slot to both registers, then change RDX's slot if both
817     // need to be spilled.
818     if (IsRCXLiveIn)
819       RCXShadowSlot = InitSlot;
820     if (IsRDXLiveIn)
821       RDXShadowSlot = InitSlot;
822     if (IsRDXLiveIn && IsRCXLiveIn)
823       RDXShadowSlot += 8;
824     // Emit the saves if needed.
825     if (IsRCXLiveIn)
826       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
827                    RCXShadowSlot)
828           .addReg(X86::RCX);
829     if (IsRDXLiveIn)
830       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
831                    RDXShadowSlot)
832           .addReg(X86::RDX);
833   } else {
834     // Not in the prolog. Copy RAX to a virtual reg.
835     BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX);
836   }
837 
838   // Add code to MBB to check for overflow and set the new target stack pointer
839   // to zero if so.
840   BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg)
841       .addReg(ZeroReg, RegState::Undef)
842       .addReg(ZeroReg, RegState::Undef);
843   BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP);
844   BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg)
845       .addReg(CopyReg)
846       .addReg(SizeReg);
847   BuildMI(&MBB, DL, TII.get(X86::CMOV64rr), FinalReg)
848       .addReg(TestReg)
849       .addReg(ZeroReg)
850       .addImm(X86::COND_B);
851 
852   // FinalReg now holds final stack pointer value, or zero if
853   // allocation would overflow. Compare against the current stack
854   // limit from the thread environment block. Note this limit is the
855   // lowest touched page on the stack, not the point at which the OS
856   // will cause an overflow exception, so this is just an optimization
857   // to avoid unnecessarily touching pages that are below the current
858   // SP but already committed to the stack by the OS.
859   BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg)
860       .addReg(0)
861       .addImm(1)
862       .addReg(0)
863       .addImm(ThreadEnvironmentStackLimit)
864       .addReg(X86::GS);
865   BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg);
866   // Jump if the desired stack pointer is at or above the stack limit.
867   BuildMI(&MBB, DL, TII.get(X86::JCC_1)).addMBB(ContinueMBB).addImm(X86::COND_AE);
868 
869   // Add code to roundMBB to round the final stack pointer to a page boundary.
870   RoundMBB->addLiveIn(FinalReg);
871   BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg)
872       .addReg(FinalReg)
873       .addImm(PageMask);
874   BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB);
875 
876   // LimitReg now holds the current stack limit, RoundedReg page-rounded
877   // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
878   // and probe until we reach RoundedReg.
879   if (!InProlog) {
880     BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg)
881         .addReg(LimitReg)
882         .addMBB(RoundMBB)
883         .addReg(ProbeReg)
884         .addMBB(LoopMBB);
885   }
886 
887   LoopMBB->addLiveIn(JoinReg);
888   addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg,
889                false, -PageSize);
890 
891   // Probe by storing a byte onto the stack.
892   BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi))
893       .addReg(ProbeReg)
894       .addImm(1)
895       .addReg(0)
896       .addImm(0)
897       .addReg(0)
898       .addImm(0);
899 
900   LoopMBB->addLiveIn(RoundedReg);
901   BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr))
902       .addReg(RoundedReg)
903       .addReg(ProbeReg);
904   BuildMI(LoopMBB, DL, TII.get(X86::JCC_1)).addMBB(LoopMBB).addImm(X86::COND_NE);
905 
906   MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
907 
908   // If in prolog, restore RDX and RCX.
909   if (InProlog) {
910     if (RCXShadowSlot) // It means we spilled RCX in the prologue.
911       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
912                            TII.get(X86::MOV64rm), X86::RCX),
913                    X86::RSP, false, RCXShadowSlot);
914     if (RDXShadowSlot) // It means we spilled RDX in the prologue.
915       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
916                            TII.get(X86::MOV64rm), X86::RDX),
917                    X86::RSP, false, RDXShadowSlot);
918   }
919 
920   // Now that the probing is done, add code to continueMBB to update
921   // the stack pointer for real.
922   ContinueMBB->addLiveIn(SizeReg);
923   BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
924       .addReg(X86::RSP)
925       .addReg(SizeReg);
926 
927   // Add the control flow edges we need.
928   MBB.addSuccessor(ContinueMBB);
929   MBB.addSuccessor(RoundMBB);
930   RoundMBB->addSuccessor(LoopMBB);
931   LoopMBB->addSuccessor(ContinueMBB);
932   LoopMBB->addSuccessor(LoopMBB);
933 
934   // Mark all the instructions added to the prolog as frame setup.
935   if (InProlog) {
936     for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
937       BeforeMBBI->setFlag(MachineInstr::FrameSetup);
938     }
939     for (MachineInstr &MI : *RoundMBB) {
940       MI.setFlag(MachineInstr::FrameSetup);
941     }
942     for (MachineInstr &MI : *LoopMBB) {
943       MI.setFlag(MachineInstr::FrameSetup);
944     }
945     for (MachineBasicBlock::iterator CMBBI = ContinueMBB->begin();
946          CMBBI != ContinueMBBI; ++CMBBI) {
947       CMBBI->setFlag(MachineInstr::FrameSetup);
948     }
949   }
950 }
951 
952 void X86FrameLowering::emitStackProbeCall(MachineFunction &MF,
953                                           MachineBasicBlock &MBB,
954                                           MachineBasicBlock::iterator MBBI,
955                                           const DebugLoc &DL,
956                                           bool InProlog) const {
957   bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
958 
959   // FIXME: Add indirect thunk support and remove this.
960   if (Is64Bit && IsLargeCodeModel && STI.useIndirectThunkCalls())
961     report_fatal_error("Emitting stack probe calls on 64-bit with the large "
962                        "code model and indirect thunks not yet implemented.");
963 
964   unsigned CallOp;
965   if (Is64Bit)
966     CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
967   else
968     CallOp = X86::CALLpcrel32;
969 
970   StringRef Symbol = STI.getTargetLowering()->getStackProbeSymbolName(MF);
971 
972   MachineInstrBuilder CI;
973   MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI);
974 
975   // All current stack probes take AX and SP as input, clobber flags, and
976   // preserve all registers. x86_64 probes leave RSP unmodified.
977   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
978     // For the large code model, we have to call through a register. Use R11,
979     // as it is scratch in all supported calling conventions.
980     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
981         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
982     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
983   } else {
984     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp))
985         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
986   }
987 
988   unsigned AX = Uses64BitFramePtr ? X86::RAX : X86::EAX;
989   unsigned SP = Uses64BitFramePtr ? X86::RSP : X86::ESP;
990   CI.addReg(AX, RegState::Implicit)
991       .addReg(SP, RegState::Implicit)
992       .addReg(AX, RegState::Define | RegState::Implicit)
993       .addReg(SP, RegState::Define | RegState::Implicit)
994       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
995 
996   if (STI.isTargetWin64() || !STI.isOSWindows()) {
997     // MSVC x32's _chkstk and cygwin/mingw's _alloca adjust %esp themselves.
998     // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
999     // themselves. They also does not clobber %rax so we can reuse it when
1000     // adjusting %rsp.
1001     // All other platforms do not specify a particular ABI for the stack probe
1002     // function, so we arbitrarily define it to not adjust %esp/%rsp itself.
1003     BuildMI(MBB, MBBI, DL, TII.get(getSUBrrOpcode(Uses64BitFramePtr)), SP)
1004         .addReg(SP)
1005         .addReg(AX);
1006   }
1007 
1008   if (InProlog) {
1009     // Apply the frame setup flag to all inserted instrs.
1010     for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
1011       ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
1012   }
1013 }
1014 
1015 MachineInstr *X86FrameLowering::emitStackProbeInlineStub(
1016     MachineFunction &MF, MachineBasicBlock &MBB,
1017     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
1018 
1019   assert(InProlog && "ChkStkStub called outside prolog!");
1020 
1021   return BuildMI(MBB, MBBI, DL, TII.get(X86::CALLpcrel32))
1022       .addExternalSymbol("__chkstk_stub");
1023 }
1024 
1025 static unsigned calculateSetFPREG(uint64_t SPAdjust) {
1026   // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
1027   // and might require smaller successive adjustments.
1028   const uint64_t Win64MaxSEHOffset = 128;
1029   uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
1030   // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
1031   return SEHFrameOffset & -16;
1032 }
1033 
1034 // If we're forcing a stack realignment we can't rely on just the frame
1035 // info, we need to know the ABI stack alignment as well in case we
1036 // have a call out.  Otherwise just make sure we have some alignment - we'll
1037 // go with the minimum SlotSize.
1038 uint64_t X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
1039   const MachineFrameInfo &MFI = MF.getFrameInfo();
1040   Align MaxAlign = MFI.getMaxAlign(); // Desired stack alignment.
1041   Align StackAlign = getStackAlign();
1042   if (MF.getFunction().hasFnAttribute("stackrealign")) {
1043     if (MFI.hasCalls())
1044       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
1045     else if (MaxAlign < SlotSize)
1046       MaxAlign = Align(SlotSize);
1047   }
1048   return MaxAlign.value();
1049 }
1050 
1051 void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
1052                                           MachineBasicBlock::iterator MBBI,
1053                                           const DebugLoc &DL, unsigned Reg,
1054                                           uint64_t MaxAlign) const {
1055   uint64_t Val = -MaxAlign;
1056   unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val);
1057   MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg)
1058                          .addReg(Reg)
1059                          .addImm(Val)
1060                          .setMIFlag(MachineInstr::FrameSetup);
1061 
1062   // The EFLAGS implicit def is dead.
1063   MI->getOperand(3).setIsDead();
1064 }
1065 
1066 bool X86FrameLowering::has128ByteRedZone(const MachineFunction& MF) const {
1067   // x86-64 (non Win64) has a 128 byte red zone which is guaranteed not to be
1068   // clobbered by any interrupt handler.
1069   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
1070          "MF used frame lowering for wrong subtarget");
1071   const Function &Fn = MF.getFunction();
1072   const bool IsWin64CC = STI.isCallingConvWin64(Fn.getCallingConv());
1073   return Is64Bit && !IsWin64CC && !Fn.hasFnAttribute(Attribute::NoRedZone);
1074 }
1075 
1076 
1077 /// emitPrologue - Push callee-saved registers onto the stack, which
1078 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
1079 /// space for local variables. Also emit labels used by the exception handler to
1080 /// generate the exception handling frames.
1081 
1082 /*
1083   Here's a gist of what gets emitted:
1084 
1085   ; Establish frame pointer, if needed
1086   [if needs FP]
1087       push  %rbp
1088       .cfi_def_cfa_offset 16
1089       .cfi_offset %rbp, -16
1090       .seh_pushreg %rpb
1091       mov  %rsp, %rbp
1092       .cfi_def_cfa_register %rbp
1093 
1094   ; Spill general-purpose registers
1095   [for all callee-saved GPRs]
1096       pushq %<reg>
1097       [if not needs FP]
1098          .cfi_def_cfa_offset (offset from RETADDR)
1099       .seh_pushreg %<reg>
1100 
1101   ; If the required stack alignment > default stack alignment
1102   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
1103   ; of unknown size in the stack frame.
1104   [if stack needs re-alignment]
1105       and  $MASK, %rsp
1106 
1107   ; Allocate space for locals
1108   [if target is Windows and allocated space > 4096 bytes]
1109       ; Windows needs special care for allocations larger
1110       ; than one page.
1111       mov $NNN, %rax
1112       call ___chkstk_ms/___chkstk
1113       sub  %rax, %rsp
1114   [else]
1115       sub  $NNN, %rsp
1116 
1117   [if needs FP]
1118       .seh_stackalloc (size of XMM spill slots)
1119       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
1120   [else]
1121       .seh_stackalloc NNN
1122 
1123   ; Spill XMMs
1124   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
1125   ; they may get spilled on any platform, if the current function
1126   ; calls @llvm.eh.unwind.init
1127   [if needs FP]
1128       [for all callee-saved XMM registers]
1129           movaps  %<xmm reg>, -MMM(%rbp)
1130       [for all callee-saved XMM registers]
1131           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
1132               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
1133   [else]
1134       [for all callee-saved XMM registers]
1135           movaps  %<xmm reg>, KKK(%rsp)
1136       [for all callee-saved XMM registers]
1137           .seh_savexmm %<xmm reg>, KKK
1138 
1139   .seh_endprologue
1140 
1141   [if needs base pointer]
1142       mov  %rsp, %rbx
1143       [if needs to restore base pointer]
1144           mov %rsp, -MMM(%rbp)
1145 
1146   ; Emit CFI info
1147   [if needs FP]
1148       [for all callee-saved registers]
1149           .cfi_offset %<reg>, (offset from %rbp)
1150   [else]
1151        .cfi_def_cfa_offset (offset from RETADDR)
1152       [for all callee-saved registers]
1153           .cfi_offset %<reg>, (offset from %rsp)
1154 
1155   Notes:
1156   - .seh directives are emitted only for Windows 64 ABI
1157   - .cv_fpo directives are emitted on win32 when emitting CodeView
1158   - .cfi directives are emitted for all other ABIs
1159   - for 32-bit code, substitute %e?? registers for %r??
1160 */
1161 
1162 void X86FrameLowering::emitPrologue(MachineFunction &MF,
1163                                     MachineBasicBlock &MBB) const {
1164   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
1165          "MF used frame lowering for wrong subtarget");
1166   MachineBasicBlock::iterator MBBI = MBB.begin();
1167   MachineFrameInfo &MFI = MF.getFrameInfo();
1168   const Function &Fn = MF.getFunction();
1169   MachineModuleInfo &MMI = MF.getMMI();
1170   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1171   uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
1172   uint64_t StackSize = MFI.getStackSize();    // Number of bytes to allocate.
1173   bool IsFunclet = MBB.isEHFuncletEntry();
1174   EHPersonality Personality = EHPersonality::Unknown;
1175   if (Fn.hasPersonalityFn())
1176     Personality = classifyEHPersonality(Fn.getPersonalityFn());
1177   bool FnHasClrFunclet =
1178       MF.hasEHFunclets() && Personality == EHPersonality::CoreCLR;
1179   bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
1180   bool HasFP = hasFP(MF);
1181   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1182   bool NeedsWin64CFI = IsWin64Prologue && Fn.needsUnwindTableEntry();
1183   // FIXME: Emit FPO data for EH funclets.
1184   bool NeedsWinFPO =
1185       !IsFunclet && STI.isTargetWin32() && MMI.getModule()->getCodeViewFlag();
1186   bool NeedsWinCFI = NeedsWin64CFI || NeedsWinFPO;
1187   bool NeedsDwarfCFI = !IsWin64Prologue && MF.needsFrameMoves();
1188   Register FramePtr = TRI->getFrameRegister(MF);
1189   const Register MachineFramePtr =
1190       STI.isTarget64BitILP32()
1191           ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
1192   Register BasePtr = TRI->getBaseRegister();
1193   bool HasWinCFI = false;
1194 
1195   // Debug location must be unknown since the first debug location is used
1196   // to determine the end of the prologue.
1197   DebugLoc DL;
1198 
1199   // Add RETADDR move area to callee saved frame size.
1200   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1201   if (TailCallReturnAddrDelta && IsWin64Prologue)
1202     report_fatal_error("Can't handle guaranteed tail call under win64 yet");
1203 
1204   if (TailCallReturnAddrDelta < 0)
1205     X86FI->setCalleeSavedFrameSize(
1206       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
1207 
1208   const bool EmitStackProbeCall =
1209       STI.getTargetLowering()->hasStackProbeSymbol(MF);
1210   unsigned StackProbeSize = STI.getTargetLowering()->getStackProbeSize(MF);
1211 
1212   // Re-align the stack on 64-bit if the x86-interrupt calling convention is
1213   // used and an error code was pushed, since the x86-64 ABI requires a 16-byte
1214   // stack alignment.
1215   if (Fn.getCallingConv() == CallingConv::X86_INTR && Is64Bit &&
1216       Fn.arg_size() == 2) {
1217     StackSize += 8;
1218     MFI.setStackSize(StackSize);
1219     emitSPUpdate(MBB, MBBI, DL, -8, /*InEpilogue=*/false);
1220   }
1221 
1222   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
1223   // function, and use up to 128 bytes of stack space, don't have a frame
1224   // pointer, calls, or dynamic alloca then we do not need to adjust the
1225   // stack pointer (we fit in the Red Zone). We also check that we don't
1226   // push and pop from the stack.
1227   if (has128ByteRedZone(MF) && !TRI->needsStackRealignment(MF) &&
1228       !MFI.hasVarSizedObjects() &&             // No dynamic alloca.
1229       !MFI.adjustsStack() &&                   // No calls.
1230       !EmitStackProbeCall &&                   // No stack probes.
1231       !MFI.hasCopyImplyingStackAdjustment() && // Don't push and pop.
1232       !MF.shouldSplitStack()) {                // Regular stack
1233     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
1234     if (HasFP) MinSize += SlotSize;
1235     X86FI->setUsesRedZone(MinSize > 0 || StackSize > 0);
1236     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
1237     MFI.setStackSize(StackSize);
1238   }
1239 
1240   // Insert stack pointer adjustment for later moving of return addr.  Only
1241   // applies to tail call optimized functions where the callee argument stack
1242   // size is bigger than the callers.
1243   if (TailCallReturnAddrDelta < 0) {
1244     BuildStackAdjustment(MBB, MBBI, DL, TailCallReturnAddrDelta,
1245                          /*InEpilogue=*/false)
1246         .setMIFlag(MachineInstr::FrameSetup);
1247   }
1248 
1249   // Mapping for machine moves:
1250   //
1251   //   DST: VirtualFP AND
1252   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
1253   //        ELSE                        => DW_CFA_def_cfa
1254   //
1255   //   SRC: VirtualFP AND
1256   //        DST: Register               => DW_CFA_def_cfa_register
1257   //
1258   //   ELSE
1259   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
1260   //        REG < 64                    => DW_CFA_offset + Reg
1261   //        ELSE                        => DW_CFA_offset_extended
1262 
1263   uint64_t NumBytes = 0;
1264   int stackGrowth = -SlotSize;
1265 
1266   // Find the funclet establisher parameter
1267   Register Establisher = X86::NoRegister;
1268   if (IsClrFunclet)
1269     Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
1270   else if (IsFunclet)
1271     Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
1272 
1273   if (IsWin64Prologue && IsFunclet && !IsClrFunclet) {
1274     // Immediately spill establisher into the home slot.
1275     // The runtime cares about this.
1276     // MOV64mr %rdx, 16(%rsp)
1277     unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1278     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16)
1279         .addReg(Establisher)
1280         .setMIFlag(MachineInstr::FrameSetup);
1281     MBB.addLiveIn(Establisher);
1282   }
1283 
1284   if (HasFP) {
1285     assert(MF.getRegInfo().isReserved(MachineFramePtr) && "FP reserved");
1286 
1287     // Calculate required stack adjustment.
1288     uint64_t FrameSize = StackSize - SlotSize;
1289     // If required, include space for extra hidden slot for stashing base pointer.
1290     if (X86FI->getRestoreBasePointer())
1291       FrameSize += SlotSize;
1292 
1293     NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
1294 
1295     // Callee-saved registers are pushed on stack before the stack is realigned.
1296     if (TRI->needsStackRealignment(MF) && !IsWin64Prologue)
1297       NumBytes = alignTo(NumBytes, MaxAlign);
1298 
1299     // Save EBP/RBP into the appropriate stack slot.
1300     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
1301       .addReg(MachineFramePtr, RegState::Kill)
1302       .setMIFlag(MachineInstr::FrameSetup);
1303 
1304     if (NeedsDwarfCFI) {
1305       // Mark the place where EBP/RBP was saved.
1306       // Define the current CFA rule to use the provided offset.
1307       assert(StackSize);
1308       BuildCFI(MBB, MBBI, DL,
1309                MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
1310 
1311       // Change the rule for the FramePtr to be an "offset" rule.
1312       unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1313       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createOffset(
1314                                   nullptr, DwarfFramePtr, 2 * stackGrowth));
1315     }
1316 
1317     if (NeedsWinCFI) {
1318       HasWinCFI = true;
1319       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1320           .addImm(FramePtr)
1321           .setMIFlag(MachineInstr::FrameSetup);
1322     }
1323 
1324     if (!IsWin64Prologue && !IsFunclet) {
1325       // Update EBP with the new base value.
1326       BuildMI(MBB, MBBI, DL,
1327               TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
1328               FramePtr)
1329           .addReg(StackPtr)
1330           .setMIFlag(MachineInstr::FrameSetup);
1331 
1332       if (NeedsDwarfCFI) {
1333         // Mark effective beginning of when frame pointer becomes valid.
1334         // Define the current CFA to use the EBP/RBP register.
1335         unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1336         BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaRegister(
1337                                     nullptr, DwarfFramePtr));
1338       }
1339 
1340       if (NeedsWinFPO) {
1341         // .cv_fpo_setframe $FramePtr
1342         HasWinCFI = true;
1343         BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
1344             .addImm(FramePtr)
1345             .addImm(0)
1346             .setMIFlag(MachineInstr::FrameSetup);
1347       }
1348     }
1349   } else {
1350     assert(!IsFunclet && "funclets without FPs not yet implemented");
1351     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
1352   }
1353 
1354   // Update the offset adjustment, which is mainly used by codeview to translate
1355   // from ESP to VFRAME relative local variable offsets.
1356   if (!IsFunclet) {
1357     if (HasFP && TRI->needsStackRealignment(MF))
1358       MFI.setOffsetAdjustment(-NumBytes);
1359     else
1360       MFI.setOffsetAdjustment(-StackSize);
1361   }
1362 
1363   // For EH funclets, only allocate enough space for outgoing calls. Save the
1364   // NumBytes value that we would've used for the parent frame.
1365   unsigned ParentFrameNumBytes = NumBytes;
1366   if (IsFunclet)
1367     NumBytes = getWinEHFuncletFrameSize(MF);
1368 
1369   // Skip the callee-saved push instructions.
1370   bool PushedRegs = false;
1371   int StackOffset = 2 * stackGrowth;
1372 
1373   while (MBBI != MBB.end() &&
1374          MBBI->getFlag(MachineInstr::FrameSetup) &&
1375          (MBBI->getOpcode() == X86::PUSH32r ||
1376           MBBI->getOpcode() == X86::PUSH64r)) {
1377     PushedRegs = true;
1378     Register Reg = MBBI->getOperand(0).getReg();
1379     ++MBBI;
1380 
1381     if (!HasFP && NeedsDwarfCFI) {
1382       // Mark callee-saved push instruction.
1383       // Define the current CFA rule to use the provided offset.
1384       assert(StackSize);
1385       BuildCFI(MBB, MBBI, DL,
1386                MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
1387       StackOffset += stackGrowth;
1388     }
1389 
1390     if (NeedsWinCFI) {
1391       HasWinCFI = true;
1392       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1393           .addImm(Reg)
1394           .setMIFlag(MachineInstr::FrameSetup);
1395     }
1396   }
1397 
1398   // Realign stack after we pushed callee-saved registers (so that we'll be
1399   // able to calculate their offsets from the frame pointer).
1400   // Don't do this for Win64, it needs to realign the stack after the prologue.
1401   if (!IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF)) {
1402     assert(HasFP && "There should be a frame pointer if stack is realigned.");
1403     BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
1404 
1405     if (NeedsWinCFI) {
1406       HasWinCFI = true;
1407       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlign))
1408           .addImm(MaxAlign)
1409           .setMIFlag(MachineInstr::FrameSetup);
1410     }
1411   }
1412 
1413   // If there is an SUB32ri of ESP immediately before this instruction, merge
1414   // the two. This can be the case when tail call elimination is enabled and
1415   // the callee has more arguments then the caller.
1416   NumBytes -= mergeSPUpdates(MBB, MBBI, true);
1417 
1418   // Adjust stack pointer: ESP -= numbytes.
1419 
1420   // Windows and cygwin/mingw require a prologue helper routine when allocating
1421   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
1422   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
1423   // stack and adjust the stack pointer in one go.  The 64-bit version of
1424   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
1425   // responsible for adjusting the stack pointer.  Touching the stack at 4K
1426   // increments is necessary to ensure that the guard pages used by the OS
1427   // virtual memory manager are allocated in correct sequence.
1428   uint64_t AlignedNumBytes = NumBytes;
1429   if (IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF))
1430     AlignedNumBytes = alignTo(AlignedNumBytes, MaxAlign);
1431   if (AlignedNumBytes >= StackProbeSize && EmitStackProbeCall) {
1432     assert(!X86FI->getUsesRedZone() &&
1433            "The Red Zone is not accounted for in stack probes");
1434 
1435     // Check whether EAX is livein for this block.
1436     bool isEAXAlive = isEAXLiveIn(MBB);
1437 
1438     if (isEAXAlive) {
1439       if (Is64Bit) {
1440         // Save RAX
1441         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1442           .addReg(X86::RAX, RegState::Kill)
1443           .setMIFlag(MachineInstr::FrameSetup);
1444       } else {
1445         // Save EAX
1446         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
1447           .addReg(X86::EAX, RegState::Kill)
1448           .setMIFlag(MachineInstr::FrameSetup);
1449       }
1450     }
1451 
1452     if (Is64Bit) {
1453       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
1454       // Function prologue is responsible for adjusting the stack pointer.
1455       int64_t Alloc = isEAXAlive ? NumBytes - 8 : NumBytes;
1456       if (isUInt<32>(Alloc)) {
1457         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
1458             .addImm(Alloc)
1459             .setMIFlag(MachineInstr::FrameSetup);
1460       } else if (isInt<32>(Alloc)) {
1461         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
1462             .addImm(Alloc)
1463             .setMIFlag(MachineInstr::FrameSetup);
1464       } else {
1465         BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
1466             .addImm(Alloc)
1467             .setMIFlag(MachineInstr::FrameSetup);
1468       }
1469     } else {
1470       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
1471       // We'll also use 4 already allocated bytes for EAX.
1472       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
1473           .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
1474           .setMIFlag(MachineInstr::FrameSetup);
1475     }
1476 
1477     // Call __chkstk, __chkstk_ms, or __alloca.
1478     emitStackProbe(MF, MBB, MBBI, DL, true);
1479 
1480     if (isEAXAlive) {
1481       // Restore RAX/EAX
1482       MachineInstr *MI;
1483       if (Is64Bit)
1484         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV64rm), X86::RAX),
1485                           StackPtr, false, NumBytes - 8);
1486       else
1487         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX),
1488                           StackPtr, false, NumBytes - 4);
1489       MI->setFlag(MachineInstr::FrameSetup);
1490       MBB.insert(MBBI, MI);
1491     }
1492   } else if (NumBytes) {
1493     emitSPUpdate(MBB, MBBI, DL, -(int64_t)NumBytes, /*InEpilogue=*/false);
1494   }
1495 
1496   if (NeedsWinCFI && NumBytes) {
1497     HasWinCFI = true;
1498     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
1499         .addImm(NumBytes)
1500         .setMIFlag(MachineInstr::FrameSetup);
1501   }
1502 
1503   int SEHFrameOffset = 0;
1504   unsigned SPOrEstablisher;
1505   if (IsFunclet) {
1506     if (IsClrFunclet) {
1507       // The establisher parameter passed to a CLR funclet is actually a pointer
1508       // to the (mostly empty) frame of its nearest enclosing funclet; we have
1509       // to find the root function establisher frame by loading the PSPSym from
1510       // the intermediate frame.
1511       unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
1512       MachinePointerInfo NoInfo;
1513       MBB.addLiveIn(Establisher);
1514       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher),
1515                    Establisher, false, PSPSlotOffset)
1516           .addMemOperand(MF.getMachineMemOperand(
1517               NoInfo, MachineMemOperand::MOLoad, SlotSize, Align(SlotSize)));
1518       ;
1519       // Save the root establisher back into the current funclet's (mostly
1520       // empty) frame, in case a sub-funclet or the GC needs it.
1521       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
1522                    false, PSPSlotOffset)
1523           .addReg(Establisher)
1524           .addMemOperand(MF.getMachineMemOperand(
1525               NoInfo,
1526               MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
1527               SlotSize, Align(SlotSize)));
1528     }
1529     SPOrEstablisher = Establisher;
1530   } else {
1531     SPOrEstablisher = StackPtr;
1532   }
1533 
1534   if (IsWin64Prologue && HasFP) {
1535     // Set RBP to a small fixed offset from RSP. In the funclet case, we base
1536     // this calculation on the incoming establisher, which holds the value of
1537     // RSP from the parent frame at the end of the prologue.
1538     SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes);
1539     if (SEHFrameOffset)
1540       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
1541                    SPOrEstablisher, false, SEHFrameOffset);
1542     else
1543       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr)
1544           .addReg(SPOrEstablisher);
1545 
1546     // If this is not a funclet, emit the CFI describing our frame pointer.
1547     if (NeedsWinCFI && !IsFunclet) {
1548       assert(!NeedsWinFPO && "this setframe incompatible with FPO data");
1549       HasWinCFI = true;
1550       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
1551           .addImm(FramePtr)
1552           .addImm(SEHFrameOffset)
1553           .setMIFlag(MachineInstr::FrameSetup);
1554       if (isAsynchronousEHPersonality(Personality))
1555         MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset;
1556     }
1557   } else if (IsFunclet && STI.is32Bit()) {
1558     // Reset EBP / ESI to something good for funclets.
1559     MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL);
1560     // If we're a catch funclet, we can be returned to via catchret. Save ESP
1561     // into the registration node so that the runtime will restore it for us.
1562     if (!MBB.isCleanupFuncletEntry()) {
1563       assert(Personality == EHPersonality::MSVC_CXX);
1564       unsigned FrameReg;
1565       int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex;
1566       int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg);
1567       // ESP is the first field, so no extra displacement is needed.
1568       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg,
1569                    false, EHRegOffset)
1570           .addReg(X86::ESP);
1571     }
1572   }
1573 
1574   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
1575     const MachineInstr &FrameInstr = *MBBI;
1576     ++MBBI;
1577 
1578     if (NeedsWinCFI) {
1579       int FI;
1580       if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
1581         if (X86::FR64RegClass.contains(Reg)) {
1582           int Offset;
1583           unsigned IgnoredFrameReg;
1584           if (IsWin64Prologue && IsFunclet)
1585             Offset = getWin64EHFrameIndexRef(MF, FI, IgnoredFrameReg);
1586           else
1587             Offset = getFrameIndexReference(MF, FI, IgnoredFrameReg) +
1588                      SEHFrameOffset;
1589 
1590           HasWinCFI = true;
1591           assert(!NeedsWinFPO && "SEH_SaveXMM incompatible with FPO data");
1592           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
1593               .addImm(Reg)
1594               .addImm(Offset)
1595               .setMIFlag(MachineInstr::FrameSetup);
1596         }
1597       }
1598     }
1599   }
1600 
1601   if (NeedsWinCFI && HasWinCFI)
1602     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
1603         .setMIFlag(MachineInstr::FrameSetup);
1604 
1605   if (FnHasClrFunclet && !IsFunclet) {
1606     // Save the so-called Initial-SP (i.e. the value of the stack pointer
1607     // immediately after the prolog)  into the PSPSlot so that funclets
1608     // and the GC can recover it.
1609     unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
1610     auto PSPInfo = MachinePointerInfo::getFixedStack(
1611         MF, MF.getWinEHFuncInfo()->PSPSymFrameIdx);
1612     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false,
1613                  PSPSlotOffset)
1614         .addReg(StackPtr)
1615         .addMemOperand(MF.getMachineMemOperand(
1616             PSPInfo, MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
1617             SlotSize, Align(SlotSize)));
1618   }
1619 
1620   // Realign stack after we spilled callee-saved registers (so that we'll be
1621   // able to calculate their offsets from the frame pointer).
1622   // Win64 requires aligning the stack after the prologue.
1623   if (IsWin64Prologue && TRI->needsStackRealignment(MF)) {
1624     assert(HasFP && "There should be a frame pointer if stack is realigned.");
1625     BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign);
1626   }
1627 
1628   // We already dealt with stack realignment and funclets above.
1629   if (IsFunclet && STI.is32Bit())
1630     return;
1631 
1632   // If we need a base pointer, set it up here. It's whatever the value
1633   // of the stack pointer is at this point. Any variable size objects
1634   // will be allocated after this, so we can still use the base pointer
1635   // to reference locals.
1636   if (TRI->hasBasePointer(MF)) {
1637     // Update the base pointer with the current stack pointer.
1638     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
1639     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
1640       .addReg(SPOrEstablisher)
1641       .setMIFlag(MachineInstr::FrameSetup);
1642     if (X86FI->getRestoreBasePointer()) {
1643       // Stash value of base pointer.  Saving RSP instead of EBP shortens
1644       // dependence chain. Used by SjLj EH.
1645       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1646       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
1647                    FramePtr, true, X86FI->getRestoreBasePointerOffset())
1648         .addReg(SPOrEstablisher)
1649         .setMIFlag(MachineInstr::FrameSetup);
1650     }
1651 
1652     if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
1653       // Stash the value of the frame pointer relative to the base pointer for
1654       // Win32 EH. This supports Win32 EH, which does the inverse of the above:
1655       // it recovers the frame pointer from the base pointer rather than the
1656       // other way around.
1657       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1658       unsigned UsedReg;
1659       int Offset =
1660           getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg);
1661       assert(UsedReg == BasePtr);
1662       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset)
1663           .addReg(FramePtr)
1664           .setMIFlag(MachineInstr::FrameSetup);
1665     }
1666   }
1667 
1668   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
1669     // Mark end of stack pointer adjustment.
1670     if (!HasFP && NumBytes) {
1671       // Define the current CFA rule to use the provided offset.
1672       assert(StackSize);
1673       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaOffset(
1674                                   nullptr, -StackSize + stackGrowth));
1675     }
1676 
1677     // Emit DWARF info specifying the offsets of the callee-saved registers.
1678     emitCalleeSavedFrameMoves(MBB, MBBI, DL);
1679   }
1680 
1681   // X86 Interrupt handling function cannot assume anything about the direction
1682   // flag (DF in EFLAGS register). Clear this flag by creating "cld" instruction
1683   // in each prologue of interrupt handler function.
1684   //
1685   // FIXME: Create "cld" instruction only in these cases:
1686   // 1. The interrupt handling function uses any of the "rep" instructions.
1687   // 2. Interrupt handling function calls another function.
1688   //
1689   if (Fn.getCallingConv() == CallingConv::X86_INTR)
1690     BuildMI(MBB, MBBI, DL, TII.get(X86::CLD))
1691         .setMIFlag(MachineInstr::FrameSetup);
1692 
1693   // At this point we know if the function has WinCFI or not.
1694   MF.setHasWinCFI(HasWinCFI);
1695 }
1696 
1697 bool X86FrameLowering::canUseLEAForSPInEpilogue(
1698     const MachineFunction &MF) const {
1699   // We can't use LEA instructions for adjusting the stack pointer if we don't
1700   // have a frame pointer in the Win64 ABI.  Only ADD instructions may be used
1701   // to deallocate the stack.
1702   // This means that we can use LEA for SP in two situations:
1703   // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
1704   // 2. We *have* a frame pointer which means we are permitted to use LEA.
1705   return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
1706 }
1707 
1708 static bool isFuncletReturnInstr(MachineInstr &MI) {
1709   switch (MI.getOpcode()) {
1710   case X86::CATCHRET:
1711   case X86::CLEANUPRET:
1712     return true;
1713   default:
1714     return false;
1715   }
1716   llvm_unreachable("impossible");
1717 }
1718 
1719 // CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
1720 // stack. It holds a pointer to the bottom of the root function frame.  The
1721 // establisher frame pointer passed to a nested funclet may point to the
1722 // (mostly empty) frame of its parent funclet, but it will need to find
1723 // the frame of the root function to access locals.  To facilitate this,
1724 // every funclet copies the pointer to the bottom of the root function
1725 // frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
1726 // same offset for the PSPSym in the root function frame that's used in the
1727 // funclets' frames allows each funclet to dynamically accept any ancestor
1728 // frame as its establisher argument (the runtime doesn't guarantee the
1729 // immediate parent for some reason lost to history), and also allows the GC,
1730 // which uses the PSPSym for some bookkeeping, to find it in any funclet's
1731 // frame with only a single offset reported for the entire method.
1732 unsigned
1733 X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
1734   const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
1735   unsigned SPReg;
1736   int Offset = getFrameIndexReferencePreferSP(MF, Info.PSPSymFrameIdx, SPReg,
1737                                               /*IgnoreSPUpdates*/ true);
1738   assert(Offset >= 0 && SPReg == TRI->getStackRegister());
1739   return static_cast<unsigned>(Offset);
1740 }
1741 
1742 unsigned
1743 X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
1744   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1745   // This is the size of the pushed CSRs.
1746   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1747   // This is the size of callee saved XMMs.
1748   const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
1749   unsigned XMMSize = WinEHXMMSlotInfo.size() *
1750                      TRI->getSpillSize(X86::VR128RegClass);
1751   // This is the amount of stack a funclet needs to allocate.
1752   unsigned UsedSize;
1753   EHPersonality Personality =
1754       classifyEHPersonality(MF.getFunction().getPersonalityFn());
1755   if (Personality == EHPersonality::CoreCLR) {
1756     // CLR funclets need to hold enough space to include the PSPSym, at the
1757     // same offset from the stack pointer (immediately after the prolog) as it
1758     // resides at in the main function.
1759     UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
1760   } else {
1761     // Other funclets just need enough stack for outgoing call arguments.
1762     UsedSize = MF.getFrameInfo().getMaxCallFrameSize();
1763   }
1764   // RBP is not included in the callee saved register block. After pushing RBP,
1765   // everything is 16 byte aligned. Everything we allocate before an outgoing
1766   // call must also be 16 byte aligned.
1767   unsigned FrameSizeMinusRBP = alignTo(CSSize + UsedSize, getStackAlign());
1768   // Subtract out the size of the callee saved registers. This is how much stack
1769   // each funclet will allocate.
1770   return FrameSizeMinusRBP + XMMSize - CSSize;
1771 }
1772 
1773 static bool isTailCallOpcode(unsigned Opc) {
1774     return Opc == X86::TCRETURNri || Opc == X86::TCRETURNdi ||
1775         Opc == X86::TCRETURNmi ||
1776         Opc == X86::TCRETURNri64 || Opc == X86::TCRETURNdi64 ||
1777         Opc == X86::TCRETURNmi64;
1778 }
1779 
1780 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
1781                                     MachineBasicBlock &MBB) const {
1782   const MachineFrameInfo &MFI = MF.getFrameInfo();
1783   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1784   MachineBasicBlock::iterator Terminator = MBB.getFirstTerminator();
1785   MachineBasicBlock::iterator MBBI = Terminator;
1786   DebugLoc DL;
1787   if (MBBI != MBB.end())
1788     DL = MBBI->getDebugLoc();
1789   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
1790   const bool Is64BitILP32 = STI.isTarget64BitILP32();
1791   Register FramePtr = TRI->getFrameRegister(MF);
1792   unsigned MachineFramePtr =
1793       Is64BitILP32 ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
1794 
1795   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1796   bool NeedsWin64CFI =
1797       IsWin64Prologue && MF.getFunction().needsUnwindTableEntry();
1798   bool IsFunclet = MBBI == MBB.end() ? false : isFuncletReturnInstr(*MBBI);
1799 
1800   // Get the number of bytes to allocate from the FrameInfo.
1801   uint64_t StackSize = MFI.getStackSize();
1802   uint64_t MaxAlign = calculateMaxStackAlign(MF);
1803   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1804   bool HasFP = hasFP(MF);
1805   uint64_t NumBytes = 0;
1806 
1807   bool NeedsDwarfCFI = (!MF.getTarget().getTargetTriple().isOSDarwin() &&
1808                         !MF.getTarget().getTargetTriple().isOSWindows()) &&
1809                        MF.needsFrameMoves();
1810 
1811   if (IsFunclet) {
1812     assert(HasFP && "EH funclets without FP not yet implemented");
1813     NumBytes = getWinEHFuncletFrameSize(MF);
1814   } else if (HasFP) {
1815     // Calculate required stack adjustment.
1816     uint64_t FrameSize = StackSize - SlotSize;
1817     NumBytes = FrameSize - CSSize;
1818 
1819     // Callee-saved registers were pushed on stack before the stack was
1820     // realigned.
1821     if (TRI->needsStackRealignment(MF) && !IsWin64Prologue)
1822       NumBytes = alignTo(FrameSize, MaxAlign);
1823   } else {
1824     NumBytes = StackSize - CSSize;
1825   }
1826   uint64_t SEHStackAllocAmt = NumBytes;
1827 
1828   if (HasFP) {
1829     // Pop EBP.
1830     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r),
1831             MachineFramePtr)
1832         .setMIFlag(MachineInstr::FrameDestroy);
1833     if (NeedsDwarfCFI) {
1834       unsigned DwarfStackPtr =
1835           TRI->getDwarfRegNum(Is64Bit ? X86::RSP : X86::ESP, true);
1836       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfa(
1837                                   nullptr, DwarfStackPtr, -SlotSize));
1838       --MBBI;
1839     }
1840   }
1841 
1842   MachineBasicBlock::iterator FirstCSPop = MBBI;
1843   // Skip the callee-saved pop instructions.
1844   while (MBBI != MBB.begin()) {
1845     MachineBasicBlock::iterator PI = std::prev(MBBI);
1846     unsigned Opc = PI->getOpcode();
1847 
1848     if (Opc != X86::DBG_VALUE && !PI->isTerminator()) {
1849       if ((Opc != X86::POP32r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
1850           (Opc != X86::POP64r || !PI->getFlag(MachineInstr::FrameDestroy)))
1851         break;
1852       FirstCSPop = PI;
1853     }
1854 
1855     --MBBI;
1856   }
1857   MBBI = FirstCSPop;
1858 
1859   if (IsFunclet && Terminator->getOpcode() == X86::CATCHRET)
1860     emitCatchRetReturnValue(MBB, FirstCSPop, &*Terminator);
1861 
1862   if (MBBI != MBB.end())
1863     DL = MBBI->getDebugLoc();
1864 
1865   // If there is an ADD32ri or SUB32ri of ESP immediately before this
1866   // instruction, merge the two instructions.
1867   if (NumBytes || MFI.hasVarSizedObjects())
1868     NumBytes += mergeSPUpdates(MBB, MBBI, true);
1869 
1870   // If dynamic alloca is used, then reset esp to point to the last callee-saved
1871   // slot before popping them off! Same applies for the case, when stack was
1872   // realigned. Don't do this if this was a funclet epilogue, since the funclets
1873   // will not do realignment or dynamic stack allocation.
1874   if ((TRI->needsStackRealignment(MF) || MFI.hasVarSizedObjects()) &&
1875       !IsFunclet) {
1876     if (TRI->needsStackRealignment(MF))
1877       MBBI = FirstCSPop;
1878     unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1879     uint64_t LEAAmount =
1880         IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
1881 
1882     // There are only two legal forms of epilogue:
1883     // - add SEHAllocationSize, %rsp
1884     // - lea SEHAllocationSize(%FramePtr), %rsp
1885     //
1886     // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1887     // However, we may use this sequence if we have a frame pointer because the
1888     // effects of the prologue can safely be undone.
1889     if (LEAAmount != 0) {
1890       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1891       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1892                    FramePtr, false, LEAAmount);
1893       --MBBI;
1894     } else {
1895       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1896       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1897         .addReg(FramePtr);
1898       --MBBI;
1899     }
1900   } else if (NumBytes) {
1901     // Adjust stack pointer back: ESP += numbytes.
1902     emitSPUpdate(MBB, MBBI, DL, NumBytes, /*InEpilogue=*/true);
1903     if (!hasFP(MF) && NeedsDwarfCFI) {
1904       // Define the current CFA rule to use the provided offset.
1905       BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaOffset(
1906                                   nullptr, -CSSize - SlotSize));
1907     }
1908     --MBBI;
1909   }
1910 
1911   // Windows unwinder will not invoke function's exception handler if IP is
1912   // either in prologue or in epilogue.  This behavior causes a problem when a
1913   // call immediately precedes an epilogue, because the return address points
1914   // into the epilogue.  To cope with that, we insert an epilogue marker here,
1915   // then replace it with a 'nop' if it ends up immediately after a CALL in the
1916   // final emitted code.
1917   if (NeedsWin64CFI && MF.hasWinCFI())
1918     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1919 
1920   if (!hasFP(MF) && NeedsDwarfCFI) {
1921     MBBI = FirstCSPop;
1922     int64_t Offset = -CSSize - SlotSize;
1923     // Mark callee-saved pop instruction.
1924     // Define the current CFA rule to use the provided offset.
1925     while (MBBI != MBB.end()) {
1926       MachineBasicBlock::iterator PI = MBBI;
1927       unsigned Opc = PI->getOpcode();
1928       ++MBBI;
1929       if (Opc == X86::POP32r || Opc == X86::POP64r) {
1930         Offset += SlotSize;
1931         BuildCFI(MBB, MBBI, DL,
1932                  MCCFIInstruction::createDefCfaOffset(nullptr, Offset));
1933       }
1934     }
1935   }
1936 
1937   if (Terminator == MBB.end() || !isTailCallOpcode(Terminator->getOpcode())) {
1938     // Add the return addr area delta back since we are not tail calling.
1939     int Offset = -1 * X86FI->getTCReturnAddrDelta();
1940     assert(Offset >= 0 && "TCDelta should never be positive");
1941     if (Offset) {
1942       // Check for possible merge with preceding ADD instruction.
1943       Offset += mergeSPUpdates(MBB, Terminator, true);
1944       emitSPUpdate(MBB, Terminator, DL, Offset, /*InEpilogue=*/true);
1945     }
1946   }
1947 }
1948 
1949 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1950                                              unsigned &FrameReg) const {
1951   const MachineFrameInfo &MFI = MF.getFrameInfo();
1952 
1953   bool IsFixed = MFI.isFixedObjectIndex(FI);
1954   // We can't calculate offset from frame pointer if the stack is realigned,
1955   // so enforce usage of stack/base pointer.  The base pointer is used when we
1956   // have dynamic allocas in addition to dynamic realignment.
1957   if (TRI->hasBasePointer(MF))
1958     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getBaseRegister();
1959   else if (TRI->needsStackRealignment(MF))
1960     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getStackRegister();
1961   else
1962     FrameReg = TRI->getFrameRegister(MF);
1963 
1964   // Offset will hold the offset from the stack pointer at function entry to the
1965   // object.
1966   // We need to factor in additional offsets applied during the prologue to the
1967   // frame, base, and stack pointer depending on which is used.
1968   int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea();
1969   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1970   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1971   uint64_t StackSize = MFI.getStackSize();
1972   bool HasFP = hasFP(MF);
1973   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1974   int64_t FPDelta = 0;
1975 
1976   // In an x86 interrupt, remove the offset we added to account for the return
1977   // address from any stack object allocated in the caller's frame. Interrupts
1978   // do not have a standard return address. Fixed objects in the current frame,
1979   // such as SSE register spills, should not get this treatment.
1980   if (MF.getFunction().getCallingConv() == CallingConv::X86_INTR &&
1981       Offset >= 0) {
1982     Offset += getOffsetOfLocalArea();
1983   }
1984 
1985   if (IsWin64Prologue) {
1986     assert(!MFI.hasCalls() || (StackSize % 16) == 8);
1987 
1988     // Calculate required stack adjustment.
1989     uint64_t FrameSize = StackSize - SlotSize;
1990     // If required, include space for extra hidden slot for stashing base pointer.
1991     if (X86FI->getRestoreBasePointer())
1992       FrameSize += SlotSize;
1993     uint64_t NumBytes = FrameSize - CSSize;
1994 
1995     uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
1996     if (FI && FI == X86FI->getFAIndex())
1997       return -SEHFrameOffset;
1998 
1999     // FPDelta is the offset from the "traditional" FP location of the old base
2000     // pointer followed by return address and the location required by the
2001     // restricted Win64 prologue.
2002     // Add FPDelta to all offsets below that go through the frame pointer.
2003     FPDelta = FrameSize - SEHFrameOffset;
2004     assert((!MFI.hasCalls() || (FPDelta % 16) == 0) &&
2005            "FPDelta isn't aligned per the Win64 ABI!");
2006   }
2007 
2008 
2009   if (TRI->hasBasePointer(MF)) {
2010     assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
2011     if (FI < 0) {
2012       // Skip the saved EBP.
2013       return Offset + SlotSize + FPDelta;
2014     } else {
2015       assert(isAligned(MFI.getObjectAlign(FI), -(Offset + StackSize)));
2016       return Offset + StackSize;
2017     }
2018   } else if (TRI->needsStackRealignment(MF)) {
2019     if (FI < 0) {
2020       // Skip the saved EBP.
2021       return Offset + SlotSize + FPDelta;
2022     } else {
2023       assert(isAligned(MFI.getObjectAlign(FI), -(Offset + StackSize)));
2024       return Offset + StackSize;
2025     }
2026     // FIXME: Support tail calls
2027   } else {
2028     if (!HasFP)
2029       return Offset + StackSize;
2030 
2031     // Skip the saved EBP.
2032     Offset += SlotSize;
2033 
2034     // Skip the RETADDR move area
2035     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
2036     if (TailCallReturnAddrDelta < 0)
2037       Offset -= TailCallReturnAddrDelta;
2038   }
2039 
2040   return Offset + FPDelta;
2041 }
2042 
2043 int X86FrameLowering::getWin64EHFrameIndexRef(const MachineFunction &MF,
2044                                               int FI, unsigned &FrameReg) const {
2045   const MachineFrameInfo &MFI = MF.getFrameInfo();
2046   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2047   const auto& WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
2048   const auto it = WinEHXMMSlotInfo.find(FI);
2049 
2050   if (it == WinEHXMMSlotInfo.end())
2051     return getFrameIndexReference(MF, FI, FrameReg);
2052 
2053   FrameReg = TRI->getStackRegister();
2054   return alignDown(MFI.getMaxCallFrameSize(), getStackAlign().value()) +
2055          it->second;
2056 }
2057 
2058 int X86FrameLowering::getFrameIndexReferenceSP(const MachineFunction &MF,
2059                                                int FI, unsigned &FrameReg,
2060                                                int Adjustment) const {
2061   const MachineFrameInfo &MFI = MF.getFrameInfo();
2062   FrameReg = TRI->getStackRegister();
2063   return MFI.getObjectOffset(FI) - getOffsetOfLocalArea() + Adjustment;
2064 }
2065 
2066 int
2067 X86FrameLowering::getFrameIndexReferencePreferSP(const MachineFunction &MF,
2068                                                  int FI, unsigned &FrameReg,
2069                                                  bool IgnoreSPUpdates) const {
2070 
2071   const MachineFrameInfo &MFI = MF.getFrameInfo();
2072   // Does not include any dynamic realign.
2073   const uint64_t StackSize = MFI.getStackSize();
2074   // LLVM arranges the stack as follows:
2075   //   ...
2076   //   ARG2
2077   //   ARG1
2078   //   RETADDR
2079   //   PUSH RBP   <-- RBP points here
2080   //   PUSH CSRs
2081   //   ~~~~~~~    <-- possible stack realignment (non-win64)
2082   //   ...
2083   //   STACK OBJECTS
2084   //   ...        <-- RSP after prologue points here
2085   //   ~~~~~~~    <-- possible stack realignment (win64)
2086   //
2087   // if (hasVarSizedObjects()):
2088   //   ...        <-- "base pointer" (ESI/RBX) points here
2089   //   DYNAMIC ALLOCAS
2090   //   ...        <-- RSP points here
2091   //
2092   // Case 1: In the simple case of no stack realignment and no dynamic
2093   // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
2094   // with fixed offsets from RSP.
2095   //
2096   // Case 2: In the case of stack realignment with no dynamic allocas, fixed
2097   // stack objects are addressed with RBP and regular stack objects with RSP.
2098   //
2099   // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
2100   // to address stack arguments for outgoing calls and nothing else. The "base
2101   // pointer" points to local variables, and RBP points to fixed objects.
2102   //
2103   // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
2104   // answer we give is relative to the SP after the prologue, and not the
2105   // SP in the middle of the function.
2106 
2107   if (MFI.isFixedObjectIndex(FI) && TRI->needsStackRealignment(MF) &&
2108       !STI.isTargetWin64())
2109     return getFrameIndexReference(MF, FI, FrameReg);
2110 
2111   // If !hasReservedCallFrame the function might have SP adjustement in the
2112   // body.  So, even though the offset is statically known, it depends on where
2113   // we are in the function.
2114   if (!IgnoreSPUpdates && !hasReservedCallFrame(MF))
2115     return getFrameIndexReference(MF, FI, FrameReg);
2116 
2117   // We don't handle tail calls, and shouldn't be seeing them either.
2118   assert(MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta() >= 0 &&
2119          "we don't handle this case!");
2120 
2121   // This is how the math works out:
2122   //
2123   //  %rsp grows (i.e. gets lower) left to right. Each box below is
2124   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
2125   //  get to.
2126   //
2127   //    ----------------------------------
2128   //    | BP | Obj0 | Obj1 | ... | ObjN |
2129   //    ----------------------------------
2130   //    ^    ^      ^                   ^
2131   //    A    B      C                   E
2132   //
2133   // A is the incoming stack pointer.
2134   // (B - A) is the local area offset (-8 for x86-64) [1]
2135   // (C - A) is the Offset returned by MFI.getObjectOffset for Obj0 [2]
2136   //
2137   // |(E - B)| is the StackSize (absolute value, positive).  For a
2138   // stack that grown down, this works out to be (B - E). [3]
2139   //
2140   // E is also the value of %rsp after stack has been set up, and we
2141   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
2142   // (C - E) == (C - A) - (B - A) + (B - E)
2143   //            { Using [1], [2] and [3] above }
2144   //         == getObjectOffset - LocalAreaOffset + StackSize
2145 
2146   return getFrameIndexReferenceSP(MF, FI, FrameReg, StackSize);
2147 }
2148 
2149 bool X86FrameLowering::assignCalleeSavedSpillSlots(
2150     MachineFunction &MF, const TargetRegisterInfo *TRI,
2151     std::vector<CalleeSavedInfo> &CSI) const {
2152   MachineFrameInfo &MFI = MF.getFrameInfo();
2153   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2154 
2155   unsigned CalleeSavedFrameSize = 0;
2156   unsigned XMMCalleeSavedFrameSize = 0;
2157   auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
2158   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
2159 
2160   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
2161 
2162   if (TailCallReturnAddrDelta < 0) {
2163     // create RETURNADDR area
2164     //   arg
2165     //   arg
2166     //   RETADDR
2167     //   { ...
2168     //     RETADDR area
2169     //     ...
2170     //   }
2171     //   [EBP]
2172     MFI.CreateFixedObject(-TailCallReturnAddrDelta,
2173                            TailCallReturnAddrDelta - SlotSize, true);
2174   }
2175 
2176   // Spill the BasePtr if it's used.
2177   if (this->TRI->hasBasePointer(MF)) {
2178     // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
2179     if (MF.hasEHFunclets()) {
2180       int FI = MFI.CreateSpillStackObject(SlotSize, Align(SlotSize));
2181       X86FI->setHasSEHFramePtrSave(true);
2182       X86FI->setSEHFramePtrSaveIndex(FI);
2183     }
2184   }
2185 
2186   if (hasFP(MF)) {
2187     // emitPrologue always spills frame register the first thing.
2188     SpillSlotOffset -= SlotSize;
2189     MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
2190 
2191     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
2192     // the frame register, we can delete it from CSI list and not have to worry
2193     // about avoiding it later.
2194     Register FPReg = TRI->getFrameRegister(MF);
2195     for (unsigned i = 0; i < CSI.size(); ++i) {
2196       if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
2197         CSI.erase(CSI.begin() + i);
2198         break;
2199       }
2200     }
2201   }
2202 
2203   // Assign slots for GPRs. It increases frame size.
2204   for (unsigned i = CSI.size(); i != 0; --i) {
2205     unsigned Reg = CSI[i - 1].getReg();
2206 
2207     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
2208       continue;
2209 
2210     SpillSlotOffset -= SlotSize;
2211     CalleeSavedFrameSize += SlotSize;
2212 
2213     int SlotIndex = MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
2214     CSI[i - 1].setFrameIdx(SlotIndex);
2215   }
2216 
2217   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
2218   MFI.setCVBytesOfCalleeSavedRegisters(CalleeSavedFrameSize);
2219 
2220   // Assign slots for XMMs.
2221   for (unsigned i = CSI.size(); i != 0; --i) {
2222     unsigned Reg = CSI[i - 1].getReg();
2223     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
2224       continue;
2225 
2226     // If this is k-register make sure we lookup via the largest legal type.
2227     MVT VT = MVT::Other;
2228     if (X86::VK16RegClass.contains(Reg))
2229       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
2230 
2231     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2232     unsigned Size = TRI->getSpillSize(*RC);
2233     Align Alignment = TRI->getSpillAlign(*RC);
2234     // ensure alignment
2235     assert(SpillSlotOffset < 0 && "SpillSlotOffset should always < 0 on X86");
2236     SpillSlotOffset = -alignTo(-SpillSlotOffset, Alignment);
2237 
2238     // spill into slot
2239     SpillSlotOffset -= Size;
2240     int SlotIndex = MFI.CreateFixedSpillStackObject(Size, SpillSlotOffset);
2241     CSI[i - 1].setFrameIdx(SlotIndex);
2242     MFI.ensureMaxAlignment(Alignment);
2243 
2244     // Save the start offset and size of XMM in stack frame for funclets.
2245     if (X86::VR128RegClass.contains(Reg)) {
2246       WinEHXMMSlotInfo[SlotIndex] = XMMCalleeSavedFrameSize;
2247       XMMCalleeSavedFrameSize += Size;
2248     }
2249   }
2250 
2251   return true;
2252 }
2253 
2254 bool X86FrameLowering::spillCalleeSavedRegisters(
2255     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2256     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2257   DebugLoc DL = MBB.findDebugLoc(MI);
2258 
2259   // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
2260   // for us, and there are no XMM CSRs on Win32.
2261   if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
2262     return true;
2263 
2264   // Push GPRs. It increases frame size.
2265   const MachineFunction &MF = *MBB.getParent();
2266   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
2267   for (unsigned i = CSI.size(); i != 0; --i) {
2268     unsigned Reg = CSI[i - 1].getReg();
2269 
2270     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
2271       continue;
2272 
2273     const MachineRegisterInfo &MRI = MF.getRegInfo();
2274     bool isLiveIn = MRI.isLiveIn(Reg);
2275     if (!isLiveIn)
2276       MBB.addLiveIn(Reg);
2277 
2278     // Decide whether we can add a kill flag to the use.
2279     bool CanKill = !isLiveIn;
2280     // Check if any subregister is live-in
2281     if (CanKill) {
2282       for (MCRegAliasIterator AReg(Reg, TRI, false); AReg.isValid(); ++AReg) {
2283         if (MRI.isLiveIn(*AReg)) {
2284           CanKill = false;
2285           break;
2286         }
2287       }
2288     }
2289 
2290     // Do not set a kill flag on values that are also marked as live-in. This
2291     // happens with the @llvm-returnaddress intrinsic and with arguments
2292     // passed in callee saved registers.
2293     // Omitting the kill flags is conservatively correct even if the live-in
2294     // is not used after all.
2295     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, getKillRegState(CanKill))
2296       .setMIFlag(MachineInstr::FrameSetup);
2297   }
2298 
2299   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
2300   // It can be done by spilling XMMs to stack frame.
2301   for (unsigned i = CSI.size(); i != 0; --i) {
2302     unsigned Reg = CSI[i-1].getReg();
2303     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
2304       continue;
2305 
2306     // If this is k-register make sure we lookup via the largest legal type.
2307     MVT VT = MVT::Other;
2308     if (X86::VK16RegClass.contains(Reg))
2309       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
2310 
2311     // Add the callee-saved register as live-in. It's killed at the spill.
2312     MBB.addLiveIn(Reg);
2313     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2314 
2315     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
2316                             TRI);
2317     --MI;
2318     MI->setFlag(MachineInstr::FrameSetup);
2319     ++MI;
2320   }
2321 
2322   return true;
2323 }
2324 
2325 void X86FrameLowering::emitCatchRetReturnValue(MachineBasicBlock &MBB,
2326                                                MachineBasicBlock::iterator MBBI,
2327                                                MachineInstr *CatchRet) const {
2328   // SEH shouldn't use catchret.
2329   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
2330              MBB.getParent()->getFunction().getPersonalityFn())) &&
2331          "SEH should not use CATCHRET");
2332   DebugLoc DL = CatchRet->getDebugLoc();
2333   MachineBasicBlock *CatchRetTarget = CatchRet->getOperand(0).getMBB();
2334 
2335   // Fill EAX/RAX with the address of the target block.
2336   if (STI.is64Bit()) {
2337     // LEA64r CatchRetTarget(%rip), %rax
2338     BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), X86::RAX)
2339         .addReg(X86::RIP)
2340         .addImm(0)
2341         .addReg(0)
2342         .addMBB(CatchRetTarget)
2343         .addReg(0);
2344   } else {
2345     // MOV32ri $CatchRetTarget, %eax
2346     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
2347         .addMBB(CatchRetTarget);
2348   }
2349 
2350   // Record that we've taken the address of CatchRetTarget and no longer just
2351   // reference it in a terminator.
2352   CatchRetTarget->setHasAddressTaken();
2353 }
2354 
2355 bool X86FrameLowering::restoreCalleeSavedRegisters(
2356     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
2357     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
2358   if (CSI.empty())
2359     return false;
2360 
2361   if (MI != MBB.end() && isFuncletReturnInstr(*MI) && STI.isOSWindows()) {
2362     // Don't restore CSRs in 32-bit EH funclets. Matches
2363     // spillCalleeSavedRegisters.
2364     if (STI.is32Bit())
2365       return true;
2366     // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
2367     // funclets. emitEpilogue transforms these to normal jumps.
2368     if (MI->getOpcode() == X86::CATCHRET) {
2369       const Function &F = MBB.getParent()->getFunction();
2370       bool IsSEH = isAsynchronousEHPersonality(
2371           classifyEHPersonality(F.getPersonalityFn()));
2372       if (IsSEH)
2373         return true;
2374     }
2375   }
2376 
2377   DebugLoc DL = MBB.findDebugLoc(MI);
2378 
2379   // Reload XMMs from stack frame.
2380   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
2381     unsigned Reg = CSI[i].getReg();
2382     if (X86::GR64RegClass.contains(Reg) ||
2383         X86::GR32RegClass.contains(Reg))
2384       continue;
2385 
2386     // If this is k-register make sure we lookup via the largest legal type.
2387     MVT VT = MVT::Other;
2388     if (X86::VK16RegClass.contains(Reg))
2389       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
2390 
2391     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2392     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
2393   }
2394 
2395   // POP GPRs.
2396   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
2397   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
2398     unsigned Reg = CSI[i].getReg();
2399     if (!X86::GR64RegClass.contains(Reg) &&
2400         !X86::GR32RegClass.contains(Reg))
2401       continue;
2402 
2403     BuildMI(MBB, MI, DL, TII.get(Opc), Reg)
2404         .setMIFlag(MachineInstr::FrameDestroy);
2405   }
2406   return true;
2407 }
2408 
2409 void X86FrameLowering::determineCalleeSaves(MachineFunction &MF,
2410                                             BitVector &SavedRegs,
2411                                             RegScavenger *RS) const {
2412   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
2413 
2414   // Spill the BasePtr if it's used.
2415   if (TRI->hasBasePointer(MF)){
2416     Register BasePtr = TRI->getBaseRegister();
2417     if (STI.isTarget64BitILP32())
2418       BasePtr = getX86SubSuperRegister(BasePtr, 64);
2419     SavedRegs.set(BasePtr);
2420   }
2421 }
2422 
2423 static bool
2424 HasNestArgument(const MachineFunction *MF) {
2425   const Function &F = MF->getFunction();
2426   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
2427        I != E; I++) {
2428     if (I->hasNestAttr() && !I->use_empty())
2429       return true;
2430   }
2431   return false;
2432 }
2433 
2434 /// GetScratchRegister - Get a temp register for performing work in the
2435 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
2436 /// and the properties of the function either one or two registers will be
2437 /// needed. Set primary to true for the first register, false for the second.
2438 static unsigned
2439 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
2440   CallingConv::ID CallingConvention = MF.getFunction().getCallingConv();
2441 
2442   // Erlang stuff.
2443   if (CallingConvention == CallingConv::HiPE) {
2444     if (Is64Bit)
2445       return Primary ? X86::R14 : X86::R13;
2446     else
2447       return Primary ? X86::EBX : X86::EDI;
2448   }
2449 
2450   if (Is64Bit) {
2451     if (IsLP64)
2452       return Primary ? X86::R11 : X86::R12;
2453     else
2454       return Primary ? X86::R11D : X86::R12D;
2455   }
2456 
2457   bool IsNested = HasNestArgument(&MF);
2458 
2459   if (CallingConvention == CallingConv::X86_FastCall ||
2460       CallingConvention == CallingConv::Fast ||
2461       CallingConvention == CallingConv::Tail) {
2462     if (IsNested)
2463       report_fatal_error("Segmented stacks does not support fastcall with "
2464                          "nested function.");
2465     return Primary ? X86::EAX : X86::ECX;
2466   }
2467   if (IsNested)
2468     return Primary ? X86::EDX : X86::EAX;
2469   return Primary ? X86::ECX : X86::EAX;
2470 }
2471 
2472 // The stack limit in the TCB is set to this many bytes above the actual stack
2473 // limit.
2474 static const uint64_t kSplitStackAvailable = 256;
2475 
2476 void X86FrameLowering::adjustForSegmentedStacks(
2477     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
2478   MachineFrameInfo &MFI = MF.getFrameInfo();
2479   uint64_t StackSize;
2480   unsigned TlsReg, TlsOffset;
2481   DebugLoc DL;
2482 
2483   // To support shrink-wrapping we would need to insert the new blocks
2484   // at the right place and update the branches to PrologueMBB.
2485   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
2486 
2487   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
2488   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
2489          "Scratch register is live-in");
2490 
2491   if (MF.getFunction().isVarArg())
2492     report_fatal_error("Segmented stacks do not support vararg functions.");
2493   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
2494       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
2495       !STI.isTargetDragonFly())
2496     report_fatal_error("Segmented stacks not supported on this platform.");
2497 
2498   // Eventually StackSize will be calculated by a link-time pass; which will
2499   // also decide whether checking code needs to be injected into this particular
2500   // prologue.
2501   StackSize = MFI.getStackSize();
2502 
2503   // Do not generate a prologue for leaf functions with a stack of size zero.
2504   // For non-leaf functions we have to allow for the possibility that the
2505   // callis to a non-split function, as in PR37807. This function could also
2506   // take the address of a non-split function. When the linker tries to adjust
2507   // its non-existent prologue, it would fail with an error. Mark the object
2508   // file so that such failures are not errors. See this Go language bug-report
2509   // https://go-review.googlesource.com/c/go/+/148819/
2510   if (StackSize == 0 && !MFI.hasTailCall()) {
2511     MF.getMMI().setHasNosplitStack(true);
2512     return;
2513   }
2514 
2515   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
2516   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
2517   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2518   bool IsNested = false;
2519 
2520   // We need to know if the function has a nest argument only in 64 bit mode.
2521   if (Is64Bit)
2522     IsNested = HasNestArgument(&MF);
2523 
2524   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
2525   // allocMBB needs to be last (terminating) instruction.
2526 
2527   for (const auto &LI : PrologueMBB.liveins()) {
2528     allocMBB->addLiveIn(LI);
2529     checkMBB->addLiveIn(LI);
2530   }
2531 
2532   if (IsNested)
2533     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
2534 
2535   MF.push_front(allocMBB);
2536   MF.push_front(checkMBB);
2537 
2538   // When the frame size is less than 256 we just compare the stack
2539   // boundary directly to the value of the stack pointer, per gcc.
2540   bool CompareStackPointer = StackSize < kSplitStackAvailable;
2541 
2542   // Read the limit off the current stacklet off the stack_guard location.
2543   if (Is64Bit) {
2544     if (STI.isTargetLinux()) {
2545       TlsReg = X86::FS;
2546       TlsOffset = IsLP64 ? 0x70 : 0x40;
2547     } else if (STI.isTargetDarwin()) {
2548       TlsReg = X86::GS;
2549       TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
2550     } else if (STI.isTargetWin64()) {
2551       TlsReg = X86::GS;
2552       TlsOffset = 0x28; // pvArbitrary, reserved for application use
2553     } else if (STI.isTargetFreeBSD()) {
2554       TlsReg = X86::FS;
2555       TlsOffset = 0x18;
2556     } else if (STI.isTargetDragonFly()) {
2557       TlsReg = X86::FS;
2558       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
2559     } else {
2560       report_fatal_error("Segmented stacks not supported on this platform.");
2561     }
2562 
2563     if (CompareStackPointer)
2564       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
2565     else
2566       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
2567         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
2568 
2569     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
2570       .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
2571   } else {
2572     if (STI.isTargetLinux()) {
2573       TlsReg = X86::GS;
2574       TlsOffset = 0x30;
2575     } else if (STI.isTargetDarwin()) {
2576       TlsReg = X86::GS;
2577       TlsOffset = 0x48 + 90*4;
2578     } else if (STI.isTargetWin32()) {
2579       TlsReg = X86::FS;
2580       TlsOffset = 0x14; // pvArbitrary, reserved for application use
2581     } else if (STI.isTargetDragonFly()) {
2582       TlsReg = X86::FS;
2583       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
2584     } else if (STI.isTargetFreeBSD()) {
2585       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
2586     } else {
2587       report_fatal_error("Segmented stacks not supported on this platform.");
2588     }
2589 
2590     if (CompareStackPointer)
2591       ScratchReg = X86::ESP;
2592     else
2593       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
2594         .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
2595 
2596     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
2597         STI.isTargetDragonFly()) {
2598       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
2599         .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
2600     } else if (STI.isTargetDarwin()) {
2601 
2602       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
2603       unsigned ScratchReg2;
2604       bool SaveScratch2;
2605       if (CompareStackPointer) {
2606         // The primary scratch register is available for holding the TLS offset.
2607         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
2608         SaveScratch2 = false;
2609       } else {
2610         // Need to use a second register to hold the TLS offset
2611         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
2612 
2613         // Unfortunately, with fastcc the second scratch register may hold an
2614         // argument.
2615         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
2616       }
2617 
2618       // If Scratch2 is live-in then it needs to be saved.
2619       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
2620              "Scratch register is live-in and not saved");
2621 
2622       if (SaveScratch2)
2623         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
2624           .addReg(ScratchReg2, RegState::Kill);
2625 
2626       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
2627         .addImm(TlsOffset);
2628       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
2629         .addReg(ScratchReg)
2630         .addReg(ScratchReg2).addImm(1).addReg(0)
2631         .addImm(0)
2632         .addReg(TlsReg);
2633 
2634       if (SaveScratch2)
2635         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
2636     }
2637   }
2638 
2639   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
2640   // It jumps to normal execution of the function body.
2641   BuildMI(checkMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_A);
2642 
2643   // On 32 bit we first push the arguments size and then the frame size. On 64
2644   // bit, we pass the stack frame size in r10 and the argument size in r11.
2645   if (Is64Bit) {
2646     // Functions with nested arguments use R10, so it needs to be saved across
2647     // the call to _morestack
2648 
2649     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
2650     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
2651     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
2652     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
2653     const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
2654 
2655     if (IsNested)
2656       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
2657 
2658     BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
2659       .addImm(StackSize);
2660     BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
2661       .addImm(X86FI->getArgumentStackSize());
2662   } else {
2663     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
2664       .addImm(X86FI->getArgumentStackSize());
2665     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
2666       .addImm(StackSize);
2667   }
2668 
2669   // __morestack is in libgcc
2670   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
2671     // Under the large code model, we cannot assume that __morestack lives
2672     // within 2^31 bytes of the call site, so we cannot use pc-relative
2673     // addressing. We cannot perform the call via a temporary register,
2674     // as the rax register may be used to store the static chain, and all
2675     // other suitable registers may be either callee-save or used for
2676     // parameter passing. We cannot use the stack at this point either
2677     // because __morestack manipulates the stack directly.
2678     //
2679     // To avoid these issues, perform an indirect call via a read-only memory
2680     // location containing the address.
2681     //
2682     // This solution is not perfect, as it assumes that the .rodata section
2683     // is laid out within 2^31 bytes of each function body, but this seems
2684     // to be sufficient for JIT.
2685     // FIXME: Add retpoline support and remove the error here..
2686     if (STI.useIndirectThunkCalls())
2687       report_fatal_error("Emitting morestack calls on 64-bit with the large "
2688                          "code model and thunks not yet implemented.");
2689     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
2690         .addReg(X86::RIP)
2691         .addImm(0)
2692         .addReg(0)
2693         .addExternalSymbol("__morestack_addr")
2694         .addReg(0);
2695     MF.getMMI().setUsesMorestackAddr(true);
2696   } else {
2697     if (Is64Bit)
2698       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
2699         .addExternalSymbol("__morestack");
2700     else
2701       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
2702         .addExternalSymbol("__morestack");
2703   }
2704 
2705   if (IsNested)
2706     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
2707   else
2708     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
2709 
2710   allocMBB->addSuccessor(&PrologueMBB);
2711 
2712   checkMBB->addSuccessor(allocMBB, BranchProbability::getZero());
2713   checkMBB->addSuccessor(&PrologueMBB, BranchProbability::getOne());
2714 
2715 #ifdef EXPENSIVE_CHECKS
2716   MF.verify();
2717 #endif
2718 }
2719 
2720 /// Lookup an ERTS parameter in the !hipe.literals named metadata node.
2721 /// HiPE provides Erlang Runtime System-internal parameters, such as PCB offsets
2722 /// to fields it needs, through a named metadata node "hipe.literals" containing
2723 /// name-value pairs.
2724 static unsigned getHiPELiteral(
2725     NamedMDNode *HiPELiteralsMD, const StringRef LiteralName) {
2726   for (int i = 0, e = HiPELiteralsMD->getNumOperands(); i != e; ++i) {
2727     MDNode *Node = HiPELiteralsMD->getOperand(i);
2728     if (Node->getNumOperands() != 2) continue;
2729     MDString *NodeName = dyn_cast<MDString>(Node->getOperand(0));
2730     ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Node->getOperand(1));
2731     if (!NodeName || !NodeVal) continue;
2732     ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(NodeVal->getValue());
2733     if (ValConst && NodeName->getString() == LiteralName) {
2734       return ValConst->getZExtValue();
2735     }
2736   }
2737 
2738   report_fatal_error("HiPE literal " + LiteralName
2739                      + " required but not provided");
2740 }
2741 
2742 // Return true if there are no non-ehpad successors to MBB and there are no
2743 // non-meta instructions between MBBI and MBB.end().
2744 static bool blockEndIsUnreachable(const MachineBasicBlock &MBB,
2745                                   MachineBasicBlock::const_iterator MBBI) {
2746   return std::all_of(
2747              MBB.succ_begin(), MBB.succ_end(),
2748              [](const MachineBasicBlock *Succ) { return Succ->isEHPad(); }) &&
2749          std::all_of(MBBI, MBB.end(), [](const MachineInstr &MI) {
2750            return MI.isMetaInstruction();
2751          });
2752 }
2753 
2754 /// Erlang programs may need a special prologue to handle the stack size they
2755 /// might need at runtime. That is because Erlang/OTP does not implement a C
2756 /// stack but uses a custom implementation of hybrid stack/heap architecture.
2757 /// (for more information see Eric Stenman's Ph.D. thesis:
2758 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
2759 ///
2760 /// CheckStack:
2761 ///       temp0 = sp - MaxStack
2762 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
2763 /// OldStart:
2764 ///       ...
2765 /// IncStack:
2766 ///       call inc_stack   # doubles the stack space
2767 ///       temp0 = sp - MaxStack
2768 ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
2769 void X86FrameLowering::adjustForHiPEPrologue(
2770     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
2771   MachineFrameInfo &MFI = MF.getFrameInfo();
2772   DebugLoc DL;
2773 
2774   // To support shrink-wrapping we would need to insert the new blocks
2775   // at the right place and update the branches to PrologueMBB.
2776   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
2777 
2778   // HiPE-specific values
2779   NamedMDNode *HiPELiteralsMD = MF.getMMI().getModule()
2780     ->getNamedMetadata("hipe.literals");
2781   if (!HiPELiteralsMD)
2782     report_fatal_error(
2783         "Can't generate HiPE prologue without runtime parameters");
2784   const unsigned HipeLeafWords
2785     = getHiPELiteral(HiPELiteralsMD,
2786                      Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS");
2787   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
2788   const unsigned Guaranteed = HipeLeafWords * SlotSize;
2789   unsigned CallerStkArity = MF.getFunction().arg_size() > CCRegisteredArgs ?
2790                             MF.getFunction().arg_size() - CCRegisteredArgs : 0;
2791   unsigned MaxStack = MFI.getStackSize() + CallerStkArity*SlotSize + SlotSize;
2792 
2793   assert(STI.isTargetLinux() &&
2794          "HiPE prologue is only supported on Linux operating systems.");
2795 
2796   // Compute the largest caller's frame that is needed to fit the callees'
2797   // frames. This 'MaxStack' is computed from:
2798   //
2799   // a) the fixed frame size, which is the space needed for all spilled temps,
2800   // b) outgoing on-stack parameter areas, and
2801   // c) the minimum stack space this function needs to make available for the
2802   //    functions it calls (a tunable ABI property).
2803   if (MFI.hasCalls()) {
2804     unsigned MoreStackForCalls = 0;
2805 
2806     for (auto &MBB : MF) {
2807       for (auto &MI : MBB) {
2808         if (!MI.isCall())
2809           continue;
2810 
2811         // Get callee operand.
2812         const MachineOperand &MO = MI.getOperand(0);
2813 
2814         // Only take account of global function calls (no closures etc.).
2815         if (!MO.isGlobal())
2816           continue;
2817 
2818         const Function *F = dyn_cast<Function>(MO.getGlobal());
2819         if (!F)
2820           continue;
2821 
2822         // Do not update 'MaxStack' for primitive and built-in functions
2823         // (encoded with names either starting with "erlang."/"bif_" or not
2824         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
2825         // "_", such as the BIF "suspend_0") as they are executed on another
2826         // stack.
2827         if (F->getName().find("erlang.") != StringRef::npos ||
2828             F->getName().find("bif_") != StringRef::npos ||
2829             F->getName().find_first_of("._") == StringRef::npos)
2830           continue;
2831 
2832         unsigned CalleeStkArity =
2833           F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
2834         if (HipeLeafWords - 1 > CalleeStkArity)
2835           MoreStackForCalls = std::max(MoreStackForCalls,
2836                                (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
2837       }
2838     }
2839     MaxStack += MoreStackForCalls;
2840   }
2841 
2842   // If the stack frame needed is larger than the guaranteed then runtime checks
2843   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
2844   if (MaxStack > Guaranteed) {
2845     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
2846     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
2847 
2848     for (const auto &LI : PrologueMBB.liveins()) {
2849       stackCheckMBB->addLiveIn(LI);
2850       incStackMBB->addLiveIn(LI);
2851     }
2852 
2853     MF.push_front(incStackMBB);
2854     MF.push_front(stackCheckMBB);
2855 
2856     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
2857     unsigned LEAop, CMPop, CALLop;
2858     SPLimitOffset = getHiPELiteral(HiPELiteralsMD, "P_NSP_LIMIT");
2859     if (Is64Bit) {
2860       SPReg = X86::RSP;
2861       PReg  = X86::RBP;
2862       LEAop = X86::LEA64r;
2863       CMPop = X86::CMP64rm;
2864       CALLop = X86::CALL64pcrel32;
2865     } else {
2866       SPReg = X86::ESP;
2867       PReg  = X86::EBP;
2868       LEAop = X86::LEA32r;
2869       CMPop = X86::CMP32rm;
2870       CALLop = X86::CALLpcrel32;
2871     }
2872 
2873     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
2874     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
2875            "HiPE prologue scratch register is live-in");
2876 
2877     // Create new MBB for StackCheck:
2878     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
2879                  SPReg, false, -MaxStack);
2880     // SPLimitOffset is in a fixed heap location (pointed by BP).
2881     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
2882                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
2883     BuildMI(stackCheckMBB, DL, TII.get(X86::JCC_1)).addMBB(&PrologueMBB).addImm(X86::COND_AE);
2884 
2885     // Create new MBB for IncStack:
2886     BuildMI(incStackMBB, DL, TII.get(CALLop)).
2887       addExternalSymbol("inc_stack_0");
2888     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
2889                  SPReg, false, -MaxStack);
2890     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
2891                  .addReg(ScratchReg), PReg, false, SPLimitOffset);
2892     BuildMI(incStackMBB, DL, TII.get(X86::JCC_1)).addMBB(incStackMBB).addImm(X86::COND_LE);
2893 
2894     stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100});
2895     stackCheckMBB->addSuccessor(incStackMBB, {1, 100});
2896     incStackMBB->addSuccessor(&PrologueMBB, {99, 100});
2897     incStackMBB->addSuccessor(incStackMBB, {1, 100});
2898   }
2899 #ifdef EXPENSIVE_CHECKS
2900   MF.verify();
2901 #endif
2902 }
2903 
2904 bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
2905                                            MachineBasicBlock::iterator MBBI,
2906                                            const DebugLoc &DL,
2907                                            int Offset) const {
2908 
2909   if (Offset <= 0)
2910     return false;
2911 
2912   if (Offset % SlotSize)
2913     return false;
2914 
2915   int NumPops = Offset / SlotSize;
2916   // This is only worth it if we have at most 2 pops.
2917   if (NumPops != 1 && NumPops != 2)
2918     return false;
2919 
2920   // Handle only the trivial case where the adjustment directly follows
2921   // a call. This is the most common one, anyway.
2922   if (MBBI == MBB.begin())
2923     return false;
2924   MachineBasicBlock::iterator Prev = std::prev(MBBI);
2925   if (!Prev->isCall() || !Prev->getOperand(1).isRegMask())
2926     return false;
2927 
2928   unsigned Regs[2];
2929   unsigned FoundRegs = 0;
2930 
2931   auto &MRI = MBB.getParent()->getRegInfo();
2932   auto RegMask = Prev->getOperand(1);
2933 
2934   auto &RegClass =
2935       Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
2936   // Try to find up to NumPops free registers.
2937   for (auto Candidate : RegClass) {
2938 
2939     // Poor man's liveness:
2940     // Since we're immediately after a call, any register that is clobbered
2941     // by the call and not defined by it can be considered dead.
2942     if (!RegMask.clobbersPhysReg(Candidate))
2943       continue;
2944 
2945     // Don't clobber reserved registers
2946     if (MRI.isReserved(Candidate))
2947       continue;
2948 
2949     bool IsDef = false;
2950     for (const MachineOperand &MO : Prev->implicit_operands()) {
2951       if (MO.isReg() && MO.isDef() &&
2952           TRI->isSuperOrSubRegisterEq(MO.getReg(), Candidate)) {
2953         IsDef = true;
2954         break;
2955       }
2956     }
2957 
2958     if (IsDef)
2959       continue;
2960 
2961     Regs[FoundRegs++] = Candidate;
2962     if (FoundRegs == (unsigned)NumPops)
2963       break;
2964   }
2965 
2966   if (FoundRegs == 0)
2967     return false;
2968 
2969   // If we found only one free register, but need two, reuse the same one twice.
2970   while (FoundRegs < (unsigned)NumPops)
2971     Regs[FoundRegs++] = Regs[0];
2972 
2973   for (int i = 0; i < NumPops; ++i)
2974     BuildMI(MBB, MBBI, DL,
2975             TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r), Regs[i]);
2976 
2977   return true;
2978 }
2979 
2980 MachineBasicBlock::iterator X86FrameLowering::
2981 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
2982                               MachineBasicBlock::iterator I) const {
2983   bool reserveCallFrame = hasReservedCallFrame(MF);
2984   unsigned Opcode = I->getOpcode();
2985   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
2986   DebugLoc DL = I->getDebugLoc();
2987   uint64_t Amount = TII.getFrameSize(*I);
2988   uint64_t InternalAmt = (isDestroy || Amount) ? TII.getFrameAdjustment(*I) : 0;
2989   I = MBB.erase(I);
2990   auto InsertPos = skipDebugInstructionsForward(I, MBB.end());
2991 
2992   // Try to avoid emitting dead SP adjustments if the block end is unreachable,
2993   // typically because the function is marked noreturn (abort, throw,
2994   // assert_fail, etc).
2995   if (isDestroy && blockEndIsUnreachable(MBB, I))
2996     return I;
2997 
2998   if (!reserveCallFrame) {
2999     // If the stack pointer can be changed after prologue, turn the
3000     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
3001     // adjcallstackdown instruction into 'add ESP, <amt>'
3002 
3003     // We need to keep the stack aligned properly.  To do this, we round the
3004     // amount of space needed for the outgoing arguments up to the next
3005     // alignment boundary.
3006     Amount = alignTo(Amount, getStackAlign());
3007 
3008     const Function &F = MF.getFunction();
3009     bool WindowsCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
3010     bool DwarfCFI = !WindowsCFI && MF.needsFrameMoves();
3011 
3012     // If we have any exception handlers in this function, and we adjust
3013     // the SP before calls, we may need to indicate this to the unwinder
3014     // using GNU_ARGS_SIZE. Note that this may be necessary even when
3015     // Amount == 0, because the preceding function may have set a non-0
3016     // GNU_ARGS_SIZE.
3017     // TODO: We don't need to reset this between subsequent functions,
3018     // if it didn't change.
3019     bool HasDwarfEHHandlers = !WindowsCFI && !MF.getLandingPads().empty();
3020 
3021     if (HasDwarfEHHandlers && !isDestroy &&
3022         MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences())
3023       BuildCFI(MBB, InsertPos, DL,
3024                MCCFIInstruction::createGnuArgsSize(nullptr, Amount));
3025 
3026     if (Amount == 0)
3027       return I;
3028 
3029     // Factor out the amount that gets handled inside the sequence
3030     // (Pushes of argument for frame setup, callee pops for frame destroy)
3031     Amount -= InternalAmt;
3032 
3033     // TODO: This is needed only if we require precise CFA.
3034     // If this is a callee-pop calling convention, emit a CFA adjust for
3035     // the amount the callee popped.
3036     if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF))
3037       BuildCFI(MBB, InsertPos, DL,
3038                MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt));
3039 
3040     // Add Amount to SP to destroy a frame, or subtract to setup.
3041     int64_t StackAdjustment = isDestroy ? Amount : -Amount;
3042 
3043     if (StackAdjustment) {
3044       // Merge with any previous or following adjustment instruction. Note: the
3045       // instructions merged with here do not have CFI, so their stack
3046       // adjustments do not feed into CfaAdjustment.
3047       StackAdjustment += mergeSPUpdates(MBB, InsertPos, true);
3048       StackAdjustment += mergeSPUpdates(MBB, InsertPos, false);
3049 
3050       if (StackAdjustment) {
3051         if (!(F.hasMinSize() &&
3052               adjustStackWithPops(MBB, InsertPos, DL, StackAdjustment)))
3053           BuildStackAdjustment(MBB, InsertPos, DL, StackAdjustment,
3054                                /*InEpilogue=*/false);
3055       }
3056     }
3057 
3058     if (DwarfCFI && !hasFP(MF)) {
3059       // If we don't have FP, but need to generate unwind information,
3060       // we need to set the correct CFA offset after the stack adjustment.
3061       // How much we adjust the CFA offset depends on whether we're emitting
3062       // CFI only for EH purposes or for debugging. EH only requires the CFA
3063       // offset to be correct at each call site, while for debugging we want
3064       // it to be more precise.
3065 
3066       int64_t CfaAdjustment = -StackAdjustment;
3067       // TODO: When not using precise CFA, we also need to adjust for the
3068       // InternalAmt here.
3069       if (CfaAdjustment) {
3070         BuildCFI(MBB, InsertPos, DL,
3071                  MCCFIInstruction::createAdjustCfaOffset(nullptr,
3072                                                          CfaAdjustment));
3073       }
3074     }
3075 
3076     return I;
3077   }
3078 
3079   if (InternalAmt) {
3080     MachineBasicBlock::iterator CI = I;
3081     MachineBasicBlock::iterator B = MBB.begin();
3082     while (CI != B && !std::prev(CI)->isCall())
3083       --CI;
3084     BuildStackAdjustment(MBB, CI, DL, -InternalAmt, /*InEpilogue=*/false);
3085   }
3086 
3087   return I;
3088 }
3089 
3090 bool X86FrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
3091   assert(MBB.getParent() && "Block is not attached to a function!");
3092   const MachineFunction &MF = *MBB.getParent();
3093   return !TRI->needsStackRealignment(MF) || !MBB.isLiveIn(X86::EFLAGS);
3094 }
3095 
3096 bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
3097   assert(MBB.getParent() && "Block is not attached to a function!");
3098 
3099   // Win64 has strict requirements in terms of epilogue and we are
3100   // not taking a chance at messing with them.
3101   // I.e., unless this block is already an exit block, we can't use
3102   // it as an epilogue.
3103   if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
3104     return false;
3105 
3106   if (canUseLEAForSPInEpilogue(*MBB.getParent()))
3107     return true;
3108 
3109   // If we cannot use LEA to adjust SP, we may need to use ADD, which
3110   // clobbers the EFLAGS. Check that we do not need to preserve it,
3111   // otherwise, conservatively assume this is not
3112   // safe to insert the epilogue here.
3113   return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
3114 }
3115 
3116 bool X86FrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
3117   // If we may need to emit frameless compact unwind information, give
3118   // up as this is currently broken: PR25614.
3119   return (MF.getFunction().hasFnAttribute(Attribute::NoUnwind) || hasFP(MF)) &&
3120          // The lowering of segmented stack and HiPE only support entry blocks
3121          // as prologue blocks: PR26107.
3122          // This limitation may be lifted if we fix:
3123          // - adjustForSegmentedStacks
3124          // - adjustForHiPEPrologue
3125          MF.getFunction().getCallingConv() != CallingConv::HiPE &&
3126          !MF.shouldSplitStack();
3127 }
3128 
3129 MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers(
3130     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
3131     const DebugLoc &DL, bool RestoreSP) const {
3132   assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
3133   assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
3134   assert(STI.is32Bit() && !Uses64BitFramePtr &&
3135          "restoring EBP/ESI on non-32-bit target");
3136 
3137   MachineFunction &MF = *MBB.getParent();
3138   Register FramePtr = TRI->getFrameRegister(MF);
3139   Register BasePtr = TRI->getBaseRegister();
3140   WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
3141   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
3142   MachineFrameInfo &MFI = MF.getFrameInfo();
3143 
3144   // FIXME: Don't set FrameSetup flag in catchret case.
3145 
3146   int FI = FuncInfo.EHRegNodeFrameIndex;
3147   int EHRegSize = MFI.getObjectSize(FI);
3148 
3149   if (RestoreSP) {
3150     // MOV32rm -EHRegSize(%ebp), %esp
3151     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP),
3152                  X86::EBP, true, -EHRegSize)
3153         .setMIFlag(MachineInstr::FrameSetup);
3154   }
3155 
3156   unsigned UsedReg;
3157   int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg);
3158   int EndOffset = -EHRegOffset - EHRegSize;
3159   FuncInfo.EHRegNodeEndOffset = EndOffset;
3160 
3161   if (UsedReg == FramePtr) {
3162     // ADD $offset, %ebp
3163     unsigned ADDri = getADDriOpcode(false, EndOffset);
3164     BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr)
3165         .addReg(FramePtr)
3166         .addImm(EndOffset)
3167         .setMIFlag(MachineInstr::FrameSetup)
3168         ->getOperand(3)
3169         .setIsDead();
3170     assert(EndOffset >= 0 &&
3171            "end of registration object above normal EBP position!");
3172   } else if (UsedReg == BasePtr) {
3173     // LEA offset(%ebp), %esi
3174     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr),
3175                  FramePtr, false, EndOffset)
3176         .setMIFlag(MachineInstr::FrameSetup);
3177     // MOV32rm SavedEBPOffset(%esi), %ebp
3178     assert(X86FI->getHasSEHFramePtrSave());
3179     int Offset =
3180         getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg);
3181     assert(UsedReg == BasePtr);
3182     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr),
3183                  UsedReg, true, Offset)
3184         .setMIFlag(MachineInstr::FrameSetup);
3185   } else {
3186     llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
3187   }
3188   return MBBI;
3189 }
3190 
3191 int X86FrameLowering::getInitialCFAOffset(const MachineFunction &MF) const {
3192   return TRI->getSlotSize();
3193 }
3194 
3195 unsigned X86FrameLowering::getInitialCFARegister(const MachineFunction &MF)
3196     const {
3197   return TRI->getDwarfRegNum(StackPtr, true);
3198 }
3199 
3200 namespace {
3201 // Struct used by orderFrameObjects to help sort the stack objects.
3202 struct X86FrameSortingObject {
3203   bool IsValid = false;         // true if we care about this Object.
3204   unsigned ObjectIndex = 0;     // Index of Object into MFI list.
3205   unsigned ObjectSize = 0;      // Size of Object in bytes.
3206   Align ObjectAlignment = Align(1); // Alignment of Object in bytes.
3207   unsigned ObjectNumUses = 0;   // Object static number of uses.
3208 };
3209 
3210 // The comparison function we use for std::sort to order our local
3211 // stack symbols. The current algorithm is to use an estimated
3212 // "density". This takes into consideration the size and number of
3213 // uses each object has in order to roughly minimize code size.
3214 // So, for example, an object of size 16B that is referenced 5 times
3215 // will get higher priority than 4 4B objects referenced 1 time each.
3216 // It's not perfect and we may be able to squeeze a few more bytes out of
3217 // it (for example : 0(esp) requires fewer bytes, symbols allocated at the
3218 // fringe end can have special consideration, given their size is less
3219 // important, etc.), but the algorithmic complexity grows too much to be
3220 // worth the extra gains we get. This gets us pretty close.
3221 // The final order leaves us with objects with highest priority going
3222 // at the end of our list.
3223 struct X86FrameSortingComparator {
3224   inline bool operator()(const X86FrameSortingObject &A,
3225                          const X86FrameSortingObject &B) {
3226     uint64_t DensityAScaled, DensityBScaled;
3227 
3228     // For consistency in our comparison, all invalid objects are placed
3229     // at the end. This also allows us to stop walking when we hit the
3230     // first invalid item after it's all sorted.
3231     if (!A.IsValid)
3232       return false;
3233     if (!B.IsValid)
3234       return true;
3235 
3236     // The density is calculated by doing :
3237     //     (double)DensityA = A.ObjectNumUses / A.ObjectSize
3238     //     (double)DensityB = B.ObjectNumUses / B.ObjectSize
3239     // Since this approach may cause inconsistencies in
3240     // the floating point <, >, == comparisons, depending on the floating
3241     // point model with which the compiler was built, we're going
3242     // to scale both sides by multiplying with
3243     // A.ObjectSize * B.ObjectSize. This ends up factoring away
3244     // the division and, with it, the need for any floating point
3245     // arithmetic.
3246     DensityAScaled = static_cast<uint64_t>(A.ObjectNumUses) *
3247       static_cast<uint64_t>(B.ObjectSize);
3248     DensityBScaled = static_cast<uint64_t>(B.ObjectNumUses) *
3249       static_cast<uint64_t>(A.ObjectSize);
3250 
3251     // If the two densities are equal, prioritize highest alignment
3252     // objects. This allows for similar alignment objects
3253     // to be packed together (given the same density).
3254     // There's room for improvement here, also, since we can pack
3255     // similar alignment (different density) objects next to each
3256     // other to save padding. This will also require further
3257     // complexity/iterations, and the overall gain isn't worth it,
3258     // in general. Something to keep in mind, though.
3259     if (DensityAScaled == DensityBScaled)
3260       return A.ObjectAlignment < B.ObjectAlignment;
3261 
3262     return DensityAScaled < DensityBScaled;
3263   }
3264 };
3265 } // namespace
3266 
3267 // Order the symbols in the local stack.
3268 // We want to place the local stack objects in some sort of sensible order.
3269 // The heuristic we use is to try and pack them according to static number
3270 // of uses and size of object in order to minimize code size.
3271 void X86FrameLowering::orderFrameObjects(
3272     const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
3273   const MachineFrameInfo &MFI = MF.getFrameInfo();
3274 
3275   // Don't waste time if there's nothing to do.
3276   if (ObjectsToAllocate.empty())
3277     return;
3278 
3279   // Create an array of all MFI objects. We won't need all of these
3280   // objects, but we're going to create a full array of them to make
3281   // it easier to index into when we're counting "uses" down below.
3282   // We want to be able to easily/cheaply access an object by simply
3283   // indexing into it, instead of having to search for it every time.
3284   std::vector<X86FrameSortingObject> SortingObjects(MFI.getObjectIndexEnd());
3285 
3286   // Walk the objects we care about and mark them as such in our working
3287   // struct.
3288   for (auto &Obj : ObjectsToAllocate) {
3289     SortingObjects[Obj].IsValid = true;
3290     SortingObjects[Obj].ObjectIndex = Obj;
3291     SortingObjects[Obj].ObjectAlignment = MFI.getObjectAlign(Obj);
3292     // Set the size.
3293     int ObjectSize = MFI.getObjectSize(Obj);
3294     if (ObjectSize == 0)
3295       // Variable size. Just use 4.
3296       SortingObjects[Obj].ObjectSize = 4;
3297     else
3298       SortingObjects[Obj].ObjectSize = ObjectSize;
3299   }
3300 
3301   // Count the number of uses for each object.
3302   for (auto &MBB : MF) {
3303     for (auto &MI : MBB) {
3304       if (MI.isDebugInstr())
3305         continue;
3306       for (const MachineOperand &MO : MI.operands()) {
3307         // Check to see if it's a local stack symbol.
3308         if (!MO.isFI())
3309           continue;
3310         int Index = MO.getIndex();
3311         // Check to see if it falls within our range, and is tagged
3312         // to require ordering.
3313         if (Index >= 0 && Index < MFI.getObjectIndexEnd() &&
3314             SortingObjects[Index].IsValid)
3315           SortingObjects[Index].ObjectNumUses++;
3316       }
3317     }
3318   }
3319 
3320   // Sort the objects using X86FrameSortingAlgorithm (see its comment for
3321   // info).
3322   llvm::stable_sort(SortingObjects, X86FrameSortingComparator());
3323 
3324   // Now modify the original list to represent the final order that
3325   // we want. The order will depend on whether we're going to access them
3326   // from the stack pointer or the frame pointer. For SP, the list should
3327   // end up with the END containing objects that we want with smaller offsets.
3328   // For FP, it should be flipped.
3329   int i = 0;
3330   for (auto &Obj : SortingObjects) {
3331     // All invalid items are sorted at the end, so it's safe to stop.
3332     if (!Obj.IsValid)
3333       break;
3334     ObjectsToAllocate[i++] = Obj.ObjectIndex;
3335   }
3336 
3337   // Flip it if we're accessing off of the FP.
3338   if (!TRI->needsStackRealignment(MF) && hasFP(MF))
3339     std::reverse(ObjectsToAllocate.begin(), ObjectsToAllocate.end());
3340 }
3341 
3342 
3343 unsigned X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const {
3344   // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
3345   unsigned Offset = 16;
3346   // RBP is immediately pushed.
3347   Offset += SlotSize;
3348   // All callee-saved registers are then pushed.
3349   Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
3350   // Every funclet allocates enough stack space for the largest outgoing call.
3351   Offset += getWinEHFuncletFrameSize(MF);
3352   return Offset;
3353 }
3354 
3355 void X86FrameLowering::processFunctionBeforeFrameFinalized(
3356     MachineFunction &MF, RegScavenger *RS) const {
3357   // Mark the function as not having WinCFI. We will set it back to true in
3358   // emitPrologue if it gets called and emits CFI.
3359   MF.setHasWinCFI(false);
3360 
3361   // If this function isn't doing Win64-style C++ EH, we don't need to do
3362   // anything.
3363   const Function &F = MF.getFunction();
3364   if (!STI.is64Bit() || !MF.hasEHFunclets() ||
3365       classifyEHPersonality(F.getPersonalityFn()) != EHPersonality::MSVC_CXX)
3366     return;
3367 
3368   // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
3369   // relative to RSP after the prologue.  Find the offset of the last fixed
3370   // object, so that we can allocate a slot immediately following it. If there
3371   // were no fixed objects, use offset -SlotSize, which is immediately after the
3372   // return address. Fixed objects have negative frame indices.
3373   MachineFrameInfo &MFI = MF.getFrameInfo();
3374   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
3375   int64_t MinFixedObjOffset = -SlotSize;
3376   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I)
3377     MinFixedObjOffset = std::min(MinFixedObjOffset, MFI.getObjectOffset(I));
3378 
3379   for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
3380     for (WinEHHandlerType &H : TBME.HandlerArray) {
3381       int FrameIndex = H.CatchObj.FrameIndex;
3382       if (FrameIndex != INT_MAX) {
3383         // Ensure alignment.
3384         unsigned Align = MFI.getObjectAlign(FrameIndex).value();
3385         MinFixedObjOffset -= std::abs(MinFixedObjOffset) % Align;
3386         MinFixedObjOffset -= MFI.getObjectSize(FrameIndex);
3387         MFI.setObjectOffset(FrameIndex, MinFixedObjOffset);
3388       }
3389     }
3390   }
3391 
3392   // Ensure alignment.
3393   MinFixedObjOffset -= std::abs(MinFixedObjOffset) % 8;
3394   int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
3395   int UnwindHelpFI =
3396       MFI.CreateFixedObject(SlotSize, UnwindHelpOffset, /*IsImmutable=*/false);
3397   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
3398 
3399   // Store -2 into UnwindHelp on function entry. We have to scan forwards past
3400   // other frame setup instructions.
3401   MachineBasicBlock &MBB = MF.front();
3402   auto MBBI = MBB.begin();
3403   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
3404     ++MBBI;
3405 
3406   DebugLoc DL = MBB.findDebugLoc(MBBI);
3407   addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),
3408                     UnwindHelpFI)
3409       .addImm(-2);
3410 }
3411 
3412 void X86FrameLowering::processFunctionBeforeFrameIndicesReplaced(
3413     MachineFunction &MF, RegScavenger *RS) const {
3414   if (STI.is32Bit() && MF.hasEHFunclets())
3415     restoreWinEHStackPointersInParent(MF);
3416 }
3417 
3418 void X86FrameLowering::restoreWinEHStackPointersInParent(
3419     MachineFunction &MF) const {
3420   // 32-bit functions have to restore stack pointers when control is transferred
3421   // back to the parent function. These blocks are identified as eh pads that
3422   // are not funclet entries.
3423   bool IsSEH = isAsynchronousEHPersonality(
3424       classifyEHPersonality(MF.getFunction().getPersonalityFn()));
3425   for (MachineBasicBlock &MBB : MF) {
3426     bool NeedsRestore = MBB.isEHPad() && !MBB.isEHFuncletEntry();
3427     if (NeedsRestore)
3428       restoreWin32EHStackPointers(MBB, MBB.begin(), DebugLoc(),
3429                                   /*RestoreSP=*/IsSEH);
3430   }
3431 }
3432