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