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