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