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