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