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