blob: f17e5a34e5010d2b3662d0a0626cd51c147a3794 [file] [log] [blame]
Jia Liub22310f2012-02-18 12:03:15 +00001//===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00002//
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//
Anton Korobeynikov2f931282011-01-10 12:39:04 +000010// This file contains the X86 implementation of TargetFrameLowering class.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000011//
12//===----------------------------------------------------------------------===//
13
Anton Korobeynikov2f931282011-01-10 12:39:04 +000014#include "X86FrameLowering.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000015#include "X86InstrBuilder.h"
16#include "X86InstrInfo.h"
17#include "X86MachineFunctionInfo.h"
Rafael Espindolac2174212011-08-30 19:39:58 +000018#include "X86Subtarget.h"
Anton Korobeynikov14ee3442010-11-18 23:25:52 +000019#include "X86TargetMachine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/SmallSet.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000021#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"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
Rafael Espindolaa01cdb02011-04-15 15:11:06 +000028#include "llvm/MC/MCAsmInfo.h"
Bill Wendlingb6adf462011-07-07 00:54:13 +000029#include "llvm/MC/MCSymbol.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000030#include "llvm/Support/CommandLine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/Target/TargetOptions.h"
NAKAMURA Takumi1db59952014-06-25 12:41:52 +000032#include "llvm/Support/Debug.h"
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000033
34using namespace llvm;
35
36// FIXME: completely move here.
37extern cl::opt<bool> ForceStackAlign;
38
Anton Korobeynikov2f931282011-01-10 12:39:04 +000039bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000040 return !MF.getFrameInfo()->hasVarSizedObjects();
41}
42
43/// hasFP - Return true if the specified function should have a dedicated frame
44/// pointer register. This is true if the function has variable sized allocas
45/// or if frame pointer elimination is disabled.
Anton Korobeynikov2f931282011-01-10 12:39:04 +000046bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000047 const MachineFrameInfo *MFI = MF.getFrameInfo();
48 const MachineModuleInfo &MMI = MF.getMMI();
Eric Christopherfc6de422014-08-05 02:39:49 +000049 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000050
Nick Lewycky50f02cb2011-12-02 22:16:29 +000051 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
Chad Rosier20b79dc2012-05-23 23:45:10 +000052 RegInfo->needsStackRealignment(MF) ||
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000053 MFI->hasVarSizedObjects() ||
Reid Kleckneree088972013-12-10 18:27:32 +000054 MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000055 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
Jakob Stoklund Olesen321d41a2012-06-22 03:04:27 +000056 MMI.callsUnwindInit() || MMI.callsEHReturn());
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000057}
58
Eli Bendersky8da87162013-02-21 20:05:00 +000059static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
60 if (IsLP64) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000061 if (isInt<8>(Imm))
62 return X86::SUB64ri8;
63 return X86::SUB64ri32;
64 } else {
65 if (isInt<8>(Imm))
66 return X86::SUB32ri8;
67 return X86::SUB32ri;
68 }
69}
70
Eli Benderskyef4558a2013-02-06 20:43:57 +000071static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
72 if (IsLP64) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000073 if (isInt<8>(Imm))
74 return X86::ADD64ri8;
75 return X86::ADD64ri32;
76 } else {
77 if (isInt<8>(Imm))
78 return X86::ADD32ri8;
79 return X86::ADD32ri;
80 }
81}
82
Eli Benderskyef4558a2013-02-06 20:43:57 +000083static unsigned getLEArOpcode(unsigned IsLP64) {
84 return IsLP64 ? X86::LEA64r : X86::LEA32r;
Evan Cheng1b81fdd2012-02-07 22:50:41 +000085}
86
Evan Cheng65089fc2011-01-03 22:53:22 +000087/// findDeadCallerSavedReg - Return a caller-saved register that isn't live
88/// when it reaches the "return" instruction. We can then pop a stack object
89/// to this register without worry about clobbering it.
90static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
91 MachineBasicBlock::iterator &MBBI,
92 const TargetRegisterInfo &TRI,
93 bool Is64Bit) {
94 const MachineFunction *MF = MBB.getParent();
95 const Function *F = MF->getFunction();
96 if (!F || MF->getMMI().callsEHReturn())
97 return 0;
98
Craig Topper1d326582012-03-04 10:43:23 +000099 static const uint16_t CallerSavedRegs32Bit[] = {
Andrew Trick210bf832011-08-12 00:49:19 +0000100 X86::EAX, X86::EDX, X86::ECX, 0
Evan Cheng65089fc2011-01-03 22:53:22 +0000101 };
102
Craig Topper1d326582012-03-04 10:43:23 +0000103 static const uint16_t CallerSavedRegs64Bit[] = {
Evan Cheng65089fc2011-01-03 22:53:22 +0000104 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
Andrew Trick210bf832011-08-12 00:49:19 +0000105 X86::R8, X86::R9, X86::R10, X86::R11, 0
Evan Cheng65089fc2011-01-03 22:53:22 +0000106 };
107
108 unsigned Opc = MBBI->getOpcode();
109 switch (Opc) {
110 default: return 0;
David Woodhouse79dd5052014-01-08 12:58:07 +0000111 case X86::RETL:
112 case X86::RETQ:
David Woodhouse4e033b02014-01-13 14:05:59 +0000113 case X86::RETIL:
114 case X86::RETIQ:
Evan Cheng65089fc2011-01-03 22:53:22 +0000115 case X86::TCRETURNdi:
116 case X86::TCRETURNri:
117 case X86::TCRETURNmi:
118 case X86::TCRETURNdi64:
119 case X86::TCRETURNri64:
120 case X86::TCRETURNmi64:
121 case X86::EH_RETURN:
122 case X86::EH_RETURN64: {
Craig Topper1d326582012-03-04 10:43:23 +0000123 SmallSet<uint16_t, 8> Uses;
Evan Cheng65089fc2011-01-03 22:53:22 +0000124 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
125 MachineOperand &MO = MBBI->getOperand(i);
126 if (!MO.isReg() || MO.isDef())
127 continue;
128 unsigned Reg = MO.getReg();
129 if (!Reg)
130 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000131 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
132 Uses.insert(*AI);
Evan Cheng65089fc2011-01-03 22:53:22 +0000133 }
134
Craig Topper1d326582012-03-04 10:43:23 +0000135 const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
Evan Cheng65089fc2011-01-03 22:53:22 +0000136 for (; *CS; ++CS)
137 if (!Uses.count(*CS))
138 return *CS;
139 }
140 }
141
142 return 0;
143}
144
145
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000146/// emitSPUpdate - Emit a series of instructions to increment / decrement the
147/// stack pointer by a constant value.
148static
149void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
Evan Cheng65089fc2011-01-03 22:53:22 +0000150 unsigned StackPtr, int64_t NumBytes,
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000151 bool Is64Bit, bool IsLP64, bool UseLEA,
Eric Christopherf4fba5c2012-10-03 08:10:01 +0000152 const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000153 bool isSub = NumBytes < 0;
154 uint64_t Offset = isSub ? -NumBytes : NumBytes;
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000155 unsigned Opc;
156 if (UseLEA)
Eli Benderskyef4558a2013-02-06 20:43:57 +0000157 Opc = getLEArOpcode(IsLP64);
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000158 else
159 Opc = isSub
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000160 ? getSUBriOpcode(IsLP64, Offset)
161 : getADDriOpcode(IsLP64, Offset);
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000162
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000163 uint64_t Chunk = (1LL << 31) - 1;
Eric Christopherf4fba5c2012-10-03 08:10:01 +0000164 DebugLoc DL = MBB.findDebugLoc(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000165
166 while (Offset) {
167 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
Evan Cheng65089fc2011-01-03 22:53:22 +0000168 if (ThisVal == (Is64Bit ? 8 : 4)) {
169 // Use push / pop instead.
170 unsigned Reg = isSub
Dale Johannesene45a2382011-01-04 19:31:24 +0000171 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
Evan Cheng65089fc2011-01-03 22:53:22 +0000172 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
173 if (Reg) {
174 Opc = isSub
175 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
176 : (Is64Bit ? X86::POP64r : X86::POP32r);
Charles Davis7ed40cb2011-06-12 01:45:54 +0000177 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
Evan Cheng65089fc2011-01-03 22:53:22 +0000178 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
Charles Davis7ed40cb2011-06-12 01:45:54 +0000179 if (isSub)
180 MI->setFlag(MachineInstr::FrameSetup);
Evan Cheng65089fc2011-01-03 22:53:22 +0000181 Offset -= ThisVal;
182 continue;
183 }
184 }
185
Craig Topper062a2ba2014-04-25 05:30:21 +0000186 MachineInstr *MI = nullptr;
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000187
188 if (UseLEA) {
189 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
190 StackPtr, false, isSub ? -ThisVal : ThisVal);
191 } else {
192 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
193 .addReg(StackPtr)
194 .addImm(ThisVal);
195 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
196 }
197
Charles Davis7ed40cb2011-06-12 01:45:54 +0000198 if (isSub)
199 MI->setFlag(MachineInstr::FrameSetup);
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000200
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000201 Offset -= ThisVal;
202 }
203}
204
205/// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
206static
207void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
Craig Topper062a2ba2014-04-25 05:30:21 +0000208 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000209 if (MBBI == MBB.begin()) return;
210
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000211 MachineBasicBlock::iterator PI = std::prev(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000212 unsigned Opc = PI->getOpcode();
213 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000214 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
215 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000216 PI->getOperand(0).getReg() == StackPtr) {
217 if (NumBytes)
218 *NumBytes += PI->getOperand(2).getImm();
219 MBB.erase(PI);
220 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
221 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
222 PI->getOperand(0).getReg() == StackPtr) {
223 if (NumBytes)
224 *NumBytes -= PI->getOperand(2).getImm();
225 MBB.erase(PI);
226 }
227}
228
Eric Christopher4237bf12014-04-29 00:16:33 +0000229/// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
230/// iterator.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000231static
232void mergeSPUpdatesDown(MachineBasicBlock &MBB,
233 MachineBasicBlock::iterator &MBBI,
Craig Topper062a2ba2014-04-25 05:30:21 +0000234 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
Sanjoy Dasf60485c2011-12-01 19:15:08 +0000235 // FIXME: THIS ISN'T RUN!!!
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000236 return;
237
238 if (MBBI == MBB.end()) return;
239
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000240 MachineBasicBlock::iterator NI = std::next(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000241 if (NI == MBB.end()) return;
242
243 unsigned Opc = NI->getOpcode();
244 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
245 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
246 NI->getOperand(0).getReg() == StackPtr) {
247 if (NumBytes)
248 *NumBytes -= NI->getOperand(2).getImm();
249 MBB.erase(NI);
250 MBBI = NI;
251 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
252 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
253 NI->getOperand(0).getReg() == StackPtr) {
254 if (NumBytes)
255 *NumBytes += NI->getOperand(2).getImm();
256 MBB.erase(NI);
257 MBBI = NI;
258 }
259}
260
261/// mergeSPUpdates - Checks the instruction before/after the passed
Eric Christopher4237bf12014-04-29 00:16:33 +0000262/// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
263/// the stack adjustment is returned as a positive value for ADD/LEA and a
264/// negative for SUB.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000265static int mergeSPUpdates(MachineBasicBlock &MBB,
Eric Christopher4237bf12014-04-29 00:16:33 +0000266 MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
267 bool doMergeWithPrevious) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000268 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
269 (!doMergeWithPrevious && MBBI == MBB.end()))
270 return 0;
271
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000272 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
Craig Topper062a2ba2014-04-25 05:30:21 +0000273 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
274 : std::next(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000275 unsigned Opc = PI->getOpcode();
276 int Offset = 0;
277
278 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000279 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
280 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000281 PI->getOperand(0).getReg() == StackPtr){
282 Offset += PI->getOperand(2).getImm();
283 MBB.erase(PI);
284 if (!doMergeWithPrevious) MBBI = NI;
285 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
286 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
287 PI->getOperand(0).getReg() == StackPtr) {
288 Offset -= PI->getOperand(2).getImm();
289 MBB.erase(PI);
290 if (!doMergeWithPrevious) MBBI = NI;
291 }
292
293 return Offset;
294}
295
296static bool isEAXLiveIn(MachineFunction &MF) {
297 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
298 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
299 unsigned Reg = II->first;
300
301 if (Reg == X86::EAX || Reg == X86::AX ||
302 Reg == X86::AH || Reg == X86::AL)
303 return true;
304 }
305
306 return false;
307}
308
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000309void
310X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
311 MachineBasicBlock::iterator MBBI,
312 DebugLoc DL) const {
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000313 MachineFunction &MF = *MBB.getParent();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000314 MachineFrameInfo *MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000315 MachineModuleInfo &MMI = MF.getMMI();
Bill Wendlingbc07a892013-06-18 07:20:20 +0000316 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +0000317 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000318
319 // Add callee saved registers to move list.
320 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
321 if (CSI.empty()) return;
322
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000323 // Calculate offsets.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000324 for (std::vector<CalleeSavedInfo>::const_iterator
325 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
326 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
327 unsigned Reg = I->getReg();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000328
Bill Wendlingbc07a892013-06-18 07:20:20 +0000329 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000330 unsigned CFIIndex =
Craig Topper062a2ba2014-04-25 05:30:21 +0000331 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
332 Offset));
Eric Christopher612bb692014-04-29 00:16:46 +0000333 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
334 .addCFIIndex(CFIIndex);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000335 }
336}
337
Nadav Rotem1bef5a02012-12-23 07:30:09 +0000338/// usesTheStack - This function checks if any of the users of EFLAGS
Nadav Rotemd5aae982012-12-21 23:48:49 +0000339/// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
340/// to use the stack, and if we don't adjust the stack we clobber the first
341/// frame index.
Nadav Rotem1bef5a02012-12-23 07:30:09 +0000342/// See X86InstrInfo::copyPhysReg.
Bill Wendling28519072013-08-15 18:46:14 +0000343static bool usesTheStack(const MachineFunction &MF) {
344 const MachineRegisterInfo &MRI = MF.getRegInfo();
Nadav Rotemd5aae982012-12-21 23:48:49 +0000345
Owen Anderson16c6bf42014-03-13 23:12:04 +0000346 for (MachineRegisterInfo::reg_instr_iterator
347 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
348 ri != re; ++ri)
Nadav Rotemd5aae982012-12-21 23:48:49 +0000349 if (ri->isCopy())
350 return true;
351
352 return false;
353}
354
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000355/// emitPrologue - Push callee-saved registers onto the stack, which
356/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
357/// space for local variables. Also emit labels used by the exception handler to
358/// generate the exception handling frames.
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000359
360/*
361 Here's a gist of what gets emitted:
362
363 ; Establish frame pointer, if needed
364 [if needs FP]
365 push %rbp
366 .cfi_def_cfa_offset 16
367 .cfi_offset %rbp, -16
368 .seh_pushreg %rpb
369 mov %rsp, %rbp
370 .cfi_def_cfa_register %rbp
371
372 ; Spill general-purpose registers
373 [for all callee-saved GPRs]
374 pushq %<reg>
375 [if not needs FP]
376 .cfi_def_cfa_offset (offset from RETADDR)
377 .seh_pushreg %<reg>
378
379 ; If the required stack alignment > default stack alignment
380 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
381 ; of unknown size in the stack frame.
382 [if stack needs re-alignment]
383 and $MASK, %rsp
384
385 ; Allocate space for locals
386 [if target is Windows and allocated space > 4096 bytes]
387 ; Windows needs special care for allocations larger
388 ; than one page.
389 mov $NNN, %rax
390 call ___chkstk_ms/___chkstk
391 sub %rax, %rsp
392 [else]
393 sub $NNN, %rsp
394
395 [if needs FP]
396 .seh_stackalloc (size of XMM spill slots)
397 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
398 [else]
399 .seh_stackalloc NNN
400
401 ; Spill XMMs
402 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
403 ; they may get spilled on any platform, if the current function
404 ; calls @llvm.eh.unwind.init
405 [if needs FP]
406 [for all callee-saved XMM registers]
407 movaps %<xmm reg>, -MMM(%rbp)
408 [for all callee-saved XMM registers]
409 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
410 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
411 [else]
412 [for all callee-saved XMM registers]
413 movaps %<xmm reg>, KKK(%rsp)
414 [for all callee-saved XMM registers]
415 .seh_savexmm %<xmm reg>, KKK
416
417 .seh_endprologue
418
419 [if needs base pointer]
420 mov %rsp, %rbx
421
422 ; Emit CFI info
423 [if needs FP]
424 [for all callee-saved registers]
425 .cfi_offset %<reg>, (offset from %rbp)
426 [else]
427 .cfi_def_cfa_offset (offset from RETADDR)
428 [for all callee-saved registers]
429 .cfi_offset %<reg>, (offset from %rsp)
430
431 Notes:
432 - .seh directives are emitted only for Windows 64 ABI
433 - .cfi directives are emitted for all other ABIs
434 - for 32-bit code, substitute %e?? registers for %r??
435*/
436
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000437void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000438 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
439 MachineBasicBlock::iterator MBBI = MBB.begin();
440 MachineFrameInfo *MFI = MF.getFrameInfo();
441 const Function *Fn = MF.getFunction();
Eric Christopherfc6de422014-08-05 02:39:49 +0000442 const X86RegisterInfo *RegInfo =
443 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
444 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000445 MachineModuleInfo &MMI = MF.getMMI();
446 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000447 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
448 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000449 bool HasFP = hasFP(MF);
Eric Christopherf4381642014-06-05 22:00:31 +0000450 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000451 bool Is64Bit = STI.is64Bit();
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000452 bool IsLP64 = STI.isTarget64BitLP64();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000453 bool IsWin64 = STI.isTargetWin64();
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000454 bool IsWinEH =
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000455 MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000456 ExceptionHandling::WinEH; // Not necessarily synonymous with IsWin64.
457 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000458 bool NeedsDwarfCFI =
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000459 !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000460 bool UseLEA = STI.useLeaForSP();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000461 unsigned StackAlign = getStackAlignment();
462 unsigned SlotSize = RegInfo->getSlotSize();
463 unsigned FramePtr = RegInfo->getFrameRegister(MF);
464 unsigned StackPtr = RegInfo->getStackRegister();
Chad Rosierbdb08ac2012-07-10 17:45:53 +0000465 unsigned BasePtr = RegInfo->getBaseRegister();
Bill Wendlingf27e3312013-09-10 00:20:27 +0000466 DebugLoc DL;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000467
468 // If we're forcing a stack realignment we can't rely on just the frame
469 // info, we need to know the ABI stack alignment as well in case we
470 // have a call out. Otherwise just make sure we have some alignment - we'll
471 // go with the minimum SlotSize.
472 if (ForceStackAlign) {
473 if (MFI->hasCalls())
474 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
475 else if (MaxAlign < SlotSize)
476 MaxAlign = SlotSize;
477 }
478
479 // Add RETADDR move area to callee saved frame size.
480 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
481 if (TailCallReturnAddrDelta < 0)
482 X86FI->setCalleeSavedFrameSize(
483 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
484
485 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
486 // function, and use up to 128 bytes of stack space, don't have a frame
487 // pointer, calls, or dynamic alloca then we do not need to adjust the
Nadav Rotemd5aae982012-12-21 23:48:49 +0000488 // stack pointer (we fit in the Red Zone). We also check that we don't
489 // push and pop from the stack.
Bill Wendling698e84f2012-12-30 10:32:01 +0000490 if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
491 Attribute::NoRedZone) &&
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000492 !RegInfo->needsStackRealignment(MF) &&
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000493 !MFI->hasVarSizedObjects() && // No dynamic alloca.
494 !MFI->adjustsStack() && // No calls.
495 !IsWin64 && // Win64 has no Red Zone
Nadav Rotem1bef5a02012-12-23 07:30:09 +0000496 !usesTheStack(MF) && // Don't push and pop.
Reid Kleckner9c658212014-04-10 22:58:43 +0000497 !MF.shouldSplitStack()) { // Regular stack
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000498 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
499 if (HasFP) MinSize += SlotSize;
500 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
501 MFI->setStackSize(StackSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000502 }
503
504 // Insert stack pointer adjustment for later moving of return addr. Only
505 // applies to tail call optimized functions where the callee argument stack
506 // size is bigger than the callers.
507 if (TailCallReturnAddrDelta < 0) {
508 MachineInstr *MI =
509 BuildMI(MBB, MBBI, DL,
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000510 TII.get(getSUBriOpcode(IsLP64, -TailCallReturnAddrDelta)),
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000511 StackPtr)
512 .addReg(StackPtr)
Charles Davis7ed40cb2011-06-12 01:45:54 +0000513 .addImm(-TailCallReturnAddrDelta)
514 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000515 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
516 }
517
518 // Mapping for machine moves:
519 //
520 // DST: VirtualFP AND
521 // SRC: VirtualFP => DW_CFA_def_cfa_offset
522 // ELSE => DW_CFA_def_cfa
523 //
524 // SRC: VirtualFP AND
525 // DST: Register => DW_CFA_def_cfa_register
526 //
527 // ELSE
528 // OFFSET < 0 => DW_CFA_offset_extended_sf
529 // REG < 64 => DW_CFA_offset + Reg
530 // ELSE => DW_CFA_offset_extended
531
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000532 uint64_t NumBytes = 0;
Michael Liao6d810bd2012-10-25 06:29:14 +0000533 int stackGrowth = -SlotSize;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000534
535 if (HasFP) {
536 // Calculate required stack adjustment.
537 uint64_t FrameSize = StackSize - SlotSize;
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000538 if (RegInfo->needsStackRealignment(MF)) {
539 // Callee-saved registers are pushed on stack before the stack
540 // is realigned.
541 FrameSize -= X86FI->getCalleeSavedFrameSize();
542 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
543 } else {
544 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
545 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000546
547 // Get the offset of the stack slot for the EBP register, which is
548 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
549 // Update the frame offset adjustment.
550 MFI->setOffsetAdjustment(-NumBytes);
551
552 // Save EBP/RBP into the appropriate stack slot.
553 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
Charles Davis7ed40cb2011-06-12 01:45:54 +0000554 .addReg(FramePtr, RegState::Kill)
555 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000556
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000557 if (NeedsDwarfCFI) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000558 // Mark the place where EBP/RBP was saved.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000559 // Define the current CFA rule to use the provided offset.
Rafael Espindola84ee6c42013-05-15 22:27:35 +0000560 assert(StackSize);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000561 unsigned CFIIndex = MMI.addFrameInst(
Craig Topper062a2ba2014-04-25 05:30:21 +0000562 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
Eric Christopher612bb692014-04-29 00:16:46 +0000563 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000564 .addCFIIndex(CFIIndex);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000565
566 // Change the rule for the FramePtr to be an "offset" rule.
Rafael Espindolab08d2c22013-05-16 21:02:15 +0000567 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(FramePtr, true);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000568 CFIIndex = MMI.addFrameInst(
Craig Topper062a2ba2014-04-25 05:30:21 +0000569 MCCFIInstruction::createOffset(nullptr,
570 DwarfFramePtr, 2 * stackGrowth));
Eric Christopher612bb692014-04-29 00:16:46 +0000571 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000572 .addCFIIndex(CFIIndex);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000573 }
574
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000575 if (NeedsWinEH) {
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000576 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
577 .addImm(FramePtr)
578 .setMIFlag(MachineInstr::FrameSetup);
579 }
580
Bill Wendlingb97270d2011-07-25 18:00:28 +0000581 // Update EBP with the new base value.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000582 BuildMI(MBB, MBBI, DL,
583 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
Charles Davis7ed40cb2011-06-12 01:45:54 +0000584 .addReg(StackPtr)
585 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000586
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000587 if (NeedsDwarfCFI) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000588 // Mark effective beginning of when frame pointer becomes valid.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000589 // Define the current CFA to use the EBP/RBP register.
Rafael Espindolab08d2c22013-05-16 21:02:15 +0000590 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(FramePtr, true);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000591 unsigned CFIIndex = MMI.addFrameInst(
Craig Topper062a2ba2014-04-25 05:30:21 +0000592 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
Eric Christopher612bb692014-04-29 00:16:46 +0000593 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000594 .addCFIIndex(CFIIndex);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000595 }
596
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000597 // Mark the FramePtr as live-in in every block.
598 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000599 I->addLiveIn(FramePtr);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000600 } else {
601 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
602 }
603
604 // Skip the callee-saved push instructions.
605 bool PushedRegs = false;
606 int StackOffset = 2 * stackGrowth;
607
608 while (MBBI != MBB.end() &&
609 (MBBI->getOpcode() == X86::PUSH32r ||
610 MBBI->getOpcode() == X86::PUSH64r)) {
611 PushedRegs = true;
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000612 unsigned Reg = MBBI->getOperand(0).getReg();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000613 ++MBBI;
614
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000615 if (!HasFP && NeedsDwarfCFI) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000616 // Mark callee-saved push instruction.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000617 // Define the current CFA rule to use the provided offset.
Rafael Espindola72421862013-05-16 04:59:17 +0000618 assert(StackSize);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000619 unsigned CFIIndex = MMI.addFrameInst(
620 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
Eric Christopher612bb692014-04-29 00:16:46 +0000621 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000622 .addCFIIndex(CFIIndex);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000623 StackOffset += stackGrowth;
624 }
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000625
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000626 if (NeedsWinEH) {
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000627 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
628 MachineInstr::FrameSetup);
629 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000630 }
631
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000632 // Realign stack after we pushed callee-saved registers (so that we'll be
633 // able to calculate their offsets from the frame pointer).
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000634 if (RegInfo->needsStackRealignment(MF)) {
635 assert(HasFP && "There should be a frame pointer if stack is realigned.");
636 MachineInstr *MI =
637 BuildMI(MBB, MBBI, DL,
638 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
639 .addReg(StackPtr)
640 .addImm(-MaxAlign)
641 .setMIFlag(MachineInstr::FrameSetup);
642
643 // The EFLAGS implicit def is dead.
644 MI->getOperand(3).setIsDead();
645 }
646
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000647 // If there is an SUB32ri of ESP immediately before this instruction, merge
648 // the two. This can be the case when tail call elimination is enabled and
649 // the callee has more arguments then the caller.
650 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
651
652 // If there is an ADD32ri or SUB32ri of ESP immediately after this
653 // instruction, merge the two instructions.
654 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
655
656 // Adjust stack pointer: ESP -= numbytes.
657
658 // Windows and cygwin/mingw require a prologue helper routine when allocating
659 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
660 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
661 // stack and adjust the stack pointer in one go. The 64-bit version of
662 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
663 // responsible for adjusting the stack pointer. Touching the stack at 4K
664 // increments is necessary to ensure that the guard pages used by the OS
665 // virtual memory manager are allocated in correct sequence.
Tim Northover9653eb52013-12-10 16:57:43 +0000666 if (NumBytes >= 4096 && STI.isOSWindows() && !STI.isTargetMacho()) {
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000667 const char *StackProbeSymbol;
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000668
669 if (Is64Bit) {
Kai Nacke87b23ae2013-12-13 05:37:05 +0000670 if (STI.isTargetCygMing()) {
671 StackProbeSymbol = "___chkstk_ms";
672 } else {
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000673 StackProbeSymbol = "__chkstk";
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000674 }
675 } else if (STI.isTargetCygMing())
676 StackProbeSymbol = "_alloca";
677 else
678 StackProbeSymbol = "_chkstk";
679
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000680 // Check whether EAX is livein for this function.
681 bool isEAXAlive = isEAXLiveIn(MF);
682
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000683 if (isEAXAlive) {
684 // Sanity check that EAX is not livein for this function.
685 // It should not be, so throw an assert.
686 assert(!Is64Bit && "EAX is livein in x64 case!");
687
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000688 // Save EAX
689 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
Bill Wendling28b6e122011-07-21 00:44:56 +0000690 .addReg(X86::EAX, RegState::Kill)
691 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000692 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000693
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000694 if (Is64Bit) {
695 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
696 // Function prologue is responsible for adjusting the stack pointer.
697 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
Bill Wendling28b6e122011-07-21 00:44:56 +0000698 .addImm(NumBytes)
699 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000700 } else {
701 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
702 // We'll also use 4 already allocated bytes for EAX.
703 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
Bill Wendling28b6e122011-07-21 00:44:56 +0000704 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
705 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000706 }
707
708 BuildMI(MBB, MBBI, DL,
709 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
710 .addExternalSymbol(StackProbeSymbol)
711 .addReg(StackPtr, RegState::Define | RegState::Implicit)
Bill Wendling28b6e122011-07-21 00:44:56 +0000712 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
713 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000714
Kai Nacke87b23ae2013-12-13 05:37:05 +0000715 if (Is64Bit) {
716 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
717 // themself. It also does not clobber %rax so we can reuse it when
718 // adjusting %rsp.
Nico Rieck51969be2013-07-08 11:20:11 +0000719 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), StackPtr)
720 .addReg(StackPtr)
721 .addReg(X86::RAX)
722 .setMIFlag(MachineInstr::FrameSetup);
723 }
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000724 if (isEAXAlive) {
725 // Restore EAX
726 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
727 X86::EAX),
728 StackPtr, false, NumBytes - 4);
Bill Wendling28b6e122011-07-21 00:44:56 +0000729 MI->setFlag(MachineInstr::FrameSetup);
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000730 MBB.insert(MBBI, MI);
731 }
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000732 } else if (NumBytes) {
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000733 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, IsLP64,
Eric Christopherf4fba5c2012-10-03 08:10:01 +0000734 UseLEA, TII, *RegInfo);
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000735 }
736
737 int SEHFrameOffset = 0;
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000738 if (NeedsWinEH) {
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000739 if (HasFP) {
740 // We need to set frame base offset low enough such that all saved
741 // register offsets would be positive relative to it, but we can't
742 // just use NumBytes, because .seh_setframe offset must be <=240.
743 // So we pretend to have only allocated enough space to spill the
744 // non-volatile registers.
745 // We don't care about the rest of stack allocation, because unwinder
746 // will restore SP to (BP - SEHFrameOffset)
747 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
748 int offset = MFI->getObjectOffset(Info.getFrameIdx());
749 SEHFrameOffset = std::max(SEHFrameOffset, abs(offset));
750 }
751 SEHFrameOffset += SEHFrameOffset % 16; // ensure alignmant
752
753 // This only needs to account for XMM spill slots, GPR slots
Reid Klecknerb5dd9452014-07-01 00:42:47 +0000754 // are covered by the .seh_pushreg's emitted above.
755 unsigned Size = SEHFrameOffset - X86FI->getCalleeSavedFrameSize();
756 if (Size) {
757 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
758 .addImm(Size)
759 .setMIFlag(MachineInstr::FrameSetup);
760 }
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000761
762 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
763 .addImm(FramePtr)
764 .addImm(SEHFrameOffset)
765 .setMIFlag(MachineInstr::FrameSetup);
766 } else {
767 // SP will be the base register for restoring XMMs
768 if (NumBytes) {
769 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
770 .addImm(NumBytes)
771 .setMIFlag(MachineInstr::FrameSetup);
772 }
773 }
774 }
775
776 // Skip the rest of register spilling code
777 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
778 ++MBBI;
779
780 // Emit SEH info for non-GPRs
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000781 if (NeedsWinEH) {
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000782 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
783 unsigned Reg = Info.getReg();
784 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
785 continue;
786 assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
787
788 int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
789 Offset += SEHFrameOffset;
790
791 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
792 .addImm(Reg)
793 .addImm(Offset)
794 .setMIFlag(MachineInstr::FrameSetup);
795 }
796
797 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
798 .setMIFlag(MachineInstr::FrameSetup);
799 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000800
Chad Rosierbdb08ac2012-07-10 17:45:53 +0000801 // If we need a base pointer, set it up here. It's whatever the value
802 // of the stack pointer is at this point. Any variable size objects
803 // will be allocated after this, so we can still use the base pointer
804 // to reference locals.
805 if (RegInfo->hasBasePointer(MF)) {
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000806 // Update the base pointer with the current stack pointer.
Chad Rosierbdb08ac2012-07-10 17:45:53 +0000807 unsigned Opc = Is64Bit ? X86::MOV64rr : X86::MOV32rr;
808 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
809 .addReg(StackPtr)
810 .setMIFlag(MachineInstr::FrameSetup);
Chad Rosierbdb08ac2012-07-10 17:45:53 +0000811 }
812
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000813 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000814 // Mark end of stack pointer adjustment.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000815 if (!HasFP && NumBytes) {
816 // Define the current CFA rule to use the provided offset.
Rafael Espindola84ee6c42013-05-15 22:27:35 +0000817 assert(StackSize);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000818 unsigned CFIIndex = MMI.addFrameInst(
Craig Topper062a2ba2014-04-25 05:30:21 +0000819 MCCFIInstruction::createDefCfaOffset(nullptr,
820 -StackSize + stackGrowth));
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000821
Eric Christopher612bb692014-04-29 00:16:46 +0000822 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000823 .addCFIIndex(CFIIndex);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000824 }
825
826 // Emit DWARF info specifying the offsets of the callee-saved registers.
827 if (PushedRegs)
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000828 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000829 }
830}
831
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000832void X86FrameLowering::emitEpilogue(MachineFunction &MF,
Nick Lewycky34a425b2011-06-14 03:23:52 +0000833 MachineBasicBlock &MBB) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000834 const MachineFrameInfo *MFI = MF.getFrameInfo();
835 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Eric Christopherfc6de422014-08-05 02:39:49 +0000836 const X86RegisterInfo *RegInfo =
837 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
838 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000839 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
840 assert(MBBI != MBB.end() && "Returning block has no instructions");
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000841 unsigned RetOpcode = MBBI->getOpcode();
842 DebugLoc DL = MBBI->getDebugLoc();
Eric Christopherf4381642014-06-05 22:00:31 +0000843 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000844 bool Is64Bit = STI.is64Bit();
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000845 bool IsLP64 = STI.isTarget64BitLP64();
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000846 bool UseLEA = STI.useLeaForSP();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000847 unsigned StackAlign = getStackAlignment();
848 unsigned SlotSize = RegInfo->getSlotSize();
849 unsigned FramePtr = RegInfo->getFrameRegister(MF);
850 unsigned StackPtr = RegInfo->getStackRegister();
851
Reid Klecknere7040102014-08-04 21:05:27 +0000852 bool IsWinEH =
853 MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
854 ExceptionHandling::WinEH;
855 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
856
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000857 switch (RetOpcode) {
858 default:
859 llvm_unreachable("Can only insert epilog into returning blocks");
David Woodhouse79dd5052014-01-08 12:58:07 +0000860 case X86::RETQ:
861 case X86::RETL:
David Woodhouse4e033b02014-01-13 14:05:59 +0000862 case X86::RETIL:
863 case X86::RETIQ:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000864 case X86::TCRETURNdi:
865 case X86::TCRETURNri:
866 case X86::TCRETURNmi:
867 case X86::TCRETURNdi64:
868 case X86::TCRETURNri64:
869 case X86::TCRETURNmi64:
870 case X86::EH_RETURN:
871 case X86::EH_RETURN64:
872 break; // These are ok
873 }
874
875 // Get the number of bytes to allocate from the FrameInfo.
876 uint64_t StackSize = MFI->getStackSize();
877 uint64_t MaxAlign = MFI->getMaxAlignment();
878 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
879 uint64_t NumBytes = 0;
880
881 // If we're forcing a stack realignment we can't rely on just the frame
882 // info, we need to know the ABI stack alignment as well in case we
883 // have a call out. Otherwise just make sure we have some alignment - we'll
884 // go with the minimum.
885 if (ForceStackAlign) {
886 if (MFI->hasCalls())
887 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
888 else
889 MaxAlign = MaxAlign ? MaxAlign : 4;
890 }
891
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000892 if (hasFP(MF)) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000893 // Calculate required stack adjustment.
894 uint64_t FrameSize = StackSize - SlotSize;
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000895 if (RegInfo->needsStackRealignment(MF)) {
896 // Callee-saved registers were pushed on stack before the stack
897 // was realigned.
898 FrameSize -= CSSize;
899 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
900 } else {
901 NumBytes = FrameSize - CSSize;
902 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000903
904 // Pop EBP.
905 BuildMI(MBB, MBBI, DL,
906 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
907 } else {
908 NumBytes = StackSize - CSSize;
909 }
910
911 // Skip the callee-saved pop instructions.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000912 while (MBBI != MBB.begin()) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000913 MachineBasicBlock::iterator PI = std::prev(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000914 unsigned Opc = PI->getOpcode();
915
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000916 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
Evan Cheng7f8e5632011-12-07 07:15:52 +0000917 !PI->isTerminator())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000918 break;
919
920 --MBBI;
921 }
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000922 MachineBasicBlock::iterator FirstCSPop = MBBI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000923
924 DL = MBBI->getDebugLoc();
925
926 // If there is an ADD32ri or SUB32ri of ESP immediately before this
927 // instruction, merge the two instructions.
928 if (NumBytes || MFI->hasVarSizedObjects())
929 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
930
931 // If dynamic alloca is used, then reset esp to point to the last callee-saved
932 // slot before popping them off! Same applies for the case, when stack was
933 // realigned.
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000934 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
935 if (RegInfo->needsStackRealignment(MF))
936 MBBI = FirstCSPop;
937 if (CSSize != 0) {
Eli Benderskyef4558a2013-02-06 20:43:57 +0000938 unsigned Opc = getLEArOpcode(IsLP64);
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000939 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
940 FramePtr, false, -CSSize);
Reid Klecknere7040102014-08-04 21:05:27 +0000941 --MBBI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000942 } else {
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000943 unsigned Opc = (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
944 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000945 .addReg(FramePtr);
Reid Klecknere7040102014-08-04 21:05:27 +0000946 --MBBI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000947 }
948 } else if (NumBytes) {
949 // Adjust stack pointer back: ESP += numbytes.
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000950 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, IsLP64, UseLEA,
951 TII, *RegInfo);
Reid Klecknere7040102014-08-04 21:05:27 +0000952 --MBBI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000953 }
954
Reid Klecknere7040102014-08-04 21:05:27 +0000955 // Windows unwinder will not invoke function's exception handler if IP is
956 // either in prologue or in epilogue. This behavior causes a problem when a
957 // call immediately precedes an epilogue, because the return address points
958 // into the epilogue. To cope with that, we insert an epilogue marker here,
959 // then replace it with a 'nop' if it ends up immediately after a CALL in the
960 // final emitted code.
961 if (NeedsWinEH)
962 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
963
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000964 // We're returning from function via eh_return.
965 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000966 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000967 MachineOperand &DestAddr = MBBI->getOperand(0);
968 assert(DestAddr.isReg() && "Offset should be in register!");
969 BuildMI(MBB, MBBI, DL,
970 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
971 StackPtr).addReg(DestAddr.getReg());
972 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
973 RetOpcode == X86::TCRETURNmi ||
974 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
975 RetOpcode == X86::TCRETURNmi64) {
976 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
977 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesenbbb1a542011-01-13 22:47:43 +0000978 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000979 MachineOperand &JumpTarget = MBBI->getOperand(0);
980 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
981 assert(StackAdjust.isImm() && "Expecting immediate value.");
982
983 // Adjust stack pointer.
984 int StackAdj = StackAdjust.getImm();
985 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
986 int Offset = 0;
987 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
988
989 // Incoporate the retaddr area.
990 Offset = StackAdj-MaxTCDelta;
991 assert(Offset >= 0 && "Offset should never be negative");
992
993 if (Offset) {
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000994 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000995 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000996 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, IsLP64,
997 UseLEA, TII, *RegInfo);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000998 }
999
1000 // Jump to label or value in register.
1001 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
Evan Chengd4b08732010-11-30 23:55:39 +00001002 MachineInstrBuilder MIB =
1003 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1004 ? X86::TAILJMPd : X86::TAILJMPd64));
1005 if (JumpTarget.isGlobal())
1006 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1007 JumpTarget.getTargetFlags());
1008 else {
1009 assert(JumpTarget.isSymbol());
1010 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1011 JumpTarget.getTargetFlags());
1012 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001013 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1014 MachineInstrBuilder MIB =
1015 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1016 ? X86::TAILJMPm : X86::TAILJMPm64));
1017 for (unsigned i = 0; i != 5; ++i)
1018 MIB.addOperand(MBBI->getOperand(i));
1019 } else if (RetOpcode == X86::TCRETURNri64) {
1020 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1021 addReg(JumpTarget.getReg(), RegState::Kill);
1022 } else {
1023 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1024 addReg(JumpTarget.getReg(), RegState::Kill);
1025 }
1026
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001027 MachineInstr *NewMI = std::prev(MBBI);
Jakob Stoklund Olesen33f5d142012-12-20 22:54:02 +00001028 NewMI->copyImplicitOps(MF, MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001029
1030 // Delete the pseudo instruction TCRETURN.
1031 MBB.erase(MBBI);
David Woodhouse4e033b02014-01-13 14:05:59 +00001032 } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
1033 RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
1034 (X86FI->getTCReturnAddrDelta() < 0)) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001035 // Add the return addr area delta back since we are not tail calling.
1036 int delta = -1*X86FI->getTCReturnAddrDelta();
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +00001037 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001038
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001039 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001040 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Eli Bendersky44a40ca2013-02-05 21:53:29 +00001041 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, IsLP64, UseLEA, TII,
1042 *RegInfo);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001043 }
1044}
Anton Korobeynikov14ee3442010-11-18 23:25:52 +00001045
Eric Christopher4237bf12014-04-29 00:16:33 +00001046int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1047 int FI) const {
Eric Christopherfc6de422014-08-05 02:39:49 +00001048 const X86RegisterInfo *RegInfo =
1049 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +00001050 const MachineFrameInfo *MFI = MF.getFrameInfo();
1051 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1052 uint64_t StackSize = MFI->getStackSize();
1053
Chad Rosierbdb08ac2012-07-10 17:45:53 +00001054 if (RegInfo->hasBasePointer(MF)) {
1055 assert (hasFP(MF) && "VLAs and dynamic stack realign, but no FP?!");
1056 if (FI < 0) {
1057 // Skip the saved EBP.
1058 return Offset + RegInfo->getSlotSize();
1059 } else {
1060 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1061 return Offset + StackSize;
1062 }
1063 } else if (RegInfo->needsStackRealignment(MF)) {
Anton Korobeynikov46877782010-11-20 15:59:32 +00001064 if (FI < 0) {
1065 // Skip the saved EBP.
Chad Rosier20b79dc2012-05-23 23:45:10 +00001066 return Offset + RegInfo->getSlotSize();
Anton Korobeynikov46877782010-11-20 15:59:32 +00001067 } else {
Duncan Sandsd278d352011-10-18 12:44:00 +00001068 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
Anton Korobeynikov46877782010-11-20 15:59:32 +00001069 return Offset + StackSize;
1070 }
1071 // FIXME: Support tail calls
1072 } else {
1073 if (!hasFP(MF))
1074 return Offset + StackSize;
1075
1076 // Skip the saved EBP.
Chad Rosier20b79dc2012-05-23 23:45:10 +00001077 Offset += RegInfo->getSlotSize();
Anton Korobeynikov46877782010-11-20 15:59:32 +00001078
1079 // Skip the RETADDR move area
1080 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1081 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1082 if (TailCallReturnAddrDelta < 0)
1083 Offset -= TailCallReturnAddrDelta;
1084 }
1085
1086 return Offset;
1087}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001088
Alexey Samsonovc4b3ad82012-05-01 15:16:06 +00001089int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1090 unsigned &FrameReg) const {
Eric Christopherfc6de422014-08-05 02:39:49 +00001091 const X86RegisterInfo *RegInfo =
1092 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
Alexey Samsonovc4b3ad82012-05-01 15:16:06 +00001093 // We can't calculate offset from frame pointer if the stack is realigned,
Chad Rosierbdb08ac2012-07-10 17:45:53 +00001094 // so enforce usage of stack/base pointer. The base pointer is used when we
1095 // have dynamic allocas in addition to dynamic realignment.
1096 if (RegInfo->hasBasePointer(MF))
1097 FrameReg = RegInfo->getBaseRegister();
1098 else if (RegInfo->needsStackRealignment(MF))
1099 FrameReg = RegInfo->getStackRegister();
1100 else
1101 FrameReg = RegInfo->getFrameRegister(MF);
Alexey Samsonovc4b3ad82012-05-01 15:16:06 +00001102 return getFrameIndexOffset(MF, FI);
1103}
1104
NAKAMURA Takumi1db59952014-06-25 12:41:52 +00001105bool X86FrameLowering::assignCalleeSavedSpillSlots(
1106 MachineFunction &MF, const TargetRegisterInfo *TRI,
1107 std::vector<CalleeSavedInfo> &CSI) const {
1108 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +00001109 const X86RegisterInfo *RegInfo =
1110 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
NAKAMURA Takumi1db59952014-06-25 12:41:52 +00001111 unsigned SlotSize = RegInfo->getSlotSize();
1112 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001113
NAKAMURA Takumi1db59952014-06-25 12:41:52 +00001114 unsigned CalleeSavedFrameSize = 0;
1115 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1116
1117 if (hasFP(MF)) {
1118 // emitPrologue always spills frame register the first thing.
1119 SpillSlotOffset -= SlotSize;
1120 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1121
1122 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1123 // the frame register, we can delete it from CSI list and not have to worry
1124 // about avoiding it later.
1125 unsigned FPReg = RegInfo->getFrameRegister(MF);
1126 for (unsigned i = 0; i < CSI.size(); ++i) {
1127 if (CSI[i].getReg() == FPReg) {
1128 CSI.erase(CSI.begin() + i);
1129 break;
1130 }
1131 }
1132 }
1133
1134 // Assign slots for GPRs. It increases frame size.
1135 for (unsigned i = CSI.size(); i != 0; --i) {
1136 unsigned Reg = CSI[i - 1].getReg();
1137
1138 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1139 continue;
1140
1141 SpillSlotOffset -= SlotSize;
1142 CalleeSavedFrameSize += SlotSize;
1143
1144 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1145 CSI[i - 1].setFrameIdx(SlotIndex);
1146 }
1147
1148 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1149
1150 // Assign slots for XMMs.
1151 for (unsigned i = CSI.size(); i != 0; --i) {
1152 unsigned Reg = CSI[i - 1].getReg();
1153 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1154 continue;
1155
1156 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1157 // ensure alignment
1158 SpillSlotOffset -= abs(SpillSlotOffset) % RC->getAlignment();
1159 // spill into slot
1160 SpillSlotOffset -= RC->getSize();
1161 int SlotIndex =
1162 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1163 CSI[i - 1].setFrameIdx(SlotIndex);
1164 MFI->ensureMaxAlignment(RC->getAlignment());
1165 }
1166
1167 return true;
1168}
1169
1170bool X86FrameLowering::spillCalleeSavedRegisters(
1171 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1172 const std::vector<CalleeSavedInfo> &CSI,
1173 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001174 DebugLoc DL = MBB.findDebugLoc(MI);
1175
1176 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +00001177 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Eric Christopherf4381642014-06-05 22:00:31 +00001178 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001179
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001180 // Push GPRs. It increases frame size.
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001181 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1182 for (unsigned i = CSI.size(); i != 0; --i) {
NAKAMURA Takumic403be12014-06-25 12:40:56 +00001183 unsigned Reg = CSI[i - 1].getReg();
1184
1185 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001186 continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001187 // Add the callee-saved register as live-in. It's killed at the spill.
1188 MBB.addLiveIn(Reg);
NAKAMURA Takumi1db59952014-06-25 12:41:52 +00001189
Charles Davis7ed40cb2011-06-12 01:45:54 +00001190 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1191 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001192 }
1193
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001194 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1195 // It can be done by spilling XMMs to stack frame.
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001196 for (unsigned i = CSI.size(); i != 0; --i) {
1197 unsigned Reg = CSI[i-1].getReg();
1198 if (X86::GR64RegClass.contains(Reg) ||
1199 X86::GR32RegClass.contains(Reg))
1200 continue;
1201 // Add the callee-saved register as live-in. It's killed at the spill.
1202 MBB.addLiveIn(Reg);
1203 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
NAKAMURA Takumic403be12014-06-25 12:40:56 +00001204
1205 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1206 TRI);
NAKAMURA Takumi1db59952014-06-25 12:41:52 +00001207 --MI;
1208 MI->setFlag(MachineInstr::FrameSetup);
1209 ++MI;
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001210 }
1211
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001212 return true;
1213}
1214
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001215bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001216 MachineBasicBlock::iterator MI,
1217 const std::vector<CalleeSavedInfo> &CSI,
1218 const TargetRegisterInfo *TRI) const {
1219 if (CSI.empty())
1220 return false;
1221
1222 DebugLoc DL = MBB.findDebugLoc(MI);
1223
1224 MachineFunction &MF = *MBB.getParent();
Eric Christopherfc6de422014-08-05 02:39:49 +00001225 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Eric Christopherf4381642014-06-05 22:00:31 +00001226 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001227
1228 // Reload XMMs from stack frame.
1229 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1230 unsigned Reg = CSI[i].getReg();
1231 if (X86::GR64RegClass.contains(Reg) ||
1232 X86::GR32RegClass.contains(Reg))
1233 continue;
NAKAMURA Takumic403be12014-06-25 12:40:56 +00001234
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001235 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
NAKAMURA Takumic403be12014-06-25 12:40:56 +00001236 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001237 }
1238
1239 // POP GPRs.
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001240 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1241 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1242 unsigned Reg = CSI[i].getReg();
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001243 if (!X86::GR64RegClass.contains(Reg) &&
1244 !X86::GR32RegClass.contains(Reg))
1245 continue;
NAKAMURA Takumi1db59952014-06-25 12:41:52 +00001246
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001247 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001248 }
1249 return true;
1250}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001251
1252void
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001253X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Eric Christopher11b05cc2014-06-05 00:09:05 +00001254 RegScavenger *RS) const {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001255 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +00001256 const X86RegisterInfo *RegInfo =
1257 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001258 unsigned SlotSize = RegInfo->getSlotSize();
1259
1260 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Tim Northoverecc018c2013-08-04 09:35:57 +00001261 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001262
1263 if (TailCallReturnAddrDelta < 0) {
1264 // create RETURNADDR area
1265 // arg
1266 // arg
1267 // RETADDR
1268 // { ...
1269 // RETADDR area
1270 // ...
1271 // }
1272 // [EBP]
1273 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
Tim Northoverecc018c2013-08-04 09:35:57 +00001274 TailCallReturnAddrDelta - SlotSize, true);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001275 }
1276
Chad Rosierbdb08ac2012-07-10 17:45:53 +00001277 // Spill the BasePtr if it's used.
1278 if (RegInfo->hasBasePointer(MF))
1279 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001280}
Rafael Espindolac2174212011-08-30 19:39:58 +00001281
1282static bool
1283HasNestArgument(const MachineFunction *MF) {
1284 const Function *F = MF->getFunction();
1285 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1286 I != E; I++) {
1287 if (I->hasNestAttr())
1288 return true;
1289 }
1290 return false;
1291}
1292
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001293/// GetScratchRegister - Get a temp register for performing work in the
1294/// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1295/// and the properties of the function either one or two registers will be
1296/// needed. Set primary to true for the first register, false for the second.
Rafael Espindolac2174212011-08-30 19:39:58 +00001297static unsigned
Rafael Espindolad90466b2012-01-11 19:00:37 +00001298GetScratchRegister(bool Is64Bit, const MachineFunction &MF, bool Primary) {
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001299 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1300
1301 // Erlang stuff.
1302 if (CallingConvention == CallingConv::HiPE) {
1303 if (Is64Bit)
1304 return Primary ? X86::R14 : X86::R13;
1305 else
1306 return Primary ? X86::EBX : X86::EDI;
1307 }
1308
David Blaikie46a9f012012-01-20 21:51:11 +00001309 if (Is64Bit)
Rafael Espindolad90466b2012-01-11 19:00:37 +00001310 return Primary ? X86::R11 : X86::R12;
Rafael Espindolac2174212011-08-30 19:39:58 +00001311
David Blaikie46a9f012012-01-20 21:51:11 +00001312 bool IsNested = HasNestArgument(&MF);
1313
1314 if (CallingConvention == CallingConv::X86_FastCall ||
1315 CallingConvention == CallingConv::Fast) {
1316 if (IsNested)
1317 report_fatal_error("Segmented stacks does not support fastcall with "
1318 "nested function.");
1319 return Primary ? X86::EAX : X86::ECX;
Rafael Espindolac2174212011-08-30 19:39:58 +00001320 }
David Blaikie46a9f012012-01-20 21:51:11 +00001321 if (IsNested)
1322 return Primary ? X86::EDX : X86::EAX;
1323 return Primary ? X86::ECX : X86::EAX;
Rafael Espindolac2174212011-08-30 19:39:58 +00001324}
1325
Sanjoy Das006e43b2011-12-03 09:32:07 +00001326// The stack limit in the TCB is set to this many bytes above the actual stack
1327// limit.
1328static const uint64_t kSplitStackAvailable = 256;
1329
Rafael Espindolac2174212011-08-30 19:39:58 +00001330void
1331X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1332 MachineBasicBlock &prologueMBB = MF.front();
1333 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherfc6de422014-08-05 02:39:49 +00001334 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Rafael Espindolac2174212011-08-30 19:39:58 +00001335 uint64_t StackSize;
Eric Christopherf4381642014-06-05 22:00:31 +00001336 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
Rafael Espindolac2174212011-08-30 19:39:58 +00001337 bool Is64Bit = STI.is64Bit();
1338 unsigned TlsReg, TlsOffset;
1339 DebugLoc DL;
Rafael Espindolac2174212011-08-30 19:39:58 +00001340
Rafael Espindolad90466b2012-01-11 19:00:37 +00001341 unsigned ScratchReg = GetScratchRegister(Is64Bit, MF, true);
Rafael Espindolac2174212011-08-30 19:39:58 +00001342 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1343 "Scratch register is live-in");
1344
1345 if (MF.getFunction()->isVarArg())
1346 report_fatal_error("Segmented stacks do not support vararg functions.");
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001347 if (!STI.isTargetLinux() && !STI.isTargetDarwin() &&
Reid Kleckner10110272014-04-01 18:34:21 +00001348 !STI.isTargetWin32() && !STI.isTargetWin64() && !STI.isTargetFreeBSD())
Rafael Espindola00e861e2012-01-12 20:24:30 +00001349 report_fatal_error("Segmented stacks not supported on this platform.");
Rafael Espindolac2174212011-08-30 19:39:58 +00001350
Tim Northoverf9e798b2014-05-22 13:03:43 +00001351 // Eventually StackSize will be calculated by a link-time pass; which will
1352 // also decide whether checking code needs to be injected into this particular
1353 // prologue.
1354 StackSize = MFI->getStackSize();
1355
1356 // Do not generate a prologue for functions with a stack of size zero
1357 if (StackSize == 0)
1358 return;
1359
Rafael Espindolac2174212011-08-30 19:39:58 +00001360 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1361 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1362 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1363 bool IsNested = false;
1364
1365 // We need to know if the function has a nest argument only in 64 bit mode.
1366 if (Is64Bit)
1367 IsNested = HasNestArgument(&MF);
1368
Bill Wendling25f6d3e2011-10-13 08:24:19 +00001369 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1370 // allocMBB needs to be last (terminating) instruction.
Bill Wendling25f6d3e2011-10-13 08:24:19 +00001371
Rafael Espindolac2174212011-08-30 19:39:58 +00001372 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1373 e = prologueMBB.livein_end(); i != e; i++) {
1374 allocMBB->addLiveIn(*i);
1375 checkMBB->addLiveIn(*i);
1376 }
1377
1378 if (IsNested)
Rafael Espindola66393c12011-10-26 21:12:27 +00001379 allocMBB->addLiveIn(X86::R10);
1380
Rafael Espindolac2174212011-08-30 19:39:58 +00001381 MF.push_front(allocMBB);
1382 MF.push_front(checkMBB);
1383
Rafael Espindolad90466b2012-01-11 19:00:37 +00001384 // When the frame size is less than 256 we just compare the stack
1385 // boundary directly to the value of the stack pointer, per gcc.
1386 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1387
Rafael Espindolac2174212011-08-30 19:39:58 +00001388 // Read the limit off the current stacklet off the stack_guard location.
1389 if (Is64Bit) {
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001390 if (STI.isTargetLinux()) {
Rafael Espindolad90466b2012-01-11 19:00:37 +00001391 TlsReg = X86::FS;
1392 TlsOffset = 0x70;
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001393 } else if (STI.isTargetDarwin()) {
Rafael Espindolad90466b2012-01-11 19:00:37 +00001394 TlsReg = X86::GS;
1395 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
Reid Kleckner10110272014-04-01 18:34:21 +00001396 } else if (STI.isTargetWin64()) {
1397 TlsReg = X86::GS;
1398 TlsOffset = 0x28; // pvArbitrary, reserved for application use
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001399 } else if (STI.isTargetFreeBSD()) {
Rafael Espindola00e861e2012-01-12 20:24:30 +00001400 TlsReg = X86::FS;
1401 TlsOffset = 0x18;
Rafael Espindola10745d32012-01-12 20:22:08 +00001402 } else {
1403 report_fatal_error("Segmented stacks not supported on this platform.");
Rafael Espindolad90466b2012-01-11 19:00:37 +00001404 }
Rafael Espindolac2174212011-08-30 19:39:58 +00001405
Rafael Espindolad90466b2012-01-11 19:00:37 +00001406 if (CompareStackPointer)
Sanjoy Das006e43b2011-12-03 09:32:07 +00001407 ScratchReg = X86::RSP;
1408 else
1409 BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RSP)
Rafael Espindola6635ae12012-01-11 18:14:03 +00001410 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
Sanjoy Das006e43b2011-12-03 09:32:07 +00001411
Rafael Espindolac2174212011-08-30 19:39:58 +00001412 BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
Rafael Espindola6635ae12012-01-11 18:14:03 +00001413 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
Rafael Espindolac2174212011-08-30 19:39:58 +00001414 } else {
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001415 if (STI.isTargetLinux()) {
Rafael Espindola10745d32012-01-12 20:22:08 +00001416 TlsReg = X86::GS;
1417 TlsOffset = 0x30;
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001418 } else if (STI.isTargetDarwin()) {
Rafael Espindola10745d32012-01-12 20:22:08 +00001419 TlsReg = X86::GS;
1420 TlsOffset = 0x48 + 90*4;
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001421 } else if (STI.isTargetWin32()) {
Rafael Espindola10745d32012-01-12 20:22:08 +00001422 TlsReg = X86::FS;
1423 TlsOffset = 0x14; // pvArbitrary, reserved for application use
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001424 } else if (STI.isTargetFreeBSD()) {
Rafael Espindola00e861e2012-01-12 20:24:30 +00001425 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
Rafael Espindola10745d32012-01-12 20:22:08 +00001426 } else {
1427 report_fatal_error("Segmented stacks not supported on this platform.");
1428 }
Rafael Espindolac2174212011-08-30 19:39:58 +00001429
Rafael Espindolad90466b2012-01-11 19:00:37 +00001430 if (CompareStackPointer)
Sanjoy Das006e43b2011-12-03 09:32:07 +00001431 ScratchReg = X86::ESP;
1432 else
1433 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
Rafael Espindola6635ae12012-01-11 18:14:03 +00001434 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
Sanjoy Das006e43b2011-12-03 09:32:07 +00001435
Reid Kleckner10110272014-04-01 18:34:21 +00001436 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64()) {
Rafael Espindolad90466b2012-01-11 19:00:37 +00001437 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1438 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001439 } else if (STI.isTargetDarwin()) {
Rafael Espindolad90466b2012-01-11 19:00:37 +00001440
Eric Christopher4237bf12014-04-29 00:16:33 +00001441 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
Rafael Espindolad90466b2012-01-11 19:00:37 +00001442 unsigned ScratchReg2;
1443 bool SaveScratch2;
1444 if (CompareStackPointer) {
Eric Christopher4237bf12014-04-29 00:16:33 +00001445 // The primary scratch register is available for holding the TLS offset.
Rafael Espindolad90466b2012-01-11 19:00:37 +00001446 ScratchReg2 = GetScratchRegister(Is64Bit, MF, true);
1447 SaveScratch2 = false;
1448 } else {
1449 // Need to use a second register to hold the TLS offset
1450 ScratchReg2 = GetScratchRegister(Is64Bit, MF, false);
1451
Eric Christopher4237bf12014-04-29 00:16:33 +00001452 // Unfortunately, with fastcc the second scratch register may hold an
1453 // argument.
Rafael Espindolad90466b2012-01-11 19:00:37 +00001454 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1455 }
1456
Eric Christopher4237bf12014-04-29 00:16:33 +00001457 // If Scratch2 is live-in then it needs to be saved.
Rafael Espindolad90466b2012-01-11 19:00:37 +00001458 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1459 "Scratch register is live-in and not saved");
1460
1461 if (SaveScratch2)
1462 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1463 .addReg(ScratchReg2, RegState::Kill);
1464
1465 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1466 .addImm(TlsOffset);
1467 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1468 .addReg(ScratchReg)
1469 .addReg(ScratchReg2).addImm(1).addReg(0)
1470 .addImm(0)
1471 .addReg(TlsReg);
1472
1473 if (SaveScratch2)
1474 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1475 }
Rafael Espindolac2174212011-08-30 19:39:58 +00001476 }
1477
1478 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1479 // It jumps to normal execution of the function body.
Rafael Espindola2b894482012-01-11 18:23:35 +00001480 BuildMI(checkMBB, DL, TII.get(X86::JA_4)).addMBB(&prologueMBB);
Rafael Espindolac2174212011-08-30 19:39:58 +00001481
1482 // On 32 bit we first push the arguments size and then the frame size. On 64
1483 // bit, we pass the stack frame size in r10 and the argument size in r11.
1484 if (Is64Bit) {
1485 // Functions with nested arguments use R10, so it needs to be saved across
1486 // the call to _morestack
1487
1488 if (IsNested)
1489 BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::RAX).addReg(X86::R10);
1490
1491 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R10)
1492 .addImm(StackSize);
1493 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R11)
1494 .addImm(X86FI->getArgumentStackSize());
1495 MF.getRegInfo().setPhysRegUsed(X86::R10);
1496 MF.getRegInfo().setPhysRegUsed(X86::R11);
1497 } else {
Rafael Espindolac2174212011-08-30 19:39:58 +00001498 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1499 .addImm(X86FI->getArgumentStackSize());
1500 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1501 .addImm(StackSize);
1502 }
1503
1504 // __morestack is in libgcc
1505 if (Is64Bit)
1506 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1507 .addExternalSymbol("__morestack");
1508 else
1509 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1510 .addExternalSymbol("__morestack");
1511
Bill Wendling25f6d3e2011-10-13 08:24:19 +00001512 if (IsNested)
Rafael Espindola66393c12011-10-26 21:12:27 +00001513 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1514 else
1515 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
Bill Wendling25f6d3e2011-10-13 08:24:19 +00001516
Rafael Espindola66393c12011-10-26 21:12:27 +00001517 allocMBB->addSuccessor(&prologueMBB);
Bill Wendling25f6d3e2011-10-13 08:24:19 +00001518
Rafael Espindolac2174212011-08-30 19:39:58 +00001519 checkMBB->addSuccessor(allocMBB);
1520 checkMBB->addSuccessor(&prologueMBB);
1521
Jakob Stoklund Olesen55cf2ed2011-09-24 01:11:19 +00001522#ifdef XDEBUG
Rafael Espindolac2174212011-08-30 19:39:58 +00001523 MF.verify();
1524#endif
1525}
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001526
Yiannis Tsiourisd4842e52013-02-28 16:59:10 +00001527/// Erlang programs may need a special prologue to handle the stack size they
1528/// might need at runtime. That is because Erlang/OTP does not implement a C
1529/// stack but uses a custom implementation of hybrid stack/heap architecture.
1530/// (for more information see Eric Stenman's Ph.D. thesis:
1531/// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1532///
1533/// CheckStack:
Eric Christopher4237bf12014-04-29 00:16:33 +00001534/// temp0 = sp - MaxStack
1535/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
Yiannis Tsiourisd4842e52013-02-28 16:59:10 +00001536/// OldStart:
Eric Christopher4237bf12014-04-29 00:16:33 +00001537/// ...
Yiannis Tsiourisd4842e52013-02-28 16:59:10 +00001538/// IncStack:
Eric Christopher4237bf12014-04-29 00:16:33 +00001539/// call inc_stack # doubles the stack space
1540/// temp0 = sp - MaxStack
1541/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001542void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
Eric Christopherfc6de422014-08-05 02:39:49 +00001543 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001544 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopher11b05cc2014-06-05 00:09:05 +00001545 const unsigned SlotSize =
Eric Christopherfc6de422014-08-05 02:39:49 +00001546 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo())
1547 ->getSlotSize();
Eric Christopherf4381642014-06-05 22:00:31 +00001548 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001549 const bool Is64Bit = STI.is64Bit();
1550 DebugLoc DL;
1551 // HiPE-specific values
1552 const unsigned HipeLeafWords = 24;
1553 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1554 const unsigned Guaranteed = HipeLeafWords * SlotSize;
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001555 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1556 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1557 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001558
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001559 assert(STI.isTargetLinux() &&
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001560 "HiPE prologue is only supported on Linux operating systems.");
1561
1562 // Compute the largest caller's frame that is needed to fit the callees'
1563 // frames. This 'MaxStack' is computed from:
1564 //
1565 // a) the fixed frame size, which is the space needed for all spilled temps,
1566 // b) outgoing on-stack parameter areas, and
1567 // c) the minimum stack space this function needs to make available for the
1568 // functions it calls (a tunable ABI property).
1569 if (MFI->hasCalls()) {
1570 unsigned MoreStackForCalls = 0;
1571
1572 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1573 MBBI != MBBE; ++MBBI)
1574 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001575 MI != ME; ++MI) {
1576 if (!MI->isCall())
1577 continue;
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001578
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001579 // Get callee operand.
1580 const MachineOperand &MO = MI->getOperand(0);
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001581
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001582 // Only take account of global function calls (no closures etc.).
1583 if (!MO.isGlobal())
1584 continue;
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001585
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001586 const Function *F = dyn_cast<Function>(MO.getGlobal());
1587 if (!F)
1588 continue;
1589
1590 // Do not update 'MaxStack' for primitive and built-in functions
1591 // (encoded with names either starting with "erlang."/"bif_" or not
1592 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1593 // "_", such as the BIF "suspend_0") as they are executed on another
1594 // stack.
1595 if (F->getName().find("erlang.") != StringRef::npos ||
1596 F->getName().find("bif_") != StringRef::npos ||
1597 F->getName().find_first_of("._") == StringRef::npos)
1598 continue;
1599
1600 unsigned CalleeStkArity =
1601 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1602 if (HipeLeafWords - 1 > CalleeStkArity)
1603 MoreStackForCalls = std::max(MoreStackForCalls,
1604 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1605 }
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001606 MaxStack += MoreStackForCalls;
1607 }
1608
1609 // If the stack frame needed is larger than the guaranteed then runtime checks
1610 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1611 if (MaxStack > Guaranteed) {
1612 MachineBasicBlock &prologueMBB = MF.front();
1613 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1614 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1615
1616 for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
1617 E = prologueMBB.livein_end(); I != E; I++) {
1618 stackCheckMBB->addLiveIn(*I);
1619 incStackMBB->addLiveIn(*I);
1620 }
1621
1622 MF.push_front(incStackMBB);
1623 MF.push_front(stackCheckMBB);
1624
1625 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1626 unsigned LEAop, CMPop, CALLop;
1627 if (Is64Bit) {
1628 SPReg = X86::RSP;
1629 PReg = X86::RBP;
1630 LEAop = X86::LEA64r;
1631 CMPop = X86::CMP64rm;
1632 CALLop = X86::CALL64pcrel32;
1633 SPLimitOffset = 0x90;
1634 } else {
1635 SPReg = X86::ESP;
1636 PReg = X86::EBP;
1637 LEAop = X86::LEA32r;
1638 CMPop = X86::CMP32rm;
1639 CALLop = X86::CALLpcrel32;
1640 SPLimitOffset = 0x4c;
1641 }
1642
1643 ScratchReg = GetScratchRegister(Is64Bit, MF, true);
1644 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1645 "HiPE prologue scratch register is live-in");
1646
1647 // Create new MBB for StackCheck:
1648 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1649 SPReg, false, -MaxStack);
1650 // SPLimitOffset is in a fixed heap location (pointed by BP).
1651 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1652 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1653 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_4)).addMBB(&prologueMBB);
1654
1655 // Create new MBB for IncStack:
1656 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1657 addExternalSymbol("inc_stack_0");
1658 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1659 SPReg, false, -MaxStack);
1660 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1661 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1662 BuildMI(incStackMBB, DL, TII.get(X86::JLE_4)).addMBB(incStackMBB);
1663
1664 stackCheckMBB->addSuccessor(&prologueMBB, 99);
1665 stackCheckMBB->addSuccessor(incStackMBB, 1);
1666 incStackMBB->addSuccessor(&prologueMBB, 99);
1667 incStackMBB->addSuccessor(incStackMBB, 1);
1668 }
1669#ifdef XDEBUG
1670 MF.verify();
1671#endif
1672}
Eli Bendersky8da87162013-02-21 20:05:00 +00001673
1674void X86FrameLowering::
1675eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1676 MachineBasicBlock::iterator I) const {
Eric Christopherfc6de422014-08-05 02:39:49 +00001677 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1678 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
1679 MF.getSubtarget().getRegisterInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00001680 unsigned StackPtr = RegInfo.getStackRegister();
1681 bool reseveCallFrame = hasReservedCallFrame(MF);
1682 int Opcode = I->getOpcode();
1683 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
Eric Christopherf4381642014-06-05 22:00:31 +00001684 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
Eli Bendersky8da87162013-02-21 20:05:00 +00001685 bool IsLP64 = STI.isTarget64BitLP64();
1686 DebugLoc DL = I->getDebugLoc();
1687 uint64_t Amount = !reseveCallFrame ? I->getOperand(0).getImm() : 0;
1688 uint64_t CalleeAmt = isDestroy ? I->getOperand(1).getImm() : 0;
1689 I = MBB.erase(I);
1690
1691 if (!reseveCallFrame) {
1692 // If the stack pointer can be changed after prologue, turn the
1693 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1694 // adjcallstackdown instruction into 'add ESP, <amt>'
1695 // TODO: consider using push / pop instead of sub + store / add
1696 if (Amount == 0)
1697 return;
1698
1699 // We need to keep the stack aligned properly. To do this, we round the
1700 // amount of space needed for the outgoing arguments up to the next
1701 // alignment boundary.
Eric Christopherd9134482014-08-04 21:25:23 +00001702 unsigned StackAlign = MF.getTarget()
1703 .getSubtargetImpl()
1704 ->getFrameLowering()
1705 ->getStackAlignment();
Eli Bendersky8da87162013-02-21 20:05:00 +00001706 Amount = (Amount + StackAlign - 1) / StackAlign * StackAlign;
1707
Craig Topper062a2ba2014-04-25 05:30:21 +00001708 MachineInstr *New = nullptr;
Eli Bendersky8da87162013-02-21 20:05:00 +00001709 if (Opcode == TII.getCallFrameSetupOpcode()) {
1710 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)),
1711 StackPtr)
1712 .addReg(StackPtr)
1713 .addImm(Amount);
1714 } else {
1715 assert(Opcode == TII.getCallFrameDestroyOpcode());
1716
1717 // Factor out the amount the callee already popped.
1718 Amount -= CalleeAmt;
1719
1720 if (Amount) {
1721 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1722 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1723 .addReg(StackPtr).addImm(Amount);
1724 }
1725 }
1726
1727 if (New) {
1728 // The EFLAGS implicit def is dead.
1729 New->getOperand(3).setIsDead();
1730
1731 // Replace the pseudo instruction with a new instruction.
1732 MBB.insert(I, New);
1733 }
1734
1735 return;
1736 }
1737
1738 if (Opcode == TII.getCallFrameDestroyOpcode() && CalleeAmt) {
1739 // If we are performing frame pointer elimination and if the callee pops
1740 // something off the stack pointer, add it back. We do this until we have
1741 // more advanced stack pointer tracking ability.
1742 unsigned Opc = getSUBriOpcode(IsLP64, CalleeAmt);
1743 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1744 .addReg(StackPtr).addImm(CalleeAmt);
1745
1746 // The EFLAGS implicit def is dead.
1747 New->getOperand(3).setIsDead();
1748
1749 // We are not tracking the stack pointer adjustment by the callee, so make
1750 // sure we restore the stack pointer immediately after the call, there may
1751 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1752 MachineBasicBlock::iterator B = MBB.begin();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001753 while (I != B && !std::prev(I)->isCall())
Eli Bendersky8da87162013-02-21 20:05:00 +00001754 --I;
1755 MBB.insert(I, New);
1756 }
1757}
1758