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