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 "MCTargetDesc/X86MCTargetDesc.h"
15#include "X86.h"
16#include "X86InstrBuilder.h"
17#include "X86InstrInfo.h"
18#include "X86MachineFunctionInfo.h"
19#include "X86Subtarget.h"
20#include "X86TargetMachine.h"
21#include "llvm/ADT/Statistic.h"
22#include "llvm/CodeGen/LivePhysRegs.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/RegisterScavenging.h"
29#include "llvm/CodeGen/WinEHFuncInfo.h"
30#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/EHPersonalities.h"
32#include "llvm/IR/Function.h"
33#include "llvm/IR/Module.h"
34#include "llvm/MC/MCAsmInfo.h"
35#include "llvm/MC/MCObjectFileInfo.h"
36#include "llvm/MC/MCSymbol.h"
37#include "llvm/Support/LEB128.h"
38#include "llvm/Target/TargetOptions.h"
39#include <cstdlib>
40
41#define DEBUG_TYPE "x86-fl"
42
43STATISTIC(NumFrameLoopProbe, "Number of loop stack probes used in prologue");
44STATISTIC(NumFrameExtraProbe,
45 "Number of extra stack probes generated in prologue");
46STATISTIC(NumFunctionUsingPush2Pop2, "Number of functions using push2/pop2");
47
48using namespace llvm;
49
50bool llvm::requireWinX64UnwindV3(const MachineFunction &MF) {
51 const Function &Fn = MF.getFunction();
52
53 // Whole module is in V3 mode.
54 if (Fn.getParent()->getWinX64EHUnwindMode() == WinX64EHUnwindMode::V3)
55 return true;
56
57 // Otherwise promote a function that may use EGPR (R16-R31), which V1/V2
58 // unwind codes cannot encode. The per-function "+egpr" feature is the signal,
59 // so an auto-dispatch APX clone gets V3 while the baseline clone stays on the
60 // module default. We conservatively promote any egpr function rather than
61 // checking for an actual EGPR save, keeping this a cheap query. (PUSH2/POP2
62 // does not need V3: V1/V2 describe a PUSH2 as two SEH_PushReg codes.)
63 return Fn.needsUnwindTableEntry() &&
64 MF.getSubtarget<X86Subtarget>().hasEGPR();
65}
66
67static const TargetRegisterClass *
68getCalleeSavedSpillRC(MCRegister Reg, const X86Subtarget &STI,
69 const TargetRegisterInfo &TRI) {
70 if (X86::VK16RegClass.contains(Reg))
71 return STI.hasBWI() ? &X86::VK64RegClass : &X86::VK16RegClass;
72 return TRI.getMinimalPhysRegClass(Reg);
73}
74
75X86FrameLowering::X86FrameLowering(const X86Subtarget &STI,
76 MaybeAlign StackAlignOverride)
77 : TargetFrameLowering(StackGrowsDown, StackAlignOverride.valueOrOne(),
78 STI.is64Bit() ? -8 : -4),
79 STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {
80 // Cache a bunch of frame-related predicates for this subtarget.
81 SlotSize = TRI->getSlotSize();
82 assert(SlotSize == 4 || SlotSize == 8);
83 Is64Bit = STI.is64Bit();
84 IsLP64 = STI.isTarget64BitLP64();
85 // standard x86_64 uses 64-bit frame/stack pointers, x32 - 32-bit.
86 Uses64BitFramePtr = STI.isTarget64BitLP64();
87 StackPtr = TRI->getStackRegister();
88}
89
90bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
91 return !MF.getFrameInfo().hasVarSizedObjects() &&
92 !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences() &&
93 !MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall();
94}
95
96/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
97/// call frame pseudos can be simplified. Having a FP, as in the default
98/// implementation, is not sufficient here since we can't always use it.
99/// Use a more nuanced condition.
100bool X86FrameLowering::canSimplifyCallFramePseudos(
101 const MachineFunction &MF) const {
102 return hasReservedCallFrame(MF) ||
103 MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() ||
104 (hasFP(MF) && !TRI->hasStackRealignment(MF)) ||
105 TRI->hasBasePointer(MF);
106}
107
108// needsFrameIndexResolution - Do we need to perform FI resolution for
109// this function. Normally, this is required only when the function
110// has any stack objects. However, FI resolution actually has another job,
111// not apparent from the title - it resolves callframesetup/destroy
112// that were not simplified earlier.
113// So, this is required for x86 functions that have push sequences even
114// when there are no stack objects.
115bool X86FrameLowering::needsFrameIndexResolution(
116 const MachineFunction &MF) const {
117 return MF.getFrameInfo().hasStackObjects() ||
118 MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
119}
120
121/// hasFPImpl - Return true if the specified function should have a dedicated
122/// frame pointer register. This is true if the function has variable sized
123/// allocas or if frame pointer elimination is disabled.
124bool X86FrameLowering::hasFPImpl(const MachineFunction &MF) const {
125 const MachineFrameInfo &MFI = MF.getFrameInfo();
126 return (MF.disableFramePointerElim() || TRI->hasStackRealignment(MF) ||
127 MFI.hasVarSizedObjects() || MFI.isFrameAddressTaken() ||
128 MFI.hasOpaqueSPAdjustment() ||
129 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
130 MF.getInfo<X86MachineFunctionInfo>()->hasPreallocatedCall() ||
131 MF.callsUnwindInit() || MF.hasEHFunclets() || MF.callsEHReturn() ||
132 MFI.hasStackMap() || MFI.hasPatchPoint() ||
133 (isWin64Prologue(MF) && MFI.hasCopyImplyingStackAdjustment()));
134}
135
136static unsigned getSUBriOpcode(bool IsLP64) {
137 return IsLP64 ? X86::SUB64ri32 : X86::SUB32ri;
138}
139
140static unsigned getADDriOpcode(bool IsLP64) {
141 return IsLP64 ? X86::ADD64ri32 : X86::ADD32ri;
142}
143
144static unsigned getSUBrrOpcode(bool IsLP64) {
145 return IsLP64 ? X86::SUB64rr : X86::SUB32rr;
146}
147
148static unsigned getADDrrOpcode(bool IsLP64) {
149 return IsLP64 ? X86::ADD64rr : X86::ADD32rr;
150}
151
152static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
153 return IsLP64 ? X86::AND64ri32 : X86::AND32ri;
154}
155
156static unsigned getLEArOpcode(bool IsLP64) {
157 return IsLP64 ? X86::LEA64r : X86::LEA32r;
158}
159
160// Push-Pop Acceleration (PPX) hint is used to indicate that the POP reads the
161// value written by the PUSH from the stack. The processor tracks these marked
162// instructions internally and fast-forwards register data between matching PUSH
163// and POP instructions, without going through memory or through the training
164// loop of the Fast Store Forwarding Predictor (FSFP). Instead, a more efficient
165// memory-renaming optimization can be used.
166//
167// The PPX hint is purely a performance hint. Instructions with this hint have
168// the same functional semantics as those without. PPX hints set by the
169// compiler that violate the balancing rule may turn off the PPX optimization,
170// but they will not affect program semantics.
171//
172// Hence, PPX is used for balanced spill/reloads (Exceptions and setjmp/longjmp
173// are not considered).
174//
175// PUSH2 and POP2 are instructions for (respectively) pushing/popping 2
176// GPRs at a time to/from the stack.
177static unsigned getPUSHOpcode(const X86Subtarget &ST) {
178 return ST.is64Bit() ? (ST.hasPPX() ? X86::PUSHP64r : X86::PUSH64r)
179 : X86::PUSH32r;
180}
181static unsigned getPOPOpcode(const X86Subtarget &ST) {
182 return ST.is64Bit() ? (ST.hasPPX() ? X86::POPP64r : X86::POP64r)
183 : X86::POP32r;
184}
185static unsigned getPUSH2Opcode(const X86Subtarget &ST) {
186 return ST.hasPPX() ? X86::PUSH2P : X86::PUSH2;
187}
188static unsigned getPOP2Opcode(const X86Subtarget &ST) {
189 return ST.hasPPX() ? X86::POP2P : X86::POP2;
190}
191
192static bool isEAXLiveIn(MachineBasicBlock &MBB) {
193 for (MachineBasicBlock::RegisterMaskPair RegMask : MBB.liveins()) {
194 MCRegister Reg = RegMask.PhysReg;
195
196 if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
197 Reg == X86::AH || Reg == X86::AL)
198 return true;
199 }
200
201 return false;
202}
203
204/// Check if the flags need to be preserved before the terminators.
205/// This would be the case, if the eflags is live-in of the region
206/// composed by the terminators or live-out of that region, without
207/// being defined by a terminator.
208static bool
209flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) {
210 for (const MachineInstr &MI : MBB.terminators()) {
211 bool BreakNext = false;
212 for (const MachineOperand &MO : MI.operands()) {
213 if (!MO.isReg())
214 continue;
215 Register Reg = MO.getReg();
216 if (Reg != X86::EFLAGS)
217 continue;
218
219 // This terminator needs an eflags that is not defined
220 // by a previous another terminator:
221 // EFLAGS is live-in of the region composed by the terminators.
222 if (!MO.isDef())
223 return true;
224 // This terminator defines the eflags, i.e., we don't need to preserve it.
225 // However, we still need to check this specific terminator does not
226 // read a live-in value.
227 BreakNext = true;
228 }
229 // We found a definition of the eflags, no need to preserve them.
230 if (BreakNext)
231 return false;
232 }
233
234 // None of the terminators use or define the eflags.
235 // Check if they are live-out, that would imply we need to preserve them.
236 for (const MachineBasicBlock *Succ : MBB.successors())
237 if (Succ->isLiveIn(Reg: X86::EFLAGS))
238 return true;
239
240 return false;
241}
242
243constexpr uint64_t MaxSPChunk = (1ULL << 31) - 1;
244
245/// emitSPUpdate - Emit a series of instructions to increment / decrement the
246/// stack pointer by a constant value.
247void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
248 MachineBasicBlock::iterator &MBBI,
249 const DebugLoc &DL, int64_t NumBytes,
250 bool InEpilogue) const {
251 bool isSub = NumBytes < 0;
252 uint64_t Offset = isSub ? -NumBytes : NumBytes;
253 MachineInstr::MIFlag Flag =
254 isSub ? MachineInstr::FrameSetup : MachineInstr::FrameDestroy;
255
256 if (!Uses64BitFramePtr && !isUInt<32>(x: Offset)) {
257 // We're being asked to adjust a 32-bit stack pointer by 4 GiB or more.
258 // This might be unreachable code, so don't complain now; just trap if
259 // it's reached at runtime.
260 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::TRAP));
261 return;
262 }
263
264 MachineFunction &MF = *MBB.getParent();
265 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
266 const X86TargetLowering &TLI = *STI.getTargetLowering();
267 const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
268
269 // It's ok to not take into account large chunks when probing, as the
270 // allocation is split in smaller chunks anyway.
271 if (EmitInlineStackProbe && !InEpilogue) {
272
273 // This pseudo-instruction is going to be expanded, potentially using a
274 // loop, by inlineStackProbe().
275 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::STACKALLOC_W_PROBING)).addImm(Val: Offset);
276 return;
277 } else if (Offset > MaxSPChunk) {
278 // Rather than emit a long series of instructions for large offsets,
279 // load the offset into a register and do one sub/add
280 unsigned Reg = 0;
281 unsigned Rax = (unsigned)(Uses64BitFramePtr ? X86::RAX : X86::EAX);
282
283 if (isSub && !isEAXLiveIn(MBB))
284 Reg = Rax;
285 else
286 Reg = getX86SubSuperRegister(Reg: TRI->findDeadCallerSavedReg(MBB, MBBI),
287 Size: Uses64BitFramePtr ? 64 : 32);
288
289 unsigned AddSubRROpc = isSub ? getSUBrrOpcode(IsLP64: Uses64BitFramePtr)
290 : getADDrrOpcode(IsLP64: Uses64BitFramePtr);
291 if (Reg) {
292 BuildMI(BB&: MBB, I: MBBI, MIMD: DL,
293 MCID: TII.get(Opcode: X86::getMOVriOpcode(Use64BitReg: Uses64BitFramePtr, Imm: Offset)), DestReg: Reg)
294 .addImm(Val: Offset)
295 .setMIFlag(Flag);
296 MachineInstr *MI = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AddSubRROpc), DestReg: StackPtr)
297 .addReg(RegNo: StackPtr)
298 .addReg(RegNo: Reg);
299 MI->getOperand(i: 3).setIsDead(); // The EFLAGS implicit def is dead.
300 return;
301 } else if (Offset > 8 * MaxSPChunk) {
302 // If we would need more than 8 add or sub instructions (a >16GB stack
303 // frame), it's worth spilling RAX to materialize this immediate.
304 // pushq %rax
305 // movabsq +-$Offset+-SlotSize, %rax
306 // addq %rsp, %rax
307 // xchg %rax, (%rsp)
308 // movq (%rsp), %rsp
309 assert(Uses64BitFramePtr && "can't have 32-bit 16GB stack frame");
310 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::PUSH64r))
311 .addReg(RegNo: Rax, Flags: RegState::Kill)
312 .setMIFlag(Flag);
313 // Subtract is not commutative, so negate the offset and always use add.
314 // Subtract 8 less and add 8 more to account for the PUSH we just did.
315 if (isSub)
316 Offset = -(Offset - SlotSize);
317 else
318 Offset = Offset + SlotSize;
319 BuildMI(BB&: MBB, I: MBBI, MIMD: DL,
320 MCID: TII.get(Opcode: X86::getMOVriOpcode(Use64BitReg: Uses64BitFramePtr, Imm: Offset)), DestReg: Rax)
321 .addImm(Val: Offset)
322 .setMIFlag(Flag);
323 MachineInstr *MI = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::ADD64rr), DestReg: Rax)
324 .addReg(RegNo: Rax)
325 .addReg(RegNo: StackPtr);
326 MI->getOperand(i: 3).setIsDead(); // The EFLAGS implicit def is dead.
327 // Exchange the new SP in RAX with the top of the stack.
328 addRegOffset(
329 MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::XCHG64rm), DestReg: Rax).addReg(RegNo: Rax),
330 Reg: StackPtr, isKill: false, Offset: 0);
331 // Load new SP from the top of the stack into RSP.
332 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64rm), DestReg: StackPtr),
333 Reg: StackPtr, isKill: false, Offset: 0);
334 return;
335 }
336 }
337
338 while (Offset) {
339 if (Offset == SlotSize) {
340 // Use push / pop for slot sized adjustments as a size optimization. We
341 // need to find a dead register when using pop.
342 unsigned Reg = isSub ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
343 : TRI->findDeadCallerSavedReg(MBB, MBBI);
344 if (Reg) {
345 unsigned Opc = isSub ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
346 : (Is64Bit ? X86::POP64r : X86::POP32r);
347 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: Opc))
348 .addReg(RegNo: Reg, Flags: getDefRegState(B: !isSub) | getUndefRegState(B: isSub))
349 .setMIFlag(Flag);
350 return;
351 }
352 }
353
354 uint64_t ThisVal = std::min(a: Offset, b: MaxSPChunk);
355
356 BuildStackAdjustment(MBB, MBBI, DL, Offset: isSub ? -ThisVal : ThisVal, InEpilogue)
357 .setMIFlag(Flag);
358
359 Offset -= ThisVal;
360 }
361}
362
363MachineInstrBuilder X86FrameLowering::BuildStackAdjustment(
364 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
365 const DebugLoc &DL, int64_t Offset, bool InEpilogue) const {
366 assert(Offset != 0 && "zero offset stack adjustment requested");
367
368 // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue
369 // is tricky.
370 bool UseLEA;
371 if (!InEpilogue) {
372 // Check if inserting the prologue at the beginning
373 // of MBB would require to use LEA operations.
374 // We need to use LEA operations if EFLAGS is live in, because
375 // it means an instruction will read it before it gets defined.
376 UseLEA = STI.useLeaForSP() || MBB.isLiveIn(Reg: X86::EFLAGS);
377 } else {
378 // If we can use LEA for SP but we shouldn't, check that none
379 // of the terminators uses the eflags. Otherwise we will insert
380 // a ADD that will redefine the eflags and break the condition.
381 // Alternatively, we could move the ADD, but this may not be possible
382 // and is an optimization anyway.
383 UseLEA = canUseLEAForSPInEpilogue(MF: *MBB.getParent());
384 if (UseLEA && !STI.useLeaForSP())
385 UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB);
386 // If that assert breaks, that means we do not do the right thing
387 // in canUseAsEpilogue.
388 assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) &&
389 "We shouldn't have allowed this insertion point");
390 }
391
392 MachineInstrBuilder MI;
393 // Use an NF (no-flags) variant as a smaller replacement for LEA when EFLAGS
394 // must be preserved (i.e. only when we would otherwise emit LEA). If EFLAGS
395 // is dead we prefer the plain SUB/ADD, which is shorter than the EVEX-encoded
396 // NF form. The NF stack-adjust opcodes below are 64-bit (SUB64ri32_NF/
397 // ADD64ri32_NF), so don't use them for the x32 ABI where the stack pointer is
398 // 32-bit. NF cannot reach a Win64 epilogue (which never uses LEA for the SP
399 // adjustment unless it has a frame pointer, and that path doesn't go through
400 // here), so the Windows epilogue unwinder never sees an undisassemblable NF
401 // add/sub.
402 bool UseNF = UseLEA && STI.hasNF() && Uses64BitFramePtr;
403 bool IsSub = Offset < 0;
404 uint64_t AbsOffset = IsSub ? -Offset : Offset;
405 if (UseNF) {
406 const unsigned Opc = IsSub ? X86::SUB64ri32_NF : X86::ADD64ri32_NF;
407 MI = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: StackPtr)
408 .addReg(RegNo: StackPtr)
409 .addImm(Val: AbsOffset);
410 // NF instructions define no EFLAGS, so there is nothing to mark dead.
411 } else if (UseLEA) {
412 MI = addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL,
413 MCID: TII.get(Opcode: getLEArOpcode(IsLP64: Uses64BitFramePtr)),
414 DestReg: StackPtr),
415 Reg: StackPtr, isKill: false, Offset);
416 } else {
417 unsigned Opc = IsSub ? getSUBriOpcode(IsLP64: Uses64BitFramePtr)
418 : getADDriOpcode(IsLP64: Uses64BitFramePtr);
419 int64_t Imm = AbsOffset;
420 // Prefer `add rsp, -128` over `sub rsp, 128` (and vice versa in the
421 // epilogue): 128 is the one magnitude whose negation fits the
422 // sign-extended 8-bit immediate while the value itself does not, so the
423 // flipped operation is three bytes shorter. EFLAGS is dead here (this
424 // branch clobbers it anyway). Windows CFI epilogues keep the canonical
425 // ADD: v1 unwind info describes no epilogues, so the unwinder detects
426 // one by disassembling forward for `add rsp, imm` (prologues are
427 // delimited by SizeOfProlog and never disassembled). Unwind v2/v3 do
428 // describe epilogues, but X86WinEHUnwindV2 expects the ADD spelling
429 // too.
430 if (AbsOffset == 128 &&
431 !(InEpilogue &&
432 MBB.getParent()->getTarget().getMCAsmInfo().usesWindowsCFI())) {
433 Opc = IsSub ? getADDriOpcode(IsLP64: Uses64BitFramePtr)
434 : getSUBriOpcode(IsLP64: Uses64BitFramePtr);
435 Imm = -128;
436 }
437 MI = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: StackPtr)
438 .addReg(RegNo: StackPtr)
439 .addImm(Val: Imm);
440 MI->getOperand(i: 3).setIsDead(); // The EFLAGS implicit def is dead.
441 }
442 return MI;
443}
444
445template <typename FoundT, typename CalcT>
446int64_t X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
447 MachineBasicBlock::iterator &MBBI,
448 FoundT FoundStackAdjust,
449 CalcT CalcNewOffset,
450 bool doMergeWithPrevious) const {
451 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
452 (!doMergeWithPrevious && MBBI == MBB.end()))
453 return CalcNewOffset(0);
454
455 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(x: MBBI) : MBBI;
456
457 PI = skipDebugInstructionsBackward(It: PI, Begin: MBB.begin());
458 // It is assumed that ADD/SUB/LEA instruction is succeded by one CFI
459 // instruction, and that there are no DBG_VALUE or other instructions between
460 // ADD/SUB/LEA and its corresponding CFI instruction.
461 /* TODO: Add support for the case where there are multiple CFI instructions
462 below the ADD/SUB/LEA, e.g.:
463 ...
464 add
465 cfi_def_cfa_offset
466 cfi_offset
467 ...
468 */
469 if (doMergeWithPrevious && PI != MBB.begin() && PI->isCFIInstruction())
470 PI = std::prev(x: PI);
471
472 int64_t Offset = 0;
473 for (;;) {
474 unsigned Opc = PI->getOpcode();
475
476 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD32ri ||
477 Opc == X86::ADD64ri32_NF) &&
478 PI->getOperand(i: 0).getReg() == StackPtr) {
479 assert(PI->getOperand(1).getReg() == StackPtr);
480 Offset = PI->getOperand(i: 2).getImm();
481 } else if ((Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
482 PI->getOperand(i: 0).getReg() == StackPtr &&
483 PI->getOperand(i: 1).getReg() == StackPtr &&
484 PI->getOperand(i: 2).getImm() == 1 &&
485 PI->getOperand(i: 3).getReg() == X86::NoRegister &&
486 PI->getOperand(i: 5).getReg() == X86::NoRegister) {
487 // For LEAs we have: def = lea SP, FI, noreg, Offset, noreg.
488 Offset = PI->getOperand(i: 4).getImm();
489 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB32ri ||
490 Opc == X86::SUB64ri32_NF) &&
491 PI->getOperand(i: 0).getReg() == StackPtr) {
492 assert(PI->getOperand(1).getReg() == StackPtr);
493 Offset = -PI->getOperand(i: 2).getImm();
494 } else
495 return CalcNewOffset(0);
496
497 FoundStackAdjust(PI, Offset);
498 if ((uint64_t)std::abs(i: (int64_t)CalcNewOffset(Offset)) < MaxSPChunk)
499 break;
500
501 if (doMergeWithPrevious ? (PI == MBB.begin()) : (PI == MBB.end()))
502 return CalcNewOffset(0);
503
504 PI = doMergeWithPrevious ? std::prev(x: PI) : std::next(x: PI);
505 }
506
507 PI = MBB.erase(I: PI);
508 if (PI != MBB.end() && PI->isCFIInstruction()) {
509 auto CIs = MBB.getParent()->getFrameInstructions();
510 MCCFIInstruction CI = CIs[PI->getOperand(i: 0).getCFIIndex()];
511 if (CI.getOperation() == MCCFIInstruction::OpDefCfaOffset ||
512 CI.getOperation() == MCCFIInstruction::OpAdjustCfaOffset)
513 PI = MBB.erase(I: PI);
514 }
515 if (!doMergeWithPrevious)
516 MBBI = skipDebugInstructionsForward(It: PI, End: MBB.end());
517
518 return CalcNewOffset(Offset);
519}
520
521int64_t X86FrameLowering::mergeSPAdd(MachineBasicBlock &MBB,
522 MachineBasicBlock::iterator &MBBI,
523 int64_t AddOffset,
524 bool doMergeWithPrevious) const {
525 return mergeSPUpdates(
526 MBB, MBBI, CalcNewOffset: [AddOffset](int64_t Offset) { return AddOffset + Offset; },
527 doMergeWithPrevious);
528}
529
530void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB,
531 MachineBasicBlock::iterator MBBI,
532 const DebugLoc &DL,
533 const MCCFIInstruction &CFIInst,
534 MachineInstr::MIFlag Flag) const {
535 MachineFunction &MF = *MBB.getParent();
536 unsigned CFIIndex = MF.addFrameInst(Inst: CFIInst);
537
538 if (CFIInst.getOperation() == MCCFIInstruction::OpAdjustCfaOffset)
539 MF.getInfo<X86MachineFunctionInfo>()->setHasCFIAdjustCfa(true);
540
541 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: TargetOpcode::CFI_INSTRUCTION))
542 .addCFIIndex(CFIIndex)
543 .setMIFlag(Flag);
544}
545
546/// Emits Dwarf Info specifying offsets of callee saved registers and
547/// frame pointer. This is called only when basic block sections are enabled.
548void X86FrameLowering::emitCalleeSavedFrameMovesFullCFA(
549 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI) const {
550 MachineFunction &MF = *MBB.getParent();
551 if (!hasFP(MF)) {
552 emitCalleeSavedFrameMoves(MBB, MBBI, DL: DebugLoc{}, IsPrologue: true);
553 return;
554 }
555 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
556 const Register FramePtr = TRI->getFrameRegister(MF);
557 const Register MachineFramePtr =
558 STI.isTarget64BitILP32() ? Register(getX86SubSuperRegister(Reg: FramePtr, Size: 64))
559 : FramePtr;
560 unsigned DwarfReg = MRI->getDwarfRegNum(Reg: MachineFramePtr, isEH: true);
561 // Offset = space for return address + size of the frame pointer itself.
562 int64_t Offset = (Is64Bit ? 8 : 4) + (Uses64BitFramePtr ? 8 : 4);
563 BuildCFI(MBB, MBBI, DL: DebugLoc{},
564 CFIInst: MCCFIInstruction::createOffset(L: nullptr, Register: DwarfReg, Offset: -Offset));
565 emitCalleeSavedFrameMoves(MBB, MBBI, DL: DebugLoc{}, IsPrologue: true);
566}
567
568void X86FrameLowering::emitCalleeSavedFrameMoves(
569 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
570 const DebugLoc &DL, bool IsPrologue) const {
571 MachineFunction &MF = *MBB.getParent();
572 MachineFrameInfo &MFI = MF.getFrameInfo();
573 const MCRegisterInfo *MRI = MF.getContext().getRegisterInfo();
574 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
575
576 // Add callee saved registers to move list.
577 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
578
579 // Calculate offsets.
580 for (const CalleeSavedInfo &I : CSI) {
581 int64_t Offset = MFI.getObjectOffset(ObjectIdx: I.getFrameIdx());
582 MCRegister Reg = I.getReg();
583 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, isEH: true);
584
585 if (IsPrologue) {
586 if (X86FI->getStackPtrSaveMI()) {
587 // +2*SlotSize because there is return address and ebp at the bottom
588 // of the stack.
589 // | retaddr |
590 // | ebp |
591 // | |<--ebp
592 Offset += 2 * SlotSize;
593 SmallString<64> CfaExpr;
594 CfaExpr.push_back(Elt: dwarf::DW_CFA_expression);
595 uint8_t buffer[16];
596 CfaExpr.append(in_start: buffer, in_end: buffer + encodeULEB128(Value: DwarfReg, p: buffer));
597 CfaExpr.push_back(Elt: 2);
598 Register FramePtr = TRI->getFrameRegister(MF);
599 const Register MachineFramePtr =
600 STI.isTarget64BitILP32()
601 ? Register(getX86SubSuperRegister(Reg: FramePtr, Size: 64))
602 : FramePtr;
603 unsigned DwarfFramePtr = MRI->getDwarfRegNum(Reg: MachineFramePtr, isEH: true);
604 CfaExpr.push_back(Elt: (uint8_t)(dwarf::DW_OP_breg0 + DwarfFramePtr));
605 CfaExpr.append(in_start: buffer, in_end: buffer + encodeSLEB128(Value: Offset, p: buffer));
606 BuildCFI(MBB, MBBI, DL,
607 CFIInst: MCCFIInstruction::createEscape(L: nullptr, Vals: CfaExpr.str()),
608 Flag: MachineInstr::FrameSetup);
609 } else {
610 BuildCFI(MBB, MBBI, DL,
611 CFIInst: MCCFIInstruction::createOffset(L: nullptr, Register: DwarfReg, Offset));
612 }
613 } else {
614 BuildCFI(MBB, MBBI, DL,
615 CFIInst: MCCFIInstruction::createRestore(L: nullptr, Register: DwarfReg));
616 }
617 }
618 if (auto *MI = X86FI->getStackPtrSaveMI()) {
619 int FI = MI->getOperand(i: 1).getIndex();
620 int64_t Offset = MFI.getObjectOffset(ObjectIdx: FI) + 2 * SlotSize;
621 SmallString<64> CfaExpr;
622 Register FramePtr = TRI->getFrameRegister(MF);
623 const Register MachineFramePtr =
624 STI.isTarget64BitILP32()
625 ? Register(getX86SubSuperRegister(Reg: FramePtr, Size: 64))
626 : FramePtr;
627 unsigned DwarfFramePtr = MRI->getDwarfRegNum(Reg: MachineFramePtr, isEH: true);
628 CfaExpr.push_back(Elt: (uint8_t)(dwarf::DW_OP_breg0 + DwarfFramePtr));
629 uint8_t buffer[16];
630 CfaExpr.append(in_start: buffer, in_end: buffer + encodeSLEB128(Value: Offset, p: buffer));
631 CfaExpr.push_back(Elt: dwarf::DW_OP_deref);
632
633 SmallString<64> DefCfaExpr;
634 DefCfaExpr.push_back(Elt: dwarf::DW_CFA_def_cfa_expression);
635 DefCfaExpr.append(in_start: buffer, in_end: buffer + encodeSLEB128(Value: CfaExpr.size(), p: buffer));
636 DefCfaExpr.append(RHS: CfaExpr.str());
637 // DW_CFA_def_cfa_expression: DW_OP_breg5 offset, DW_OP_deref
638 BuildCFI(MBB, MBBI, DL,
639 CFIInst: MCCFIInstruction::createEscape(L: nullptr, Vals: DefCfaExpr.str()),
640 Flag: MachineInstr::FrameSetup);
641 }
642}
643
644void X86FrameLowering::emitZeroCallUsedRegs(BitVector RegsToZero,
645 MachineBasicBlock &MBB,
646 RegScavenger *) const {
647 const MachineFunction &MF = *MBB.getParent();
648
649 // Insertion point.
650 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
651
652 // Fake a debug loc.
653 DebugLoc DL;
654 if (MBBI != MBB.end())
655 DL = MBBI->getDebugLoc();
656
657 // Zero out FP stack if referenced. Do this outside of the loop below so that
658 // it's done only once.
659 for (MCRegister Reg : RegsToZero.set_bits()) {
660 if (!X86::RFP80RegClass.contains(Reg))
661 continue;
662
663 // Do not push zeros over x87 return values. X86FloatingPoint records
664 // returned values as implicit ST0/ST1 uses on the return instruction.
665 unsigned NumFPRegs = 8;
666 if (MBBI->hasRegisterImplicitUseOperand(Reg: X86::ST0))
667 --NumFPRegs;
668 if (MBBI->hasRegisterImplicitUseOperand(Reg: X86::ST1))
669 --NumFPRegs;
670
671 for (unsigned i = 0; i != NumFPRegs; ++i)
672 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::LD_F0));
673
674 for (unsigned i = 0; i != NumFPRegs; ++i)
675 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::ST_FPrr)).addReg(RegNo: X86::ST0);
676 break;
677 }
678
679 // For GPRs, we only care to clear out the 32-bit register.
680 BitVector GPRsToZero(TRI->getNumRegs());
681 for (MCRegister Reg : RegsToZero.set_bits())
682 if (TRI->isGeneralPurposeRegister(MF, Reg)) {
683 GPRsToZero.set(getX86SubSuperRegister(Reg, Size: 32));
684 RegsToZero.reset(Idx: Reg);
685 }
686
687 // Zero out the GPRs first.
688 for (MCRegister Reg : GPRsToZero.set_bits())
689 TII.buildClearRegister(Reg, MBB, Iter: MBBI, DL);
690
691 // Zero out the remaining registers.
692 for (MCRegister Reg : RegsToZero.set_bits())
693 TII.buildClearRegister(Reg, MBB, Iter: MBBI, DL);
694}
695
696void X86FrameLowering::emitStackProbe(
697 MachineFunction &MF, MachineBasicBlock &MBB,
698 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
699 std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
700 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
701 if (STI.isTargetWindowsCoreCLR()) {
702 if (InProlog) {
703 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::STACKALLOC_W_PROBING))
704 .addImm(Val: 0 /* no explicit stack size */);
705 } else {
706 emitStackProbeInline(MF, MBB, MBBI, DL, InProlog: false);
707 }
708 } else {
709 emitStackProbeCall(MF, MBB, MBBI, DL, InProlog, InstrNum);
710 }
711}
712
713bool X86FrameLowering::stackProbeFunctionModifiesSP() const {
714 return STI.isOSWindows() && !STI.isTargetWin64();
715}
716
717void X86FrameLowering::inlineStackProbe(MachineFunction &MF,
718 MachineBasicBlock &PrologMBB) const {
719 auto Where = llvm::find_if(Range&: PrologMBB, P: [](MachineInstr &MI) {
720 return MI.getOpcode() == X86::STACKALLOC_W_PROBING;
721 });
722 if (Where != PrologMBB.end()) {
723 DebugLoc DL = PrologMBB.findDebugLoc(MBBI: Where);
724 emitStackProbeInline(MF, MBB&: PrologMBB, MBBI: Where, DL, InProlog: true);
725 Where->eraseFromParent();
726 }
727}
728
729void X86FrameLowering::emitStackProbeInline(MachineFunction &MF,
730 MachineBasicBlock &MBB,
731 MachineBasicBlock::iterator MBBI,
732 const DebugLoc &DL,
733 bool InProlog) const {
734 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
735 if (STI.isTargetWindowsCoreCLR() && STI.is64Bit())
736 emitStackProbeInlineWindowsCoreCLR64(MF, MBB, MBBI, DL, InProlog);
737 else
738 emitStackProbeInlineGeneric(MF, MBB, MBBI, DL, InProlog);
739}
740
741void X86FrameLowering::emitStackProbeInlineGeneric(
742 MachineFunction &MF, MachineBasicBlock &MBB,
743 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
744 MachineInstr &AllocWithProbe = *MBBI;
745 uint64_t Offset = AllocWithProbe.getOperand(i: 0).getImm();
746
747 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
748 const X86TargetLowering &TLI = *STI.getTargetLowering();
749 assert(!(STI.is64Bit() && STI.isTargetWindowsCoreCLR()) &&
750 "different expansion expected for CoreCLR 64 bit");
751
752 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
753 uint64_t ProbeChunk = StackProbeSize * 8;
754
755 uint64_t MaxAlign =
756 TRI->hasStackRealignment(MF) ? calculateMaxStackAlign(MF) : 0;
757
758 // Synthesize a loop or unroll it, depending on the number of iterations.
759 // BuildStackAlignAND ensures that only MaxAlign % StackProbeSize bits left
760 // between the unaligned rsp and current rsp.
761 if (Offset > ProbeChunk) {
762 emitStackProbeInlineGenericLoop(MF, MBB, MBBI, DL, Offset,
763 Align: MaxAlign % StackProbeSize);
764 } else {
765 emitStackProbeInlineGenericBlock(MF, MBB, MBBI, DL, Offset,
766 Align: MaxAlign % StackProbeSize);
767 }
768}
769
770void X86FrameLowering::emitStackProbeInlineGenericBlock(
771 MachineFunction &MF, MachineBasicBlock &MBB,
772 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, uint64_t Offset,
773 uint64_t AlignOffset) const {
774
775 const bool NeedsDwarfCFI = needsDwarfCFI(MF);
776 const bool HasFP = hasFP(MF);
777 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
778 const X86TargetLowering &TLI = *STI.getTargetLowering();
779 const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
780 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
781
782 uint64_t CurrentOffset = 0;
783
784 assert(AlignOffset < StackProbeSize);
785
786 // If the offset is so small it fits within a page, there's nothing to do.
787 if (StackProbeSize < Offset + AlignOffset) {
788
789 uint64_t StackAdjustment = StackProbeSize - AlignOffset;
790 BuildStackAdjustment(MBB, MBBI, DL, Offset: -StackAdjustment, /*InEpilogue=*/false)
791 .setMIFlag(MachineInstr::FrameSetup);
792 if (!HasFP && NeedsDwarfCFI) {
793 BuildCFI(
794 MBB, MBBI, DL,
795 CFIInst: MCCFIInstruction::createAdjustCfaOffset(L: nullptr, Adjustment: StackAdjustment));
796 }
797
798 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: MovMIOpc))
799 .setMIFlag(MachineInstr::FrameSetup),
800 Reg: StackPtr, isKill: false, Offset: 0)
801 .addImm(Val: 0)
802 .setMIFlag(MachineInstr::FrameSetup);
803 NumFrameExtraProbe++;
804 CurrentOffset = StackProbeSize - AlignOffset;
805 }
806
807 // For the next N - 1 pages, just probe. I tried to take advantage of
808 // natural probes but it implies much more logic and there was very few
809 // interesting natural probes to interleave.
810 while (CurrentOffset + StackProbeSize < Offset) {
811 BuildStackAdjustment(MBB, MBBI, DL, Offset: -StackProbeSize, /*InEpilogue=*/false)
812 .setMIFlag(MachineInstr::FrameSetup);
813
814 if (!HasFP && NeedsDwarfCFI) {
815 BuildCFI(
816 MBB, MBBI, DL,
817 CFIInst: MCCFIInstruction::createAdjustCfaOffset(L: nullptr, Adjustment: StackProbeSize));
818 }
819 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: MovMIOpc))
820 .setMIFlag(MachineInstr::FrameSetup),
821 Reg: StackPtr, isKill: false, Offset: 0)
822 .addImm(Val: 0)
823 .setMIFlag(MachineInstr::FrameSetup);
824 NumFrameExtraProbe++;
825 CurrentOffset += StackProbeSize;
826 }
827
828 // No need to probe the tail, it is smaller than a Page.
829 uint64_t ChunkSize = Offset - CurrentOffset;
830 if (ChunkSize == SlotSize) {
831 // Use push for slot sized adjustments as a size optimization,
832 // like emitSPUpdate does when not probing.
833 unsigned Reg = Is64Bit ? X86::RAX : X86::EAX;
834 unsigned Opc = Is64Bit ? X86::PUSH64r : X86::PUSH32r;
835 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: Opc))
836 .addReg(RegNo: Reg, Flags: RegState::Undef)
837 .setMIFlag(MachineInstr::FrameSetup);
838 } else {
839 BuildStackAdjustment(MBB, MBBI, DL, Offset: -ChunkSize, /*InEpilogue=*/false)
840 .setMIFlag(MachineInstr::FrameSetup);
841 }
842 // No need to adjust Dwarf CFA offset here, the last position of the stack has
843 // been defined
844}
845
846void X86FrameLowering::emitStackProbeInlineGenericLoop(
847 MachineFunction &MF, MachineBasicBlock &MBB,
848 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, uint64_t Offset,
849 uint64_t AlignOffset) const {
850 assert(Offset && "null offset");
851
852 assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
853 MachineBasicBlock::LQR_Live &&
854 "Inline stack probe loop will clobber live EFLAGS.");
855
856 const bool NeedsDwarfCFI = needsDwarfCFI(MF);
857 const bool HasFP = hasFP(MF);
858 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
859 const X86TargetLowering &TLI = *STI.getTargetLowering();
860 const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
861 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
862
863 if (AlignOffset) {
864 if (AlignOffset < StackProbeSize) {
865 // Perform a first smaller allocation followed by a probe.
866 BuildStackAdjustment(MBB, MBBI, DL, Offset: -AlignOffset, /*InEpilogue=*/false)
867 .setMIFlag(MachineInstr::FrameSetup);
868
869 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: MovMIOpc))
870 .setMIFlag(MachineInstr::FrameSetup),
871 Reg: StackPtr, isKill: false, Offset: 0)
872 .addImm(Val: 0)
873 .setMIFlag(MachineInstr::FrameSetup);
874 NumFrameExtraProbe++;
875 Offset -= AlignOffset;
876 }
877 }
878
879 // Synthesize a loop
880 NumFrameLoopProbe++;
881 const BasicBlock *LLVM_BB = MBB.getBasicBlock();
882
883 MachineBasicBlock *testMBB = MF.CreateMachineBasicBlock(BB: LLVM_BB);
884 MachineBasicBlock *tailMBB = MF.CreateMachineBasicBlock(BB: LLVM_BB);
885
886 MachineFunction::iterator MBBIter = ++MBB.getIterator();
887 MF.insert(MBBI: MBBIter, MBB: testMBB);
888 MF.insert(MBBI: MBBIter, MBB: tailMBB);
889
890 Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
891 : Is64Bit ? X86::R11D
892 : X86::EAX;
893
894 // save loop bound
895 {
896 const uint64_t BoundOffset = alignDown(Value: Offset, Align: StackProbeSize);
897
898 // Can we calculate the loop bound using SUB with a 32-bit immediate?
899 // Note that the immediate gets sign-extended when used with a 64-bit
900 // register, so in that case we only have 31 bits to work with.
901 bool canUseSub =
902 Uses64BitFramePtr ? isUInt<31>(x: BoundOffset) : isUInt<32>(x: BoundOffset);
903
904 if (canUseSub) {
905 const unsigned SUBOpc = getSUBriOpcode(IsLP64: Uses64BitFramePtr);
906
907 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: TargetOpcode::COPY), DestReg: FinalStackProbed)
908 .addReg(RegNo: StackPtr)
909 .setMIFlag(MachineInstr::FrameSetup);
910 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: SUBOpc), DestReg: FinalStackProbed)
911 .addReg(RegNo: FinalStackProbed)
912 .addImm(Val: BoundOffset)
913 .setMIFlag(MachineInstr::FrameSetup);
914 } else if (Uses64BitFramePtr) {
915 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64ri), DestReg: FinalStackProbed)
916 .addImm(Val: -BoundOffset)
917 .setMIFlag(MachineInstr::FrameSetup);
918 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::ADD64rr), DestReg: FinalStackProbed)
919 .addReg(RegNo: FinalStackProbed)
920 .addReg(RegNo: StackPtr)
921 .setMIFlag(MachineInstr::FrameSetup);
922 } else {
923 llvm_unreachable("Offset too large for 32-bit stack pointer");
924 }
925
926 // while in the loop, use loop-invariant reg for CFI,
927 // instead of the stack pointer, which changes during the loop
928 if (!HasFP && NeedsDwarfCFI) {
929 // x32 uses the same DWARF register numbers as x86-64,
930 // so there isn't a register number for r11d, we must use r11 instead
931 const Register DwarfFinalStackProbed =
932 STI.isTarget64BitILP32()
933 ? Register(getX86SubSuperRegister(Reg: FinalStackProbed, Size: 64))
934 : FinalStackProbed;
935
936 BuildCFI(MBB, MBBI, DL,
937 CFIInst: MCCFIInstruction::createDefCfaRegister(
938 L: nullptr, Register: TRI->getDwarfRegNum(Reg: DwarfFinalStackProbed, isEH: true)));
939 BuildCFI(MBB, MBBI, DL,
940 CFIInst: MCCFIInstruction::createAdjustCfaOffset(L: nullptr, Adjustment: BoundOffset));
941 }
942 }
943
944 // allocate a page
945 BuildStackAdjustment(MBB&: *testMBB, MBBI: testMBB->end(), DL, Offset: -StackProbeSize,
946 /*InEpilogue=*/false)
947 .setMIFlag(MachineInstr::FrameSetup);
948
949 // touch the page
950 addRegOffset(MIB: BuildMI(BB: testMBB, MIMD: DL, MCID: TII.get(Opcode: MovMIOpc))
951 .setMIFlag(MachineInstr::FrameSetup),
952 Reg: StackPtr, isKill: false, Offset: 0)
953 .addImm(Val: 0)
954 .setMIFlag(MachineInstr::FrameSetup);
955
956 // cmp with stack pointer bound
957 BuildMI(BB: testMBB, MIMD: DL, MCID: TII.get(Opcode: Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
958 .addReg(RegNo: StackPtr)
959 .addReg(RegNo: FinalStackProbed)
960 .setMIFlag(MachineInstr::FrameSetup);
961
962 // jump
963 BuildMI(BB: testMBB, MIMD: DL, MCID: TII.get(Opcode: X86::JCC_1))
964 .addMBB(MBB: testMBB)
965 .addImm(Val: X86::COND_NE)
966 .setMIFlag(MachineInstr::FrameSetup);
967 testMBB->addSuccessor(Succ: testMBB);
968 testMBB->addSuccessor(Succ: tailMBB);
969
970 // BB management
971 tailMBB->splice(Where: tailMBB->end(), Other: &MBB, From: MBBI, To: MBB.end());
972 tailMBB->transferSuccessorsAndUpdatePHIs(FromMBB: &MBB);
973 MBB.addSuccessor(Succ: testMBB);
974
975 // handle tail
976 const uint64_t TailOffset = Offset % StackProbeSize;
977 MachineBasicBlock::iterator TailMBBIter = tailMBB->begin();
978 if (TailOffset) {
979 BuildStackAdjustment(MBB&: *tailMBB, MBBI: TailMBBIter, DL, Offset: -TailOffset,
980 /*InEpilogue=*/false)
981 .setMIFlag(MachineInstr::FrameSetup);
982 }
983
984 // after the loop, switch back to stack pointer for CFI
985 if (!HasFP && NeedsDwarfCFI) {
986 // x32 uses the same DWARF register numbers as x86-64,
987 // so there isn't a register number for esp, we must use rsp instead
988 const Register DwarfStackPtr =
989 STI.isTarget64BitILP32()
990 ? Register(getX86SubSuperRegister(Reg: StackPtr, Size: 64))
991 : Register(StackPtr);
992
993 BuildCFI(MBB&: *tailMBB, MBBI: TailMBBIter, DL,
994 CFIInst: MCCFIInstruction::createDefCfaRegister(
995 L: nullptr, Register: TRI->getDwarfRegNum(Reg: DwarfStackPtr, isEH: true)));
996 }
997
998 // Update Live In information
999 fullyRecomputeLiveIns(MBBs: {tailMBB, testMBB});
1000}
1001
1002void X86FrameLowering::emitStackProbeInlineWindowsCoreCLR64(
1003 MachineFunction &MF, MachineBasicBlock &MBB,
1004 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog) const {
1005 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1006 assert(STI.is64Bit() && "different expansion needed for 32 bit");
1007 assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
1008 const TargetInstrInfo &TII = *STI.getInstrInfo();
1009 const BasicBlock *LLVM_BB = MBB.getBasicBlock();
1010
1011 assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
1012 MachineBasicBlock::LQR_Live &&
1013 "Inline stack probe loop will clobber live EFLAGS.");
1014
1015 // RAX contains the number of bytes of desired stack adjustment.
1016 // The handling here assumes this value has already been updated so as to
1017 // maintain stack alignment.
1018 //
1019 // We need to exit with RSP modified by this amount and execute suitable
1020 // page touches to notify the OS that we're growing the stack responsibly.
1021 // All stack probing must be done without modifying RSP.
1022 //
1023 // MBB:
1024 // SizeReg = RAX;
1025 // ZeroReg = 0
1026 // CopyReg = RSP
1027 // Flags, TestReg = CopyReg - SizeReg
1028 // FinalReg = !Flags.Ovf ? TestReg : ZeroReg
1029 // LimitReg = gs magic thread env access
1030 // if FinalReg >= LimitReg goto ContinueMBB
1031 // RoundBB:
1032 // RoundReg = page address of FinalReg
1033 // LoopMBB:
1034 // LoopReg = PHI(LimitReg,ProbeReg)
1035 // ProbeReg = LoopReg - PageSize
1036 // [ProbeReg] = 0
1037 // if (ProbeReg > RoundReg) goto LoopMBB
1038 // ContinueMBB:
1039 // RSP = RSP - RAX
1040 // [rest of original MBB]
1041
1042 // Set up the new basic blocks
1043 MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(BB: LLVM_BB);
1044 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(BB: LLVM_BB);
1045 MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(BB: LLVM_BB);
1046
1047 MachineFunction::iterator MBBIter = std::next(x: MBB.getIterator());
1048 MF.insert(MBBI: MBBIter, MBB: RoundMBB);
1049 MF.insert(MBBI: MBBIter, MBB: LoopMBB);
1050 MF.insert(MBBI: MBBIter, MBB: ContinueMBB);
1051
1052 // Split MBB and move the tail portion down to ContinueMBB.
1053 MachineBasicBlock::iterator BeforeMBBI = std::prev(x: MBBI);
1054 ContinueMBB->splice(Where: ContinueMBB->begin(), Other: &MBB, From: MBBI, To: MBB.end());
1055 ContinueMBB->transferSuccessorsAndUpdatePHIs(FromMBB: &MBB);
1056
1057 // Some useful constants
1058 const int64_t ThreadEnvironmentStackLimit = 0x10;
1059 const int64_t PageSize = 0x1000;
1060 const int64_t PageMask = ~(PageSize - 1);
1061
1062 // Registers we need. For the normal case we use virtual
1063 // registers. For the prolog expansion we use RAX, RCX and RDX.
1064 MachineRegisterInfo &MRI = MF.getRegInfo();
1065 const TargetRegisterClass *RegClass = &X86::GR64RegClass;
1066 const Register
1067 SizeReg = InProlog ? X86::RAX : MRI.createVirtualRegister(RegClass),
1068 ZeroReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass),
1069 CopyReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
1070 TestReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
1071 FinalReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
1072 RoundedReg = InProlog ? X86::RDX : MRI.createVirtualRegister(RegClass),
1073 LimitReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass),
1074 JoinReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass),
1075 ProbeReg = InProlog ? X86::RCX : MRI.createVirtualRegister(RegClass);
1076
1077 // SP-relative offsets where we can save RCX and RDX.
1078 int64_t RCXShadowSlot = 0;
1079 int64_t RDXShadowSlot = 0;
1080
1081 // If inlining in the prolog, save RCX and RDX.
1082 if (InProlog) {
1083 // Compute the offsets. We need to account for things already
1084 // pushed onto the stack at this point: return address, frame
1085 // pointer (if used), and callee saves.
1086 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1087 const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
1088 const bool HasFP = hasFP(MF);
1089
1090 // Check if we need to spill RCX and/or RDX.
1091 // Here we assume that no earlier prologue instruction changes RCX and/or
1092 // RDX, so checking the block live-ins is enough.
1093 const bool IsRCXLiveIn = MBB.isLiveIn(Reg: X86::RCX);
1094 const bool IsRDXLiveIn = MBB.isLiveIn(Reg: X86::RDX);
1095 int64_t InitSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
1096 // Assign the initial slot to both registers, then change RDX's slot if both
1097 // need to be spilled.
1098 if (IsRCXLiveIn)
1099 RCXShadowSlot = InitSlot;
1100 if (IsRDXLiveIn)
1101 RDXShadowSlot = InitSlot;
1102 if (IsRDXLiveIn && IsRCXLiveIn)
1103 RDXShadowSlot += 8;
1104 // Emit the saves if needed.
1105 if (IsRCXLiveIn)
1106 addRegOffset(MIB: BuildMI(BB: &MBB, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64mr)), Reg: X86::RSP, isKill: false,
1107 Offset: RCXShadowSlot)
1108 .addReg(RegNo: X86::RCX);
1109 if (IsRDXLiveIn)
1110 addRegOffset(MIB: BuildMI(BB: &MBB, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64mr)), Reg: X86::RSP, isKill: false,
1111 Offset: RDXShadowSlot)
1112 .addReg(RegNo: X86::RDX);
1113 } else {
1114 // Not in the prolog. Copy RAX to a virtual reg.
1115 BuildMI(BB: &MBB, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64rr), DestReg: SizeReg).addReg(RegNo: X86::RAX);
1116 }
1117
1118 // Add code to MBB to check for overflow and set the new target stack pointer
1119 // to zero if so.
1120 BuildMI(BB: &MBB, MIMD: DL, MCID: TII.get(Opcode: X86::XOR64rr), DestReg: ZeroReg)
1121 .addReg(RegNo: ZeroReg, Flags: RegState::Undef)
1122 .addReg(RegNo: ZeroReg, Flags: RegState::Undef);
1123 BuildMI(BB: &MBB, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64rr), DestReg: CopyReg).addReg(RegNo: X86::RSP);
1124 BuildMI(BB: &MBB, MIMD: DL, MCID: TII.get(Opcode: X86::SUB64rr), DestReg: TestReg)
1125 .addReg(RegNo: CopyReg)
1126 .addReg(RegNo: SizeReg);
1127 BuildMI(BB: &MBB, MIMD: DL, MCID: TII.get(Opcode: X86::CMOV64rr), DestReg: FinalReg)
1128 .addReg(RegNo: TestReg)
1129 .addReg(RegNo: ZeroReg)
1130 .addImm(Val: X86::COND_B);
1131
1132 // FinalReg now holds final stack pointer value, or zero if
1133 // allocation would overflow. Compare against the current stack
1134 // limit from the thread environment block. Note this limit is the
1135 // lowest touched page on the stack, not the point at which the OS
1136 // will cause an overflow exception, so this is just an optimization
1137 // to avoid unnecessarily touching pages that are below the current
1138 // SP but already committed to the stack by the OS.
1139 BuildMI(BB: &MBB, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64rm), DestReg: LimitReg)
1140 .addReg(RegNo: 0)
1141 .addImm(Val: 1)
1142 .addReg(RegNo: 0)
1143 .addImm(Val: ThreadEnvironmentStackLimit)
1144 .addReg(RegNo: X86::GS);
1145 BuildMI(BB: &MBB, MIMD: DL, MCID: TII.get(Opcode: X86::CMP64rr)).addReg(RegNo: FinalReg).addReg(RegNo: LimitReg);
1146 // Jump if the desired stack pointer is at or above the stack limit.
1147 BuildMI(BB: &MBB, MIMD: DL, MCID: TII.get(Opcode: X86::JCC_1))
1148 .addMBB(MBB: ContinueMBB)
1149 .addImm(Val: X86::COND_AE);
1150
1151 // Add code to roundMBB to round the final stack pointer to a page boundary.
1152 if (InProlog)
1153 RoundMBB->addLiveIn(PhysReg: FinalReg);
1154 BuildMI(BB: RoundMBB, MIMD: DL, MCID: TII.get(Opcode: X86::AND64ri32), DestReg: RoundedReg)
1155 .addReg(RegNo: FinalReg)
1156 .addImm(Val: PageMask);
1157 BuildMI(BB: RoundMBB, MIMD: DL, MCID: TII.get(Opcode: X86::JMP_1)).addMBB(MBB: LoopMBB);
1158
1159 // LimitReg now holds the current stack limit, RoundedReg page-rounded
1160 // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
1161 // and probe until we reach RoundedReg.
1162 if (!InProlog) {
1163 BuildMI(BB: LoopMBB, MIMD: DL, MCID: TII.get(Opcode: X86::PHI), DestReg: JoinReg)
1164 .addReg(RegNo: LimitReg)
1165 .addMBB(MBB: RoundMBB)
1166 .addReg(RegNo: ProbeReg)
1167 .addMBB(MBB: LoopMBB);
1168 }
1169
1170 if (InProlog)
1171 LoopMBB->addLiveIn(PhysReg: JoinReg);
1172 addRegOffset(MIB: BuildMI(BB: LoopMBB, MIMD: DL, MCID: TII.get(Opcode: X86::LEA64r), DestReg: ProbeReg), Reg: JoinReg,
1173 isKill: false, Offset: -PageSize);
1174
1175 // Probe by storing a byte onto the stack.
1176 BuildMI(BB: LoopMBB, MIMD: DL, MCID: TII.get(Opcode: X86::MOV8mi))
1177 .addReg(RegNo: ProbeReg)
1178 .addImm(Val: 1)
1179 .addReg(RegNo: 0)
1180 .addImm(Val: 0)
1181 .addReg(RegNo: 0)
1182 .addImm(Val: 0);
1183
1184 if (InProlog)
1185 LoopMBB->addLiveIn(PhysReg: RoundedReg);
1186 BuildMI(BB: LoopMBB, MIMD: DL, MCID: TII.get(Opcode: X86::CMP64rr))
1187 .addReg(RegNo: RoundedReg)
1188 .addReg(RegNo: ProbeReg);
1189 BuildMI(BB: LoopMBB, MIMD: DL, MCID: TII.get(Opcode: X86::JCC_1))
1190 .addMBB(MBB: LoopMBB)
1191 .addImm(Val: X86::COND_NE);
1192
1193 MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
1194
1195 // If in prolog, restore RDX and RCX.
1196 if (InProlog) {
1197 if (RCXShadowSlot) // It means we spilled RCX in the prologue.
1198 addRegOffset(MIB: BuildMI(BB&: *ContinueMBB, I: ContinueMBBI, MIMD: DL,
1199 MCID: TII.get(Opcode: X86::MOV64rm), DestReg: X86::RCX),
1200 Reg: X86::RSP, isKill: false, Offset: RCXShadowSlot);
1201 if (RDXShadowSlot) // It means we spilled RDX in the prologue.
1202 addRegOffset(MIB: BuildMI(BB&: *ContinueMBB, I: ContinueMBBI, MIMD: DL,
1203 MCID: TII.get(Opcode: X86::MOV64rm), DestReg: X86::RDX),
1204 Reg: X86::RSP, isKill: false, Offset: RDXShadowSlot);
1205 }
1206
1207 // Now that the probing is done, add code to continueMBB to update
1208 // the stack pointer for real.
1209 BuildMI(BB&: *ContinueMBB, I: ContinueMBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SUB64rr), DestReg: X86::RSP)
1210 .addReg(RegNo: X86::RSP)
1211 .addReg(RegNo: SizeReg);
1212
1213 // Add the control flow edges we need.
1214 MBB.addSuccessor(Succ: ContinueMBB);
1215 MBB.addSuccessor(Succ: RoundMBB);
1216 RoundMBB->addSuccessor(Succ: LoopMBB);
1217 LoopMBB->addSuccessor(Succ: ContinueMBB);
1218 LoopMBB->addSuccessor(Succ: LoopMBB);
1219
1220 if (InProlog) {
1221 LivePhysRegs LiveRegs;
1222 computeAndAddLiveIns(LiveRegs, MBB&: *ContinueMBB);
1223 }
1224
1225 // Mark all the instructions added to the prolog as frame setup.
1226 if (InProlog) {
1227 for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
1228 BeforeMBBI->setFlag(MachineInstr::FrameSetup);
1229 }
1230 for (MachineInstr &MI : *RoundMBB) {
1231 MI.setFlag(MachineInstr::FrameSetup);
1232 }
1233 for (MachineInstr &MI : *LoopMBB) {
1234 MI.setFlag(MachineInstr::FrameSetup);
1235 }
1236 for (MachineInstr &MI :
1237 llvm::make_range(x: ContinueMBB->begin(), y: ContinueMBBI)) {
1238 MI.setFlag(MachineInstr::FrameSetup);
1239 }
1240 }
1241}
1242
1243void X86FrameLowering::emitStackProbeCall(
1244 MachineFunction &MF, MachineBasicBlock &MBB,
1245 MachineBasicBlock::iterator MBBI, const DebugLoc &DL, bool InProlog,
1246 std::optional<MachineFunction::DebugInstrOperandPair> InstrNum) const {
1247 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
1248
1249 // FIXME: Add indirect thunk support and remove this.
1250 if (Is64Bit && IsLargeCodeModel && STI.useIndirectThunkCalls())
1251 report_fatal_error(reason: "Emitting stack probe calls on 64-bit with the large "
1252 "code model and indirect thunks not yet implemented.");
1253
1254 assert(MBB.computeRegisterLiveness(TRI, X86::EFLAGS, MBBI) !=
1255 MachineBasicBlock::LQR_Live &&
1256 "Stack probe calls will clobber live EFLAGS.");
1257
1258 unsigned CallOp;
1259 if (Is64Bit)
1260 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
1261 else
1262 CallOp = X86::CALLpcrel32;
1263
1264 StringRef Symbol = STI.getTargetLowering()->getStackProbeSymbolName(MF);
1265
1266 MachineInstrBuilder CI;
1267 MachineBasicBlock::iterator ExpansionMBBI = std::prev(x: MBBI);
1268
1269 // All current stack probes take AX and SP as input, clobber flags, and
1270 // preserve all registers. x86_64 probes leave RSP unmodified.
1271 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1272 // For the large code model, we have to call through a register. Use R11,
1273 // as it is scratch in all supported calling conventions.
1274 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64ri), DestReg: X86::R11)
1275 .addExternalSymbol(FnName: MF.createExternalSymbolName(Name: Symbol));
1276 CI = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: CallOp)).addReg(RegNo: X86::R11);
1277 } else {
1278 CI = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: CallOp))
1279 .addExternalSymbol(FnName: MF.createExternalSymbolName(Name: Symbol));
1280 }
1281
1282 unsigned AX = Uses64BitFramePtr ? X86::RAX : X86::EAX;
1283 unsigned SP = Uses64BitFramePtr ? X86::RSP : X86::ESP;
1284 CI.addReg(RegNo: AX, Flags: RegState::Implicit)
1285 .addReg(RegNo: SP, Flags: RegState::Implicit)
1286 .addReg(RegNo: AX, Flags: RegState::Define | RegState::Implicit)
1287 .addReg(RegNo: SP, Flags: RegState::Define | RegState::Implicit)
1288 .addReg(RegNo: X86::EFLAGS, Flags: RegState::Define | RegState::Implicit);
1289
1290 MachineInstr *ModInst = CI;
1291 if (STI.isTargetWin64() || !STI.isOSWindows()) {
1292 // MSVC x32's _chkstk and cygwin/mingw's _alloca adjust %esp themselves.
1293 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
1294 // themselves. They also does not clobber %rax so we can reuse it when
1295 // adjusting %rsp.
1296 // All other platforms do not specify a particular ABI for the stack probe
1297 // function, so we arbitrarily define it to not adjust %esp/%rsp itself.
1298 ModInst =
1299 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: getSUBrrOpcode(IsLP64: Uses64BitFramePtr)), DestReg: SP)
1300 .addReg(RegNo: SP)
1301 .addReg(RegNo: AX);
1302 }
1303
1304 // DebugInfo variable locations -- if there's an instruction number for the
1305 // allocation (i.e., DYN_ALLOC_*), substitute it for the instruction that
1306 // modifies SP.
1307 if (InstrNum) {
1308 if (STI.isTargetWin64() || !STI.isOSWindows()) {
1309 // Label destination operand of the subtract.
1310 MF.makeDebugValueSubstitution(*InstrNum,
1311 {ModInst->getDebugInstrNum(), 0});
1312 } else {
1313 // Label the call. The operand number is the penultimate operand, zero
1314 // based.
1315 unsigned SPDefOperand = ModInst->getNumOperands() - 2;
1316 MF.makeDebugValueSubstitution(
1317 *InstrNum, {ModInst->getDebugInstrNum(), SPDefOperand});
1318 }
1319 }
1320
1321 if (InProlog) {
1322 // Apply the frame setup flag to all inserted instrs.
1323 for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
1324 ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
1325 }
1326}
1327
1328static unsigned calculateSetFPREG(uint64_t SPAdjust) {
1329 // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
1330 // and might require smaller successive adjustments.
1331 const uint64_t Win64MaxSEHOffset = 128;
1332 uint64_t SEHFrameOffset = std::min(a: SPAdjust, b: Win64MaxSEHOffset);
1333 // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
1334 return SEHFrameOffset & -16;
1335}
1336
1337// If we're forcing a stack realignment we can't rely on just the frame
1338// info, we need to know the ABI stack alignment as well in case we
1339// have a call out. Otherwise just make sure we have some alignment - we'll
1340// go with the minimum SlotSize.
1341uint64_t
1342X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
1343 const MachineFrameInfo &MFI = MF.getFrameInfo();
1344 Align MaxAlign = MFI.getMaxAlign(); // Desired stack alignment.
1345 Align StackAlign = getStackAlign();
1346 bool HasRealign = MF.getFunction().hasFnAttribute(Kind: "stackrealign");
1347 if (HasRealign) {
1348 if (MFI.hasCalls())
1349 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
1350 else if (MaxAlign < SlotSize)
1351 MaxAlign = Align(SlotSize);
1352 }
1353
1354 if (!Is64Bit && MF.getFunction().getCallingConv() == CallingConv::X86_INTR) {
1355 if (HasRealign)
1356 MaxAlign = (MaxAlign > 16) ? MaxAlign : Align(16);
1357 else
1358 MaxAlign = Align(16);
1359 }
1360 return MaxAlign.value();
1361}
1362
1363void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
1364 MachineBasicBlock::iterator MBBI,
1365 const DebugLoc &DL, Register Reg,
1366 uint64_t MaxAlign) const {
1367 uint64_t Val = -MaxAlign;
1368 unsigned AndOp = getANDriOpcode(IsLP64: Uses64BitFramePtr, Imm: Val);
1369
1370 MachineFunction &MF = *MBB.getParent();
1371 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1372 const X86TargetLowering &TLI = *STI.getTargetLowering();
1373 const uint64_t StackProbeSize = TLI.getStackProbeSize(MF);
1374 const bool EmitInlineStackProbe = TLI.hasInlineStackProbe(MF);
1375
1376 // We want to make sure that (in worst case) less than StackProbeSize bytes
1377 // are not probed after the AND. This assumption is used in
1378 // emitStackProbeInlineGeneric.
1379 if (Reg == StackPtr && EmitInlineStackProbe && MaxAlign >= StackProbeSize) {
1380 {
1381 NumFrameLoopProbe++;
1382 MachineBasicBlock *entryMBB =
1383 MF.CreateMachineBasicBlock(BB: MBB.getBasicBlock());
1384 MachineBasicBlock *headMBB =
1385 MF.CreateMachineBasicBlock(BB: MBB.getBasicBlock());
1386 MachineBasicBlock *bodyMBB =
1387 MF.CreateMachineBasicBlock(BB: MBB.getBasicBlock());
1388 MachineBasicBlock *footMBB =
1389 MF.CreateMachineBasicBlock(BB: MBB.getBasicBlock());
1390
1391 MachineFunction::iterator MBBIter = MBB.getIterator();
1392 MF.insert(MBBI: MBBIter, MBB: entryMBB);
1393 MF.insert(MBBI: MBBIter, MBB: headMBB);
1394 MF.insert(MBBI: MBBIter, MBB: bodyMBB);
1395 MF.insert(MBBI: MBBIter, MBB: footMBB);
1396 const unsigned MovMIOpc = Is64Bit ? X86::MOV64mi32 : X86::MOV32mi;
1397 Register FinalStackProbed = Uses64BitFramePtr ? X86::R11
1398 : Is64Bit ? X86::R11D
1399 : X86::EAX;
1400
1401 // Setup entry block
1402 {
1403
1404 entryMBB->splice(Where: entryMBB->end(), Other: &MBB, From: MBB.begin(), To: MBBI);
1405 BuildMI(BB: entryMBB, MIMD: DL, MCID: TII.get(Opcode: TargetOpcode::COPY), DestReg: FinalStackProbed)
1406 .addReg(RegNo: StackPtr)
1407 .setMIFlag(MachineInstr::FrameSetup);
1408 MachineInstr *MI =
1409 BuildMI(BB: entryMBB, MIMD: DL, MCID: TII.get(Opcode: AndOp), DestReg: FinalStackProbed)
1410 .addReg(RegNo: FinalStackProbed)
1411 .addImm(Val)
1412 .setMIFlag(MachineInstr::FrameSetup);
1413
1414 // The EFLAGS implicit def is dead.
1415 MI->getOperand(i: 3).setIsDead();
1416
1417 BuildMI(BB: entryMBB, MIMD: DL,
1418 MCID: TII.get(Opcode: Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1419 .addReg(RegNo: FinalStackProbed)
1420 .addReg(RegNo: StackPtr)
1421 .setMIFlag(MachineInstr::FrameSetup);
1422 BuildMI(BB: entryMBB, MIMD: DL, MCID: TII.get(Opcode: X86::JCC_1))
1423 .addMBB(MBB: &MBB)
1424 .addImm(Val: X86::COND_E)
1425 .setMIFlag(MachineInstr::FrameSetup);
1426 entryMBB->addSuccessor(Succ: headMBB);
1427 entryMBB->addSuccessor(Succ: &MBB);
1428 }
1429
1430 // Loop entry block
1431
1432 {
1433 const unsigned SUBOpc = getSUBriOpcode(IsLP64: Uses64BitFramePtr);
1434 BuildMI(BB: headMBB, MIMD: DL, MCID: TII.get(Opcode: SUBOpc), DestReg: StackPtr)
1435 .addReg(RegNo: StackPtr)
1436 .addImm(Val: StackProbeSize)
1437 .setMIFlag(MachineInstr::FrameSetup);
1438
1439 BuildMI(BB: headMBB, MIMD: DL,
1440 MCID: TII.get(Opcode: Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1441 .addReg(RegNo: StackPtr)
1442 .addReg(RegNo: FinalStackProbed)
1443 .setMIFlag(MachineInstr::FrameSetup);
1444
1445 // jump to the footer if StackPtr < FinalStackProbed
1446 BuildMI(BB: headMBB, MIMD: DL, MCID: TII.get(Opcode: X86::JCC_1))
1447 .addMBB(MBB: footMBB)
1448 .addImm(Val: X86::COND_B)
1449 .setMIFlag(MachineInstr::FrameSetup);
1450
1451 headMBB->addSuccessor(Succ: bodyMBB);
1452 headMBB->addSuccessor(Succ: footMBB);
1453 }
1454
1455 // setup loop body
1456 {
1457 addRegOffset(MIB: BuildMI(BB: bodyMBB, MIMD: DL, MCID: TII.get(Opcode: MovMIOpc))
1458 .setMIFlag(MachineInstr::FrameSetup),
1459 Reg: StackPtr, isKill: false, Offset: 0)
1460 .addImm(Val: 0)
1461 .setMIFlag(MachineInstr::FrameSetup);
1462
1463 const unsigned SUBOpc = getSUBriOpcode(IsLP64: Uses64BitFramePtr);
1464 BuildMI(BB: bodyMBB, MIMD: DL, MCID: TII.get(Opcode: SUBOpc), DestReg: StackPtr)
1465 .addReg(RegNo: StackPtr)
1466 .addImm(Val: StackProbeSize)
1467 .setMIFlag(MachineInstr::FrameSetup);
1468
1469 // cmp with stack pointer bound
1470 BuildMI(BB: bodyMBB, MIMD: DL,
1471 MCID: TII.get(Opcode: Uses64BitFramePtr ? X86::CMP64rr : X86::CMP32rr))
1472 .addReg(RegNo: FinalStackProbed)
1473 .addReg(RegNo: StackPtr)
1474 .setMIFlag(MachineInstr::FrameSetup);
1475
1476 // jump back while FinalStackProbed < StackPtr
1477 BuildMI(BB: bodyMBB, MIMD: DL, MCID: TII.get(Opcode: X86::JCC_1))
1478 .addMBB(MBB: bodyMBB)
1479 .addImm(Val: X86::COND_B)
1480 .setMIFlag(MachineInstr::FrameSetup);
1481 bodyMBB->addSuccessor(Succ: bodyMBB);
1482 bodyMBB->addSuccessor(Succ: footMBB);
1483 }
1484
1485 // setup loop footer
1486 {
1487 BuildMI(BB: footMBB, MIMD: DL, MCID: TII.get(Opcode: TargetOpcode::COPY), DestReg: StackPtr)
1488 .addReg(RegNo: FinalStackProbed)
1489 .setMIFlag(MachineInstr::FrameSetup);
1490 addRegOffset(MIB: BuildMI(BB: footMBB, MIMD: DL, MCID: TII.get(Opcode: MovMIOpc))
1491 .setMIFlag(MachineInstr::FrameSetup),
1492 Reg: StackPtr, isKill: false, Offset: 0)
1493 .addImm(Val: 0)
1494 .setMIFlag(MachineInstr::FrameSetup);
1495 footMBB->addSuccessor(Succ: &MBB);
1496 }
1497
1498 fullyRecomputeLiveIns(MBBs: {footMBB, bodyMBB, headMBB, &MBB});
1499 }
1500 } else {
1501 MachineInstr *MI = BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: AndOp), DestReg: Reg)
1502 .addReg(RegNo: Reg)
1503 .addImm(Val)
1504 .setMIFlag(MachineInstr::FrameSetup);
1505
1506 // The EFLAGS implicit def is dead.
1507 MI->getOperand(i: 3).setIsDead();
1508 }
1509}
1510
1511bool X86FrameLowering::has128ByteRedZone(const MachineFunction &MF) const {
1512 // x86-64 (non Win64) has a 128 byte red zone which is guaranteed not to be
1513 // clobbered by any interrupt handler.
1514 assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
1515 "MF used frame lowering for wrong subtarget");
1516 const Function &Fn = MF.getFunction();
1517 const bool IsWin64CC = STI.isCallingConvWin64(CC: Fn.getCallingConv());
1518 return Is64Bit && !IsWin64CC && !Fn.hasFnAttribute(Kind: Attribute::NoRedZone);
1519}
1520
1521/// Return true if we need to use the restricted Windows x64 prologue and
1522/// epilogue code patterns that can be described with WinCFI (.seh_*
1523/// directives).
1524bool X86FrameLowering::isWin64Prologue(const MachineFunction &MF) const {
1525 return MF.getTarget().getMCAsmInfo().usesWindowsCFI();
1526}
1527
1528bool X86FrameLowering::needsDwarfCFI(const MachineFunction &MF) const {
1529 return !isWin64Prologue(MF) && MF.needsFrameMoves();
1530}
1531
1532/// Return true if an opcode is part of the REP group of instructions
1533static bool isOpcodeRep(unsigned Opcode) {
1534 switch (Opcode) {
1535 case X86::REPNE_PREFIX:
1536 case X86::REP_MOVSB_32:
1537 case X86::REP_MOVSB_64:
1538 case X86::REP_MOVSD_32:
1539 case X86::REP_MOVSD_64:
1540 case X86::REP_MOVSQ_32:
1541 case X86::REP_MOVSQ_64:
1542 case X86::REP_MOVSW_32:
1543 case X86::REP_MOVSW_64:
1544 case X86::REP_PREFIX:
1545 case X86::REP_STOSB_32:
1546 case X86::REP_STOSB_64:
1547 case X86::REP_STOSD_32:
1548 case X86::REP_STOSD_64:
1549 case X86::REP_STOSQ_32:
1550 case X86::REP_STOSQ_64:
1551 case X86::REP_STOSW_32:
1552 case X86::REP_STOSW_64:
1553 return true;
1554 default:
1555 break;
1556 }
1557 return false;
1558}
1559
1560/// emitPrologue - Push callee-saved registers onto the stack, which
1561/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
1562/// space for local variables. Also emit labels used by the exception handler to
1563/// generate the exception handling frames.
1564
1565/*
1566 Here's a gist of what gets emitted:
1567
1568 ; Establish frame pointer, if needed
1569 [if needs FP]
1570 push %rbp
1571 .cfi_def_cfa_offset 16
1572 .cfi_offset %rbp, -16
1573 .seh_pushreg %rpb
1574 mov %rsp, %rbp
1575 .cfi_def_cfa_register %rbp
1576
1577 ; Spill general-purpose registers
1578 [for all callee-saved GPRs]
1579 pushq %<reg>
1580 [if not needs FP]
1581 .cfi_def_cfa_offset (offset from RETADDR)
1582 .seh_pushreg %<reg>
1583
1584 ; If the required stack alignment > default stack alignment
1585 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
1586 ; of unknown size in the stack frame.
1587 [if stack needs re-alignment]
1588 and $MASK, %rsp
1589
1590 ; Allocate space for locals
1591 [if target is Windows and allocated space > 4096 bytes]
1592 ; Windows needs special care for allocations larger
1593 ; than one page.
1594 mov $NNN, %rax
1595 call ___chkstk_ms/___chkstk
1596 sub %rax, %rsp
1597 [else]
1598 sub $NNN, %rsp
1599
1600 [if needs FP]
1601 .seh_stackalloc (size of XMM spill slots)
1602 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
1603 [else]
1604 .seh_stackalloc NNN
1605
1606 ; Spill XMMs
1607 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
1608 ; they may get spilled on any platform, if the current function
1609 ; calls @llvm.eh.unwind.init
1610 [if needs FP]
1611 [for all callee-saved XMM registers]
1612 movaps %<xmm reg>, -MMM(%rbp)
1613 [for all callee-saved XMM registers]
1614 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
1615 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
1616 [else]
1617 [for all callee-saved XMM registers]
1618 movaps %<xmm reg>, KKK(%rsp)
1619 [for all callee-saved XMM registers]
1620 .seh_savexmm %<xmm reg>, KKK
1621
1622 .seh_endprologue
1623
1624 [if needs base pointer]
1625 mov %rsp, %rbx
1626 [if needs to restore base pointer]
1627 mov %rsp, -MMM(%rbp)
1628
1629 ; Emit CFI info
1630 [if needs FP]
1631 [for all callee-saved registers]
1632 .cfi_offset %<reg>, (offset from %rbp)
1633 [else]
1634 .cfi_def_cfa_offset (offset from RETADDR)
1635 [for all callee-saved registers]
1636 .cfi_offset %<reg>, (offset from %rsp)
1637
1638 Notes:
1639 - .seh directives are emitted only for Windows 64 ABI
1640 - .cv_fpo directives are emitted on win32 when emitting CodeView
1641 - .cfi directives are emitted for all other ABIs
1642 - for 32-bit code, substitute %e?? registers for %r??
1643*/
1644
1645void X86FrameLowering::emitPrologue(MachineFunction &MF,
1646 MachineBasicBlock &MBB) const {
1647 assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
1648 "MF used frame lowering for wrong subtarget");
1649 MachineBasicBlock::iterator MBBI = MBB.begin();
1650 MachineFrameInfo &MFI = MF.getFrameInfo();
1651 const Function &Fn = MF.getFunction();
1652 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1653 uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
1654 uint64_t StackSize = MFI.getStackSize(); // Number of bytes to allocate.
1655 bool IsFunclet = MBB.isEHFuncletEntry();
1656 EHPersonality Personality = EHPersonality::Unknown;
1657 if (Fn.hasPersonalityFn())
1658 Personality = classifyEHPersonality(Pers: Fn.getPersonalityFn());
1659 bool FnHasClrFunclet =
1660 MF.hasEHFunclets() && Personality == EHPersonality::CoreCLR;
1661 bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
1662 bool HasFP = hasFP(MF);
1663 bool IsWin64Prologue = isWin64Prologue(MF);
1664 bool NeedsWin64CFI = IsWin64Prologue && Fn.needsUnwindTableEntry();
1665 // FIXME: Emit FPO data for EH funclets.
1666 bool NeedsWinFPO = !IsFunclet && STI.isTargetWin32() &&
1667 MF.getFunction().getParent()->getCodeViewFlag();
1668 bool NeedsWinCFI = NeedsWin64CFI || NeedsWinFPO;
1669 bool NeedsDwarfCFI = needsDwarfCFI(MF);
1670 bool IsWin64UnwindV3 = NeedsWin64CFI && requireWinX64UnwindV3(MF);
1671 Register FramePtr = TRI->getFrameRegister(MF);
1672 const Register MachineFramePtr =
1673 STI.isTarget64BitILP32() ? Register(getX86SubSuperRegister(Reg: FramePtr, Size: 64))
1674 : FramePtr;
1675 Register BasePtr = TRI->getBaseRegister();
1676 bool HasWinCFI = false;
1677
1678 // Helpers to emit Windows x64 unwind SEH pseudos with the correct placement.
1679 // V1/V2: pseudo goes after the real instruction.
1680 // V3: pseudo goes before the real instruction.
1681 // Usage:
1682 // EmitSEHBefore([&]{ BuildMI(...SEH_PushReg...); });
1683 // BuildMI(... real instruction ...);
1684 // EmitSEHAfter([&]{ BuildMI(...SEH_PushReg...); });
1685 auto EmitSEHBefore = [&](auto EmitFn) {
1686 if (NeedsWinCFI && IsWin64UnwindV3) {
1687 HasWinCFI = true;
1688 EmitFn();
1689 }
1690 };
1691 auto EmitSEHAfter = [&](auto EmitFn) {
1692 if (NeedsWinCFI && !IsWin64UnwindV3) {
1693 HasWinCFI = true;
1694 EmitFn();
1695 }
1696 };
1697
1698 // Debug location must be unknown since the first debug location is used
1699 // to determine the end of the prologue.
1700 DebugLoc DL;
1701 Register ArgBaseReg;
1702
1703 // Emit extra prolog for argument stack slot reference.
1704 if (auto *MI = X86FI->getStackPtrSaveMI()) {
1705 // MI is lea instruction that created in X86ArgumentStackSlotPass.
1706 // Creat extra prolog for stack realignment.
1707 ArgBaseReg = MI->getOperand(i: 0).getReg();
1708 // leal 4(%esp), %basereg
1709 // .cfi_def_cfa %basereg, 0
1710 // andl $-128, %esp
1711 // pushl -4(%basereg)
1712 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: Is64Bit ? X86::LEA64r : X86::LEA32r),
1713 DestReg: ArgBaseReg)
1714 .addUse(RegNo: StackPtr)
1715 .addImm(Val: 1)
1716 .addUse(RegNo: X86::NoRegister)
1717 .addImm(Val: SlotSize)
1718 .addUse(RegNo: X86::NoRegister)
1719 .setMIFlag(MachineInstr::FrameSetup);
1720 if (NeedsDwarfCFI) {
1721 // .cfi_def_cfa %basereg, 0
1722 unsigned DwarfStackPtr = TRI->getDwarfRegNum(Reg: ArgBaseReg, isEH: true);
1723 BuildCFI(MBB, MBBI, DL,
1724 CFIInst: MCCFIInstruction::cfiDefCfa(L: nullptr, Register: DwarfStackPtr, Offset: 0),
1725 Flag: MachineInstr::FrameSetup);
1726 }
1727 BuildStackAlignAND(MBB, MBBI, DL, Reg: StackPtr, MaxAlign);
1728 int64_t Offset = -(int64_t)SlotSize;
1729 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: Is64Bit ? X86::PUSH64rmm : X86::PUSH32rmm))
1730 .addReg(RegNo: ArgBaseReg)
1731 .addImm(Val: 1)
1732 .addReg(RegNo: X86::NoRegister)
1733 .addImm(Val: Offset)
1734 .addReg(RegNo: X86::NoRegister)
1735 .setMIFlag(MachineInstr::FrameSetup);
1736 }
1737
1738 // Space reserved for stack-based arguments when making a (ABI-guaranteed)
1739 // tail call.
1740 unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
1741 if (TailCallArgReserveSize && IsWin64Prologue)
1742 report_fatal_error(reason: "Can't handle guaranteed tail call under win64 yet");
1743
1744 const bool EmitStackProbeCall =
1745 STI.getTargetLowering()->hasStackProbeSymbol(MF);
1746 unsigned StackProbeSize = STI.getTargetLowering()->getStackProbeSize(MF);
1747
1748 if (HasFP && X86FI->hasSwiftAsyncContext()) {
1749 switch (MF.getTarget().Options.SwiftAsyncFramePointer) {
1750 case SwiftAsyncFramePointerMode::DeploymentBased:
1751 if (STI.swiftAsyncContextIsDynamicallySet()) {
1752 // The special symbol below is absolute and has a *value* suitable to be
1753 // combined with the frame pointer directly.
1754 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::OR64rm), DestReg: MachineFramePtr)
1755 .addUse(RegNo: MachineFramePtr)
1756 .addUse(RegNo: X86::RIP)
1757 .addImm(Val: 1)
1758 .addUse(RegNo: X86::NoRegister)
1759 .addExternalSymbol(FnName: "swift_async_extendedFramePointerFlags",
1760 TargetFlags: X86II::MO_GOTPCREL)
1761 .addUse(RegNo: X86::NoRegister);
1762 break;
1763 }
1764 [[fallthrough]];
1765
1766 case SwiftAsyncFramePointerMode::Always:
1767 assert(
1768 !IsWin64Prologue &&
1769 "win64 prologue does not set the bit 60 in the saved frame pointer");
1770 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::BTS64ri8), DestReg: MachineFramePtr)
1771 .addUse(RegNo: MachineFramePtr)
1772 .addImm(Val: 60)
1773 .setMIFlag(MachineInstr::FrameSetup);
1774 break;
1775
1776 case SwiftAsyncFramePointerMode::Never:
1777 break;
1778 }
1779 }
1780
1781 // Re-align the stack on 64-bit if the x86-interrupt calling convention is
1782 // used and an error code was pushed, since the x86-64 ABI requires a 16-byte
1783 // stack alignment.
1784 if (Fn.getCallingConv() == CallingConv::X86_INTR && Is64Bit &&
1785 Fn.arg_size() == 2) {
1786 StackSize += 8;
1787 MFI.setStackSize(StackSize);
1788
1789 // Update the stack pointer by pushing a register. This is the instruction
1790 // emitted that would be end up being emitted by a call to `emitSPUpdate`.
1791 // Hard-coding the update to a push avoids emitting a second
1792 // `STACKALLOC_W_PROBING` instruction in the save block: We know that stack
1793 // probing isn't needed anyways for an 8-byte update.
1794 // Pushing a register leaves us in a similar situation to a regular
1795 // function call where we know that the address at (rsp-8) is writeable.
1796 // That way we avoid any off-by-ones with stack probing for additional
1797 // stack pointer updates later on.
1798 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::PUSH64r))
1799 .addReg(RegNo: X86::RAX, Flags: RegState::Undef)
1800 .setMIFlag(MachineInstr::FrameSetup);
1801 }
1802
1803 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
1804 // function, and use up to 128 bytes of stack space, don't have a frame
1805 // pointer, calls, or dynamic alloca then we do not need to adjust the
1806 // stack pointer (we fit in the Red Zone). We also check that we don't
1807 // push and pop from the stack.
1808 if (has128ByteRedZone(MF) && !TRI->hasStackRealignment(MF) &&
1809 !MFI.hasVarSizedObjects() && // No dynamic alloca.
1810 !MFI.adjustsStack() && // No calls.
1811 !EmitStackProbeCall && // No stack probes.
1812 !MFI.hasCopyImplyingStackAdjustment() && // Don't push and pop.
1813 !MF.shouldSplitStack()) { // Regular stack
1814 uint64_t MinSize =
1815 X86FI->getCalleeSavedFrameSize() - X86FI->getTCReturnAddrDelta();
1816 if (HasFP)
1817 MinSize += SlotSize;
1818 X86FI->setUsesRedZone(MinSize > 0 || StackSize > 0);
1819 StackSize = std::max(a: MinSize, b: StackSize > 128 ? StackSize - 128 : 0);
1820 MFI.setStackSize(StackSize);
1821 }
1822
1823 // Insert stack pointer adjustment for later moving of return addr. Only
1824 // applies to tail call optimized functions where the callee argument stack
1825 // size is bigger than the callers.
1826 if (TailCallArgReserveSize != 0) {
1827 BuildStackAdjustment(MBB, MBBI, DL, Offset: -(int)TailCallArgReserveSize,
1828 /*InEpilogue=*/false)
1829 .setMIFlag(MachineInstr::FrameSetup);
1830 }
1831
1832 // Mapping for machine moves:
1833 //
1834 // DST: VirtualFP AND
1835 // SRC: VirtualFP => DW_CFA_def_cfa_offset
1836 // ELSE => DW_CFA_def_cfa
1837 //
1838 // SRC: VirtualFP AND
1839 // DST: Register => DW_CFA_def_cfa_register
1840 //
1841 // ELSE
1842 // OFFSET < 0 => DW_CFA_offset_extended_sf
1843 // REG < 64 => DW_CFA_offset + Reg
1844 // ELSE => DW_CFA_offset_extended
1845
1846 uint64_t NumBytes = 0;
1847 int stackGrowth = -SlotSize;
1848
1849 // Find the funclet establisher parameter
1850 MCRegister Establisher;
1851 if (IsClrFunclet)
1852 Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
1853 else if (IsFunclet)
1854 Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
1855
1856 if (IsWin64Prologue && IsFunclet && !IsClrFunclet) {
1857 // Immediately spill establisher into the home slot.
1858 // The runtime cares about this.
1859 // MOV64mr %rdx, 16(%rsp)
1860 unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1861 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: MOVmr)), Reg: StackPtr, isKill: true, Offset: 16)
1862 .addReg(RegNo: Establisher)
1863 .setMIFlag(MachineInstr::FrameSetup);
1864 MBB.addLiveIn(PhysReg: Establisher);
1865 }
1866
1867 if (HasFP) {
1868 assert(MF.getRegInfo().isReserved(MachineFramePtr) && "FP reserved");
1869
1870 // Calculate required stack adjustment.
1871 uint64_t FrameSize = StackSize - SlotSize;
1872 NumBytes =
1873 FrameSize - (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
1874
1875 // Callee-saved registers are pushed on stack before the stack is realigned.
1876 if (TRI->hasStackRealignment(MF) && !IsWin64Prologue)
1877 NumBytes = alignTo(Value: NumBytes, Align: MaxAlign);
1878
1879 // Save EBP/RBP into the appropriate stack slot.
1880 auto EmitSEHPushFramePtr = [&]() {
1881 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_PushReg))
1882 .addImm(Val: FramePtr)
1883 .setMIFlag(MachineInstr::FrameSetup);
1884 };
1885 EmitSEHBefore(EmitSEHPushFramePtr);
1886 BuildMI(BB&: MBB, I: MBBI, MIMD: DL,
1887 MCID: TII.get(Opcode: getPUSHOpcode(ST: MF.getSubtarget<X86Subtarget>())))
1888 .addReg(RegNo: MachineFramePtr, Flags: RegState::Kill)
1889 .setMIFlag(MachineInstr::FrameSetup);
1890 EmitSEHAfter(EmitSEHPushFramePtr);
1891
1892 if (NeedsDwarfCFI && !ArgBaseReg.isValid()) {
1893 // Mark the place where EBP/RBP was saved.
1894 // Define the current CFA rule to use the provided offset.
1895 assert(StackSize);
1896 BuildCFI(MBB, MBBI, DL,
1897 CFIInst: MCCFIInstruction::cfiDefCfaOffset(
1898 L: nullptr, Offset: -2 * stackGrowth + (int)TailCallArgReserveSize),
1899 Flag: MachineInstr::FrameSetup);
1900
1901 // Change the rule for the FramePtr to be an "offset" rule.
1902 unsigned DwarfFramePtr = TRI->getDwarfRegNum(Reg: MachineFramePtr, isEH: true);
1903 BuildCFI(MBB, MBBI, DL,
1904 CFIInst: MCCFIInstruction::createOffset(L: nullptr, Register: DwarfFramePtr,
1905 Offset: 2 * stackGrowth -
1906 (int)TailCallArgReserveSize),
1907 Flag: MachineInstr::FrameSetup);
1908 }
1909
1910 if (!IsFunclet) {
1911 if (X86FI->hasSwiftAsyncContext()) {
1912 assert(!IsWin64Prologue &&
1913 "win64 prologue does not store async context right below rbp");
1914 const auto &Attrs = MF.getFunction().getAttributes();
1915
1916 // Before we update the live frame pointer we have to ensure there's a
1917 // valid (or null) asynchronous context in its slot just before FP in
1918 // the frame record, so store it now.
1919 auto EmitSEHPushR14 = [&]() {
1920 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_PushReg))
1921 .addImm(Val: X86::R14)
1922 .setMIFlag(MachineInstr::FrameSetup);
1923 };
1924 EmitSEHBefore(EmitSEHPushR14);
1925 if (Attrs.hasAttrSomewhere(Kind: Attribute::SwiftAsync)) {
1926 // We have an initial context in r14, store it just before the frame
1927 // pointer.
1928 MBB.addLiveIn(PhysReg: X86::R14);
1929 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::PUSH64r))
1930 .addReg(RegNo: X86::R14)
1931 .setMIFlag(MachineInstr::FrameSetup);
1932 } else {
1933 // No initial context, store null so that there's no pointer that
1934 // could be misused.
1935 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::PUSH64i32))
1936 .addImm(Val: 0)
1937 .setMIFlag(MachineInstr::FrameSetup);
1938 }
1939
1940 // Update CFA offset for the async-context push.
1941 if (NeedsDwarfCFI && !ArgBaseReg.isValid()) {
1942 BuildCFI(
1943 MBB, MBBI, DL,
1944 CFIInst: MCCFIInstruction::createAdjustCfaOffset(L: nullptr, Adjustment: -stackGrowth),
1945 Flag: MachineInstr::FrameSetup);
1946 }
1947
1948 EmitSEHAfter(EmitSEHPushR14);
1949
1950 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::LEA64r), DestReg: FramePtr)
1951 .addUse(RegNo: X86::RSP)
1952 .addImm(Val: 1)
1953 .addUse(RegNo: X86::NoRegister)
1954 .addImm(Val: 8)
1955 .addUse(RegNo: X86::NoRegister)
1956 .setMIFlag(MachineInstr::FrameSetup);
1957
1958 // Switch to an FP-relative CFA before adjusting RSP below.
1959 if (NeedsDwarfCFI && !ArgBaseReg.isValid()) {
1960 unsigned DwarfFramePtr = TRI->getDwarfRegNum(Reg: MachineFramePtr, isEH: true);
1961 BuildCFI(MBB, MBBI, DL,
1962 CFIInst: MCCFIInstruction::cfiDefCfa(L: nullptr, Register: DwarfFramePtr,
1963 Offset: -2 * stackGrowth +
1964 (int)TailCallArgReserveSize),
1965 Flag: MachineInstr::FrameSetup);
1966 }
1967
1968 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SUB64ri32), DestReg: X86::RSP)
1969 .addUse(RegNo: X86::RSP)
1970 .addImm(Val: 8)
1971 .setMIFlag(MachineInstr::FrameSetup);
1972 }
1973
1974 if (!IsWin64Prologue && !IsFunclet) {
1975 // Update EBP with the new base value.
1976 if (!X86FI->hasSwiftAsyncContext())
1977 BuildMI(BB&: MBB, I: MBBI, MIMD: DL,
1978 MCID: TII.get(Opcode: Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
1979 DestReg: FramePtr)
1980 .addReg(RegNo: StackPtr)
1981 .setMIFlag(MachineInstr::FrameSetup);
1982
1983 if (NeedsDwarfCFI) {
1984 if (ArgBaseReg.isValid()) {
1985 SmallString<64> CfaExpr;
1986 CfaExpr.push_back(Elt: dwarf::DW_CFA_expression);
1987 uint8_t buffer[16];
1988 unsigned DwarfReg = TRI->getDwarfRegNum(Reg: MachineFramePtr, isEH: true);
1989 CfaExpr.append(in_start: buffer, in_end: buffer + encodeULEB128(Value: DwarfReg, p: buffer));
1990 CfaExpr.push_back(Elt: 2);
1991 CfaExpr.push_back(Elt: (uint8_t)(dwarf::DW_OP_breg0 + DwarfReg));
1992 CfaExpr.push_back(Elt: 0);
1993 // DW_CFA_expression: reg5 DW_OP_breg5 +0
1994 BuildCFI(MBB, MBBI, DL,
1995 CFIInst: MCCFIInstruction::createEscape(L: nullptr, Vals: CfaExpr.str()),
1996 Flag: MachineInstr::FrameSetup);
1997 } else if (!X86FI->hasSwiftAsyncContext()) {
1998 // Mark effective beginning of when frame pointer becomes valid.
1999 // Define the current CFA to use the EBP/RBP register.
2000 unsigned DwarfFramePtr = TRI->getDwarfRegNum(Reg: MachineFramePtr, isEH: true);
2001 BuildCFI(
2002 MBB, MBBI, DL,
2003 CFIInst: MCCFIInstruction::createDefCfaRegister(L: nullptr, Register: DwarfFramePtr),
2004 Flag: MachineInstr::FrameSetup);
2005 }
2006 }
2007
2008 if (NeedsWinFPO) {
2009 // .cv_fpo_setframe $FramePtr
2010 // NeedsWinFPO is Win32 only, so we're never using Unwind v3, hence it
2011 // is always inserted afterwards.
2012 assert(!IsWin64UnwindV3);
2013 HasWinCFI = true;
2014 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_SetFrame))
2015 .addImm(Val: FramePtr)
2016 .addImm(Val: 0)
2017 .setMIFlag(MachineInstr::FrameSetup);
2018 }
2019 }
2020 }
2021 } else {
2022 assert(!IsFunclet && "funclets without FPs not yet implemented");
2023 NumBytes =
2024 StackSize - (X86FI->getCalleeSavedFrameSize() + TailCallArgReserveSize);
2025 }
2026
2027 // Update the offset adjustment, which is mainly used by codeview to translate
2028 // from ESP to VFRAME relative local variable offsets.
2029 if (!IsFunclet) {
2030 if (HasFP && TRI->hasStackRealignment(MF))
2031 MFI.setOffsetAdjustment(-NumBytes);
2032 else
2033 MFI.setOffsetAdjustment(-StackSize);
2034 }
2035
2036 // For EH funclets, only allocate enough space for outgoing calls. Save the
2037 // NumBytes value that we would've used for the parent frame.
2038 unsigned ParentFrameNumBytes = NumBytes;
2039 if (IsFunclet)
2040 NumBytes = getWinEHFuncletFrameSize(MF);
2041
2042 // Skip the callee-saved push instructions.
2043 bool PushedRegs = false;
2044 int StackOffset = 2 * stackGrowth;
2045 MachineBasicBlock::const_iterator LastCSPush = MBBI;
2046 auto IsCSPush = [&](const MachineBasicBlock::iterator &MBBI) {
2047 if (MBBI == MBB.end() || !MBBI->getFlag(Flag: MachineInstr::FrameSetup))
2048 return false;
2049 unsigned Opc = MBBI->getOpcode();
2050 return Opc == X86::PUSH32r || Opc == X86::PUSH64r || Opc == X86::PUSHP64r ||
2051 Opc == X86::PUSH2 || Opc == X86::PUSH2P;
2052 };
2053
2054 while (IsCSPush(MBBI)) {
2055 PushedRegs = true;
2056 Register Reg = MBBI->getOperand(i: 0).getReg();
2057 LastCSPush = MBBI;
2058 unsigned Opc = LastCSPush->getOpcode();
2059 bool IsPush2 = Opc == X86::PUSH2 || Opc == X86::PUSH2P;
2060
2061 // V3: emit SEH pseudo before the real instruction.
2062 EmitSEHBefore([&]() {
2063 if (IsPush2) {
2064 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_Push2Regs))
2065 .addImm(Val: Reg)
2066 .addImm(Val: LastCSPush->getOperand(i: 1).getReg())
2067 .setMIFlag(MachineInstr::FrameSetup);
2068 } else {
2069 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_PushReg))
2070 .addImm(Val: Reg)
2071 .setMIFlag(MachineInstr::FrameSetup);
2072 }
2073 });
2074 ++MBBI;
2075
2076 if (!HasFP && NeedsDwarfCFI) {
2077 // Mark callee-saved push instruction.
2078 // Define the current CFA rule to use the provided offset.
2079 assert(StackSize);
2080 // Compared to push, push2 introduces more stack offset (one more
2081 // register).
2082 if (IsPush2)
2083 StackOffset += stackGrowth;
2084 BuildCFI(MBB, MBBI, DL,
2085 CFIInst: MCCFIInstruction::cfiDefCfaOffset(L: nullptr, Offset: -StackOffset),
2086 Flag: MachineInstr::FrameSetup);
2087 StackOffset += stackGrowth;
2088 }
2089
2090 // V1/V2: emit SEH pseudo after the real instruction.
2091 EmitSEHAfter([&]() {
2092 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_PushReg))
2093 .addImm(Val: Reg)
2094 .setMIFlag(MachineInstr::FrameSetup);
2095 if (IsPush2)
2096 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_PushReg))
2097 .addImm(Val: LastCSPush->getOperand(i: 1).getReg())
2098 .setMIFlag(MachineInstr::FrameSetup);
2099 });
2100 }
2101
2102 // Realign stack after we pushed callee-saved registers (so that we'll be
2103 // able to calculate their offsets from the frame pointer).
2104 // Don't do this for Win64, it needs to realign the stack after the prologue.
2105 if (!IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF) &&
2106 !ArgBaseReg.isValid()) {
2107 assert(HasFP && "There should be a frame pointer if stack is realigned.");
2108 auto EmitSEHStackAlign = [&]() {
2109 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_StackAlign))
2110 .addImm(Val: MaxAlign)
2111 .setMIFlag(MachineInstr::FrameSetup);
2112 };
2113 EmitSEHBefore(EmitSEHStackAlign);
2114 BuildStackAlignAND(MBB, MBBI, DL, Reg: StackPtr, MaxAlign);
2115 EmitSEHAfter(EmitSEHStackAlign);
2116 }
2117
2118 // If there is an SUB32ri of ESP immediately before this instruction, merge
2119 // the two. This can be the case when tail call elimination is enabled and
2120 // the callee has more arguments than the caller.
2121 NumBytes = mergeSPUpdates(
2122 MBB, MBBI, CalcNewOffset: [NumBytes](int64_t Offset) { return NumBytes - Offset; },
2123 doMergeWithPrevious: true);
2124
2125 // Adjust stack pointer: ESP -= numbytes.
2126
2127 // Windows and cygwin/mingw require a prologue helper routine when allocating
2128 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
2129 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
2130 // stack and adjust the stack pointer in one go. The 64-bit version of
2131 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
2132 // responsible for adjusting the stack pointer. Touching the stack at 4K
2133 // increments is necessary to ensure that the guard pages used by the OS
2134 // virtual memory manager are allocated in correct sequence.
2135 uint64_t AlignedNumBytes = NumBytes;
2136 if (IsWin64Prologue && !IsFunclet && TRI->hasStackRealignment(MF))
2137 AlignedNumBytes = alignTo(Value: AlignedNumBytes, Align: MaxAlign);
2138
2139 auto EmitSEHStackAlloc = [&]() {
2140 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_StackAlloc))
2141 .addImm(Val: NumBytes)
2142 .setMIFlag(MachineInstr::FrameSetup);
2143 };
2144 if (NumBytes)
2145 EmitSEHBefore(EmitSEHStackAlloc);
2146
2147 if (AlignedNumBytes >= StackProbeSize && EmitStackProbeCall) {
2148 assert(!X86FI->getUsesRedZone() &&
2149 "The Red Zone is not accounted for in stack probes");
2150
2151 // Check whether EAX is livein for this block.
2152 bool isEAXAlive = isEAXLiveIn(MBB);
2153
2154 if (isEAXAlive) {
2155 if (Is64Bit) {
2156 // Save RAX
2157 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::PUSH64r))
2158 .addReg(RegNo: X86::RAX, Flags: RegState::Kill)
2159 .setMIFlag(MachineInstr::FrameSetup);
2160 } else {
2161 // Save EAX
2162 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::PUSH32r))
2163 .addReg(RegNo: X86::EAX, Flags: RegState::Kill)
2164 .setMIFlag(MachineInstr::FrameSetup);
2165 }
2166 }
2167
2168 if (Is64Bit) {
2169 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
2170 // Function prologue is responsible for adjusting the stack pointer.
2171 int64_t Alloc = isEAXAlive ? NumBytes - 8 : NumBytes;
2172 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::getMOVriOpcode(Use64BitReg: Is64Bit, Imm: Alloc)),
2173 DestReg: X86::RAX)
2174 .addImm(Val: Alloc)
2175 .setMIFlag(MachineInstr::FrameSetup);
2176 } else {
2177 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
2178 // We'll also use 4 already allocated bytes for EAX.
2179 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV32ri), DestReg: X86::EAX)
2180 .addImm(Val: isEAXAlive ? NumBytes - 4 : NumBytes)
2181 .setMIFlag(MachineInstr::FrameSetup);
2182 }
2183
2184 // Call __chkstk, __chkstk_ms, or __alloca.
2185 emitStackProbe(MF, MBB, MBBI, DL, InProlog: true);
2186
2187 if (isEAXAlive) {
2188 // Restore RAX/EAX
2189 MachineInstr *MI;
2190 if (Is64Bit)
2191 MI = addRegOffset(MIB: BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64rm), DestReg: X86::RAX),
2192 Reg: StackPtr, isKill: false, Offset: NumBytes - 8);
2193 else
2194 MI = addRegOffset(MIB: BuildMI(MF, MIMD: DL, MCID: TII.get(Opcode: X86::MOV32rm), DestReg: X86::EAX),
2195 Reg: StackPtr, isKill: false, Offset: NumBytes - 4);
2196 MI->setFlag(MachineInstr::FrameSetup);
2197 MBB.insert(I: MBBI, MI);
2198 }
2199 } else if (NumBytes) {
2200 emitSPUpdate(MBB, MBBI, DL, NumBytes: -(int64_t)NumBytes, /*InEpilogue=*/false);
2201 }
2202
2203 if (NumBytes)
2204 EmitSEHAfter(EmitSEHStackAlloc);
2205
2206 int SEHFrameOffset = 0;
2207 Register SPOrEstablisher;
2208 if (IsFunclet) {
2209 if (IsClrFunclet) {
2210 // The establisher parameter passed to a CLR funclet is actually a pointer
2211 // to the (mostly empty) frame of its nearest enclosing funclet; we have
2212 // to find the root function establisher frame by loading the PSPSym from
2213 // the intermediate frame.
2214 unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
2215 MachinePointerInfo NoInfo;
2216 MBB.addLiveIn(PhysReg: Establisher);
2217 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64rm), DestReg: Establisher),
2218 Reg: Establisher, isKill: false, Offset: PSPSlotOffset)
2219 .addMemOperand(MMO: MF.getMachineMemOperand(
2220 PtrInfo: NoInfo, F: MachineMemOperand::MOLoad, Size: SlotSize, BaseAlignment: Align(SlotSize)));
2221 ;
2222 // Save the root establisher back into the current funclet's (mostly
2223 // empty) frame, in case a sub-funclet or the GC needs it.
2224 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64mr)), Reg: StackPtr,
2225 isKill: false, Offset: PSPSlotOffset)
2226 .addReg(RegNo: Establisher)
2227 .addMemOperand(MMO: MF.getMachineMemOperand(
2228 PtrInfo: NoInfo,
2229 F: MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
2230 Size: SlotSize, BaseAlignment: Align(SlotSize)));
2231 }
2232 SPOrEstablisher = Establisher;
2233 } else {
2234 SPOrEstablisher = StackPtr;
2235 }
2236
2237 if (IsWin64Prologue && HasFP) {
2238 // Set RBP to a small fixed offset from RSP. In the funclet case, we base
2239 // this calculation on the incoming establisher, which holds the value of
2240 // RSP from the parent frame at the end of the prologue.
2241 SEHFrameOffset = calculateSetFPREG(SPAdjust: ParentFrameNumBytes);
2242
2243 // If this is not a funclet, emit the CFI describing our frame pointer.
2244 if (NeedsWinCFI && !IsFunclet) {
2245 assert(!NeedsWinFPO && "this setframe incompatible with FPO data");
2246 HasWinCFI = true;
2247 if (isAsynchronousEHPersonality(Pers: Personality) || MF.hasEHFunclets()) {
2248 if (TRI->hasBasePointer(MF))
2249 MF.getWinEHFuncInfo()->SEHSetFrameOffset =
2250 getWinEHParentFrameOffset(MF);
2251 else
2252 MF.getWinEHFuncInfo()->SEHSetFrameOffset = SEHFrameOffset;
2253 }
2254 }
2255
2256 auto EmitSEHSetFrame = [&]() {
2257 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_SetFrame))
2258 .addImm(Val: FramePtr)
2259 .addImm(Val: SEHFrameOffset)
2260 .setMIFlag(MachineInstr::FrameSetup);
2261 };
2262
2263 if (!IsFunclet)
2264 EmitSEHBefore(EmitSEHSetFrame);
2265
2266 if (SEHFrameOffset)
2267 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::LEA64r), DestReg: FramePtr),
2268 Reg: SPOrEstablisher, isKill: false, Offset: SEHFrameOffset);
2269 else
2270 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64rr), DestReg: FramePtr)
2271 .addReg(RegNo: SPOrEstablisher);
2272
2273 if (!IsFunclet)
2274 EmitSEHAfter(EmitSEHSetFrame);
2275 } else if (IsFunclet && STI.is32Bit()) {
2276 // Reset EBP / ESI to something good for funclets.
2277 MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL);
2278 // If we're a catch funclet, we can be returned to via catchret. Save ESP
2279 // into the registration node so that the runtime will restore it for us.
2280 if (!MBB.isCleanupFuncletEntry()) {
2281 assert(Personality == EHPersonality::MSVC_CXX);
2282 Register FrameReg;
2283 int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex;
2284 int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg).getFixed();
2285 // ESP is the first field, so no extra displacement is needed.
2286 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV32mr)), Reg: FrameReg,
2287 isKill: false, Offset: EHRegOffset)
2288 .addReg(RegNo: X86::ESP);
2289 }
2290 }
2291
2292 while (MBBI != MBB.end() && MBBI->getFlag(Flag: MachineInstr::FrameSetup)) {
2293 const MachineInstr &FrameInstr = *MBBI;
2294
2295 if (NeedsWinCFI) {
2296 int FI;
2297 if (Register Reg = TII.isStoreToStackSlot(MI: FrameInstr, FrameIndex&: FI)) {
2298 if (X86::FR64RegClass.contains(Reg)) {
2299 int Offset;
2300 Register IgnoredFrameReg;
2301 if (IsWin64Prologue && IsFunclet)
2302 Offset = getWin64EHFrameIndexRef(MF, FI, SPReg&: IgnoredFrameReg);
2303 else
2304 Offset =
2305 getFrameIndexReference(MF, FI, FrameReg&: IgnoredFrameReg).getFixed() +
2306 SEHFrameOffset;
2307
2308 assert(!NeedsWinFPO && "SEH_SaveXMM incompatible with FPO data");
2309 auto EmitSEHSaveXMM = [&]() {
2310 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_SaveXMM))
2311 .addImm(Val: Reg)
2312 .addImm(Val: Offset)
2313 .setMIFlag(MachineInstr::FrameSetup);
2314 };
2315 EmitSEHBefore(EmitSEHSaveXMM);
2316 ++MBBI;
2317 EmitSEHAfter(EmitSEHSaveXMM);
2318 continue;
2319 }
2320 }
2321 }
2322 ++MBBI;
2323 }
2324
2325 if (NeedsWinCFI && HasWinCFI) {
2326 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_EndPrologue))
2327 .setMIFlag(MachineInstr::FrameSetup);
2328 }
2329
2330 if (FnHasClrFunclet && !IsFunclet) {
2331 // Save the so-called Initial-SP (i.e. the value of the stack pointer
2332 // immediately after the prolog) into the PSPSlot so that funclets
2333 // and the GC can recover it.
2334 unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
2335 auto PSPInfo = MachinePointerInfo::getFixedStack(
2336 MF, FI: MF.getWinEHFuncInfo()->PSPSymFrameIdx);
2337 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64mr)), Reg: StackPtr, isKill: false,
2338 Offset: PSPSlotOffset)
2339 .addReg(RegNo: StackPtr)
2340 .addMemOperand(MMO: MF.getMachineMemOperand(
2341 PtrInfo: PSPInfo, F: MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
2342 Size: SlotSize, BaseAlignment: Align(SlotSize)));
2343 }
2344
2345 // Realign stack after we spilled callee-saved registers (so that we'll be
2346 // able to calculate their offsets from the frame pointer).
2347 // Win64 requires aligning the stack after the prologue.
2348 if (IsWin64Prologue && TRI->hasStackRealignment(MF)) {
2349 assert(HasFP && "There should be a frame pointer if stack is realigned.");
2350 BuildStackAlignAND(MBB, MBBI, DL, Reg: SPOrEstablisher, MaxAlign);
2351 }
2352
2353 // We already dealt with stack realignment and funclets above.
2354 if (IsFunclet && STI.is32Bit())
2355 return;
2356
2357 // If we need a base pointer, set it up here. It's whatever the value
2358 // of the stack pointer is at this point. Any variable size objects
2359 // will be allocated after this, so we can still use the base pointer
2360 // to reference locals.
2361 if (TRI->hasBasePointer(MF)) {
2362 // Update the base pointer with the current stack pointer.
2363 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
2364 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: BasePtr)
2365 .addReg(RegNo: SPOrEstablisher)
2366 .setMIFlag(MachineInstr::FrameSetup);
2367 if (X86FI->getRestoreBasePointer()) {
2368 // Stash value of base pointer. Saving RSP instead of EBP shortens
2369 // dependence chain. Used by SjLj EH.
2370 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
2371 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: Opm)), Reg: FramePtr, isKill: true,
2372 Offset: X86FI->getRestoreBasePointerOffset())
2373 .addReg(RegNo: SPOrEstablisher)
2374 .setMIFlag(MachineInstr::FrameSetup);
2375 }
2376
2377 if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
2378 // Stash the value of the frame pointer relative to the base pointer for
2379 // Win32 EH. This supports Win32 EH, which does the inverse of the above:
2380 // it recovers the frame pointer from the base pointer rather than the
2381 // other way around.
2382 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
2383 Register UsedReg;
2384 int Offset =
2385 getFrameIndexReference(MF, FI: X86FI->getSEHFramePtrSaveIndex(), FrameReg&: UsedReg)
2386 .getFixed();
2387 assert(UsedReg == BasePtr);
2388 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: Opm)), Reg: UsedReg, isKill: true, Offset)
2389 .addReg(RegNo: FramePtr)
2390 .setMIFlag(MachineInstr::FrameSetup);
2391 }
2392 }
2393 if (ArgBaseReg.isValid()) {
2394 // Save argument base pointer.
2395 auto *MI = X86FI->getStackPtrSaveMI();
2396 int FI = MI->getOperand(i: 1).getIndex();
2397 unsigned MOVmr = Is64Bit ? X86::MOV64mr : X86::MOV32mr;
2398 // movl %basereg, offset(%ebp)
2399 addFrameReference(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: MOVmr)), FI)
2400 .addReg(RegNo: ArgBaseReg)
2401 .setMIFlag(MachineInstr::FrameSetup);
2402 }
2403
2404 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
2405 // Mark end of stack pointer adjustment.
2406 if (!HasFP && NumBytes) {
2407 // Define the current CFA rule to use the provided offset.
2408 assert(StackSize);
2409 BuildCFI(
2410 MBB, MBBI, DL,
2411 CFIInst: MCCFIInstruction::cfiDefCfaOffset(L: nullptr, Offset: StackSize - stackGrowth),
2412 Flag: MachineInstr::FrameSetup);
2413 }
2414
2415 // Emit DWARF info specifying the offsets of the callee-saved registers.
2416 emitCalleeSavedFrameMoves(MBB, MBBI, DL, IsPrologue: true);
2417 }
2418
2419 // X86 Interrupt handling function cannot assume anything about the direction
2420 // flag (DF in EFLAGS register). Clear this flag by creating "cld" instruction
2421 // in each prologue of interrupt handler function.
2422 //
2423 // Create "cld" instruction only in these cases:
2424 // 1. The interrupt handling function uses any of the "rep" instructions.
2425 // 2. Interrupt handling function calls another function.
2426 // 3. If there are any inline asm blocks, as we do not know what they do
2427 //
2428 // TODO: We should also emit cld if we detect the use of std, but as of now,
2429 // the compiler does not even emit that instruction or even define it, so in
2430 // practice, this would only happen with inline asm, which we cover anyway.
2431 if (Fn.getCallingConv() == CallingConv::X86_INTR) {
2432 bool NeedsCLD = false;
2433
2434 for (const MachineBasicBlock &B : MF) {
2435 for (const MachineInstr &MI : B) {
2436 if (MI.isCall()) {
2437 NeedsCLD = true;
2438 break;
2439 }
2440
2441 if (isOpcodeRep(Opcode: MI.getOpcode())) {
2442 NeedsCLD = true;
2443 break;
2444 }
2445
2446 if (MI.isInlineAsm()) {
2447 // TODO: Parse asm for rep instructions or call sites?
2448 // For now, let's play it safe and emit a cld instruction
2449 // just in case.
2450 NeedsCLD = true;
2451 break;
2452 }
2453 }
2454 }
2455
2456 if (NeedsCLD) {
2457 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::CLD))
2458 .setMIFlag(MachineInstr::FrameSetup);
2459 }
2460 }
2461
2462 // At this point we know if the function has WinCFI or not.
2463 MF.setHasWinCFI(HasWinCFI);
2464}
2465
2466bool X86FrameLowering::canUseLEAForSPInEpilogue(
2467 const MachineFunction &MF) const {
2468 // We can't use LEA instructions for adjusting the stack pointer if we don't
2469 // have a frame pointer in the Win64 ABI. Only ADD instructions may be used
2470 // to deallocate the stack.
2471 // This means that we can use LEA for SP in two situations:
2472 // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
2473 // 2. We *have* a frame pointer which means we are permitted to use LEA.
2474 return !MF.getTarget().getMCAsmInfo().usesWindowsCFI() || hasFP(MF);
2475}
2476
2477static bool isFuncletReturnInstr(MachineInstr &MI) {
2478 switch (MI.getOpcode()) {
2479 case X86::CATCHRET:
2480 case X86::CLEANUPRET:
2481 return true;
2482 default:
2483 return false;
2484 }
2485 llvm_unreachable("impossible");
2486}
2487
2488// CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
2489// stack. It holds a pointer to the bottom of the root function frame. The
2490// establisher frame pointer passed to a nested funclet may point to the
2491// (mostly empty) frame of its parent funclet, but it will need to find
2492// the frame of the root function to access locals. To facilitate this,
2493// every funclet copies the pointer to the bottom of the root function
2494// frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
2495// same offset for the PSPSym in the root function frame that's used in the
2496// funclets' frames allows each funclet to dynamically accept any ancestor
2497// frame as its establisher argument (the runtime doesn't guarantee the
2498// immediate parent for some reason lost to history), and also allows the GC,
2499// which uses the PSPSym for some bookkeeping, to find it in any funclet's
2500// frame with only a single offset reported for the entire method.
2501unsigned
2502X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
2503 const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
2504 Register SPReg;
2505 int Offset = getFrameIndexReferencePreferSP(MF, FI: Info.PSPSymFrameIdx, FrameReg&: SPReg,
2506 /*IgnoreSPUpdates*/ true)
2507 .getFixed();
2508 assert(Offset >= 0 && SPReg == TRI->getStackRegister());
2509 return static_cast<unsigned>(Offset);
2510}
2511
2512unsigned
2513X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
2514 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2515 // This is the size of the pushed CSRs.
2516 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2517 // This is the size of callee saved XMMs.
2518 const auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
2519 unsigned XMMSize =
2520 WinEHXMMSlotInfo.size() * TRI->getSpillSize(RC: X86::VR128RegClass);
2521 // This is the amount of stack a funclet needs to allocate.
2522 unsigned UsedSize;
2523 EHPersonality Personality =
2524 classifyEHPersonality(Pers: MF.getFunction().getPersonalityFn());
2525 if (Personality == EHPersonality::CoreCLR) {
2526 // CLR funclets need to hold enough space to include the PSPSym, at the
2527 // same offset from the stack pointer (immediately after the prolog) as it
2528 // resides at in the main function.
2529 UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
2530 } else {
2531 // Other funclets just need enough stack for outgoing call arguments.
2532 UsedSize = MF.getFrameInfo().getMaxCallFrameSize();
2533 }
2534 // RBP is not included in the callee saved register block. After pushing RBP,
2535 // everything is 16 byte aligned. Everything we allocate before an outgoing
2536 // call must also be 16 byte aligned.
2537 unsigned FrameSizeMinusRBP = alignTo(Size: CSSize + UsedSize, A: getStackAlign());
2538 // Subtract out the size of the callee saved registers. This is how much stack
2539 // each funclet will allocate.
2540 return FrameSizeMinusRBP + XMMSize - CSSize;
2541}
2542
2543static bool isTailCallOpcode(unsigned Opc) {
2544 return Opc == X86::TCRETURNri || Opc == X86::TCRETURN_WIN64ri ||
2545 Opc == X86::TCRETURN_HIPE32ri || Opc == X86::TCRETURNdi ||
2546 Opc == X86::TCRETURNmi || Opc == X86::TCRETURNri64 ||
2547 Opc == X86::TCRETURNri64_ImpCall || Opc == X86::TCRETURNdi64 ||
2548 Opc == X86::TCRETURNmi64 || Opc == X86::TCRETURN_WINmi64;
2549}
2550
2551void X86FrameLowering::emitEpilogue(MachineFunction &MF,
2552 MachineBasicBlock &MBB) const {
2553 const MachineFrameInfo &MFI = MF.getFrameInfo();
2554 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2555 MachineBasicBlock::iterator Terminator = MBB.getFirstTerminator();
2556 MachineBasicBlock::iterator MBBI = Terminator;
2557 DebugLoc DL;
2558 if (MBBI != MBB.end())
2559 DL = MBBI->getDebugLoc();
2560 // standard x86_64 uses 64-bit frame/stack pointers, x32 - 32-bit.
2561 const bool Is64BitILP32 = STI.isTarget64BitILP32();
2562 Register FramePtr = TRI->getFrameRegister(MF);
2563 Register MachineFramePtr =
2564 Is64BitILP32 ? Register(getX86SubSuperRegister(Reg: FramePtr, Size: 64)) : FramePtr;
2565
2566 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo().usesWindowsCFI();
2567 bool NeedsWin64CFI =
2568 IsWin64Prologue && MF.getFunction().needsUnwindTableEntry();
2569 // For V3 unwind, epilog SEH pseudos are emitted inline before each
2570 // unwind-effecting instruction.
2571 bool IsWin64UnwindV3 =
2572 NeedsWin64CFI && MF.hasWinCFI() && requireWinX64UnwindV3(MF);
2573 bool IsFunclet = MBBI == MBB.end() ? false : isFuncletReturnInstr(MI&: *MBBI);
2574
2575 // Get the number of bytes to allocate from the FrameInfo.
2576 uint64_t StackSize = MFI.getStackSize();
2577 uint64_t MaxAlign = calculateMaxStackAlign(MF);
2578 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2579 unsigned TailCallArgReserveSize = -X86FI->getTCReturnAddrDelta();
2580 bool HasFP = hasFP(MF);
2581 uint64_t NumBytes = 0;
2582
2583 bool NeedsDwarfCFI = (!MF.getTarget().getTargetTriple().isOSDarwin() &&
2584 !MF.getTarget().getTargetTriple().isOSWindows() &&
2585 !MF.getTarget().getTargetTriple().isUEFI()) &&
2586 MF.needsFrameMoves();
2587
2588 Register ArgBaseReg;
2589 if (auto *MI = X86FI->getStackPtrSaveMI()) {
2590 unsigned Opc = X86::LEA32r;
2591 Register StackReg = X86::ESP;
2592 ArgBaseReg = MI->getOperand(i: 0).getReg();
2593 if (STI.is64Bit()) {
2594 Opc = X86::LEA64r;
2595 StackReg = X86::RSP;
2596 }
2597 // leal -4(%basereg), %esp
2598 // .cfi_def_cfa %esp, 4
2599 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: StackReg)
2600 .addUse(RegNo: ArgBaseReg)
2601 .addImm(Val: 1)
2602 .addUse(RegNo: X86::NoRegister)
2603 .addImm(Val: -(int64_t)SlotSize)
2604 .addUse(RegNo: X86::NoRegister)
2605 .setMIFlag(MachineInstr::FrameDestroy);
2606 if (NeedsDwarfCFI) {
2607 unsigned DwarfStackPtr = TRI->getDwarfRegNum(Reg: StackReg, isEH: true);
2608 BuildCFI(MBB, MBBI, DL,
2609 CFIInst: MCCFIInstruction::cfiDefCfa(L: nullptr, Register: DwarfStackPtr, Offset: SlotSize),
2610 Flag: MachineInstr::FrameDestroy);
2611 --MBBI;
2612 }
2613 --MBBI;
2614 }
2615
2616 if (IsFunclet) {
2617 assert(HasFP && "EH funclets without FP not yet implemented");
2618 NumBytes = getWinEHFuncletFrameSize(MF);
2619 } else if (HasFP) {
2620 // Calculate required stack adjustment.
2621 uint64_t FrameSize = StackSize - SlotSize;
2622 NumBytes = FrameSize - CSSize - TailCallArgReserveSize;
2623
2624 // Callee-saved registers were pushed on stack before the stack was
2625 // realigned.
2626 if (TRI->hasStackRealignment(MF) && !IsWin64Prologue)
2627 NumBytes = alignTo(Value: FrameSize, Align: MaxAlign);
2628 } else {
2629 NumBytes = StackSize - CSSize - TailCallArgReserveSize;
2630 }
2631 uint64_t SEHStackAllocAmt = NumBytes;
2632
2633 unsigned SEHFrameOffset = 0;
2634 if (IsWin64Prologue && HasFP)
2635 SEHFrameOffset = calculateSetFPREG(SPAdjust: SEHStackAllocAmt);
2636
2637 // AfterPop is the position to insert .cfi_restore.
2638 MachineBasicBlock::iterator AfterPop = MBBI;
2639 if (HasFP) {
2640 if (X86FI->hasSwiftAsyncContext()) {
2641 // Discard the context.
2642 int64_t Offset = mergeSPAdd(MBB, MBBI, AddOffset: 16, doMergeWithPrevious: true);
2643 emitSPUpdate(MBB, MBBI, DL, NumBytes: Offset, /*InEpilogue*/ true);
2644 }
2645 // Pop EBP.
2646 if (IsWin64UnwindV3)
2647 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_PushReg))
2648 .addImm(Val: FramePtr)
2649 .setMIFlag(MachineInstr::FrameDestroy);
2650 BuildMI(BB&: MBB, I: MBBI, MIMD: DL,
2651 MCID: TII.get(Opcode: getPOPOpcode(ST: MF.getSubtarget<X86Subtarget>())),
2652 DestReg: MachineFramePtr)
2653 .setMIFlag(MachineInstr::FrameDestroy);
2654
2655 // We need to reset FP to its untagged state on return. Bit 60 is currently
2656 // used to show the presence of an extended frame.
2657 if (X86FI->hasSwiftAsyncContext()) {
2658 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::BTR64ri8), DestReg: MachineFramePtr)
2659 .addUse(RegNo: MachineFramePtr)
2660 .addImm(Val: 60)
2661 .setMIFlag(MachineInstr::FrameDestroy);
2662 }
2663
2664 if (NeedsDwarfCFI) {
2665 if (!ArgBaseReg.isValid()) {
2666 unsigned DwarfStackPtr =
2667 TRI->getDwarfRegNum(Reg: Is64Bit ? X86::RSP : X86::ESP, isEH: true);
2668 BuildCFI(MBB, MBBI, DL,
2669 CFIInst: MCCFIInstruction::cfiDefCfa(L: nullptr, Register: DwarfStackPtr, Offset: SlotSize),
2670 Flag: MachineInstr::FrameDestroy);
2671 }
2672 if (!MBB.succ_empty() && !MBB.isReturnBlock()) {
2673 unsigned DwarfFramePtr = TRI->getDwarfRegNum(Reg: MachineFramePtr, isEH: true);
2674 BuildCFI(MBB, MBBI: AfterPop, DL,
2675 CFIInst: MCCFIInstruction::createRestore(L: nullptr, Register: DwarfFramePtr),
2676 Flag: MachineInstr::FrameDestroy);
2677 --MBBI;
2678 --AfterPop;
2679 }
2680 --MBBI;
2681 }
2682 }
2683
2684 MachineBasicBlock::iterator FirstCSPop = MBBI;
2685 // Skip the callee-saved pop instructions.
2686 while (MBBI != MBB.begin()) {
2687 MachineBasicBlock::iterator PI = std::prev(x: MBBI);
2688 unsigned Opc = PI->getOpcode();
2689
2690 if (Opc != X86::DBG_VALUE && !PI->isTerminator()) {
2691 if (!PI->getFlag(Flag: MachineInstr::FrameDestroy) ||
2692 (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::BTR64ri8 &&
2693 Opc != X86::ADD64ri32 && Opc != X86::POPP64r && Opc != X86::POP2 &&
2694 Opc != X86::POP2P && Opc != X86::LEA64r && Opc != X86::SEH_PushReg &&
2695 Opc != X86::SEH_Push2Regs && Opc != X86::SEH_StackAlloc &&
2696 Opc != X86::ADD64ri32_NF))
2697 break;
2698 FirstCSPop = PI;
2699 }
2700
2701 --MBBI;
2702 }
2703 if (ArgBaseReg.isValid()) {
2704 // Restore argument base pointer.
2705 auto *MI = X86FI->getStackPtrSaveMI();
2706 int FI = MI->getOperand(i: 1).getIndex();
2707 unsigned MOVrm = Is64Bit ? X86::MOV64rm : X86::MOV32rm;
2708 // movl offset(%ebp), %basereg
2709 addFrameReference(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: MOVrm), DestReg: ArgBaseReg), FI)
2710 .setMIFlag(MachineInstr::FrameDestroy);
2711 }
2712 MBBI = FirstCSPop;
2713
2714 if (IsFunclet && Terminator->getOpcode() == X86::CATCHRET)
2715 emitCatchRetReturnValue(MBB, MBBI: FirstCSPop, CatchRet: &*Terminator);
2716
2717 if (MBBI != MBB.end())
2718 DL = MBBI->getDebugLoc();
2719 // If there is an ADD32ri or SUB32ri of ESP immediately before this
2720 // instruction, merge the two instructions.
2721 if (NumBytes || MFI.hasVarSizedObjects())
2722 NumBytes = mergeSPAdd(MBB, MBBI, AddOffset: NumBytes, doMergeWithPrevious: true);
2723
2724 if (IsWin64UnwindV3 && NeedsWin64CFI && MF.hasWinCFI()) {
2725 // Find the XMM restores that were tagged with FrameDestroy, now that we
2726 // know the offset we can emit the SEH pseudos for them.
2727 auto EpilogStart = MBBI;
2728 {
2729 auto ScanIt = MBBI;
2730 while (ScanIt != MBB.begin()) {
2731 auto PI = std::prev(x: ScanIt);
2732 int FI;
2733 if (PI->getFlag(Flag: MachineInstr::FrameDestroy) &&
2734 TII.isLoadFromStackSlot(MI: *PI, FrameIndex&: FI)) {
2735 Register Reg = PI->getOperand(i: 0).getReg();
2736 if (X86::FR64RegClass.contains(Reg)) {
2737 Register IgnoredFrameReg;
2738 int Offset =
2739 getFrameIndexReference(MF, FI, FrameReg&: IgnoredFrameReg).getFixed() +
2740 SEHFrameOffset;
2741 BuildMI(BB&: MBB, I: PI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_SaveXMM))
2742 .addImm(Val: Reg)
2743 .addImm(Val: Offset)
2744 .setMIFlag(MachineInstr::FrameDestroy);
2745 // std::prev(PI) is the SEH_SaveXMM we just inserted (before PI).
2746 // We start ScanIt from that point so that the next
2747 // std::prev(ScanIt) will examine the instruction before the pseudo,
2748 // i.e. the next potential XMM restore further up the block.
2749 EpilogStart = std::prev(x: PI);
2750 ScanIt = EpilogStart;
2751 continue;
2752 }
2753 }
2754 break;
2755 }
2756 }
2757
2758 // For V3, SEH_BeginEpilogue must be emitted before any epilog SEH pseudos.
2759 BuildMI(BB&: MBB, I: EpilogStart, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_BeginEpilogue));
2760 }
2761
2762 // If dynamic alloca is used, then reset esp to point to the last callee-saved
2763 // slot before popping them off! Same applies for the case, when stack was
2764 // realigned. Don't do this if this was a funclet epilogue, since the funclets
2765 // will not do realignment or dynamic stack allocation.
2766 if (((TRI->hasStackRealignment(MF)) || MFI.hasVarSizedObjects()) &&
2767 !IsFunclet) {
2768 if (TRI->hasStackRealignment(MF))
2769 MBBI = FirstCSPop;
2770 uint64_t LEAAmount =
2771 IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
2772
2773 if (X86FI->hasSwiftAsyncContext())
2774 LEAAmount -= 16;
2775
2776 // There are only two legal forms of epilogue:
2777 // - add SEHAllocationSize, %rsp
2778 // - lea SEHAllocationSize(%FramePtr), %rsp
2779 //
2780 // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
2781 // However, we may use this sequence if we have a frame pointer because the
2782 // effects of the prologue can safely be undone.
2783 if (IsWin64UnwindV3) {
2784 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_SetFrame))
2785 .addImm(Val: FramePtr)
2786 .addImm(Val: SEHFrameOffset)
2787 .setMIFlag(MachineInstr::FrameDestroy);
2788 if (SEHStackAllocAmt)
2789 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_StackAlloc))
2790 .addImm(Val: SEHStackAllocAmt)
2791 .setMIFlag(MachineInstr::FrameDestroy);
2792 }
2793 if (LEAAmount != 0) {
2794 unsigned Opc = getLEArOpcode(IsLP64: Uses64BitFramePtr);
2795 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: StackPtr), Reg: FramePtr,
2796 isKill: false, Offset: LEAAmount);
2797 --MBBI;
2798 } else {
2799 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
2800 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: StackPtr).addReg(RegNo: FramePtr);
2801 --MBBI;
2802 }
2803 } else if (NumBytes) {
2804 // Adjust stack pointer back: ESP += numbytes.
2805 if (IsWin64UnwindV3)
2806 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_StackAlloc))
2807 .addImm(Val: NumBytes)
2808 .setMIFlag(MachineInstr::FrameDestroy);
2809 emitSPUpdate(MBB, MBBI, DL, NumBytes, /*InEpilogue=*/true);
2810 if (!HasFP && NeedsDwarfCFI) {
2811 // Define the current CFA rule to use the provided offset.
2812 BuildCFI(MBB, MBBI, DL,
2813 CFIInst: MCCFIInstruction::cfiDefCfaOffset(
2814 L: nullptr, Offset: CSSize + TailCallArgReserveSize + SlotSize),
2815 Flag: MachineInstr::FrameDestroy);
2816 }
2817 --MBBI;
2818 }
2819
2820 // For V1/V2, emit SEH_BeginEpilogue after stack restore code.
2821 if (!IsWin64UnwindV3 && NeedsWin64CFI && MF.hasWinCFI())
2822 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_BeginEpilogue));
2823
2824 if (!HasFP && NeedsDwarfCFI) {
2825 MBBI = FirstCSPop;
2826 int64_t Offset = -(int64_t)CSSize - SlotSize;
2827 // Mark callee-saved pop instruction.
2828 // Define the current CFA rule to use the provided offset.
2829 while (MBBI != MBB.end()) {
2830 MachineBasicBlock::iterator PI = MBBI;
2831 unsigned Opc = PI->getOpcode();
2832 ++MBBI;
2833 if (Opc == X86::POP32r || Opc == X86::POP64r || Opc == X86::POPP64r ||
2834 Opc == X86::POP2 || Opc == X86::POP2P) {
2835 Offset += SlotSize;
2836 // Compared to pop, pop2 introduces more stack offset (one more
2837 // register).
2838 if (Opc == X86::POP2 || Opc == X86::POP2P)
2839 Offset += SlotSize;
2840 BuildCFI(MBB, MBBI, DL,
2841 CFIInst: MCCFIInstruction::cfiDefCfaOffset(L: nullptr, Offset: -Offset),
2842 Flag: MachineInstr::FrameDestroy);
2843 }
2844 }
2845 }
2846
2847 // Emit DWARF info specifying the restores of the callee-saved registers.
2848 // For epilogue with return inside or being other block without successor,
2849 // no need to generate .cfi_restore for callee-saved registers.
2850 if (NeedsDwarfCFI && !MBB.succ_empty())
2851 emitCalleeSavedFrameMoves(MBB, MBBI: AfterPop, DL, IsPrologue: false);
2852
2853 if (Terminator == MBB.end() || !isTailCallOpcode(Opc: Terminator->getOpcode())) {
2854 // Add the return addr area delta back since we are not tail calling.
2855 int64_t Delta = X86FI->getTCReturnAddrDelta();
2856 assert(Delta <= 0 && "TCDelta should never be positive");
2857 if (Delta) {
2858 // Check for possible merge with preceding ADD instruction.
2859 int64_t Offset = mergeSPAdd(MBB, MBBI&: Terminator, AddOffset: -Delta, doMergeWithPrevious: true);
2860 emitSPUpdate(MBB, MBBI&: Terminator, DL, NumBytes: Offset, /*InEpilogue=*/true);
2861 }
2862 }
2863
2864 // Emit tilerelease for AMX kernel.
2865 if (X86FI->getAMXProgModel() == AMXProgModelEnum::ManagedRA)
2866 BuildMI(BB&: MBB, I: Terminator, MIMD: DL, MCID: TII.get(Opcode: X86::TILERELEASE));
2867
2868 if (NeedsWin64CFI && MF.hasWinCFI())
2869 BuildMI(BB&: MBB, I: Terminator, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_EndEpilogue));
2870}
2871
2872StackOffset X86FrameLowering::getFrameIndexReference(const MachineFunction &MF,
2873 int FI,
2874 Register &FrameReg) const {
2875 const MachineFrameInfo &MFI = MF.getFrameInfo();
2876
2877 bool IsFixed = MFI.isFixedObjectIndex(ObjectIdx: FI);
2878 // We can't calculate offset from frame pointer if the stack is realigned,
2879 // so enforce usage of stack/base pointer. The base pointer is used when we
2880 // have dynamic allocas in addition to dynamic realignment.
2881 if (TRI->hasBasePointer(MF))
2882 FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getBaseRegister();
2883 else if (TRI->hasStackRealignment(MF))
2884 FrameReg = IsFixed ? TRI->getFramePtr() : TRI->getStackRegister();
2885 else
2886 FrameReg = TRI->getFrameRegister(MF);
2887
2888 // Offset will hold the offset from the stack pointer at function entry to the
2889 // object.
2890 // We need to factor in additional offsets applied during the prologue to the
2891 // frame, base, and stack pointer depending on which is used.
2892 int64_t Offset = MFI.getObjectOffset(ObjectIdx: FI) - getOffsetOfLocalArea();
2893 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2894 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
2895 uint64_t StackSize = MFI.getStackSize();
2896 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo().usesWindowsCFI();
2897 int64_t FPDelta = 0;
2898
2899 // In an x86 interrupt, remove the offset we added to account for the return
2900 // address from any stack object allocated in the caller's frame. Interrupts
2901 // do not have a standard return address. Fixed objects in the current frame,
2902 // such as SSE register spills, should not get this treatment.
2903 if (MF.getFunction().getCallingConv() == CallingConv::X86_INTR &&
2904 Offset >= 0) {
2905 Offset += getOffsetOfLocalArea();
2906 }
2907
2908 if (IsWin64Prologue) {
2909 assert(!MFI.hasCalls() || (StackSize % 16) == 8);
2910
2911 // Calculate required stack adjustment.
2912 uint64_t FrameSize = StackSize - SlotSize;
2913 // If required, include space for extra hidden slot for stashing base
2914 // pointer.
2915 if (X86FI->getRestoreBasePointer())
2916 FrameSize += SlotSize;
2917 uint64_t NumBytes = FrameSize - CSSize;
2918
2919 uint64_t SEHFrameOffset = calculateSetFPREG(SPAdjust: NumBytes);
2920 if (FI && FI == X86FI->getFAIndex())
2921 return StackOffset::getFixed(Fixed: -SEHFrameOffset);
2922
2923 // FPDelta is the offset from the "traditional" FP location of the old base
2924 // pointer followed by return address and the location required by the
2925 // restricted Win64 prologue.
2926 // Add FPDelta to all offsets below that go through the frame pointer.
2927 FPDelta = FrameSize - SEHFrameOffset;
2928 assert((!MFI.hasCalls() || (FPDelta % 16) == 0) &&
2929 "FPDelta isn't aligned per the Win64 ABI!");
2930 }
2931
2932 if (FrameReg == TRI->getFramePtr()) {
2933 // Skip saved EBP/RBP
2934 Offset += SlotSize;
2935
2936 // Account for restricted Windows prologue.
2937 Offset += FPDelta;
2938
2939 // Skip the RETADDR move area
2940 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
2941 if (TailCallReturnAddrDelta < 0)
2942 Offset -= TailCallReturnAddrDelta;
2943
2944 return StackOffset::getFixed(Fixed: Offset);
2945 }
2946
2947 // FrameReg is either the stack pointer or a base pointer. But the base is
2948 // located at the end of the statically known StackSize so the distinction
2949 // doesn't really matter.
2950 if (TRI->hasStackRealignment(MF) || TRI->hasBasePointer(MF))
2951 assert(isAligned(MFI.getObjectAlign(FI), -(Offset + StackSize)));
2952 return StackOffset::getFixed(Fixed: Offset + StackSize);
2953}
2954
2955int X86FrameLowering::getWin64EHFrameIndexRef(const MachineFunction &MF, int FI,
2956 Register &FrameReg) const {
2957 const MachineFrameInfo &MFI = MF.getFrameInfo();
2958 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2959 const auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
2960 const auto it = WinEHXMMSlotInfo.find(Val: FI);
2961
2962 if (it == WinEHXMMSlotInfo.end())
2963 return getFrameIndexReference(MF, FI, FrameReg).getFixed();
2964
2965 FrameReg = TRI->getStackRegister();
2966 return alignDown(Value: MFI.getMaxCallFrameSize(), Align: getStackAlign().value()) +
2967 it->second;
2968}
2969
2970StackOffset
2971X86FrameLowering::getFrameIndexReferenceSP(const MachineFunction &MF, int FI,
2972 Register &FrameReg,
2973 int Adjustment) const {
2974 const MachineFrameInfo &MFI = MF.getFrameInfo();
2975 FrameReg = TRI->getStackRegister();
2976 return StackOffset::getFixed(Fixed: MFI.getObjectOffset(ObjectIdx: FI) -
2977 getOffsetOfLocalArea() + Adjustment);
2978}
2979
2980StackOffset
2981X86FrameLowering::getFrameIndexReferencePreferSP(const MachineFunction &MF,
2982 int FI, Register &FrameReg,
2983 bool IgnoreSPUpdates) const {
2984
2985 const MachineFrameInfo &MFI = MF.getFrameInfo();
2986 // Does not include any dynamic realign.
2987 const uint64_t StackSize = MFI.getStackSize();
2988 // LLVM arranges the stack as follows:
2989 // ...
2990 // ARG2
2991 // ARG1
2992 // RETADDR
2993 // PUSH RBP <-- RBP points here
2994 // PUSH CSRs
2995 // ~~~~~~~ <-- possible stack realignment (non-win64)
2996 // ...
2997 // STACK OBJECTS
2998 // ... <-- RSP after prologue points here
2999 // ~~~~~~~ <-- possible stack realignment (win64)
3000 //
3001 // if (hasVarSizedObjects()):
3002 // ... <-- "base pointer" (ESI/RBX) points here
3003 // DYNAMIC ALLOCAS
3004 // ... <-- RSP points here
3005 //
3006 // Case 1: In the simple case of no stack realignment and no dynamic
3007 // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
3008 // with fixed offsets from RSP.
3009 //
3010 // Case 2: In the case of stack realignment with no dynamic allocas, fixed
3011 // stack objects are addressed with RBP and regular stack objects with RSP.
3012 //
3013 // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
3014 // to address stack arguments for outgoing calls and nothing else. The "base
3015 // pointer" points to local variables, and RBP points to fixed objects.
3016 //
3017 // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
3018 // answer we give is relative to the SP after the prologue, and not the
3019 // SP in the middle of the function.
3020
3021 if (MFI.isFixedObjectIndex(ObjectIdx: FI) && TRI->hasStackRealignment(MF) &&
3022 !STI.isTargetWin64())
3023 return getFrameIndexReference(MF, FI, FrameReg);
3024
3025 // If !hasReservedCallFrame the function might have SP adjustement in the
3026 // body. So, even though the offset is statically known, it depends on where
3027 // we are in the function.
3028 if (!IgnoreSPUpdates && !hasReservedCallFrame(MF))
3029 return getFrameIndexReference(MF, FI, FrameReg);
3030
3031 // We don't handle tail calls, and shouldn't be seeing them either.
3032 assert(MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta() >= 0 &&
3033 "we don't handle this case!");
3034
3035 // This is how the math works out:
3036 //
3037 // %rsp grows (i.e. gets lower) left to right. Each box below is
3038 // one word (eight bytes). Obj0 is the stack slot we're trying to
3039 // get to.
3040 //
3041 // ----------------------------------
3042 // | BP | Obj0 | Obj1 | ... | ObjN |
3043 // ----------------------------------
3044 // ^ ^ ^ ^
3045 // A B C E
3046 //
3047 // A is the incoming stack pointer.
3048 // (B - A) is the local area offset (-8 for x86-64) [1]
3049 // (C - A) is the Offset returned by MFI.getObjectOffset for Obj0 [2]
3050 //
3051 // |(E - B)| is the StackSize (absolute value, positive). For a
3052 // stack that grown down, this works out to be (B - E). [3]
3053 //
3054 // E is also the value of %rsp after stack has been set up, and we
3055 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
3056 // (C - E) == (C - A) - (B - A) + (B - E)
3057 // { Using [1], [2] and [3] above }
3058 // == getObjectOffset - LocalAreaOffset + StackSize
3059
3060 return getFrameIndexReferenceSP(MF, FI, FrameReg, Adjustment: StackSize);
3061}
3062
3063bool X86FrameLowering::assignCalleeSavedSpillSlots(
3064 MachineFunction &MF, const TargetRegisterInfo *TRI,
3065 std::vector<CalleeSavedInfo> &CSI) const {
3066 MachineFrameInfo &MFI = MF.getFrameInfo();
3067 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
3068
3069 unsigned CalleeSavedFrameSize = 0;
3070 unsigned XMMCalleeSavedFrameSize = 0;
3071 auto &WinEHXMMSlotInfo = X86FI->getWinEHXMMSlotInfo();
3072 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
3073
3074 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
3075
3076 if (TailCallReturnAddrDelta < 0) {
3077 // create RETURNADDR area
3078 // arg
3079 // arg
3080 // RETADDR
3081 // { ...
3082 // RETADDR area
3083 // ...
3084 // }
3085 // [EBP]
3086 MFI.CreateFixedObject(Size: -TailCallReturnAddrDelta,
3087 SPOffset: TailCallReturnAddrDelta - SlotSize, IsImmutable: true);
3088 }
3089
3090 // Spill the BasePtr if it's used.
3091 if (this->TRI->hasBasePointer(MF)) {
3092 // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
3093 if (MF.hasEHFunclets()) {
3094 int FI = MFI.CreateSpillStackObject(Size: SlotSize, Alignment: Align(SlotSize));
3095 X86FI->setHasSEHFramePtrSave(true);
3096 X86FI->setSEHFramePtrSaveIndex(FI);
3097 }
3098 }
3099
3100 bool IsFPRemovedFromCSI = false;
3101 if (hasFP(MF)) {
3102 // emitPrologue always spills frame register the first thing.
3103 SpillSlotOffset -= SlotSize;
3104 MFI.CreateFixedSpillStackObject(Size: SlotSize, SPOffset: SpillSlotOffset);
3105
3106 // The async context lives directly before the frame pointer, and we
3107 // allocate a second slot to preserve stack alignment.
3108 if (X86FI->hasSwiftAsyncContext()) {
3109 SpillSlotOffset -= SlotSize;
3110 MFI.CreateFixedSpillStackObject(Size: SlotSize, SPOffset: SpillSlotOffset);
3111 SpillSlotOffset -= SlotSize;
3112 }
3113
3114 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
3115 // the frame register, we can delete it from CSI list and not have to worry
3116 // about avoiding it later.
3117 Register FPReg = TRI->getFrameRegister(MF);
3118 for (unsigned i = 0; i < CSI.size(); ++i) {
3119 if (TRI->regsOverlap(RegA: CSI[i].getReg(), RegB: FPReg)) {
3120 CSI.erase(position: CSI.begin() + i);
3121 IsFPRemovedFromCSI = true;
3122 break;
3123 }
3124 }
3125 }
3126
3127 // Strategy:
3128 // 1. Use push2 when
3129 // a) number of CSR > 1 if no need padding
3130 // b) number of CSR > 2 if need padding
3131 // c) stack alignment >= 16 bytes
3132 // 2. When the number of CSR push is odd
3133 // a. Start to use push2 from the 1st push if stack is 16B aligned.
3134 // b. Start to use push2 from the 2nd push if stack is not 16B aligned.
3135 // 3. When the number of CSR push is even, start to use push2 from the 1st
3136 // push and make the stack 16B aligned before the push
3137 unsigned NumRegsForPush2 = 0;
3138 if (STI.hasPush2Pop2() && getStackAlignment() >= 16) {
3139 unsigned NumCSGPR = llvm::count_if(Range&: CSI, P: [](const CalleeSavedInfo &I) {
3140 return X86::GR64RegClass.contains(Reg: I.getReg());
3141 });
3142 bool UsePush2Pop2 = !IsFPRemovedFromCSI ? NumCSGPR > 2 : NumCSGPR > 1;
3143 NumRegsForPush2 =
3144 UsePush2Pop2
3145 ? alignDown(Value: IsFPRemovedFromCSI ? NumCSGPR : NumCSGPR - 1, Align: 2)
3146 : 0;
3147 }
3148
3149 // Assign slots for GPRs. It increases frame size.
3150 for (CalleeSavedInfo &I : llvm::reverse(C&: CSI)) {
3151 MCRegister Reg = I.getReg();
3152
3153 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
3154 continue;
3155
3156 // A CSR is a candidate for push2/pop2 when it's slot offset is 16B aligned
3157 // or only an odd number of registers in the candidates.
3158 if (X86FI->getNumCandidatesForPush2Pop2() < NumRegsForPush2 &&
3159 (SpillSlotOffset % 16 == 0 ||
3160 X86FI->getNumCandidatesForPush2Pop2() % 2))
3161 X86FI->addCandidateForPush2Pop2(Reg);
3162
3163 SpillSlotOffset -= SlotSize;
3164 CalleeSavedFrameSize += SlotSize;
3165
3166 int SlotIndex = MFI.CreateFixedSpillStackObject(Size: SlotSize, SPOffset: SpillSlotOffset);
3167 I.setFrameIdx(SlotIndex);
3168 }
3169
3170 // Adjust the offset of spill slot as we know the accurate callee saved frame
3171 // size.
3172 if (X86FI->getRestoreBasePointer()) {
3173 SpillSlotOffset -= SlotSize;
3174 CalleeSavedFrameSize += SlotSize;
3175
3176 MFI.CreateFixedSpillStackObject(Size: SlotSize, SPOffset: SpillSlotOffset);
3177 // TODO: saving the slot index is better?
3178 X86FI->setRestoreBasePointer(CalleeSavedFrameSize);
3179 }
3180 assert(X86FI->getNumCandidatesForPush2Pop2() % 2 == 0 &&
3181 "Expect even candidates for push2/pop2");
3182 if (X86FI->getNumCandidatesForPush2Pop2())
3183 ++NumFunctionUsingPush2Pop2;
3184 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
3185 MFI.setCVBytesOfCalleeSavedRegisters(CalleeSavedFrameSize);
3186
3187 // Assign slots for XMMs.
3188 for (CalleeSavedInfo &I : llvm::reverse(C&: CSI)) {
3189 MCRegister Reg = I.getReg();
3190 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
3191 continue;
3192
3193 const TargetRegisterClass *RC = getCalleeSavedSpillRC(Reg, STI, TRI: *TRI);
3194 unsigned Size = TRI->getSpillSize(RC: *RC);
3195 Align Alignment = TRI->getSpillAlign(RC: *RC);
3196 // ensure alignment
3197 assert(SpillSlotOffset < 0 && "SpillSlotOffset should always < 0 on X86");
3198 SpillSlotOffset = -alignTo(Size: -SpillSlotOffset, A: Alignment);
3199
3200 // spill into slot
3201 SpillSlotOffset -= Size;
3202 int SlotIndex = MFI.CreateFixedSpillStackObject(Size, SPOffset: SpillSlotOffset);
3203 I.setFrameIdx(SlotIndex);
3204 MFI.ensureMaxAlignment(Alignment);
3205
3206 // Save the start offset and size of XMM in stack frame for funclets.
3207 if (X86::VR128RegClass.contains(Reg)) {
3208 WinEHXMMSlotInfo[SlotIndex] = XMMCalleeSavedFrameSize;
3209 XMMCalleeSavedFrameSize += Size;
3210 }
3211 }
3212
3213 return true;
3214}
3215
3216bool X86FrameLowering::spillCalleeSavedRegisters(
3217 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
3218 ArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
3219 DebugLoc DL = MBB.findDebugLoc(MBBI: MI);
3220
3221 // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
3222 // for us, and there are no XMM CSRs on Win32.
3223 if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
3224 return true;
3225
3226 // Push GPRs. It increases frame size.
3227 const MachineFunction &MF = *MBB.getParent();
3228 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
3229
3230 // Update LiveIn of the basic block and decide whether we can add a kill flag
3231 // to the use.
3232 auto UpdateLiveInCheckCanKill = [&](Register Reg) {
3233 const MachineRegisterInfo &MRI = MF.getRegInfo();
3234 // Do not set a kill flag on values that are also marked as live-in. This
3235 // happens with the @llvm-returnaddress intrinsic and with arguments
3236 // passed in callee saved registers.
3237 // Omitting the kill flags is conservatively correct even if the live-in
3238 // is not used after all.
3239 if (MRI.isLiveIn(Reg))
3240 return false;
3241 MBB.addLiveIn(PhysReg: Reg);
3242 // Check if any subregister is live-in
3243 for (MCRegAliasIterator AReg(Reg, TRI, false); AReg.isValid(); ++AReg)
3244 if (MRI.isLiveIn(Reg: *AReg))
3245 return false;
3246 return true;
3247 };
3248 auto UpdateLiveInGetKillRegState = [&](Register Reg) {
3249 return getKillRegState(B: UpdateLiveInCheckCanKill(Reg));
3250 };
3251
3252 for (auto RI = CSI.rbegin(), RE = CSI.rend(); RI != RE; ++RI) {
3253 MCRegister Reg = RI->getReg();
3254 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
3255 continue;
3256
3257 if (X86FI->isCandidateForPush2Pop2(Reg)) {
3258 MCRegister Reg2 = (++RI)->getReg();
3259 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: getPUSH2Opcode(ST: STI)))
3260 .addReg(RegNo: Reg, Flags: UpdateLiveInGetKillRegState(Reg))
3261 .addReg(RegNo: Reg2, Flags: UpdateLiveInGetKillRegState(Reg2))
3262 .setMIFlag(MachineInstr::FrameSetup);
3263 } else {
3264 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: getPUSHOpcode(ST: STI)))
3265 .addReg(RegNo: Reg, Flags: UpdateLiveInGetKillRegState(Reg))
3266 .setMIFlag(MachineInstr::FrameSetup);
3267 }
3268 }
3269
3270 if (X86FI->getRestoreBasePointer()) {
3271 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
3272 Register BaseReg = this->TRI->getBaseRegister();
3273 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: Opc))
3274 .addReg(RegNo: BaseReg, Flags: getKillRegState(B: true))
3275 .setMIFlag(MachineInstr::FrameSetup);
3276 }
3277
3278 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
3279 // It can be done by spilling XMMs to stack frame.
3280 for (const CalleeSavedInfo &I : llvm::reverse(C&: CSI)) {
3281 MCRegister Reg = I.getReg();
3282 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
3283 continue;
3284
3285 // Add the callee-saved register as live-in. It's killed at the spill.
3286 MBB.addLiveIn(PhysReg: Reg);
3287 const TargetRegisterClass *RC = getCalleeSavedSpillRC(Reg, STI, TRI: *TRI);
3288
3289 TII.storeRegToStackSlot(MBB, MI, SrcReg: Reg, isKill: true, FrameIndex: I.getFrameIdx(), RC, VReg: Register(),
3290 Flags: MachineInstr::FrameSetup);
3291 }
3292
3293 return true;
3294}
3295
3296void X86FrameLowering::emitCatchRetReturnValue(MachineBasicBlock &MBB,
3297 MachineBasicBlock::iterator MBBI,
3298 MachineInstr *CatchRet) const {
3299 // SEH shouldn't use catchret.
3300 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
3301 MBB.getParent()->getFunction().getPersonalityFn())) &&
3302 "SEH should not use CATCHRET");
3303 const DebugLoc &DL = CatchRet->getDebugLoc();
3304 MachineBasicBlock *CatchRetTarget = CatchRet->getOperand(i: 0).getMBB();
3305
3306 // Fill EAX/RAX with the address of the target block.
3307 if (STI.is64Bit()) {
3308 // LEA64r CatchRetTarget(%rip), %rax
3309 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::LEA64r), DestReg: X86::RAX)
3310 .addReg(RegNo: X86::RIP)
3311 .addImm(Val: 0)
3312 .addReg(RegNo: 0)
3313 .addMBB(MBB: CatchRetTarget)
3314 .addReg(RegNo: 0);
3315 } else {
3316 // MOV32ri $CatchRetTarget, %eax
3317 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV32ri), DestReg: X86::EAX)
3318 .addMBB(MBB: CatchRetTarget);
3319 }
3320
3321 // Record that we've taken the address of CatchRetTarget and no longer just
3322 // reference it in a terminator.
3323 CatchRetTarget->setMachineBlockAddressTaken();
3324}
3325
3326bool X86FrameLowering::restoreCalleeSavedRegisters(
3327 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
3328 MutableArrayRef<CalleeSavedInfo> CSI, const TargetRegisterInfo *TRI) const {
3329 if (CSI.empty())
3330 return false;
3331
3332 if (MI != MBB.end() && isFuncletReturnInstr(MI&: *MI) && STI.isOSWindows()) {
3333 // Don't restore CSRs in 32-bit EH funclets. Matches
3334 // spillCalleeSavedRegisters.
3335 if (STI.is32Bit())
3336 return true;
3337 // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
3338 // funclets. emitEpilogue transforms these to normal jumps.
3339 if (MI->getOpcode() == X86::CATCHRET) {
3340 const Function &F = MBB.getParent()->getFunction();
3341 bool IsSEH = isAsynchronousEHPersonality(
3342 Pers: classifyEHPersonality(Pers: F.getPersonalityFn()));
3343 if (IsSEH)
3344 return true;
3345 }
3346 }
3347
3348 DebugLoc DL = MBB.findDebugLoc(MBBI: MI);
3349 MachineFunction &MF = *MBB.getParent();
3350 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
3351
3352 bool NeedsWin64CFI =
3353 isWin64Prologue(MF) && MF.getFunction().needsUnwindTableEntry();
3354 bool IsWin64UnwindV3 = NeedsWin64CFI && requireWinX64UnwindV3(MF);
3355
3356 // Reload XMMs from stack frame.
3357 for (const CalleeSavedInfo &I : CSI) {
3358 MCRegister Reg = I.getReg();
3359 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
3360 continue;
3361
3362 const TargetRegisterClass *RC = getCalleeSavedSpillRC(Reg, STI, TRI: *TRI);
3363 TII.loadRegFromStackSlot(MBB, MI, DestReg: Reg, FrameIndex: I.getFrameIdx(), RC, VReg: Register(), SubReg: 0,
3364 Flags: MachineInstr::FrameDestroy);
3365 }
3366
3367 // Clear the stack slot for spill base pointer register.
3368 if (X86FI->getRestoreBasePointer()) {
3369 if (IsWin64UnwindV3)
3370 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_PushReg))
3371 .addImm(Val: this->TRI->getBaseRegister())
3372 .setMIFlag(MachineInstr::FrameDestroy);
3373 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
3374 Register BaseReg = this->TRI->getBaseRegister();
3375 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: Opc), DestReg: BaseReg)
3376 .setMIFlag(MachineInstr::FrameDestroy);
3377 }
3378
3379 // POP GPRs.
3380 for (auto I = CSI.begin(), E = CSI.end(); I != E; ++I) {
3381 MCRegister Reg = I->getReg();
3382 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
3383 continue;
3384
3385 if (X86FI->isCandidateForPush2Pop2(Reg)) {
3386 MCRegister Reg2 = (++I)->getReg();
3387 if (IsWin64UnwindV3) {
3388 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_Push2Regs))
3389 .addImm(Val: Reg)
3390 .addImm(Val: Reg2)
3391 .setMIFlag(MachineInstr::FrameDestroy);
3392 }
3393 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: getPOP2Opcode(ST: STI)), DestReg: Reg)
3394 .addReg(RegNo: Reg2, Flags: RegState::Define)
3395 .setMIFlag(MachineInstr::FrameDestroy);
3396 } else {
3397 if (IsWin64UnwindV3)
3398 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: X86::SEH_PushReg))
3399 .addImm(Val: Reg)
3400 .setMIFlag(MachineInstr::FrameDestroy);
3401 BuildMI(BB&: MBB, I: MI, MIMD: DL, MCID: TII.get(Opcode: getPOPOpcode(ST: STI)), DestReg: Reg)
3402 .setMIFlag(MachineInstr::FrameDestroy);
3403 }
3404 }
3405
3406 return true;
3407}
3408
3409void X86FrameLowering::determineCalleeSaves(MachineFunction &MF,
3410 BitVector &SavedRegs,
3411 RegScavenger *RS) const {
3412 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
3413
3414 // Spill the BasePtr if it's used.
3415 if (TRI->hasBasePointer(MF)) {
3416 Register BasePtr = TRI->getBaseRegister();
3417 if (STI.isTarget64BitILP32())
3418 BasePtr = getX86SubSuperRegister(Reg: BasePtr, Size: 64);
3419 SavedRegs.set(BasePtr);
3420 }
3421 if (STI.hasUserReservedRegisters()) {
3422 for (int Reg = SavedRegs.find_first(); Reg != -1;
3423 Reg = SavedRegs.find_next(Prev: Reg)) {
3424 if (STI.isRegisterReservedByUser(i: Reg)) {
3425 SavedRegs.reset(Idx: Reg);
3426 }
3427 }
3428 }
3429}
3430
3431static bool HasNestArgument(const MachineFunction *MF) {
3432 const Function &F = MF->getFunction();
3433 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3434 I++) {
3435 if (I->hasNestAttr() && !I->use_empty())
3436 return true;
3437 }
3438 return false;
3439}
3440
3441/// GetScratchRegister - Get a temp register for performing work in the
3442/// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
3443/// and the properties of the function either one or two registers will be
3444/// needed. Set primary to true for the first register, false for the second.
3445static unsigned GetScratchRegister(bool Is64Bit, bool IsLP64,
3446 const MachineFunction &MF, bool Primary) {
3447 CallingConv::ID CallingConvention = MF.getFunction().getCallingConv();
3448
3449 // Erlang stuff.
3450 if (CallingConvention == CallingConv::HiPE) {
3451 if (Is64Bit)
3452 return Primary ? X86::R14 : X86::R13;
3453 else
3454 return Primary ? X86::EBX : X86::EDI;
3455 }
3456
3457 if (Is64Bit) {
3458 if (IsLP64)
3459 return Primary ? X86::R11 : X86::R12;
3460 else
3461 return Primary ? X86::R11D : X86::R12D;
3462 }
3463
3464 bool IsNested = HasNestArgument(MF: &MF);
3465
3466 if (CallingConvention == CallingConv::X86_FastCall ||
3467 CallingConvention == CallingConv::Fast ||
3468 CallingConvention == CallingConv::Tail) {
3469 if (IsNested)
3470 report_fatal_error(reason: "Segmented stacks does not support fastcall with "
3471 "nested function.");
3472 return Primary ? X86::EAX : X86::ECX;
3473 }
3474 if (IsNested)
3475 return Primary ? X86::EDX : X86::EAX;
3476 return Primary ? X86::ECX : X86::EAX;
3477}
3478
3479// The stack limit in the TCB is set to this many bytes above the actual stack
3480// limit.
3481static const uint64_t kSplitStackAvailable = 256;
3482
3483void X86FrameLowering::adjustForSegmentedStacks(
3484 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
3485 MachineFrameInfo &MFI = MF.getFrameInfo();
3486 uint64_t StackSize;
3487 unsigned TlsReg, TlsOffset;
3488 DebugLoc DL;
3489
3490 // To support shrink-wrapping we would need to insert the new blocks
3491 // at the right place and update the branches to PrologueMBB.
3492 assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
3493
3494 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, Primary: true);
3495 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
3496 "Scratch register is live-in");
3497
3498 if (MF.getFunction().isVarArg())
3499 report_fatal_error(reason: "Segmented stacks do not support vararg functions.");
3500 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
3501 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
3502 !STI.isTargetDragonFly())
3503 report_fatal_error(reason: "Segmented stacks not supported on this platform.");
3504
3505 // Eventually StackSize will be calculated by a link-time pass; which will
3506 // also decide whether checking code needs to be injected into this particular
3507 // prologue.
3508 StackSize = MFI.getStackSize();
3509
3510 if (!MFI.needsSplitStackProlog())
3511 return;
3512
3513 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
3514 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
3515 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
3516 bool IsNested = false;
3517
3518 // We need to know if the function has a nest argument only in 64 bit mode.
3519 if (Is64Bit)
3520 IsNested = HasNestArgument(MF: &MF);
3521
3522 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
3523 // allocMBB needs to be last (terminating) instruction.
3524
3525 for (const auto &LI : PrologueMBB.liveins()) {
3526 allocMBB->addLiveIn(RegMaskPair: LI);
3527 checkMBB->addLiveIn(RegMaskPair: LI);
3528 }
3529
3530 if (IsNested)
3531 allocMBB->addLiveIn(PhysReg: IsLP64 ? X86::R10 : X86::R10D);
3532
3533 MF.push_front(MBB: allocMBB);
3534 MF.push_front(MBB: checkMBB);
3535
3536 // When the frame size is less than 256 we just compare the stack
3537 // boundary directly to the value of the stack pointer, per gcc.
3538 bool CompareStackPointer = StackSize < kSplitStackAvailable;
3539
3540 // Read the limit off the current stacklet off the stack_guard location.
3541 if (Is64Bit) {
3542 if (STI.isTargetLinux()) {
3543 TlsReg = X86::FS;
3544 TlsOffset = IsLP64 ? 0x70 : 0x40;
3545 } else if (STI.isTargetDarwin()) {
3546 TlsReg = X86::GS;
3547 TlsOffset = 0x60 + 90 * 8; // See pthread_machdep.h. Steal TLS slot 90.
3548 } else if (STI.isTargetWin64()) {
3549 TlsReg = X86::GS;
3550 TlsOffset = 0x28; // pvArbitrary, reserved for application use
3551 } else if (STI.isTargetFreeBSD()) {
3552 TlsReg = X86::FS;
3553 TlsOffset = 0x18;
3554 } else if (STI.isTargetDragonFly()) {
3555 TlsReg = X86::FS;
3556 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
3557 } else {
3558 report_fatal_error(reason: "Segmented stacks not supported on this platform.");
3559 }
3560
3561 if (CompareStackPointer)
3562 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
3563 else
3564 BuildMI(BB: checkMBB, MIMD: DL, MCID: TII.get(Opcode: IsLP64 ? X86::LEA64r : X86::LEA64_32r),
3565 DestReg: ScratchReg)
3566 .addReg(RegNo: X86::RSP)
3567 .addImm(Val: 1)
3568 .addReg(RegNo: 0)
3569 .addImm(Val: -StackSize)
3570 .addReg(RegNo: 0);
3571
3572 BuildMI(BB: checkMBB, MIMD: DL, MCID: TII.get(Opcode: IsLP64 ? X86::CMP64rm : X86::CMP32rm))
3573 .addReg(RegNo: ScratchReg)
3574 .addReg(RegNo: 0)
3575 .addImm(Val: 1)
3576 .addReg(RegNo: 0)
3577 .addImm(Val: TlsOffset)
3578 .addReg(RegNo: TlsReg);
3579 } else {
3580 if (STI.isTargetLinux()) {
3581 TlsReg = X86::GS;
3582 TlsOffset = 0x30;
3583 } else if (STI.isTargetDarwin()) {
3584 TlsReg = X86::GS;
3585 TlsOffset = 0x48 + 90 * 4;
3586 } else if (STI.isTargetWin32()) {
3587 TlsReg = X86::FS;
3588 TlsOffset = 0x14; // pvArbitrary, reserved for application use
3589 } else if (STI.isTargetDragonFly()) {
3590 TlsReg = X86::FS;
3591 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
3592 } else if (STI.isTargetFreeBSD()) {
3593 report_fatal_error(reason: "Segmented stacks not supported on FreeBSD i386.");
3594 } else {
3595 report_fatal_error(reason: "Segmented stacks not supported on this platform.");
3596 }
3597
3598 if (CompareStackPointer)
3599 ScratchReg = X86::ESP;
3600 else
3601 BuildMI(BB: checkMBB, MIMD: DL, MCID: TII.get(Opcode: X86::LEA32r), DestReg: ScratchReg)
3602 .addReg(RegNo: X86::ESP)
3603 .addImm(Val: 1)
3604 .addReg(RegNo: 0)
3605 .addImm(Val: -StackSize)
3606 .addReg(RegNo: 0);
3607
3608 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
3609 STI.isTargetDragonFly()) {
3610 BuildMI(BB: checkMBB, MIMD: DL, MCID: TII.get(Opcode: X86::CMP32rm))
3611 .addReg(RegNo: ScratchReg)
3612 .addReg(RegNo: 0)
3613 .addImm(Val: 0)
3614 .addReg(RegNo: 0)
3615 .addImm(Val: TlsOffset)
3616 .addReg(RegNo: TlsReg);
3617 } else if (STI.isTargetDarwin()) {
3618
3619 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
3620 unsigned ScratchReg2;
3621 bool SaveScratch2;
3622 if (CompareStackPointer) {
3623 // The primary scratch register is available for holding the TLS offset.
3624 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, Primary: true);
3625 SaveScratch2 = false;
3626 } else {
3627 // Need to use a second register to hold the TLS offset
3628 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, Primary: false);
3629
3630 // Unfortunately, with fastcc the second scratch register may hold an
3631 // argument.
3632 SaveScratch2 = MF.getRegInfo().isLiveIn(Reg: ScratchReg2);
3633 }
3634
3635 // If Scratch2 is live-in then it needs to be saved.
3636 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
3637 "Scratch register is live-in and not saved");
3638
3639 if (SaveScratch2)
3640 BuildMI(BB: checkMBB, MIMD: DL, MCID: TII.get(Opcode: X86::PUSH32r))
3641 .addReg(RegNo: ScratchReg2, Flags: RegState::Kill);
3642
3643 BuildMI(BB: checkMBB, MIMD: DL, MCID: TII.get(Opcode: X86::MOV32ri), DestReg: ScratchReg2)
3644 .addImm(Val: TlsOffset);
3645 BuildMI(BB: checkMBB, MIMD: DL, MCID: TII.get(Opcode: X86::CMP32rm))
3646 .addReg(RegNo: ScratchReg)
3647 .addReg(RegNo: ScratchReg2)
3648 .addImm(Val: 1)
3649 .addReg(RegNo: 0)
3650 .addImm(Val: 0)
3651 .addReg(RegNo: TlsReg);
3652
3653 if (SaveScratch2)
3654 BuildMI(BB: checkMBB, MIMD: DL, MCID: TII.get(Opcode: X86::POP32r), DestReg: ScratchReg2);
3655 }
3656 }
3657
3658 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
3659 // It jumps to normal execution of the function body.
3660 BuildMI(BB: checkMBB, MIMD: DL, MCID: TII.get(Opcode: X86::JCC_1))
3661 .addMBB(MBB: &PrologueMBB)
3662 .addImm(Val: X86::COND_A);
3663
3664 // On 32 bit we first push the arguments size and then the frame size. On 64
3665 // bit, we pass the stack frame size in r10 and the argument size in r11.
3666 if (Is64Bit) {
3667 // Functions with nested arguments use R10, so it needs to be saved across
3668 // the call to _morestack
3669
3670 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
3671 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
3672 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
3673 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
3674
3675 if (IsNested)
3676 BuildMI(BB: allocMBB, MIMD: DL, MCID: TII.get(Opcode: MOVrr), DestReg: RegAX).addReg(RegNo: Reg10);
3677
3678 BuildMI(BB: allocMBB, MIMD: DL, MCID: TII.get(Opcode: X86::getMOVriOpcode(Use64BitReg: IsLP64, Imm: StackSize)),
3679 DestReg: Reg10)
3680 .addImm(Val: StackSize);
3681 BuildMI(BB: allocMBB, MIMD: DL,
3682 MCID: TII.get(Opcode: X86::getMOVriOpcode(Use64BitReg: IsLP64, Imm: X86FI->getArgumentStackSize())),
3683 DestReg: Reg11)
3684 .addImm(Val: X86FI->getArgumentStackSize());
3685 } else {
3686 BuildMI(BB: allocMBB, MIMD: DL, MCID: TII.get(Opcode: X86::PUSH32i))
3687 .addImm(Val: X86FI->getArgumentStackSize());
3688 BuildMI(BB: allocMBB, MIMD: DL, MCID: TII.get(Opcode: X86::PUSH32i)).addImm(Val: StackSize);
3689 }
3690
3691 // __morestack is in libgcc
3692 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
3693 // Under the large code model, we cannot assume that __morestack lives
3694 // within 2^31 bytes of the call site, so we cannot use pc-relative
3695 // addressing. We cannot perform the call via a temporary register,
3696 // as the rax register may be used to store the static chain, and all
3697 // other suitable registers may be either callee-save or used for
3698 // parameter passing. We cannot use the stack at this point either
3699 // because __morestack manipulates the stack directly.
3700 //
3701 // To avoid these issues, perform an indirect call via a read-only memory
3702 // location containing the address.
3703 //
3704 // This solution is not perfect, as it assumes that the .rodata section
3705 // is laid out within 2^31 bytes of each function body, but this seems
3706 // to be sufficient for JIT.
3707 // FIXME: Add retpoline support and remove the error here..
3708 if (STI.useIndirectThunkCalls())
3709 report_fatal_error(reason: "Emitting morestack calls on 64-bit with the large "
3710 "code model and thunks not yet implemented.");
3711 BuildMI(BB: allocMBB, MIMD: DL, MCID: TII.get(Opcode: X86::CALL64m))
3712 .addReg(RegNo: X86::RIP)
3713 .addImm(Val: 0)
3714 .addReg(RegNo: 0)
3715 .addExternalSymbol(FnName: "__morestack_addr")
3716 .addReg(RegNo: 0);
3717 } else {
3718 if (Is64Bit)
3719 BuildMI(BB: allocMBB, MIMD: DL, MCID: TII.get(Opcode: X86::CALL64pcrel32))
3720 .addExternalSymbol(FnName: "__morestack");
3721 else
3722 BuildMI(BB: allocMBB, MIMD: DL, MCID: TII.get(Opcode: X86::CALLpcrel32))
3723 .addExternalSymbol(FnName: "__morestack");
3724 }
3725
3726 if (IsNested)
3727 BuildMI(BB: allocMBB, MIMD: DL, MCID: TII.get(Opcode: X86::MORESTACK_RET_RESTORE_R10));
3728 else
3729 BuildMI(BB: allocMBB, MIMD: DL, MCID: TII.get(Opcode: X86::MORESTACK_RET));
3730
3731 allocMBB->addSuccessor(Succ: &PrologueMBB);
3732
3733 checkMBB->addSuccessor(Succ: allocMBB, Prob: BranchProbability::getZero());
3734 checkMBB->addSuccessor(Succ: &PrologueMBB, Prob: BranchProbability::getOne());
3735
3736#ifdef EXPENSIVE_CHECKS
3737 MF.verify();
3738#endif
3739}
3740
3741/// Lookup an ERTS parameter in the !hipe.literals named metadata node.
3742/// HiPE provides Erlang Runtime System-internal parameters, such as PCB offsets
3743/// to fields it needs, through a named metadata node "hipe.literals" containing
3744/// name-value pairs.
3745static unsigned getHiPELiteral(NamedMDNode *HiPELiteralsMD,
3746 const StringRef LiteralName) {
3747 for (int i = 0, e = HiPELiteralsMD->getNumOperands(); i != e; ++i) {
3748 MDNode *Node = HiPELiteralsMD->getOperand(i);
3749 if (Node->getNumOperands() != 2)
3750 continue;
3751 MDString *NodeName = dyn_cast<MDString>(Val: Node->getOperand(I: 0));
3752 ValueAsMetadata *NodeVal = dyn_cast<ValueAsMetadata>(Val: Node->getOperand(I: 1));
3753 if (!NodeName || !NodeVal)
3754 continue;
3755 ConstantInt *ValConst = dyn_cast_or_null<ConstantInt>(Val: NodeVal->getValue());
3756 if (ValConst && NodeName->getString() == LiteralName) {
3757 return ValConst->getZExtValue();
3758 }
3759 }
3760
3761 report_fatal_error(reason: "HiPE literal " + LiteralName +
3762 " required but not provided");
3763}
3764
3765// Return true if there are no non-ehpad successors to MBB and there are no
3766// non-meta instructions between MBBI and MBB.end().
3767static bool blockEndIsUnreachable(const MachineBasicBlock &MBB,
3768 MachineBasicBlock::const_iterator MBBI) {
3769 return llvm::all_of(
3770 Range: MBB.successors(),
3771 P: [](const MachineBasicBlock *Succ) { return Succ->isEHPad(); }) &&
3772 std::all_of(first: MBBI, last: MBB.end(), pred: [](const MachineInstr &MI) {
3773 return MI.isMetaInstruction();
3774 });
3775}
3776
3777/// Erlang programs may need a special prologue to handle the stack size they
3778/// might need at runtime. That is because Erlang/OTP does not implement a C
3779/// stack but uses a custom implementation of hybrid stack/heap architecture.
3780/// (for more information see Eric Stenman's Ph.D. thesis:
3781/// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
3782///
3783/// CheckStack:
3784/// temp0 = sp - MaxStack
3785/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
3786/// OldStart:
3787/// ...
3788/// IncStack:
3789/// call inc_stack # doubles the stack space
3790/// temp0 = sp - MaxStack
3791/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
3792void X86FrameLowering::adjustForHiPEPrologue(
3793 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
3794 MachineFrameInfo &MFI = MF.getFrameInfo();
3795 DebugLoc DL;
3796
3797 // To support shrink-wrapping we would need to insert the new blocks
3798 // at the right place and update the branches to PrologueMBB.
3799 assert(&(*MF.begin()) == &PrologueMBB && "Shrink-wrapping not supported yet");
3800
3801 // HiPE-specific values
3802 NamedMDNode *HiPELiteralsMD =
3803 MF.getFunction().getParent()->getNamedMetadata(Name: "hipe.literals");
3804 if (!HiPELiteralsMD)
3805 report_fatal_error(
3806 reason: "Can't generate HiPE prologue without runtime parameters");
3807 const unsigned HipeLeafWords = getHiPELiteral(
3808 HiPELiteralsMD, LiteralName: Is64Bit ? "AMD64_LEAF_WORDS" : "X86_LEAF_WORDS");
3809 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
3810 const unsigned Guaranteed = HipeLeafWords * SlotSize;
3811 unsigned CallerStkArity = MF.getFunction().arg_size() > CCRegisteredArgs
3812 ? MF.getFunction().arg_size() - CCRegisteredArgs
3813 : 0;
3814 unsigned MaxStack = MFI.getStackSize() + CallerStkArity * SlotSize + SlotSize;
3815
3816 assert(STI.isTargetLinux() &&
3817 "HiPE prologue is only supported on Linux operating systems.");
3818
3819 // Compute the largest caller's frame that is needed to fit the callees'
3820 // frames. This 'MaxStack' is computed from:
3821 //
3822 // a) the fixed frame size, which is the space needed for all spilled temps,
3823 // b) outgoing on-stack parameter areas, and
3824 // c) the minimum stack space this function needs to make available for the
3825 // functions it calls (a tunable ABI property).
3826 if (MFI.hasCalls()) {
3827 unsigned MoreStackForCalls = 0;
3828
3829 for (auto &MBB : MF) {
3830 for (auto &MI : MBB) {
3831 if (!MI.isCall())
3832 continue;
3833
3834 // Get callee operand.
3835 const MachineOperand &MO = MI.getOperand(i: 0);
3836
3837 // Only take account of global function calls (no closures etc.).
3838 if (!MO.isGlobal())
3839 continue;
3840
3841 const Function *F = dyn_cast<Function>(Val: MO.getGlobal());
3842 if (!F)
3843 continue;
3844
3845 // Do not update 'MaxStack' for primitive and built-in functions
3846 // (encoded with names either starting with "erlang."/"bif_" or not
3847 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
3848 // "_", such as the BIF "suspend_0") as they are executed on another
3849 // stack.
3850 if (F->getName().contains(Other: "erlang.") || F->getName().contains(Other: "bif_") ||
3851 F->getName().find_first_of(Chars: "._") == StringRef::npos)
3852 continue;
3853
3854 unsigned CalleeStkArity = F->arg_size() > CCRegisteredArgs
3855 ? F->arg_size() - CCRegisteredArgs
3856 : 0;
3857 if (HipeLeafWords - 1 > CalleeStkArity)
3858 MoreStackForCalls =
3859 std::max(a: MoreStackForCalls,
3860 b: (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
3861 }
3862 }
3863 MaxStack += MoreStackForCalls;
3864 }
3865
3866 // If the stack frame needed is larger than the guaranteed then runtime checks
3867 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
3868 if (MaxStack > Guaranteed) {
3869 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
3870 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
3871
3872 for (const auto &LI : PrologueMBB.liveins()) {
3873 stackCheckMBB->addLiveIn(RegMaskPair: LI);
3874 incStackMBB->addLiveIn(RegMaskPair: LI);
3875 }
3876
3877 MF.push_front(MBB: incStackMBB);
3878 MF.push_front(MBB: stackCheckMBB);
3879
3880 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
3881 unsigned LEAop, CMPop, CALLop;
3882 SPLimitOffset = getHiPELiteral(HiPELiteralsMD, LiteralName: "P_NSP_LIMIT");
3883 if (Is64Bit) {
3884 SPReg = X86::RSP;
3885 PReg = X86::RBP;
3886 LEAop = X86::LEA64r;
3887 CMPop = X86::CMP64rm;
3888 CALLop = X86::CALL64pcrel32;
3889 } else {
3890 SPReg = X86::ESP;
3891 PReg = X86::EBP;
3892 LEAop = X86::LEA32r;
3893 CMPop = X86::CMP32rm;
3894 CALLop = X86::CALLpcrel32;
3895 }
3896
3897 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, Primary: true);
3898 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
3899 "HiPE prologue scratch register is live-in");
3900
3901 // Create new MBB for StackCheck:
3902 addRegOffset(MIB: BuildMI(BB: stackCheckMBB, MIMD: DL, MCID: TII.get(Opcode: LEAop), DestReg: ScratchReg), Reg: SPReg,
3903 isKill: false, Offset: -MaxStack);
3904 // SPLimitOffset is in a fixed heap location (pointed by BP).
3905 addRegOffset(MIB: BuildMI(BB: stackCheckMBB, MIMD: DL, MCID: TII.get(Opcode: CMPop)).addReg(RegNo: ScratchReg),
3906 Reg: PReg, isKill: false, Offset: SPLimitOffset);
3907 BuildMI(BB: stackCheckMBB, MIMD: DL, MCID: TII.get(Opcode: X86::JCC_1))
3908 .addMBB(MBB: &PrologueMBB)
3909 .addImm(Val: X86::COND_AE);
3910
3911 // Create new MBB for IncStack:
3912 BuildMI(BB: incStackMBB, MIMD: DL, MCID: TII.get(Opcode: CALLop)).addExternalSymbol(FnName: "inc_stack_0");
3913 addRegOffset(MIB: BuildMI(BB: incStackMBB, MIMD: DL, MCID: TII.get(Opcode: LEAop), DestReg: ScratchReg), Reg: SPReg,
3914 isKill: false, Offset: -MaxStack);
3915 addRegOffset(MIB: BuildMI(BB: incStackMBB, MIMD: DL, MCID: TII.get(Opcode: CMPop)).addReg(RegNo: ScratchReg),
3916 Reg: PReg, isKill: false, Offset: SPLimitOffset);
3917 BuildMI(BB: incStackMBB, MIMD: DL, MCID: TII.get(Opcode: X86::JCC_1))
3918 .addMBB(MBB: incStackMBB)
3919 .addImm(Val: X86::COND_LE);
3920
3921 stackCheckMBB->addSuccessor(Succ: &PrologueMBB, Prob: {99, 100});
3922 stackCheckMBB->addSuccessor(Succ: incStackMBB, Prob: {1, 100});
3923 incStackMBB->addSuccessor(Succ: &PrologueMBB, Prob: {99, 100});
3924 incStackMBB->addSuccessor(Succ: incStackMBB, Prob: {1, 100});
3925 }
3926#ifdef EXPENSIVE_CHECKS
3927 MF.verify();
3928#endif
3929}
3930
3931bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
3932 MachineBasicBlock::iterator MBBI,
3933 const DebugLoc &DL,
3934 int Offset) const {
3935 if (Offset <= 0)
3936 return false;
3937
3938 if (Offset % SlotSize)
3939 return false;
3940
3941 int NumPops = Offset / SlotSize;
3942 // This is only worth it if we have at most 2 pops.
3943 if (NumPops != 1 && NumPops != 2)
3944 return false;
3945
3946 // Handle only the trivial case where the adjustment directly follows
3947 // a call. This is the most common one, anyway.
3948 if (MBBI == MBB.begin())
3949 return false;
3950 MachineBasicBlock::iterator Prev = std::prev(x: MBBI);
3951 if (!Prev->isCall() || !Prev->getOperand(i: 1).isRegMask())
3952 return false;
3953
3954 unsigned Regs[2];
3955 unsigned FoundRegs = 0;
3956
3957 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
3958 const MachineOperand &RegMask = Prev->getOperand(i: 1);
3959
3960 auto &RegClass =
3961 Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
3962 // Try to find up to NumPops free registers.
3963 for (auto Candidate : RegClass) {
3964 // Poor man's liveness:
3965 // Since we're immediately after a call, any register that is clobbered
3966 // by the call and not defined by it can be considered dead.
3967 if (!RegMask.clobbersPhysReg(PhysReg: Candidate))
3968 continue;
3969
3970 // Don't clobber reserved registers
3971 if (MRI.isReserved(PhysReg: Candidate))
3972 continue;
3973
3974 bool IsDef = false;
3975 for (const MachineOperand &MO : Prev->implicit_operands()) {
3976 if (MO.isReg() && MO.isDef() &&
3977 TRI->isSuperOrSubRegisterEq(RegA: MO.getReg(), RegB: Candidate)) {
3978 IsDef = true;
3979 break;
3980 }
3981 }
3982
3983 if (IsDef)
3984 continue;
3985
3986 Regs[FoundRegs++] = Candidate;
3987 if (FoundRegs == (unsigned)NumPops)
3988 break;
3989 }
3990
3991 if (FoundRegs == 0)
3992 return false;
3993
3994 // If we found only one free register, but need two, reuse the same one twice.
3995 while (FoundRegs < (unsigned)NumPops)
3996 Regs[FoundRegs++] = Regs[0];
3997
3998 for (int i = 0; i < NumPops; ++i)
3999 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: STI.is64Bit() ? X86::POP64r : X86::POP32r),
4000 DestReg: Regs[i]);
4001
4002 return true;
4003}
4004
4005MachineBasicBlock::iterator X86FrameLowering::eliminateCallFramePseudoInstr(
4006 MachineFunction &MF, MachineBasicBlock &MBB,
4007 MachineBasicBlock::iterator I) const {
4008 bool reserveCallFrame = hasReservedCallFrame(MF);
4009 unsigned Opcode = I->getOpcode();
4010 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
4011 DebugLoc DL = I->getDebugLoc(); // copy DebugLoc as I will be erased.
4012 uint64_t Amount = TII.getFrameSize(I: *I);
4013 uint64_t InternalAmt = (isDestroy || Amount) ? TII.getFrameAdjustment(I: *I) : 0;
4014 I = MBB.erase(I);
4015 auto InsertPos = skipDebugInstructionsForward(It: I, End: MBB.end());
4016
4017 // Try to avoid emitting dead SP adjustments if the block end is unreachable,
4018 // typically because the function is marked noreturn (abort, throw,
4019 // assert_fail, etc).
4020 if (isDestroy && blockEndIsUnreachable(MBB, MBBI: I))
4021 return I;
4022
4023 if (!reserveCallFrame) {
4024 // If the stack pointer can be changed after prologue, turn the
4025 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
4026 // adjcallstackdown instruction into 'add ESP, <amt>'
4027
4028 // We need to keep the stack aligned properly. To do this, we round the
4029 // amount of space needed for the outgoing arguments up to the next
4030 // alignment boundary.
4031 Amount = alignTo(Size: Amount, A: getStackAlign());
4032
4033 const Function &F = MF.getFunction();
4034 bool WindowsCFI = MF.getTarget().getMCAsmInfo().usesWindowsCFI();
4035 bool DwarfCFI = !WindowsCFI && MF.needsFrameMoves();
4036
4037 // If we have any exception handlers in this function, and we adjust
4038 // the SP before calls, we may need to indicate this to the unwinder
4039 // using GNU_ARGS_SIZE. Note that this may be necessary even when
4040 // Amount == 0, because the preceding function may have set a non-0
4041 // GNU_ARGS_SIZE.
4042 // TODO: We don't need to reset this between subsequent functions,
4043 // if it didn't change.
4044 bool HasDwarfEHHandlers = !WindowsCFI && !MF.getLandingPads().empty();
4045
4046 if (HasDwarfEHHandlers && !isDestroy &&
4047 MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences())
4048 BuildCFI(MBB, MBBI: InsertPos, DL,
4049 CFIInst: MCCFIInstruction::createGnuArgsSize(L: nullptr, Size: Amount));
4050
4051 if (Amount == 0)
4052 return I;
4053
4054 // Factor out the amount that gets handled inside the sequence
4055 // (Pushes of argument for frame setup, callee pops for frame destroy)
4056 Amount -= InternalAmt;
4057
4058 // TODO: This is needed only if we require precise CFA.
4059 // If this is a callee-pop calling convention, emit a CFA adjust for
4060 // the amount the callee popped.
4061 if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF))
4062 BuildCFI(MBB, MBBI: InsertPos, DL,
4063 CFIInst: MCCFIInstruction::createAdjustCfaOffset(L: nullptr, Adjustment: -InternalAmt));
4064
4065 // Add Amount to SP to destroy a frame, or subtract to setup.
4066 int64_t StackAdjustment = isDestroy ? Amount : -Amount;
4067 int64_t CfaAdjustment = StackAdjustment;
4068
4069 if (StackAdjustment) {
4070 // Merge with any previous or following adjustment instruction. Note: the
4071 // instructions merged with here do not have CFI, so their stack
4072 // adjustments do not feed into CfaAdjustment
4073
4074 auto CalcCfaAdjust = [&CfaAdjustment](MachineBasicBlock::iterator PI,
4075 int64_t Offset) {
4076 CfaAdjustment += Offset;
4077 };
4078 auto CalcNewOffset = [&StackAdjustment](int64_t Offset) {
4079 return StackAdjustment + Offset;
4080 };
4081 StackAdjustment =
4082 mergeSPUpdates(MBB, MBBI&: InsertPos, FoundStackAdjust: CalcCfaAdjust, CalcNewOffset, doMergeWithPrevious: true);
4083 StackAdjustment =
4084 mergeSPUpdates(MBB, MBBI&: InsertPos, FoundStackAdjust: CalcCfaAdjust, CalcNewOffset, doMergeWithPrevious: false);
4085
4086 if (StackAdjustment) {
4087 if (!(F.hasMinSize() &&
4088 adjustStackWithPops(MBB, MBBI: InsertPos, DL, Offset: StackAdjustment)))
4089 BuildStackAdjustment(MBB, MBBI: InsertPos, DL, Offset: StackAdjustment,
4090 /*InEpilogue=*/false);
4091 }
4092 }
4093
4094 if (DwarfCFI && !hasFP(MF) && CfaAdjustment) {
4095 // If we don't have FP, but need to generate unwind information,
4096 // we need to set the correct CFA offset after the stack adjustment.
4097 // How much we adjust the CFA offset depends on whether we're emitting
4098 // CFI only for EH purposes or for debugging. EH only requires the CFA
4099 // offset to be correct at each call site, while for debugging we want
4100 // it to be more precise.
4101
4102 // TODO: When not using precise CFA, we also need to adjust for the
4103 // InternalAmt here.
4104 BuildCFI(
4105 MBB, MBBI: InsertPos, DL,
4106 CFIInst: MCCFIInstruction::createAdjustCfaOffset(L: nullptr, Adjustment: -CfaAdjustment));
4107 }
4108
4109 return I;
4110 }
4111
4112 if (InternalAmt) {
4113 MachineBasicBlock::iterator CI = I;
4114 MachineBasicBlock::iterator B = MBB.begin();
4115 while (CI != B && !std::prev(x: CI)->isCall())
4116 --CI;
4117 BuildStackAdjustment(MBB, MBBI: CI, DL, Offset: -InternalAmt, /*InEpilogue=*/false);
4118 }
4119
4120 return I;
4121}
4122
4123bool X86FrameLowering::canUseAsPrologue(const MachineBasicBlock &MBB) const {
4124 assert(MBB.getParent() && "Block is not attached to a function!");
4125 const MachineFunction &MF = *MBB.getParent();
4126 if (!MBB.isLiveIn(Reg: X86::EFLAGS))
4127 return true;
4128
4129 // If stack probes have to loop inline or call, that will clobber EFLAGS.
4130 // FIXME: we could allow cases that will use emitStackProbeInlineGenericBlock.
4131 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
4132 const X86TargetLowering &TLI = *STI.getTargetLowering();
4133 if (TLI.hasInlineStackProbe(MF) || TLI.hasStackProbeSymbol(MF))
4134 return false;
4135
4136 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
4137 return !TRI->hasStackRealignment(MF) && !X86FI->hasSwiftAsyncContext();
4138}
4139
4140bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
4141 assert(MBB.getParent() && "Block is not attached to a function!");
4142
4143 // Win64 has strict requirements in terms of epilogue and we are
4144 // not taking a chance at messing with them.
4145 // I.e., unless this block is already an exit block, we can't use
4146 // it as an epilogue.
4147 if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
4148 return false;
4149
4150 // Swift async context epilogue has a BTR instruction that clobbers parts of
4151 // EFLAGS.
4152 const MachineFunction &MF = *MBB.getParent();
4153 if (MF.getInfo<X86MachineFunctionInfo>()->hasSwiftAsyncContext())
4154 return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
4155
4156 if (canUseLEAForSPInEpilogue(MF: *MBB.getParent()))
4157 return true;
4158
4159 // If we cannot use LEA to adjust SP, we may need to use ADD, which
4160 // clobbers the EFLAGS. Check that we do not need to preserve it,
4161 // otherwise, conservatively assume this is not
4162 // safe to insert the epilogue here.
4163 return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
4164}
4165
4166bool X86FrameLowering::enableShrinkWrapping(const MachineFunction &MF) const {
4167 // If we may need to emit frameless compact unwind information, give
4168 // up as this is currently broken: PR25614.
4169 bool CompactUnwind =
4170 MF.getContext().getObjectFileInfo()->getCompactUnwindSection() != nullptr;
4171 return (MF.getFunction().hasFnAttribute(Kind: Attribute::NoUnwind) || hasFP(MF) ||
4172 !CompactUnwind) &&
4173 // The lowering of segmented stack and HiPE only support entry
4174 // blocks as prologue blocks: PR26107. This limitation may be
4175 // lifted if we fix:
4176 // - adjustForSegmentedStacks
4177 // - adjustForHiPEPrologue
4178 MF.getFunction().getCallingConv() != CallingConv::HiPE &&
4179 !MF.shouldSplitStack();
4180}
4181
4182MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers(
4183 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
4184 const DebugLoc &DL, bool RestoreSP) const {
4185 assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
4186 assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
4187 assert(STI.is32Bit() && !Uses64BitFramePtr &&
4188 "restoring EBP/ESI on non-32-bit target");
4189
4190 MachineFunction &MF = *MBB.getParent();
4191 Register FramePtr = TRI->getFrameRegister(MF);
4192 Register BasePtr = TRI->getBaseRegister();
4193 WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
4194 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
4195 MachineFrameInfo &MFI = MF.getFrameInfo();
4196
4197 // FIXME: Don't set FrameSetup flag in catchret case.
4198
4199 int FI = FuncInfo.EHRegNodeFrameIndex;
4200 int EHRegSize = MFI.getObjectSize(ObjectIdx: FI);
4201
4202 if (RestoreSP) {
4203 // MOV32rm -EHRegSize(%ebp), %esp
4204 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV32rm), DestReg: X86::ESP),
4205 Reg: X86::EBP, isKill: true, Offset: -EHRegSize)
4206 .setMIFlag(MachineInstr::FrameSetup);
4207 }
4208
4209 Register UsedReg;
4210 int EHRegOffset = getFrameIndexReference(MF, FI, FrameReg&: UsedReg).getFixed();
4211 int EndOffset = -EHRegOffset - EHRegSize;
4212 FuncInfo.EHRegNodeEndOffset = EndOffset;
4213
4214 if (UsedReg == FramePtr) {
4215 // ADD $offset, %ebp
4216 unsigned ADDri = getADDriOpcode(IsLP64: false);
4217 BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: ADDri), DestReg: FramePtr)
4218 .addReg(RegNo: FramePtr)
4219 .addImm(Val: EndOffset)
4220 .setMIFlag(MachineInstr::FrameSetup)
4221 ->getOperand(i: 3)
4222 .setIsDead();
4223 assert(EndOffset >= 0 &&
4224 "end of registration object above normal EBP position!");
4225 } else if (UsedReg == BasePtr) {
4226 // LEA offset(%ebp), %esi
4227 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::LEA32r), DestReg: BasePtr),
4228 Reg: FramePtr, isKill: false, Offset: EndOffset)
4229 .setMIFlag(MachineInstr::FrameSetup);
4230 // MOV32rm SavedEBPOffset(%esi), %ebp
4231 assert(X86FI->getHasSEHFramePtrSave());
4232 int Offset =
4233 getFrameIndexReference(MF, FI: X86FI->getSEHFramePtrSaveIndex(), FrameReg&: UsedReg)
4234 .getFixed();
4235 assert(UsedReg == BasePtr);
4236 addRegOffset(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV32rm), DestReg: FramePtr),
4237 Reg: UsedReg, isKill: true, Offset)
4238 .setMIFlag(MachineInstr::FrameSetup);
4239 } else {
4240 llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
4241 }
4242 return MBBI;
4243}
4244
4245int X86FrameLowering::getInitialCFAOffset(const MachineFunction &MF) const {
4246 return TRI->getSlotSize();
4247}
4248
4249Register
4250X86FrameLowering::getInitialCFARegister(const MachineFunction &MF) const {
4251 return StackPtr;
4252}
4253
4254TargetFrameLowering::DwarfFrameBase
4255X86FrameLowering::getDwarfFrameBase(const MachineFunction &MF) const {
4256 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
4257 Register FrameRegister = RI->getFrameRegister(MF);
4258 if (getInitialCFARegister(MF) == FrameRegister &&
4259 MF.getInfo<X86MachineFunctionInfo>()->hasCFIAdjustCfa()) {
4260 DwarfFrameBase FrameBase;
4261 FrameBase.Kind = DwarfFrameBase::CFA;
4262 FrameBase.Location.Offset =
4263 -MF.getFrameInfo().getStackSize() - getInitialCFAOffset(MF);
4264 return FrameBase;
4265 }
4266
4267 return DwarfFrameBase{.Kind: DwarfFrameBase::Register, .Location: {.Reg: FrameRegister}};
4268}
4269
4270namespace {
4271// Struct used by orderFrameObjects to help sort the stack objects.
4272struct X86FrameSortingObject {
4273 bool IsValid = false; // true if we care about this Object.
4274 unsigned ObjectIndex = 0; // Index of Object into MFI list.
4275 unsigned ObjectSize = 0; // Size of Object in bytes.
4276 Align ObjectAlignment = Align(1); // Alignment of Object in bytes.
4277 unsigned ObjectNumUses = 0; // Object static number of uses.
4278};
4279
4280// The comparison function we use for std::sort to order our local
4281// stack symbols. The current algorithm is to use an estimated
4282// "density". This takes into consideration the size and number of
4283// uses each object has in order to roughly minimize code size.
4284// So, for example, an object of size 16B that is referenced 5 times
4285// will get higher priority than 4 4B objects referenced 1 time each.
4286// It's not perfect and we may be able to squeeze a few more bytes out of
4287// it (for example : 0(esp) requires fewer bytes, symbols allocated at the
4288// fringe end can have special consideration, given their size is less
4289// important, etc.), but the algorithmic complexity grows too much to be
4290// worth the extra gains we get. This gets us pretty close.
4291// The final order leaves us with objects with highest priority going
4292// at the end of our list.
4293struct X86FrameSortingComparator {
4294 inline bool operator()(const X86FrameSortingObject &A,
4295 const X86FrameSortingObject &B) const {
4296 uint64_t DensityAScaled, DensityBScaled;
4297
4298 // For consistency in our comparison, all invalid objects are placed
4299 // at the end. This also allows us to stop walking when we hit the
4300 // first invalid item after it's all sorted.
4301 if (!A.IsValid)
4302 return false;
4303 if (!B.IsValid)
4304 return true;
4305
4306 // The density is calculated by doing :
4307 // (double)DensityA = A.ObjectNumUses / A.ObjectSize
4308 // (double)DensityB = B.ObjectNumUses / B.ObjectSize
4309 // Since this approach may cause inconsistencies in
4310 // the floating point <, >, == comparisons, depending on the floating
4311 // point model with which the compiler was built, we're going
4312 // to scale both sides by multiplying with
4313 // A.ObjectSize * B.ObjectSize. This ends up factoring away
4314 // the division and, with it, the need for any floating point
4315 // arithmetic.
4316 DensityAScaled = static_cast<uint64_t>(A.ObjectNumUses) *
4317 static_cast<uint64_t>(B.ObjectSize);
4318 DensityBScaled = static_cast<uint64_t>(B.ObjectNumUses) *
4319 static_cast<uint64_t>(A.ObjectSize);
4320
4321 // If the two densities are equal, prioritize highest alignment
4322 // objects. This allows for similar alignment objects
4323 // to be packed together (given the same density).
4324 // There's room for improvement here, also, since we can pack
4325 // similar alignment (different density) objects next to each
4326 // other to save padding. This will also require further
4327 // complexity/iterations, and the overall gain isn't worth it,
4328 // in general. Something to keep in mind, though.
4329 if (DensityAScaled == DensityBScaled)
4330 return A.ObjectAlignment < B.ObjectAlignment;
4331
4332 return DensityAScaled < DensityBScaled;
4333 }
4334};
4335} // namespace
4336
4337// Order the symbols in the local stack.
4338// We want to place the local stack objects in some sort of sensible order.
4339// The heuristic we use is to try and pack them according to static number
4340// of uses and size of object in order to minimize code size.
4341void X86FrameLowering::orderFrameObjects(
4342 const MachineFunction &MF, SmallVectorImpl<int> &ObjectsToAllocate) const {
4343 const MachineFrameInfo &MFI = MF.getFrameInfo();
4344
4345 // Don't waste time if there's nothing to do.
4346 if (ObjectsToAllocate.empty())
4347 return;
4348
4349 // Create an array of all MFI objects. We won't need all of these
4350 // objects, but we're going to create a full array of them to make
4351 // it easier to index into when we're counting "uses" down below.
4352 // We want to be able to easily/cheaply access an object by simply
4353 // indexing into it, instead of having to search for it every time.
4354 std::vector<X86FrameSortingObject> SortingObjects(MFI.getObjectIndexEnd());
4355
4356 // Walk the objects we care about and mark them as such in our working
4357 // struct.
4358 for (auto &Obj : ObjectsToAllocate) {
4359 SortingObjects[Obj].IsValid = true;
4360 SortingObjects[Obj].ObjectIndex = Obj;
4361 SortingObjects[Obj].ObjectAlignment = MFI.getObjectAlign(ObjectIdx: Obj);
4362 // Set the size.
4363 int ObjectSize = MFI.getObjectSize(ObjectIdx: Obj);
4364 if (ObjectSize == 0)
4365 // Variable size. Just use 4.
4366 SortingObjects[Obj].ObjectSize = 4;
4367 else
4368 SortingObjects[Obj].ObjectSize = ObjectSize;
4369 }
4370
4371 // Count the number of uses for each object.
4372 for (auto &MBB : MF) {
4373 for (auto &MI : MBB) {
4374 if (MI.isDebugInstr())
4375 continue;
4376 for (const MachineOperand &MO : MI.operands()) {
4377 // Check to see if it's a local stack symbol.
4378 if (!MO.isFI())
4379 continue;
4380 int Index = MO.getIndex();
4381 // Check to see if it falls within our range, and is tagged
4382 // to require ordering.
4383 if (Index >= 0 && Index < MFI.getObjectIndexEnd() &&
4384 SortingObjects[Index].IsValid)
4385 SortingObjects[Index].ObjectNumUses++;
4386 }
4387 }
4388 }
4389
4390 // Sort the objects using X86FrameSortingAlgorithm (see its comment for
4391 // info).
4392 llvm::stable_sort(Range&: SortingObjects, C: X86FrameSortingComparator());
4393
4394 // Now modify the original list to represent the final order that
4395 // we want. The order will depend on whether we're going to access them
4396 // from the stack pointer or the frame pointer. For SP, the list should
4397 // end up with the END containing objects that we want with smaller offsets.
4398 // For FP, it should be flipped.
4399 int i = 0;
4400 for (auto &Obj : SortingObjects) {
4401 // All invalid items are sorted at the end, so it's safe to stop.
4402 if (!Obj.IsValid)
4403 break;
4404 ObjectsToAllocate[i++] = Obj.ObjectIndex;
4405 }
4406
4407 // Flip it if we're accessing off of the FP.
4408 if (!TRI->hasStackRealignment(MF) && hasFP(MF))
4409 std::reverse(first: ObjectsToAllocate.begin(), last: ObjectsToAllocate.end());
4410}
4411
4412unsigned
4413X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const {
4414 // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
4415 unsigned Offset = 16;
4416 // RBP is immediately pushed.
4417 Offset += SlotSize;
4418 // All callee-saved registers are then pushed.
4419 Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
4420 // Every funclet allocates enough stack space for the largest outgoing call.
4421 Offset += getWinEHFuncletFrameSize(MF);
4422 return Offset;
4423}
4424
4425void X86FrameLowering::processFunctionBeforeFrameFinalized(
4426 MachineFunction &MF, RegScavenger *RS) const {
4427 // Mark the function as not having WinCFI. We will set it back to true in
4428 // emitPrologue if it gets called and emits CFI.
4429 MF.setHasWinCFI(false);
4430
4431 MachineFrameInfo &MFI = MF.getFrameInfo();
4432 // If the frame is big enough that we might need to scavenge a register to
4433 // handle huge offsets, reserve a stack slot for that now.
4434 if (!isInt<32>(x: MFI.estimateStackSize(MF))) {
4435 int FI = MFI.CreateStackObject(Size: SlotSize, Alignment: Align(SlotSize), isSpillSlot: false);
4436 RS->addScavengingFrameIndex(FI);
4437 }
4438
4439 // If we are using Windows x64 CFI, ensure that the stack is always 8 byte
4440 // aligned. The format doesn't support misaligned stack adjustments.
4441 if (MF.getTarget().getMCAsmInfo().usesWindowsCFI())
4442 MF.getFrameInfo().ensureMaxAlignment(Alignment: Align(SlotSize));
4443
4444 // If this function isn't doing Win64-style C++ EH, we don't need to do
4445 // anything.
4446 if (STI.is64Bit() && MF.hasEHFunclets() &&
4447 classifyEHPersonality(Pers: MF.getFunction().getPersonalityFn()) ==
4448 EHPersonality::MSVC_CXX) {
4449 adjustFrameForMsvcCxxEh(MF);
4450 }
4451}
4452
4453void X86FrameLowering::adjustFrameForMsvcCxxEh(MachineFunction &MF) const {
4454 // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
4455 // relative to RSP after the prologue. Find the offset of the last fixed
4456 // object, so that we can allocate a slot immediately following it. If there
4457 // were no fixed objects, use offset -SlotSize, which is immediately after the
4458 // return address. Fixed objects have negative frame indices.
4459 MachineFrameInfo &MFI = MF.getFrameInfo();
4460 WinEHFuncInfo &EHInfo = *MF.getWinEHFuncInfo();
4461 int64_t MinFixedObjOffset = -SlotSize;
4462 for (int I = MFI.getObjectIndexBegin(); I < 0; ++I)
4463 MinFixedObjOffset = std::min(a: MinFixedObjOffset, b: MFI.getObjectOffset(ObjectIdx: I));
4464
4465 for (WinEHTryBlockMapEntry &TBME : EHInfo.TryBlockMap) {
4466 for (WinEHHandlerType &H : TBME.HandlerArray) {
4467 int FrameIndex = H.CatchObj.FrameIndex;
4468 if ((FrameIndex != INT_MAX) && MFI.getObjectOffset(ObjectIdx: FrameIndex) == 0) {
4469 // Ensure alignment.
4470 unsigned Align = MFI.getObjectAlign(ObjectIdx: FrameIndex).value();
4471 MinFixedObjOffset -= std::abs(i: MinFixedObjOffset) % Align;
4472 MinFixedObjOffset -= MFI.getObjectSize(ObjectIdx: FrameIndex);
4473 MFI.setObjectOffset(ObjectIdx: FrameIndex, SPOffset: MinFixedObjOffset);
4474 }
4475 }
4476 }
4477
4478 // Ensure alignment.
4479 MinFixedObjOffset -= std::abs(i: MinFixedObjOffset) % 8;
4480 int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
4481 int UnwindHelpFI =
4482 MFI.CreateFixedObject(Size: SlotSize, SPOffset: UnwindHelpOffset, /*IsImmutable=*/false);
4483 EHInfo.UnwindHelpFrameIdx = UnwindHelpFI;
4484
4485 // Store -2 into UnwindHelp on function entry. We have to scan forwards past
4486 // other frame setup instructions.
4487 MachineBasicBlock &MBB = MF.front();
4488 auto MBBI = MBB.begin();
4489 while (MBBI != MBB.end() && MBBI->getFlag(Flag: MachineInstr::FrameSetup))
4490 ++MBBI;
4491
4492 DebugLoc DL = MBB.findDebugLoc(MBBI);
4493 addFrameReference(MIB: BuildMI(BB&: MBB, I: MBBI, MIMD: DL, MCID: TII.get(Opcode: X86::MOV64mi32)),
4494 FI: UnwindHelpFI)
4495 .addImm(Val: -2);
4496}
4497
4498void X86FrameLowering::processFunctionBeforeFrameIndicesReplaced(
4499 MachineFunction &MF, RegScavenger *RS) const {
4500 auto *X86FI = MF.getInfo<X86MachineFunctionInfo>();
4501
4502 if (STI.is32Bit() && MF.hasEHFunclets())
4503 restoreWinEHStackPointersInParent(MF);
4504 // We have emitted prolog and epilog. Don't need stack pointer saving
4505 // instruction any more.
4506 if (MachineInstr *MI = X86FI->getStackPtrSaveMI()) {
4507 MI->eraseFromParent();
4508 X86FI->setStackPtrSaveMI(nullptr);
4509 }
4510}
4511
4512void X86FrameLowering::restoreWinEHStackPointersInParent(
4513 MachineFunction &MF) const {
4514 // 32-bit functions have to restore stack pointers when control is transferred
4515 // back to the parent function. These blocks are identified as eh pads that
4516 // are not funclet entries.
4517 bool IsSEH = isAsynchronousEHPersonality(
4518 Pers: classifyEHPersonality(Pers: MF.getFunction().getPersonalityFn()));
4519 for (MachineBasicBlock &MBB : MF) {
4520 bool NeedsRestore = MBB.isEHPad() && !MBB.isEHFuncletEntry();
4521 if (NeedsRestore)
4522 restoreWin32EHStackPointers(MBB, MBBI: MBB.begin(), DL: DebugLoc(),
4523 /*RestoreSP=*/IsSEH);
4524 }
4525}
4526
4527// Compute the alignment gap between current SP after spilling FP/BP and the
4528// next properly aligned stack offset.
4529static int computeFPBPAlignmentGap(MachineFunction &MF,
4530 const TargetRegisterClass *RC,
4531 unsigned NumSpilledRegs) {
4532 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
4533 unsigned AllocSize = TRI->getSpillSize(RC: *RC) * NumSpilledRegs;
4534 Align StackAlign = MF.getSubtarget().getFrameLowering()->getStackAlign();
4535 unsigned AlignedSize = alignTo(Size: AllocSize, A: StackAlign);
4536 return AlignedSize - AllocSize;
4537}
4538
4539void X86FrameLowering::spillFPBPUsingSP(MachineFunction &MF,
4540 MachineBasicBlock::iterator BeforeMI,
4541 Register FP, Register BP,
4542 int SPAdjust) const {
4543 assert(FP.isValid() || BP.isValid());
4544
4545 MachineBasicBlock *MBB = BeforeMI->getParent();
4546 DebugLoc DL = BeforeMI->getDebugLoc();
4547
4548 // Spill FP.
4549 if (FP.isValid()) {
4550 BuildMI(BB&: *MBB, I: BeforeMI, MIMD: DL,
4551 MCID: TII.get(Opcode: getPUSHOpcode(ST: MF.getSubtarget<X86Subtarget>())))
4552 .addReg(RegNo: FP);
4553 }
4554
4555 // Spill BP.
4556 if (BP.isValid()) {
4557 BuildMI(BB&: *MBB, I: BeforeMI, MIMD: DL,
4558 MCID: TII.get(Opcode: getPUSHOpcode(ST: MF.getSubtarget<X86Subtarget>())))
4559 .addReg(RegNo: BP);
4560 }
4561
4562 // Make sure SP is aligned.
4563 if (SPAdjust)
4564 emitSPUpdate(MBB&: *MBB, MBBI&: BeforeMI, DL, NumBytes: -SPAdjust, InEpilogue: false);
4565
4566 // Emit unwinding information.
4567 if (FP.isValid() && needsDwarfCFI(MF)) {
4568 // Emit .cfi_remember_state to remember old frame.
4569 unsigned CFIIndex =
4570 MF.addFrameInst(Inst: MCCFIInstruction::createRememberState(L: nullptr));
4571 BuildMI(BB&: *MBB, I: BeforeMI, MIMD: DL, MCID: TII.get(Opcode: TargetOpcode::CFI_INSTRUCTION))
4572 .addCFIIndex(CFIIndex);
4573
4574 // Setup new CFA value with DW_CFA_def_cfa_expression:
4575 // DW_OP_breg7+offset, DW_OP_deref, DW_OP_consts 16, DW_OP_plus
4576 SmallString<64> CfaExpr;
4577 uint8_t buffer[16];
4578 int Offset = SPAdjust;
4579 if (BP.isValid())
4580 Offset += TRI->getSpillSize(RC: *TRI->getMinimalPhysRegClass(Reg: BP));
4581 // If BeforeMI is a frame setup instruction, we need to adjust the position
4582 // and offset of the new cfi instruction.
4583 if (TII.isFrameSetup(I: *BeforeMI)) {
4584 Offset += alignTo(Size: TII.getFrameSize(I: *BeforeMI), A: getStackAlign());
4585 BeforeMI = std::next(x: BeforeMI);
4586 }
4587 Register StackPtr = TRI->getStackRegister();
4588 if (STI.isTarget64BitILP32())
4589 StackPtr = Register(getX86SubSuperRegister(Reg: StackPtr, Size: 64));
4590 unsigned DwarfStackPtr = TRI->getDwarfRegNum(Reg: StackPtr, isEH: true);
4591 CfaExpr.push_back(Elt: (uint8_t)(dwarf::DW_OP_breg0 + DwarfStackPtr));
4592 CfaExpr.append(in_start: buffer, in_end: buffer + encodeSLEB128(Value: Offset, p: buffer));
4593 CfaExpr.push_back(Elt: dwarf::DW_OP_deref);
4594 CfaExpr.push_back(Elt: dwarf::DW_OP_consts);
4595 CfaExpr.append(in_start: buffer, in_end: buffer + encodeSLEB128(Value: SlotSize * 2, p: buffer));
4596 CfaExpr.push_back(Elt: (uint8_t)dwarf::DW_OP_plus);
4597
4598 SmallString<64> DefCfaExpr;
4599 DefCfaExpr.push_back(Elt: dwarf::DW_CFA_def_cfa_expression);
4600 DefCfaExpr.append(in_start: buffer, in_end: buffer + encodeSLEB128(Value: CfaExpr.size(), p: buffer));
4601 DefCfaExpr.append(RHS: CfaExpr.str());
4602 BuildCFI(MBB&: *MBB, MBBI: BeforeMI, DL,
4603 CFIInst: MCCFIInstruction::createEscape(L: nullptr, Vals: DefCfaExpr.str()),
4604 Flag: MachineInstr::FrameSetup);
4605 }
4606}
4607
4608void X86FrameLowering::restoreFPBPUsingSP(MachineFunction &MF,
4609 MachineBasicBlock::iterator AfterMI,
4610 Register FP, Register BP,
4611 int SPAdjust) const {
4612 assert(FP.isValid() || BP.isValid());
4613
4614 // Adjust SP so it points to spilled FP or BP.
4615 MachineBasicBlock *MBB = AfterMI->getParent();
4616 MachineBasicBlock::iterator Pos = std::next(x: AfterMI);
4617 DebugLoc DL = AfterMI->getDebugLoc();
4618 if (SPAdjust)
4619 emitSPUpdate(MBB&: *MBB, MBBI&: Pos, DL, NumBytes: SPAdjust, InEpilogue: false);
4620
4621 // Restore BP.
4622 if (BP.isValid()) {
4623 BuildMI(BB&: *MBB, I: Pos, MIMD: DL,
4624 MCID: TII.get(Opcode: getPOPOpcode(ST: MF.getSubtarget<X86Subtarget>())), DestReg: BP);
4625 }
4626
4627 // Restore FP.
4628 if (FP.isValid()) {
4629 BuildMI(BB&: *MBB, I: Pos, MIMD: DL,
4630 MCID: TII.get(Opcode: getPOPOpcode(ST: MF.getSubtarget<X86Subtarget>())), DestReg: FP);
4631
4632 // Emit unwinding information.
4633 if (needsDwarfCFI(MF)) {
4634 // Restore original frame with .cfi_restore_state.
4635 unsigned CFIIndex =
4636 MF.addFrameInst(Inst: MCCFIInstruction::createRestoreState(L: nullptr));
4637 BuildMI(BB&: *MBB, I: Pos, MIMD: DL, MCID: TII.get(Opcode: TargetOpcode::CFI_INSTRUCTION))
4638 .addCFIIndex(CFIIndex);
4639 }
4640 }
4641}
4642
4643void X86FrameLowering::saveAndRestoreFPBPUsingSP(
4644 MachineFunction &MF, MachineBasicBlock::iterator BeforeMI,
4645 MachineBasicBlock::iterator AfterMI, bool SpillFP, bool SpillBP) const {
4646 assert(SpillFP || SpillBP);
4647
4648 Register FP, BP;
4649 const TargetRegisterClass *RC;
4650 unsigned NumRegs = 0;
4651
4652 if (SpillFP) {
4653 FP = TRI->getFrameRegister(MF);
4654 if (STI.isTarget64BitILP32())
4655 FP = Register(getX86SubSuperRegister(Reg: FP, Size: 64));
4656 RC = TRI->getMinimalPhysRegClass(Reg: FP);
4657 ++NumRegs;
4658 }
4659 if (SpillBP) {
4660 BP = TRI->getBaseRegister();
4661 if (STI.isTarget64BitILP32())
4662 BP = Register(getX86SubSuperRegister(Reg: BP, Size: 64));
4663 RC = TRI->getMinimalPhysRegClass(Reg: BP);
4664 ++NumRegs;
4665 }
4666 int SPAdjust = computeFPBPAlignmentGap(MF, RC, NumSpilledRegs: NumRegs);
4667
4668 spillFPBPUsingSP(MF, BeforeMI, FP, BP, SPAdjust);
4669 restoreFPBPUsingSP(MF, AfterMI, FP, BP, SPAdjust);
4670}
4671
4672bool X86FrameLowering::skipSpillFPBP(
4673 MachineFunction &MF, MachineBasicBlock::reverse_iterator &MI) const {
4674 if (MI->getOpcode() == X86::LCMPXCHG16B_SAVE_RBX) {
4675 // The pseudo instruction LCMPXCHG16B_SAVE_RBX is generated in the form
4676 // SaveRbx = COPY RBX
4677 // SaveRbx = LCMPXCHG16B_SAVE_RBX ..., SaveRbx, implicit-def rbx
4678 // And later LCMPXCHG16B_SAVE_RBX is expanded to restore RBX from SaveRbx.
4679 // We should skip this instruction sequence.
4680 int FI;
4681 Register Reg;
4682 while (!(MI->getOpcode() == TargetOpcode::COPY &&
4683 MI->getOperand(i: 1).getReg() == X86::RBX) &&
4684 !((Reg = TII.isStoreToStackSlot(MI: *MI, FrameIndex&: FI)) && Reg == X86::RBX))
4685 ++MI;
4686 return true;
4687 }
4688 return false;
4689}
4690
4691static bool isFPBPAccess(const MachineInstr &MI, Register FP, Register BP,
4692 const TargetRegisterInfo *TRI, bool &AccessFP,
4693 bool &AccessBP) {
4694 AccessFP = AccessBP = false;
4695 if (FP) {
4696 if (MI.findRegisterUseOperandIdx(Reg: FP, TRI, isKill: false) != -1 ||
4697 MI.findRegisterDefOperandIdx(Reg: FP, TRI, isDead: false, Overlap: true) != -1)
4698 AccessFP = true;
4699 }
4700 if (BP) {
4701 if (MI.findRegisterUseOperandIdx(Reg: BP, TRI, isKill: false) != -1 ||
4702 MI.findRegisterDefOperandIdx(Reg: BP, TRI, isDead: false, Overlap: true) != -1)
4703 AccessBP = true;
4704 }
4705 return AccessFP || AccessBP;
4706}
4707
4708// Invoke instruction has been lowered to normal function call. We try to figure
4709// out if MI comes from Invoke.
4710// Do we have any better method?
4711static bool isInvoke(const MachineInstr &MI, bool InsideEHLabels) {
4712 if (!MI.isCall())
4713 return false;
4714 if (InsideEHLabels)
4715 return true;
4716
4717 const MachineBasicBlock *MBB = MI.getParent();
4718 if (!MBB->hasEHPadSuccessor())
4719 return false;
4720
4721 // Check if there is another call instruction from MI to the end of MBB.
4722 MachineBasicBlock::const_iterator MBBI = MI, ME = MBB->end();
4723 for (++MBBI; MBBI != ME; ++MBBI)
4724 if (MBBI->isCall())
4725 return false;
4726 return true;
4727}
4728
4729/// Given the live range of FP or BP (DefMI, KillMI), check if there is any
4730/// interfered stack access in the range, usually generated by register spill.
4731void X86FrameLowering::checkInterferedAccess(
4732 MachineFunction &MF, MachineBasicBlock::reverse_iterator DefMI,
4733 MachineBasicBlock::reverse_iterator KillMI, bool SpillFP,
4734 bool SpillBP) const {
4735 if (DefMI == KillMI)
4736 return;
4737 if (TRI->hasBasePointer(MF)) {
4738 if (!SpillBP)
4739 return;
4740 } else {
4741 if (!SpillFP)
4742 return;
4743 }
4744
4745 auto MI = KillMI;
4746 while (MI != DefMI) {
4747 if (any_of(Range: MI->operands(),
4748 P: [](const MachineOperand &MO) { return MO.isFI(); }))
4749 MF.getContext().reportError(L: SMLoc(),
4750 Msg: "Interference usage of base pointer/frame "
4751 "pointer.");
4752 MI++;
4753 }
4754}
4755
4756/// If a function uses base pointer and the base pointer is clobbered by inline
4757/// asm, RA doesn't detect this case, and after the inline asm, the base pointer
4758/// contains garbage value.
4759/// For example if a 32b x86 function uses base pointer esi, and esi is
4760/// clobbered by following inline asm
4761/// asm("rep movsb" : "+D"(ptr), "+S"(x), "+c"(c)::"memory");
4762/// We need to save esi before the asm and restore it after the asm.
4763///
4764/// The problem can also occur to frame pointer if there is a function call, and
4765/// the callee uses a different calling convention and clobbers the fp.
4766///
4767/// Because normal frame objects (spill slots) are accessed through fp/bp
4768/// register, so we can't spill fp/bp to normal spill slots.
4769///
4770/// FIXME: There are 2 possible enhancements:
4771/// 1. In many cases there are different physical registers not clobbered by
4772/// inline asm, we can use one of them as base pointer. Or use a virtual
4773/// register as base pointer and let RA allocate a physical register to it.
4774/// 2. If there is no other instructions access stack with fp/bp from the
4775/// inline asm to the epilog, and no cfi requirement for a correct fp, we can
4776/// skip the save and restore operations.
4777void X86FrameLowering::spillFPBP(MachineFunction &MF) const {
4778 Register FP, BP;
4779 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
4780 if (TFI.hasFP(MF))
4781 FP = TRI->getFrameRegister(MF);
4782 if (TRI->hasBasePointer(MF))
4783 BP = TRI->getBaseRegister();
4784
4785 // Currently only inline asm and function call can clobbers fp/bp. So we can
4786 // do some quick test and return early.
4787 if (!MF.hasInlineAsm()) {
4788 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
4789 if (!X86FI->getFPClobberedByCall())
4790 FP = 0;
4791 if (!X86FI->getBPClobberedByCall())
4792 BP = 0;
4793 }
4794 if (!FP && !BP)
4795 return;
4796
4797 for (MachineBasicBlock &MBB : MF) {
4798 bool InsideEHLabels = false;
4799 auto MI = MBB.rbegin(), ME = MBB.rend();
4800 auto TermMI = MBB.getFirstTerminator();
4801 if (TermMI == MBB.begin())
4802 continue;
4803 MI = *(std::prev(x: TermMI));
4804
4805 while (MI != ME) {
4806 // Skip frame setup/destroy instructions.
4807 // Skip Invoke (call inside try block) instructions.
4808 // Skip instructions handled by target.
4809 if (MI->getFlag(Flag: MachineInstr::MIFlag::FrameSetup) ||
4810 MI->getFlag(Flag: MachineInstr::MIFlag::FrameDestroy) ||
4811 isInvoke(MI: *MI, InsideEHLabels) || skipSpillFPBP(MF, MI)) {
4812 ++MI;
4813 continue;
4814 }
4815
4816 if (MI->getOpcode() == TargetOpcode::EH_LABEL) {
4817 InsideEHLabels = !InsideEHLabels;
4818 ++MI;
4819 continue;
4820 }
4821
4822 bool AccessFP, AccessBP;
4823 // Check if fp or bp is used in MI.
4824 if (!isFPBPAccess(MI: *MI, FP, BP, TRI, AccessFP, AccessBP)) {
4825 ++MI;
4826 continue;
4827 }
4828
4829 // Look for the range [DefMI, KillMI] in which fp or bp is defined and
4830 // used.
4831 bool FPLive = false, BPLive = false;
4832 bool SpillFP = false, SpillBP = false;
4833 auto DefMI = MI, KillMI = MI;
4834 do {
4835 SpillFP |= AccessFP;
4836 SpillBP |= AccessBP;
4837
4838 // Maintain FPLive and BPLive.
4839 if (FPLive && MI->findRegisterDefOperandIdx(Reg: FP, TRI, isDead: false, Overlap: true) != -1)
4840 FPLive = false;
4841 if (FP && MI->findRegisterUseOperandIdx(Reg: FP, TRI, isKill: false) != -1)
4842 FPLive = true;
4843 if (BPLive && MI->findRegisterDefOperandIdx(Reg: BP, TRI, isDead: false, Overlap: true) != -1)
4844 BPLive = false;
4845 if (BP && MI->findRegisterUseOperandIdx(Reg: BP, TRI, isKill: false) != -1)
4846 BPLive = true;
4847
4848 DefMI = MI++;
4849 } while ((MI != ME) &&
4850 (FPLive || BPLive ||
4851 isFPBPAccess(MI: *MI, FP, BP, TRI, AccessFP, AccessBP)));
4852
4853 // Don't need to save/restore if FP is accessed through llvm.frameaddress.
4854 if (FPLive && !SpillBP)
4855 continue;
4856
4857 // If the bp is clobbered by a call, we should save and restore outside of
4858 // the frame setup instructions.
4859 if (KillMI->isCall() && DefMI != ME) {
4860 auto FrameSetup = std::next(x: DefMI);
4861 // Look for frame setup instruction toward the start of the BB.
4862 // If we reach another call instruction, it means no frame setup
4863 // instruction for the current call instruction.
4864 while (FrameSetup != ME && !TII.isFrameSetup(I: *FrameSetup) &&
4865 !FrameSetup->isCall())
4866 ++FrameSetup;
4867 // If a frame setup instruction is found, we need to find out the
4868 // corresponding frame destroy instruction.
4869 if (FrameSetup != ME && TII.isFrameSetup(I: *FrameSetup) &&
4870 (TII.getFrameSize(I: *FrameSetup) ||
4871 TII.getFrameAdjustment(I: *FrameSetup))) {
4872 while (!TII.isFrameInstr(I: *KillMI))
4873 --KillMI;
4874 DefMI = FrameSetup;
4875 MI = DefMI;
4876 ++MI;
4877 }
4878 }
4879
4880 checkInterferedAccess(MF, DefMI, KillMI, SpillFP, SpillBP);
4881
4882 // Call target function to spill and restore FP and BP registers.
4883 saveAndRestoreFPBPUsingSP(MF, BeforeMI: &(*DefMI), AfterMI: &(*KillMI), SpillFP, SpillBP);
4884 }
4885 }
4886}
4887