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