xref: /freebsd-src/contrib/llvm-project/llvm/lib/Target/X86/X86FrameLowering.cpp (revision 36b606ae6aa4b24061096ba18582e0a08ccd5dba)
10b57cec5SDimitry Andric //===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file contains the X86 implementation of TargetFrameLowering class.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "X86FrameLowering.h"
1481ad6265SDimitry Andric #include "MCTargetDesc/X86MCTargetDesc.h"
150b57cec5SDimitry Andric #include "X86InstrBuilder.h"
160b57cec5SDimitry Andric #include "X86InstrInfo.h"
170b57cec5SDimitry Andric #include "X86MachineFunctionInfo.h"
180b57cec5SDimitry Andric #include "X86Subtarget.h"
190b57cec5SDimitry Andric #include "X86TargetMachine.h"
205ffd83dbSDimitry Andric #include "llvm/ADT/Statistic.h"
2181ad6265SDimitry Andric #include "llvm/CodeGen/LivePhysRegs.h"
220b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
230b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
240b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
250b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
260b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
270b57cec5SDimitry Andric #include "llvm/CodeGen/WinEHFuncInfo.h"
280b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
2906c3fb27SDimitry Andric #include "llvm/IR/EHPersonalities.h"
300b57cec5SDimitry Andric #include "llvm/IR/Function.h"
310fca6ea1SDimitry Andric #include "llvm/IR/Module.h"
320b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
33e8d8bef9SDimitry Andric #include "llvm/MC/MCObjectFileInfo.h"
340b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
350b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
3606c3fb27SDimitry Andric #include "llvm/Support/LEB128.h"
370b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
380b57cec5SDimitry Andric #include <cstdlib>
390b57cec5SDimitry Andric 
405ffd83dbSDimitry Andric #define DEBUG_TYPE "x86-fl"
415ffd83dbSDimitry Andric 
425ffd83dbSDimitry Andric STATISTIC(NumFrameLoopProbe, "Number of loop stack probes used in prologue");
435ffd83dbSDimitry Andric STATISTIC(NumFrameExtraProbe,
445ffd83dbSDimitry Andric           "Number of extra stack probes generated in prologue");
455f757f3fSDimitry Andric STATISTIC(NumFunctionUsingPush2Pop2, "Number of funtions using push2/pop2");
465ffd83dbSDimitry Andric 
470b57cec5SDimitry Andric using namespace llvm;
480b57cec5SDimitry Andric 
490b57cec5SDimitry Andric X86FrameLowering::X86FrameLowering(const X86Subtarget &STI,
508bcb0991SDimitry Andric                                    MaybeAlign StackAlignOverride)
518bcb0991SDimitry Andric     : TargetFrameLowering(StackGrowsDown, StackAlignOverride.valueOrOne(),
520b57cec5SDimitry Andric                           STI.is64Bit() ? -8 : -4),
530b57cec5SDimitry Andric       STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {
540b57cec5SDimitry Andric   // Cache a bunch of frame-related predicates for this subtarget.
550b57cec5SDimitry Andric   SlotSize = TRI->getSlotSize();
560b57cec5SDimitry Andric   Is64Bit = STI.is64Bit();
570b57cec5SDimitry Andric   IsLP64 = STI.isTarget64BitLP64();
580b57cec5SDimitry Andric   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
590b57cec5SDimitry Andric   Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
600b57cec5SDimitry Andric   StackPtr = TRI->getStackRegister();
610b57cec5SDimitry Andric }
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
640b57cec5SDimitry Andric   return !MF.getFrameInfo().hasVarSizedObjects() &&
655ffd83dbSDimitry Andric          !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences() &&
665ffd83dbSDimitry Andric          !MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall();
670b57cec5SDimitry Andric }
680b57cec5SDimitry Andric 
690b57cec5SDimitry Andric /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
700b57cec5SDimitry Andric /// call frame pseudos can be simplified.  Having a FP, as in the default
710b57cec5SDimitry Andric /// implementation, is not sufficient here since we can't always use it.
720b57cec5SDimitry Andric /// Use a more nuanced condition.
735f757f3fSDimitry Andric bool X86FrameLowering::canSimplifyCallFramePseudos(
745f757f3fSDimitry Andric     const MachineFunction &MF) const {
750b57cec5SDimitry Andric   return hasReservedCallFrame(MF) ||
765ffd83dbSDimitry Andric          MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() ||
77fe6060f1SDimitry Andric          (hasFP(MF) && !TRI->hasStackRealignment(MF)) ||
780b57cec5SDimitry Andric          TRI->hasBasePointer(MF);
790b57cec5SDimitry Andric }
800b57cec5SDimitry Andric 
810b57cec5SDimitry Andric // needsFrameIndexResolution - Do we need to perform FI resolution for
820b57cec5SDimitry Andric // this function. Normally, this is required only when the function
830b57cec5SDimitry Andric // has any stack objects. However, FI resolution actually has another job,
840b57cec5SDimitry Andric // not apparent from the title - it resolves callframesetup/destroy
850b57cec5SDimitry Andric // that were not simplified earlier.
860b57cec5SDimitry Andric // So, this is required for x86 functions that have push sequences even
870b57cec5SDimitry Andric // when there are no stack objects.
885f757f3fSDimitry Andric bool X86FrameLowering::needsFrameIndexResolution(
895f757f3fSDimitry Andric     const MachineFunction &MF) const {
900b57cec5SDimitry Andric   return MF.getFrameInfo().hasStackObjects() ||
910b57cec5SDimitry Andric          MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
920b57cec5SDimitry Andric }
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric /// hasFP - Return true if the specified function should have a dedicated frame
950b57cec5SDimitry Andric /// pointer register.  This is true if the function has variable sized allocas
960b57cec5SDimitry Andric /// or if frame pointer elimination is disabled.
970b57cec5SDimitry Andric bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
980b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
990b57cec5SDimitry Andric   return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
100fe6060f1SDimitry Andric           TRI->hasStackRealignment(MF) || MFI.hasVarSizedObjects() ||
1010b57cec5SDimitry Andric           MFI.isFrameAddressTaken() || MFI.hasOpaqueSPAdjustment() ||
1020b57cec5SDimitry Andric           MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
1035ffd83dbSDimitry Andric           MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() ||
1040b57cec5SDimitry Andric           MF.callsUnwindInit() || MF.hasEHFunclets() || MF.callsEHReturn() ||
1050b57cec5SDimitry Andric           MFI.hasStackMap() || MFI.hasPatchPoint() ||
106d56accc7SDimitry Andric           (isWin64Prologue(MF) && MFI.hasCopyImplyingStackAdjustment()));
1070b57cec5SDimitry Andric }
1080b57cec5SDimitry Andric 
10906c3fb27SDimitry Andric static unsigned getSUBriOpcode(bool IsLP64) {
11006c3fb27SDimitry Andric   return IsLP64 ? X86::SUB64ri32 : X86::SUB32ri;
1110b57cec5SDimitry Andric }
1120b57cec5SDimitry Andric 
11306c3fb27SDimitry Andric static unsigned getADDriOpcode(bool IsLP64) {
11406c3fb27SDimitry Andric   return IsLP64 ? X86::ADD64ri32 : X86::ADD32ri;
1150b57cec5SDimitry Andric }
1160b57cec5SDimitry Andric 
117480093f4SDimitry Andric static unsigned getSUBrrOpcode(bool IsLP64) {
118480093f4SDimitry Andric   return IsLP64 ? X86::SUB64rr : X86::SUB32rr;
1190b57cec5SDimitry Andric }
1200b57cec5SDimitry Andric 
121480093f4SDimitry Andric static unsigned getADDrrOpcode(bool IsLP64) {
122480093f4SDimitry Andric   return IsLP64 ? X86::ADD64rr : X86::ADD32rr;
1230b57cec5SDimitry Andric }
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
12606c3fb27SDimitry Andric   return IsLP64 ? X86::AND64ri32 : X86::AND32ri;
1270b57cec5SDimitry Andric }
1280b57cec5SDimitry Andric 
129480093f4SDimitry Andric static unsigned getLEArOpcode(bool IsLP64) {
1300b57cec5SDimitry Andric   return IsLP64 ? X86::LEA64r : X86::LEA32r;
1310b57cec5SDimitry Andric }
1320b57cec5SDimitry Andric 
13304eeddc0SDimitry Andric static unsigned getMOVriOpcode(bool Use64BitReg, int64_t Imm) {
13404eeddc0SDimitry Andric   if (Use64BitReg) {
13504eeddc0SDimitry Andric     if (isUInt<32>(Imm))
13604eeddc0SDimitry Andric       return X86::MOV32ri64;
13704eeddc0SDimitry Andric     if (isInt<32>(Imm))
13804eeddc0SDimitry Andric       return X86::MOV64ri32;
13904eeddc0SDimitry Andric     return X86::MOV64ri;
14004eeddc0SDimitry Andric   }
14104eeddc0SDimitry Andric   return X86::MOV32ri;
14204eeddc0SDimitry Andric }
14304eeddc0SDimitry Andric 
1445f757f3fSDimitry Andric // Push-Pop Acceleration (PPX) hint is used to indicate that the POP reads the
1455f757f3fSDimitry Andric // value written by the PUSH from the stack. The processor tracks these marked
1465f757f3fSDimitry Andric // instructions internally and fast-forwards register data between matching PUSH
1475f757f3fSDimitry Andric // and POP instructions, without going through memory or through the training
1485f757f3fSDimitry Andric // loop of the Fast Store Forwarding Predictor (FSFP). Instead, a more efficient
1495f757f3fSDimitry Andric // memory-renaming optimization can be used.
1505f757f3fSDimitry Andric //
1515f757f3fSDimitry Andric // The PPX hint is purely a performance hint. Instructions with this hint have
1525f757f3fSDimitry Andric // the same functional semantics as those without. PPX hints set by the
1535f757f3fSDimitry Andric // compiler that violate the balancing rule may turn off the PPX optimization,
1545f757f3fSDimitry Andric // but they will not affect program semantics.
1555f757f3fSDimitry Andric //
1565f757f3fSDimitry Andric // Hence, PPX is used for balanced spill/reloads (Exceptions and setjmp/longjmp
1575f757f3fSDimitry Andric // are not considered).
1585f757f3fSDimitry Andric //
1595f757f3fSDimitry Andric // PUSH2 and POP2 are instructions for (respectively) pushing/popping 2
1605f757f3fSDimitry Andric // GPRs at a time to/from the stack.
1615f757f3fSDimitry Andric static unsigned getPUSHOpcode(const X86Subtarget &ST) {
1625f757f3fSDimitry Andric   return ST.is64Bit() ? (ST.hasPPX() ? X86::PUSHP64r : X86::PUSH64r)
1635f757f3fSDimitry Andric                       : X86::PUSH32r;
1645f757f3fSDimitry Andric }
1655f757f3fSDimitry Andric static unsigned getPOPOpcode(const X86Subtarget &ST) {
1665f757f3fSDimitry Andric   return ST.is64Bit() ? (ST.hasPPX() ? X86::POPP64r : X86::POP64r)
1675f757f3fSDimitry Andric                       : X86::POP32r;
1685f757f3fSDimitry Andric }
1695f757f3fSDimitry Andric static unsigned getPUSH2Opcode(const X86Subtarget &ST) {
1705f757f3fSDimitry Andric   return ST.hasPPX() ? X86::PUSH2P : X86::PUSH2;
1715f757f3fSDimitry Andric }
1725f757f3fSDimitry Andric static unsigned getPOP2Opcode(const X86Subtarget &ST) {
1735f757f3fSDimitry Andric   return ST.hasPPX() ? X86::POP2P : X86::POP2;
1745f757f3fSDimitry Andric }
1755f757f3fSDimitry Andric 
1760b57cec5SDimitry Andric static bool isEAXLiveIn(MachineBasicBlock &MBB) {
1770b57cec5SDimitry Andric   for (MachineBasicBlock::RegisterMaskPair RegMask : MBB.liveins()) {
1780b57cec5SDimitry Andric     unsigned Reg = RegMask.PhysReg;
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric     if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
1810b57cec5SDimitry Andric         Reg == X86::AH || Reg == X86::AL)
1820b57cec5SDimitry Andric       return true;
1830b57cec5SDimitry Andric   }
1840b57cec5SDimitry Andric 
1850b57cec5SDimitry Andric   return false;
1860b57cec5SDimitry Andric }
1870b57cec5SDimitry Andric 
1880b57cec5SDimitry Andric /// Check if the flags need to be preserved before the terminators.
1890b57cec5SDimitry Andric /// This would be the case, if the eflags is live-in of the region
1900b57cec5SDimitry Andric /// composed by the terminators or live-out of that region, without
1910b57cec5SDimitry Andric /// being defined by a terminator.
1920b57cec5SDimitry Andric static bool
1930b57cec5SDimitry Andric flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) {
1940b57cec5SDimitry Andric   for (const MachineInstr &MI : MBB.terminators()) {
1950b57cec5SDimitry Andric     bool BreakNext = false;
1960b57cec5SDimitry Andric     for (const MachineOperand &MO : MI.operands()) {
1970b57cec5SDimitry Andric       if (!MO.isReg())
1980b57cec5SDimitry Andric         continue;
1998bcb0991SDimitry Andric       Register Reg = MO.getReg();
2000b57cec5SDimitry Andric       if (Reg != X86::EFLAGS)
2010b57cec5SDimitry Andric         continue;
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric       // This terminator needs an eflags that is not defined
2040b57cec5SDimitry Andric       // by a previous another terminator:
2050b57cec5SDimitry Andric       // EFLAGS is live-in of the region composed by the terminators.
2060b57cec5SDimitry Andric       if (!MO.isDef())
2070b57cec5SDimitry Andric         return true;
2080b57cec5SDimitry Andric       // This terminator defines the eflags, i.e., we don't need to preserve it.
2090b57cec5SDimitry Andric       // However, we still need to check this specific terminator does not
2100b57cec5SDimitry Andric       // read a live-in value.
2110b57cec5SDimitry Andric       BreakNext = true;
2120b57cec5SDimitry Andric     }
2130b57cec5SDimitry Andric     // We found a definition of the eflags, no need to preserve them.
2140b57cec5SDimitry Andric     if (BreakNext)
2150b57cec5SDimitry Andric       return false;
2160b57cec5SDimitry Andric   }
2170b57cec5SDimitry Andric 
2180b57cec5SDimitry Andric   // None of the terminators use or define the eflags.
2190b57cec5SDimitry Andric   // Check if they are live-out, that would imply we need to preserve them.
2200b57cec5SDimitry Andric   for (const MachineBasicBlock *Succ : MBB.successors())
2210b57cec5SDimitry Andric     if (Succ->isLiveIn(X86::EFLAGS))
2220b57cec5SDimitry Andric       return true;
2230b57cec5SDimitry Andric 
2240b57cec5SDimitry Andric   return false;
2250b57cec5SDimitry Andric }
2260b57cec5SDimitry Andric 
2270b57cec5SDimitry Andric /// emitSPUpdate - Emit a series of instructions to increment / decrement the
2280b57cec5SDimitry Andric /// stack pointer by a constant value.
2290b57cec5SDimitry Andric void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
2300b57cec5SDimitry Andric                                     MachineBasicBlock::iterator &MBBI,
2315f757f3fSDimitry Andric                                     const DebugLoc &DL, int64_t NumBytes,
2325f757f3fSDimitry Andric                                     bool InEpilogue) const {
2330b57cec5SDimitry Andric   bool isSub = NumBytes < 0;
2340b57cec5SDimitry Andric   uint64_t Offset = isSub ? -NumBytes : NumBytes;
2350b57cec5SDimitry Andric   MachineInstr::MIFlag Flag =
2360b57cec5SDimitry Andric       isSub ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy;
2370b57cec5SDimitry Andric 
2380b57cec5SDimitry Andric   uint64_t Chunk = (1LL << 31) - 1;
2390b57cec5SDimitry Andric 
2405ffd83dbSDimitry Andric   MachineFunction &MF = *MBB.getParent();
2415ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
2425ffd83dbSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
2435ffd83dbSDimitry Andric   const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
2445ffd83dbSDimitry Andric 
2455ffd83dbSDimitry Andric   // It's ok to not take into account large chunks when probing, as the
2465ffd83dbSDimitry Andric   // allocation is split in smaller chunks anyway.
2475ffd83dbSDimitry Andric   if (EmitInlineStackProbe && !InEpilogue) {
2485ffd83dbSDimitry Andric 
2495ffd83dbSDimitry Andric     // This pseudo-instruction is going to be expanded, potentially using a
2505ffd83dbSDimitry Andric     // loop, by inlineStackProbe().
2515ffd83dbSDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::STACKALLOC_W_PROBING)).addImm(Offset);
2525ffd83dbSDimitry Andric     return;
2535ffd83dbSDimitry Andric   } else if (Offset > Chunk) {
2540b57cec5SDimitry Andric     // Rather than emit a long series of instructions for large offsets,
2550b57cec5SDimitry Andric     // load the offset into a register and do one sub/add
2560b57cec5SDimitry Andric     unsigned Reg = 0;
2570b57cec5SDimitry Andric     unsigned Rax = (unsigned)(Is64Bit ? X86::RAX : X86::EAX);
2580b57cec5SDimitry Andric 
2590b57cec5SDimitry Andric     if (isSub && !isEAXLiveIn(MBB))
2600b57cec5SDimitry Andric       Reg = Rax;
2610b57cec5SDimitry Andric     else
262e8d8bef9SDimitry Andric       Reg = TRI->findDeadCallerSavedReg(MBB, MBBI);
2630b57cec5SDimitry Andric 
2640b57cec5SDimitry Andric     unsigned AddSubRROpc =
2650b57cec5SDimitry Andric         isSub ? getSUBrrOpcode(Is64Bit) : getADDrrOpcode(Is64Bit);
2660b57cec5SDimitry Andric     if (Reg) {
26704eeddc0SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Offset)), Reg)
2680b57cec5SDimitry Andric           .addImm(Offset)
2690b57cec5SDimitry Andric           .setMIFlag(Flag);
2700b57cec5SDimitry Andric       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AddSubRROpc), StackPtr)
2710b57cec5SDimitry Andric                              .addReg(StackPtr)
2720b57cec5SDimitry Andric                              .addReg(Reg);
2730b57cec5SDimitry Andric       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
2740b57cec5SDimitry Andric       return;
2750b57cec5SDimitry Andric     } else if (Offset > 8 * Chunk) {
2760b57cec5SDimitry Andric       // If we would need more than 8 add or sub instructions (a >16GB stack
2770b57cec5SDimitry Andric       // frame), it's worth spilling RAX to materialize this immediate.
2780b57cec5SDimitry Andric       //   pushq %rax
2790b57cec5SDimitry Andric       //   movabsq +-$Offset+-SlotSize, %rax
2800b57cec5SDimitry Andric       //   addq %rsp, %rax
2810b57cec5SDimitry Andric       //   xchg %rax, (%rsp)
2820b57cec5SDimitry Andric       //   movq (%rsp), %rsp
2830b57cec5SDimitry Andric       assert(Is64Bit && "can't have 32-bit 16GB stack frame");
2840b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
2850b57cec5SDimitry Andric           .addReg(Rax, RegState::Kill)
2860b57cec5SDimitry Andric           .setMIFlag(Flag);
2870b57cec5SDimitry Andric       // Subtract is not commutative, so negate the offset and always use add.
2880b57cec5SDimitry Andric       // Subtract 8 less and add 8 more to account for the PUSH we just did.
2890b57cec5SDimitry Andric       if (isSub)
2900b57cec5SDimitry Andric         Offset = -(Offset - SlotSize);
2910b57cec5SDimitry Andric       else
2920b57cec5SDimitry Andric         Offset = Offset + SlotSize;
29304eeddc0SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Offset)), Rax)
2940b57cec5SDimitry Andric           .addImm(Offset)
2950b57cec5SDimitry Andric           .setMIFlag(Flag);
2960b57cec5SDimitry Andric       MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(X86::ADD64rr), Rax)
2970b57cec5SDimitry Andric                              .addReg(Rax)
2980b57cec5SDimitry Andric                              .addReg(StackPtr);
2990b57cec5SDimitry Andric       MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
3000b57cec5SDimitry Andric       // Exchange the new SP in RAX with the top of the stack.
3010b57cec5SDimitry Andric       addRegOffset(
3020b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::XCHG64rm), Rax).addReg(Rax),
3030b57cec5SDimitry Andric           StackPtr, false, 0);
3040b57cec5SDimitry Andric       // Load new SP from the top of the stack into RSP.
3050b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), StackPtr),
3060b57cec5SDimitry Andric                    StackPtr, false, 0);
3070b57cec5SDimitry Andric       return;
3080b57cec5SDimitry Andric     }
3090b57cec5SDimitry Andric   }
3100b57cec5SDimitry Andric 
3110b57cec5SDimitry Andric   while (Offset) {
3120b57cec5SDimitry Andric     uint64_t ThisVal = std::min(Offset, Chunk);
3130b57cec5SDimitry Andric     if (ThisVal == SlotSize) {
3140b57cec5SDimitry Andric       // Use push / pop for slot sized adjustments as a size optimization. We
3150b57cec5SDimitry Andric       // need to find a dead register when using pop.
3165f757f3fSDimitry Andric       unsigned Reg = isSub ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
317e8d8bef9SDimitry Andric                            : TRI->findDeadCallerSavedReg(MBB, MBBI);
3180b57cec5SDimitry Andric       if (Reg) {
3195f757f3fSDimitry Andric         unsigned Opc = isSub ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
3200b57cec5SDimitry Andric                              : (Is64Bit ? X86::POP64r : X86::POP32r);
3210b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(Opc))
3220b57cec5SDimitry Andric             .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub))
3230b57cec5SDimitry Andric             .setMIFlag(Flag);
3240b57cec5SDimitry Andric         Offset -= ThisVal;
3250b57cec5SDimitry Andric         continue;
3260b57cec5SDimitry Andric       }
3270b57cec5SDimitry Andric     }
3280b57cec5SDimitry Andric 
3290b57cec5SDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue)
3300b57cec5SDimitry Andric         .setMIFlag(Flag);
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric     Offset -= ThisVal;
3330b57cec5SDimitry Andric   }
3340b57cec5SDimitry Andric }
3350b57cec5SDimitry Andric 
3360b57cec5SDimitry Andric MachineInstrBuilder X86FrameLowering::BuildStackAdjustment(
3370b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
3380b57cec5SDimitry Andric     const DebugLoc &DL, int64_t Offset, bool InEpilogue) const {
3390b57cec5SDimitry Andric   assert(Offset != 0 && "zero offset stack adjustment requested");
3400b57cec5SDimitry Andric 
3410b57cec5SDimitry Andric   // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue
3420b57cec5SDimitry Andric   // is tricky.
3430b57cec5SDimitry Andric   bool UseLEA;
3440b57cec5SDimitry Andric   if (!InEpilogue) {
3450b57cec5SDimitry Andric     // Check if inserting the prologue at the beginning
3460b57cec5SDimitry Andric     // of MBB would require to use LEA operations.
3470b57cec5SDimitry Andric     // We need to use LEA operations if EFLAGS is live in, because
3480b57cec5SDimitry Andric     // it means an instruction will read it before it gets defined.
3490b57cec5SDimitry Andric     UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS);
3500b57cec5SDimitry Andric   } else {
3510b57cec5SDimitry Andric     // If we can use LEA for SP but we shouldn't, check that none
3520b57cec5SDimitry Andric     // of the terminators uses the eflags. Otherwise we will insert
3530b57cec5SDimitry Andric     // a ADD that will redefine the eflags and break the condition.
3540b57cec5SDimitry Andric     // Alternatively, we could move the ADD, but this may not be possible
3550b57cec5SDimitry Andric     // and is an optimization anyway.
3560b57cec5SDimitry Andric     UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent());
3570b57cec5SDimitry Andric     if (UseLEA && !STI.useLeaForSP())
3580b57cec5SDimitry Andric       UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB);
3590b57cec5SDimitry Andric     // If that assert breaks, that means we do not do the right thing
3600b57cec5SDimitry Andric     // in canUseAsEpilogue.
3610b57cec5SDimitry Andric     assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) &&
3620b57cec5SDimitry Andric            "We shouldn't have allowed this insertion point");
3630b57cec5SDimitry Andric   }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   MachineInstrBuilder MI;
3660b57cec5SDimitry Andric   if (UseLEA) {
3670b57cec5SDimitry Andric     MI = addRegOffset(BuildMI(MBB, MBBI, DL,
3680b57cec5SDimitry Andric                               TII.get(getLEArOpcode(Uses64BitFramePtr)),
3690b57cec5SDimitry Andric                               StackPtr),
3700b57cec5SDimitry Andric                       StackPtr, false, Offset);
3710b57cec5SDimitry Andric   } else {
3720b57cec5SDimitry Andric     bool IsSub = Offset < 0;
3730b57cec5SDimitry Andric     uint64_t AbsOffset = IsSub ? -Offset : Offset;
37406c3fb27SDimitry Andric     const unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr)
37506c3fb27SDimitry Andric                                : getADDriOpcode(Uses64BitFramePtr);
3760b57cec5SDimitry Andric     MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
3770b57cec5SDimitry Andric              .addReg(StackPtr)
3780b57cec5SDimitry Andric              .addImm(AbsOffset);
3790b57cec5SDimitry Andric     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
3800b57cec5SDimitry Andric   }
3810b57cec5SDimitry Andric   return MI;
3820b57cec5SDimitry Andric }
3830b57cec5SDimitry Andric 
3840b57cec5SDimitry Andric int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
3850b57cec5SDimitry Andric                                      MachineBasicBlock::iterator &MBBI,
3860b57cec5SDimitry Andric                                      bool doMergeWithPrevious) const {
3870b57cec5SDimitry Andric   if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
3880b57cec5SDimitry Andric       (!doMergeWithPrevious && MBBI == MBB.end()))
3890b57cec5SDimitry Andric     return 0;
3900b57cec5SDimitry Andric 
3910b57cec5SDimitry Andric   MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   PI = skipDebugInstructionsBackward(PI, MBB.begin());
3940b57cec5SDimitry Andric   // It is assumed that ADD/SUB/LEA instruction is succeded by one CFI
3950b57cec5SDimitry Andric   // instruction, and that there are no DBG_VALUE or other instructions between
3960b57cec5SDimitry Andric   // ADD/SUB/LEA and its corresponding CFI instruction.
3970b57cec5SDimitry Andric   /* TODO: Add support for the case where there are multiple CFI instructions
3980b57cec5SDimitry Andric     below the ADD/SUB/LEA, e.g.:
3990b57cec5SDimitry Andric     ...
4000b57cec5SDimitry Andric     add
4010b57cec5SDimitry Andric     cfi_def_cfa_offset
4020b57cec5SDimitry Andric     cfi_offset
4030b57cec5SDimitry Andric     ...
4040b57cec5SDimitry Andric   */
4050b57cec5SDimitry Andric   if (doMergeWithPrevious && PI != MBB.begin() && PI->isCFIInstruction())
4060b57cec5SDimitry Andric     PI = std::prev(PI);
4070b57cec5SDimitry Andric 
4080b57cec5SDimitry Andric   unsigned Opc = PI->getOpcode();
4090b57cec5SDimitry Andric   int Offset = 0;
4100b57cec5SDimitry Andric 
41106c3fb27SDimitry Andric   if ((Opc == X86::ADD64ri32 || Opc == X86::ADD32ri) &&
4120b57cec5SDimitry Andric       PI->getOperand(0).getReg() == StackPtr) {
4130b57cec5SDimitry Andric     assert(PI->getOperand(1).getReg() == StackPtr);
4140b57cec5SDimitry Andric     Offset = PI->getOperand(2).getImm();
4150b57cec5SDimitry Andric   } else if ((Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
4160b57cec5SDimitry Andric              PI->getOperand(0).getReg() == StackPtr &&
4170b57cec5SDimitry Andric              PI->getOperand(1).getReg() == StackPtr &&
4180b57cec5SDimitry Andric              PI->getOperand(2).getImm() == 1 &&
4190b57cec5SDimitry Andric              PI->getOperand(3).getReg() == X86::NoRegister &&
4200b57cec5SDimitry Andric              PI->getOperand(5).getReg() == X86::NoRegister) {
4210b57cec5SDimitry Andric     // For LEAs we have: def = lea SP, FI, noreg, Offset, noreg.
4220b57cec5SDimitry Andric     Offset = PI->getOperand(4).getImm();
42306c3fb27SDimitry Andric   } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB32ri) &&
4240b57cec5SDimitry Andric              PI->getOperand(0).getReg() == StackPtr) {
4250b57cec5SDimitry Andric     assert(PI->getOperand(1).getReg() == StackPtr);
4260b57cec5SDimitry Andric     Offset = -PI->getOperand(2).getImm();
4270b57cec5SDimitry Andric   } else
4280b57cec5SDimitry Andric     return 0;
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   PI = MBB.erase(PI);
431fe6060f1SDimitry Andric   if (PI != MBB.end() && PI->isCFIInstruction()) {
432fe6060f1SDimitry Andric     auto CIs = MBB.getParent()->getFrameInstructions();
433fe6060f1SDimitry Andric     MCCFIInstruction CI = CIs[PI->getOperand(0).getCFIIndex()];
434fe6060f1SDimitry Andric     if (CI.getOperation() == MCCFIInstruction::OpDefCfaOffset ||
435fe6060f1SDimitry Andric         CI.getOperation() == MCCFIInstruction::OpAdjustCfaOffset)
436fe6060f1SDimitry Andric       PI = MBB.erase(PI);
437fe6060f1SDimitry Andric   }
4380b57cec5SDimitry Andric   if (!doMergeWithPrevious)
4390b57cec5SDimitry Andric     MBBI = skipDebugInstructionsForward(PI, MBB.end());
4400b57cec5SDimitry Andric 
4410b57cec5SDimitry Andric   return Offset;
4420b57cec5SDimitry Andric }
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB,
4450b57cec5SDimitry Andric                                 MachineBasicBlock::iterator MBBI,
4460b57cec5SDimitry Andric                                 const DebugLoc &DL,
44781ad6265SDimitry Andric                                 const MCCFIInstruction &CFIInst,
44881ad6265SDimitry Andric                                 MachineInstr::MIFlag Flag) const {
4490b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
4500b57cec5SDimitry Andric   unsigned CFIIndex = MF.addFrameInst(CFIInst);
45106c3fb27SDimitry Andric 
45206c3fb27SDimitry Andric   if (CFIInst.getOperation() == MCCFIInstruction::OpAdjustCfaOffset)
45306c3fb27SDimitry Andric     MF.getInfo<X86MachineFunctionInfo>()->setHasCFIAdjustCfa(true);
45406c3fb27SDimitry Andric 
4550b57cec5SDimitry Andric   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
45681ad6265SDimitry Andric       .addCFIIndex(CFIIndex)
45781ad6265SDimitry Andric       .setMIFlag(Flag);
4580b57cec5SDimitry Andric }
4590b57cec5SDimitry Andric 
4605ffd83dbSDimitry Andric /// Emits Dwarf Info specifying offsets of callee saved registers and
4615ffd83dbSDimitry Andric /// frame pointer. This is called only when basic block sections are enabled.
46204eeddc0SDimitry Andric void X86FrameLowering::emitCalleeSavedFrameMovesFullCFA(
4635ffd83dbSDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
4645ffd83dbSDimitry Andric   MachineFunction &MF = *MBB.getParent();
4655ffd83dbSDimitry Andric   if (!hasFP(MF)) {
4665ffd83dbSDimitry Andric     emitCalleeSavedFrameMoves(MBB, MBBI, DebugLoc{}, true);
4675ffd83dbSDimitry Andric     return;
4685ffd83dbSDimitry Andric   }
4690fca6ea1SDimitry Andric   const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
470e8d8bef9SDimitry Andric   const Register FramePtr = TRI->getFrameRegister(MF);
471e8d8bef9SDimitry Andric   const Register MachineFramePtr =
472e8d8bef9SDimitry Andric       STI.isTarget64BitILP32() ? Register(getX86SubSuperRegister(FramePtr, 64))
4735ffd83dbSDimitry Andric                                : FramePtr;
4745ffd83dbSDimitry Andric   unsigned DwarfReg = MRI->getDwarfRegNum(MachineFramePtr, true);
4755ffd83dbSDimitry Andric   // Offset = space for return address + size of the frame pointer itself.
476*36b606aeSDimitry Andric   int64_t Offset = (Is64Bit ? 8 : 4) + (Uses64BitFramePtr ? 8 : 4);
4775ffd83dbSDimitry Andric   BuildCFI(MBB, MBBI, DebugLoc{},
4785ffd83dbSDimitry Andric            MCCFIInstruction::createOffset(nullptr, DwarfReg, -Offset));
4795ffd83dbSDimitry Andric   emitCalleeSavedFrameMoves(MBB, MBBI, DebugLoc{}, true);
4805ffd83dbSDimitry Andric }
4815ffd83dbSDimitry Andric 
4820b57cec5SDimitry Andric void X86FrameLowering::emitCalleeSavedFrameMoves(
4830b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
4845ffd83dbSDimitry Andric     const DebugLoc &DL, bool IsPrologue) const {
4850b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
4860b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
4870fca6ea1SDimitry Andric   const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
48806c3fb27SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric   // Add callee saved registers to move list.
4910b57cec5SDimitry Andric   const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
4920b57cec5SDimitry Andric 
4930b57cec5SDimitry Andric   // Calculate offsets.
4944824e7fdSDimitry Andric   for (const CalleeSavedInfo &I : CSI) {
4954824e7fdSDimitry Andric     int64_t Offset = MFI.getObjectOffset(I.getFrameIdx());
49604eeddc0SDimitry Andric     Register Reg = I.getReg();
4970b57cec5SDimitry Andric     unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
4985ffd83dbSDimitry Andric 
4995ffd83dbSDimitry Andric     if (IsPrologue) {
50006c3fb27SDimitry Andric       if (X86FI->getStackPtrSaveMI()) {
50106c3fb27SDimitry Andric         // +2*SlotSize because there is return address and ebp at the bottom
50206c3fb27SDimitry Andric         // of the stack.
50306c3fb27SDimitry Andric         // | retaddr |
50406c3fb27SDimitry Andric         // | ebp     |
50506c3fb27SDimitry Andric         // |         |<--ebp
50606c3fb27SDimitry Andric         Offset += 2 * SlotSize;
50706c3fb27SDimitry Andric         SmallString<64> CfaExpr;
50806c3fb27SDimitry Andric         CfaExpr.push_back(dwarf::DW_CFA_expression);
50906c3fb27SDimitry Andric         uint8_t buffer[16];
51006c3fb27SDimitry Andric         CfaExpr.append(buffer, buffer + encodeULEB128(DwarfReg, buffer));
51106c3fb27SDimitry Andric         CfaExpr.push_back(2);
51206c3fb27SDimitry Andric         Register FramePtr = TRI->getFrameRegister(MF);
51306c3fb27SDimitry Andric         const Register MachineFramePtr =
51406c3fb27SDimitry Andric             STI.isTarget64BitILP32()
51506c3fb27SDimitry Andric                 ? Register(getX86SubSuperRegister(FramePtr, 64))
51606c3fb27SDimitry Andric                 : FramePtr;
51706c3fb27SDimitry Andric         unsigned DwarfFramePtr = MRI->getDwarfRegNum(MachineFramePtr, true);
51806c3fb27SDimitry Andric         CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfFramePtr));
51906c3fb27SDimitry Andric         CfaExpr.append(buffer, buffer + encodeSLEB128(Offset, buffer));
52006c3fb27SDimitry Andric         BuildCFI(MBB, MBBI, DL,
52106c3fb27SDimitry Andric                  MCCFIInstruction::createEscape(nullptr, CfaExpr.str()),
52206c3fb27SDimitry Andric                  MachineInstr::FrameSetup);
52306c3fb27SDimitry Andric       } else {
5240b57cec5SDimitry Andric         BuildCFI(MBB, MBBI, DL,
5250b57cec5SDimitry Andric                  MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
52606c3fb27SDimitry Andric       }
5275ffd83dbSDimitry Andric     } else {
5285ffd83dbSDimitry Andric       BuildCFI(MBB, MBBI, DL,
5295ffd83dbSDimitry Andric                MCCFIInstruction::createRestore(nullptr, DwarfReg));
5305ffd83dbSDimitry Andric     }
5310b57cec5SDimitry Andric   }
53206c3fb27SDimitry Andric   if (auto *MI = X86FI->getStackPtrSaveMI()) {
53306c3fb27SDimitry Andric     int FI = MI->getOperand(1).getIndex();
53406c3fb27SDimitry Andric     int64_t Offset = MFI.getObjectOffset(FI) + 2 * SlotSize;
53506c3fb27SDimitry Andric     SmallString<64> CfaExpr;
53606c3fb27SDimitry Andric     Register FramePtr = TRI->getFrameRegister(MF);
53706c3fb27SDimitry Andric     const Register MachineFramePtr =
53806c3fb27SDimitry Andric         STI.isTarget64BitILP32()
53906c3fb27SDimitry Andric             ? Register(getX86SubSuperRegister(FramePtr, 64))
54006c3fb27SDimitry Andric             : FramePtr;
54106c3fb27SDimitry Andric     unsigned DwarfFramePtr = MRI->getDwarfRegNum(MachineFramePtr, true);
54206c3fb27SDimitry Andric     CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfFramePtr));
54306c3fb27SDimitry Andric     uint8_t buffer[16];
54406c3fb27SDimitry Andric     CfaExpr.append(buffer, buffer + encodeSLEB128(Offset, buffer));
54506c3fb27SDimitry Andric     CfaExpr.push_back(dwarf::DW_OP_deref);
54606c3fb27SDimitry Andric 
54706c3fb27SDimitry Andric     SmallString<64> DefCfaExpr;
54806c3fb27SDimitry Andric     DefCfaExpr.push_back(dwarf::DW_CFA_def_cfa_expression);
54906c3fb27SDimitry Andric     DefCfaExpr.append(buffer, buffer + encodeSLEB128(CfaExpr.size(), buffer));
55006c3fb27SDimitry Andric     DefCfaExpr.append(CfaExpr.str());
55106c3fb27SDimitry Andric     // DW_CFA_def_cfa_expression: DW_OP_breg5 offset, DW_OP_deref
55206c3fb27SDimitry Andric     BuildCFI(MBB, MBBI, DL,
55306c3fb27SDimitry Andric              MCCFIInstruction::createEscape(nullptr, DefCfaExpr.str()),
55406c3fb27SDimitry Andric              MachineInstr::FrameSetup);
55506c3fb27SDimitry Andric   }
5560b57cec5SDimitry Andric }
5570b57cec5SDimitry Andric 
55881ad6265SDimitry Andric void X86FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
55981ad6265SDimitry Andric                                             MachineBasicBlock &MBB) const {
56081ad6265SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
56181ad6265SDimitry Andric 
56281ad6265SDimitry Andric   // Insertion point.
56381ad6265SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
56481ad6265SDimitry Andric 
56581ad6265SDimitry Andric   // Fake a debug loc.
56681ad6265SDimitry Andric   DebugLoc DL;
56781ad6265SDimitry Andric   if (MBBI != MBB.end())
56881ad6265SDimitry Andric     DL = MBBI->getDebugLoc();
56981ad6265SDimitry Andric 
57081ad6265SDimitry Andric   // Zero out FP stack if referenced. Do this outside of the loop below so that
57181ad6265SDimitry Andric   // it's done only once.
57281ad6265SDimitry Andric   const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
57381ad6265SDimitry Andric   for (MCRegister Reg : RegsToZero.set_bits()) {
57481ad6265SDimitry Andric     if (!X86::RFP80RegClass.contains(Reg))
57581ad6265SDimitry Andric       continue;
57681ad6265SDimitry Andric 
57781ad6265SDimitry Andric     unsigned NumFPRegs = ST.is64Bit() ? 8 : 7;
57881ad6265SDimitry Andric     for (unsigned i = 0; i != NumFPRegs; ++i)
57981ad6265SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::LD_F0));
58081ad6265SDimitry Andric 
58181ad6265SDimitry Andric     for (unsigned i = 0; i != NumFPRegs; ++i)
58281ad6265SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::ST_FPrr)).addReg(X86::ST0);
58381ad6265SDimitry Andric     break;
58481ad6265SDimitry Andric   }
58581ad6265SDimitry Andric 
58681ad6265SDimitry Andric   // For GPRs, we only care to clear out the 32-bit register.
58781ad6265SDimitry Andric   BitVector GPRsToZero(TRI->getNumRegs());
58881ad6265SDimitry Andric   for (MCRegister Reg : RegsToZero.set_bits())
58981ad6265SDimitry Andric     if (TRI->isGeneralPurposeRegister(MF, Reg)) {
59006c3fb27SDimitry Andric       GPRsToZero.set(getX86SubSuperRegister(Reg, 32));
59181ad6265SDimitry Andric       RegsToZero.reset(Reg);
59281ad6265SDimitry Andric     }
59381ad6265SDimitry Andric 
5945f757f3fSDimitry Andric   // Zero out the GPRs first.
59581ad6265SDimitry Andric   for (MCRegister Reg : GPRsToZero.set_bits())
5965f757f3fSDimitry Andric     TII.buildClearRegister(Reg, MBB, MBBI, DL);
59781ad6265SDimitry Andric 
5985f757f3fSDimitry Andric   // Zero out the remaining registers.
5995f757f3fSDimitry Andric   for (MCRegister Reg : RegsToZero.set_bits())
6005f757f3fSDimitry Andric     TII.buildClearRegister(Reg, MBB, MBBI, DL);
60181ad6265SDimitry Andric }
60281ad6265SDimitry Andric 
6034824e7fdSDimitry Andric void X86FrameLowering::emitStackProbe(
6044824e7fdSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
6054824e7fdSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
606bdd1243dSDimitry Andric     std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
6070b57cec5SDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
6080b57cec5SDimitry Andric   if (STI.isTargetWindowsCoreCLR()) {
6090b57cec5SDimitry Andric     if (InProlog) {
6105ffd83dbSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::STACKALLOC_W_PROBING))
6115ffd83dbSDimitry Andric           .addImm(0 /* no explicit stack size */);
6120b57cec5SDimitry Andric     } else {
6130b57cec5SDimitry Andric       emitStackProbeInline(MF, MBB, MBBI, DL, false);
6140b57cec5SDimitry Andric     }
6150b57cec5SDimitry Andric   } else {
6164824e7fdSDimitry Andric     emitStackProbeCall(MF, MBB, MBBI, DL, InProlog, InstrNum);
6170b57cec5SDimitry Andric   }
6180b57cec5SDimitry Andric }
6190b57cec5SDimitry Andric 
6204824e7fdSDimitry Andric bool X86FrameLowering::stackProbeFunctionModifiesSP() const {
6214824e7fdSDimitry Andric   return STI.isOSWindows() && !STI.isTargetWin64();
6224824e7fdSDimitry Andric }
6234824e7fdSDimitry Andric 
6240b57cec5SDimitry Andric void X86FrameLowering::inlineStackProbe(MachineFunction &MF,
6250b57cec5SDimitry Andric                                         MachineBasicBlock &PrologMBB) const {
6265ffd83dbSDimitry Andric   auto Where = llvm::find_if(PrologMBB, [](MachineInstr &MI) {
6275ffd83dbSDimitry Andric     return MI.getOpcode() == X86::STACKALLOC_W_PROBING;
6285ffd83dbSDimitry Andric   });
6295ffd83dbSDimitry Andric   if (Where != PrologMBB.end()) {
6305ffd83dbSDimitry Andric     DebugLoc DL = PrologMBB.findDebugLoc(Where);
6315ffd83dbSDimitry Andric     emitStackProbeInline(MF, PrologMBB, Where, DL, true);
6325ffd83dbSDimitry Andric     Where->eraseFromParent();
6330b57cec5SDimitry Andric   }
6340b57cec5SDimitry Andric }
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric void X86FrameLowering::emitStackProbeInline(MachineFunction &MF,
6370b57cec5SDimitry Andric                                             MachineBasicBlock &MBB,
6380b57cec5SDimitry Andric                                             MachineBasicBlock::iterator MBBI,
6390b57cec5SDimitry Andric                                             const DebugLoc &DL,
6400b57cec5SDimitry Andric                                             bool InProlog) const {
6410b57cec5SDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
6425ffd83dbSDimitry Andric   if (STI.isTargetWindowsCoreCLR() && STI.is64Bit())
6435ffd83dbSDimitry Andric     emitStackProbeInlineWindowsCoreCLR64(MF, MBB, MBBI, DL, InProlog);
6445ffd83dbSDimitry Andric   else
6455ffd83dbSDimitry Andric     emitStackProbeInlineGeneric(MF, MBB, MBBI, DL, InProlog);
6465ffd83dbSDimitry Andric }
6475ffd83dbSDimitry Andric 
6485ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineGeneric(
6495ffd83dbSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
6505ffd83dbSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
6515ffd83dbSDimitry Andric   MachineInstr &AllocWithProbe = *MBBI;
6525ffd83dbSDimitry Andric   uint64_t Offset = AllocWithProbe.getOperand(0).getImm();
6535ffd83dbSDimitry Andric 
6545ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
6555ffd83dbSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
6565ffd83dbSDimitry Andric   assert(!(STI.is64Bit() && STI.isTargetWindowsCoreCLR()) &&
6575ffd83dbSDimitry Andric          "different expansion expected for CoreCLR 64 bit");
6585ffd83dbSDimitry Andric 
6595ffd83dbSDimitry Andric   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
6605ffd83dbSDimitry Andric   uint64_t ProbeChunk = StackProbeSize * 8;
6615ffd83dbSDimitry Andric 
662eaeb601bSDimitry Andric   uint64_t MaxAlign =
663fe6060f1SDimitry Andric       TRI->hasStackRealignment(MF) ? calculateMaxStackAlign(MF) : 0;
664eaeb601bSDimitry Andric 
6655ffd83dbSDimitry Andric   // Synthesize a loop or unroll it, depending on the number of iterations.
666eaeb601bSDimitry Andric   // BuildStackAlignAND ensures that only MaxAlign % StackProbeSize bits left
667eaeb601bSDimitry Andric   // between the unaligned rsp and current rsp.
6685ffd83dbSDimitry Andric   if (Offset > ProbeChunk) {
669eaeb601bSDimitry Andric     emitStackProbeInlineGenericLoop(MF, MBB, MBBI, DL, Offset,
670eaeb601bSDimitry Andric                                     MaxAlign % StackProbeSize);
6715ffd83dbSDimitry Andric   } else {
672eaeb601bSDimitry Andric     emitStackProbeInlineGenericBlock(MF, MBB, MBBI, DL, Offset,
673eaeb601bSDimitry Andric                                      MaxAlign % StackProbeSize);
6745ffd83dbSDimitry Andric   }
6755ffd83dbSDimitry Andric }
6765ffd83dbSDimitry Andric 
6775ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineGenericBlock(
6785ffd83dbSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
679eaeb601bSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, uint64_t Offset,
680eaeb601bSDimitry Andric     uint64_t AlignOffset) const {
6815ffd83dbSDimitry Andric 
682fe6060f1SDimitry Andric   const bool NeedsDwarfCFI = needsDwarfCFI(MF);
683fe6060f1SDimitry Andric   const bool HasFP = hasFP(MF);
6845ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
6855ffd83dbSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
6865ffd83dbSDimitry Andric   const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
6875ffd83dbSDimitry Andric   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
6885ffd83dbSDimitry Andric 
689eaeb601bSDimitry Andric   uint64_t CurrentOffset = 0;
690eaeb601bSDimitry Andric 
691eaeb601bSDimitry Andric   assert(AlignOffset < StackProbeSize);
692eaeb601bSDimitry Andric 
693eaeb601bSDimitry Andric   // If the offset is so small it fits within a page, there's nothing to do.
694eaeb601bSDimitry Andric   if (StackProbeSize < Offset + AlignOffset) {
695eaeb601bSDimitry Andric 
696bdd1243dSDimitry Andric     uint64_t StackAdjustment = StackProbeSize - AlignOffset;
697bdd1243dSDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, -StackAdjustment, /*InEpilogue=*/false)
698eaeb601bSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
699fe6060f1SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
700bdd1243dSDimitry Andric       BuildCFI(
701bdd1243dSDimitry Andric           MBB, MBBI, DL,
702bdd1243dSDimitry Andric           MCCFIInstruction::createAdjustCfaOffset(nullptr, StackAdjustment));
703fe6060f1SDimitry Andric     }
704eaeb601bSDimitry Andric 
705eaeb601bSDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
706eaeb601bSDimitry Andric                      .setMIFlag(MachineInstr::FrameSetup),
707eaeb601bSDimitry Andric                  StackPtr, false, 0)
708eaeb601bSDimitry Andric         .addImm(0)
709eaeb601bSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
710eaeb601bSDimitry Andric     NumFrameExtraProbe++;
711eaeb601bSDimitry Andric     CurrentOffset = StackProbeSize - AlignOffset;
712eaeb601bSDimitry Andric   }
713eaeb601bSDimitry Andric 
714eaeb601bSDimitry Andric   // For the next N - 1 pages, just probe. I tried to take advantage of
7155ffd83dbSDimitry Andric   // natural probes but it implies much more logic and there was very few
7165ffd83dbSDimitry Andric   // interesting natural probes to interleave.
7175ffd83dbSDimitry Andric   while (CurrentOffset + StackProbeSize < Offset) {
718bdd1243dSDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, -StackProbeSize, /*InEpilogue=*/false)
7195ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
7205ffd83dbSDimitry Andric 
721fe6060f1SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
722fe6060f1SDimitry Andric       BuildCFI(
723fe6060f1SDimitry Andric           MBB, MBBI, DL,
724fe6060f1SDimitry Andric           MCCFIInstruction::createAdjustCfaOffset(nullptr, StackProbeSize));
725fe6060f1SDimitry Andric     }
7265ffd83dbSDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
7275ffd83dbSDimitry Andric                      .setMIFlag(MachineInstr::FrameSetup),
7285ffd83dbSDimitry Andric                  StackPtr, false, 0)
7295ffd83dbSDimitry Andric         .addImm(0)
7305ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
7315ffd83dbSDimitry Andric     NumFrameExtraProbe++;
7325ffd83dbSDimitry Andric     CurrentOffset += StackProbeSize;
7335ffd83dbSDimitry Andric   }
7345ffd83dbSDimitry Andric 
735eaeb601bSDimitry Andric   // No need to probe the tail, it is smaller than a Page.
7365ffd83dbSDimitry Andric   uint64_t ChunkSize = Offset - CurrentOffset;
737bdd1243dSDimitry Andric   if (ChunkSize == SlotSize) {
738bdd1243dSDimitry Andric     // Use push for slot sized adjustments as a size optimization,
739bdd1243dSDimitry Andric     // like emitSPUpdate does when not probing.
740bdd1243dSDimitry Andric     unsigned Reg = Is64Bit ? X86::RAX : X86::EAX;
741bdd1243dSDimitry Andric     unsigned Opc = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
742bdd1243dSDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Opc))
743bdd1243dSDimitry Andric         .addReg(Reg, RegState::Undef)
7445ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
745bdd1243dSDimitry Andric   } else {
746bdd1243dSDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, -ChunkSize, /*InEpilogue=*/false)
747bdd1243dSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
748bdd1243dSDimitry Andric   }
749fe6060f1SDimitry Andric   // No need to adjust Dwarf CFA offset here, the last position of the stack has
750fe6060f1SDimitry Andric   // been defined
7515ffd83dbSDimitry Andric }
7525ffd83dbSDimitry Andric 
7535ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineGenericLoop(
7545ffd83dbSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
755eaeb601bSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, uint64_t Offset,
756eaeb601bSDimitry Andric     uint64_t AlignOffset) const {
7575ffd83dbSDimitry Andric   assert(Offset && "null offset");
7585ffd83dbSDimitry Andric 
759bdd1243dSDimitry Andric   assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
760bdd1243dSDimitry Andric              MachineBasicBlock::LQR_Live &&
761bdd1243dSDimitry Andric          "Inline stack probe loop will clobber live EFLAGS.");
762bdd1243dSDimitry Andric 
76304eeddc0SDimitry Andric   const bool NeedsDwarfCFI = needsDwarfCFI(MF);
76404eeddc0SDimitry Andric   const bool HasFP = hasFP(MF);
7655ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
7665ffd83dbSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
7675ffd83dbSDimitry Andric   const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
7685ffd83dbSDimitry Andric   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
7695ffd83dbSDimitry Andric 
770eaeb601bSDimitry Andric   if (AlignOffset) {
771eaeb601bSDimitry Andric     if (AlignOffset < StackProbeSize) {
772eaeb601bSDimitry Andric       // Perform a first smaller allocation followed by a probe.
773bdd1243dSDimitry Andric       BuildStackAdjustment(MBB, MBBI, DL, -AlignOffset, /*InEpilogue=*/false)
774eaeb601bSDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
775eaeb601bSDimitry Andric 
776eaeb601bSDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MovMIOpc))
777eaeb601bSDimitry Andric                        .setMIFlag(MachineInstr::FrameSetup),
778eaeb601bSDimitry Andric                    StackPtr, false, 0)
779eaeb601bSDimitry Andric           .addImm(0)
780eaeb601bSDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
781eaeb601bSDimitry Andric       NumFrameExtraProbe++;
782eaeb601bSDimitry Andric       Offset -= AlignOffset;
783eaeb601bSDimitry Andric     }
784eaeb601bSDimitry Andric   }
785eaeb601bSDimitry Andric 
7865ffd83dbSDimitry Andric   // Synthesize a loop
7875ffd83dbSDimitry Andric   NumFrameLoopProbe++;
7885ffd83dbSDimitry Andric   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
7895ffd83dbSDimitry Andric 
7905ffd83dbSDimitry Andric   MachineBasicBlock *testMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7915ffd83dbSDimitry Andric   MachineBasicBlock *tailMBB = MF.CreateMachineBasicBlock(LLVM_BB);
7925ffd83dbSDimitry Andric 
7935ffd83dbSDimitry Andric   MachineFunction::iterator MBBIter = ++MBB.getIterator();
7945ffd83dbSDimitry Andric   MF.insert(MBBIter, testMBB);
7955ffd83dbSDimitry Andric   MF.insert(MBBIter, tailMBB);
7965ffd83dbSDimitry Andric 
7978c6f6c0cSDimitry Andric   Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
7988c6f6c0cSDimitry Andric                               : Is64Bit         ? X86::R11D
7998c6f6c0cSDimitry Andric                                                 : X86::EAX;
80004eeddc0SDimitry Andric 
8015ffd83dbSDimitry Andric   BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::COPY), FinalStackProbed)
8025ffd83dbSDimitry Andric       .addReg(StackPtr)
8035ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8045ffd83dbSDimitry Andric 
8055ffd83dbSDimitry Andric   // save loop bound
8065ffd83dbSDimitry Andric   {
80704eeddc0SDimitry Andric     const unsigned BoundOffset = alignDown(Offset, StackProbeSize);
80806c3fb27SDimitry Andric     const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr);
809eaeb601bSDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(SUBOpc), FinalStackProbed)
8105ffd83dbSDimitry Andric         .addReg(FinalStackProbed)
81104eeddc0SDimitry Andric         .addImm(BoundOffset)
8125ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
81304eeddc0SDimitry Andric 
81404eeddc0SDimitry Andric     // while in the loop, use loop-invariant reg for CFI,
81504eeddc0SDimitry Andric     // instead of the stack pointer, which changes during the loop
81604eeddc0SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
81704eeddc0SDimitry Andric       // x32 uses the same DWARF register numbers as x86-64,
81804eeddc0SDimitry Andric       // so there isn't a register number for r11d, we must use r11 instead
81904eeddc0SDimitry Andric       const Register DwarfFinalStackProbed =
82004eeddc0SDimitry Andric           STI.isTarget64BitILP32()
82104eeddc0SDimitry Andric               ? Register(getX86SubSuperRegister(FinalStackProbed, 64))
82204eeddc0SDimitry Andric               : FinalStackProbed;
82304eeddc0SDimitry Andric 
82404eeddc0SDimitry Andric       BuildCFI(MBB, MBBI, DL,
82504eeddc0SDimitry Andric                MCCFIInstruction::createDefCfaRegister(
82604eeddc0SDimitry Andric                    nullptr, TRI->getDwarfRegNum(DwarfFinalStackProbed, true)));
82704eeddc0SDimitry Andric       BuildCFI(MBB, MBBI, DL,
82804eeddc0SDimitry Andric                MCCFIInstruction::createAdjustCfaOffset(nullptr, BoundOffset));
82904eeddc0SDimitry Andric     }
8305ffd83dbSDimitry Andric   }
8315ffd83dbSDimitry Andric 
8325ffd83dbSDimitry Andric   // allocate a page
833bdd1243dSDimitry Andric   BuildStackAdjustment(*testMBB, testMBB->end(), DL, -StackProbeSize,
834bdd1243dSDimitry Andric                        /*InEpilogue=*/false)
8355ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8365ffd83dbSDimitry Andric 
8375ffd83dbSDimitry Andric   // touch the page
8385ffd83dbSDimitry Andric   addRegOffset(BuildMI(testMBB, DL, TII.get(MovMIOpc))
8395ffd83dbSDimitry Andric                    .setMIFlag(MachineInstr::FrameSetup),
8405ffd83dbSDimitry Andric                StackPtr, false, 0)
8415ffd83dbSDimitry Andric       .addImm(0)
8425ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8435ffd83dbSDimitry Andric 
8445ffd83dbSDimitry Andric   // cmp with stack pointer bound
8455ffd83dbSDimitry Andric   BuildMI(testMBB, DL, TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
8465ffd83dbSDimitry Andric       .addReg(StackPtr)
8475ffd83dbSDimitry Andric       .addReg(FinalStackProbed)
8485ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8495ffd83dbSDimitry Andric 
8505ffd83dbSDimitry Andric   // jump
8515ffd83dbSDimitry Andric   BuildMI(testMBB, DL, TII.get(X86::JCC_1))
8525ffd83dbSDimitry Andric       .addMBB(testMBB)
8535ffd83dbSDimitry Andric       .addImm(X86::COND_NE)
8545ffd83dbSDimitry Andric       .setMIFlag(MachineInstr::FrameSetup);
8555ffd83dbSDimitry Andric   testMBB->addSuccessor(testMBB);
8565ffd83dbSDimitry Andric   testMBB->addSuccessor(tailMBB);
8575ffd83dbSDimitry Andric 
8585ffd83dbSDimitry Andric   // BB management
8595ffd83dbSDimitry Andric   tailMBB->splice(tailMBB->end(), &MBB, MBBI, MBB.end());
8605ffd83dbSDimitry Andric   tailMBB->transferSuccessorsAndUpdatePHIs(&MBB);
8615ffd83dbSDimitry Andric   MBB.addSuccessor(testMBB);
8625ffd83dbSDimitry Andric 
8635ffd83dbSDimitry Andric   // handle tail
864bdd1243dSDimitry Andric   const uint64_t TailOffset = Offset % StackProbeSize;
86504eeddc0SDimitry Andric   MachineBasicBlock::iterator TailMBBIter = tailMBB->begin();
8665ffd83dbSDimitry Andric   if (TailOffset) {
867bdd1243dSDimitry Andric     BuildStackAdjustment(*tailMBB, TailMBBIter, DL, -TailOffset,
868bdd1243dSDimitry Andric                          /*InEpilogue=*/false)
8695ffd83dbSDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
8705ffd83dbSDimitry Andric   }
8715ffd83dbSDimitry Andric 
87204eeddc0SDimitry Andric   // after the loop, switch back to stack pointer for CFI
87304eeddc0SDimitry Andric   if (!HasFP && NeedsDwarfCFI) {
87404eeddc0SDimitry Andric     // x32 uses the same DWARF register numbers as x86-64,
87504eeddc0SDimitry Andric     // so there isn't a register number for esp, we must use rsp instead
87604eeddc0SDimitry Andric     const Register DwarfStackPtr =
87704eeddc0SDimitry Andric         STI.isTarget64BitILP32()
87804eeddc0SDimitry Andric             ? Register(getX86SubSuperRegister(StackPtr, 64))
87904eeddc0SDimitry Andric             : Register(StackPtr);
88004eeddc0SDimitry Andric 
88104eeddc0SDimitry Andric     BuildCFI(*tailMBB, TailMBBIter, DL,
88204eeddc0SDimitry Andric              MCCFIInstruction::createDefCfaRegister(
88304eeddc0SDimitry Andric                  nullptr, TRI->getDwarfRegNum(DwarfStackPtr, true)));
88404eeddc0SDimitry Andric   }
88504eeddc0SDimitry Andric 
8865ffd83dbSDimitry Andric   // Update Live In information
8870fca6ea1SDimitry Andric   fullyRecomputeLiveIns({tailMBB, testMBB});
8885ffd83dbSDimitry Andric }
8895ffd83dbSDimitry Andric 
8905ffd83dbSDimitry Andric void X86FrameLowering::emitStackProbeInlineWindowsCoreCLR64(
8915ffd83dbSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
8925ffd83dbSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
8935ffd83dbSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
8940b57cec5SDimitry Andric   assert(STI.is64Bit() && "different expansion needed for 32 bit");
8950b57cec5SDimitry Andric   assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
8960b57cec5SDimitry Andric   const TargetInstrInfo &TII = *STI.getInstrInfo();
8970b57cec5SDimitry Andric   const BasicBlock *LLVM_BB = MBB.getBasicBlock();
8980b57cec5SDimitry Andric 
899bdd1243dSDimitry Andric   assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
900bdd1243dSDimitry Andric              MachineBasicBlock::LQR_Live &&
901bdd1243dSDimitry Andric          "Inline stack probe loop will clobber live EFLAGS.");
902bdd1243dSDimitry Andric 
9030b57cec5SDimitry Andric   // RAX contains the number of bytes of desired stack adjustment.
9040b57cec5SDimitry Andric   // The handling here assumes this value has already been updated so as to
9050b57cec5SDimitry Andric   // maintain stack alignment.
9060b57cec5SDimitry Andric   //
9070b57cec5SDimitry Andric   // We need to exit with RSP modified by this amount and execute suitable
9080b57cec5SDimitry Andric   // page touches to notify the OS that we're growing the stack responsibly.
9090b57cec5SDimitry Andric   // All stack probing must be done without modifying RSP.
9100b57cec5SDimitry Andric   //
9110b57cec5SDimitry Andric   // MBB:
9120b57cec5SDimitry Andric   //    SizeReg = RAX;
9130b57cec5SDimitry Andric   //    ZeroReg = 0
9140b57cec5SDimitry Andric   //    CopyReg = RSP
9150b57cec5SDimitry Andric   //    Flags, TestReg = CopyReg - SizeReg
9160b57cec5SDimitry Andric   //    FinalReg = !Flags.Ovf ? TestReg : ZeroReg
9170b57cec5SDimitry Andric   //    LimitReg = gs magic thread env access
9180b57cec5SDimitry Andric   //    if FinalReg >= LimitReg goto ContinueMBB
9190b57cec5SDimitry Andric   // RoundBB:
9200b57cec5SDimitry Andric   //    RoundReg = page address of FinalReg
9210b57cec5SDimitry Andric   // LoopMBB:
9220b57cec5SDimitry Andric   //    LoopReg = PHI(LimitReg,ProbeReg)
9230b57cec5SDimitry Andric   //    ProbeReg = LoopReg - PageSize
9240b57cec5SDimitry Andric   //    [ProbeReg] = 0
9250b57cec5SDimitry Andric   //    if (ProbeReg > RoundReg) goto LoopMBB
9260b57cec5SDimitry Andric   // ContinueMBB:
9270b57cec5SDimitry Andric   //    RSP = RSP - RAX
9280b57cec5SDimitry Andric   //    [rest of original MBB]
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric   // Set up the new basic blocks
9310b57cec5SDimitry Andric   MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9320b57cec5SDimitry Andric   MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9330b57cec5SDimitry Andric   MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB);
9340b57cec5SDimitry Andric 
9350b57cec5SDimitry Andric   MachineFunction::iterator MBBIter = std::next(MBB.getIterator());
9360b57cec5SDimitry Andric   MF.insert(MBBIter, RoundMBB);
9370b57cec5SDimitry Andric   MF.insert(MBBIter, LoopMBB);
9380b57cec5SDimitry Andric   MF.insert(MBBIter, ContinueMBB);
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric   // Split MBB and move the tail portion down to ContinueMBB.
9410b57cec5SDimitry Andric   MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI);
9420b57cec5SDimitry Andric   ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end());
9430b57cec5SDimitry Andric   ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB);
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric   // Some useful constants
9460b57cec5SDimitry Andric   const int64_t ThreadEnvironmentStackLimit = 0x10;
9470b57cec5SDimitry Andric   const int64_t PageSize = 0x1000;
9480b57cec5SDimitry Andric   const int64_t PageMask = ~(PageSize - 1);
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   // Registers we need. For the normal case we use virtual
9510b57cec5SDimitry Andric   // registers. For the prolog expansion we use RAX, RCX and RDX.
9520b57cec5SDimitry Andric   MachineRegisterInfo &MRI = MF.getRegInfo();
9530b57cec5SDimitry Andric   const TargetRegisterClass *RegClass = &X86::GR64RegClass;
9545f757f3fSDimitry Andric   const Register
9555f757f3fSDimitry Andric       SizeReg = InProlog ? X86::RAX : MRI.createVirtualRegister(RegClass),
9565f757f3fSDimitry Andric       ZeroReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass),
9575f757f3fSDimitry Andric       CopyReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
9585f757f3fSDimitry Andric       TestReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
9595f757f3fSDimitry Andric       FinalReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
9605f757f3fSDimitry Andric       RoundedReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
9615f757f3fSDimitry Andric       LimitReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass),
9625f757f3fSDimitry Andric       JoinReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass),
9635f757f3fSDimitry Andric       ProbeReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass);
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric   // SP-relative offsets where we can save RCX and RDX.
9660b57cec5SDimitry Andric   int64_t RCXShadowSlot = 0;
9670b57cec5SDimitry Andric   int64_t RDXShadowSlot = 0;
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric   // If inlining in the prolog, save RCX and RDX.
9700b57cec5SDimitry Andric   if (InProlog) {
9710b57cec5SDimitry Andric     // Compute the offsets. We need to account for things already
9720b57cec5SDimitry Andric     // pushed onto the stack at this point: return address, frame
9730b57cec5SDimitry Andric     // pointer (if used), and callee saves.
9740b57cec5SDimitry Andric     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
9750b57cec5SDimitry Andric     const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
9760b57cec5SDimitry Andric     const bool HasFP = hasFP(MF);
9770b57cec5SDimitry Andric 
9780b57cec5SDimitry Andric     // Check if we need to spill RCX and/or RDX.
9790b57cec5SDimitry Andric     // Here we assume that no earlier prologue instruction changes RCX and/or
9800b57cec5SDimitry Andric     // RDX, so checking the block live-ins is enough.
9810b57cec5SDimitry Andric     const bool IsRCXLiveIn = MBB.isLiveIn(X86::RCX);
9820b57cec5SDimitry Andric     const bool IsRDXLiveIn = MBB.isLiveIn(X86::RDX);
9830b57cec5SDimitry Andric     int64_t InitSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
9840b57cec5SDimitry Andric     // Assign the initial slot to both registers, then change RDX's slot if both
9850b57cec5SDimitry Andric     // need to be spilled.
9860b57cec5SDimitry Andric     if (IsRCXLiveIn)
9870b57cec5SDimitry Andric       RCXShadowSlot = InitSlot;
9880b57cec5SDimitry Andric     if (IsRDXLiveIn)
9890b57cec5SDimitry Andric       RDXShadowSlot = InitSlot;
9900b57cec5SDimitry Andric     if (IsRDXLiveIn && IsRCXLiveIn)
9910b57cec5SDimitry Andric       RDXShadowSlot += 8;
9920b57cec5SDimitry Andric     // Emit the saves if needed.
9930b57cec5SDimitry Andric     if (IsRCXLiveIn)
9940b57cec5SDimitry Andric       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
9950b57cec5SDimitry Andric                    RCXShadowSlot)
9960b57cec5SDimitry Andric           .addReg(X86::RCX);
9970b57cec5SDimitry Andric     if (IsRDXLiveIn)
9980b57cec5SDimitry Andric       addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
9990b57cec5SDimitry Andric                    RDXShadowSlot)
10000b57cec5SDimitry Andric           .addReg(X86::RDX);
10010b57cec5SDimitry Andric   } else {
10020b57cec5SDimitry Andric     // Not in the prolog. Copy RAX to a virtual reg.
10030b57cec5SDimitry Andric     BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX);
10040b57cec5SDimitry Andric   }
10050b57cec5SDimitry Andric 
10060b57cec5SDimitry Andric   // Add code to MBB to check for overflow and set the new target stack pointer
10070b57cec5SDimitry Andric   // to zero if so.
10080b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg)
10090b57cec5SDimitry Andric       .addReg(ZeroReg, RegState::Undef)
10100b57cec5SDimitry Andric       .addReg(ZeroReg, RegState::Undef);
10110b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP);
10120b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg)
10130b57cec5SDimitry Andric       .addReg(CopyReg)
10140b57cec5SDimitry Andric       .addReg(SizeReg);
10150b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::CMOV64rr), FinalReg)
10160b57cec5SDimitry Andric       .addReg(TestReg)
10170b57cec5SDimitry Andric       .addReg(ZeroReg)
10180b57cec5SDimitry Andric       .addImm(X86::COND_B);
10190b57cec5SDimitry Andric 
10200b57cec5SDimitry Andric   // FinalReg now holds final stack pointer value, or zero if
10210b57cec5SDimitry Andric   // allocation would overflow. Compare against the current stack
10220b57cec5SDimitry Andric   // limit from the thread environment block. Note this limit is the
10230b57cec5SDimitry Andric   // lowest touched page on the stack, not the point at which the OS
10240b57cec5SDimitry Andric   // will cause an overflow exception, so this is just an optimization
10250b57cec5SDimitry Andric   // to avoid unnecessarily touching pages that are below the current
10260b57cec5SDimitry Andric   // SP but already committed to the stack by the OS.
10270b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg)
10280b57cec5SDimitry Andric       .addReg(0)
10290b57cec5SDimitry Andric       .addImm(1)
10300b57cec5SDimitry Andric       .addReg(0)
10310b57cec5SDimitry Andric       .addImm(ThreadEnvironmentStackLimit)
10320b57cec5SDimitry Andric       .addReg(X86::GS);
10330b57cec5SDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg);
10340b57cec5SDimitry Andric   // Jump if the desired stack pointer is at or above the stack limit.
10355f757f3fSDimitry Andric   BuildMI(&MBB, DL, TII.get(X86::JCC_1))
10365f757f3fSDimitry Andric       .addMBB(ContinueMBB)
10375f757f3fSDimitry Andric       .addImm(X86::COND_AE);
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric   // Add code to roundMBB to round the final stack pointer to a page boundary.
10400b57cec5SDimitry Andric   RoundMBB->addLiveIn(FinalReg);
10410b57cec5SDimitry Andric   BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg)
10420b57cec5SDimitry Andric       .addReg(FinalReg)
10430b57cec5SDimitry Andric       .addImm(PageMask);
10440b57cec5SDimitry Andric   BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB);
10450b57cec5SDimitry Andric 
10460b57cec5SDimitry Andric   // LimitReg now holds the current stack limit, RoundedReg page-rounded
10470b57cec5SDimitry Andric   // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
10480b57cec5SDimitry Andric   // and probe until we reach RoundedReg.
10490b57cec5SDimitry Andric   if (!InProlog) {
10500b57cec5SDimitry Andric     BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg)
10510b57cec5SDimitry Andric         .addReg(LimitReg)
10520b57cec5SDimitry Andric         .addMBB(RoundMBB)
10530b57cec5SDimitry Andric         .addReg(ProbeReg)
10540b57cec5SDimitry Andric         .addMBB(LoopMBB);
10550b57cec5SDimitry Andric   }
10560b57cec5SDimitry Andric 
10570b57cec5SDimitry Andric   LoopMBB->addLiveIn(JoinReg);
10580b57cec5SDimitry Andric   addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg,
10590b57cec5SDimitry Andric                false, -PageSize);
10600b57cec5SDimitry Andric 
10610b57cec5SDimitry Andric   // Probe by storing a byte onto the stack.
10620b57cec5SDimitry Andric   BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi))
10630b57cec5SDimitry Andric       .addReg(ProbeReg)
10640b57cec5SDimitry Andric       .addImm(1)
10650b57cec5SDimitry Andric       .addReg(0)
10660b57cec5SDimitry Andric       .addImm(0)
10670b57cec5SDimitry Andric       .addReg(0)
10680b57cec5SDimitry Andric       .addImm(0);
10690b57cec5SDimitry Andric 
10700b57cec5SDimitry Andric   LoopMBB->addLiveIn(RoundedReg);
10710b57cec5SDimitry Andric   BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr))
10720b57cec5SDimitry Andric       .addReg(RoundedReg)
10730b57cec5SDimitry Andric       .addReg(ProbeReg);
10745f757f3fSDimitry Andric   BuildMI(LoopMBB, DL, TII.get(X86::JCC_1))
10755f757f3fSDimitry Andric       .addMBB(LoopMBB)
10765f757f3fSDimitry Andric       .addImm(X86::COND_NE);
10770b57cec5SDimitry Andric 
10780b57cec5SDimitry Andric   MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric   // If in prolog, restore RDX and RCX.
10810b57cec5SDimitry Andric   if (InProlog) {
10820b57cec5SDimitry Andric     if (RCXShadowSlot) // It means we spilled RCX in the prologue.
10830b57cec5SDimitry Andric       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
10840b57cec5SDimitry Andric                            TII.get(X86::MOV64rm), X86::RCX),
10850b57cec5SDimitry Andric                    X86::RSP, false, RCXShadowSlot);
10860b57cec5SDimitry Andric     if (RDXShadowSlot) // It means we spilled RDX in the prologue.
10870b57cec5SDimitry Andric       addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL,
10880b57cec5SDimitry Andric                            TII.get(X86::MOV64rm), X86::RDX),
10890b57cec5SDimitry Andric                    X86::RSP, false, RDXShadowSlot);
10900b57cec5SDimitry Andric   }
10910b57cec5SDimitry Andric 
10920b57cec5SDimitry Andric   // Now that the probing is done, add code to continueMBB to update
10930b57cec5SDimitry Andric   // the stack pointer for real.
10940b57cec5SDimitry Andric   ContinueMBB->addLiveIn(SizeReg);
10950b57cec5SDimitry Andric   BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
10960b57cec5SDimitry Andric       .addReg(X86::RSP)
10970b57cec5SDimitry Andric       .addReg(SizeReg);
10980b57cec5SDimitry Andric 
10990b57cec5SDimitry Andric   // Add the control flow edges we need.
11000b57cec5SDimitry Andric   MBB.addSuccessor(ContinueMBB);
11010b57cec5SDimitry Andric   MBB.addSuccessor(RoundMBB);
11020b57cec5SDimitry Andric   RoundMBB->addSuccessor(LoopMBB);
11030b57cec5SDimitry Andric   LoopMBB->addSuccessor(ContinueMBB);
11040b57cec5SDimitry Andric   LoopMBB->addSuccessor(LoopMBB);
11050b57cec5SDimitry Andric 
11060b57cec5SDimitry Andric   // Mark all the instructions added to the prolog as frame setup.
11070b57cec5SDimitry Andric   if (InProlog) {
11080b57cec5SDimitry Andric     for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
11090b57cec5SDimitry Andric       BeforeMBBI->setFlag(MachineInstr::FrameSetup);
11100b57cec5SDimitry Andric     }
11110b57cec5SDimitry Andric     for (MachineInstr &MI : *RoundMBB) {
11120b57cec5SDimitry Andric       MI.setFlag(MachineInstr::FrameSetup);
11130b57cec5SDimitry Andric     }
11140b57cec5SDimitry Andric     for (MachineInstr &MI : *LoopMBB) {
11150b57cec5SDimitry Andric       MI.setFlag(MachineInstr::FrameSetup);
11160b57cec5SDimitry Andric     }
1117bdd1243dSDimitry Andric     for (MachineInstr &MI :
1118bdd1243dSDimitry Andric          llvm::make_range(ContinueMBB->begin(), ContinueMBBI)) {
1119bdd1243dSDimitry Andric       MI.setFlag(MachineInstr::FrameSetup);
11200b57cec5SDimitry Andric     }
11210b57cec5SDimitry Andric   }
11220b57cec5SDimitry Andric }
11230b57cec5SDimitry Andric 
11244824e7fdSDimitry Andric void X86FrameLowering::emitStackProbeCall(
11254824e7fdSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
11264824e7fdSDimitry Andric     MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
1127bdd1243dSDimitry Andric     std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
11280b57cec5SDimitry Andric   bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
11290b57cec5SDimitry Andric 
11300946e70aSDimitry Andric   // FIXME: Add indirect thunk support and remove this.
11310946e70aSDimitry Andric   if (Is64Bit && IsLargeCodeModel && STI.useIndirectThunkCalls())
11320b57cec5SDimitry Andric     report_fatal_error("Emitting stack probe calls on 64-bit with the large "
11330946e70aSDimitry Andric                        "code model and indirect thunks not yet implemented.");
11340b57cec5SDimitry Andric 
1135bdd1243dSDimitry Andric   assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
1136bdd1243dSDimitry Andric              MachineBasicBlock::LQR_Live &&
1137bdd1243dSDimitry Andric          "Stack probe calls will clobber live EFLAGS.");
1138bdd1243dSDimitry Andric 
11390b57cec5SDimitry Andric   unsigned CallOp;
11400b57cec5SDimitry Andric   if (Is64Bit)
11410b57cec5SDimitry Andric     CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
11420b57cec5SDimitry Andric   else
11430b57cec5SDimitry Andric     CallOp = X86::CALLpcrel32;
11440b57cec5SDimitry Andric 
11450b57cec5SDimitry Andric   StringRef Symbol = STI.getTargetLowering()->getStackProbeSymbolName(MF);
11460b57cec5SDimitry Andric 
11470b57cec5SDimitry Andric   MachineInstrBuilder CI;
11480b57cec5SDimitry Andric   MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI);
11490b57cec5SDimitry Andric 
11500b57cec5SDimitry Andric   // All current stack probes take AX and SP as input, clobber flags, and
11510b57cec5SDimitry Andric   // preserve all registers. x86_64 probes leave RSP unmodified.
11520b57cec5SDimitry Andric   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
11530b57cec5SDimitry Andric     // For the large code model, we have to call through a register. Use R11,
11540b57cec5SDimitry Andric     // as it is scratch in all supported calling conventions.
11550b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
11560b57cec5SDimitry Andric         .addExternalSymbol(MF.createExternalSymbolName(Symbol));
11570b57cec5SDimitry Andric     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
11580b57cec5SDimitry Andric   } else {
11590b57cec5SDimitry Andric     CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp))
11600b57cec5SDimitry Andric              .addExternalSymbol(MF.createExternalSymbolName(Symbol));
11610b57cec5SDimitry Andric   }
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric   unsigned AX = Uses64BitFramePtr ? X86::RAX : X86::EAX;
11640b57cec5SDimitry Andric   unsigned SP = Uses64BitFramePtr ? X86::RSP : X86::ESP;
11650b57cec5SDimitry Andric   CI.addReg(AX, RegState::Implicit)
11660b57cec5SDimitry Andric       .addReg(SP, RegState::Implicit)
11670b57cec5SDimitry Andric       .addReg(AX, RegState::Define | RegState::Implicit)
11680b57cec5SDimitry Andric       .addReg(SP, RegState::Define | RegState::Implicit)
11690b57cec5SDimitry Andric       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
11700b57cec5SDimitry Andric 
11714824e7fdSDimitry Andric   MachineInstr *ModInst = CI;
11720b57cec5SDimitry Andric   if (STI.isTargetWin64() || !STI.isOSWindows()) {
11730b57cec5SDimitry Andric     // MSVC x32's _chkstk and cygwin/mingw's _alloca adjust %esp themselves.
11740b57cec5SDimitry Andric     // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
11750b57cec5SDimitry Andric     // themselves. They also does not clobber %rax so we can reuse it when
11760b57cec5SDimitry Andric     // adjusting %rsp.
11770b57cec5SDimitry Andric     // All other platforms do not specify a particular ABI for the stack probe
11780b57cec5SDimitry Andric     // function, so we arbitrarily define it to not adjust %esp/%rsp itself.
11794824e7fdSDimitry Andric     ModInst =
11800b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(getSUBrrOpcode(Uses64BitFramePtr)), SP)
11810b57cec5SDimitry Andric             .addReg(SP)
11820b57cec5SDimitry Andric             .addReg(AX);
11830b57cec5SDimitry Andric   }
11840b57cec5SDimitry Andric 
11854824e7fdSDimitry Andric   // DebugInfo variable locations -- if there's an instruction number for the
11864824e7fdSDimitry Andric   // allocation (i.e., DYN_ALLOC_*), substitute it for the instruction that
11874824e7fdSDimitry Andric   // modifies SP.
11884824e7fdSDimitry Andric   if (InstrNum) {
11894824e7fdSDimitry Andric     if (STI.isTargetWin64() || !STI.isOSWindows()) {
11904824e7fdSDimitry Andric       // Label destination operand of the subtract.
11914824e7fdSDimitry Andric       MF.makeDebugValueSubstitution(*InstrNum,
11924824e7fdSDimitry Andric                                     {ModInst->getDebugInstrNum(), 0});
11934824e7fdSDimitry Andric     } else {
11944824e7fdSDimitry Andric       // Label the call. The operand number is the penultimate operand, zero
11954824e7fdSDimitry Andric       // based.
11964824e7fdSDimitry Andric       unsigned SPDefOperand = ModInst->getNumOperands() - 2;
11974824e7fdSDimitry Andric       MF.makeDebugValueSubstitution(
11984824e7fdSDimitry Andric           *InstrNum, {ModInst->getDebugInstrNum(), SPDefOperand});
11994824e7fdSDimitry Andric     }
12004824e7fdSDimitry Andric   }
12014824e7fdSDimitry Andric 
12020b57cec5SDimitry Andric   if (InProlog) {
12030b57cec5SDimitry Andric     // Apply the frame setup flag to all inserted instrs.
12040b57cec5SDimitry Andric     for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
12050b57cec5SDimitry Andric       ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
12060b57cec5SDimitry Andric   }
12070b57cec5SDimitry Andric }
12080b57cec5SDimitry Andric 
12090b57cec5SDimitry Andric static unsigned calculateSetFPREG(uint64_t SPAdjust) {
12100b57cec5SDimitry Andric   // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
12110b57cec5SDimitry Andric   // and might require smaller successive adjustments.
12120b57cec5SDimitry Andric   const uint64_t Win64MaxSEHOffset = 128;
12130b57cec5SDimitry Andric   uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
12140b57cec5SDimitry Andric   // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
12150b57cec5SDimitry Andric   return SEHFrameOffset & -16;
12160b57cec5SDimitry Andric }
12170b57cec5SDimitry Andric 
12180b57cec5SDimitry Andric // If we're forcing a stack realignment we can't rely on just the frame
12190b57cec5SDimitry Andric // info, we need to know the ABI stack alignment as well in case we
12200b57cec5SDimitry Andric // have a call out.  Otherwise just make sure we have some alignment - we'll
12210b57cec5SDimitry Andric // go with the minimum SlotSize.
12225f757f3fSDimitry Andric uint64_t
12235f757f3fSDimitry Andric X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
12240b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
12255ffd83dbSDimitry Andric   Align MaxAlign = MFI.getMaxAlign(); // Desired stack alignment.
12265ffd83dbSDimitry Andric   Align StackAlign = getStackAlign();
122706c3fb27SDimitry Andric   bool HasRealign = MF.getFunction().hasFnAttribute("stackrealign");
122806c3fb27SDimitry Andric   if (HasRealign) {
12290b57cec5SDimitry Andric     if (MFI.hasCalls())
12300b57cec5SDimitry Andric       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
12310b57cec5SDimitry Andric     else if (MaxAlign < SlotSize)
12325ffd83dbSDimitry Andric       MaxAlign = Align(SlotSize);
12330b57cec5SDimitry Andric   }
123406c3fb27SDimitry Andric 
123506c3fb27SDimitry Andric   if (!Is64Bit && MF.getFunction().getCallingConv() == CallingConv::X86_INTR) {
123606c3fb27SDimitry Andric     if (HasRealign)
123706c3fb27SDimitry Andric       MaxAlign = (MaxAlign > 16) ? MaxAlign : Align(16);
123806c3fb27SDimitry Andric     else
123906c3fb27SDimitry Andric       MaxAlign = Align(16);
124006c3fb27SDimitry Andric   }
12415ffd83dbSDimitry Andric   return MaxAlign.value();
12420b57cec5SDimitry Andric }
12430b57cec5SDimitry Andric 
12440b57cec5SDimitry Andric void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
12450b57cec5SDimitry Andric                                           MachineBasicBlock::iterator MBBI,
12460b57cec5SDimitry Andric                                           const DebugLoc &DL, unsigned Reg,
12470b57cec5SDimitry Andric                                           uint64_t MaxAlign) const {
12480b57cec5SDimitry Andric   uint64_t Val = -MaxAlign;
12490b57cec5SDimitry Andric   unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val);
1250eaeb601bSDimitry Andric 
1251eaeb601bSDimitry Andric   MachineFunction &MF = *MBB.getParent();
1252eaeb601bSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1253eaeb601bSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
1254eaeb601bSDimitry Andric   const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
1255eaeb601bSDimitry Andric   const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
1256eaeb601bSDimitry Andric 
1257eaeb601bSDimitry Andric   // We want to make sure that (in worst case) less than StackProbeSize bytes
1258eaeb601bSDimitry Andric   // are not probed after the AND. This assumption is used in
1259eaeb601bSDimitry Andric   // emitStackProbeInlineGeneric.
1260eaeb601bSDimitry Andric   if (Reg == StackPtr && EmitInlineStackProbe && MaxAlign >= StackProbeSize) {
1261eaeb601bSDimitry Andric     {
1262eaeb601bSDimitry Andric       NumFrameLoopProbe++;
1263eaeb601bSDimitry Andric       MachineBasicBlock *entryMBB =
1264eaeb601bSDimitry Andric           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1265eaeb601bSDimitry Andric       MachineBasicBlock *headMBB =
1266eaeb601bSDimitry Andric           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1267eaeb601bSDimitry Andric       MachineBasicBlock *bodyMBB =
1268eaeb601bSDimitry Andric           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1269eaeb601bSDimitry Andric       MachineBasicBlock *footMBB =
1270eaeb601bSDimitry Andric           MF.CreateMachineBasicBlock(MBB.getBasicBlock());
1271eaeb601bSDimitry Andric 
1272eaeb601bSDimitry Andric       MachineFunction::iterator MBBIter = MBB.getIterator();
1273eaeb601bSDimitry Andric       MF.insert(MBBIter, entryMBB);
1274eaeb601bSDimitry Andric       MF.insert(MBBIter, headMBB);
1275eaeb601bSDimitry Andric       MF.insert(MBBIter, bodyMBB);
1276eaeb601bSDimitry Andric       MF.insert(MBBIter, footMBB);
1277eaeb601bSDimitry Andric       const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
12788c6f6c0cSDimitry Andric       Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
12798c6f6c0cSDimitry Andric                                   : Is64Bit         ? X86::R11D
12808c6f6c0cSDimitry Andric                                                     : X86::EAX;
1281eaeb601bSDimitry Andric 
1282eaeb601bSDimitry Andric       // Setup entry block
1283eaeb601bSDimitry Andric       {
1284eaeb601bSDimitry Andric 
1285eaeb601bSDimitry Andric         entryMBB->splice(entryMBB->end(), &MBB, MBB.begin(), MBBI);
1286eaeb601bSDimitry Andric         BuildMI(entryMBB, DL, TII.get(TargetOpcode::COPY), FinalStackProbed)
1287eaeb601bSDimitry Andric             .addReg(StackPtr)
1288eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1289eaeb601bSDimitry Andric         MachineInstr *MI =
1290eaeb601bSDimitry Andric             BuildMI(entryMBB, DL, TII.get(AndOp), FinalStackProbed)
1291eaeb601bSDimitry Andric                 .addReg(FinalStackProbed)
1292eaeb601bSDimitry Andric                 .addImm(Val)
1293eaeb601bSDimitry Andric                 .setMIFlag(MachineInstr::FrameSetup);
1294eaeb601bSDimitry Andric 
1295eaeb601bSDimitry Andric         // The EFLAGS implicit def is dead.
1296eaeb601bSDimitry Andric         MI->getOperand(3).setIsDead();
1297eaeb601bSDimitry Andric 
1298eaeb601bSDimitry Andric         BuildMI(entryMBB, DL,
1299eaeb601bSDimitry Andric                 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1300eaeb601bSDimitry Andric             .addReg(FinalStackProbed)
1301eaeb601bSDimitry Andric             .addReg(StackPtr)
1302eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1303eaeb601bSDimitry Andric         BuildMI(entryMBB, DL, TII.get(X86::JCC_1))
1304eaeb601bSDimitry Andric             .addMBB(&MBB)
1305eaeb601bSDimitry Andric             .addImm(X86::COND_E)
1306eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1307eaeb601bSDimitry Andric         entryMBB->addSuccessor(headMBB);
1308eaeb601bSDimitry Andric         entryMBB->addSuccessor(&MBB);
1309eaeb601bSDimitry Andric       }
1310eaeb601bSDimitry Andric 
1311eaeb601bSDimitry Andric       // Loop entry block
1312eaeb601bSDimitry Andric 
1313eaeb601bSDimitry Andric       {
13145f757f3fSDimitry Andric         const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr);
1315eaeb601bSDimitry Andric         BuildMI(headMBB, DL, TII.get(SUBOpc), StackPtr)
1316eaeb601bSDimitry Andric             .addReg(StackPtr)
1317eaeb601bSDimitry Andric             .addImm(StackProbeSize)
1318eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1319eaeb601bSDimitry Andric 
1320eaeb601bSDimitry Andric         BuildMI(headMBB, DL,
1321eaeb601bSDimitry Andric                 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1322eaeb601bSDimitry Andric             .addReg(StackPtr)
1323bdd1243dSDimitry Andric             .addReg(FinalStackProbed)
1324eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1325eaeb601bSDimitry Andric 
1326bdd1243dSDimitry Andric         // jump to the footer if StackPtr < FinalStackProbed
1327eaeb601bSDimitry Andric         BuildMI(headMBB, DL, TII.get(X86::JCC_1))
1328eaeb601bSDimitry Andric             .addMBB(footMBB)
1329eaeb601bSDimitry Andric             .addImm(X86::COND_B)
1330eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1331eaeb601bSDimitry Andric 
1332eaeb601bSDimitry Andric         headMBB->addSuccessor(bodyMBB);
1333eaeb601bSDimitry Andric         headMBB->addSuccessor(footMBB);
1334eaeb601bSDimitry Andric       }
1335eaeb601bSDimitry Andric 
1336eaeb601bSDimitry Andric       // setup loop body
1337eaeb601bSDimitry Andric       {
1338eaeb601bSDimitry Andric         addRegOffset(BuildMI(bodyMBB, DL, TII.get(MovMIOpc))
1339eaeb601bSDimitry Andric                          .setMIFlag(MachineInstr::FrameSetup),
1340eaeb601bSDimitry Andric                      StackPtr, false, 0)
1341eaeb601bSDimitry Andric             .addImm(0)
1342eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1343eaeb601bSDimitry Andric 
13445f757f3fSDimitry Andric         const unsigned SUBOpc = getSUBriOpcode(Uses64BitFramePtr);
1345eaeb601bSDimitry Andric         BuildMI(bodyMBB, DL, TII.get(SUBOpc), StackPtr)
1346eaeb601bSDimitry Andric             .addReg(StackPtr)
1347eaeb601bSDimitry Andric             .addImm(StackProbeSize)
1348eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1349eaeb601bSDimitry Andric 
1350eaeb601bSDimitry Andric         // cmp with stack pointer bound
1351eaeb601bSDimitry Andric         BuildMI(bodyMBB, DL,
1352eaeb601bSDimitry Andric                 TII.get(Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1353eaeb601bSDimitry Andric             .addReg(FinalStackProbed)
1354eaeb601bSDimitry Andric             .addReg(StackPtr)
1355eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1356eaeb601bSDimitry Andric 
1357bdd1243dSDimitry Andric         // jump back while FinalStackProbed < StackPtr
1358eaeb601bSDimitry Andric         BuildMI(bodyMBB, DL, TII.get(X86::JCC_1))
1359eaeb601bSDimitry Andric             .addMBB(bodyMBB)
1360eaeb601bSDimitry Andric             .addImm(X86::COND_B)
1361eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1362eaeb601bSDimitry Andric         bodyMBB->addSuccessor(bodyMBB);
1363eaeb601bSDimitry Andric         bodyMBB->addSuccessor(footMBB);
1364eaeb601bSDimitry Andric       }
1365eaeb601bSDimitry Andric 
1366eaeb601bSDimitry Andric       // setup loop footer
1367eaeb601bSDimitry Andric       {
1368eaeb601bSDimitry Andric         BuildMI(footMBB, DL, TII.get(TargetOpcode::COPY), StackPtr)
1369eaeb601bSDimitry Andric             .addReg(FinalStackProbed)
1370eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1371eaeb601bSDimitry Andric         addRegOffset(BuildMI(footMBB, DL, TII.get(MovMIOpc))
1372eaeb601bSDimitry Andric                          .setMIFlag(MachineInstr::FrameSetup),
1373eaeb601bSDimitry Andric                      StackPtr, false, 0)
1374eaeb601bSDimitry Andric             .addImm(0)
1375eaeb601bSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1376eaeb601bSDimitry Andric         footMBB->addSuccessor(&MBB);
1377eaeb601bSDimitry Andric       }
1378eaeb601bSDimitry Andric 
13790fca6ea1SDimitry Andric       fullyRecomputeLiveIns({footMBB, bodyMBB, headMBB, &MBB});
1380eaeb601bSDimitry Andric     }
1381eaeb601bSDimitry Andric   } else {
13820b57cec5SDimitry Andric     MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg)
13830b57cec5SDimitry Andric                            .addReg(Reg)
13840b57cec5SDimitry Andric                            .addImm(Val)
13850b57cec5SDimitry Andric                            .setMIFlag(MachineInstr::FrameSetup);
13860b57cec5SDimitry Andric 
13870b57cec5SDimitry Andric     // The EFLAGS implicit def is dead.
13880b57cec5SDimitry Andric     MI->getOperand(3).setIsDead();
13890b57cec5SDimitry Andric   }
1390eaeb601bSDimitry Andric }
13910b57cec5SDimitry Andric 
13920b57cec5SDimitry Andric bool X86FrameLowering::has128ByteRedZone(const MachineFunction &MF) const {
13930b57cec5SDimitry Andric   // x86-64 (non Win64) has a 128 byte red zone which is guaranteed not to be
13940b57cec5SDimitry Andric   // clobbered by any interrupt handler.
13950b57cec5SDimitry Andric   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
13960b57cec5SDimitry Andric          "MF used frame lowering for wrong subtarget");
13970b57cec5SDimitry Andric   const Function &Fn = MF.getFunction();
13980b57cec5SDimitry Andric   const bool IsWin64CC = STI.isCallingConvWin64(Fn.getCallingConv());
13990b57cec5SDimitry Andric   return Is64Bit && !IsWin64CC && !Fn.hasFnAttribute(Attribute::NoRedZone);
14000b57cec5SDimitry Andric }
14010b57cec5SDimitry Andric 
1402d56accc7SDimitry Andric /// Return true if we need to use the restricted Windows x64 prologue and
1403d56accc7SDimitry Andric /// epilogue code patterns that can be described with WinCFI (.seh_*
1404d56accc7SDimitry Andric /// directives).
1405fe6060f1SDimitry Andric bool X86FrameLowering::isWin64Prologue(const MachineFunction &MF) const {
1406fe6060f1SDimitry Andric   return MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1407fe6060f1SDimitry Andric }
1408fe6060f1SDimitry Andric 
1409fe6060f1SDimitry Andric bool X86FrameLowering::needsDwarfCFI(const MachineFunction &MF) const {
1410fe6060f1SDimitry Andric   return !isWin64Prologue(MF) && MF.needsFrameMoves();
1411fe6060f1SDimitry Andric }
14120b57cec5SDimitry Andric 
14130fca6ea1SDimitry Andric /// Return true if an opcode is part of the REP group of instructions
14140fca6ea1SDimitry Andric static bool isOpcodeRep(unsigned Opcode) {
14150fca6ea1SDimitry Andric   switch (Opcode) {
14160fca6ea1SDimitry Andric   case X86::REPNE_PREFIX:
14170fca6ea1SDimitry Andric   case X86::REP_MOVSB_32:
14180fca6ea1SDimitry Andric   case X86::REP_MOVSB_64:
14190fca6ea1SDimitry Andric   case X86::REP_MOVSD_32:
14200fca6ea1SDimitry Andric   case X86::REP_MOVSD_64:
14210fca6ea1SDimitry Andric   case X86::REP_MOVSQ_32:
14220fca6ea1SDimitry Andric   case X86::REP_MOVSQ_64:
14230fca6ea1SDimitry Andric   case X86::REP_MOVSW_32:
14240fca6ea1SDimitry Andric   case X86::REP_MOVSW_64:
14250fca6ea1SDimitry Andric   case X86::REP_PREFIX:
14260fca6ea1SDimitry Andric   case X86::REP_STOSB_32:
14270fca6ea1SDimitry Andric   case X86::REP_STOSB_64:
14280fca6ea1SDimitry Andric   case X86::REP_STOSD_32:
14290fca6ea1SDimitry Andric   case X86::REP_STOSD_64:
14300fca6ea1SDimitry Andric   case X86::REP_STOSQ_32:
14310fca6ea1SDimitry Andric   case X86::REP_STOSQ_64:
14320fca6ea1SDimitry Andric   case X86::REP_STOSW_32:
14330fca6ea1SDimitry Andric   case X86::REP_STOSW_64:
14340fca6ea1SDimitry Andric     return true;
14350fca6ea1SDimitry Andric   default:
14360fca6ea1SDimitry Andric     break;
14370fca6ea1SDimitry Andric   }
14380fca6ea1SDimitry Andric   return false;
14390fca6ea1SDimitry Andric }
14400fca6ea1SDimitry Andric 
14410b57cec5SDimitry Andric /// emitPrologue - Push callee-saved registers onto the stack, which
14420b57cec5SDimitry Andric /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
14430b57cec5SDimitry Andric /// space for local variables. Also emit labels used by the exception handler to
14440b57cec5SDimitry Andric /// generate the exception handling frames.
14450b57cec5SDimitry Andric 
14460b57cec5SDimitry Andric /*
14470b57cec5SDimitry Andric   Here's a gist of what gets emitted:
14480b57cec5SDimitry Andric 
14490b57cec5SDimitry Andric   ; Establish frame pointer, if needed
14500b57cec5SDimitry Andric   [if needs FP]
14510b57cec5SDimitry Andric       push  %rbp
14520b57cec5SDimitry Andric       .cfi_def_cfa_offset 16
14530b57cec5SDimitry Andric       .cfi_offset %rbp, -16
14540b57cec5SDimitry Andric       .seh_pushreg %rpb
14550b57cec5SDimitry Andric       mov  %rsp, %rbp
14560b57cec5SDimitry Andric       .cfi_def_cfa_register %rbp
14570b57cec5SDimitry Andric 
14580b57cec5SDimitry Andric   ; Spill general-purpose registers
14590b57cec5SDimitry Andric   [for all callee-saved GPRs]
14600b57cec5SDimitry Andric       pushq %<reg>
14610b57cec5SDimitry Andric       [if not needs FP]
14620b57cec5SDimitry Andric          .cfi_def_cfa_offset (offset from RETADDR)
14630b57cec5SDimitry Andric       .seh_pushreg %<reg>
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric   ; If the required stack alignment > default stack alignment
14660b57cec5SDimitry Andric   ; rsp needs to be re-aligned.  This creates a "re-alignment gap"
14670b57cec5SDimitry Andric   ; of unknown size in the stack frame.
14680b57cec5SDimitry Andric   [if stack needs re-alignment]
14690b57cec5SDimitry Andric       and  $MASK, %rsp
14700b57cec5SDimitry Andric 
14710b57cec5SDimitry Andric   ; Allocate space for locals
14720b57cec5SDimitry Andric   [if target is Windows and allocated space > 4096 bytes]
14730b57cec5SDimitry Andric       ; Windows needs special care for allocations larger
14740b57cec5SDimitry Andric       ; than one page.
14750b57cec5SDimitry Andric       mov $NNN, %rax
14760b57cec5SDimitry Andric       call ___chkstk_ms/___chkstk
14770b57cec5SDimitry Andric       sub  %rax, %rsp
14780b57cec5SDimitry Andric   [else]
14790b57cec5SDimitry Andric       sub  $NNN, %rsp
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric   [if needs FP]
14820b57cec5SDimitry Andric       .seh_stackalloc (size of XMM spill slots)
14830b57cec5SDimitry Andric       .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
14840b57cec5SDimitry Andric   [else]
14850b57cec5SDimitry Andric       .seh_stackalloc NNN
14860b57cec5SDimitry Andric 
14870b57cec5SDimitry Andric   ; Spill XMMs
14880b57cec5SDimitry Andric   ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
14890b57cec5SDimitry Andric   ; they may get spilled on any platform, if the current function
14900b57cec5SDimitry Andric   ; calls @llvm.eh.unwind.init
14910b57cec5SDimitry Andric   [if needs FP]
14920b57cec5SDimitry Andric       [for all callee-saved XMM registers]
14930b57cec5SDimitry Andric           movaps  %<xmm reg>, -MMM(%rbp)
14940b57cec5SDimitry Andric       [for all callee-saved XMM registers]
14950b57cec5SDimitry Andric           .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
14960b57cec5SDimitry Andric               ; i.e. the offset relative to (%rbp - SEHFrameOffset)
14970b57cec5SDimitry Andric   [else]
14980b57cec5SDimitry Andric       [for all callee-saved XMM registers]
14990b57cec5SDimitry Andric           movaps  %<xmm reg>, KKK(%rsp)
15000b57cec5SDimitry Andric       [for all callee-saved XMM registers]
15010b57cec5SDimitry Andric           .seh_savexmm %<xmm reg>, KKK
15020b57cec5SDimitry Andric 
15030b57cec5SDimitry Andric   .seh_endprologue
15040b57cec5SDimitry Andric 
15050b57cec5SDimitry Andric   [if needs base pointer]
15060b57cec5SDimitry Andric       mov  %rsp, %rbx
15070b57cec5SDimitry Andric       [if needs to restore base pointer]
15080b57cec5SDimitry Andric           mov %rsp, -MMM(%rbp)
15090b57cec5SDimitry Andric 
15100b57cec5SDimitry Andric   ; Emit CFI info
15110b57cec5SDimitry Andric   [if needs FP]
15120b57cec5SDimitry Andric       [for all callee-saved registers]
15130b57cec5SDimitry Andric           .cfi_offset %<reg>, (offset from %rbp)
15140b57cec5SDimitry Andric   [else]
15150b57cec5SDimitry Andric        .cfi_def_cfa_offset (offset from RETADDR)
15160b57cec5SDimitry Andric       [for all callee-saved registers]
15170b57cec5SDimitry Andric           .cfi_offset %<reg>, (offset from %rsp)
15180b57cec5SDimitry Andric 
15190b57cec5SDimitry Andric   Notes:
15200b57cec5SDimitry Andric   - .seh directives are emitted only for Windows 64 ABI
15210b57cec5SDimitry Andric   - .cv_fpo directives are emitted on win32 when emitting CodeView
15220b57cec5SDimitry Andric   - .cfi directives are emitted for all other ABIs
15230b57cec5SDimitry Andric   - for 32-bit code, substitute %e?? registers for %r??
15240b57cec5SDimitry Andric */
15250b57cec5SDimitry Andric 
15260b57cec5SDimitry Andric void X86FrameLowering::emitPrologue(MachineFunction &MF,
15270b57cec5SDimitry Andric                                     MachineBasicBlock &MBB) const {
15280b57cec5SDimitry Andric   assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
15290b57cec5SDimitry Andric          "MF used frame lowering for wrong subtarget");
15300b57cec5SDimitry Andric   MachineBasicBlock::iterator MBBI = MBB.begin();
15310b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
15320b57cec5SDimitry Andric   const Function &Fn = MF.getFunction();
15330b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
15340b57cec5SDimitry Andric   uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
15350b57cec5SDimitry Andric   uint64_t StackSize = MFI.getStackSize(); // Number of bytes to allocate.
15360b57cec5SDimitry Andric   bool IsFunclet = MBB.isEHFuncletEntry();
15370b57cec5SDimitry Andric   EHPersonality Personality = EHPersonality::Unknown;
15380b57cec5SDimitry Andric   if (Fn.hasPersonalityFn())
15390b57cec5SDimitry Andric     Personality = classifyEHPersonality(Fn.getPersonalityFn());
15400b57cec5SDimitry Andric   bool FnHasClrFunclet =
15410b57cec5SDimitry Andric       MF.hasEHFunclets() && Personality == EHPersonality::CoreCLR;
15420b57cec5SDimitry Andric   bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
15430b57cec5SDimitry Andric   bool HasFP = hasFP(MF);
1544fe6060f1SDimitry Andric   bool IsWin64Prologue = isWin64Prologue(MF);
15450b57cec5SDimitry Andric   bool NeedsWin64CFI = IsWin64Prologue && Fn.needsUnwindTableEntry();
15460b57cec5SDimitry Andric   // FIXME: Emit FPO data for EH funclets.
15470fca6ea1SDimitry Andric   bool NeedsWinFPO = !IsFunclet && STI.isTargetWin32() &&
15480fca6ea1SDimitry Andric                      MF.getFunction().getParent()->getCodeViewFlag();
15490b57cec5SDimitry Andric   bool NeedsWinCFI = NeedsWin64CFI || NeedsWinFPO;
1550fe6060f1SDimitry Andric   bool NeedsDwarfCFI = needsDwarfCFI(MF);
15518bcb0991SDimitry Andric   Register FramePtr = TRI->getFrameRegister(MF);
15528bcb0991SDimitry Andric   const Register MachineFramePtr =
15535f757f3fSDimitry Andric       STI.isTarget64BitILP32() ? Register(getX86SubSuperRegister(FramePtr, 64))
15545f757f3fSDimitry Andric                                : FramePtr;
15558bcb0991SDimitry Andric   Register BasePtr = TRI->getBaseRegister();
15560b57cec5SDimitry Andric   bool HasWinCFI = false;
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric   // Debug location must be unknown since the first debug location is used
15590b57cec5SDimitry Andric   // to determine the end of the prologue.
15600b57cec5SDimitry Andric   DebugLoc DL;
156106c3fb27SDimitry Andric   Register ArgBaseReg;
156206c3fb27SDimitry Andric 
156306c3fb27SDimitry Andric   // Emit extra prolog for argument stack slot reference.
156406c3fb27SDimitry Andric   if (auto *MI = X86FI->getStackPtrSaveMI()) {
156506c3fb27SDimitry Andric     // MI is lea instruction that created in X86ArgumentStackSlotPass.
156606c3fb27SDimitry Andric     // Creat extra prolog for stack realignment.
156706c3fb27SDimitry Andric     ArgBaseReg = MI->getOperand(0).getReg();
156806c3fb27SDimitry Andric     // leal    4(%esp), %basereg
156906c3fb27SDimitry Andric     // .cfi_def_cfa %basereg, 0
157006c3fb27SDimitry Andric     // andl    $-128, %esp
157106c3fb27SDimitry Andric     // pushl   -4(%basereg)
157206c3fb27SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::LEA64r : X86::LEA32r),
157306c3fb27SDimitry Andric             ArgBaseReg)
157406c3fb27SDimitry Andric         .addUse(StackPtr)
157506c3fb27SDimitry Andric         .addImm(1)
157606c3fb27SDimitry Andric         .addUse(X86::NoRegister)
157706c3fb27SDimitry Andric         .addImm(SlotSize)
157806c3fb27SDimitry Andric         .addUse(X86::NoRegister)
157906c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
158006c3fb27SDimitry Andric     if (NeedsDwarfCFI) {
158106c3fb27SDimitry Andric       // .cfi_def_cfa %basereg, 0
158206c3fb27SDimitry Andric       unsigned DwarfStackPtr = TRI->getDwarfRegNum(ArgBaseReg, true);
158306c3fb27SDimitry Andric       BuildCFI(MBB, MBBI, DL,
158406c3fb27SDimitry Andric                MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, 0),
158506c3fb27SDimitry Andric                MachineInstr::FrameSetup);
158606c3fb27SDimitry Andric     }
158706c3fb27SDimitry Andric     BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
158806c3fb27SDimitry Andric     int64_t Offset = -(int64_t)SlotSize;
158906c3fb27SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm))
159006c3fb27SDimitry Andric         .addReg(ArgBaseReg)
159106c3fb27SDimitry Andric         .addImm(1)
159206c3fb27SDimitry Andric         .addReg(X86::NoRegister)
159306c3fb27SDimitry Andric         .addImm(Offset)
159406c3fb27SDimitry Andric         .addReg(X86::NoRegister)
159506c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
159606c3fb27SDimitry Andric   }
15970b57cec5SDimitry Andric 
1598349cc55cSDimitry Andric   // Space reserved for stack-based arguments when making a (ABI-guaranteed)
1599349cc55cSDimitry Andric   // tail call.
1600349cc55cSDimitry Andric   unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
1601349cc55cSDimitry Andric   if (TailCallArgReserveSize && IsWin64Prologue)
16020b57cec5SDimitry Andric     report_fatal_error("Can't handle guaranteed tail call under win64 yet");
16030b57cec5SDimitry Andric 
16045ffd83dbSDimitry Andric   const bool EmitStackProbeCall =
16055ffd83dbSDimitry Andric       STI.getTargetLowering()->hasStackProbeSymbol(MF);
16068bcb0991SDimitry Andric   unsigned StackProbeSize = STI.getTargetLowering()->getStackProbeSize(MF);
16070b57cec5SDimitry Andric 
1608fe6060f1SDimitry Andric   if (HasFP && X86FI->hasSwiftAsyncContext()) {
1609349cc55cSDimitry Andric     switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
1610349cc55cSDimitry Andric     case SwiftAsyncFramePointerMode::DeploymentBased:
1611349cc55cSDimitry Andric       if (STI.swiftAsyncContextIsDynamicallySet()) {
1612349cc55cSDimitry Andric         // The special symbol below is absolute and has a *value* suitable to be
1613349cc55cSDimitry Andric         // combined with the frame pointer directly.
1614349cc55cSDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::OR64rm), MachineFramePtr)
1615349cc55cSDimitry Andric             .addUse(MachineFramePtr)
1616349cc55cSDimitry Andric             .addUse(X86::RIP)
1617349cc55cSDimitry Andric             .addImm(1)
1618349cc55cSDimitry Andric             .addUse(X86::NoRegister)
1619349cc55cSDimitry Andric             .addExternalSymbol("swift_async_extendedFramePointerFlags",
1620349cc55cSDimitry Andric                                X86II::MO_GOTPCREL)
1621349cc55cSDimitry Andric             .addUse(X86::NoRegister);
1622349cc55cSDimitry Andric         break;
1623349cc55cSDimitry Andric       }
1624bdd1243dSDimitry Andric       [[fallthrough]];
1625349cc55cSDimitry Andric 
1626349cc55cSDimitry Andric     case SwiftAsyncFramePointerMode::Always:
16270fca6ea1SDimitry Andric       assert(
16280fca6ea1SDimitry Andric           !IsWin64Prologue &&
16290fca6ea1SDimitry Andric           "win64 prologue does not set the bit 60 in the saved frame pointer");
1630349cc55cSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::BTS64ri8), MachineFramePtr)
1631fe6060f1SDimitry Andric           .addUse(MachineFramePtr)
1632fe6060f1SDimitry Andric           .addImm(60)
1633fe6060f1SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
1634349cc55cSDimitry Andric       break;
1635349cc55cSDimitry Andric 
1636349cc55cSDimitry Andric     case SwiftAsyncFramePointerMode::Never:
1637349cc55cSDimitry Andric       break;
1638349cc55cSDimitry Andric     }
1639fe6060f1SDimitry Andric   }
1640fe6060f1SDimitry Andric 
16410b57cec5SDimitry Andric   // Re-align the stack on 64-bit if the x86-interrupt calling convention is
16420b57cec5SDimitry Andric   // used and an error code was pushed, since the x86-64 ABI requires a 16-byte
16430b57cec5SDimitry Andric   // stack alignment.
16440b57cec5SDimitry Andric   if (Fn.getCallingConv() == CallingConv::X86_INTR && Is64Bit &&
16450b57cec5SDimitry Andric       Fn.arg_size() == 2) {
16460b57cec5SDimitry Andric     StackSize += 8;
16470b57cec5SDimitry Andric     MFI.setStackSize(StackSize);
1648a324c340SDimitry Andric 
1649a324c340SDimitry Andric     // Update the stack pointer by pushing a register. This is the instruction
1650a324c340SDimitry Andric     // emitted that would be end up being emitted by a call to `emitSPUpdate`.
1651a324c340SDimitry Andric     // Hard-coding the update to a push avoids emitting a second
1652a324c340SDimitry Andric     // `STACKALLOC_W_PROBING` instruction in the save block: We know that stack
1653a324c340SDimitry Andric     // probing isn't needed anyways for an 8-byte update.
1654a324c340SDimitry Andric     // Pushing a register leaves us in a similar situation to a regular
1655a324c340SDimitry Andric     // function call where we know that the address at (rsp-8) is writeable.
1656a324c340SDimitry Andric     // That way we avoid any off-by-ones with stack probing for additional
1657a324c340SDimitry Andric     // stack pointer updates later on.
1658a324c340SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1659a324c340SDimitry Andric         .addReg(X86::RAX, RegState::Undef)
1660a324c340SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
16610b57cec5SDimitry Andric   }
16620b57cec5SDimitry Andric 
16630b57cec5SDimitry Andric   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
16640b57cec5SDimitry Andric   // function, and use up to 128 bytes of stack space, don't have a frame
16650b57cec5SDimitry Andric   // pointer, calls, or dynamic alloca then we do not need to adjust the
16660b57cec5SDimitry Andric   // stack pointer (we fit in the Red Zone). We also check that we don't
16670b57cec5SDimitry Andric   // push and pop from the stack.
1668fe6060f1SDimitry Andric   if (has128ByteRedZone(MF) && !TRI->hasStackRealignment(MF) &&
16690b57cec5SDimitry Andric       !MFI.hasVarSizedObjects() &&             // No dynamic alloca.
16700b57cec5SDimitry Andric       !MFI.adjustsStack() &&                   // No calls.
16715ffd83dbSDimitry Andric       !EmitStackProbeCall &&                   // No stack probes.
16720b57cec5SDimitry Andric       !MFI.hasCopyImplyingStackAdjustment() && // Don't push and pop.
16730b57cec5SDimitry Andric       !MF.shouldSplitStack()) {                // Regular stack
1674349cc55cSDimitry Andric     uint64_t MinSize =
1675349cc55cSDimitry Andric         X86FI->getCalleeSavedFrameSize() - X86FI->getTCReturnAddrDelta();
16765f757f3fSDimitry Andric     if (HasFP)
16775f757f3fSDimitry Andric       MinSize += SlotSize;
16780b57cec5SDimitry Andric     X86FI->setUsesRedZone(MinSize > 0 || StackSize > 0);
16790b57cec5SDimitry Andric     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
16800b57cec5SDimitry Andric     MFI.setStackSize(StackSize);
16810b57cec5SDimitry Andric   }
16820b57cec5SDimitry Andric 
16830b57cec5SDimitry Andric   // Insert stack pointer adjustment for later moving of return addr.  Only
16840b57cec5SDimitry Andric   // applies to tail call optimized functions where the callee argument stack
16850b57cec5SDimitry Andric   // size is bigger than the callers.
1686349cc55cSDimitry Andric   if (TailCallArgReserveSize != 0) {
1687349cc55cSDimitry Andric     BuildStackAdjustment(MBB, MBBI, DL, -(int)TailCallArgReserveSize,
16880b57cec5SDimitry Andric                          /*InEpilogue=*/false)
16890b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
16900b57cec5SDimitry Andric   }
16910b57cec5SDimitry Andric 
16920b57cec5SDimitry Andric   // Mapping for machine moves:
16930b57cec5SDimitry Andric   //
16940b57cec5SDimitry Andric   //   DST: VirtualFP AND
16950b57cec5SDimitry Andric   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
16960b57cec5SDimitry Andric   //        ELSE                        => DW_CFA_def_cfa
16970b57cec5SDimitry Andric   //
16980b57cec5SDimitry Andric   //   SRC: VirtualFP AND
16990b57cec5SDimitry Andric   //        DST: Register               => DW_CFA_def_cfa_register
17000b57cec5SDimitry Andric   //
17010b57cec5SDimitry Andric   //   ELSE
17020b57cec5SDimitry Andric   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
17030b57cec5SDimitry Andric   //        REG < 64                    => DW_CFA_offset + Reg
17040b57cec5SDimitry Andric   //        ELSE                        => DW_CFA_offset_extended
17050b57cec5SDimitry Andric 
17060b57cec5SDimitry Andric   uint64_t NumBytes = 0;
17070b57cec5SDimitry Andric   int stackGrowth = -SlotSize;
17080b57cec5SDimitry Andric 
17090b57cec5SDimitry Andric   // Find the funclet establisher parameter
17108bcb0991SDimitry Andric   Register Establisher = X86::NoRegister;
17110b57cec5SDimitry Andric   if (IsClrFunclet)
17120b57cec5SDimitry Andric     Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
17130b57cec5SDimitry Andric   else if (IsFunclet)
17140b57cec5SDimitry Andric     Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
17150b57cec5SDimitry Andric 
17160b57cec5SDimitry Andric   if (IsWin64Prologue && IsFunclet && !IsClrFunclet) {
17170b57cec5SDimitry Andric     // Immediately spill establisher into the home slot.
17180b57cec5SDimitry Andric     // The runtime cares about this.
17190b57cec5SDimitry Andric     // MOV64mr %rdx, 16(%rsp)
17200b57cec5SDimitry Andric     unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
17210b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16)
17220b57cec5SDimitry Andric         .addReg(Establisher)
17230b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
17240b57cec5SDimitry Andric     MBB.addLiveIn(Establisher);
17250b57cec5SDimitry Andric   }
17260b57cec5SDimitry Andric 
17270b57cec5SDimitry Andric   if (HasFP) {
17280b57cec5SDimitry Andric     assert(MF.getRegInfo().isReserved(MachineFramePtr) && "FP reserved");
17290b57cec5SDimitry Andric 
17300b57cec5SDimitry Andric     // Calculate required stack adjustment.
17310b57cec5SDimitry Andric     uint64_t FrameSize = StackSize - SlotSize;
17325f757f3fSDimitry Andric     NumBytes =
17335f757f3fSDimitry Andric         FrameSize - (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric     // Callee-saved registers are pushed on stack before the stack is realigned.
1736fe6060f1SDimitry Andric     if (TRI->hasStackRealignment(MF) && !IsWin64Prologue)
17370b57cec5SDimitry Andric       NumBytes = alignTo(NumBytes, MaxAlign);
17380b57cec5SDimitry Andric 
17390b57cec5SDimitry Andric     // Save EBP/RBP into the appropriate stack slot.
17405f757f3fSDimitry Andric     BuildMI(MBB, MBBI, DL,
17415f757f3fSDimitry Andric             TII.get(getPUSHOpcode(MF.getSubtarget<X86Subtarget>())))
17420b57cec5SDimitry Andric         .addReg(MachineFramePtr, RegState::Kill)
17430b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
17440b57cec5SDimitry Andric 
174506c3fb27SDimitry Andric     if (NeedsDwarfCFI && !ArgBaseReg.isValid()) {
17460b57cec5SDimitry Andric       // Mark the place where EBP/RBP was saved.
17470b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
17480b57cec5SDimitry Andric       assert(StackSize);
17490b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL,
175006c3fb27SDimitry Andric                MCCFIInstruction::cfiDefCfaOffset(
175106c3fb27SDimitry Andric                    nullptr, -2 * stackGrowth + (int)TailCallArgReserveSize),
175281ad6265SDimitry Andric                MachineInstr::FrameSetup);
17530b57cec5SDimitry Andric 
17540b57cec5SDimitry Andric       // Change the rule for the FramePtr to be an "offset" rule.
17550b57cec5SDimitry Andric       unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
175681ad6265SDimitry Andric       BuildCFI(MBB, MBBI, DL,
175781ad6265SDimitry Andric                MCCFIInstruction::createOffset(nullptr, DwarfFramePtr,
175806c3fb27SDimitry Andric                                               2 * stackGrowth -
175906c3fb27SDimitry Andric                                                   (int)TailCallArgReserveSize),
176081ad6265SDimitry Andric                MachineInstr::FrameSetup);
17610b57cec5SDimitry Andric     }
17620b57cec5SDimitry Andric 
17630b57cec5SDimitry Andric     if (NeedsWinCFI) {
17640b57cec5SDimitry Andric       HasWinCFI = true;
17650b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
17660b57cec5SDimitry Andric           .addImm(FramePtr)
17670b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
17680b57cec5SDimitry Andric     }
17690b57cec5SDimitry Andric 
1770fe6060f1SDimitry Andric     if (!IsFunclet) {
1771fe6060f1SDimitry Andric       if (X86FI->hasSwiftAsyncContext()) {
17720fca6ea1SDimitry Andric         assert(!IsWin64Prologue &&
17730fca6ea1SDimitry Andric                "win64 prologue does not store async context right below rbp");
1774fe6060f1SDimitry Andric         const auto &Attrs = MF.getFunction().getAttributes();
1775fe6060f1SDimitry Andric 
1776fe6060f1SDimitry Andric         // Before we update the live frame pointer we have to ensure there's a
1777fe6060f1SDimitry Andric         // valid (or null) asynchronous context in its slot just before FP in
1778fe6060f1SDimitry Andric         // the frame record, so store it now.
1779fe6060f1SDimitry Andric         if (Attrs.hasAttrSomewhere(Attribute::SwiftAsync)) {
1780fe6060f1SDimitry Andric           // We have an initial context in r14, store it just before the frame
1781fe6060f1SDimitry Andric           // pointer.
1782fe6060f1SDimitry Andric           MBB.addLiveIn(X86::R14);
1783fe6060f1SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
1784fe6060f1SDimitry Andric               .addReg(X86::R14)
1785fe6060f1SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
1786fe6060f1SDimitry Andric         } else {
1787fe6060f1SDimitry Andric           // No initial context, store null so that there's no pointer that
1788fe6060f1SDimitry Andric           // could be misused.
178906c3fb27SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64i32))
1790fe6060f1SDimitry Andric               .addImm(0)
1791fe6060f1SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
1792fe6060f1SDimitry Andric         }
1793fe6060f1SDimitry Andric 
1794fe6060f1SDimitry Andric         if (NeedsWinCFI) {
1795fe6060f1SDimitry Andric           HasWinCFI = true;
1796fe6060f1SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1797fe6060f1SDimitry Andric               .addImm(X86::R14)
1798fe6060f1SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
1799fe6060f1SDimitry Andric         }
1800fe6060f1SDimitry Andric 
1801fe6060f1SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr)
1802fe6060f1SDimitry Andric             .addUse(X86::RSP)
1803fe6060f1SDimitry Andric             .addImm(1)
1804fe6060f1SDimitry Andric             .addUse(X86::NoRegister)
1805fe6060f1SDimitry Andric             .addImm(8)
1806fe6060f1SDimitry Andric             .addUse(X86::NoRegister)
1807fe6060f1SDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
180806c3fb27SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64ri32), X86::RSP)
1809fe6060f1SDimitry Andric             .addUse(X86::RSP)
1810fe6060f1SDimitry Andric             .addImm(8)
1811fe6060f1SDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
1812fe6060f1SDimitry Andric       }
1813fe6060f1SDimitry Andric 
18140b57cec5SDimitry Andric       if (!IsWin64Prologue && !IsFunclet) {
18150b57cec5SDimitry Andric         // Update EBP with the new base value.
1816fe6060f1SDimitry Andric         if (!X86FI->hasSwiftAsyncContext())
18170b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL,
18180b57cec5SDimitry Andric                   TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
18190b57cec5SDimitry Andric                   FramePtr)
18200b57cec5SDimitry Andric               .addReg(StackPtr)
18210b57cec5SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric         if (NeedsDwarfCFI) {
182406c3fb27SDimitry Andric           if (ArgBaseReg.isValid()) {
182506c3fb27SDimitry Andric             SmallString<64> CfaExpr;
182606c3fb27SDimitry Andric             CfaExpr.push_back(dwarf::DW_CFA_expression);
182706c3fb27SDimitry Andric             uint8_t buffer[16];
182806c3fb27SDimitry Andric             unsigned DwarfReg = TRI->getDwarfRegNum(MachineFramePtr, true);
182906c3fb27SDimitry Andric             CfaExpr.append(buffer, buffer + encodeULEB128(DwarfReg, buffer));
183006c3fb27SDimitry Andric             CfaExpr.push_back(2);
183106c3fb27SDimitry Andric             CfaExpr.push_back((uint8_t)(dwarf::DW_OP_breg0 + DwarfReg));
183206c3fb27SDimitry Andric             CfaExpr.push_back(0);
183306c3fb27SDimitry Andric             // DW_CFA_expression: reg5 DW_OP_breg5 +0
183406c3fb27SDimitry Andric             BuildCFI(MBB, MBBI, DL,
183506c3fb27SDimitry Andric                      MCCFIInstruction::createEscape(nullptr, CfaExpr.str()),
183606c3fb27SDimitry Andric                      MachineInstr::FrameSetup);
183706c3fb27SDimitry Andric           } else {
18380b57cec5SDimitry Andric             // Mark effective beginning of when frame pointer becomes valid.
18390b57cec5SDimitry Andric             // Define the current CFA to use the EBP/RBP register.
18400b57cec5SDimitry Andric             unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1841fe6060f1SDimitry Andric             BuildCFI(
1842fe6060f1SDimitry Andric                 MBB, MBBI, DL,
184381ad6265SDimitry Andric                 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr),
184481ad6265SDimitry Andric                 MachineInstr::FrameSetup);
18450b57cec5SDimitry Andric           }
184606c3fb27SDimitry Andric         }
18470b57cec5SDimitry Andric 
18480b57cec5SDimitry Andric         if (NeedsWinFPO) {
18490b57cec5SDimitry Andric           // .cv_fpo_setframe $FramePtr
18500b57cec5SDimitry Andric           HasWinCFI = true;
18510b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
18520b57cec5SDimitry Andric               .addImm(FramePtr)
18530b57cec5SDimitry Andric               .addImm(0)
18540b57cec5SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
18550b57cec5SDimitry Andric         }
18560b57cec5SDimitry Andric       }
1857fe6060f1SDimitry Andric     }
18580b57cec5SDimitry Andric   } else {
18590b57cec5SDimitry Andric     assert(!IsFunclet && "funclets without FPs not yet implemented");
18605f757f3fSDimitry Andric     NumBytes =
18615f757f3fSDimitry Andric         StackSize - (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
18620b57cec5SDimitry Andric   }
18630b57cec5SDimitry Andric 
18640b57cec5SDimitry Andric   // Update the offset adjustment, which is mainly used by codeview to translate
18650b57cec5SDimitry Andric   // from ESP to VFRAME relative local variable offsets.
18660b57cec5SDimitry Andric   if (!IsFunclet) {
1867fe6060f1SDimitry Andric     if (HasFP && TRI->hasStackRealignment(MF))
18680b57cec5SDimitry Andric       MFI.setOffsetAdjustment(-NumBytes);
18690b57cec5SDimitry Andric     else
18700b57cec5SDimitry Andric       MFI.setOffsetAdjustment(-StackSize);
18710b57cec5SDimitry Andric   }
18720b57cec5SDimitry Andric 
18730b57cec5SDimitry Andric   // For EH funclets, only allocate enough space for outgoing calls. Save the
18740b57cec5SDimitry Andric   // NumBytes value that we would've used for the parent frame.
18750b57cec5SDimitry Andric   unsigned ParentFrameNumBytes = NumBytes;
18760b57cec5SDimitry Andric   if (IsFunclet)
18770b57cec5SDimitry Andric     NumBytes = getWinEHFuncletFrameSize(MF);
18780b57cec5SDimitry Andric 
18790b57cec5SDimitry Andric   // Skip the callee-saved push instructions.
18800b57cec5SDimitry Andric   bool PushedRegs = false;
18810b57cec5SDimitry Andric   int StackOffset = 2 * stackGrowth;
18825f757f3fSDimitry Andric   MachineBasicBlock::const_iterator LastCSPush = MBBI;
18835f757f3fSDimitry Andric   auto IsCSPush = [&](const MachineBasicBlock::iterator &MBBI) {
18845f757f3fSDimitry Andric     if (MBBI == MBB.end() || !MBBI->getFlag(MachineInstr::FrameSetup))
18855f757f3fSDimitry Andric       return false;
18865f757f3fSDimitry Andric     unsigned Opc = MBBI->getOpcode();
18875f757f3fSDimitry Andric     return Opc == X86::PUSH32r || Opc == X86::PUSH64r || Opc == X86::PUSHP64r ||
18885f757f3fSDimitry Andric            Opc == X86::PUSH2 || Opc == X86::PUSH2P;
18895f757f3fSDimitry Andric   };
18900b57cec5SDimitry Andric 
18915f757f3fSDimitry Andric   while (IsCSPush(MBBI)) {
18920b57cec5SDimitry Andric     PushedRegs = true;
18938bcb0991SDimitry Andric     Register Reg = MBBI->getOperand(0).getReg();
18945f757f3fSDimitry Andric     LastCSPush = MBBI;
18950b57cec5SDimitry Andric     ++MBBI;
18965f757f3fSDimitry Andric     unsigned Opc = LastCSPush->getOpcode();
18970b57cec5SDimitry Andric 
18980b57cec5SDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
18990b57cec5SDimitry Andric       // Mark callee-saved push instruction.
19000b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
19010b57cec5SDimitry Andric       assert(StackSize);
19025f757f3fSDimitry Andric       // Compared to push, push2 introduces more stack offset (one more
19035f757f3fSDimitry Andric       // register).
19045f757f3fSDimitry Andric       if (Opc == X86::PUSH2 || Opc == X86::PUSH2P)
19055f757f3fSDimitry Andric         StackOffset += stackGrowth;
19060b57cec5SDimitry Andric       BuildCFI(MBB, MBBI, DL,
190781ad6265SDimitry Andric                MCCFIInstruction::cfiDefCfaOffset(nullptr, -StackOffset),
190881ad6265SDimitry Andric                MachineInstr::FrameSetup);
19090b57cec5SDimitry Andric       StackOffset += stackGrowth;
19100b57cec5SDimitry Andric     }
19110b57cec5SDimitry Andric 
19120b57cec5SDimitry Andric     if (NeedsWinCFI) {
19130b57cec5SDimitry Andric       HasWinCFI = true;
19140b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
19150b57cec5SDimitry Andric           .addImm(Reg)
19160b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
19175f757f3fSDimitry Andric       if (Opc == X86::PUSH2 || Opc == X86::PUSH2P)
19185f757f3fSDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
19195f757f3fSDimitry Andric             .addImm(LastCSPush->getOperand(1).getReg())
19205f757f3fSDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
19210b57cec5SDimitry Andric     }
19220b57cec5SDimitry Andric   }
19230b57cec5SDimitry Andric 
19240b57cec5SDimitry Andric   // Realign stack after we pushed callee-saved registers (so that we'll be
19250b57cec5SDimitry Andric   // able to calculate their offsets from the frame pointer).
19260b57cec5SDimitry Andric   // Don't do this for Win64, it needs to realign the stack after the prologue.
192706c3fb27SDimitry Andric   if (!IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF) &&
192806c3fb27SDimitry Andric       !ArgBaseReg.isValid()) {
19290b57cec5SDimitry Andric     assert(HasFP && "There should be a frame pointer if stack is realigned.");
19300b57cec5SDimitry Andric     BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
19310b57cec5SDimitry Andric 
19320b57cec5SDimitry Andric     if (NeedsWinCFI) {
19330b57cec5SDimitry Andric       HasWinCFI = true;
19340b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlign))
19350b57cec5SDimitry Andric           .addImm(MaxAlign)
19360b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
19370b57cec5SDimitry Andric     }
19380b57cec5SDimitry Andric   }
19390b57cec5SDimitry Andric 
19400b57cec5SDimitry Andric   // If there is an SUB32ri of ESP immediately before this instruction, merge
19410b57cec5SDimitry Andric   // the two. This can be the case when tail call elimination is enabled and
19420b57cec5SDimitry Andric   // the callee has more arguments then the caller.
19430b57cec5SDimitry Andric   NumBytes -= mergeSPUpdates(MBB, MBBI, true);
19440b57cec5SDimitry Andric 
19450b57cec5SDimitry Andric   // Adjust stack pointer: ESP -= numbytes.
19460b57cec5SDimitry Andric 
19470b57cec5SDimitry Andric   // Windows and cygwin/mingw require a prologue helper routine when allocating
19480b57cec5SDimitry Andric   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
19490b57cec5SDimitry Andric   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
19500b57cec5SDimitry Andric   // stack and adjust the stack pointer in one go.  The 64-bit version of
19510b57cec5SDimitry Andric   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
19520b57cec5SDimitry Andric   // responsible for adjusting the stack pointer.  Touching the stack at 4K
19530b57cec5SDimitry Andric   // increments is necessary to ensure that the guard pages used by the OS
19540b57cec5SDimitry Andric   // virtual memory manager are allocated in correct sequence.
19550b57cec5SDimitry Andric   uint64_t AlignedNumBytes = NumBytes;
1956fe6060f1SDimitry Andric   if (IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF))
19570b57cec5SDimitry Andric     AlignedNumBytes = alignTo(AlignedNumBytes, MaxAlign);
19585ffd83dbSDimitry Andric   if (AlignedNumBytes >= StackProbeSize && EmitStackProbeCall) {
19590b57cec5SDimitry Andric     assert(!X86FI->getUsesRedZone() &&
19600b57cec5SDimitry Andric            "The Red Zone is not accounted for in stack probes");
19610b57cec5SDimitry Andric 
19620b57cec5SDimitry Andric     // Check whether EAX is livein for this block.
19630b57cec5SDimitry Andric     bool isEAXAlive = isEAXLiveIn(MBB);
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric     if (isEAXAlive) {
19660b57cec5SDimitry Andric       if (Is64Bit) {
19670b57cec5SDimitry Andric         // Save RAX
19680b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH64r))
19690b57cec5SDimitry Andric             .addReg(X86::RAX, RegState::Kill)
19700b57cec5SDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
19710b57cec5SDimitry Andric       } else {
19720b57cec5SDimitry Andric         // Save EAX
19730b57cec5SDimitry Andric         BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
19740b57cec5SDimitry Andric             .addReg(X86::EAX, RegState::Kill)
19750b57cec5SDimitry Andric             .setMIFlag(MachineInstr::FrameSetup);
19760b57cec5SDimitry Andric       }
19770b57cec5SDimitry Andric     }
19780b57cec5SDimitry Andric 
19790b57cec5SDimitry Andric     if (Is64Bit) {
19800b57cec5SDimitry Andric       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
19810b57cec5SDimitry Andric       // Function prologue is responsible for adjusting the stack pointer.
1982480093f4SDimitry Andric       int64_t Alloc = isEAXAlive ? NumBytes - 8 : NumBytes;
198304eeddc0SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(getMOVriOpcode(Is64Bit, Alloc)), X86::RAX)
19840b57cec5SDimitry Andric           .addImm(Alloc)
19850b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
19860b57cec5SDimitry Andric     } else {
19870b57cec5SDimitry Andric       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
19880b57cec5SDimitry Andric       // We'll also use 4 already allocated bytes for EAX.
19890b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
19900b57cec5SDimitry Andric           .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
19910b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
19920b57cec5SDimitry Andric     }
19930b57cec5SDimitry Andric 
19940b57cec5SDimitry Andric     // Call __chkstk, __chkstk_ms, or __alloca.
19950b57cec5SDimitry Andric     emitStackProbe(MF, MBB, MBBI, DL, true);
19960b57cec5SDimitry Andric 
19970b57cec5SDimitry Andric     if (isEAXAlive) {
19980b57cec5SDimitry Andric       // Restore RAX/EAX
19990b57cec5SDimitry Andric       MachineInstr *MI;
20000b57cec5SDimitry Andric       if (Is64Bit)
20010b57cec5SDimitry Andric         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV64rm), X86::RAX),
20020b57cec5SDimitry Andric                           StackPtr, false, NumBytes - 8);
20030b57cec5SDimitry Andric       else
20040b57cec5SDimitry Andric         MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX),
20050b57cec5SDimitry Andric                           StackPtr, false, NumBytes - 4);
20060b57cec5SDimitry Andric       MI->setFlag(MachineInstr::FrameSetup);
20070b57cec5SDimitry Andric       MBB.insert(MBBI, MI);
20080b57cec5SDimitry Andric     }
20090b57cec5SDimitry Andric   } else if (NumBytes) {
20100b57cec5SDimitry Andric     emitSPUpdate(MBB, MBBI, DL, -(int64_t)NumBytes, /*InEpilogue=*/false);
20110b57cec5SDimitry Andric   }
20120b57cec5SDimitry Andric 
20130b57cec5SDimitry Andric   if (NeedsWinCFI && NumBytes) {
20140b57cec5SDimitry Andric     HasWinCFI = true;
20150b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
20160b57cec5SDimitry Andric         .addImm(NumBytes)
20170b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
20180b57cec5SDimitry Andric   }
20190b57cec5SDimitry Andric 
20200b57cec5SDimitry Andric   int SEHFrameOffset = 0;
20210b57cec5SDimitry Andric   unsigned SPOrEstablisher;
20220b57cec5SDimitry Andric   if (IsFunclet) {
20230b57cec5SDimitry Andric     if (IsClrFunclet) {
20240b57cec5SDimitry Andric       // The establisher parameter passed to a CLR funclet is actually a pointer
20250b57cec5SDimitry Andric       // to the (mostly empty) frame of its nearest enclosing funclet; we have
20260b57cec5SDimitry Andric       // to find the root function establisher frame by loading the PSPSym from
20270b57cec5SDimitry Andric       // the intermediate frame.
20280b57cec5SDimitry Andric       unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
20290b57cec5SDimitry Andric       MachinePointerInfo NoInfo;
20300b57cec5SDimitry Andric       MBB.addLiveIn(Establisher);
20310b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher),
20320b57cec5SDimitry Andric                    Establisher, false, PSPSlotOffset)
20330b57cec5SDimitry Andric           .addMemOperand(MF.getMachineMemOperand(
20345ffd83dbSDimitry Andric               NoInfo, MachineMemOperand::MOLoad, SlotSize, Align(SlotSize)));
20350b57cec5SDimitry Andric       ;
20360b57cec5SDimitry Andric       // Save the root establisher back into the current funclet's (mostly
20370b57cec5SDimitry Andric       // empty) frame, in case a sub-funclet or the GC needs it.
20380b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
20390b57cec5SDimitry Andric                    false, PSPSlotOffset)
20400b57cec5SDimitry Andric           .addReg(Establisher)
20415ffd83dbSDimitry Andric           .addMemOperand(MF.getMachineMemOperand(
20425ffd83dbSDimitry Andric               NoInfo,
20435ffd83dbSDimitry Andric               MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
20445ffd83dbSDimitry Andric               SlotSize, Align(SlotSize)));
20450b57cec5SDimitry Andric     }
20460b57cec5SDimitry Andric     SPOrEstablisher = Establisher;
20470b57cec5SDimitry Andric   } else {
20480b57cec5SDimitry Andric     SPOrEstablisher = StackPtr;
20490b57cec5SDimitry Andric   }
20500b57cec5SDimitry Andric 
20510b57cec5SDimitry Andric   if (IsWin64Prologue && HasFP) {
20520b57cec5SDimitry Andric     // Set RBP to a small fixed offset from RSP. In the funclet case, we base
20530b57cec5SDimitry Andric     // this calculation on the incoming establisher, which holds the value of
20540b57cec5SDimitry Andric     // RSP from the parent frame at the end of the prologue.
20550b57cec5SDimitry Andric     SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes);
20560b57cec5SDimitry Andric     if (SEHFrameOffset)
20570b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
20580b57cec5SDimitry Andric                    SPOrEstablisher, false, SEHFrameOffset);
20590b57cec5SDimitry Andric     else
20600b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr)
20610b57cec5SDimitry Andric           .addReg(SPOrEstablisher);
20620b57cec5SDimitry Andric 
20630b57cec5SDimitry Andric     // If this is not a funclet, emit the CFI describing our frame pointer.
20640b57cec5SDimitry Andric     if (NeedsWinCFI && !IsFunclet) {
20650b57cec5SDimitry Andric       assert(!NeedsWinFPO && "this setframe incompatible with FPO data");
20660b57cec5SDimitry Andric       HasWinCFI = true;
20670b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
20680b57cec5SDimitry Andric           .addImm(FramePtr)
20690b57cec5SDimitry Andric           .addImm(SEHFrameOffset)
20700b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
20710b57cec5SDimitry Andric       if (isAsynchronousEHPersonality(Personality))
20720b57cec5SDimitry Andric         MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset;
20730b57cec5SDimitry Andric     }
20740b57cec5SDimitry Andric   } else if (IsFunclet && STI.is32Bit()) {
20750b57cec5SDimitry Andric     // Reset EBP / ESI to something good for funclets.
20760b57cec5SDimitry Andric     MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL);
20770b57cec5SDimitry Andric     // If we're a catch funclet, we can be returned to via catchret. Save ESP
20780b57cec5SDimitry Andric     // into the registration node so that the runtime will restore it for us.
20790b57cec5SDimitry Andric     if (!MBB.isCleanupFuncletEntry()) {
20800b57cec5SDimitry Andric       assert(Personality == EHPersonality::MSVC_CXX);
20815ffd83dbSDimitry Andric       Register FrameReg;
20820b57cec5SDimitry Andric       int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex;
2083e8d8bef9SDimitry Andric       int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg).getFixed();
20840b57cec5SDimitry Andric       // ESP is the first field, so no extra displacement is needed.
20850b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg,
20860b57cec5SDimitry Andric                    false, EHRegOffset)
20870b57cec5SDimitry Andric           .addReg(X86::ESP);
20880b57cec5SDimitry Andric     }
20890b57cec5SDimitry Andric   }
20900b57cec5SDimitry Andric 
20910b57cec5SDimitry Andric   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
20920b57cec5SDimitry Andric     const MachineInstr &FrameInstr = *MBBI;
20930b57cec5SDimitry Andric     ++MBBI;
20940b57cec5SDimitry Andric 
20950b57cec5SDimitry Andric     if (NeedsWinCFI) {
20960b57cec5SDimitry Andric       int FI;
20970fca6ea1SDimitry Andric       if (Register Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
20980b57cec5SDimitry Andric         if (X86::FR64RegClass.contains(Reg)) {
2099c14a5a88SDimitry Andric           int Offset;
21005ffd83dbSDimitry Andric           Register IgnoredFrameReg;
2101c14a5a88SDimitry Andric           if (IsWin64Prologue && IsFunclet)
2102c14a5a88SDimitry Andric             Offset = getWin64EHFrameIndexRef(MF, FI, IgnoredFrameReg);
2103c14a5a88SDimitry Andric           else
2104e8d8bef9SDimitry Andric             Offset =
2105e8d8bef9SDimitry Andric                 getFrameIndexReference(MF, FI, IgnoredFrameReg).getFixed() +
2106c14a5a88SDimitry Andric                 SEHFrameOffset;
21070b57cec5SDimitry Andric 
21080b57cec5SDimitry Andric           HasWinCFI = true;
21090b57cec5SDimitry Andric           assert(!NeedsWinFPO && "SEH_SaveXMM incompatible with FPO data");
21100b57cec5SDimitry Andric           BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
21110b57cec5SDimitry Andric               .addImm(Reg)
21120b57cec5SDimitry Andric               .addImm(Offset)
21130b57cec5SDimitry Andric               .setMIFlag(MachineInstr::FrameSetup);
21140b57cec5SDimitry Andric         }
21150b57cec5SDimitry Andric       }
21160b57cec5SDimitry Andric     }
21170b57cec5SDimitry Andric   }
21180b57cec5SDimitry Andric 
21190b57cec5SDimitry Andric   if (NeedsWinCFI && HasWinCFI)
21200b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
21210b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
21220b57cec5SDimitry Andric 
21230b57cec5SDimitry Andric   if (FnHasClrFunclet && !IsFunclet) {
21240b57cec5SDimitry Andric     // Save the so-called Initial-SP (i.e. the value of the stack pointer
21250b57cec5SDimitry Andric     // immediately after the prolog)  into the PSPSlot so that funclets
21260b57cec5SDimitry Andric     // and the GC can recover it.
21270b57cec5SDimitry Andric     unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
21280b57cec5SDimitry Andric     auto PSPInfo = MachinePointerInfo::getFixedStack(
21290b57cec5SDimitry Andric         MF, MF.getWinEHFuncInfo()->PSPSymFrameIdx);
21300b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false,
21310b57cec5SDimitry Andric                  PSPSlotOffset)
21320b57cec5SDimitry Andric         .addReg(StackPtr)
21330b57cec5SDimitry Andric         .addMemOperand(MF.getMachineMemOperand(
21340b57cec5SDimitry Andric             PSPInfo, MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
21355ffd83dbSDimitry Andric             SlotSize, Align(SlotSize)));
21360b57cec5SDimitry Andric   }
21370b57cec5SDimitry Andric 
21380b57cec5SDimitry Andric   // Realign stack after we spilled callee-saved registers (so that we'll be
21390b57cec5SDimitry Andric   // able to calculate their offsets from the frame pointer).
21400b57cec5SDimitry Andric   // Win64 requires aligning the stack after the prologue.
2141fe6060f1SDimitry Andric   if (IsWin64Prologue && TRI->hasStackRealignment(MF)) {
21420b57cec5SDimitry Andric     assert(HasFP && "There should be a frame pointer if stack is realigned.");
21430b57cec5SDimitry Andric     BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign);
21440b57cec5SDimitry Andric   }
21450b57cec5SDimitry Andric 
21460b57cec5SDimitry Andric   // We already dealt with stack realignment and funclets above.
21470b57cec5SDimitry Andric   if (IsFunclet && STI.is32Bit())
21480b57cec5SDimitry Andric     return;
21490b57cec5SDimitry Andric 
21500b57cec5SDimitry Andric   // If we need a base pointer, set it up here. It's whatever the value
21510b57cec5SDimitry Andric   // of the stack pointer is at this point. Any variable size objects
21520b57cec5SDimitry Andric   // will be allocated after this, so we can still use the base pointer
21530b57cec5SDimitry Andric   // to reference locals.
21540b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF)) {
21550b57cec5SDimitry Andric     // Update the base pointer with the current stack pointer.
21560b57cec5SDimitry Andric     unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
21570b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
21580b57cec5SDimitry Andric         .addReg(SPOrEstablisher)
21590b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
21600b57cec5SDimitry Andric     if (X86FI->getRestoreBasePointer()) {
21610b57cec5SDimitry Andric       // Stash value of base pointer.  Saving RSP instead of EBP shortens
21620b57cec5SDimitry Andric       // dependence chain. Used by SjLj EH.
21630b57cec5SDimitry Andric       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
21645f757f3fSDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), FramePtr, true,
21655f757f3fSDimitry Andric                    X86FI->getRestoreBasePointerOffset())
21660b57cec5SDimitry Andric           .addReg(SPOrEstablisher)
21670b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
21680b57cec5SDimitry Andric     }
21690b57cec5SDimitry Andric 
21700b57cec5SDimitry Andric     if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
21710b57cec5SDimitry Andric       // Stash the value of the frame pointer relative to the base pointer for
21720b57cec5SDimitry Andric       // Win32 EH. This supports Win32 EH, which does the inverse of the above:
21730b57cec5SDimitry Andric       // it recovers the frame pointer from the base pointer rather than the
21740b57cec5SDimitry Andric       // other way around.
21750b57cec5SDimitry Andric       unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
21765ffd83dbSDimitry Andric       Register UsedReg;
21770b57cec5SDimitry Andric       int Offset =
2178e8d8bef9SDimitry Andric           getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg)
2179e8d8bef9SDimitry Andric               .getFixed();
21800b57cec5SDimitry Andric       assert(UsedReg == BasePtr);
21810b57cec5SDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset)
21820b57cec5SDimitry Andric           .addReg(FramePtr)
21830b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
21840b57cec5SDimitry Andric     }
21850b57cec5SDimitry Andric   }
218606c3fb27SDimitry Andric   if (ArgBaseReg.isValid()) {
218706c3fb27SDimitry Andric     // Save argument base pointer.
218806c3fb27SDimitry Andric     auto *MI = X86FI->getStackPtrSaveMI();
218906c3fb27SDimitry Andric     int FI = MI->getOperand(1).getIndex();
219006c3fb27SDimitry Andric     unsigned MOVmr = Is64Bit ? X86::MOV64mr : X86::MOV32mr;
219106c3fb27SDimitry Andric     // movl    %basereg, offset(%ebp)
219206c3fb27SDimitry Andric     addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), FI)
219306c3fb27SDimitry Andric         .addReg(ArgBaseReg)
219406c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
219506c3fb27SDimitry Andric   }
21960b57cec5SDimitry Andric 
21970b57cec5SDimitry Andric   if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
21980b57cec5SDimitry Andric     // Mark end of stack pointer adjustment.
21990b57cec5SDimitry Andric     if (!HasFP && NumBytes) {
22000b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
22010b57cec5SDimitry Andric       assert(StackSize);
22025ffd83dbSDimitry Andric       BuildCFI(
22035ffd83dbSDimitry Andric           MBB, MBBI, DL,
220481ad6265SDimitry Andric           MCCFIInstruction::cfiDefCfaOffset(nullptr, StackSize - stackGrowth),
220581ad6265SDimitry Andric           MachineInstr::FrameSetup);
22060b57cec5SDimitry Andric     }
22070b57cec5SDimitry Andric 
22080b57cec5SDimitry Andric     // Emit DWARF info specifying the offsets of the callee-saved registers.
22095ffd83dbSDimitry Andric     emitCalleeSavedFrameMoves(MBB, MBBI, DL, true);
22100b57cec5SDimitry Andric   }
22110b57cec5SDimitry Andric 
22120b57cec5SDimitry Andric   // X86 Interrupt handling function cannot assume anything about the direction
22130b57cec5SDimitry Andric   // flag (DF in EFLAGS register). Clear this flag by creating "cld" instruction
22140b57cec5SDimitry Andric   // in each prologue of interrupt handler function.
22150b57cec5SDimitry Andric   //
22160fca6ea1SDimitry Andric   // Create "cld" instruction only in these cases:
22170b57cec5SDimitry Andric   // 1. The interrupt handling function uses any of the "rep" instructions.
22180b57cec5SDimitry Andric   // 2. Interrupt handling function calls another function.
22190fca6ea1SDimitry Andric   // 3. If there are any inline asm blocks, as we do not know what they do
22200b57cec5SDimitry Andric   //
22210fca6ea1SDimitry Andric   // TODO: We should also emit cld if we detect the use of std, but as of now,
22220fca6ea1SDimitry Andric   // the compiler does not even emit that instruction or even define it, so in
22230fca6ea1SDimitry Andric   // practice, this would only happen with inline asm, which we cover anyway.
22240fca6ea1SDimitry Andric   if (Fn.getCallingConv() == CallingConv::X86_INTR) {
22250fca6ea1SDimitry Andric     bool NeedsCLD = false;
22260fca6ea1SDimitry Andric 
22270fca6ea1SDimitry Andric     for (const MachineBasicBlock &B : MF) {
22280fca6ea1SDimitry Andric       for (const MachineInstr &MI : B) {
22290fca6ea1SDimitry Andric         if (MI.isCall()) {
22300fca6ea1SDimitry Andric           NeedsCLD = true;
22310fca6ea1SDimitry Andric           break;
22320fca6ea1SDimitry Andric         }
22330fca6ea1SDimitry Andric 
22340fca6ea1SDimitry Andric         if (isOpcodeRep(MI.getOpcode())) {
22350fca6ea1SDimitry Andric           NeedsCLD = true;
22360fca6ea1SDimitry Andric           break;
22370fca6ea1SDimitry Andric         }
22380fca6ea1SDimitry Andric 
22390fca6ea1SDimitry Andric         if (MI.isInlineAsm()) {
22400fca6ea1SDimitry Andric           // TODO: Parse asm for rep instructions or call sites?
22410fca6ea1SDimitry Andric           // For now, let's play it safe and emit a cld instruction
22420fca6ea1SDimitry Andric           // just in case.
22430fca6ea1SDimitry Andric           NeedsCLD = true;
22440fca6ea1SDimitry Andric           break;
22450fca6ea1SDimitry Andric         }
22460fca6ea1SDimitry Andric       }
22470fca6ea1SDimitry Andric     }
22480fca6ea1SDimitry Andric 
22490fca6ea1SDimitry Andric     if (NeedsCLD) {
22500b57cec5SDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::CLD))
22510b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
22520fca6ea1SDimitry Andric     }
22530fca6ea1SDimitry Andric   }
22540b57cec5SDimitry Andric 
22550b57cec5SDimitry Andric   // At this point we know if the function has WinCFI or not.
22560b57cec5SDimitry Andric   MF.setHasWinCFI(HasWinCFI);
22570b57cec5SDimitry Andric }
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric bool X86FrameLowering::canUseLEAForSPInEpilogue(
22600b57cec5SDimitry Andric     const MachineFunction &MF) const {
22610b57cec5SDimitry Andric   // We can't use LEA instructions for adjusting the stack pointer if we don't
22620b57cec5SDimitry Andric   // have a frame pointer in the Win64 ABI.  Only ADD instructions may be used
22630b57cec5SDimitry Andric   // to deallocate the stack.
22640b57cec5SDimitry Andric   // This means that we can use LEA for SP in two situations:
22650b57cec5SDimitry Andric   // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
22660b57cec5SDimitry Andric   // 2. We *have* a frame pointer which means we are permitted to use LEA.
22670b57cec5SDimitry Andric   return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
22680b57cec5SDimitry Andric }
22690b57cec5SDimitry Andric 
22700b57cec5SDimitry Andric static bool isFuncletReturnInstr(MachineInstr &MI) {
22710b57cec5SDimitry Andric   switch (MI.getOpcode()) {
22720b57cec5SDimitry Andric   case X86::CATCHRET:
22730b57cec5SDimitry Andric   case X86::CLEANUPRET:
22740b57cec5SDimitry Andric     return true;
22750b57cec5SDimitry Andric   default:
22760b57cec5SDimitry Andric     return false;
22770b57cec5SDimitry Andric   }
22780b57cec5SDimitry Andric   llvm_unreachable("impossible");
22790b57cec5SDimitry Andric }
22800b57cec5SDimitry Andric 
22810b57cec5SDimitry Andric // CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
22820b57cec5SDimitry Andric // stack. It holds a pointer to the bottom of the root function frame.  The
22830b57cec5SDimitry Andric // establisher frame pointer passed to a nested funclet may point to the
22840b57cec5SDimitry Andric // (mostly empty) frame of its parent funclet, but it will need to find
22850b57cec5SDimitry Andric // the frame of the root function to access locals.  To facilitate this,
22860b57cec5SDimitry Andric // every funclet copies the pointer to the bottom of the root function
22870b57cec5SDimitry Andric // frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
22880b57cec5SDimitry Andric // same offset for the PSPSym in the root function frame that's used in the
22890b57cec5SDimitry Andric // funclets' frames allows each funclet to dynamically accept any ancestor
22900b57cec5SDimitry Andric // frame as its establisher argument (the runtime doesn't guarantee the
22910b57cec5SDimitry Andric // immediate parent for some reason lost to history), and also allows the GC,
22920b57cec5SDimitry Andric // which uses the PSPSym for some bookkeeping, to find it in any funclet's
22930b57cec5SDimitry Andric // frame with only a single offset reported for the entire method.
22940b57cec5SDimitry Andric unsigned
22950b57cec5SDimitry Andric X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
22960b57cec5SDimitry Andric   const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
22975ffd83dbSDimitry Andric   Register SPReg;
22980b57cec5SDimitry Andric   int Offset = getFrameIndexReferencePreferSP(MF, Info.PSPSymFrameIdx, SPReg,
2299e8d8bef9SDimitry Andric                                               /*IgnoreSPUpdates*/ true)
2300e8d8bef9SDimitry Andric                    .getFixed();
23010b57cec5SDimitry Andric   assert(Offset >= 0 && SPReg == TRI->getStackRegister());
23020b57cec5SDimitry Andric   return static_cast<unsigned>(Offset);
23030b57cec5SDimitry Andric }
23040b57cec5SDimitry Andric 
23050b57cec5SDimitry Andric unsigned
23060b57cec5SDimitry Andric X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
2307c14a5a88SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
23080b57cec5SDimitry Andric   // This is the size of the pushed CSRs.
2309c14a5a88SDimitry Andric   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2310c14a5a88SDimitry Andric   // This is the size of callee saved XMMs.
2311c14a5a88SDimitry Andric   const auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
23125f757f3fSDimitry Andric   unsigned XMMSize =
23135f757f3fSDimitry Andric       WinEHXMMSlotInfo.size() * TRI->getSpillSize(X86::VR128RegClass);
23140b57cec5SDimitry Andric   // This is the amount of stack a funclet needs to allocate.
23150b57cec5SDimitry Andric   unsigned UsedSize;
23160b57cec5SDimitry Andric   EHPersonality Personality =
23170b57cec5SDimitry Andric       classifyEHPersonality(MF.getFunction().getPersonalityFn());
23180b57cec5SDimitry Andric   if (Personality == EHPersonality::CoreCLR) {
23190b57cec5SDimitry Andric     // CLR funclets need to hold enough space to include the PSPSym, at the
23200b57cec5SDimitry Andric     // same offset from the stack pointer (immediately after the prolog) as it
23210b57cec5SDimitry Andric     // resides at in the main function.
23220b57cec5SDimitry Andric     UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
23230b57cec5SDimitry Andric   } else {
23240b57cec5SDimitry Andric     // Other funclets just need enough stack for outgoing call arguments.
23250b57cec5SDimitry Andric     UsedSize = MF.getFrameInfo().getMaxCallFrameSize();
23260b57cec5SDimitry Andric   }
23270b57cec5SDimitry Andric   // RBP is not included in the callee saved register block. After pushing RBP,
23280b57cec5SDimitry Andric   // everything is 16 byte aligned. Everything we allocate before an outgoing
23290b57cec5SDimitry Andric   // call must also be 16 byte aligned.
23305ffd83dbSDimitry Andric   unsigned FrameSizeMinusRBP = alignTo(CSSize + UsedSize, getStackAlign());
23310b57cec5SDimitry Andric   // Subtract out the size of the callee saved registers. This is how much stack
23320b57cec5SDimitry Andric   // each funclet will allocate.
2333c14a5a88SDimitry Andric   return FrameSizeMinusRBP + XMMSize - CSSize;
23340b57cec5SDimitry Andric }
23350b57cec5SDimitry Andric 
23360b57cec5SDimitry Andric static bool isTailCallOpcode(unsigned Opc) {
23370b57cec5SDimitry Andric   return Opc == X86::TCRETURNri || Opc == X86::TCRETURNdi ||
23385f757f3fSDimitry Andric          Opc == X86::TCRETURNmi || Opc == X86::TCRETURNri64 ||
23395f757f3fSDimitry Andric          Opc == X86::TCRETURNdi64 || Opc == X86::TCRETURNmi64;
23400b57cec5SDimitry Andric }
23410b57cec5SDimitry Andric 
23420b57cec5SDimitry Andric void X86FrameLowering::emitEpilogue(MachineFunction &MF,
23430b57cec5SDimitry Andric                                     MachineBasicBlock &MBB) const {
23440b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
23450b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
23460b57cec5SDimitry Andric   MachineBasicBlock::iterator Terminator = MBB.getFirstTerminator();
23470b57cec5SDimitry Andric   MachineBasicBlock::iterator MBBI = Terminator;
23480b57cec5SDimitry Andric   DebugLoc DL;
23490b57cec5SDimitry Andric   if (MBBI != MBB.end())
23500b57cec5SDimitry Andric     DL = MBBI->getDebugLoc();
23510b57cec5SDimitry Andric   // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
23520b57cec5SDimitry Andric   const bool Is64BitILP32 = STI.isTarget64BitILP32();
23538bcb0991SDimitry Andric   Register FramePtr = TRI->getFrameRegister(MF);
2354e8d8bef9SDimitry Andric   Register MachineFramePtr =
23558bcb0991SDimitry Andric       Is64BitILP32 ? Register(getX86SubSuperRegister(FramePtr, 64)) : FramePtr;
23560b57cec5SDimitry Andric 
23570b57cec5SDimitry Andric   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
23580b57cec5SDimitry Andric   bool NeedsWin64CFI =
23590b57cec5SDimitry Andric       IsWin64Prologue && MF.getFunction().needsUnwindTableEntry();
23600b57cec5SDimitry Andric   bool IsFunclet = MBBI == MBB.end() ? false : isFuncletReturnInstr(*MBBI);
23610b57cec5SDimitry Andric 
23620b57cec5SDimitry Andric   // Get the number of bytes to allocate from the FrameInfo.
23630b57cec5SDimitry Andric   uint64_t StackSize = MFI.getStackSize();
23640b57cec5SDimitry Andric   uint64_t MaxAlign = calculateMaxStackAlign(MF);
23650b57cec5SDimitry Andric   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2366349cc55cSDimitry Andric   unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
23670b57cec5SDimitry Andric   bool HasFP = hasFP(MF);
23680b57cec5SDimitry Andric   uint64_t NumBytes = 0;
23690b57cec5SDimitry Andric 
2370480093f4SDimitry Andric   bool NeedsDwarfCFI = (!MF.getTarget().getTargetTriple().isOSDarwin() &&
23710b57cec5SDimitry Andric                         !MF.getTarget().getTargetTriple().isOSWindows()) &&
2372480093f4SDimitry Andric                        MF.needsFrameMoves();
23730b57cec5SDimitry Andric 
237406c3fb27SDimitry Andric   Register ArgBaseReg;
237506c3fb27SDimitry Andric   if (auto *MI = X86FI->getStackPtrSaveMI()) {
237606c3fb27SDimitry Andric     unsigned Opc = X86::LEA32r;
237706c3fb27SDimitry Andric     Register StackReg = X86::ESP;
237806c3fb27SDimitry Andric     ArgBaseReg = MI->getOperand(0).getReg();
237906c3fb27SDimitry Andric     if (STI.is64Bit()) {
238006c3fb27SDimitry Andric       Opc = X86::LEA64r;
238106c3fb27SDimitry Andric       StackReg = X86::RSP;
238206c3fb27SDimitry Andric     }
238306c3fb27SDimitry Andric     // leal    -4(%basereg), %esp
238406c3fb27SDimitry Andric     // .cfi_def_cfa %esp, 4
238506c3fb27SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(Opc), StackReg)
238606c3fb27SDimitry Andric         .addUse(ArgBaseReg)
238706c3fb27SDimitry Andric         .addImm(1)
238806c3fb27SDimitry Andric         .addUse(X86::NoRegister)
238906c3fb27SDimitry Andric         .addImm(-(int64_t)SlotSize)
239006c3fb27SDimitry Andric         .addUse(X86::NoRegister)
239106c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
239206c3fb27SDimitry Andric     if (NeedsDwarfCFI) {
239306c3fb27SDimitry Andric       unsigned DwarfStackPtr = TRI->getDwarfRegNum(StackReg, true);
239406c3fb27SDimitry Andric       BuildCFI(MBB, MBBI, DL,
239506c3fb27SDimitry Andric                MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, SlotSize),
239606c3fb27SDimitry Andric                MachineInstr::FrameDestroy);
239706c3fb27SDimitry Andric       --MBBI;
239806c3fb27SDimitry Andric     }
239906c3fb27SDimitry Andric     --MBBI;
240006c3fb27SDimitry Andric   }
240106c3fb27SDimitry Andric 
24020b57cec5SDimitry Andric   if (IsFunclet) {
24030b57cec5SDimitry Andric     assert(HasFP && "EH funclets without FP not yet implemented");
24040b57cec5SDimitry Andric     NumBytes = getWinEHFuncletFrameSize(MF);
24050b57cec5SDimitry Andric   } else if (HasFP) {
24060b57cec5SDimitry Andric     // Calculate required stack adjustment.
24070b57cec5SDimitry Andric     uint64_t FrameSize = StackSize - SlotSize;
2408349cc55cSDimitry Andric     NumBytes = FrameSize - CSSize - TailCallArgReserveSize;
24090b57cec5SDimitry Andric 
24100b57cec5SDimitry Andric     // Callee-saved registers were pushed on stack before the stack was
24110b57cec5SDimitry Andric     // realigned.
2412fe6060f1SDimitry Andric     if (TRI->hasStackRealignment(MF) && !IsWin64Prologue)
24130b57cec5SDimitry Andric       NumBytes = alignTo(FrameSize, MaxAlign);
24140b57cec5SDimitry Andric   } else {
2415349cc55cSDimitry Andric     NumBytes = StackSize - CSSize - TailCallArgReserveSize;
24160b57cec5SDimitry Andric   }
24170b57cec5SDimitry Andric   uint64_t SEHStackAllocAmt = NumBytes;
24180b57cec5SDimitry Andric 
24195ffd83dbSDimitry Andric   // AfterPop is the position to insert .cfi_restore.
24205ffd83dbSDimitry Andric   MachineBasicBlock::iterator AfterPop = MBBI;
24210b57cec5SDimitry Andric   if (HasFP) {
2422fe6060f1SDimitry Andric     if (X86FI->hasSwiftAsyncContext()) {
2423fe6060f1SDimitry Andric       // Discard the context.
2424fe6060f1SDimitry Andric       int Offset = 16 + mergeSPUpdates(MBB, MBBI, true);
2425fe6060f1SDimitry Andric       emitSPUpdate(MBB, MBBI, DL, Offset, /*InEpilogue*/ true);
2426fe6060f1SDimitry Andric     }
24270b57cec5SDimitry Andric     // Pop EBP.
24285f757f3fSDimitry Andric     BuildMI(MBB, MBBI, DL,
24295f757f3fSDimitry Andric             TII.get(getPOPOpcode(MF.getSubtarget<X86Subtarget>())),
24300b57cec5SDimitry Andric             MachineFramePtr)
24310b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
2432fe6060f1SDimitry Andric 
2433fe6060f1SDimitry Andric     // We need to reset FP to its untagged state on return. Bit 60 is currently
2434fe6060f1SDimitry Andric     // used to show the presence of an extended frame.
2435fe6060f1SDimitry Andric     if (X86FI->hasSwiftAsyncContext()) {
24365f757f3fSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(X86::BTR64ri8), MachineFramePtr)
2437fe6060f1SDimitry Andric           .addUse(MachineFramePtr)
2438fe6060f1SDimitry Andric           .addImm(60)
2439fe6060f1SDimitry Andric           .setMIFlag(MachineInstr::FrameDestroy);
2440fe6060f1SDimitry Andric     }
2441fe6060f1SDimitry Andric 
24420b57cec5SDimitry Andric     if (NeedsDwarfCFI) {
244306c3fb27SDimitry Andric       if (!ArgBaseReg.isValid()) {
24440b57cec5SDimitry Andric         unsigned DwarfStackPtr =
24450b57cec5SDimitry Andric             TRI->getDwarfRegNum(Is64Bit ? X86::RSP : X86::ESP, true);
24465ffd83dbSDimitry Andric         BuildCFI(MBB, MBBI, DL,
244781ad6265SDimitry Andric                  MCCFIInstruction::cfiDefCfa(nullptr, DwarfStackPtr, SlotSize),
244881ad6265SDimitry Andric                  MachineInstr::FrameDestroy);
244906c3fb27SDimitry Andric       }
24505ffd83dbSDimitry Andric       if (!MBB.succ_empty() && !MBB.isReturnBlock()) {
24515ffd83dbSDimitry Andric         unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
24525ffd83dbSDimitry Andric         BuildCFI(MBB, AfterPop, DL,
245381ad6265SDimitry Andric                  MCCFIInstruction::createRestore(nullptr, DwarfFramePtr),
245481ad6265SDimitry Andric                  MachineInstr::FrameDestroy);
24555ffd83dbSDimitry Andric         --MBBI;
24565ffd83dbSDimitry Andric         --AfterPop;
24575ffd83dbSDimitry Andric       }
24580b57cec5SDimitry Andric       --MBBI;
24590b57cec5SDimitry Andric     }
24600b57cec5SDimitry Andric   }
24610b57cec5SDimitry Andric 
24620b57cec5SDimitry Andric   MachineBasicBlock::iterator FirstCSPop = MBBI;
24630b57cec5SDimitry Andric   // Skip the callee-saved pop instructions.
24640b57cec5SDimitry Andric   while (MBBI != MBB.begin()) {
24650b57cec5SDimitry Andric     MachineBasicBlock::iterator PI = std::prev(MBBI);
24660b57cec5SDimitry Andric     unsigned Opc = PI->getOpcode();
24670b57cec5SDimitry Andric 
24680b57cec5SDimitry Andric     if (Opc != X86::DBG_VALUE && !PI->isTerminator()) {
24695f757f3fSDimitry Andric       if (!PI->getFlag(MachineInstr::FrameDestroy) ||
24705f757f3fSDimitry Andric           (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::BTR64ri8 &&
24715f757f3fSDimitry Andric            Opc != X86::ADD64ri32 && Opc != X86::POPP64r && Opc != X86::POP2 &&
24725f757f3fSDimitry Andric            Opc != X86::POP2P && Opc != X86::LEA64r))
24730b57cec5SDimitry Andric         break;
24740b57cec5SDimitry Andric       FirstCSPop = PI;
24750b57cec5SDimitry Andric     }
24760b57cec5SDimitry Andric 
24770b57cec5SDimitry Andric     --MBBI;
24780b57cec5SDimitry Andric   }
247906c3fb27SDimitry Andric   if (ArgBaseReg.isValid()) {
248006c3fb27SDimitry Andric     // Restore argument base pointer.
248106c3fb27SDimitry Andric     auto *MI = X86FI->getStackPtrSaveMI();
248206c3fb27SDimitry Andric     int FI = MI->getOperand(1).getIndex();
248306c3fb27SDimitry Andric     unsigned MOVrm = Is64Bit ? X86::MOV64rm : X86::MOV32rm;
248406c3fb27SDimitry Andric     // movl   offset(%ebp), %basereg
248506c3fb27SDimitry Andric     addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(MOVrm), ArgBaseReg), FI)
248606c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
248706c3fb27SDimitry Andric   }
24880b57cec5SDimitry Andric   MBBI = FirstCSPop;
24890b57cec5SDimitry Andric 
24900b57cec5SDimitry Andric   if (IsFunclet && Terminator->getOpcode() == X86::CATCHRET)
24910b57cec5SDimitry Andric     emitCatchRetReturnValue(MBB, FirstCSPop, &*Terminator);
24920b57cec5SDimitry Andric 
24930b57cec5SDimitry Andric   if (MBBI != MBB.end())
24940b57cec5SDimitry Andric     DL = MBBI->getDebugLoc();
24950b57cec5SDimitry Andric   // If there is an ADD32ri or SUB32ri of ESP immediately before this
24960b57cec5SDimitry Andric   // instruction, merge the two instructions.
24970b57cec5SDimitry Andric   if (NumBytes || MFI.hasVarSizedObjects())
24980b57cec5SDimitry Andric     NumBytes += mergeSPUpdates(MBB, MBBI, true);
24990b57cec5SDimitry Andric 
25000b57cec5SDimitry Andric   // If dynamic alloca is used, then reset esp to point to the last callee-saved
25010b57cec5SDimitry Andric   // slot before popping them off! Same applies for the case, when stack was
25020b57cec5SDimitry Andric   // realigned. Don't do this if this was a funclet epilogue, since the funclets
25030b57cec5SDimitry Andric   // will not do realignment or dynamic stack allocation.
2504fe6060f1SDimitry Andric   if (((TRI->hasStackRealignment(MF)) || MFI.hasVarSizedObjects()) &&
25050b57cec5SDimitry Andric       !IsFunclet) {
2506fe6060f1SDimitry Andric     if (TRI->hasStackRealignment(MF))
25070b57cec5SDimitry Andric       MBBI = FirstCSPop;
25080b57cec5SDimitry Andric     unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
25090b57cec5SDimitry Andric     uint64_t LEAAmount =
25100b57cec5SDimitry Andric         IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
25110b57cec5SDimitry Andric 
2512fe6060f1SDimitry Andric     if (X86FI->hasSwiftAsyncContext())
2513fe6060f1SDimitry Andric       LEAAmount -= 16;
2514fe6060f1SDimitry Andric 
25150b57cec5SDimitry Andric     // There are only two legal forms of epilogue:
25160b57cec5SDimitry Andric     // - add SEHAllocationSize, %rsp
25170b57cec5SDimitry Andric     // - lea SEHAllocationSize(%FramePtr), %rsp
25180b57cec5SDimitry Andric     //
25190b57cec5SDimitry Andric     // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
25200b57cec5SDimitry Andric     // However, we may use this sequence if we have a frame pointer because the
25210b57cec5SDimitry Andric     // effects of the prologue can safely be undone.
25220b57cec5SDimitry Andric     if (LEAAmount != 0) {
25230b57cec5SDimitry Andric       unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
25245f757f3fSDimitry Andric       addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr), FramePtr,
25255f757f3fSDimitry Andric                    false, LEAAmount);
25260b57cec5SDimitry Andric       --MBBI;
25270b57cec5SDimitry Andric     } else {
25280b57cec5SDimitry Andric       unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
25295f757f3fSDimitry Andric       BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr).addReg(FramePtr);
25300b57cec5SDimitry Andric       --MBBI;
25310b57cec5SDimitry Andric     }
25320b57cec5SDimitry Andric   } else if (NumBytes) {
25330b57cec5SDimitry Andric     // Adjust stack pointer back: ESP += numbytes.
25340b57cec5SDimitry Andric     emitSPUpdate(MBB, MBBI, DL, NumBytes, /*InEpilogue=*/true);
2535349cc55cSDimitry Andric     if (!HasFP && NeedsDwarfCFI) {
25360b57cec5SDimitry Andric       // Define the current CFA rule to use the provided offset.
25375ffd83dbSDimitry Andric       BuildCFI(MBB, MBBI, DL,
2538349cc55cSDimitry Andric                MCCFIInstruction::cfiDefCfaOffset(
253981ad6265SDimitry Andric                    nullptr, CSSize + TailCallArgReserveSize + SlotSize),
254081ad6265SDimitry Andric                MachineInstr::FrameDestroy);
25410b57cec5SDimitry Andric     }
25420b57cec5SDimitry Andric     --MBBI;
25430b57cec5SDimitry Andric   }
25440b57cec5SDimitry Andric 
25450b57cec5SDimitry Andric   // Windows unwinder will not invoke function's exception handler if IP is
25460b57cec5SDimitry Andric   // either in prologue or in epilogue.  This behavior causes a problem when a
25470b57cec5SDimitry Andric   // call immediately precedes an epilogue, because the return address points
25480b57cec5SDimitry Andric   // into the epilogue.  To cope with that, we insert an epilogue marker here,
25490b57cec5SDimitry Andric   // then replace it with a 'nop' if it ends up immediately after a CALL in the
25500b57cec5SDimitry Andric   // final emitted code.
25510b57cec5SDimitry Andric   if (NeedsWin64CFI && MF.hasWinCFI())
25520b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
25530b57cec5SDimitry Andric 
2554349cc55cSDimitry Andric   if (!HasFP && NeedsDwarfCFI) {
25550b57cec5SDimitry Andric     MBBI = FirstCSPop;
2556*36b606aeSDimitry Andric     int64_t Offset = -(int64_t)CSSize - SlotSize;
25570b57cec5SDimitry Andric     // Mark callee-saved pop instruction.
25580b57cec5SDimitry Andric     // Define the current CFA rule to use the provided offset.
25590b57cec5SDimitry Andric     while (MBBI != MBB.end()) {
25600b57cec5SDimitry Andric       MachineBasicBlock::iterator PI = MBBI;
25610b57cec5SDimitry Andric       unsigned Opc = PI->getOpcode();
25620b57cec5SDimitry Andric       ++MBBI;
25635f757f3fSDimitry Andric       if (Opc == X86::POP32r || Opc == X86::POP64r || Opc == X86::POPP64r ||
25645f757f3fSDimitry Andric           Opc == X86::POP2 || Opc == X86::POP2P) {
25655f757f3fSDimitry Andric         Offset += SlotSize;
25665f757f3fSDimitry Andric         // Compared to pop, pop2 introduces more stack offset (one more
25675f757f3fSDimitry Andric         // register).
25685f757f3fSDimitry Andric         if (Opc == X86::POP2 || Opc == X86::POP2P)
25690b57cec5SDimitry Andric           Offset += SlotSize;
25700b57cec5SDimitry Andric         BuildCFI(MBB, MBBI, DL,
257181ad6265SDimitry Andric                  MCCFIInstruction::cfiDefCfaOffset(nullptr, -Offset),
257281ad6265SDimitry Andric                  MachineInstr::FrameDestroy);
25730b57cec5SDimitry Andric       }
25740b57cec5SDimitry Andric     }
25750b57cec5SDimitry Andric   }
25760b57cec5SDimitry Andric 
25775ffd83dbSDimitry Andric   // Emit DWARF info specifying the restores of the callee-saved registers.
25785ffd83dbSDimitry Andric   // For epilogue with return inside or being other block without successor,
25795ffd83dbSDimitry Andric   // no need to generate .cfi_restore for callee-saved registers.
2580349cc55cSDimitry Andric   if (NeedsDwarfCFI && !MBB.succ_empty())
25815ffd83dbSDimitry Andric     emitCalleeSavedFrameMoves(MBB, AfterPop, DL, false);
25825ffd83dbSDimitry Andric 
25830b57cec5SDimitry Andric   if (Terminator == MBB.end() || !isTailCallOpcode(Terminator->getOpcode())) {
25840b57cec5SDimitry Andric     // Add the return addr area delta back since we are not tail calling.
25850b57cec5SDimitry Andric     int Offset = -1 * X86FI->getTCReturnAddrDelta();
25860b57cec5SDimitry Andric     assert(Offset >= 0 && "TCDelta should never be positive");
25870b57cec5SDimitry Andric     if (Offset) {
25880b57cec5SDimitry Andric       // Check for possible merge with preceding ADD instruction.
25890b57cec5SDimitry Andric       Offset += mergeSPUpdates(MBB, Terminator, true);
25900b57cec5SDimitry Andric       emitSPUpdate(MBB, Terminator, DL, Offset, /*InEpilogue=*/true);
25910b57cec5SDimitry Andric     }
25920b57cec5SDimitry Andric   }
2593e8d8bef9SDimitry Andric 
2594e8d8bef9SDimitry Andric   // Emit tilerelease for AMX kernel.
25950fca6ea1SDimitry Andric   if (X86FI->getAMXProgModel() == AMXProgModelEnum::ManagedRA)
2596e8d8bef9SDimitry Andric     BuildMI(MBB, Terminator, DL, TII.get(X86::TILERELEASE));
25970b57cec5SDimitry Andric }
25980b57cec5SDimitry Andric 
2599e8d8bef9SDimitry Andric StackOffset X86FrameLowering::getFrameIndexReference(const MachineFunction &MF,
2600e8d8bef9SDimitry Andric                                                      int FI,
26015ffd83dbSDimitry Andric                                                      Register &FrameReg) const {
26020b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
26030b57cec5SDimitry Andric 
26040b57cec5SDimitry Andric   bool IsFixed = MFI.isFixedObjectIndex(FI);
26050b57cec5SDimitry Andric   // We can't calculate offset from frame pointer if the stack is realigned,
26060b57cec5SDimitry Andric   // so enforce usage of stack/base pointer.  The base pointer is used when we
26070b57cec5SDimitry Andric   // have dynamic allocas in addition to dynamic realignment.
26080b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF))
26090b57cec5SDimitry Andric     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getBaseRegister();
2610fe6060f1SDimitry Andric   else if (TRI->hasStackRealignment(MF))
26110b57cec5SDimitry Andric     FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getStackRegister();
26120b57cec5SDimitry Andric   else
26130b57cec5SDimitry Andric     FrameReg = TRI->getFrameRegister(MF);
26140b57cec5SDimitry Andric 
26150b57cec5SDimitry Andric   // Offset will hold the offset from the stack pointer at function entry to the
26160b57cec5SDimitry Andric   // object.
26170b57cec5SDimitry Andric   // We need to factor in additional offsets applied during the prologue to the
26180b57cec5SDimitry Andric   // frame, base, and stack pointer depending on which is used.
26190b57cec5SDimitry Andric   int Offset = MFI.getObjectOffset(FI) - getOffsetOfLocalArea();
26200b57cec5SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
26210b57cec5SDimitry Andric   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
26220b57cec5SDimitry Andric   uint64_t StackSize = MFI.getStackSize();
26230b57cec5SDimitry Andric   bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
26240b57cec5SDimitry Andric   int64_t FPDelta = 0;
26250b57cec5SDimitry Andric 
26260b57cec5SDimitry Andric   // In an x86 interrupt, remove the offset we added to account for the return
26270b57cec5SDimitry Andric   // address from any stack object allocated in the caller's frame. Interrupts
26280b57cec5SDimitry Andric   // do not have a standard return address. Fixed objects in the current frame,
26290b57cec5SDimitry Andric   // such as SSE register spills, should not get this treatment.
26300b57cec5SDimitry Andric   if (MF.getFunction().getCallingConv() == CallingConv::X86_INTR &&
26310b57cec5SDimitry Andric       Offset >= 0) {
26320b57cec5SDimitry Andric     Offset += getOffsetOfLocalArea();
26330b57cec5SDimitry Andric   }
26340b57cec5SDimitry Andric 
26350b57cec5SDimitry Andric   if (IsWin64Prologue) {
26360b57cec5SDimitry Andric     assert(!MFI.hasCalls() || (StackSize % 16) == 8);
26370b57cec5SDimitry Andric 
26380b57cec5SDimitry Andric     // Calculate required stack adjustment.
26390b57cec5SDimitry Andric     uint64_t FrameSize = StackSize - SlotSize;
26405f757f3fSDimitry Andric     // If required, include space for extra hidden slot for stashing base
26415f757f3fSDimitry Andric     // pointer.
26420b57cec5SDimitry Andric     if (X86FI->getRestoreBasePointer())
26430b57cec5SDimitry Andric       FrameSize += SlotSize;
26440b57cec5SDimitry Andric     uint64_t NumBytes = FrameSize - CSSize;
26450b57cec5SDimitry Andric 
26460b57cec5SDimitry Andric     uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
26470b57cec5SDimitry Andric     if (FI && FI == X86FI->getFAIndex())
2648e8d8bef9SDimitry Andric       return StackOffset::getFixed(-SEHFrameOffset);
26490b57cec5SDimitry Andric 
26500b57cec5SDimitry Andric     // FPDelta is the offset from the "traditional" FP location of the old base
26510b57cec5SDimitry Andric     // pointer followed by return address and the location required by the
26520b57cec5SDimitry Andric     // restricted Win64 prologue.
26530b57cec5SDimitry Andric     // Add FPDelta to all offsets below that go through the frame pointer.
26540b57cec5SDimitry Andric     FPDelta = FrameSize - SEHFrameOffset;
26550b57cec5SDimitry Andric     assert((!MFI.hasCalls() || (FPDelta % 16) == 0) &&
26560b57cec5SDimitry Andric            "FPDelta isn't aligned per the Win64 ABI!");
26570b57cec5SDimitry Andric   }
26580b57cec5SDimitry Andric 
2659349cc55cSDimitry Andric   if (FrameReg == TRI->getFramePtr()) {
2660349cc55cSDimitry Andric     // Skip saved EBP/RBP
26610b57cec5SDimitry Andric     Offset += SlotSize;
26620b57cec5SDimitry Andric 
2663349cc55cSDimitry Andric     // Account for restricted Windows prologue.
2664349cc55cSDimitry Andric     Offset += FPDelta;
2665349cc55cSDimitry Andric 
26660b57cec5SDimitry Andric     // Skip the RETADDR move area
26670b57cec5SDimitry Andric     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
26680b57cec5SDimitry Andric     if (TailCallReturnAddrDelta < 0)
26690b57cec5SDimitry Andric       Offset -= TailCallReturnAddrDelta;
2670349cc55cSDimitry Andric 
2671349cc55cSDimitry Andric     return StackOffset::getFixed(Offset);
26720b57cec5SDimitry Andric   }
26730b57cec5SDimitry Andric 
2674349cc55cSDimitry Andric   // FrameReg is either the stack pointer or a base pointer. But the base is
2675349cc55cSDimitry Andric   // located at the end of the statically known StackSize so the distinction
2676349cc55cSDimitry Andric   // doesn't really matter.
2677349cc55cSDimitry Andric   if (TRI->hasStackRealignment(MF) || TRI->hasBasePointer(MF))
2678349cc55cSDimitry Andric     assert(isAligned(MFI.getObjectAlign(FI), -(Offset + StackSize)));
2679349cc55cSDimitry Andric   return StackOffset::getFixed(Offset + StackSize);
26800b57cec5SDimitry Andric }
26810b57cec5SDimitry Andric 
26825ffd83dbSDimitry Andric int X86FrameLowering::getWin64EHFrameIndexRef(const MachineFunction &MF, int FI,
26835ffd83dbSDimitry Andric                                               Register &FrameReg) const {
2684c14a5a88SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
2685c14a5a88SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2686c14a5a88SDimitry Andric   const auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
2687c14a5a88SDimitry Andric   const auto it = WinEHXMMSlotInfo.find(FI);
2688c14a5a88SDimitry Andric 
2689c14a5a88SDimitry Andric   if (it == WinEHXMMSlotInfo.end())
2690e8d8bef9SDimitry Andric     return getFrameIndexReference(MF, FI, FrameReg).getFixed();
2691c14a5a88SDimitry Andric 
2692c14a5a88SDimitry Andric   FrameReg = TRI->getStackRegister();
26935ffd83dbSDimitry Andric   return alignDown(MFI.getMaxCallFrameSize(), getStackAlign().value()) +
26945ffd83dbSDimitry Andric          it->second;
2695c14a5a88SDimitry Andric }
2696c14a5a88SDimitry Andric 
2697e8d8bef9SDimitry Andric StackOffset
2698e8d8bef9SDimitry Andric X86FrameLowering::getFrameIndexReferenceSP(const MachineFunction &MF, int FI,
2699e8d8bef9SDimitry Andric                                            Register &FrameReg,
27000b57cec5SDimitry Andric                                            int Adjustment) const {
27010b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
27020b57cec5SDimitry Andric   FrameReg = TRI->getStackRegister();
2703e8d8bef9SDimitry Andric   return StackOffset::getFixed(MFI.getObjectOffset(FI) -
2704e8d8bef9SDimitry Andric                                getOffsetOfLocalArea() + Adjustment);
27050b57cec5SDimitry Andric }
27060b57cec5SDimitry Andric 
2707e8d8bef9SDimitry Andric StackOffset
2708e8d8bef9SDimitry Andric X86FrameLowering::getFrameIndexReferencePreferSP(const MachineFunction &MF,
2709e8d8bef9SDimitry Andric                                                  int FI, Register &FrameReg,
27100b57cec5SDimitry Andric                                                  bool IgnoreSPUpdates) const {
27110b57cec5SDimitry Andric 
27120b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
27130b57cec5SDimitry Andric   // Does not include any dynamic realign.
27140b57cec5SDimitry Andric   const uint64_t StackSize = MFI.getStackSize();
27150b57cec5SDimitry Andric   // LLVM arranges the stack as follows:
27160b57cec5SDimitry Andric   //   ...
27170b57cec5SDimitry Andric   //   ARG2
27180b57cec5SDimitry Andric   //   ARG1
27190b57cec5SDimitry Andric   //   RETADDR
27200b57cec5SDimitry Andric   //   PUSH RBP   <-- RBP points here
27210b57cec5SDimitry Andric   //   PUSH CSRs
27220b57cec5SDimitry Andric   //   ~~~~~~~    <-- possible stack realignment (non-win64)
27230b57cec5SDimitry Andric   //   ...
27240b57cec5SDimitry Andric   //   STACK OBJECTS
27250b57cec5SDimitry Andric   //   ...        <-- RSP after prologue points here
27260b57cec5SDimitry Andric   //   ~~~~~~~    <-- possible stack realignment (win64)
27270b57cec5SDimitry Andric   //
27280b57cec5SDimitry Andric   // if (hasVarSizedObjects()):
27290b57cec5SDimitry Andric   //   ...        <-- "base pointer" (ESI/RBX) points here
27300b57cec5SDimitry Andric   //   DYNAMIC ALLOCAS
27310b57cec5SDimitry Andric   //   ...        <-- RSP points here
27320b57cec5SDimitry Andric   //
27330b57cec5SDimitry Andric   // Case 1: In the simple case of no stack realignment and no dynamic
27340b57cec5SDimitry Andric   // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
27350b57cec5SDimitry Andric   // with fixed offsets from RSP.
27360b57cec5SDimitry Andric   //
27370b57cec5SDimitry Andric   // Case 2: In the case of stack realignment with no dynamic allocas, fixed
27380b57cec5SDimitry Andric   // stack objects are addressed with RBP and regular stack objects with RSP.
27390b57cec5SDimitry Andric   //
27400b57cec5SDimitry Andric   // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
27410b57cec5SDimitry Andric   // to address stack arguments for outgoing calls and nothing else. The "base
27420b57cec5SDimitry Andric   // pointer" points to local variables, and RBP points to fixed objects.
27430b57cec5SDimitry Andric   //
27440b57cec5SDimitry Andric   // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
27450b57cec5SDimitry Andric   // answer we give is relative to the SP after the prologue, and not the
27460b57cec5SDimitry Andric   // SP in the middle of the function.
27470b57cec5SDimitry Andric 
2748fe6060f1SDimitry Andric   if (MFI.isFixedObjectIndex(FI) && TRI->hasStackRealignment(MF) &&
27490b57cec5SDimitry Andric       !STI.isTargetWin64())
27500b57cec5SDimitry Andric     return getFrameIndexReference(MF, FI, FrameReg);
27510b57cec5SDimitry Andric 
27520b57cec5SDimitry Andric   // If !hasReservedCallFrame the function might have SP adjustement in the
27530b57cec5SDimitry Andric   // body.  So, even though the offset is statically known, it depends on where
27540b57cec5SDimitry Andric   // we are in the function.
27550b57cec5SDimitry Andric   if (!IgnoreSPUpdates && !hasReservedCallFrame(MF))
27560b57cec5SDimitry Andric     return getFrameIndexReference(MF, FI, FrameReg);
27570b57cec5SDimitry Andric 
27580b57cec5SDimitry Andric   // We don't handle tail calls, and shouldn't be seeing them either.
27590b57cec5SDimitry Andric   assert(MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta() >= 0 &&
27600b57cec5SDimitry Andric          "we don't handle this case!");
27610b57cec5SDimitry Andric 
27620b57cec5SDimitry Andric   // This is how the math works out:
27630b57cec5SDimitry Andric   //
27640b57cec5SDimitry Andric   //  %rsp grows (i.e. gets lower) left to right. Each box below is
27650b57cec5SDimitry Andric   //  one word (eight bytes).  Obj0 is the stack slot we're trying to
27660b57cec5SDimitry Andric   //  get to.
27670b57cec5SDimitry Andric   //
27680b57cec5SDimitry Andric   //    ----------------------------------
27690b57cec5SDimitry Andric   //    | BP | Obj0 | Obj1 | ... | ObjN |
27700b57cec5SDimitry Andric   //    ----------------------------------
27710b57cec5SDimitry Andric   //    ^    ^      ^                   ^
27720b57cec5SDimitry Andric   //    A    B      C                   E
27730b57cec5SDimitry Andric   //
27740b57cec5SDimitry Andric   // A is the incoming stack pointer.
27750b57cec5SDimitry Andric   // (B - A) is the local area offset (-8 for x86-64) [1]
27760b57cec5SDimitry Andric   // (C - A) is the Offset returned by MFI.getObjectOffset for Obj0 [2]
27770b57cec5SDimitry Andric   //
27780b57cec5SDimitry Andric   // |(E - B)| is the StackSize (absolute value, positive).  For a
27790b57cec5SDimitry Andric   // stack that grown down, this works out to be (B - E). [3]
27800b57cec5SDimitry Andric   //
27810b57cec5SDimitry Andric   // E is also the value of %rsp after stack has been set up, and we
27820b57cec5SDimitry Andric   // want (C - E) -- the value we can add to %rsp to get to Obj0.  Now
27830b57cec5SDimitry Andric   // (C - E) == (C - A) - (B - A) + (B - E)
27840b57cec5SDimitry Andric   //            { Using [1], [2] and [3] above }
27850b57cec5SDimitry Andric   //         == getObjectOffset - LocalAreaOffset + StackSize
27860b57cec5SDimitry Andric 
27870b57cec5SDimitry Andric   return getFrameIndexReferenceSP(MF, FI, FrameReg, StackSize);
27880b57cec5SDimitry Andric }
27890b57cec5SDimitry Andric 
27900b57cec5SDimitry Andric bool X86FrameLowering::assignCalleeSavedSpillSlots(
27910b57cec5SDimitry Andric     MachineFunction &MF, const TargetRegisterInfo *TRI,
27920b57cec5SDimitry Andric     std::vector<CalleeSavedInfo> &CSI) const {
27930b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
27940b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
27950b57cec5SDimitry Andric 
27960b57cec5SDimitry Andric   unsigned CalleeSavedFrameSize = 0;
2797c14a5a88SDimitry Andric   unsigned XMMCalleeSavedFrameSize = 0;
2798c14a5a88SDimitry Andric   auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
27990b57cec5SDimitry Andric   int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
28000b57cec5SDimitry Andric 
28010b57cec5SDimitry Andric   int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
28020b57cec5SDimitry Andric 
28030b57cec5SDimitry Andric   if (TailCallReturnAddrDelta < 0) {
28040b57cec5SDimitry Andric     // create RETURNADDR area
28050b57cec5SDimitry Andric     //   arg
28060b57cec5SDimitry Andric     //   arg
28070b57cec5SDimitry Andric     //   RETADDR
28080b57cec5SDimitry Andric     //   { ...
28090b57cec5SDimitry Andric     //     RETADDR area
28100b57cec5SDimitry Andric     //     ...
28110b57cec5SDimitry Andric     //   }
28120b57cec5SDimitry Andric     //   [EBP]
28130b57cec5SDimitry Andric     MFI.CreateFixedObject(-TailCallReturnAddrDelta,
28140b57cec5SDimitry Andric                           TailCallReturnAddrDelta - SlotSize, true);
28150b57cec5SDimitry Andric   }
28160b57cec5SDimitry Andric 
28170b57cec5SDimitry Andric   // Spill the BasePtr if it's used.
28180b57cec5SDimitry Andric   if (this->TRI->hasBasePointer(MF)) {
28190b57cec5SDimitry Andric     // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
28200b57cec5SDimitry Andric     if (MF.hasEHFunclets()) {
28215ffd83dbSDimitry Andric       int FI = MFI.CreateSpillStackObject(SlotSize, Align(SlotSize));
28220b57cec5SDimitry Andric       X86FI->setHasSEHFramePtrSave(true);
28230b57cec5SDimitry Andric       X86FI->setSEHFramePtrSaveIndex(FI);
28240b57cec5SDimitry Andric     }
28250b57cec5SDimitry Andric   }
28260b57cec5SDimitry Andric 
28270b57cec5SDimitry Andric   if (hasFP(MF)) {
28280b57cec5SDimitry Andric     // emitPrologue always spills frame register the first thing.
28290b57cec5SDimitry Andric     SpillSlotOffset -= SlotSize;
28300b57cec5SDimitry Andric     MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
28310b57cec5SDimitry Andric 
2832fe6060f1SDimitry Andric     // The async context lives directly before the frame pointer, and we
2833fe6060f1SDimitry Andric     // allocate a second slot to preserve stack alignment.
2834fe6060f1SDimitry Andric     if (X86FI->hasSwiftAsyncContext()) {
2835fe6060f1SDimitry Andric       SpillSlotOffset -= SlotSize;
2836fe6060f1SDimitry Andric       MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
2837fe6060f1SDimitry Andric       SpillSlotOffset -= SlotSize;
2838fe6060f1SDimitry Andric     }
2839fe6060f1SDimitry Andric 
28400b57cec5SDimitry Andric     // Since emitPrologue and emitEpilogue will handle spilling and restoring of
28410b57cec5SDimitry Andric     // the frame register, we can delete it from CSI list and not have to worry
28420b57cec5SDimitry Andric     // about avoiding it later.
28438bcb0991SDimitry Andric     Register FPReg = TRI->getFrameRegister(MF);
28440b57cec5SDimitry Andric     for (unsigned i = 0; i < CSI.size(); ++i) {
28450b57cec5SDimitry Andric       if (TRI->regsOverlap(CSI[i].getReg(), FPReg)) {
28460b57cec5SDimitry Andric         CSI.erase(CSI.begin() + i);
28470b57cec5SDimitry Andric         break;
28480b57cec5SDimitry Andric       }
28490b57cec5SDimitry Andric     }
28500b57cec5SDimitry Andric   }
28510b57cec5SDimitry Andric 
28525f757f3fSDimitry Andric   // Strategy:
28535f757f3fSDimitry Andric   // 1. Use push2 when
28545f757f3fSDimitry Andric   //       a) number of CSR > 1 if no need padding
28555f757f3fSDimitry Andric   //       b) number of CSR > 2 if need padding
28565f757f3fSDimitry Andric   // 2. When the number of CSR push is odd
28575f757f3fSDimitry Andric   //    a. Start to use push2 from the 1st push if stack is 16B aligned.
28585f757f3fSDimitry Andric   //    b. Start to use push2 from the 2nd push if stack is not 16B aligned.
28595f757f3fSDimitry Andric   // 3. When the number of CSR push is even, start to use push2 from the 1st
28605f757f3fSDimitry Andric   //    push and make the stack 16B aligned before the push
28615f757f3fSDimitry Andric   unsigned NumRegsForPush2 = 0;
28625f757f3fSDimitry Andric   if (STI.hasPush2Pop2()) {
28635f757f3fSDimitry Andric     unsigned NumCSGPR = llvm::count_if(CSI, [](const CalleeSavedInfo &I) {
28645f757f3fSDimitry Andric       return X86::GR64RegClass.contains(I.getReg());
28655f757f3fSDimitry Andric     });
28665f757f3fSDimitry Andric     bool NeedPadding = (SpillSlotOffset % 16 != 0) && (NumCSGPR % 2 == 0);
28675f757f3fSDimitry Andric     bool UsePush2Pop2 = NeedPadding ? NumCSGPR > 2 : NumCSGPR > 1;
28685f757f3fSDimitry Andric     X86FI->setPadForPush2Pop2(NeedPadding && UsePush2Pop2);
28695f757f3fSDimitry Andric     NumRegsForPush2 = UsePush2Pop2 ? alignDown(NumCSGPR, 2) : 0;
28705f757f3fSDimitry Andric     if (X86FI->padForPush2Pop2()) {
28715f757f3fSDimitry Andric       SpillSlotOffset -= SlotSize;
28725f757f3fSDimitry Andric       MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
28735f757f3fSDimitry Andric     }
28745f757f3fSDimitry Andric   }
28755f757f3fSDimitry Andric 
28760b57cec5SDimitry Andric   // Assign slots for GPRs. It increases frame size.
28770eae32dcSDimitry Andric   for (CalleeSavedInfo &I : llvm::reverse(CSI)) {
287804eeddc0SDimitry Andric     Register Reg = I.getReg();
28790b57cec5SDimitry Andric 
28800b57cec5SDimitry Andric     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
28810b57cec5SDimitry Andric       continue;
28820b57cec5SDimitry Andric 
28835f757f3fSDimitry Andric     // A CSR is a candidate for push2/pop2 when it's slot offset is 16B aligned
28845f757f3fSDimitry Andric     // or only an odd number of registers in the candidates.
28855f757f3fSDimitry Andric     if (X86FI->getNumCandidatesForPush2Pop2() < NumRegsForPush2 &&
28865f757f3fSDimitry Andric         (SpillSlotOffset % 16 == 0 ||
28875f757f3fSDimitry Andric          X86FI->getNumCandidatesForPush2Pop2() % 2))
28885f757f3fSDimitry Andric       X86FI->addCandidateForPush2Pop2(Reg);
28895f757f3fSDimitry Andric 
28900b57cec5SDimitry Andric     SpillSlotOffset -= SlotSize;
28910b57cec5SDimitry Andric     CalleeSavedFrameSize += SlotSize;
28920b57cec5SDimitry Andric 
28930b57cec5SDimitry Andric     int SlotIndex = MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
28940eae32dcSDimitry Andric     I.setFrameIdx(SlotIndex);
28950b57cec5SDimitry Andric   }
28960b57cec5SDimitry Andric 
289706c3fb27SDimitry Andric   // Adjust the offset of spill slot as we know the accurate callee saved frame
289806c3fb27SDimitry Andric   // size.
289906c3fb27SDimitry Andric   if (X86FI->getRestoreBasePointer()) {
290006c3fb27SDimitry Andric     SpillSlotOffset -= SlotSize;
290106c3fb27SDimitry Andric     CalleeSavedFrameSize += SlotSize;
290206c3fb27SDimitry Andric 
290306c3fb27SDimitry Andric     MFI.CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
290406c3fb27SDimitry Andric     // TODO: saving the slot index is better?
290506c3fb27SDimitry Andric     X86FI->setRestoreBasePointer(CalleeSavedFrameSize);
290606c3fb27SDimitry Andric   }
29075f757f3fSDimitry Andric   assert(X86FI->getNumCandidatesForPush2Pop2() % 2 == 0 &&
29085f757f3fSDimitry Andric          "Expect even candidates for push2/pop2");
29095f757f3fSDimitry Andric   if (X86FI->getNumCandidatesForPush2Pop2())
29105f757f3fSDimitry Andric     ++NumFunctionUsingPush2Pop2;
29110b57cec5SDimitry Andric   X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
29120b57cec5SDimitry Andric   MFI.setCVBytesOfCalleeSavedRegisters(CalleeSavedFrameSize);
29130b57cec5SDimitry Andric 
29140b57cec5SDimitry Andric   // Assign slots for XMMs.
29150eae32dcSDimitry Andric   for (CalleeSavedInfo &I : llvm::reverse(CSI)) {
291604eeddc0SDimitry Andric     Register Reg = I.getReg();
29170b57cec5SDimitry Andric     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
29180b57cec5SDimitry Andric       continue;
29190b57cec5SDimitry Andric 
29200b57cec5SDimitry Andric     // If this is k-register make sure we lookup via the largest legal type.
29210b57cec5SDimitry Andric     MVT VT = MVT::Other;
29220b57cec5SDimitry Andric     if (X86::VK16RegClass.contains(Reg))
29230b57cec5SDimitry Andric       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
29240b57cec5SDimitry Andric 
29250b57cec5SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
29260b57cec5SDimitry Andric     unsigned Size = TRI->getSpillSize(*RC);
29275ffd83dbSDimitry Andric     Align Alignment = TRI->getSpillAlign(*RC);
29280b57cec5SDimitry Andric     // ensure alignment
2929c14a5a88SDimitry Andric     assert(SpillSlotOffset < 0 && "SpillSlotOffset should always < 0 on X86");
29305ffd83dbSDimitry Andric     SpillSlotOffset = -alignTo(-SpillSlotOffset, Alignment);
2931c14a5a88SDimitry Andric 
29320b57cec5SDimitry Andric     // spill into slot
29330b57cec5SDimitry Andric     SpillSlotOffset -= Size;
29340b57cec5SDimitry Andric     int SlotIndex = MFI.CreateFixedSpillStackObject(Size, SpillSlotOffset);
29350eae32dcSDimitry Andric     I.setFrameIdx(SlotIndex);
29365ffd83dbSDimitry Andric     MFI.ensureMaxAlignment(Alignment);
2937c14a5a88SDimitry Andric 
2938c14a5a88SDimitry Andric     // Save the start offset and size of XMM in stack frame for funclets.
2939c14a5a88SDimitry Andric     if (X86::VR128RegClass.contains(Reg)) {
2940c14a5a88SDimitry Andric       WinEHXMMSlotInfo[SlotIndex] = XMMCalleeSavedFrameSize;
2941c14a5a88SDimitry Andric       XMMCalleeSavedFrameSize += Size;
2942c14a5a88SDimitry Andric     }
29430b57cec5SDimitry Andric   }
29440b57cec5SDimitry Andric 
29450b57cec5SDimitry Andric   return true;
29460b57cec5SDimitry Andric }
29470b57cec5SDimitry Andric 
29480b57cec5SDimitry Andric bool X86FrameLowering::spillCalleeSavedRegisters(
29490b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
29505ffd83dbSDimitry Andric     ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
29510b57cec5SDimitry Andric   DebugLoc DL = MBB.findDebugLoc(MI);
29520b57cec5SDimitry Andric 
29530b57cec5SDimitry Andric   // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
29540b57cec5SDimitry Andric   // for us, and there are no XMM CSRs on Win32.
29550b57cec5SDimitry Andric   if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
29560b57cec5SDimitry Andric     return true;
29570b57cec5SDimitry Andric 
29580b57cec5SDimitry Andric   // Push GPRs. It increases frame size.
29590b57cec5SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
29605f757f3fSDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
29615f757f3fSDimitry Andric   if (X86FI->padForPush2Pop2())
29625f757f3fSDimitry Andric     emitSPUpdate(MBB, MI, DL, -(int64_t)SlotSize, /*InEpilogue=*/false);
29630b57cec5SDimitry Andric 
29645f757f3fSDimitry Andric   // Update LiveIn of the basic block and decide whether we can add a kill flag
29655f757f3fSDimitry Andric   // to the use.
29665f757f3fSDimitry Andric   auto UpdateLiveInCheckCanKill = [&](Register Reg) {
29670b57cec5SDimitry Andric     const MachineRegisterInfo &MRI = MF.getRegInfo();
29680b57cec5SDimitry Andric     // Do not set a kill flag on values that are also marked as live-in. This
29690b57cec5SDimitry Andric     // happens with the @llvm-returnaddress intrinsic and with arguments
29700b57cec5SDimitry Andric     // passed in callee saved registers.
29710b57cec5SDimitry Andric     // Omitting the kill flags is conservatively correct even if the live-in
29720b57cec5SDimitry Andric     // is not used after all.
29735f757f3fSDimitry Andric     if (MRI.isLiveIn(Reg))
29745f757f3fSDimitry Andric       return false;
29755f757f3fSDimitry Andric     MBB.addLiveIn(Reg);
29765f757f3fSDimitry Andric     // Check if any subregister is live-in
29775f757f3fSDimitry Andric     for (MCRegAliasIterator AReg(Reg, TRI, false); AReg.isValid(); ++AReg)
29785f757f3fSDimitry Andric       if (MRI.isLiveIn(*AReg))
29795f757f3fSDimitry Andric         return false;
29805f757f3fSDimitry Andric     return true;
29815f757f3fSDimitry Andric   };
29825f757f3fSDimitry Andric   auto UpdateLiveInGetKillRegState = [&](Register Reg) {
29835f757f3fSDimitry Andric     return getKillRegState(UpdateLiveInCheckCanKill(Reg));
29845f757f3fSDimitry Andric   };
29855f757f3fSDimitry Andric 
29865f757f3fSDimitry Andric   for (auto RI = CSI.rbegin(), RE = CSI.rend(); RI != RE; ++RI) {
29875f757f3fSDimitry Andric     Register Reg = RI->getReg();
29885f757f3fSDimitry Andric     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
29895f757f3fSDimitry Andric       continue;
29905f757f3fSDimitry Andric 
29915f757f3fSDimitry Andric     if (X86FI->isCandidateForPush2Pop2(Reg)) {
29925f757f3fSDimitry Andric       Register Reg2 = (++RI)->getReg();
29935f757f3fSDimitry Andric       BuildMI(MBB, MI, DL, TII.get(getPUSH2Opcode(STI)))
29945f757f3fSDimitry Andric           .addReg(Reg, UpdateLiveInGetKillRegState(Reg))
29955f757f3fSDimitry Andric           .addReg(Reg2, UpdateLiveInGetKillRegState(Reg2))
29965f757f3fSDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
29975f757f3fSDimitry Andric     } else {
29985f757f3fSDimitry Andric       BuildMI(MBB, MI, DL, TII.get(getPUSHOpcode(STI)))
29995f757f3fSDimitry Andric           .addReg(Reg, UpdateLiveInGetKillRegState(Reg))
30000b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameSetup);
30010b57cec5SDimitry Andric     }
30025f757f3fSDimitry Andric   }
30030b57cec5SDimitry Andric 
300406c3fb27SDimitry Andric   if (X86FI->getRestoreBasePointer()) {
300506c3fb27SDimitry Andric     unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
300606c3fb27SDimitry Andric     Register BaseReg = this->TRI->getBaseRegister();
300706c3fb27SDimitry Andric     BuildMI(MBB, MI, DL, TII.get(Opc))
300806c3fb27SDimitry Andric         .addReg(BaseReg, getKillRegState(true))
300906c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
301006c3fb27SDimitry Andric   }
301106c3fb27SDimitry Andric 
30120b57cec5SDimitry Andric   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
30130b57cec5SDimitry Andric   // It can be done by spilling XMMs to stack frame.
30140eae32dcSDimitry Andric   for (const CalleeSavedInfo &I : llvm::reverse(CSI)) {
301504eeddc0SDimitry Andric     Register Reg = I.getReg();
30160b57cec5SDimitry Andric     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
30170b57cec5SDimitry Andric       continue;
30180b57cec5SDimitry Andric 
30190b57cec5SDimitry Andric     // If this is k-register make sure we lookup via the largest legal type.
30200b57cec5SDimitry Andric     MVT VT = MVT::Other;
30210b57cec5SDimitry Andric     if (X86::VK16RegClass.contains(Reg))
30220b57cec5SDimitry Andric       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
30230b57cec5SDimitry Andric 
30240b57cec5SDimitry Andric     // Add the callee-saved register as live-in. It's killed at the spill.
30250b57cec5SDimitry Andric     MBB.addLiveIn(Reg);
30260b57cec5SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
30270b57cec5SDimitry Andric 
3028bdd1243dSDimitry Andric     TII.storeRegToStackSlot(MBB, MI, Reg, true, I.getFrameIdx(), RC, TRI,
3029bdd1243dSDimitry Andric                             Register());
30300b57cec5SDimitry Andric     --MI;
30310b57cec5SDimitry Andric     MI->setFlag(MachineInstr::FrameSetup);
30320b57cec5SDimitry Andric     ++MI;
30330b57cec5SDimitry Andric   }
30340b57cec5SDimitry Andric 
30350b57cec5SDimitry Andric   return true;
30360b57cec5SDimitry Andric }
30370b57cec5SDimitry Andric 
30380b57cec5SDimitry Andric void X86FrameLowering::emitCatchRetReturnValue(MachineBasicBlock &MBB,
30390b57cec5SDimitry Andric                                                MachineBasicBlock::iterator MBBI,
30400b57cec5SDimitry Andric                                                MachineInstr *CatchRet) const {
30410b57cec5SDimitry Andric   // SEH shouldn't use catchret.
30420b57cec5SDimitry Andric   assert(!isAsynchronousEHPersonality(classifyEHPersonality(
30430b57cec5SDimitry Andric              MBB.getParent()->getFunction().getPersonalityFn())) &&
30440b57cec5SDimitry Andric          "SEH should not use CATCHRET");
3045fe6060f1SDimitry Andric   const DebugLoc &DL = CatchRet->getDebugLoc();
30460b57cec5SDimitry Andric   MachineBasicBlock *CatchRetTarget = CatchRet->getOperand(0).getMBB();
30470b57cec5SDimitry Andric 
30480b57cec5SDimitry Andric   // Fill EAX/RAX with the address of the target block.
30490b57cec5SDimitry Andric   if (STI.is64Bit()) {
30500b57cec5SDimitry Andric     // LEA64r CatchRetTarget(%rip), %rax
30510b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), X86::RAX)
30520b57cec5SDimitry Andric         .addReg(X86::RIP)
30530b57cec5SDimitry Andric         .addImm(0)
30540b57cec5SDimitry Andric         .addReg(0)
30550b57cec5SDimitry Andric         .addMBB(CatchRetTarget)
30560b57cec5SDimitry Andric         .addReg(0);
30570b57cec5SDimitry Andric   } else {
30580b57cec5SDimitry Andric     // MOV32ri $CatchRetTarget, %eax
30590b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
30600b57cec5SDimitry Andric         .addMBB(CatchRetTarget);
30610b57cec5SDimitry Andric   }
30620b57cec5SDimitry Andric 
30630b57cec5SDimitry Andric   // Record that we've taken the address of CatchRetTarget and no longer just
30640b57cec5SDimitry Andric   // reference it in a terminator.
3065bdd1243dSDimitry Andric   CatchRetTarget->setMachineBlockAddressTaken();
30660b57cec5SDimitry Andric }
30670b57cec5SDimitry Andric 
30685ffd83dbSDimitry Andric bool X86FrameLowering::restoreCalleeSavedRegisters(
30695ffd83dbSDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
30705ffd83dbSDimitry Andric     MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
30710b57cec5SDimitry Andric   if (CSI.empty())
30720b57cec5SDimitry Andric     return false;
30730b57cec5SDimitry Andric 
30740b57cec5SDimitry Andric   if (MI != MBB.end() && isFuncletReturnInstr(*MI) && STI.isOSWindows()) {
30750b57cec5SDimitry Andric     // Don't restore CSRs in 32-bit EH funclets. Matches
30760b57cec5SDimitry Andric     // spillCalleeSavedRegisters.
30770b57cec5SDimitry Andric     if (STI.is32Bit())
30780b57cec5SDimitry Andric       return true;
30790b57cec5SDimitry Andric     // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
30800b57cec5SDimitry Andric     // funclets. emitEpilogue transforms these to normal jumps.
30810b57cec5SDimitry Andric     if (MI->getOpcode() == X86::CATCHRET) {
30820b57cec5SDimitry Andric       const Function &F = MBB.getParent()->getFunction();
30830b57cec5SDimitry Andric       bool IsSEH = isAsynchronousEHPersonality(
30840b57cec5SDimitry Andric           classifyEHPersonality(F.getPersonalityFn()));
30850b57cec5SDimitry Andric       if (IsSEH)
30860b57cec5SDimitry Andric         return true;
30870b57cec5SDimitry Andric     }
30880b57cec5SDimitry Andric   }
30890b57cec5SDimitry Andric 
30900b57cec5SDimitry Andric   DebugLoc DL = MBB.findDebugLoc(MI);
30910b57cec5SDimitry Andric 
30920b57cec5SDimitry Andric   // Reload XMMs from stack frame.
30934824e7fdSDimitry Andric   for (const CalleeSavedInfo &I : CSI) {
309404eeddc0SDimitry Andric     Register Reg = I.getReg();
30955f757f3fSDimitry Andric     if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
30960b57cec5SDimitry Andric       continue;
30970b57cec5SDimitry Andric 
30980b57cec5SDimitry Andric     // If this is k-register make sure we lookup via the largest legal type.
30990b57cec5SDimitry Andric     MVT VT = MVT::Other;
31000b57cec5SDimitry Andric     if (X86::VK16RegClass.contains(Reg))
31010b57cec5SDimitry Andric       VT = STI.hasBWI() ? MVT::v64i1 : MVT::v16i1;
31020b57cec5SDimitry Andric 
31030b57cec5SDimitry Andric     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
3104bdd1243dSDimitry Andric     TII.loadRegFromStackSlot(MBB, MI, Reg, I.getFrameIdx(), RC, TRI,
3105bdd1243dSDimitry Andric                              Register());
31060b57cec5SDimitry Andric   }
31070b57cec5SDimitry Andric 
310806c3fb27SDimitry Andric   // Clear the stack slot for spill base pointer register.
310906c3fb27SDimitry Andric   MachineFunction &MF = *MBB.getParent();
311006c3fb27SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
311106c3fb27SDimitry Andric   if (X86FI->getRestoreBasePointer()) {
311206c3fb27SDimitry Andric     unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
311306c3fb27SDimitry Andric     Register BaseReg = this->TRI->getBaseRegister();
311406c3fb27SDimitry Andric     BuildMI(MBB, MI, DL, TII.get(Opc), BaseReg)
311506c3fb27SDimitry Andric         .setMIFlag(MachineInstr::FrameDestroy);
311606c3fb27SDimitry Andric   }
311706c3fb27SDimitry Andric 
31180b57cec5SDimitry Andric   // POP GPRs.
31195f757f3fSDimitry Andric   for (auto I = CSI.begin(), E = CSI.end(); I != E; ++I) {
31205f757f3fSDimitry Andric     Register Reg = I->getReg();
31215f757f3fSDimitry Andric     if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
31220b57cec5SDimitry Andric       continue;
31230b57cec5SDimitry Andric 
31245f757f3fSDimitry Andric     if (X86FI->isCandidateForPush2Pop2(Reg))
31255f757f3fSDimitry Andric       BuildMI(MBB, MI, DL, TII.get(getPOP2Opcode(STI)), Reg)
31265f757f3fSDimitry Andric           .addReg((++I)->getReg(), RegState::Define)
31275f757f3fSDimitry Andric           .setMIFlag(MachineInstr::FrameDestroy);
31285f757f3fSDimitry Andric     else
31295f757f3fSDimitry Andric       BuildMI(MBB, MI, DL, TII.get(getPOPOpcode(STI)), Reg)
31300b57cec5SDimitry Andric           .setMIFlag(MachineInstr::FrameDestroy);
31310b57cec5SDimitry Andric   }
31325f757f3fSDimitry Andric   if (X86FI->padForPush2Pop2())
31335f757f3fSDimitry Andric     emitSPUpdate(MBB, MI, DL, SlotSize, /*InEpilogue=*/true);
31345f757f3fSDimitry Andric 
31350b57cec5SDimitry Andric   return true;
31360b57cec5SDimitry Andric }
31370b57cec5SDimitry Andric 
31380b57cec5SDimitry Andric void X86FrameLowering::determineCalleeSaves(MachineFunction &MF,
31390b57cec5SDimitry Andric                                             BitVector &SavedRegs,
31400b57cec5SDimitry Andric                                             RegScavenger *RS) const {
31410b57cec5SDimitry Andric   TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
31420b57cec5SDimitry Andric 
31430b57cec5SDimitry Andric   // Spill the BasePtr if it's used.
31440b57cec5SDimitry Andric   if (TRI->hasBasePointer(MF)) {
31458bcb0991SDimitry Andric     Register BasePtr = TRI->getBaseRegister();
31460b57cec5SDimitry Andric     if (STI.isTarget64BitILP32())
31470b57cec5SDimitry Andric       BasePtr = getX86SubSuperRegister(BasePtr, 64);
31480b57cec5SDimitry Andric     SavedRegs.set(BasePtr);
31490b57cec5SDimitry Andric   }
31500b57cec5SDimitry Andric }
31510b57cec5SDimitry Andric 
31525f757f3fSDimitry Andric static bool HasNestArgument(const MachineFunction *MF) {
31530b57cec5SDimitry Andric   const Function &F = MF->getFunction();
31545f757f3fSDimitry Andric   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
31555f757f3fSDimitry Andric        I++) {
31568bcb0991SDimitry Andric     if (I->hasNestAttr() && !I->use_empty())
31570b57cec5SDimitry Andric       return true;
31580b57cec5SDimitry Andric   }
31590b57cec5SDimitry Andric   return false;
31600b57cec5SDimitry Andric }
31610b57cec5SDimitry Andric 
31620b57cec5SDimitry Andric /// GetScratchRegister - Get a temp register for performing work in the
31630b57cec5SDimitry Andric /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
31640b57cec5SDimitry Andric /// and the properties of the function either one or two registers will be
31650b57cec5SDimitry Andric /// needed. Set primary to true for the first register, false for the second.
31665f757f3fSDimitry Andric static unsigned GetScratchRegister(bool Is64Bit, bool IsLP64,
31675f757f3fSDimitry Andric                                    const MachineFunction &MF, bool Primary) {
31680b57cec5SDimitry Andric   CallingConv::ID CallingConvention = MF.getFunction().getCallingConv();
31690b57cec5SDimitry Andric 
31700b57cec5SDimitry Andric   // Erlang stuff.
31710b57cec5SDimitry Andric   if (CallingConvention == CallingConv::HiPE) {
31720b57cec5SDimitry Andric     if (Is64Bit)
31730b57cec5SDimitry Andric       return Primary ? X86::R14 : X86::R13;
31740b57cec5SDimitry Andric     else
31750b57cec5SDimitry Andric       return Primary ? X86::EBX : X86::EDI;
31760b57cec5SDimitry Andric   }
31770b57cec5SDimitry Andric 
31780b57cec5SDimitry Andric   if (Is64Bit) {
31790b57cec5SDimitry Andric     if (IsLP64)
31800b57cec5SDimitry Andric       return Primary ? X86::R11 : X86::R12;
31810b57cec5SDimitry Andric     else
31820b57cec5SDimitry Andric       return Primary ? X86::R11D : X86::R12D;
31830b57cec5SDimitry Andric   }
31840b57cec5SDimitry Andric 
31850b57cec5SDimitry Andric   bool IsNested = HasNestArgument(&MF);
31860b57cec5SDimitry Andric 
31870b57cec5SDimitry Andric   if (CallingConvention == CallingConv::X86_FastCall ||
31888bcb0991SDimitry Andric       CallingConvention == CallingConv::Fast ||
31898bcb0991SDimitry Andric       CallingConvention == CallingConv::Tail) {
31900b57cec5SDimitry Andric     if (IsNested)
31910b57cec5SDimitry Andric       report_fatal_error("Segmented stacks does not support fastcall with "
31920b57cec5SDimitry Andric                          "nested function.");
31930b57cec5SDimitry Andric     return Primary ? X86::EAX : X86::ECX;
31940b57cec5SDimitry Andric   }
31950b57cec5SDimitry Andric   if (IsNested)
31960b57cec5SDimitry Andric     return Primary ? X86::EDX : X86::EAX;
31970b57cec5SDimitry Andric   return Primary ? X86::ECX : X86::EAX;
31980b57cec5SDimitry Andric }
31990b57cec5SDimitry Andric 
32000b57cec5SDimitry Andric // The stack limit in the TCB is set to this many bytes above the actual stack
32010b57cec5SDimitry Andric // limit.
32020b57cec5SDimitry Andric static const uint64_t kSplitStackAvailable = 256;
32030b57cec5SDimitry Andric 
32040b57cec5SDimitry Andric void X86FrameLowering::adjustForSegmentedStacks(
32050b57cec5SDimitry Andric     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
32060b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
32070b57cec5SDimitry Andric   uint64_t StackSize;
32080b57cec5SDimitry Andric   unsigned TlsReg, TlsOffset;
32090b57cec5SDimitry Andric   DebugLoc DL;
32100b57cec5SDimitry Andric 
32110b57cec5SDimitry Andric   // To support shrink-wrapping we would need to insert the new blocks
32120b57cec5SDimitry Andric   // at the right place and update the branches to PrologueMBB.
32130b57cec5SDimitry Andric   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
32140b57cec5SDimitry Andric 
32150b57cec5SDimitry Andric   unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
32160b57cec5SDimitry Andric   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
32170b57cec5SDimitry Andric          "Scratch register is live-in");
32180b57cec5SDimitry Andric 
32190b57cec5SDimitry Andric   if (MF.getFunction().isVarArg())
32200b57cec5SDimitry Andric     report_fatal_error("Segmented stacks do not support vararg functions.");
32210b57cec5SDimitry Andric   if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
32220b57cec5SDimitry Andric       !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
32230b57cec5SDimitry Andric       !STI.isTargetDragonFly())
32240b57cec5SDimitry Andric     report_fatal_error("Segmented stacks not supported on this platform.");
32250b57cec5SDimitry Andric 
32260b57cec5SDimitry Andric   // Eventually StackSize will be calculated by a link-time pass; which will
32270b57cec5SDimitry Andric   // also decide whether checking code needs to be injected into this particular
32280b57cec5SDimitry Andric   // prologue.
32290b57cec5SDimitry Andric   StackSize = MFI.getStackSize();
32300b57cec5SDimitry Andric 
323181ad6265SDimitry Andric   if (!MFI.needsSplitStackProlog())
32320b57cec5SDimitry Andric     return;
32330b57cec5SDimitry Andric 
32340b57cec5SDimitry Andric   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
32350b57cec5SDimitry Andric   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
32360b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
32370b57cec5SDimitry Andric   bool IsNested = false;
32380b57cec5SDimitry Andric 
32390b57cec5SDimitry Andric   // We need to know if the function has a nest argument only in 64 bit mode.
32400b57cec5SDimitry Andric   if (Is64Bit)
32410b57cec5SDimitry Andric     IsNested = HasNestArgument(&MF);
32420b57cec5SDimitry Andric 
32430b57cec5SDimitry Andric   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
32440b57cec5SDimitry Andric   // allocMBB needs to be last (terminating) instruction.
32450b57cec5SDimitry Andric 
32460b57cec5SDimitry Andric   for (const auto &LI : PrologueMBB.liveins()) {
32470b57cec5SDimitry Andric     allocMBB->addLiveIn(LI);
32480b57cec5SDimitry Andric     checkMBB->addLiveIn(LI);
32490b57cec5SDimitry Andric   }
32500b57cec5SDimitry Andric 
32510b57cec5SDimitry Andric   if (IsNested)
32520b57cec5SDimitry Andric     allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
32530b57cec5SDimitry Andric 
32540b57cec5SDimitry Andric   MF.push_front(allocMBB);
32550b57cec5SDimitry Andric   MF.push_front(checkMBB);
32560b57cec5SDimitry Andric 
32570b57cec5SDimitry Andric   // When the frame size is less than 256 we just compare the stack
32580b57cec5SDimitry Andric   // boundary directly to the value of the stack pointer, per gcc.
32590b57cec5SDimitry Andric   bool CompareStackPointer = StackSize < kSplitStackAvailable;
32600b57cec5SDimitry Andric 
32610b57cec5SDimitry Andric   // Read the limit off the current stacklet off the stack_guard location.
32620b57cec5SDimitry Andric   if (Is64Bit) {
32630b57cec5SDimitry Andric     if (STI.isTargetLinux()) {
32640b57cec5SDimitry Andric       TlsReg = X86::FS;
32650b57cec5SDimitry Andric       TlsOffset = IsLP64 ? 0x70 : 0x40;
32660b57cec5SDimitry Andric     } else if (STI.isTargetDarwin()) {
32670b57cec5SDimitry Andric       TlsReg = X86::GS;
32680b57cec5SDimitry Andric       TlsOffset = 0x60 + 90 * 8; // See pthread_machdep.h. Steal TLS slot 90.
32690b57cec5SDimitry Andric     } else if (STI.isTargetWin64()) {
32700b57cec5SDimitry Andric       TlsReg = X86::GS;
32710b57cec5SDimitry Andric       TlsOffset = 0x28; // pvArbitrary, reserved for application use
32720b57cec5SDimitry Andric     } else if (STI.isTargetFreeBSD()) {
32730b57cec5SDimitry Andric       TlsReg = X86::FS;
32740b57cec5SDimitry Andric       TlsOffset = 0x18;
32750b57cec5SDimitry Andric     } else if (STI.isTargetDragonFly()) {
32760b57cec5SDimitry Andric       TlsReg = X86::FS;
32770b57cec5SDimitry Andric       TlsOffset = 0x20; // use tls_tcb.tcb_segstack
32780b57cec5SDimitry Andric     } else {
32790b57cec5SDimitry Andric       report_fatal_error("Segmented stacks not supported on this platform.");
32800b57cec5SDimitry Andric     }
32810b57cec5SDimitry Andric 
32820b57cec5SDimitry Andric     if (CompareStackPointer)
32830b57cec5SDimitry Andric       ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
32840b57cec5SDimitry Andric     else
32855f757f3fSDimitry Andric       BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r),
32865f757f3fSDimitry Andric               ScratchReg)
32875f757f3fSDimitry Andric           .addReg(X86::RSP)
32885f757f3fSDimitry Andric           .addImm(1)
32895f757f3fSDimitry Andric           .addReg(0)
32905f757f3fSDimitry Andric           .addImm(-StackSize)
32915f757f3fSDimitry Andric           .addReg(0);
32920b57cec5SDimitry Andric 
32935f757f3fSDimitry Andric     BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm))
32945f757f3fSDimitry Andric         .addReg(ScratchReg)
32955f757f3fSDimitry Andric         .addReg(0)
32965f757f3fSDimitry Andric         .addImm(1)
32975f757f3fSDimitry Andric         .addReg(0)
32985f757f3fSDimitry Andric         .addImm(TlsOffset)
32995f757f3fSDimitry Andric         .addReg(TlsReg);
33000b57cec5SDimitry Andric   } else {
33010b57cec5SDimitry Andric     if (STI.isTargetLinux()) {
33020b57cec5SDimitry Andric       TlsReg = X86::GS;
33030b57cec5SDimitry Andric       TlsOffset = 0x30;
33040b57cec5SDimitry Andric     } else if (STI.isTargetDarwin()) {
33050b57cec5SDimitry Andric       TlsReg = X86::GS;
33060b57cec5SDimitry Andric       TlsOffset = 0x48 + 90 * 4;
33070b57cec5SDimitry Andric     } else if (STI.isTargetWin32()) {
33080b57cec5SDimitry Andric       TlsReg = X86::FS;
33090b57cec5SDimitry Andric       TlsOffset = 0x14; // pvArbitrary, reserved for application use
33100b57cec5SDimitry Andric     } else if (STI.isTargetDragonFly()) {
33110b57cec5SDimitry Andric       TlsReg = X86::FS;
33120b57cec5SDimitry Andric       TlsOffset = 0x10; // use tls_tcb.tcb_segstack
33130b57cec5SDimitry Andric     } else if (STI.isTargetFreeBSD()) {
33140b57cec5SDimitry Andric       report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
33150b57cec5SDimitry Andric     } else {
33160b57cec5SDimitry Andric       report_fatal_error("Segmented stacks not supported on this platform.");
33170b57cec5SDimitry Andric     }
33180b57cec5SDimitry Andric 
33190b57cec5SDimitry Andric     if (CompareStackPointer)
33200b57cec5SDimitry Andric       ScratchReg = X86::ESP;
33210b57cec5SDimitry Andric     else
33225f757f3fSDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg)
33235f757f3fSDimitry Andric           .addReg(X86::ESP)
33245f757f3fSDimitry Andric           .addImm(1)
33255f757f3fSDimitry Andric           .addReg(0)
33265f757f3fSDimitry Andric           .addImm(-StackSize)
33275f757f3fSDimitry Andric           .addReg(0);
33280b57cec5SDimitry Andric 
33290b57cec5SDimitry Andric     if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
33300b57cec5SDimitry Andric         STI.isTargetDragonFly()) {
33315f757f3fSDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
33325f757f3fSDimitry Andric           .addReg(ScratchReg)
33335f757f3fSDimitry Andric           .addReg(0)
33345f757f3fSDimitry Andric           .addImm(0)
33355f757f3fSDimitry Andric           .addReg(0)
33365f757f3fSDimitry Andric           .addImm(TlsOffset)
33375f757f3fSDimitry Andric           .addReg(TlsReg);
33380b57cec5SDimitry Andric     } else if (STI.isTargetDarwin()) {
33390b57cec5SDimitry Andric 
33400b57cec5SDimitry Andric       // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
33410b57cec5SDimitry Andric       unsigned ScratchReg2;
33420b57cec5SDimitry Andric       bool SaveScratch2;
33430b57cec5SDimitry Andric       if (CompareStackPointer) {
33440b57cec5SDimitry Andric         // The primary scratch register is available for holding the TLS offset.
33450b57cec5SDimitry Andric         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
33460b57cec5SDimitry Andric         SaveScratch2 = false;
33470b57cec5SDimitry Andric       } else {
33480b57cec5SDimitry Andric         // Need to use a second register to hold the TLS offset
33490b57cec5SDimitry Andric         ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
33500b57cec5SDimitry Andric 
33510b57cec5SDimitry Andric         // Unfortunately, with fastcc the second scratch register may hold an
33520b57cec5SDimitry Andric         // argument.
33530b57cec5SDimitry Andric         SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
33540b57cec5SDimitry Andric       }
33550b57cec5SDimitry Andric 
33560b57cec5SDimitry Andric       // If Scratch2 is live-in then it needs to be saved.
33570b57cec5SDimitry Andric       assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
33580b57cec5SDimitry Andric              "Scratch register is live-in and not saved");
33590b57cec5SDimitry Andric 
33600b57cec5SDimitry Andric       if (SaveScratch2)
33610b57cec5SDimitry Andric         BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
33620b57cec5SDimitry Andric             .addReg(ScratchReg2, RegState::Kill);
33630b57cec5SDimitry Andric 
33640b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
33650b57cec5SDimitry Andric           .addImm(TlsOffset);
33660b57cec5SDimitry Andric       BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
33670b57cec5SDimitry Andric           .addReg(ScratchReg)
33685f757f3fSDimitry Andric           .addReg(ScratchReg2)
33695f757f3fSDimitry Andric           .addImm(1)
33705f757f3fSDimitry Andric           .addReg(0)
33710b57cec5SDimitry Andric           .addImm(0)
33720b57cec5SDimitry Andric           .addReg(TlsReg);
33730b57cec5SDimitry Andric 
33740b57cec5SDimitry Andric       if (SaveScratch2)
33750b57cec5SDimitry Andric         BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
33760b57cec5SDimitry Andric     }
33770b57cec5SDimitry Andric   }
33780b57cec5SDimitry Andric 
33790b57cec5SDimitry Andric   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
33800b57cec5SDimitry Andric   // It jumps to normal execution of the function body.
33815f757f3fSDimitry Andric   BuildMI(checkMBB, DL, TII.get(X86::JCC_1))
33825f757f3fSDimitry Andric       .addMBB(&PrologueMBB)
33835f757f3fSDimitry Andric       .addImm(X86::COND_A);
33840b57cec5SDimitry Andric 
33850b57cec5SDimitry Andric   // On 32 bit we first push the arguments size and then the frame size. On 64
33860b57cec5SDimitry Andric   // bit, we pass the stack frame size in r10 and the argument size in r11.
33870b57cec5SDimitry Andric   if (Is64Bit) {
33880b57cec5SDimitry Andric     // Functions with nested arguments use R10, so it needs to be saved across
33890b57cec5SDimitry Andric     // the call to _morestack
33900b57cec5SDimitry Andric 
33910b57cec5SDimitry Andric     const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
33920b57cec5SDimitry Andric     const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
33930b57cec5SDimitry Andric     const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
33940b57cec5SDimitry Andric     const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
33950b57cec5SDimitry Andric 
33960b57cec5SDimitry Andric     if (IsNested)
33970b57cec5SDimitry Andric       BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
33980b57cec5SDimitry Andric 
339904eeddc0SDimitry Andric     BuildMI(allocMBB, DL, TII.get(getMOVriOpcode(IsLP64, StackSize)), Reg10)
34000b57cec5SDimitry Andric         .addImm(StackSize);
340104eeddc0SDimitry Andric     BuildMI(allocMBB, DL,
340204eeddc0SDimitry Andric             TII.get(getMOVriOpcode(IsLP64, X86FI->getArgumentStackSize())),
340304eeddc0SDimitry Andric             Reg11)
34040b57cec5SDimitry Andric         .addImm(X86FI->getArgumentStackSize());
34050b57cec5SDimitry Andric   } else {
340606c3fb27SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::PUSH32i))
34070b57cec5SDimitry Andric         .addImm(X86FI->getArgumentStackSize());
34085f757f3fSDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::PUSH32i)).addImm(StackSize);
34090b57cec5SDimitry Andric   }
34100b57cec5SDimitry Andric 
34110b57cec5SDimitry Andric   // __morestack is in libgcc
34120b57cec5SDimitry Andric   if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
34130b57cec5SDimitry Andric     // Under the large code model, we cannot assume that __morestack lives
34140b57cec5SDimitry Andric     // within 2^31 bytes of the call site, so we cannot use pc-relative
34150b57cec5SDimitry Andric     // addressing. We cannot perform the call via a temporary register,
34160b57cec5SDimitry Andric     // as the rax register may be used to store the static chain, and all
34170b57cec5SDimitry Andric     // other suitable registers may be either callee-save or used for
34180b57cec5SDimitry Andric     // parameter passing. We cannot use the stack at this point either
34190b57cec5SDimitry Andric     // because __morestack manipulates the stack directly.
34200b57cec5SDimitry Andric     //
34210b57cec5SDimitry Andric     // To avoid these issues, perform an indirect call via a read-only memory
34220b57cec5SDimitry Andric     // location containing the address.
34230b57cec5SDimitry Andric     //
34240b57cec5SDimitry Andric     // This solution is not perfect, as it assumes that the .rodata section
34250b57cec5SDimitry Andric     // is laid out within 2^31 bytes of each function body, but this seems
34260b57cec5SDimitry Andric     // to be sufficient for JIT.
34270b57cec5SDimitry Andric     // FIXME: Add retpoline support and remove the error here..
34280946e70aSDimitry Andric     if (STI.useIndirectThunkCalls())
34290b57cec5SDimitry Andric       report_fatal_error("Emitting morestack calls on 64-bit with the large "
34300946e70aSDimitry Andric                          "code model and thunks not yet implemented.");
34310b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
34320b57cec5SDimitry Andric         .addReg(X86::RIP)
34330b57cec5SDimitry Andric         .addImm(0)
34340b57cec5SDimitry Andric         .addReg(0)
34350b57cec5SDimitry Andric         .addExternalSymbol("__morestack_addr")
34360b57cec5SDimitry Andric         .addReg(0);
34370b57cec5SDimitry Andric   } else {
34380b57cec5SDimitry Andric     if (Is64Bit)
34390b57cec5SDimitry Andric       BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
34400b57cec5SDimitry Andric           .addExternalSymbol("__morestack");
34410b57cec5SDimitry Andric     else
34420b57cec5SDimitry Andric       BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
34430b57cec5SDimitry Andric           .addExternalSymbol("__morestack");
34440b57cec5SDimitry Andric   }
34450b57cec5SDimitry Andric 
34460b57cec5SDimitry Andric   if (IsNested)
34470b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
34480b57cec5SDimitry Andric   else
34490b57cec5SDimitry Andric     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
34500b57cec5SDimitry Andric 
34510b57cec5SDimitry Andric   allocMBB->addSuccessor(&PrologueMBB);
34520b57cec5SDimitry Andric 
34530b57cec5SDimitry Andric   checkMBB->addSuccessor(allocMBB, BranchProbability::getZero());
34540b57cec5SDimitry Andric   checkMBB->addSuccessor(&PrologueMBB, BranchProbability::getOne());
34550b57cec5SDimitry Andric 
34560b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS
34570b57cec5SDimitry Andric   MF.verify();
34580b57cec5SDimitry Andric #endif
34590b57cec5SDimitry Andric }
34600b57cec5SDimitry Andric 
34610b57cec5SDimitry Andric /// Lookup an ERTS parameter in the !hipe.literals named metadata node.
34620b57cec5SDimitry Andric /// HiPE provides Erlang Runtime System-internal parameters, such as PCB offsets
34630b57cec5SDimitry Andric /// to fields it needs, through a named metadata node "hipe.literals" containing
34640b57cec5SDimitry Andric /// name-value pairs.
34655f757f3fSDimitry Andric static unsigned getHiPELiteral(NamedMDNode *HiPELiteralsMD,
34665f757f3fSDimitry Andric                                const StringRef LiteralName) {
34670b57cec5SDimitry Andric   for (int i = 0, e = HiPELiteralsMD->getNumOperands(); i != e; ++i) {
34680b57cec5SDimitry Andric     MDNode *Node = HiPELiteralsMD->getOperand(i);
34695f757f3fSDimitry Andric     if (Node->getNumOperands() != 2)
34705f757f3fSDimitry Andric       continue;
34710b57cec5SDimitry Andric     MDString *NodeName = dyn_cast<MDString>(Node->getOperand(0));
34720b57cec5SDimitry Andric     ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Node->getOperand(1));
34735f757f3fSDimitry Andric     if (!NodeName || !NodeVal)
34745f757f3fSDimitry Andric       continue;
34750b57cec5SDimitry Andric     ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(NodeVal->getValue());
34760b57cec5SDimitry Andric     if (ValConst && NodeName->getString() == LiteralName) {
34770b57cec5SDimitry Andric       return ValConst->getZExtValue();
34780b57cec5SDimitry Andric     }
34790b57cec5SDimitry Andric   }
34800b57cec5SDimitry Andric 
34815f757f3fSDimitry Andric   report_fatal_error("HiPE literal " + LiteralName +
34825f757f3fSDimitry Andric                      " required but not provided");
34830b57cec5SDimitry Andric }
34840b57cec5SDimitry Andric 
34858bcb0991SDimitry Andric // Return true if there are no non-ehpad successors to MBB and there are no
34868bcb0991SDimitry Andric // non-meta instructions between MBBI and MBB.end().
34878bcb0991SDimitry Andric static bool blockEndIsUnreachable(const MachineBasicBlock &MBB,
34888bcb0991SDimitry Andric                                   MachineBasicBlock::const_iterator MBBI) {
3489e8d8bef9SDimitry Andric   return llvm::all_of(
3490e8d8bef9SDimitry Andric              MBB.successors(),
34918bcb0991SDimitry Andric              [](const MachineBasicBlock *Succ) { return Succ->isEHPad(); }) &&
34928bcb0991SDimitry Andric          std::all_of(MBBI, MBB.end(), [](const MachineInstr &MI) {
34938bcb0991SDimitry Andric            return MI.isMetaInstruction();
34948bcb0991SDimitry Andric          });
34958bcb0991SDimitry Andric }
34968bcb0991SDimitry Andric 
34970b57cec5SDimitry Andric /// Erlang programs may need a special prologue to handle the stack size they
34980b57cec5SDimitry Andric /// might need at runtime. That is because Erlang/OTP does not implement a C
34990b57cec5SDimitry Andric /// stack but uses a custom implementation of hybrid stack/heap architecture.
35000b57cec5SDimitry Andric /// (for more information see Eric Stenman's Ph.D. thesis:
35010b57cec5SDimitry Andric /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
35020b57cec5SDimitry Andric ///
35030b57cec5SDimitry Andric /// CheckStack:
35040b57cec5SDimitry Andric ///       temp0 = sp - MaxStack
35050b57cec5SDimitry Andric ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
35060b57cec5SDimitry Andric /// OldStart:
35070b57cec5SDimitry Andric ///       ...
35080b57cec5SDimitry Andric /// IncStack:
35090b57cec5SDimitry Andric ///       call inc_stack   # doubles the stack space
35100b57cec5SDimitry Andric ///       temp0 = sp - MaxStack
35110b57cec5SDimitry Andric ///       if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
35120b57cec5SDimitry Andric void X86FrameLowering::adjustForHiPEPrologue(
35130b57cec5SDimitry Andric     MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
35140b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
35150b57cec5SDimitry Andric   DebugLoc DL;
35160b57cec5SDimitry Andric 
35170b57cec5SDimitry Andric   // To support shrink-wrapping we would need to insert the new blocks
35180b57cec5SDimitry Andric   // at the right place and update the branches to PrologueMBB.
35190b57cec5SDimitry Andric   assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
35200b57cec5SDimitry Andric 
35210b57cec5SDimitry Andric   // HiPE-specific values
35225f757f3fSDimitry Andric   NamedMDNode *HiPELiteralsMD =
35230fca6ea1SDimitry Andric       MF.getFunction().getParent()->getNamedMetadata("hipe.literals");
35240b57cec5SDimitry Andric   if (!HiPELiteralsMD)
35250b57cec5SDimitry Andric     report_fatal_error(
35260b57cec5SDimitry Andric         "Can't generate HiPE prologue without runtime parameters");
35275f757f3fSDimitry Andric   const unsigned HipeLeafWords = getHiPELiteral(
35285f757f3fSDimitry Andric       HiPELiteralsMD, Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS");
35290b57cec5SDimitry Andric   const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
35300b57cec5SDimitry Andric   const unsigned Guaranteed = HipeLeafWords * SlotSize;
35315f757f3fSDimitry Andric   unsigned CallerStkArity = MF.getFunction().arg_size() > CCRegisteredArgs
35325f757f3fSDimitry Andric                                 ? MF.getFunction().arg_size() - CCRegisteredArgs
35335f757f3fSDimitry Andric                                 : 0;
35340b57cec5SDimitry Andric   unsigned MaxStack = MFI.getStackSize() + CallerStkArity * SlotSize + SlotSize;
35350b57cec5SDimitry Andric 
35360b57cec5SDimitry Andric   assert(STI.isTargetLinux() &&
35370b57cec5SDimitry Andric          "HiPE prologue is only supported on Linux operating systems.");
35380b57cec5SDimitry Andric 
35390b57cec5SDimitry Andric   // Compute the largest caller's frame that is needed to fit the callees'
35400b57cec5SDimitry Andric   // frames. This 'MaxStack' is computed from:
35410b57cec5SDimitry Andric   //
35420b57cec5SDimitry Andric   // a) the fixed frame size, which is the space needed for all spilled temps,
35430b57cec5SDimitry Andric   // b) outgoing on-stack parameter areas, and
35440b57cec5SDimitry Andric   // c) the minimum stack space this function needs to make available for the
35450b57cec5SDimitry Andric   //    functions it calls (a tunable ABI property).
35460b57cec5SDimitry Andric   if (MFI.hasCalls()) {
35470b57cec5SDimitry Andric     unsigned MoreStackForCalls = 0;
35480b57cec5SDimitry Andric 
35490b57cec5SDimitry Andric     for (auto &MBB : MF) {
35500b57cec5SDimitry Andric       for (auto &MI : MBB) {
35510b57cec5SDimitry Andric         if (!MI.isCall())
35520b57cec5SDimitry Andric           continue;
35530b57cec5SDimitry Andric 
35540b57cec5SDimitry Andric         // Get callee operand.
35550b57cec5SDimitry Andric         const MachineOperand &MO = MI.getOperand(0);
35560b57cec5SDimitry Andric 
35570b57cec5SDimitry Andric         // Only take account of global function calls (no closures etc.).
35580b57cec5SDimitry Andric         if (!MO.isGlobal())
35590b57cec5SDimitry Andric           continue;
35600b57cec5SDimitry Andric 
35610b57cec5SDimitry Andric         const Function *F = dyn_cast<Function>(MO.getGlobal());
35620b57cec5SDimitry Andric         if (!F)
35630b57cec5SDimitry Andric           continue;
35640b57cec5SDimitry Andric 
35650b57cec5SDimitry Andric         // Do not update 'MaxStack' for primitive and built-in functions
35660b57cec5SDimitry Andric         // (encoded with names either starting with "erlang."/"bif_" or not
35670b57cec5SDimitry Andric         // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
35680b57cec5SDimitry Andric         // "_", such as the BIF "suspend_0") as they are executed on another
35690b57cec5SDimitry Andric         // stack.
3570349cc55cSDimitry Andric         if (F->getName().contains("erlang.") || F->getName().contains("bif_") ||
35710b57cec5SDimitry Andric             F->getName().find_first_of("._") == StringRef::npos)
35720b57cec5SDimitry Andric           continue;
35730b57cec5SDimitry Andric 
35745f757f3fSDimitry Andric         unsigned CalleeStkArity = F->arg_size() > CCRegisteredArgs
35755f757f3fSDimitry Andric                                       ? F->arg_size() - CCRegisteredArgs
35765f757f3fSDimitry Andric                                       : 0;
35770b57cec5SDimitry Andric         if (HipeLeafWords - 1 > CalleeStkArity)
35785f757f3fSDimitry Andric           MoreStackForCalls =
35795f757f3fSDimitry Andric               std::max(MoreStackForCalls,
35800b57cec5SDimitry Andric                        (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
35810b57cec5SDimitry Andric       }
35820b57cec5SDimitry Andric     }
35830b57cec5SDimitry Andric     MaxStack += MoreStackForCalls;
35840b57cec5SDimitry Andric   }
35850b57cec5SDimitry Andric 
35860b57cec5SDimitry Andric   // If the stack frame needed is larger than the guaranteed then runtime checks
35870b57cec5SDimitry Andric   // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
35880b57cec5SDimitry Andric   if (MaxStack > Guaranteed) {
35890b57cec5SDimitry Andric     MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
35900b57cec5SDimitry Andric     MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
35910b57cec5SDimitry Andric 
35920b57cec5SDimitry Andric     for (const auto &LI : PrologueMBB.liveins()) {
35930b57cec5SDimitry Andric       stackCheckMBB->addLiveIn(LI);
35940b57cec5SDimitry Andric       incStackMBB->addLiveIn(LI);
35950b57cec5SDimitry Andric     }
35960b57cec5SDimitry Andric 
35970b57cec5SDimitry Andric     MF.push_front(incStackMBB);
35980b57cec5SDimitry Andric     MF.push_front(stackCheckMBB);
35990b57cec5SDimitry Andric 
36000b57cec5SDimitry Andric     unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
36010b57cec5SDimitry Andric     unsigned LEAop, CMPop, CALLop;
36020b57cec5SDimitry Andric     SPLimitOffset = getHiPELiteral(HiPELiteralsMD, "P_NSP_LIMIT");
36030b57cec5SDimitry Andric     if (Is64Bit) {
36040b57cec5SDimitry Andric       SPReg = X86::RSP;
36050b57cec5SDimitry Andric       PReg = X86::RBP;
36060b57cec5SDimitry Andric       LEAop = X86::LEA64r;
36070b57cec5SDimitry Andric       CMPop = X86::CMP64rm;
36080b57cec5SDimitry Andric       CALLop = X86::CALL64pcrel32;
36090b57cec5SDimitry Andric     } else {
36100b57cec5SDimitry Andric       SPReg = X86::ESP;
36110b57cec5SDimitry Andric       PReg = X86::EBP;
36120b57cec5SDimitry Andric       LEAop = X86::LEA32r;
36130b57cec5SDimitry Andric       CMPop = X86::CMP32rm;
36140b57cec5SDimitry Andric       CALLop = X86::CALLpcrel32;
36150b57cec5SDimitry Andric     }
36160b57cec5SDimitry Andric 
36170b57cec5SDimitry Andric     ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
36180b57cec5SDimitry Andric     assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
36190b57cec5SDimitry Andric            "HiPE prologue scratch register is live-in");
36200b57cec5SDimitry Andric 
36210b57cec5SDimitry Andric     // Create new MBB for StackCheck:
36225f757f3fSDimitry Andric     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg), SPReg,
36235f757f3fSDimitry Andric                  false, -MaxStack);
36240b57cec5SDimitry Andric     // SPLimitOffset is in a fixed heap location (pointed by BP).
36255f757f3fSDimitry Andric     addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop)).addReg(ScratchReg),
36265f757f3fSDimitry Andric                  PReg, false, SPLimitOffset);
36275f757f3fSDimitry Andric     BuildMI(stackCheckMBB, DL, TII.get(X86::JCC_1))
36285f757f3fSDimitry Andric         .addMBB(&PrologueMBB)
36295f757f3fSDimitry Andric         .addImm(X86::COND_AE);
36300b57cec5SDimitry Andric 
36310b57cec5SDimitry Andric     // Create new MBB for IncStack:
36325f757f3fSDimitry Andric     BuildMI(incStackMBB, DL, TII.get(CALLop)).addExternalSymbol("inc_stack_0");
36335f757f3fSDimitry Andric     addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg), SPReg,
36345f757f3fSDimitry Andric                  false, -MaxStack);
36355f757f3fSDimitry Andric     addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop)).addReg(ScratchReg),
36365f757f3fSDimitry Andric                  PReg, false, SPLimitOffset);
36375f757f3fSDimitry Andric     BuildMI(incStackMBB, DL, TII.get(X86::JCC_1))
36385f757f3fSDimitry Andric         .addMBB(incStackMBB)
36395f757f3fSDimitry Andric         .addImm(X86::COND_LE);
36400b57cec5SDimitry Andric 
36410b57cec5SDimitry Andric     stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100});
36420b57cec5SDimitry Andric     stackCheckMBB->addSuccessor(incStackMBB, {1, 100});
36430b57cec5SDimitry Andric     incStackMBB->addSuccessor(&PrologueMBB, {99, 100});
36440b57cec5SDimitry Andric     incStackMBB->addSuccessor(incStackMBB, {1, 100});
36450b57cec5SDimitry Andric   }
36460b57cec5SDimitry Andric #ifdef EXPENSIVE_CHECKS
36470b57cec5SDimitry Andric   MF.verify();
36480b57cec5SDimitry Andric #endif
36490b57cec5SDimitry Andric }
36500b57cec5SDimitry Andric 
36510b57cec5SDimitry Andric bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
36520b57cec5SDimitry Andric                                            MachineBasicBlock::iterator MBBI,
36530b57cec5SDimitry Andric                                            const DebugLoc &DL,
36540b57cec5SDimitry Andric                                            int Offset) const {
36550b57cec5SDimitry Andric   if (Offset <= 0)
36560b57cec5SDimitry Andric     return false;
36570b57cec5SDimitry Andric 
36580b57cec5SDimitry Andric   if (Offset % SlotSize)
36590b57cec5SDimitry Andric     return false;
36600b57cec5SDimitry Andric 
36610b57cec5SDimitry Andric   int NumPops = Offset / SlotSize;
36620b57cec5SDimitry Andric   // This is only worth it if we have at most 2 pops.
36630b57cec5SDimitry Andric   if (NumPops != 1 && NumPops != 2)
36640b57cec5SDimitry Andric     return false;
36650b57cec5SDimitry Andric 
36660b57cec5SDimitry Andric   // Handle only the trivial case where the adjustment directly follows
36670b57cec5SDimitry Andric   // a call. This is the most common one, anyway.
36680b57cec5SDimitry Andric   if (MBBI == MBB.begin())
36690b57cec5SDimitry Andric     return false;
36700b57cec5SDimitry Andric   MachineBasicBlock::iterator Prev = std::prev(MBBI);
36710b57cec5SDimitry Andric   if (!Prev->isCall() || !Prev->getOperand(1).isRegMask())
36720b57cec5SDimitry Andric     return false;
36730b57cec5SDimitry Andric 
36740b57cec5SDimitry Andric   unsigned Regs[2];
36750b57cec5SDimitry Andric   unsigned FoundRegs = 0;
36760b57cec5SDimitry Andric 
3677e8d8bef9SDimitry Andric   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3678e8d8bef9SDimitry Andric   const MachineOperand &RegMask = Prev->getOperand(1);
36790b57cec5SDimitry Andric 
36800b57cec5SDimitry Andric   auto &RegClass =
36810b57cec5SDimitry Andric       Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
36820b57cec5SDimitry Andric   // Try to find up to NumPops free registers.
36830b57cec5SDimitry Andric   for (auto Candidate : RegClass) {
36840b57cec5SDimitry Andric     // Poor man's liveness:
36850b57cec5SDimitry Andric     // Since we're immediately after a call, any register that is clobbered
36860b57cec5SDimitry Andric     // by the call and not defined by it can be considered dead.
36870b57cec5SDimitry Andric     if (!RegMask.clobbersPhysReg(Candidate))
36880b57cec5SDimitry Andric       continue;
36890b57cec5SDimitry Andric 
36900b57cec5SDimitry Andric     // Don't clobber reserved registers
36910b57cec5SDimitry Andric     if (MRI.isReserved(Candidate))
36920b57cec5SDimitry Andric       continue;
36930b57cec5SDimitry Andric 
36940b57cec5SDimitry Andric     bool IsDef = false;
36950b57cec5SDimitry Andric     for (const MachineOperand &MO : Prev->implicit_operands()) {
36960b57cec5SDimitry Andric       if (MO.isReg() && MO.isDef() &&
36970b57cec5SDimitry Andric           TRI->isSuperOrSubRegisterEq(MO.getReg(), Candidate)) {
36980b57cec5SDimitry Andric         IsDef = true;
36990b57cec5SDimitry Andric         break;
37000b57cec5SDimitry Andric       }
37010b57cec5SDimitry Andric     }
37020b57cec5SDimitry Andric 
37030b57cec5SDimitry Andric     if (IsDef)
37040b57cec5SDimitry Andric       continue;
37050b57cec5SDimitry Andric 
37060b57cec5SDimitry Andric     Regs[FoundRegs++] = Candidate;
37070b57cec5SDimitry Andric     if (FoundRegs == (unsigned)NumPops)
37080b57cec5SDimitry Andric       break;
37090b57cec5SDimitry Andric   }
37100b57cec5SDimitry Andric 
37110b57cec5SDimitry Andric   if (FoundRegs == 0)
37120b57cec5SDimitry Andric     return false;
37130b57cec5SDimitry Andric 
37140b57cec5SDimitry Andric   // If we found only one free register, but need two, reuse the same one twice.
37150b57cec5SDimitry Andric   while (FoundRegs < (unsigned)NumPops)
37160b57cec5SDimitry Andric     Regs[FoundRegs++] = Regs[0];
37170b57cec5SDimitry Andric 
37180b57cec5SDimitry Andric   for (int i = 0; i < NumPops; ++i)
37195f757f3fSDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r),
37205f757f3fSDimitry Andric             Regs[i]);
37210b57cec5SDimitry Andric 
37220b57cec5SDimitry Andric   return true;
37230b57cec5SDimitry Andric }
37240b57cec5SDimitry Andric 
37255f757f3fSDimitry Andric MachineBasicBlock::iterator X86FrameLowering::eliminateCallFramePseudoInstr(
37265f757f3fSDimitry Andric     MachineFunction &MF, MachineBasicBlock &MBB,
37270b57cec5SDimitry Andric     MachineBasicBlock::iterator I) const {
37280b57cec5SDimitry Andric   bool reserveCallFrame = hasReservedCallFrame(MF);
37290b57cec5SDimitry Andric   unsigned Opcode = I->getOpcode();
37300b57cec5SDimitry Andric   bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
3731fe6060f1SDimitry Andric   DebugLoc DL = I->getDebugLoc(); // copy DebugLoc as I will be erased.
37328bcb0991SDimitry Andric   uint64_t Amount = TII.getFrameSize(*I);
37330b57cec5SDimitry Andric   uint64_t InternalAmt = (isDestroy || Amount) ? TII.getFrameAdjustment(*I) : 0;
37340b57cec5SDimitry Andric   I = MBB.erase(I);
37350b57cec5SDimitry Andric   auto InsertPos = skipDebugInstructionsForward(I, MBB.end());
37360b57cec5SDimitry Andric 
37375ffd83dbSDimitry Andric   // Try to avoid emitting dead SP adjustments if the block end is unreachable,
37385ffd83dbSDimitry Andric   // typically because the function is marked noreturn (abort, throw,
37395ffd83dbSDimitry Andric   // assert_fail, etc).
37405ffd83dbSDimitry Andric   if (isDestroy && blockEndIsUnreachable(MBB, I))
37415ffd83dbSDimitry Andric     return I;
37425ffd83dbSDimitry Andric 
37430b57cec5SDimitry Andric   if (!reserveCallFrame) {
37440b57cec5SDimitry Andric     // If the stack pointer can be changed after prologue, turn the
37450b57cec5SDimitry Andric     // adjcallstackup instruction into a 'sub ESP, <amt>' and the
37460b57cec5SDimitry Andric     // adjcallstackdown instruction into 'add ESP, <amt>'
37470b57cec5SDimitry Andric 
37480b57cec5SDimitry Andric     // We need to keep the stack aligned properly.  To do this, we round the
37490b57cec5SDimitry Andric     // amount of space needed for the outgoing arguments up to the next
37500b57cec5SDimitry Andric     // alignment boundary.
37515ffd83dbSDimitry Andric     Amount = alignTo(Amount, getStackAlign());
37520b57cec5SDimitry Andric 
37530b57cec5SDimitry Andric     const Function &F = MF.getFunction();
37540b57cec5SDimitry Andric     bool WindowsCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
3755480093f4SDimitry Andric     bool DwarfCFI = !WindowsCFI && MF.needsFrameMoves();
37560b57cec5SDimitry Andric 
37570b57cec5SDimitry Andric     // If we have any exception handlers in this function, and we adjust
37580b57cec5SDimitry Andric     // the SP before calls, we may need to indicate this to the unwinder
37590b57cec5SDimitry Andric     // using GNU_ARGS_SIZE. Note that this may be necessary even when
37600b57cec5SDimitry Andric     // Amount == 0, because the preceding function may have set a non-0
37610b57cec5SDimitry Andric     // GNU_ARGS_SIZE.
37620b57cec5SDimitry Andric     // TODO: We don't need to reset this between subsequent functions,
37630b57cec5SDimitry Andric     // if it didn't change.
37640b57cec5SDimitry Andric     bool HasDwarfEHHandlers = !WindowsCFI && !MF.getLandingPads().empty();
37650b57cec5SDimitry Andric 
37660b57cec5SDimitry Andric     if (HasDwarfEHHandlers && !isDestroy &&
37670b57cec5SDimitry Andric         MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences())
37680b57cec5SDimitry Andric       BuildCFI(MBB, InsertPos, DL,
37690b57cec5SDimitry Andric                MCCFIInstruction::createGnuArgsSize(nullptr, Amount));
37700b57cec5SDimitry Andric 
37710b57cec5SDimitry Andric     if (Amount == 0)
37720b57cec5SDimitry Andric       return I;
37730b57cec5SDimitry Andric 
37740b57cec5SDimitry Andric     // Factor out the amount that gets handled inside the sequence
37750b57cec5SDimitry Andric     // (Pushes of argument for frame setup, callee pops for frame destroy)
37760b57cec5SDimitry Andric     Amount -= InternalAmt;
37770b57cec5SDimitry Andric 
37780b57cec5SDimitry Andric     // TODO: This is needed only if we require precise CFA.
37790b57cec5SDimitry Andric     // If this is a callee-pop calling convention, emit a CFA adjust for
37800b57cec5SDimitry Andric     // the amount the callee popped.
37810b57cec5SDimitry Andric     if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF))
37820b57cec5SDimitry Andric       BuildCFI(MBB, InsertPos, DL,
37830b57cec5SDimitry Andric                MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt));
37840b57cec5SDimitry Andric 
37850b57cec5SDimitry Andric     // Add Amount to SP to destroy a frame, or subtract to setup.
37860b57cec5SDimitry Andric     int64_t StackAdjustment = isDestroy ? Amount : -Amount;
37870b57cec5SDimitry Andric 
37880b57cec5SDimitry Andric     if (StackAdjustment) {
37890b57cec5SDimitry Andric       // Merge with any previous or following adjustment instruction. Note: the
37900b57cec5SDimitry Andric       // instructions merged with here do not have CFI, so their stack
37910b57cec5SDimitry Andric       // adjustments do not feed into CfaAdjustment.
37920b57cec5SDimitry Andric       StackAdjustment += mergeSPUpdates(MBB, InsertPos, true);
37930b57cec5SDimitry Andric       StackAdjustment += mergeSPUpdates(MBB, InsertPos, false);
37940b57cec5SDimitry Andric 
37950b57cec5SDimitry Andric       if (StackAdjustment) {
37960b57cec5SDimitry Andric         if (!(F.hasMinSize() &&
37970b57cec5SDimitry Andric               adjustStackWithPops(MBB, InsertPos, DL, StackAdjustment)))
37980b57cec5SDimitry Andric           BuildStackAdjustment(MBB, InsertPos, DL, StackAdjustment,
37990b57cec5SDimitry Andric                                /*InEpilogue=*/false);
38000b57cec5SDimitry Andric       }
38010b57cec5SDimitry Andric     }
38020b57cec5SDimitry Andric 
38030b57cec5SDimitry Andric     if (DwarfCFI && !hasFP(MF)) {
38040b57cec5SDimitry Andric       // If we don't have FP, but need to generate unwind information,
38050b57cec5SDimitry Andric       // we need to set the correct CFA offset after the stack adjustment.
38060b57cec5SDimitry Andric       // How much we adjust the CFA offset depends on whether we're emitting
38070b57cec5SDimitry Andric       // CFI only for EH purposes or for debugging. EH only requires the CFA
38080b57cec5SDimitry Andric       // offset to be correct at each call site, while for debugging we want
38090b57cec5SDimitry Andric       // it to be more precise.
38100b57cec5SDimitry Andric 
38110b57cec5SDimitry Andric       int64_t CfaAdjustment = -StackAdjustment;
38120b57cec5SDimitry Andric       // TODO: When not using precise CFA, we also need to adjust for the
38130b57cec5SDimitry Andric       // InternalAmt here.
38140b57cec5SDimitry Andric       if (CfaAdjustment) {
38155f757f3fSDimitry Andric         BuildCFI(
38165f757f3fSDimitry Andric             MBB, InsertPos, DL,
38175f757f3fSDimitry Andric             MCCFIInstruction::createAdjustCfaOffset(nullptr, CfaAdjustment));
38180b57cec5SDimitry Andric       }
38190b57cec5SDimitry Andric     }
38200b57cec5SDimitry Andric 
38210b57cec5SDimitry Andric     return I;
38220b57cec5SDimitry Andric   }
38230b57cec5SDimitry Andric 
38245ffd83dbSDimitry Andric   if (InternalAmt) {
38250b57cec5SDimitry Andric     MachineBasicBlock::iterator CI = I;
38260b57cec5SDimitry Andric     MachineBasicBlock::iterator B = MBB.begin();
38270b57cec5SDimitry Andric     while (CI != B && !std::prev(CI)->isCall())
38280b57cec5SDimitry Andric       --CI;
38290b57cec5SDimitry Andric     BuildStackAdjustment(MBB, CI, DL, -InternalAmt, /*InEpilogue=*/false);
38300b57cec5SDimitry Andric   }
38310b57cec5SDimitry Andric 
38320b57cec5SDimitry Andric   return I;
38330b57cec5SDimitry Andric }
38340b57cec5SDimitry Andric 
38350b57cec5SDimitry Andric bool X86FrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
38360b57cec5SDimitry Andric   assert(MBB.getParent() && "Block is not attached to a function!");
38370b57cec5SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
3838fe6060f1SDimitry Andric   if (!MBB.isLiveIn(X86::EFLAGS))
3839fe6060f1SDimitry Andric     return true;
3840fe6060f1SDimitry Andric 
3841bdd1243dSDimitry Andric   // If stack probes have to loop inline or call, that will clobber EFLAGS.
3842bdd1243dSDimitry Andric   // FIXME: we could allow cases that will use emitStackProbeInlineGenericBlock.
3843bdd1243dSDimitry Andric   const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
3844bdd1243dSDimitry Andric   const X86TargetLowering &TLI = *STI.getTargetLowering();
3845bdd1243dSDimitry Andric   if (TLI.hasInlineStackProbe(MF) || TLI.hasStackProbeSymbol(MF))
3846bdd1243dSDimitry Andric     return false;
3847bdd1243dSDimitry Andric 
3848fe6060f1SDimitry Andric   const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
3849fe6060f1SDimitry Andric   return !TRI->hasStackRealignment(MF) && !X86FI->hasSwiftAsyncContext();
38500b57cec5SDimitry Andric }
38510b57cec5SDimitry Andric 
38520b57cec5SDimitry Andric bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
38530b57cec5SDimitry Andric   assert(MBB.getParent() && "Block is not attached to a function!");
38540b57cec5SDimitry Andric 
38550b57cec5SDimitry Andric   // Win64 has strict requirements in terms of epilogue and we are
38560b57cec5SDimitry Andric   // not taking a chance at messing with them.
38570b57cec5SDimitry Andric   // I.e., unless this block is already an exit block, we can't use
38580b57cec5SDimitry Andric   // it as an epilogue.
38590b57cec5SDimitry Andric   if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
38600b57cec5SDimitry Andric     return false;
38610b57cec5SDimitry Andric 
3862fe6060f1SDimitry Andric   // Swift async context epilogue has a BTR instruction that clobbers parts of
3863fe6060f1SDimitry Andric   // EFLAGS.
3864fe6060f1SDimitry Andric   const MachineFunction &MF = *MBB.getParent();
3865fe6060f1SDimitry Andric   if (MF.getInfo<X86MachineFunctionInfo>()->hasSwiftAsyncContext())
3866fe6060f1SDimitry Andric     return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
3867fe6060f1SDimitry Andric 
38680b57cec5SDimitry Andric   if (canUseLEAForSPInEpilogue(*MBB.getParent()))
38690b57cec5SDimitry Andric     return true;
38700b57cec5SDimitry Andric 
38710b57cec5SDimitry Andric   // If we cannot use LEA to adjust SP, we may need to use ADD, which
38720b57cec5SDimitry Andric   // clobbers the EFLAGS. Check that we do not need to preserve it,
38730b57cec5SDimitry Andric   // otherwise, conservatively assume this is not
38740b57cec5SDimitry Andric   // safe to insert the epilogue here.
38750b57cec5SDimitry Andric   return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
38760b57cec5SDimitry Andric }
38770b57cec5SDimitry Andric 
38780b57cec5SDimitry Andric bool X86FrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
38790b57cec5SDimitry Andric   // If we may need to emit frameless compact unwind information, give
38800b57cec5SDimitry Andric   // up as this is currently broken: PR25614.
3881e8d8bef9SDimitry Andric   bool CompactUnwind =
38820fca6ea1SDimitry Andric       MF.getContext().getObjectFileInfo()->getCompactUnwindSection() != nullptr;
3883e8d8bef9SDimitry Andric   return (MF.getFunction().hasFnAttribute(Attribute::NoUnwind) || hasFP(MF) ||
3884e8d8bef9SDimitry Andric           !CompactUnwind) &&
3885e8d8bef9SDimitry Andric          // The lowering of segmented stack and HiPE only support entry
3886e8d8bef9SDimitry Andric          // blocks as prologue blocks: PR26107. This limitation may be
3887e8d8bef9SDimitry Andric          // lifted if we fix:
38880b57cec5SDimitry Andric          // - adjustForSegmentedStacks
38890b57cec5SDimitry Andric          // - adjustForHiPEPrologue
38900b57cec5SDimitry Andric          MF.getFunction().getCallingConv() != CallingConv::HiPE &&
38910b57cec5SDimitry Andric          !MF.shouldSplitStack();
38920b57cec5SDimitry Andric }
38930b57cec5SDimitry Andric 
38940b57cec5SDimitry Andric MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers(
38950b57cec5SDimitry Andric     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
38960b57cec5SDimitry Andric     const DebugLoc &DL, bool RestoreSP) const {
38970b57cec5SDimitry Andric   assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
38980b57cec5SDimitry Andric   assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
38990b57cec5SDimitry Andric   assert(STI.is32Bit() && !Uses64BitFramePtr &&
39000b57cec5SDimitry Andric          "restoring EBP/ESI on non-32-bit target");
39010b57cec5SDimitry Andric 
39020b57cec5SDimitry Andric   MachineFunction &MF = *MBB.getParent();
39038bcb0991SDimitry Andric   Register FramePtr = TRI->getFrameRegister(MF);
39048bcb0991SDimitry Andric   Register BasePtr = TRI->getBaseRegister();
39050b57cec5SDimitry Andric   WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
39060b57cec5SDimitry Andric   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
39070b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
39080b57cec5SDimitry Andric 
39090b57cec5SDimitry Andric   // FIXME: Don't set FrameSetup flag in catchret case.
39100b57cec5SDimitry Andric 
39110b57cec5SDimitry Andric   int FI = FuncInfo.EHRegNodeFrameIndex;
39120b57cec5SDimitry Andric   int EHRegSize = MFI.getObjectSize(FI);
39130b57cec5SDimitry Andric 
39140b57cec5SDimitry Andric   if (RestoreSP) {
39150b57cec5SDimitry Andric     // MOV32rm -EHRegSize(%ebp), %esp
39160b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP),
39170b57cec5SDimitry Andric                  X86::EBP, true, -EHRegSize)
39180b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
39190b57cec5SDimitry Andric   }
39200b57cec5SDimitry Andric 
39215ffd83dbSDimitry Andric   Register UsedReg;
3922e8d8bef9SDimitry Andric   int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg).getFixed();
39230b57cec5SDimitry Andric   int EndOffset = -EHRegOffset - EHRegSize;
39240b57cec5SDimitry Andric   FuncInfo.EHRegNodeEndOffset = EndOffset;
39250b57cec5SDimitry Andric 
39260b57cec5SDimitry Andric   if (UsedReg == FramePtr) {
39270b57cec5SDimitry Andric     // ADD $offset, %ebp
392806c3fb27SDimitry Andric     unsigned ADDri = getADDriOpcode(false);
39290b57cec5SDimitry Andric     BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr)
39300b57cec5SDimitry Andric         .addReg(FramePtr)
39310b57cec5SDimitry Andric         .addImm(EndOffset)
39320b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup)
39330b57cec5SDimitry Andric         ->getOperand(3)
39340b57cec5SDimitry Andric         .setIsDead();
39350b57cec5SDimitry Andric     assert(EndOffset >= 0 &&
39360b57cec5SDimitry Andric            "end of registration object above normal EBP position!");
39370b57cec5SDimitry Andric   } else if (UsedReg == BasePtr) {
39380b57cec5SDimitry Andric     // LEA offset(%ebp), %esi
39390b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr),
39400b57cec5SDimitry Andric                  FramePtr, false, EndOffset)
39410b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
39420b57cec5SDimitry Andric     // MOV32rm SavedEBPOffset(%esi), %ebp
39430b57cec5SDimitry Andric     assert(X86FI->getHasSEHFramePtrSave());
39440b57cec5SDimitry Andric     int Offset =
3945e8d8bef9SDimitry Andric         getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg)
3946e8d8bef9SDimitry Andric             .getFixed();
39470b57cec5SDimitry Andric     assert(UsedReg == BasePtr);
39480b57cec5SDimitry Andric     addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr),
39490b57cec5SDimitry Andric                  UsedReg, true, Offset)
39500b57cec5SDimitry Andric         .setMIFlag(MachineInstr::FrameSetup);
39510b57cec5SDimitry Andric   } else {
39520b57cec5SDimitry Andric     llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
39530b57cec5SDimitry Andric   }
39540b57cec5SDimitry Andric   return MBBI;
39550b57cec5SDimitry Andric }
39560b57cec5SDimitry Andric 
39570b57cec5SDimitry Andric int X86FrameLowering::getInitialCFAOffset(const MachineFunction &MF) const {
39580b57cec5SDimitry Andric   return TRI->getSlotSize();
39590b57cec5SDimitry Andric }
39600b57cec5SDimitry Andric 
39615ffd83dbSDimitry Andric Register
39625ffd83dbSDimitry Andric X86FrameLowering::getInitialCFARegister(const MachineFunction &MF) const {
396306c3fb27SDimitry Andric   return StackPtr;
396406c3fb27SDimitry Andric }
396506c3fb27SDimitry Andric 
396606c3fb27SDimitry Andric TargetFrameLowering::DwarfFrameBase
396706c3fb27SDimitry Andric X86FrameLowering::getDwarfFrameBase(const MachineFunction &MF) const {
396806c3fb27SDimitry Andric   const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
396906c3fb27SDimitry Andric   Register FrameRegister = RI->getFrameRegister(MF);
397006c3fb27SDimitry Andric   if (getInitialCFARegister(MF) == FrameRegister &&
397106c3fb27SDimitry Andric       MF.getInfo<X86MachineFunctionInfo>()->hasCFIAdjustCfa()) {
397206c3fb27SDimitry Andric     DwarfFrameBase FrameBase;
397306c3fb27SDimitry Andric     FrameBase.Kind = DwarfFrameBase::CFA;
397406c3fb27SDimitry Andric     FrameBase.Location.Offset =
397506c3fb27SDimitry Andric         -MF.getFrameInfo().getStackSize() - getInitialCFAOffset(MF);
397606c3fb27SDimitry Andric     return FrameBase;
397706c3fb27SDimitry Andric   }
397806c3fb27SDimitry Andric 
397906c3fb27SDimitry Andric   return DwarfFrameBase{DwarfFrameBase::Register, {FrameRegister}};
39800b57cec5SDimitry Andric }
39810b57cec5SDimitry Andric 
39820b57cec5SDimitry Andric namespace {
39830b57cec5SDimitry Andric // Struct used by orderFrameObjects to help sort the stack objects.
39840b57cec5SDimitry Andric struct X86FrameSortingObject {
39850b57cec5SDimitry Andric   bool IsValid = false;             // true if we care about this Object.
39860b57cec5SDimitry Andric   unsigned ObjectIndex = 0;         // Index of Object into MFI list.
39870b57cec5SDimitry Andric   unsigned ObjectSize = 0;          // Size of Object in bytes.
39885ffd83dbSDimitry Andric   Align ObjectAlignment = Align(1); // Alignment of Object in bytes.
39890b57cec5SDimitry Andric   unsigned ObjectNumUses = 0;       // Object static number of uses.
39900b57cec5SDimitry Andric };
39910b57cec5SDimitry Andric 
39920b57cec5SDimitry Andric // The comparison function we use for std::sort to order our local
39930b57cec5SDimitry Andric // stack symbols. The current algorithm is to use an estimated
39940b57cec5SDimitry Andric // "density". This takes into consideration the size and number of
39950b57cec5SDimitry Andric // uses each object has in order to roughly minimize code size.
39960b57cec5SDimitry Andric // So, for example, an object of size 16B that is referenced 5 times
39970b57cec5SDimitry Andric // will get higher priority than 4 4B objects referenced 1 time each.
39980b57cec5SDimitry Andric // It's not perfect and we may be able to squeeze a few more bytes out of
39990b57cec5SDimitry Andric // it (for example : 0(esp) requires fewer bytes, symbols allocated at the
40000b57cec5SDimitry Andric // fringe end can have special consideration, given their size is less
40010b57cec5SDimitry Andric // important, etc.), but the algorithmic complexity grows too much to be
40020b57cec5SDimitry Andric // worth the extra gains we get. This gets us pretty close.
40030b57cec5SDimitry Andric // The final order leaves us with objects with highest priority going
40040b57cec5SDimitry Andric // at the end of our list.
40050b57cec5SDimitry Andric struct X86FrameSortingComparator {
40060b57cec5SDimitry Andric   inline bool operator()(const X86FrameSortingObject &A,
4007e8d8bef9SDimitry Andric                          const X86FrameSortingObject &B) const {
40080b57cec5SDimitry Andric     uint64_t DensityAScaled, DensityBScaled;
40090b57cec5SDimitry Andric 
40100b57cec5SDimitry Andric     // For consistency in our comparison, all invalid objects are placed
40110b57cec5SDimitry Andric     // at the end. This also allows us to stop walking when we hit the
40120b57cec5SDimitry Andric     // first invalid item after it's all sorted.
40130b57cec5SDimitry Andric     if (!A.IsValid)
40140b57cec5SDimitry Andric       return false;
40150b57cec5SDimitry Andric     if (!B.IsValid)
40160b57cec5SDimitry Andric       return true;
40170b57cec5SDimitry Andric 
40180b57cec5SDimitry Andric     // The density is calculated by doing :
40190b57cec5SDimitry Andric     //     (double)DensityA = A.ObjectNumUses / A.ObjectSize
40200b57cec5SDimitry Andric     //     (double)DensityB = B.ObjectNumUses / B.ObjectSize
40210b57cec5SDimitry Andric     // Since this approach may cause inconsistencies in
40220b57cec5SDimitry Andric     // the floating point <, >, == comparisons, depending on the floating
40230b57cec5SDimitry Andric     // point model with which the compiler was built, we're going
40240b57cec5SDimitry Andric     // to scale both sides by multiplying with
40250b57cec5SDimitry Andric     // A.ObjectSize * B.ObjectSize. This ends up factoring away
40260b57cec5SDimitry Andric     // the division and, with it, the need for any floating point
40270b57cec5SDimitry Andric     // arithmetic.
40280b57cec5SDimitry Andric     DensityAScaled = static_cast<uint64_t>(A.ObjectNumUses) *
40290b57cec5SDimitry Andric                      static_cast<uint64_t>(B.ObjectSize);
40300b57cec5SDimitry Andric     DensityBScaled = static_cast<uint64_t>(B.ObjectNumUses) *
40310b57cec5SDimitry Andric                      static_cast<uint64_t>(A.ObjectSize);
40320b57cec5SDimitry Andric 
40330b57cec5SDimitry Andric     // If the two densities are equal, prioritize highest alignment
40340b57cec5SDimitry Andric     // objects. This allows for similar alignment objects
40350b57cec5SDimitry Andric     // to be packed together (given the same density).
40360b57cec5SDimitry Andric     // There's room for improvement here, also, since we can pack
40370b57cec5SDimitry Andric     // similar alignment (different density) objects next to each
40380b57cec5SDimitry Andric     // other to save padding. This will also require further
40390b57cec5SDimitry Andric     // complexity/iterations, and the overall gain isn't worth it,
40400b57cec5SDimitry Andric     // in general. Something to keep in mind, though.
40410b57cec5SDimitry Andric     if (DensityAScaled == DensityBScaled)
40420b57cec5SDimitry Andric       return A.ObjectAlignment < B.ObjectAlignment;
40430b57cec5SDimitry Andric 
40440b57cec5SDimitry Andric     return DensityAScaled < DensityBScaled;
40450b57cec5SDimitry Andric   }
40460b57cec5SDimitry Andric };
40470b57cec5SDimitry Andric } // namespace
40480b57cec5SDimitry Andric 
40490b57cec5SDimitry Andric // Order the symbols in the local stack.
40500b57cec5SDimitry Andric // We want to place the local stack objects in some sort of sensible order.
40510b57cec5SDimitry Andric // The heuristic we use is to try and pack them according to static number
40520b57cec5SDimitry Andric // of uses and size of object in order to minimize code size.
40530b57cec5SDimitry Andric void X86FrameLowering::orderFrameObjects(
40540b57cec5SDimitry Andric     const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
40550b57cec5SDimitry Andric   const MachineFrameInfo &MFI = MF.getFrameInfo();
40560b57cec5SDimitry Andric 
40570b57cec5SDimitry Andric   // Don't waste time if there's nothing to do.
40580b57cec5SDimitry Andric   if (ObjectsToAllocate.empty())
40590b57cec5SDimitry Andric     return;
40600b57cec5SDimitry Andric 
40610b57cec5SDimitry Andric   // Create an array of all MFI objects. We won't need all of these
40620b57cec5SDimitry Andric   // objects, but we're going to create a full array of them to make
40630b57cec5SDimitry Andric   // it easier to index into when we're counting "uses" down below.
40640b57cec5SDimitry Andric   // We want to be able to easily/cheaply access an object by simply
40650b57cec5SDimitry Andric   // indexing into it, instead of having to search for it every time.
40660b57cec5SDimitry Andric   std::vector<X86FrameSortingObject> SortingObjects(MFI.getObjectIndexEnd());
40670b57cec5SDimitry Andric 
40680b57cec5SDimitry Andric   // Walk the objects we care about and mark them as such in our working
40690b57cec5SDimitry Andric   // struct.
40700b57cec5SDimitry Andric   for (auto &Obj : ObjectsToAllocate) {
40710b57cec5SDimitry Andric     SortingObjects[Obj].IsValid = true;
40720b57cec5SDimitry Andric     SortingObjects[Obj].ObjectIndex = Obj;
40735ffd83dbSDimitry Andric     SortingObjects[Obj].ObjectAlignment = MFI.getObjectAlign(Obj);
40740b57cec5SDimitry Andric     // Set the size.
40750b57cec5SDimitry Andric     int ObjectSize = MFI.getObjectSize(Obj);
40760b57cec5SDimitry Andric     if (ObjectSize == 0)
40770b57cec5SDimitry Andric       // Variable size. Just use 4.
40780b57cec5SDimitry Andric       SortingObjects[Obj].ObjectSize = 4;
40790b57cec5SDimitry Andric     else
40800b57cec5SDimitry Andric       SortingObjects[Obj].ObjectSize = ObjectSize;
40810b57cec5SDimitry Andric   }
40820b57cec5SDimitry Andric 
40830b57cec5SDimitry Andric   // Count the number of uses for each object.
40840b57cec5SDimitry Andric   for (auto &MBB : MF) {
40850b57cec5SDimitry Andric     for (auto &MI : MBB) {
40860b57cec5SDimitry Andric       if (MI.isDebugInstr())
40870b57cec5SDimitry Andric         continue;
40880b57cec5SDimitry Andric       for (const MachineOperand &MO : MI.operands()) {
40890b57cec5SDimitry Andric         // Check to see if it's a local stack symbol.
40900b57cec5SDimitry Andric         if (!MO.isFI())
40910b57cec5SDimitry Andric           continue;
40920b57cec5SDimitry Andric         int Index = MO.getIndex();
40930b57cec5SDimitry Andric         // Check to see if it falls within our range, and is tagged
40940b57cec5SDimitry Andric         // to require ordering.
40950b57cec5SDimitry Andric         if (Index >= 0 && Index < MFI.getObjectIndexEnd() &&
40960b57cec5SDimitry Andric             SortingObjects[Index].IsValid)
40970b57cec5SDimitry Andric           SortingObjects[Index].ObjectNumUses++;
40980b57cec5SDimitry Andric       }
40990b57cec5SDimitry Andric     }
41000b57cec5SDimitry Andric   }
41010b57cec5SDimitry Andric 
41020b57cec5SDimitry Andric   // Sort the objects using X86FrameSortingAlgorithm (see its comment for
41030b57cec5SDimitry Andric   // info).
41040b57cec5SDimitry Andric   llvm::stable_sort(SortingObjects, X86FrameSortingComparator());
41050b57cec5SDimitry Andric 
41060b57cec5SDimitry Andric   // Now modify the original list to represent the final order that
41070b57cec5SDimitry Andric   // we want. The order will depend on whether we're going to access them
41080b57cec5SDimitry Andric   // from the stack pointer or the frame pointer. For SP, the list should
41090b57cec5SDimitry Andric   // end up with the END containing objects that we want with smaller offsets.
41100b57cec5SDimitry Andric   // For FP, it should be flipped.
41110b57cec5SDimitry Andric   int i = 0;
41120b57cec5SDimitry Andric   for (auto &Obj : SortingObjects) {
41130b57cec5SDimitry Andric     // All invalid items are sorted at the end, so it's safe to stop.
41140b57cec5SDimitry Andric     if (!Obj.IsValid)
41150b57cec5SDimitry Andric       break;
41160b57cec5SDimitry Andric     ObjectsToAllocate[i++] = Obj.ObjectIndex;
41170b57cec5SDimitry Andric   }
41180b57cec5SDimitry Andric 
41190b57cec5SDimitry Andric   // Flip it if we're accessing off of the FP.
4120fe6060f1SDimitry Andric   if (!TRI->hasStackRealignment(MF) && hasFP(MF))
41210b57cec5SDimitry Andric     std::reverse(ObjectsToAllocate.begin(), ObjectsToAllocate.end());
41220b57cec5SDimitry Andric }
41230b57cec5SDimitry Andric 
41245f757f3fSDimitry Andric unsigned
41255f757f3fSDimitry Andric X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const {
41260b57cec5SDimitry Andric   // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
41270b57cec5SDimitry Andric   unsigned Offset = 16;
41280b57cec5SDimitry Andric   // RBP is immediately pushed.
41290b57cec5SDimitry Andric   Offset += SlotSize;
41300b57cec5SDimitry Andric   // All callee-saved registers are then pushed.
41310b57cec5SDimitry Andric   Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
41320b57cec5SDimitry Andric   // Every funclet allocates enough stack space for the largest outgoing call.
41330b57cec5SDimitry Andric   Offset += getWinEHFuncletFrameSize(MF);
41340b57cec5SDimitry Andric   return Offset;
41350b57cec5SDimitry Andric }
41360b57cec5SDimitry Andric 
41370b57cec5SDimitry Andric void X86FrameLowering::processFunctionBeforeFrameFinalized(
41380b57cec5SDimitry Andric     MachineFunction &MF, RegScavenger *RS) const {
41390b57cec5SDimitry Andric   // Mark the function as not having WinCFI. We will set it back to true in
41400b57cec5SDimitry Andric   // emitPrologue if it gets called and emits CFI.
41410b57cec5SDimitry Andric   MF.setHasWinCFI(false);
41420b57cec5SDimitry Andric 
4143e8d8bef9SDimitry Andric   // If we are using Windows x64 CFI, ensure that the stack is always 8 byte
4144e8d8bef9SDimitry Andric   // aligned. The format doesn't support misaligned stack adjustments.
4145e8d8bef9SDimitry Andric   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI())
4146e8d8bef9SDimitry Andric     MF.getFrameInfo().ensureMaxAlignment(Align(SlotSize));
4147e8d8bef9SDimitry Andric 
41480b57cec5SDimitry Andric   // If this function isn't doing Win64-style C++ EH, we don't need to do
41490b57cec5SDimitry Andric   // anything.
4150e8d8bef9SDimitry Andric   if (STI.is64Bit() && MF.hasEHFunclets() &&
4151e8d8bef9SDimitry Andric       classifyEHPersonality(MF.getFunction().getPersonalityFn()) ==
4152e8d8bef9SDimitry Andric           EHPersonality::MSVC_CXX) {
4153e8d8bef9SDimitry Andric     adjustFrameForMsvcCxxEh(MF);
4154e8d8bef9SDimitry Andric   }
4155e8d8bef9SDimitry Andric }
41560b57cec5SDimitry Andric 
4157e8d8bef9SDimitry Andric void X86FrameLowering::adjustFrameForMsvcCxxEh(MachineFunction &MF) const {
41580b57cec5SDimitry Andric   // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
41590b57cec5SDimitry Andric   // relative to RSP after the prologue.  Find the offset of the last fixed
41600b57cec5SDimitry Andric   // object, so that we can allocate a slot immediately following it. If there
41610b57cec5SDimitry Andric   // were no fixed objects, use offset -SlotSize, which is immediately after the
41620b57cec5SDimitry Andric   // return address. Fixed objects have negative frame indices.
41630b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF.getFrameInfo();
41640b57cec5SDimitry Andric   WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
41650b57cec5SDimitry Andric   int64_t MinFixedObjOffset = -SlotSize;
41660b57cec5SDimitry Andric   for (int I = MFI.getObjectIndexBegin(); I < 0; ++I)
41670b57cec5SDimitry Andric     MinFixedObjOffset = std::min(MinFixedObjOffset, MFI.getObjectOffset(I));
41680b57cec5SDimitry Andric 
41690b57cec5SDimitry Andric   for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
41700b57cec5SDimitry Andric     for (WinEHHandlerType &H : TBME.HandlerArray) {
41710b57cec5SDimitry Andric       int FrameIndex = H.CatchObj.FrameIndex;
41720b57cec5SDimitry Andric       if (FrameIndex != INT_MAX) {
41730b57cec5SDimitry Andric         // Ensure alignment.
41745ffd83dbSDimitry Andric         unsigned Align = MFI.getObjectAlign(FrameIndex).value();
41750b57cec5SDimitry Andric         MinFixedObjOffset -= std::abs(MinFixedObjOffset) % Align;
41760b57cec5SDimitry Andric         MinFixedObjOffset -= MFI.getObjectSize(FrameIndex);
41770b57cec5SDimitry Andric         MFI.setObjectOffset(FrameIndex, MinFixedObjOffset);
41780b57cec5SDimitry Andric       }
41790b57cec5SDimitry Andric     }
41800b57cec5SDimitry Andric   }
41810b57cec5SDimitry Andric 
41820b57cec5SDimitry Andric   // Ensure alignment.
41830b57cec5SDimitry Andric   MinFixedObjOffset -= std::abs(MinFixedObjOffset) % 8;
41840b57cec5SDimitry Andric   int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
41850b57cec5SDimitry Andric   int UnwindHelpFI =
41860b57cec5SDimitry Andric       MFI.CreateFixedObject(SlotSize, UnwindHelpOffset, /*IsImmutable=*/false);
41870b57cec5SDimitry Andric   EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
41880b57cec5SDimitry Andric 
41890b57cec5SDimitry Andric   // Store -2 into UnwindHelp on function entry. We have to scan forwards past
41900b57cec5SDimitry Andric   // other frame setup instructions.
41910b57cec5SDimitry Andric   MachineBasicBlock &MBB = MF.front();
41920b57cec5SDimitry Andric   auto MBBI = MBB.begin();
41930b57cec5SDimitry Andric   while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
41940b57cec5SDimitry Andric     ++MBBI;
41950b57cec5SDimitry Andric 
41960b57cec5SDimitry Andric   DebugLoc DL = MBB.findDebugLoc(MBBI);
41970b57cec5SDimitry Andric   addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),
41980b57cec5SDimitry Andric                     UnwindHelpFI)
41990b57cec5SDimitry Andric       .addImm(-2);
42000b57cec5SDimitry Andric }
42015ffd83dbSDimitry Andric 
42025ffd83dbSDimitry Andric void X86FrameLowering::processFunctionBeforeFrameIndicesReplaced(
42035ffd83dbSDimitry Andric     MachineFunction &MF, RegScavenger *RS) const {
420406c3fb27SDimitry Andric   auto *X86FI = MF.getInfo<X86MachineFunctionInfo>();
420506c3fb27SDimitry Andric 
42065ffd83dbSDimitry Andric   if (STI.is32Bit() && MF.hasEHFunclets())
42075ffd83dbSDimitry Andric     restoreWinEHStackPointersInParent(MF);
420806c3fb27SDimitry Andric   // We have emitted prolog and epilog. Don't need stack pointer saving
420906c3fb27SDimitry Andric   // instruction any more.
421006c3fb27SDimitry Andric   if (MachineInstr *MI = X86FI->getStackPtrSaveMI()) {
421106c3fb27SDimitry Andric     MI->eraseFromParent();
421206c3fb27SDimitry Andric     X86FI->setStackPtrSaveMI(nullptr);
421306c3fb27SDimitry Andric   }
42145ffd83dbSDimitry Andric }
42155ffd83dbSDimitry Andric 
42165ffd83dbSDimitry Andric void X86FrameLowering::restoreWinEHStackPointersInParent(
42175ffd83dbSDimitry Andric     MachineFunction &MF) const {
42185ffd83dbSDimitry Andric   // 32-bit functions have to restore stack pointers when control is transferred
42195ffd83dbSDimitry Andric   // back to the parent function. These blocks are identified as eh pads that
42205ffd83dbSDimitry Andric   // are not funclet entries.
42215ffd83dbSDimitry Andric   bool IsSEH = isAsynchronousEHPersonality(
42225ffd83dbSDimitry Andric       classifyEHPersonality(MF.getFunction().getPersonalityFn()));
42235ffd83dbSDimitry Andric   for (MachineBasicBlock &MBB : MF) {
42245ffd83dbSDimitry Andric     bool NeedsRestore = MBB.isEHPad() && !MBB.isEHFuncletEntry();
42255ffd83dbSDimitry Andric     if (NeedsRestore)
42265ffd83dbSDimitry Andric       restoreWin32EHStackPointers(MBB, MBB.begin(), DebugLoc(),
42275ffd83dbSDimitry Andric                                   /*RestoreSP=*/IsSEH);
42285ffd83dbSDimitry Andric   }
42295ffd83dbSDimitry Andric }
4230