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