blob: 248f6eca4c4f5465436f33d22e31d02c578058d1 [file] [log] [blame]
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001//===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the X86 implementation of TargetFrameLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "X86FrameLowering.h"
15#include "X86InstrBuilder.h"
16#include "X86InstrInfo.h"
17#include "X86MachineFunctionInfo.h"
18#include "X86Subtarget.h"
19#include "X86TargetMachine.h"
20#include "llvm/ADT/SmallSet.h"
21#include "llvm/CodeGen/MachineFrameInfo.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachineModuleInfo.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/MC/MCAsmInfo.h"
29#include "llvm/MC/MCSymbol.h"
30#include "llvm/Support/CommandLine.h"
31#include "llvm/Target/TargetOptions.h"
32#include "llvm/Support/Debug.h"
33#include <cstdlib>
34
35using namespace llvm;
36
37// FIXME: completely move here.
38extern cl::opt<bool> ForceStackAlign;
39
40bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Michael Kuperstein13fbd452015-02-01 16:56:04 +000041 return !MF.getFrameInfo()->hasVarSizedObjects() &&
42 !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
43}
44
45/// canSimplifyCallFramePseudos - If there is a reserved call frame, the
46/// call frame pseudos can be simplified. Having a FP, as in the default
47/// implementation, is not sufficient here since we can't always use it.
48/// Use a more nuanced condition.
49bool
50X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
Reid Kleckner09543c22015-06-17 21:35:02 +000051 const X86RegisterInfo *TRI = static_cast<const X86RegisterInfo *>
52 (MF.getSubtarget().getRegisterInfo());
Michael Kuperstein13fbd452015-02-01 16:56:04 +000053 return hasReservedCallFrame(MF) ||
Reid Kleckner09543c22015-06-17 21:35:02 +000054 (hasFP(MF) && !TRI->needsStackRealignment(MF))
55 || TRI->hasBasePointer(MF);
Michael Kuperstein13fbd452015-02-01 16:56:04 +000056}
57
58// needsFrameIndexResolution - Do we need to perform FI resolution for
59// this function. Normally, this is required only when the function
60// has any stack objects. However, FI resolution actually has another job,
61// not apparent from the title - it resolves callframesetup/destroy
62// that were not simplified earlier.
63// So, this is required for x86 functions that have push sequences even
64// when there are no stack objects.
65bool
66X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
67 return MF.getFrameInfo()->hasStackObjects() ||
68 MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000069}
70
71/// hasFP - Return true if the specified function should have a dedicated frame
72/// pointer register. This is true if the function has variable sized allocas
73/// or if frame pointer elimination is disabled.
74bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
75 const MachineFrameInfo *MFI = MF.getFrameInfo();
76 const MachineModuleInfo &MMI = MF.getMMI();
Reid Kleckner09543c22015-06-17 21:35:02 +000077 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +000078
79 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
80 RegInfo->needsStackRealignment(MF) ||
81 MFI->hasVarSizedObjects() ||
82 MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
83 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
84 MMI.callsUnwindInit() || MMI.callsEHReturn() ||
85 MFI->hasStackMap() || MFI->hasPatchPoint());
86}
87
88static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
89 if (IsLP64) {
90 if (isInt<8>(Imm))
91 return X86::SUB64ri8;
92 return X86::SUB64ri32;
93 } else {
94 if (isInt<8>(Imm))
95 return X86::SUB32ri8;
96 return X86::SUB32ri;
97 }
98}
99
100static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
101 if (IsLP64) {
102 if (isInt<8>(Imm))
103 return X86::ADD64ri8;
104 return X86::ADD64ri32;
105 } else {
106 if (isInt<8>(Imm))
107 return X86::ADD32ri8;
108 return X86::ADD32ri;
109 }
110}
111
112static unsigned getSUBrrOpcode(unsigned isLP64) {
113 return isLP64 ? X86::SUB64rr : X86::SUB32rr;
114}
115
116static unsigned getADDrrOpcode(unsigned isLP64) {
117 return isLP64 ? X86::ADD64rr : X86::ADD32rr;
118}
119
120static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
121 if (IsLP64) {
122 if (isInt<8>(Imm))
123 return X86::AND64ri8;
124 return X86::AND64ri32;
125 }
126 if (isInt<8>(Imm))
127 return X86::AND32ri8;
128 return X86::AND32ri;
129}
130
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000131static unsigned getLEArOpcode(unsigned IsLP64) {
132 return IsLP64 ? X86::LEA64r : X86::LEA32r;
133}
134
135/// findDeadCallerSavedReg - Return a caller-saved register that isn't live
136/// when it reaches the "return" instruction. We can then pop a stack object
137/// to this register without worry about clobbering it.
138static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
139 MachineBasicBlock::iterator &MBBI,
140 const TargetRegisterInfo &TRI,
141 bool Is64Bit) {
142 const MachineFunction *MF = MBB.getParent();
143 const Function *F = MF->getFunction();
144 if (!F || MF->getMMI().callsEHReturn())
145 return 0;
146
147 static const uint16_t CallerSavedRegs32Bit[] = {
148 X86::EAX, X86::EDX, X86::ECX, 0
149 };
150
151 static const uint16_t CallerSavedRegs64Bit[] = {
152 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
153 X86::R8, X86::R9, X86::R10, X86::R11, 0
154 };
155
156 unsigned Opc = MBBI->getOpcode();
157 switch (Opc) {
158 default: return 0;
159 case X86::RETL:
160 case X86::RETQ:
161 case X86::RETIL:
162 case X86::RETIQ:
163 case X86::TCRETURNdi:
164 case X86::TCRETURNri:
165 case X86::TCRETURNmi:
166 case X86::TCRETURNdi64:
167 case X86::TCRETURNri64:
168 case X86::TCRETURNmi64:
169 case X86::EH_RETURN:
170 case X86::EH_RETURN64: {
171 SmallSet<uint16_t, 8> Uses;
172 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
173 MachineOperand &MO = MBBI->getOperand(i);
174 if (!MO.isReg() || MO.isDef())
175 continue;
176 unsigned Reg = MO.getReg();
177 if (!Reg)
178 continue;
179 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
180 Uses.insert(*AI);
181 }
182
183 const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
184 for (; *CS; ++CS)
185 if (!Uses.count(*CS))
186 return *CS;
187 }
188 }
189
190 return 0;
191}
192
193static bool isEAXLiveIn(MachineFunction &MF) {
194 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
195 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
196 unsigned Reg = II->first;
197
198 if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
199 Reg == X86::AH || Reg == X86::AL)
200 return true;
201 }
202
203 return false;
204}
205
206/// emitSPUpdate - Emit a series of instructions to increment / decrement the
207/// stack pointer by a constant value.
Quentin Colombet494eb602015-05-22 18:10:47 +0000208void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
209 MachineBasicBlock::iterator &MBBI,
210 unsigned StackPtr, int64_t NumBytes,
211 bool Is64BitTarget, bool Is64BitStackPtr,
212 bool UseLEA, const TargetInstrInfo &TII,
Reid Kleckner09543c22015-06-17 21:35:02 +0000213 const TargetRegisterInfo &TRI) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000214 bool isSub = NumBytes < 0;
215 uint64_t Offset = isSub ? -NumBytes : NumBytes;
216 unsigned Opc;
217 if (UseLEA)
218 Opc = getLEArOpcode(Is64BitStackPtr);
219 else
220 Opc = isSub
221 ? getSUBriOpcode(Is64BitStackPtr, Offset)
222 : getADDriOpcode(Is64BitStackPtr, Offset);
223
224 uint64_t Chunk = (1LL << 31) - 1;
225 DebugLoc DL = MBB.findDebugLoc(MBBI);
226
227 while (Offset) {
228 if (Offset > Chunk) {
229 // Rather than emit a long series of instructions for large offsets,
230 // load the offset into a register and do one sub/add
231 unsigned Reg = 0;
232
233 if (isSub && !isEAXLiveIn(*MBB.getParent()))
234 Reg = (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX);
235 else
236 Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
237
238 if (Reg) {
239 Opc = Is64BitTarget ? X86::MOV64ri : X86::MOV32ri;
240 BuildMI(MBB, MBBI, DL, TII.get(Opc), Reg)
241 .addImm(Offset);
242 Opc = isSub
243 ? getSUBrrOpcode(Is64BitTarget)
244 : getADDrrOpcode(Is64BitTarget);
245 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
246 .addReg(StackPtr)
247 .addReg(Reg);
248 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
249 Offset = 0;
250 continue;
251 }
252 }
253
David Majnemer3aa0bd82015-02-24 00:11:32 +0000254 uint64_t ThisVal = std::min(Offset, Chunk);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000255 if (ThisVal == (Is64BitTarget ? 8 : 4)) {
256 // Use push / pop instead.
257 unsigned Reg = isSub
258 ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
259 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
260 if (Reg) {
261 Opc = isSub
262 ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
263 : (Is64BitTarget ? X86::POP64r : X86::POP32r);
264 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
265 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
266 if (isSub)
267 MI->setFlag(MachineInstr::FrameSetup);
268 Offset -= ThisVal;
269 continue;
270 }
271 }
272
273 MachineInstr *MI = nullptr;
274
275 if (UseLEA) {
276 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
277 StackPtr, false, isSub ? -ThisVal : ThisVal);
278 } else {
279 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
280 .addReg(StackPtr)
281 .addImm(ThisVal);
282 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
283 }
284
285 if (isSub)
286 MI->setFlag(MachineInstr::FrameSetup);
287
288 Offset -= ThisVal;
289 }
290}
291
292/// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
293static
294void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
295 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
296 if (MBBI == MBB.begin()) return;
297
298 MachineBasicBlock::iterator PI = std::prev(MBBI);
299 unsigned Opc = PI->getOpcode();
300 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
301 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
302 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
303 PI->getOperand(0).getReg() == StackPtr) {
304 if (NumBytes)
305 *NumBytes += PI->getOperand(2).getImm();
306 MBB.erase(PI);
307 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
308 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
309 PI->getOperand(0).getReg() == StackPtr) {
310 if (NumBytes)
311 *NumBytes -= PI->getOperand(2).getImm();
312 MBB.erase(PI);
313 }
314}
315
Quentin Colombet494eb602015-05-22 18:10:47 +0000316int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
317 MachineBasicBlock::iterator &MBBI,
318 unsigned StackPtr,
Reid Kleckner09543c22015-06-17 21:35:02 +0000319 bool doMergeWithPrevious) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000320 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
321 (!doMergeWithPrevious && MBBI == MBB.end()))
322 return 0;
323
324 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
325 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
326 : std::next(MBBI);
327 unsigned Opc = PI->getOpcode();
328 int Offset = 0;
329
330 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
331 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
332 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
333 PI->getOperand(0).getReg() == StackPtr){
334 Offset += PI->getOperand(2).getImm();
335 MBB.erase(PI);
336 if (!doMergeWithPrevious) MBBI = NI;
337 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
338 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
339 PI->getOperand(0).getReg() == StackPtr) {
340 Offset -= PI->getOperand(2).getImm();
341 MBB.erase(PI);
342 if (!doMergeWithPrevious) MBBI = NI;
343 }
344
345 return Offset;
346}
347
Reid Kleckner7f189f82015-06-15 23:45:08 +0000348/// Wraps up getting a CFI index and building a MachineInstr for it.
349static void BuildCFI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
350 DebugLoc DL, const TargetInstrInfo &TII,
351 MCCFIInstruction CFIInst) {
352 MachineFunction &MF = *MBB.getParent();
353 unsigned CFIIndex = MF.getMMI().addFrameInst(CFIInst);
354 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
355 .addCFIIndex(CFIIndex);
356}
357
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000358void
359X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
360 MachineBasicBlock::iterator MBBI,
361 DebugLoc DL) const {
362 MachineFunction &MF = *MBB.getParent();
363 MachineFrameInfo *MFI = MF.getFrameInfo();
364 MachineModuleInfo &MMI = MF.getMMI();
365 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
Reid Kleckner09543c22015-06-17 21:35:02 +0000366 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000367
368 // Add callee saved registers to move list.
369 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
370 if (CSI.empty()) return;
371
372 // Calculate offsets.
373 for (std::vector<CalleeSavedInfo>::const_iterator
374 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
375 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
376 unsigned Reg = I->getReg();
377
378 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Reid Kleckner7f189f82015-06-15 23:45:08 +0000379 BuildCFI(MBB, MBBI, DL, TII,
380 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000381 }
382}
383
384/// usesTheStack - This function checks if any of the users of EFLAGS
385/// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
386/// to use the stack, and if we don't adjust the stack we clobber the first
387/// frame index.
388/// See X86InstrInfo::copyPhysReg.
389static bool usesTheStack(const MachineFunction &MF) {
390 const MachineRegisterInfo &MRI = MF.getRegInfo();
391
392 for (MachineRegisterInfo::reg_instr_iterator
393 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
394 ri != re; ++ri)
395 if (ri->isCopy())
396 return true;
397
398 return false;
399}
400
401void X86FrameLowering::emitStackProbeCall(MachineFunction &MF,
402 MachineBasicBlock &MBB,
403 MachineBasicBlock::iterator MBBI,
Reid Kleckner09543c22015-06-17 21:35:02 +0000404 DebugLoc DL) {
405 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
406 const TargetInstrInfo &TII = *STI.getInstrInfo();
407 bool Is64Bit = STI.is64Bit();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000408 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
409
410 unsigned CallOp;
411 if (Is64Bit)
412 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
413 else
414 CallOp = X86::CALLpcrel32;
415
416 const char *Symbol;
417 if (Is64Bit) {
418 if (STI.isTargetCygMing()) {
419 Symbol = "___chkstk_ms";
420 } else {
421 Symbol = "__chkstk";
422 }
423 } else if (STI.isTargetCygMing())
424 Symbol = "_alloca";
425 else
426 Symbol = "_chkstk";
427
428 MachineInstrBuilder CI;
429
430 // All current stack probes take AX and SP as input, clobber flags, and
431 // preserve all registers. x86_64 probes leave RSP unmodified.
432 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
433 // For the large code model, we have to call through a register. Use R11,
434 // as it is scratch in all supported calling conventions.
435 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
436 .addExternalSymbol(Symbol);
437 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
438 } else {
439 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addExternalSymbol(Symbol);
440 }
441
442 unsigned AX = Is64Bit ? X86::RAX : X86::EAX;
443 unsigned SP = Is64Bit ? X86::RSP : X86::ESP;
444 CI.addReg(AX, RegState::Implicit)
445 .addReg(SP, RegState::Implicit)
446 .addReg(AX, RegState::Define | RegState::Implicit)
447 .addReg(SP, RegState::Define | RegState::Implicit)
448 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
449
450 if (Is64Bit) {
451 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
452 // themselves. It also does not clobber %rax so we can reuse it when
453 // adjusting %rsp.
454 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
455 .addReg(X86::RSP)
456 .addReg(X86::RAX);
457 }
458}
459
David Majnemer93c22a42015-02-10 00:57:42 +0000460static unsigned calculateSetFPREG(uint64_t SPAdjust) {
461 // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
462 // and might require smaller successive adjustments.
463 const uint64_t Win64MaxSEHOffset = 128;
464 uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
465 // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
David Majnemer89d05642015-02-21 01:04:47 +0000466 return SEHFrameOffset & -16;
David Majnemer93c22a42015-02-10 00:57:42 +0000467}
468
469// If we're forcing a stack realignment we can't rely on just the frame
470// info, we need to know the ABI stack alignment as well in case we
471// have a call out. Otherwise just make sure we have some alignment - we'll
472// go with the minimum SlotSize.
Reid Kleckner09543c22015-06-17 21:35:02 +0000473static uint64_t calculateMaxStackAlign(const MachineFunction &MF) {
David Majnemer93c22a42015-02-10 00:57:42 +0000474 const MachineFrameInfo *MFI = MF.getFrameInfo();
475 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
Reid Kleckner09543c22015-06-17 21:35:02 +0000476 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
477 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
478 unsigned SlotSize = RegInfo->getSlotSize();
479 unsigned StackAlign = STI.getFrameLowering()->getStackAlignment();
David Majnemer93c22a42015-02-10 00:57:42 +0000480 if (ForceStackAlign) {
481 if (MFI->hasCalls())
482 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
483 else if (MaxAlign < SlotSize)
484 MaxAlign = SlotSize;
485 }
486 return MaxAlign;
487}
488
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000489/// emitPrologue - Push callee-saved registers onto the stack, which
490/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
491/// space for local variables. Also emit labels used by the exception handler to
492/// generate the exception handling frames.
493
494/*
495 Here's a gist of what gets emitted:
496
497 ; Establish frame pointer, if needed
498 [if needs FP]
499 push %rbp
500 .cfi_def_cfa_offset 16
501 .cfi_offset %rbp, -16
502 .seh_pushreg %rpb
503 mov %rsp, %rbp
504 .cfi_def_cfa_register %rbp
505
506 ; Spill general-purpose registers
507 [for all callee-saved GPRs]
508 pushq %<reg>
509 [if not needs FP]
510 .cfi_def_cfa_offset (offset from RETADDR)
511 .seh_pushreg %<reg>
512
513 ; If the required stack alignment > default stack alignment
514 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
515 ; of unknown size in the stack frame.
516 [if stack needs re-alignment]
517 and $MASK, %rsp
518
519 ; Allocate space for locals
520 [if target is Windows and allocated space > 4096 bytes]
521 ; Windows needs special care for allocations larger
522 ; than one page.
523 mov $NNN, %rax
524 call ___chkstk_ms/___chkstk
525 sub %rax, %rsp
526 [else]
527 sub $NNN, %rsp
528
529 [if needs FP]
530 .seh_stackalloc (size of XMM spill slots)
531 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
532 [else]
533 .seh_stackalloc NNN
534
535 ; Spill XMMs
536 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
537 ; they may get spilled on any platform, if the current function
538 ; calls @llvm.eh.unwind.init
539 [if needs FP]
540 [for all callee-saved XMM registers]
541 movaps %<xmm reg>, -MMM(%rbp)
542 [for all callee-saved XMM registers]
543 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
544 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
545 [else]
546 [for all callee-saved XMM registers]
547 movaps %<xmm reg>, KKK(%rsp)
548 [for all callee-saved XMM registers]
549 .seh_savexmm %<xmm reg>, KKK
550
551 .seh_endprologue
552
553 [if needs base pointer]
554 mov %rsp, %rbx
555 [if needs to restore base pointer]
556 mov %rsp, -MMM(%rbp)
557
558 ; Emit CFI info
559 [if needs FP]
560 [for all callee-saved registers]
561 .cfi_offset %<reg>, (offset from %rbp)
562 [else]
563 .cfi_def_cfa_offset (offset from RETADDR)
564 [for all callee-saved registers]
565 .cfi_offset %<reg>, (offset from %rsp)
566
567 Notes:
568 - .seh directives are emitted only for Windows 64 ABI
569 - .cfi directives are emitted for all other ABIs
570 - for 32-bit code, substitute %e?? registers for %r??
571*/
572
Quentin Colombet61b305e2015-05-05 17:38:16 +0000573void X86FrameLowering::emitPrologue(MachineFunction &MF,
574 MachineBasicBlock &MBB) const {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000575 MachineBasicBlock::iterator MBBI = MBB.begin();
576 MachineFrameInfo *MFI = MF.getFrameInfo();
577 const Function *Fn = MF.getFunction();
Reid Kleckner09543c22015-06-17 21:35:02 +0000578 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
579 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
580 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000581 MachineModuleInfo &MMI = MF.getMMI();
582 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
David Majnemer93c22a42015-02-10 00:57:42 +0000583 uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000584 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
585 bool HasFP = hasFP(MF);
Reid Kleckner09543c22015-06-17 21:35:02 +0000586 bool Is64Bit = STI.is64Bit();
587 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
588 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000589 bool IsWin64CC = STI.isCallingConvWin64(Fn->getCallingConv());
Reid Kleckner09543c22015-06-17 21:35:02 +0000590 // Not necessarily synonymous with IsWin64CC.
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000591 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
592 bool NeedsWinCFI = IsWin64Prologue && Fn->needsUnwindTableEntry();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000593 bool NeedsDwarfCFI =
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000594 !IsWin64Prologue && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000595 bool UseLEA = STI.useLeaForSP();
Reid Kleckner09543c22015-06-17 21:35:02 +0000596 unsigned SlotSize = RegInfo->getSlotSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000597 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Eric Christopher05b81972015-02-02 17:38:43 +0000598 const unsigned MachineFramePtr =
599 STI.isTarget64BitILP32()
600 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
601 : FramePtr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000602 unsigned StackPtr = RegInfo->getStackRegister();
603 unsigned BasePtr = RegInfo->getBaseRegister();
604 DebugLoc DL;
605
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000606 // Add RETADDR move area to callee saved frame size.
607 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000608 if (TailCallReturnAddrDelta && IsWin64Prologue)
David Majnemer93c22a42015-02-10 00:57:42 +0000609 report_fatal_error("Can't handle guaranteed tail call under win64 yet");
610
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000611 if (TailCallReturnAddrDelta < 0)
612 X86FI->setCalleeSavedFrameSize(
613 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
614
615 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
616
617 // The default stack probe size is 4096 if the function has no stackprobesize
618 // attribute.
619 unsigned StackProbeSize = 4096;
620 if (Fn->hasFnAttribute("stack-probe-size"))
621 Fn->getFnAttribute("stack-probe-size")
622 .getValueAsString()
623 .getAsInteger(0, StackProbeSize);
624
625 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
626 // function, and use up to 128 bytes of stack space, don't have a frame
627 // pointer, calls, or dynamic alloca then we do not need to adjust the
628 // stack pointer (we fit in the Red Zone). We also check that we don't
629 // push and pop from the stack.
Duncan P. N. Exon Smith5975a702015-02-14 01:59:52 +0000630 if (Is64Bit && !Fn->hasFnAttribute(Attribute::NoRedZone) &&
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000631 !RegInfo->needsStackRealignment(MF) &&
Duncan P. N. Exon Smith5975a702015-02-14 01:59:52 +0000632 !MFI->hasVarSizedObjects() && // No dynamic alloca.
633 !MFI->adjustsStack() && // No calls.
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000634 !IsWin64CC && // Win64 has no Red Zone
Duncan P. N. Exon Smith5975a702015-02-14 01:59:52 +0000635 !usesTheStack(MF) && // Don't push and pop.
636 !MF.shouldSplitStack()) { // Regular stack
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000637 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
638 if (HasFP) MinSize += SlotSize;
639 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
640 MFI->setStackSize(StackSize);
641 }
642
643 // Insert stack pointer adjustment for later moving of return addr. Only
644 // applies to tail call optimized functions where the callee argument stack
645 // size is bigger than the callers.
646 if (TailCallReturnAddrDelta < 0) {
647 MachineInstr *MI =
648 BuildMI(MBB, MBBI, DL,
649 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
650 StackPtr)
651 .addReg(StackPtr)
652 .addImm(-TailCallReturnAddrDelta)
653 .setMIFlag(MachineInstr::FrameSetup);
654 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
655 }
656
657 // Mapping for machine moves:
658 //
659 // DST: VirtualFP AND
660 // SRC: VirtualFP => DW_CFA_def_cfa_offset
661 // ELSE => DW_CFA_def_cfa
662 //
663 // SRC: VirtualFP AND
664 // DST: Register => DW_CFA_def_cfa_register
665 //
666 // ELSE
667 // OFFSET < 0 => DW_CFA_offset_extended_sf
668 // REG < 64 => DW_CFA_offset + Reg
669 // ELSE => DW_CFA_offset_extended
670
671 uint64_t NumBytes = 0;
672 int stackGrowth = -SlotSize;
673
674 if (HasFP) {
675 // Calculate required stack adjustment.
676 uint64_t FrameSize = StackSize - SlotSize;
677 // If required, include space for extra hidden slot for stashing base pointer.
678 if (X86FI->getRestoreBasePointer())
679 FrameSize += SlotSize;
David Majnemer89d05642015-02-21 01:04:47 +0000680
681 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
682
683 // Callee-saved registers are pushed on stack before the stack is realigned.
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000684 if (RegInfo->needsStackRealignment(MF) && !IsWin64Prologue)
David Majnemer89d05642015-02-21 01:04:47 +0000685 NumBytes = RoundUpToAlignment(NumBytes, MaxAlign);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000686
687 // Get the offset of the stack slot for the EBP register, which is
688 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
689 // Update the frame offset adjustment.
690 MFI->setOffsetAdjustment(-NumBytes);
691
692 // Save EBP/RBP into the appropriate stack slot.
693 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
694 .addReg(MachineFramePtr, RegState::Kill)
695 .setMIFlag(MachineInstr::FrameSetup);
696
697 if (NeedsDwarfCFI) {
698 // Mark the place where EBP/RBP was saved.
699 // Define the current CFA rule to use the provided offset.
700 assert(StackSize);
Reid Kleckner7f189f82015-06-15 23:45:08 +0000701 BuildCFI(MBB, MBBI, DL, TII,
702 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000703
704 // Change the rule for the FramePtr to be an "offset" rule.
705 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
Reid Kleckner7f189f82015-06-15 23:45:08 +0000706 BuildCFI(MBB, MBBI, DL, TII,
707 MCCFIInstruction::createOffset(nullptr, DwarfFramePtr,
708 2 * stackGrowth));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000709 }
710
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000711 if (NeedsWinCFI) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000712 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
713 .addImm(FramePtr)
714 .setMIFlag(MachineInstr::FrameSetup);
715 }
716
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000717 if (!IsWin64Prologue) {
David Majnemer93c22a42015-02-10 00:57:42 +0000718 // Update EBP with the new base value.
719 BuildMI(MBB, MBBI, DL,
720 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
721 FramePtr)
722 .addReg(StackPtr)
723 .setMIFlag(MachineInstr::FrameSetup);
724 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000725
726 if (NeedsDwarfCFI) {
727 // Mark effective beginning of when frame pointer becomes valid.
728 // Define the current CFA to use the EBP/RBP register.
729 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
Reid Kleckner7f189f82015-06-15 23:45:08 +0000730 BuildCFI(MBB, MBBI, DL, TII,
731 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000732 }
733
734 // Mark the FramePtr as live-in in every block.
735 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
736 I->addLiveIn(MachineFramePtr);
737 } else {
738 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
739 }
740
741 // Skip the callee-saved push instructions.
742 bool PushedRegs = false;
743 int StackOffset = 2 * stackGrowth;
744
745 while (MBBI != MBB.end() &&
746 (MBBI->getOpcode() == X86::PUSH32r ||
747 MBBI->getOpcode() == X86::PUSH64r)) {
748 PushedRegs = true;
749 unsigned Reg = MBBI->getOperand(0).getReg();
750 ++MBBI;
751
752 if (!HasFP && NeedsDwarfCFI) {
753 // Mark callee-saved push instruction.
754 // Define the current CFA rule to use the provided offset.
755 assert(StackSize);
Reid Kleckner7f189f82015-06-15 23:45:08 +0000756 BuildCFI(MBB, MBBI, DL, TII,
757 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000758 StackOffset += stackGrowth;
759 }
760
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000761 if (NeedsWinCFI) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000762 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
763 MachineInstr::FrameSetup);
764 }
765 }
766
767 // Realign stack after we pushed callee-saved registers (so that we'll be
768 // able to calculate their offsets from the frame pointer).
David Majnemer93c22a42015-02-10 00:57:42 +0000769 // Don't do this for Win64, it needs to realign the stack after the prologue.
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000770 if (!IsWin64Prologue && RegInfo->needsStackRealignment(MF)) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000771 assert(HasFP && "There should be a frame pointer if stack is realigned.");
772 uint64_t Val = -MaxAlign;
773 MachineInstr *MI =
David Majnemer93c22a42015-02-10 00:57:42 +0000774 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
775 StackPtr)
776 .addReg(StackPtr)
777 .addImm(Val)
778 .setMIFlag(MachineInstr::FrameSetup);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000779
780 // The EFLAGS implicit def is dead.
781 MI->getOperand(3).setIsDead();
782 }
783
784 // If there is an SUB32ri of ESP immediately before this instruction, merge
785 // the two. This can be the case when tail call elimination is enabled and
786 // the callee has more arguments then the caller.
787 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
788
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000789 // Adjust stack pointer: ESP -= numbytes.
790
791 // Windows and cygwin/mingw require a prologue helper routine when allocating
792 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
793 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
794 // stack and adjust the stack pointer in one go. The 64-bit version of
795 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
796 // responsible for adjusting the stack pointer. Touching the stack at 4K
797 // increments is necessary to ensure that the guard pages used by the OS
798 // virtual memory manager are allocated in correct sequence.
David Majnemer89d05642015-02-21 01:04:47 +0000799 uint64_t AlignedNumBytes = NumBytes;
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000800 if (IsWin64Prologue && RegInfo->needsStackRealignment(MF))
David Majnemer89d05642015-02-21 01:04:47 +0000801 AlignedNumBytes = RoundUpToAlignment(AlignedNumBytes, MaxAlign);
802 if (AlignedNumBytes >= StackProbeSize && UseStackProbe) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000803 // Check whether EAX is livein for this function.
804 bool isEAXAlive = isEAXLiveIn(MF);
805
806 if (isEAXAlive) {
807 // Sanity check that EAX is not livein for this function.
808 // It should not be, so throw an assert.
809 assert(!Is64Bit && "EAX is livein in x64 case!");
810
811 // Save EAX
812 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
813 .addReg(X86::EAX, RegState::Kill)
814 .setMIFlag(MachineInstr::FrameSetup);
815 }
816
817 if (Is64Bit) {
818 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
819 // Function prologue is responsible for adjusting the stack pointer.
David Majnemer006c4902015-02-23 21:50:30 +0000820 if (isUInt<32>(NumBytes)) {
821 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
822 .addImm(NumBytes)
823 .setMIFlag(MachineInstr::FrameSetup);
824 } else if (isInt<32>(NumBytes)) {
825 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
826 .addImm(NumBytes)
827 .setMIFlag(MachineInstr::FrameSetup);
828 } else {
829 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
830 .addImm(NumBytes)
831 .setMIFlag(MachineInstr::FrameSetup);
832 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000833 } else {
834 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
835 // We'll also use 4 already allocated bytes for EAX.
836 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
837 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
838 .setMIFlag(MachineInstr::FrameSetup);
839 }
840
841 // Save a pointer to the MI where we set AX.
842 MachineBasicBlock::iterator SetRAX = MBBI;
843 --SetRAX;
844
845 // Call __chkstk, __chkstk_ms, or __alloca.
846 emitStackProbeCall(MF, MBB, MBBI, DL);
847
848 // Apply the frame setup flag to all inserted instrs.
849 for (; SetRAX != MBBI; ++SetRAX)
850 SetRAX->setFlag(MachineInstr::FrameSetup);
851
852 if (isEAXAlive) {
853 // Restore EAX
854 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
855 X86::EAX),
856 StackPtr, false, NumBytes - 4);
857 MI->setFlag(MachineInstr::FrameSetup);
858 MBB.insert(MBBI, MI);
859 }
860 } else if (NumBytes) {
861 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
862 UseLEA, TII, *RegInfo);
863 }
864
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000865 if (NeedsWinCFI && NumBytes)
David Majnemer93c22a42015-02-10 00:57:42 +0000866 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
867 .addImm(NumBytes)
868 .setMIFlag(MachineInstr::FrameSetup);
869
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000870 int SEHFrameOffset = 0;
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000871 if (IsWin64Prologue && HasFP) {
David Majnemer93c22a42015-02-10 00:57:42 +0000872 SEHFrameOffset = calculateSetFPREG(NumBytes);
David Majnemer31d868b2015-02-23 21:50:27 +0000873 if (SEHFrameOffset)
874 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
875 StackPtr, false, SEHFrameOffset);
876 else
877 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr).addReg(StackPtr);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000878
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000879 if (NeedsWinCFI)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000880 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
881 .addImm(FramePtr)
882 .addImm(SEHFrameOffset)
883 .setMIFlag(MachineInstr::FrameSetup);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000884 }
885
David Majnemera7d908e2015-02-10 19:01:47 +0000886 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
887 const MachineInstr *FrameInstr = &*MBBI;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000888 ++MBBI;
889
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000890 if (NeedsWinCFI) {
David Majnemera7d908e2015-02-10 19:01:47 +0000891 int FI;
892 if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
893 if (X86::FR64RegClass.contains(Reg)) {
894 int Offset = getFrameIndexOffset(MF, FI);
895 Offset += SEHFrameOffset;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000896
David Majnemera7d908e2015-02-10 19:01:47 +0000897 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
898 .addImm(Reg)
899 .addImm(Offset)
900 .setMIFlag(MachineInstr::FrameSetup);
901 }
902 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000903 }
David Majnemera7d908e2015-02-10 19:01:47 +0000904 }
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000905
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000906 if (NeedsWinCFI)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000907 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
908 .setMIFlag(MachineInstr::FrameSetup);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000909
David Majnemer93c22a42015-02-10 00:57:42 +0000910 // Realign stack after we spilled callee-saved registers (so that we'll be
911 // able to calculate their offsets from the frame pointer).
912 // Win64 requires aligning the stack after the prologue.
Reid Kleckner1c140bd2015-06-16 18:08:57 +0000913 if (IsWin64Prologue && RegInfo->needsStackRealignment(MF)) {
David Majnemer93c22a42015-02-10 00:57:42 +0000914 assert(HasFP && "There should be a frame pointer if stack is realigned.");
915 uint64_t Val = -MaxAlign;
916 MachineInstr *MI =
917 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
918 StackPtr)
919 .addReg(StackPtr)
920 .addImm(Val)
921 .setMIFlag(MachineInstr::FrameSetup);
922
923 // The EFLAGS implicit def is dead.
924 MI->getOperand(3).setIsDead();
925 }
926
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000927 // If we need a base pointer, set it up here. It's whatever the value
928 // of the stack pointer is at this point. Any variable size objects
929 // will be allocated after this, so we can still use the base pointer
930 // to reference locals.
931 if (RegInfo->hasBasePointer(MF)) {
932 // Update the base pointer with the current stack pointer.
933 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
934 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
935 .addReg(StackPtr)
936 .setMIFlag(MachineInstr::FrameSetup);
937 if (X86FI->getRestoreBasePointer()) {
938 // Stash value of base pointer. Saving RSP instead of EBP shortens dependence chain.
939 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
940 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
941 FramePtr, true, X86FI->getRestoreBasePointerOffset())
942 .addReg(StackPtr)
943 .setMIFlag(MachineInstr::FrameSetup);
944 }
945 }
946
947 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
948 // Mark end of stack pointer adjustment.
949 if (!HasFP && NumBytes) {
950 // Define the current CFA rule to use the provided offset.
951 assert(StackSize);
Reid Kleckner7f189f82015-06-15 23:45:08 +0000952 BuildCFI(MBB, MBBI, DL, TII, MCCFIInstruction::createDefCfaOffset(
953 nullptr, -StackSize + stackGrowth));
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000954 }
955
956 // Emit DWARF info specifying the offsets of the callee-saved registers.
957 if (PushedRegs)
958 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
959 }
960}
961
Quentin Colombetaa8020752015-05-27 06:28:41 +0000962bool X86FrameLowering::canUseLEAForSPInEpilogue(
963 const MachineFunction &MF) const {
Quentin Colombet494eb602015-05-22 18:10:47 +0000964 // We can't use LEA instructions for adjusting the stack pointer if this is a
965 // leaf function in the Win64 ABI. Only ADD instructions may be used to
966 // deallocate the stack.
967 // This means that we can use LEA for SP in two situations:
968 // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
969 // 2. We *have* a frame pointer which means we are permitted to use LEA.
Quentin Colombetaa8020752015-05-27 06:28:41 +0000970 return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
971}
972
973/// Check whether or not the terminators of \p MBB needs to read EFLAGS.
974static bool terminatorsNeedFlagsAsInput(const MachineBasicBlock &MBB) {
975 for (const MachineInstr &MI : MBB.terminators()) {
976 bool BreakNext = false;
977 for (const MachineOperand &MO : MI.operands()) {
978 if (!MO.isReg())
979 continue;
980 unsigned Reg = MO.getReg();
981 if (Reg != X86::EFLAGS)
982 continue;
983
984 // This terminator needs an eflag that is not defined
985 // by a previous terminator.
986 if (!MO.isDef())
987 return true;
988 BreakNext = true;
989 }
990 if (BreakNext)
991 break;
992 }
993 return false;
Quentin Colombet494eb602015-05-22 18:10:47 +0000994}
995
Michael Kupersteine86aa9a2015-02-01 16:15:07 +0000996void X86FrameLowering::emitEpilogue(MachineFunction &MF,
997 MachineBasicBlock &MBB) const {
998 const MachineFrameInfo *MFI = MF.getFrameInfo();
999 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Reid Kleckner09543c22015-06-17 21:35:02 +00001000 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1001 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
1002 const TargetInstrInfo &TII = *STI.getInstrInfo();
Quentin Colombetaa8020752015-05-27 06:28:41 +00001003 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1004 DebugLoc DL;
1005 if (MBBI != MBB.end())
1006 DL = MBBI->getDebugLoc();
Reid Kleckner09543c22015-06-17 21:35:02 +00001007 bool Is64Bit = STI.is64Bit();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001008 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
Reid Kleckner09543c22015-06-17 21:35:02 +00001009 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001010 const bool Is64BitILP32 = STI.isTarget64BitILP32();
Reid Kleckner09543c22015-06-17 21:35:02 +00001011 unsigned SlotSize = RegInfo->getSlotSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001012 unsigned FramePtr = RegInfo->getFrameRegister(MF);
Eric Christopher05b81972015-02-02 17:38:43 +00001013 unsigned MachineFramePtr =
1014 Is64BitILP32 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
1015 : FramePtr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001016 unsigned StackPtr = RegInfo->getStackRegister();
1017
Reid Kleckner1c140bd2015-06-16 18:08:57 +00001018 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1019 bool NeedsWinCFI =
1020 IsWin64Prologue && MF.getFunction()->needsUnwindTableEntry();
Quentin Colombetaa8020752015-05-27 06:28:41 +00001021 bool UseLEAForSP = canUseLEAForSPInEpilogue(MF);
1022 // If we can use LEA for SP but we shouldn't, check that none
1023 // of the terminators uses the eflags. Otherwise we will insert
1024 // a ADD that will redefine the eflags and break the condition.
1025 // Alternatively, we could move the ADD, but this may not be possible
1026 // and is an optimization anyway.
Reid Kleckner09543c22015-06-17 21:35:02 +00001027 if (UseLEAForSP && !MF.getSubtarget<X86Subtarget>().useLeaForSP())
Quentin Colombetaa8020752015-05-27 06:28:41 +00001028 UseLEAForSP = terminatorsNeedFlagsAsInput(MBB);
1029 // If that assert breaks, that means we do not do the right thing
1030 // in canUseAsEpilogue.
1031 assert((UseLEAForSP || !terminatorsNeedFlagsAsInput(MBB)) &&
1032 "We shouldn't have allowed this insertion point");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001033
1034 // Get the number of bytes to allocate from the FrameInfo.
1035 uint64_t StackSize = MFI->getStackSize();
David Majnemer93c22a42015-02-10 00:57:42 +00001036 uint64_t MaxAlign = calculateMaxStackAlign(MF);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001037 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1038 uint64_t NumBytes = 0;
1039
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001040 if (hasFP(MF)) {
1041 // Calculate required stack adjustment.
1042 uint64_t FrameSize = StackSize - SlotSize;
David Majnemer89d05642015-02-21 01:04:47 +00001043 NumBytes = FrameSize - CSSize;
1044
1045 // Callee-saved registers were pushed on stack before the stack was
1046 // realigned.
Reid Kleckner1c140bd2015-06-16 18:08:57 +00001047 if (RegInfo->needsStackRealignment(MF) && !IsWin64Prologue)
David Majnemer89d05642015-02-21 01:04:47 +00001048 NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001049
1050 // Pop EBP.
1051 BuildMI(MBB, MBBI, DL,
1052 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1053 } else {
1054 NumBytes = StackSize - CSSize;
1055 }
David Majnemer93c22a42015-02-10 00:57:42 +00001056 uint64_t SEHStackAllocAmt = NumBytes;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001057
1058 // Skip the callee-saved pop instructions.
1059 while (MBBI != MBB.begin()) {
1060 MachineBasicBlock::iterator PI = std::prev(MBBI);
1061 unsigned Opc = PI->getOpcode();
1062
1063 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1064 !PI->isTerminator())
1065 break;
1066
1067 --MBBI;
1068 }
1069 MachineBasicBlock::iterator FirstCSPop = MBBI;
1070
Quentin Colombetaa8020752015-05-27 06:28:41 +00001071 if (MBBI != MBB.end())
1072 DL = MBBI->getDebugLoc();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001073
1074 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1075 // instruction, merge the two instructions.
1076 if (NumBytes || MFI->hasVarSizedObjects())
1077 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1078
1079 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1080 // slot before popping them off! Same applies for the case, when stack was
1081 // realigned.
1082 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1083 if (RegInfo->needsStackRealignment(MF))
1084 MBBI = FirstCSPop;
David Majnemere1bbad92015-02-25 21:13:37 +00001085 unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
Reid Kleckner1c140bd2015-06-16 18:08:57 +00001086 uint64_t LEAAmount =
1087 IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
David Majnemere1bbad92015-02-25 21:13:37 +00001088
1089 // There are only two legal forms of epilogue:
1090 // - add SEHAllocationSize, %rsp
1091 // - lea SEHAllocationSize(%FramePtr), %rsp
1092 //
1093 // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1094 // However, we may use this sequence if we have a frame pointer because the
1095 // effects of the prologue can safely be undone.
1096 if (LEAAmount != 0) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001097 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1098 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
David Majnemere1bbad92015-02-25 21:13:37 +00001099 FramePtr, false, LEAAmount);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001100 --MBBI;
1101 } else {
1102 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1103 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1104 .addReg(FramePtr);
1105 --MBBI;
1106 }
1107 } else if (NumBytes) {
1108 // Adjust stack pointer back: ESP += numbytes.
David Majnemer3aa0bd82015-02-24 00:11:32 +00001109 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr,
1110 UseLEAForSP, TII, *RegInfo);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001111 --MBBI;
1112 }
1113
1114 // Windows unwinder will not invoke function's exception handler if IP is
1115 // either in prologue or in epilogue. This behavior causes a problem when a
1116 // call immediately precedes an epilogue, because the return address points
1117 // into the epilogue. To cope with that, we insert an epilogue marker here,
1118 // then replace it with a 'nop' if it ends up immediately after a CALL in the
1119 // final emitted code.
Reid Kleckner1c140bd2015-06-16 18:08:57 +00001120 if (NeedsWinCFI)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001121 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1122
Quentin Colombet494eb602015-05-22 18:10:47 +00001123 // Add the return addr area delta back since we are not tail calling.
1124 int Offset = -1 * X86FI->getTCReturnAddrDelta();
1125 assert(Offset >= 0 && "TCDelta should never be positive");
1126 if (Offset) {
1127 MBBI = MBB.getFirstTerminator();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001128
1129 // Check for possible merge with preceding ADD instruction.
Quentin Colombet494eb602015-05-22 18:10:47 +00001130 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1131 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
David Majnemer3aa0bd82015-02-24 00:11:32 +00001132 UseLEAForSP, TII, *RegInfo);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001133 }
1134}
1135
1136int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1137 int FI) const {
Reid Kleckner09543c22015-06-17 21:35:02 +00001138 const X86RegisterInfo *RegInfo =
1139 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001140 const MachineFrameInfo *MFI = MF.getFrameInfo();
David Majnemer93c22a42015-02-10 00:57:42 +00001141 // Offset will hold the offset from the stack pointer at function entry to the
1142 // object.
1143 // We need to factor in additional offsets applied during the prologue to the
1144 // frame, base, and stack pointer depending on which is used.
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001145 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
David Majnemer93c22a42015-02-10 00:57:42 +00001146 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1147 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001148 uint64_t StackSize = MFI->getStackSize();
Reid Kleckner09543c22015-06-17 21:35:02 +00001149 unsigned SlotSize = RegInfo->getSlotSize();
David Majnemer93c22a42015-02-10 00:57:42 +00001150 bool HasFP = hasFP(MF);
Reid Kleckner1c140bd2015-06-16 18:08:57 +00001151 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
David Majnemer93c22a42015-02-10 00:57:42 +00001152 int64_t FPDelta = 0;
1153
Reid Kleckner1c140bd2015-06-16 18:08:57 +00001154 if (IsWin64Prologue) {
David Majnemer89d05642015-02-21 01:04:47 +00001155 assert(!MFI->hasCalls() || (StackSize % 16) == 8);
1156
David Majnemer93c22a42015-02-10 00:57:42 +00001157 // Calculate required stack adjustment.
1158 uint64_t FrameSize = StackSize - SlotSize;
1159 // If required, include space for extra hidden slot for stashing base pointer.
1160 if (X86FI->getRestoreBasePointer())
1161 FrameSize += SlotSize;
David Majnemer89d05642015-02-21 01:04:47 +00001162 uint64_t NumBytes = FrameSize - CSSize;
David Majnemer93c22a42015-02-10 00:57:42 +00001163
David Majnemer93c22a42015-02-10 00:57:42 +00001164 uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
David Majnemer13d0b112015-02-10 21:22:05 +00001165 if (FI && FI == X86FI->getFAIndex())
1166 return -SEHFrameOffset;
1167
David Majnemer93c22a42015-02-10 00:57:42 +00001168 // FPDelta is the offset from the "traditional" FP location of the old base
1169 // pointer followed by return address and the location required by the
1170 // restricted Win64 prologue.
1171 // Add FPDelta to all offsets below that go through the frame pointer.
David Majnemer89d05642015-02-21 01:04:47 +00001172 FPDelta = FrameSize - SEHFrameOffset;
1173 assert((!MFI->hasCalls() || (FPDelta % 16) == 0) &&
1174 "FPDelta isn't aligned per the Win64 ABI!");
David Majnemer93c22a42015-02-10 00:57:42 +00001175 }
1176
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001177
1178 if (RegInfo->hasBasePointer(MF)) {
David Majnemer93c22a42015-02-10 00:57:42 +00001179 assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001180 if (FI < 0) {
1181 // Skip the saved EBP.
David Majnemer93c22a42015-02-10 00:57:42 +00001182 return Offset + SlotSize + FPDelta;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001183 } else {
1184 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1185 return Offset + StackSize;
1186 }
1187 } else if (RegInfo->needsStackRealignment(MF)) {
1188 if (FI < 0) {
1189 // Skip the saved EBP.
David Majnemer93c22a42015-02-10 00:57:42 +00001190 return Offset + SlotSize + FPDelta;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001191 } else {
1192 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1193 return Offset + StackSize;
1194 }
1195 // FIXME: Support tail calls
1196 } else {
David Majnemer93c22a42015-02-10 00:57:42 +00001197 if (!HasFP)
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001198 return Offset + StackSize;
1199
1200 // Skip the saved EBP.
David Majnemer93c22a42015-02-10 00:57:42 +00001201 Offset += SlotSize;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001202
1203 // Skip the RETADDR move area
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001204 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1205 if (TailCallReturnAddrDelta < 0)
1206 Offset -= TailCallReturnAddrDelta;
1207 }
1208
David Majnemer89d05642015-02-21 01:04:47 +00001209 return Offset + FPDelta;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001210}
1211
1212int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1213 unsigned &FrameReg) const {
Reid Kleckner09543c22015-06-17 21:35:02 +00001214 const X86RegisterInfo *RegInfo =
1215 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001216 // We can't calculate offset from frame pointer if the stack is realigned,
1217 // so enforce usage of stack/base pointer. The base pointer is used when we
1218 // have dynamic allocas in addition to dynamic realignment.
1219 if (RegInfo->hasBasePointer(MF))
1220 FrameReg = RegInfo->getBaseRegister();
1221 else if (RegInfo->needsStackRealignment(MF))
1222 FrameReg = RegInfo->getStackRegister();
1223 else
1224 FrameReg = RegInfo->getFrameRegister(MF);
1225 return getFrameIndexOffset(MF, FI);
1226}
1227
1228// Simplified from getFrameIndexOffset keeping only StackPointer cases
1229int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1230 const MachineFrameInfo *MFI = MF.getFrameInfo();
1231 // Does not include any dynamic realign.
1232 const uint64_t StackSize = MFI->getStackSize();
1233 {
1234#ifndef NDEBUG
Reid Kleckner09543c22015-06-17 21:35:02 +00001235 const X86RegisterInfo *RegInfo =
1236 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001237 // Note: LLVM arranges the stack as:
1238 // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1239 // > "Stack Slots" (<--SP)
1240 // We can always address StackSlots from RSP. We can usually (unless
1241 // needsStackRealignment) address CSRs from RSP, but sometimes need to
1242 // address them from RBP. FixedObjects can be placed anywhere in the stack
1243 // frame depending on their specific requirements (i.e. we can actually
1244 // refer to arguments to the function which are stored in the *callers*
1245 // frame). As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1246 // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1247
1248 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1249
1250 // We don't handle tail calls, and shouldn't be seeing them
1251 // either.
1252 int TailCallReturnAddrDelta =
1253 MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1254 assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1255#endif
1256 }
1257
1258 // This is how the math works out:
1259 //
1260 // %rsp grows (i.e. gets lower) left to right. Each box below is
1261 // one word (eight bytes). Obj0 is the stack slot we're trying to
1262 // get to.
1263 //
1264 // ----------------------------------
1265 // | BP | Obj0 | Obj1 | ... | ObjN |
1266 // ----------------------------------
1267 // ^ ^ ^ ^
1268 // A B C E
1269 //
1270 // A is the incoming stack pointer.
1271 // (B - A) is the local area offset (-8 for x86-64) [1]
1272 // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1273 //
1274 // |(E - B)| is the StackSize (absolute value, positive). For a
1275 // stack that grown down, this works out to be (B - E). [3]
1276 //
1277 // E is also the value of %rsp after stack has been set up, and we
1278 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
1279 // (C - E) == (C - A) - (B - A) + (B - E)
1280 // { Using [1], [2] and [3] above }
1281 // == getObjectOffset - LocalAreaOffset + StackSize
1282 //
1283
1284 // Get the Offset from the StackPointer
1285 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1286
1287 return Offset + StackSize;
1288}
1289// Simplified from getFrameIndexReference keeping only StackPointer cases
Eric Christopher05b81972015-02-02 17:38:43 +00001290int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
1291 int FI,
1292 unsigned &FrameReg) const {
Reid Kleckner09543c22015-06-17 21:35:02 +00001293 const X86RegisterInfo *RegInfo =
1294 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001295 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1296
1297 FrameReg = RegInfo->getStackRegister();
1298 return getFrameIndexOffsetFromSP(MF, FI);
1299}
1300
1301bool X86FrameLowering::assignCalleeSavedSpillSlots(
1302 MachineFunction &MF, const TargetRegisterInfo *TRI,
1303 std::vector<CalleeSavedInfo> &CSI) const {
1304 MachineFrameInfo *MFI = MF.getFrameInfo();
Reid Kleckner09543c22015-06-17 21:35:02 +00001305 const X86RegisterInfo *RegInfo =
1306 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1307 unsigned SlotSize = RegInfo->getSlotSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001308 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1309
1310 unsigned CalleeSavedFrameSize = 0;
1311 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1312
1313 if (hasFP(MF)) {
1314 // emitPrologue always spills frame register the first thing.
1315 SpillSlotOffset -= SlotSize;
1316 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1317
1318 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1319 // the frame register, we can delete it from CSI list and not have to worry
1320 // about avoiding it later.
1321 unsigned FPReg = RegInfo->getFrameRegister(MF);
1322 for (unsigned i = 0; i < CSI.size(); ++i) {
1323 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1324 CSI.erase(CSI.begin() + i);
1325 break;
1326 }
1327 }
1328 }
1329
1330 // Assign slots for GPRs. It increases frame size.
1331 for (unsigned i = CSI.size(); i != 0; --i) {
1332 unsigned Reg = CSI[i - 1].getReg();
1333
1334 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1335 continue;
1336
1337 SpillSlotOffset -= SlotSize;
1338 CalleeSavedFrameSize += SlotSize;
1339
1340 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1341 CSI[i - 1].setFrameIdx(SlotIndex);
1342 }
1343
1344 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1345
1346 // Assign slots for XMMs.
1347 for (unsigned i = CSI.size(); i != 0; --i) {
1348 unsigned Reg = CSI[i - 1].getReg();
1349 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1350 continue;
1351
1352 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1353 // ensure alignment
1354 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1355 // spill into slot
1356 SpillSlotOffset -= RC->getSize();
1357 int SlotIndex =
1358 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1359 CSI[i - 1].setFrameIdx(SlotIndex);
1360 MFI->ensureMaxAlignment(RC->getAlignment());
1361 }
1362
1363 return true;
1364}
1365
1366bool X86FrameLowering::spillCalleeSavedRegisters(
1367 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1368 const std::vector<CalleeSavedInfo> &CSI,
1369 const TargetRegisterInfo *TRI) const {
1370 DebugLoc DL = MBB.findDebugLoc(MI);
1371
Reid Kleckner09543c22015-06-17 21:35:02 +00001372 MachineFunction &MF = *MBB.getParent();
1373 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1374 const TargetInstrInfo &TII = *STI.getInstrInfo();
1375
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001376 // Push GPRs. It increases frame size.
1377 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1378 for (unsigned i = CSI.size(); i != 0; --i) {
1379 unsigned Reg = CSI[i - 1].getReg();
1380
1381 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1382 continue;
1383 // Add the callee-saved register as live-in. It's killed at the spill.
1384 MBB.addLiveIn(Reg);
1385
1386 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1387 .setMIFlag(MachineInstr::FrameSetup);
1388 }
1389
1390 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1391 // It can be done by spilling XMMs to stack frame.
1392 for (unsigned i = CSI.size(); i != 0; --i) {
1393 unsigned Reg = CSI[i-1].getReg();
David Majnemera7d908e2015-02-10 19:01:47 +00001394 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001395 continue;
1396 // Add the callee-saved register as live-in. It's killed at the spill.
1397 MBB.addLiveIn(Reg);
1398 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1399
1400 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1401 TRI);
1402 --MI;
1403 MI->setFlag(MachineInstr::FrameSetup);
1404 ++MI;
1405 }
1406
1407 return true;
1408}
1409
1410bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1411 MachineBasicBlock::iterator MI,
1412 const std::vector<CalleeSavedInfo> &CSI,
1413 const TargetRegisterInfo *TRI) const {
1414 if (CSI.empty())
1415 return false;
1416
1417 DebugLoc DL = MBB.findDebugLoc(MI);
1418
Reid Kleckner09543c22015-06-17 21:35:02 +00001419 MachineFunction &MF = *MBB.getParent();
1420 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1421 const TargetInstrInfo &TII = *STI.getInstrInfo();
1422
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001423 // Reload XMMs from stack frame.
1424 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1425 unsigned Reg = CSI[i].getReg();
1426 if (X86::GR64RegClass.contains(Reg) ||
1427 X86::GR32RegClass.contains(Reg))
1428 continue;
1429
1430 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1431 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1432 }
1433
1434 // POP GPRs.
1435 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1436 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1437 unsigned Reg = CSI[i].getReg();
1438 if (!X86::GR64RegClass.contains(Reg) &&
1439 !X86::GR32RegClass.contains(Reg))
1440 continue;
1441
1442 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1443 }
1444 return true;
1445}
1446
1447void
1448X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1449 RegScavenger *RS) const {
1450 MachineFrameInfo *MFI = MF.getFrameInfo();
Reid Kleckner09543c22015-06-17 21:35:02 +00001451 const X86RegisterInfo *RegInfo =
1452 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1453 unsigned SlotSize = RegInfo->getSlotSize();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001454
1455 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1456 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1457
1458 if (TailCallReturnAddrDelta < 0) {
1459 // create RETURNADDR area
1460 // arg
1461 // arg
1462 // RETADDR
1463 // { ...
1464 // RETADDR area
1465 // ...
1466 // }
1467 // [EBP]
1468 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1469 TailCallReturnAddrDelta - SlotSize, true);
1470 }
1471
1472 // Spill the BasePtr if it's used.
1473 if (RegInfo->hasBasePointer(MF))
1474 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1475}
1476
1477static bool
1478HasNestArgument(const MachineFunction *MF) {
1479 const Function *F = MF->getFunction();
1480 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1481 I != E; I++) {
1482 if (I->hasNestAttr())
1483 return true;
1484 }
1485 return false;
1486}
1487
1488/// GetScratchRegister - Get a temp register for performing work in the
1489/// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1490/// and the properties of the function either one or two registers will be
1491/// needed. Set primary to true for the first register, false for the second.
1492static unsigned
1493GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1494 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1495
1496 // Erlang stuff.
1497 if (CallingConvention == CallingConv::HiPE) {
1498 if (Is64Bit)
1499 return Primary ? X86::R14 : X86::R13;
1500 else
1501 return Primary ? X86::EBX : X86::EDI;
1502 }
1503
1504 if (Is64Bit) {
1505 if (IsLP64)
1506 return Primary ? X86::R11 : X86::R12;
1507 else
1508 return Primary ? X86::R11D : X86::R12D;
1509 }
1510
1511 bool IsNested = HasNestArgument(&MF);
1512
1513 if (CallingConvention == CallingConv::X86_FastCall ||
1514 CallingConvention == CallingConv::Fast) {
1515 if (IsNested)
1516 report_fatal_error("Segmented stacks does not support fastcall with "
1517 "nested function.");
1518 return Primary ? X86::EAX : X86::ECX;
1519 }
1520 if (IsNested)
1521 return Primary ? X86::EDX : X86::EAX;
1522 return Primary ? X86::ECX : X86::EAX;
1523}
1524
1525// The stack limit in the TCB is set to this many bytes above the actual stack
1526// limit.
1527static const uint64_t kSplitStackAvailable = 256;
1528
Quentin Colombet61b305e2015-05-05 17:38:16 +00001529void X86FrameLowering::adjustForSegmentedStacks(
1530 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001531 MachineFrameInfo *MFI = MF.getFrameInfo();
Reid Kleckner09543c22015-06-17 21:35:02 +00001532 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1533 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001534 uint64_t StackSize;
Reid Kleckner09543c22015-06-17 21:35:02 +00001535 bool Is64Bit = STI.is64Bit();
1536 const bool IsLP64 = STI.isTarget64BitLP64();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001537 unsigned TlsReg, TlsOffset;
1538 DebugLoc DL;
1539
1540 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1541 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1542 "Scratch register is live-in");
1543
1544 if (MF.getFunction()->isVarArg())
1545 report_fatal_error("Segmented stacks do not support vararg functions.");
1546 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1547 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1548 !STI.isTargetDragonFly())
1549 report_fatal_error("Segmented stacks not supported on this platform.");
1550
1551 // Eventually StackSize will be calculated by a link-time pass; which will
1552 // also decide whether checking code needs to be injected into this particular
1553 // prologue.
1554 StackSize = MFI->getStackSize();
1555
1556 // Do not generate a prologue for functions with a stack of size zero
1557 if (StackSize == 0)
1558 return;
1559
1560 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1561 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1562 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1563 bool IsNested = false;
1564
1565 // We need to know if the function has a nest argument only in 64 bit mode.
1566 if (Is64Bit)
1567 IsNested = HasNestArgument(&MF);
1568
1569 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1570 // allocMBB needs to be last (terminating) instruction.
1571
Quentin Colombet61b305e2015-05-05 17:38:16 +00001572 for (MachineBasicBlock::livein_iterator i = PrologueMBB.livein_begin(),
1573 e = PrologueMBB.livein_end();
1574 i != e; i++) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001575 allocMBB->addLiveIn(*i);
1576 checkMBB->addLiveIn(*i);
1577 }
1578
1579 if (IsNested)
1580 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1581
1582 MF.push_front(allocMBB);
1583 MF.push_front(checkMBB);
1584
1585 // When the frame size is less than 256 we just compare the stack
1586 // boundary directly to the value of the stack pointer, per gcc.
1587 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1588
1589 // Read the limit off the current stacklet off the stack_guard location.
1590 if (Is64Bit) {
1591 if (STI.isTargetLinux()) {
1592 TlsReg = X86::FS;
1593 TlsOffset = IsLP64 ? 0x70 : 0x40;
1594 } else if (STI.isTargetDarwin()) {
1595 TlsReg = X86::GS;
1596 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1597 } else if (STI.isTargetWin64()) {
1598 TlsReg = X86::GS;
1599 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1600 } else if (STI.isTargetFreeBSD()) {
1601 TlsReg = X86::FS;
1602 TlsOffset = 0x18;
1603 } else if (STI.isTargetDragonFly()) {
1604 TlsReg = X86::FS;
1605 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1606 } else {
1607 report_fatal_error("Segmented stacks not supported on this platform.");
1608 }
1609
1610 if (CompareStackPointer)
1611 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1612 else
1613 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1614 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1615
1616 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1617 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1618 } else {
1619 if (STI.isTargetLinux()) {
1620 TlsReg = X86::GS;
1621 TlsOffset = 0x30;
1622 } else if (STI.isTargetDarwin()) {
1623 TlsReg = X86::GS;
1624 TlsOffset = 0x48 + 90*4;
1625 } else if (STI.isTargetWin32()) {
1626 TlsReg = X86::FS;
1627 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1628 } else if (STI.isTargetDragonFly()) {
1629 TlsReg = X86::FS;
1630 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1631 } else if (STI.isTargetFreeBSD()) {
1632 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1633 } else {
1634 report_fatal_error("Segmented stacks not supported on this platform.");
1635 }
1636
1637 if (CompareStackPointer)
1638 ScratchReg = X86::ESP;
1639 else
1640 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1641 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1642
1643 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1644 STI.isTargetDragonFly()) {
1645 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1646 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1647 } else if (STI.isTargetDarwin()) {
1648
1649 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1650 unsigned ScratchReg2;
1651 bool SaveScratch2;
1652 if (CompareStackPointer) {
1653 // The primary scratch register is available for holding the TLS offset.
1654 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1655 SaveScratch2 = false;
1656 } else {
1657 // Need to use a second register to hold the TLS offset
1658 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1659
1660 // Unfortunately, with fastcc the second scratch register may hold an
1661 // argument.
1662 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1663 }
1664
1665 // If Scratch2 is live-in then it needs to be saved.
1666 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1667 "Scratch register is live-in and not saved");
1668
1669 if (SaveScratch2)
1670 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1671 .addReg(ScratchReg2, RegState::Kill);
1672
1673 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1674 .addImm(TlsOffset);
1675 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1676 .addReg(ScratchReg)
1677 .addReg(ScratchReg2).addImm(1).addReg(0)
1678 .addImm(0)
1679 .addReg(TlsReg);
1680
1681 if (SaveScratch2)
1682 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1683 }
1684 }
1685
1686 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1687 // It jumps to normal execution of the function body.
Quentin Colombet61b305e2015-05-05 17:38:16 +00001688 BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&PrologueMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001689
1690 // On 32 bit we first push the arguments size and then the frame size. On 64
1691 // bit, we pass the stack frame size in r10 and the argument size in r11.
1692 if (Is64Bit) {
1693 // Functions with nested arguments use R10, so it needs to be saved across
1694 // the call to _morestack
1695
1696 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1697 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1698 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1699 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1700 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1701
1702 if (IsNested)
1703 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1704
1705 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1706 .addImm(StackSize);
1707 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1708 .addImm(X86FI->getArgumentStackSize());
1709 MF.getRegInfo().setPhysRegUsed(Reg10);
1710 MF.getRegInfo().setPhysRegUsed(Reg11);
1711 } else {
1712 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1713 .addImm(X86FI->getArgumentStackSize());
1714 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1715 .addImm(StackSize);
1716 }
1717
1718 // __morestack is in libgcc
1719 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1720 // Under the large code model, we cannot assume that __morestack lives
1721 // within 2^31 bytes of the call site, so we cannot use pc-relative
1722 // addressing. We cannot perform the call via a temporary register,
1723 // as the rax register may be used to store the static chain, and all
1724 // other suitable registers may be either callee-save or used for
1725 // parameter passing. We cannot use the stack at this point either
1726 // because __morestack manipulates the stack directly.
1727 //
1728 // To avoid these issues, perform an indirect call via a read-only memory
1729 // location containing the address.
1730 //
1731 // This solution is not perfect, as it assumes that the .rodata section
1732 // is laid out within 2^31 bytes of each function body, but this seems
1733 // to be sufficient for JIT.
1734 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1735 .addReg(X86::RIP)
1736 .addImm(0)
1737 .addReg(0)
1738 .addExternalSymbol("__morestack_addr")
1739 .addReg(0);
1740 MF.getMMI().setUsesMorestackAddr(true);
1741 } else {
1742 if (Is64Bit)
1743 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1744 .addExternalSymbol("__morestack");
1745 else
1746 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1747 .addExternalSymbol("__morestack");
1748 }
1749
1750 if (IsNested)
1751 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1752 else
1753 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1754
Quentin Colombet61b305e2015-05-05 17:38:16 +00001755 allocMBB->addSuccessor(&PrologueMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001756
1757 checkMBB->addSuccessor(allocMBB);
Quentin Colombet61b305e2015-05-05 17:38:16 +00001758 checkMBB->addSuccessor(&PrologueMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001759
1760#ifdef XDEBUG
1761 MF.verify();
1762#endif
1763}
1764
1765/// Erlang programs may need a special prologue to handle the stack size they
1766/// might need at runtime. That is because Erlang/OTP does not implement a C
1767/// stack but uses a custom implementation of hybrid stack/heap architecture.
1768/// (for more information see Eric Stenman's Ph.D. thesis:
1769/// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1770///
1771/// CheckStack:
1772/// temp0 = sp - MaxStack
1773/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1774/// OldStart:
1775/// ...
1776/// IncStack:
1777/// call inc_stack # doubles the stack space
1778/// temp0 = sp - MaxStack
1779/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
Quentin Colombet61b305e2015-05-05 17:38:16 +00001780void X86FrameLowering::adjustForHiPEPrologue(
1781 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
Reid Kleckner09543c22015-06-17 21:35:02 +00001782 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1783 const TargetInstrInfo &TII = *STI.getInstrInfo();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001784 MachineFrameInfo *MFI = MF.getFrameInfo();
Reid Kleckner09543c22015-06-17 21:35:02 +00001785 const unsigned SlotSize = STI.getRegisterInfo()->getSlotSize();
1786 const bool Is64Bit = STI.is64Bit();
1787 const bool IsLP64 = STI.isTarget64BitLP64();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001788 DebugLoc DL;
1789 // HiPE-specific values
1790 const unsigned HipeLeafWords = 24;
1791 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1792 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1793 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1794 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1795 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1796
1797 assert(STI.isTargetLinux() &&
1798 "HiPE prologue is only supported on Linux operating systems.");
1799
1800 // Compute the largest caller's frame that is needed to fit the callees'
1801 // frames. This 'MaxStack' is computed from:
1802 //
1803 // a) the fixed frame size, which is the space needed for all spilled temps,
1804 // b) outgoing on-stack parameter areas, and
1805 // c) the minimum stack space this function needs to make available for the
1806 // functions it calls (a tunable ABI property).
1807 if (MFI->hasCalls()) {
1808 unsigned MoreStackForCalls = 0;
1809
1810 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1811 MBBI != MBBE; ++MBBI)
1812 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1813 MI != ME; ++MI) {
1814 if (!MI->isCall())
1815 continue;
1816
1817 // Get callee operand.
1818 const MachineOperand &MO = MI->getOperand(0);
1819
1820 // Only take account of global function calls (no closures etc.).
1821 if (!MO.isGlobal())
1822 continue;
1823
1824 const Function *F = dyn_cast<Function>(MO.getGlobal());
1825 if (!F)
1826 continue;
1827
1828 // Do not update 'MaxStack' for primitive and built-in functions
1829 // (encoded with names either starting with "erlang."/"bif_" or not
1830 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1831 // "_", such as the BIF "suspend_0") as they are executed on another
1832 // stack.
1833 if (F->getName().find("erlang.") != StringRef::npos ||
1834 F->getName().find("bif_") != StringRef::npos ||
1835 F->getName().find_first_of("._") == StringRef::npos)
1836 continue;
1837
1838 unsigned CalleeStkArity =
1839 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1840 if (HipeLeafWords - 1 > CalleeStkArity)
1841 MoreStackForCalls = std::max(MoreStackForCalls,
1842 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1843 }
1844 MaxStack += MoreStackForCalls;
1845 }
1846
1847 // If the stack frame needed is larger than the guaranteed then runtime checks
1848 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1849 if (MaxStack > Guaranteed) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001850 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1851 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1852
Quentin Colombet61b305e2015-05-05 17:38:16 +00001853 for (MachineBasicBlock::livein_iterator I = PrologueMBB.livein_begin(),
1854 E = PrologueMBB.livein_end();
1855 I != E; I++) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001856 stackCheckMBB->addLiveIn(*I);
1857 incStackMBB->addLiveIn(*I);
1858 }
1859
1860 MF.push_front(incStackMBB);
1861 MF.push_front(stackCheckMBB);
1862
1863 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1864 unsigned LEAop, CMPop, CALLop;
1865 if (Is64Bit) {
1866 SPReg = X86::RSP;
1867 PReg = X86::RBP;
1868 LEAop = X86::LEA64r;
1869 CMPop = X86::CMP64rm;
1870 CALLop = X86::CALL64pcrel32;
1871 SPLimitOffset = 0x90;
1872 } else {
1873 SPReg = X86::ESP;
1874 PReg = X86::EBP;
1875 LEAop = X86::LEA32r;
1876 CMPop = X86::CMP32rm;
1877 CALLop = X86::CALLpcrel32;
1878 SPLimitOffset = 0x4c;
1879 }
1880
1881 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1882 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1883 "HiPE prologue scratch register is live-in");
1884
1885 // Create new MBB for StackCheck:
1886 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1887 SPReg, false, -MaxStack);
1888 // SPLimitOffset is in a fixed heap location (pointed by BP).
1889 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1890 .addReg(ScratchReg), PReg, false, SPLimitOffset);
Quentin Colombet61b305e2015-05-05 17:38:16 +00001891 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&PrologueMBB);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001892
1893 // Create new MBB for IncStack:
1894 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1895 addExternalSymbol("inc_stack_0");
1896 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1897 SPReg, false, -MaxStack);
1898 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1899 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1900 BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1901
Quentin Colombet61b305e2015-05-05 17:38:16 +00001902 stackCheckMBB->addSuccessor(&PrologueMBB, 99);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001903 stackCheckMBB->addSuccessor(incStackMBB, 1);
Quentin Colombet61b305e2015-05-05 17:38:16 +00001904 incStackMBB->addSuccessor(&PrologueMBB, 99);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001905 incStackMBB->addSuccessor(incStackMBB, 1);
1906 }
1907#ifdef XDEBUG
1908 MF.verify();
1909#endif
1910}
1911
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001912void X86FrameLowering::
1913eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1914 MachineBasicBlock::iterator I) const {
Reid Kleckner09543c22015-06-17 21:35:02 +00001915 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1916 const TargetInstrInfo &TII = *STI.getInstrInfo();
1917 const X86RegisterInfo &RegInfo = *STI.getRegisterInfo();
1918 unsigned StackPtr = RegInfo.getStackRegister();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001919 bool reserveCallFrame = hasReservedCallFrame(MF);
Matthias Braunfa3872e2015-05-18 20:27:55 +00001920 unsigned Opcode = I->getOpcode();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001921 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
Reid Kleckner09543c22015-06-17 21:35:02 +00001922 bool IsLP64 = STI.isTarget64BitLP64();
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001923 DebugLoc DL = I->getDebugLoc();
1924 uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
Michael Kuperstein13fbd452015-02-01 16:56:04 +00001925 uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001926 I = MBB.erase(I);
1927
1928 if (!reserveCallFrame) {
1929 // If the stack pointer can be changed after prologue, turn the
1930 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1931 // adjcallstackdown instruction into 'add ESP, <amt>'
1932 if (Amount == 0)
1933 return;
1934
1935 // We need to keep the stack aligned properly. To do this, we round the
1936 // amount of space needed for the outgoing arguments up to the next
1937 // alignment boundary.
David Majnemer93c22a42015-02-10 00:57:42 +00001938 unsigned StackAlign = getStackAlignment();
1939 Amount = RoundUpToAlignment(Amount, StackAlign);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001940
1941 MachineInstr *New = nullptr;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001942
Michael Kuperstein13fbd452015-02-01 16:56:04 +00001943 // Factor out the amount that gets handled inside the sequence
1944 // (Pushes of argument for frame setup, callee pops for frame destroy)
1945 Amount -= InternalAmt;
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001946
Michael Kuperstein13fbd452015-02-01 16:56:04 +00001947 if (Amount) {
1948 if (Opcode == TII.getCallFrameSetupOpcode()) {
1949 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)), StackPtr)
1950 .addReg(StackPtr).addImm(Amount);
1951 } else {
1952 assert(Opcode == TII.getCallFrameDestroyOpcode());
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001953
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001954 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1955 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1956 .addReg(StackPtr).addImm(Amount);
1957 }
1958 }
1959
1960 if (New) {
1961 // The EFLAGS implicit def is dead.
1962 New->getOperand(3).setIsDead();
1963
1964 // Replace the pseudo instruction with a new instruction.
1965 MBB.insert(I, New);
1966 }
1967
1968 return;
1969 }
1970
Michael Kuperstein13fbd452015-02-01 16:56:04 +00001971 if (Opcode == TII.getCallFrameDestroyOpcode() && InternalAmt) {
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001972 // If we are performing frame pointer elimination and if the callee pops
1973 // something off the stack pointer, add it back. We do this until we have
1974 // more advanced stack pointer tracking ability.
Michael Kuperstein13fbd452015-02-01 16:56:04 +00001975 unsigned Opc = getSUBriOpcode(IsLP64, InternalAmt);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001976 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
Michael Kuperstein13fbd452015-02-01 16:56:04 +00001977 .addReg(StackPtr).addImm(InternalAmt);
Michael Kupersteine86aa9a2015-02-01 16:15:07 +00001978
1979 // The EFLAGS implicit def is dead.
1980 New->getOperand(3).setIsDead();
1981
1982 // We are not tracking the stack pointer adjustment by the callee, so make
1983 // sure we restore the stack pointer immediately after the call, there may
1984 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1985 MachineBasicBlock::iterator B = MBB.begin();
1986 while (I != B && !std::prev(I)->isCall())
1987 --I;
1988 MBB.insert(I, New);
1989 }
1990}
1991
Quentin Colombetaa8020752015-05-27 06:28:41 +00001992bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
1993 assert(MBB.getParent() && "Block is not attached to a function!");
1994
1995 if (canUseLEAForSPInEpilogue(*MBB.getParent()))
1996 return true;
1997
1998 // If we cannot use LEA to adjust SP, we may need to use ADD, which
1999 // clobbers the EFLAGS. Check that none of the terminators reads the
2000 // EFLAGS, and if one uses it, conservatively assume this is not
2001 // safe to insert the epilogue here.
2002 return !terminatorsNeedFlagsAsInput(MBB);
2003}