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