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