blob: d078c4d18cdc30dd321195c9a94f6c4dfb84950b [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 Christopherd9134482014-08-04 21:25:23 +000049 const TargetRegisterInfo *RegInfo =
50 MF.getTarget().getSubtargetImpl()->getRegisterInfo();
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000051
Nick Lewycky50f02cb2011-12-02 22:16:29 +000052 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
Chad Rosier20b79dc2012-05-23 23:45:10 +000053 RegInfo->needsStackRealignment(MF) ||
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000054 MFI->hasVarSizedObjects() ||
Reid Kleckneree088972013-12-10 18:27:32 +000055 MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000056 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
Jakob Stoklund Olesen321d41a2012-06-22 03:04:27 +000057 MMI.callsUnwindInit() || MMI.callsEHReturn());
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +000058}
59
Eli Bendersky8da87162013-02-21 20:05:00 +000060static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
61 if (IsLP64) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000062 if (isInt<8>(Imm))
63 return X86::SUB64ri8;
64 return X86::SUB64ri32;
65 } else {
66 if (isInt<8>(Imm))
67 return X86::SUB32ri8;
68 return X86::SUB32ri;
69 }
70}
71
Eli Benderskyef4558a2013-02-06 20:43:57 +000072static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
73 if (IsLP64) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +000074 if (isInt<8>(Imm))
75 return X86::ADD64ri8;
76 return X86::ADD64ri32;
77 } else {
78 if (isInt<8>(Imm))
79 return X86::ADD32ri8;
80 return X86::ADD32ri;
81 }
82}
83
Eli Benderskyef4558a2013-02-06 20:43:57 +000084static unsigned getLEArOpcode(unsigned IsLP64) {
85 return IsLP64 ? X86::LEA64r : X86::LEA32r;
Evan Cheng1b81fdd2012-02-07 22:50:41 +000086}
87
Evan Cheng65089fc2011-01-03 22:53:22 +000088/// findDeadCallerSavedReg - Return a caller-saved register that isn't live
89/// when it reaches the "return" instruction. We can then pop a stack object
90/// to this register without worry about clobbering it.
91static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
92 MachineBasicBlock::iterator &MBBI,
93 const TargetRegisterInfo &TRI,
94 bool Is64Bit) {
95 const MachineFunction *MF = MBB.getParent();
96 const Function *F = MF->getFunction();
97 if (!F || MF->getMMI().callsEHReturn())
98 return 0;
99
Craig Topper1d326582012-03-04 10:43:23 +0000100 static const uint16_t CallerSavedRegs32Bit[] = {
Andrew Trick210bf832011-08-12 00:49:19 +0000101 X86::EAX, X86::EDX, X86::ECX, 0
Evan Cheng65089fc2011-01-03 22:53:22 +0000102 };
103
Craig Topper1d326582012-03-04 10:43:23 +0000104 static const uint16_t CallerSavedRegs64Bit[] = {
Evan Cheng65089fc2011-01-03 22:53:22 +0000105 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
Andrew Trick210bf832011-08-12 00:49:19 +0000106 X86::R8, X86::R9, X86::R10, X86::R11, 0
Evan Cheng65089fc2011-01-03 22:53:22 +0000107 };
108
109 unsigned Opc = MBBI->getOpcode();
110 switch (Opc) {
111 default: return 0;
David Woodhouse79dd5052014-01-08 12:58:07 +0000112 case X86::RETL:
113 case X86::RETQ:
David Woodhouse4e033b02014-01-13 14:05:59 +0000114 case X86::RETIL:
115 case X86::RETIQ:
Evan Cheng65089fc2011-01-03 22:53:22 +0000116 case X86::TCRETURNdi:
117 case X86::TCRETURNri:
118 case X86::TCRETURNmi:
119 case X86::TCRETURNdi64:
120 case X86::TCRETURNri64:
121 case X86::TCRETURNmi64:
122 case X86::EH_RETURN:
123 case X86::EH_RETURN64: {
Craig Topper1d326582012-03-04 10:43:23 +0000124 SmallSet<uint16_t, 8> Uses;
Evan Cheng65089fc2011-01-03 22:53:22 +0000125 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
126 MachineOperand &MO = MBBI->getOperand(i);
127 if (!MO.isReg() || MO.isDef())
128 continue;
129 unsigned Reg = MO.getReg();
130 if (!Reg)
131 continue;
Jakob Stoklund Olesen54038d72012-06-01 23:28:30 +0000132 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
133 Uses.insert(*AI);
Evan Cheng65089fc2011-01-03 22:53:22 +0000134 }
135
Craig Topper1d326582012-03-04 10:43:23 +0000136 const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
Evan Cheng65089fc2011-01-03 22:53:22 +0000137 for (; *CS; ++CS)
138 if (!Uses.count(*CS))
139 return *CS;
140 }
141 }
142
143 return 0;
144}
145
146
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000147/// emitSPUpdate - Emit a series of instructions to increment / decrement the
148/// stack pointer by a constant value.
149static
150void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
Evan Cheng65089fc2011-01-03 22:53:22 +0000151 unsigned StackPtr, int64_t NumBytes,
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000152 bool Is64Bit, bool IsLP64, bool UseLEA,
Eric Christopherf4fba5c2012-10-03 08:10:01 +0000153 const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000154 bool isSub = NumBytes < 0;
155 uint64_t Offset = isSub ? -NumBytes : NumBytes;
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000156 unsigned Opc;
157 if (UseLEA)
Eli Benderskyef4558a2013-02-06 20:43:57 +0000158 Opc = getLEArOpcode(IsLP64);
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000159 else
160 Opc = isSub
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000161 ? getSUBriOpcode(IsLP64, Offset)
162 : getADDriOpcode(IsLP64, Offset);
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000163
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000164 uint64_t Chunk = (1LL << 31) - 1;
Eric Christopherf4fba5c2012-10-03 08:10:01 +0000165 DebugLoc DL = MBB.findDebugLoc(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000166
167 while (Offset) {
168 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
Evan Cheng65089fc2011-01-03 22:53:22 +0000169 if (ThisVal == (Is64Bit ? 8 : 4)) {
170 // Use push / pop instead.
171 unsigned Reg = isSub
Dale Johannesene45a2382011-01-04 19:31:24 +0000172 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
Evan Cheng65089fc2011-01-03 22:53:22 +0000173 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
174 if (Reg) {
175 Opc = isSub
176 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
177 : (Is64Bit ? X86::POP64r : X86::POP32r);
Charles Davis7ed40cb2011-06-12 01:45:54 +0000178 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
Evan Cheng65089fc2011-01-03 22:53:22 +0000179 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
Charles Davis7ed40cb2011-06-12 01:45:54 +0000180 if (isSub)
181 MI->setFlag(MachineInstr::FrameSetup);
Evan Cheng65089fc2011-01-03 22:53:22 +0000182 Offset -= ThisVal;
183 continue;
184 }
185 }
186
Craig Topper062a2ba2014-04-25 05:30:21 +0000187 MachineInstr *MI = nullptr;
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000188
189 if (UseLEA) {
190 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
191 StackPtr, false, isSub ? -ThisVal : ThisVal);
192 } else {
193 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
194 .addReg(StackPtr)
195 .addImm(ThisVal);
196 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
197 }
198
Charles Davis7ed40cb2011-06-12 01:45:54 +0000199 if (isSub)
200 MI->setFlag(MachineInstr::FrameSetup);
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000201
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000202 Offset -= ThisVal;
203 }
204}
205
206/// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
207static
208void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
Craig Topper062a2ba2014-04-25 05:30:21 +0000209 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000210 if (MBBI == MBB.begin()) return;
211
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000212 MachineBasicBlock::iterator PI = std::prev(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000213 unsigned Opc = PI->getOpcode();
214 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000215 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
216 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000217 PI->getOperand(0).getReg() == StackPtr) {
218 if (NumBytes)
219 *NumBytes += PI->getOperand(2).getImm();
220 MBB.erase(PI);
221 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
222 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
223 PI->getOperand(0).getReg() == StackPtr) {
224 if (NumBytes)
225 *NumBytes -= PI->getOperand(2).getImm();
226 MBB.erase(PI);
227 }
228}
229
Eric Christopher4237bf12014-04-29 00:16:33 +0000230/// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
231/// iterator.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000232static
233void mergeSPUpdatesDown(MachineBasicBlock &MBB,
234 MachineBasicBlock::iterator &MBBI,
Craig Topper062a2ba2014-04-25 05:30:21 +0000235 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
Sanjoy Dasf60485c2011-12-01 19:15:08 +0000236 // FIXME: THIS ISN'T RUN!!!
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000237 return;
238
239 if (MBBI == MBB.end()) return;
240
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000241 MachineBasicBlock::iterator NI = std::next(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000242 if (NI == MBB.end()) return;
243
244 unsigned Opc = NI->getOpcode();
245 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
246 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
247 NI->getOperand(0).getReg() == StackPtr) {
248 if (NumBytes)
249 *NumBytes -= NI->getOperand(2).getImm();
250 MBB.erase(NI);
251 MBBI = NI;
252 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
253 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
254 NI->getOperand(0).getReg() == StackPtr) {
255 if (NumBytes)
256 *NumBytes += NI->getOperand(2).getImm();
257 MBB.erase(NI);
258 MBBI = NI;
259 }
260}
261
262/// mergeSPUpdates - Checks the instruction before/after the passed
Eric Christopher4237bf12014-04-29 00:16:33 +0000263/// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
264/// the stack adjustment is returned as a positive value for ADD/LEA and a
265/// negative for SUB.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000266static int mergeSPUpdates(MachineBasicBlock &MBB,
Eric Christopher4237bf12014-04-29 00:16:33 +0000267 MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
268 bool doMergeWithPrevious) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000269 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
270 (!doMergeWithPrevious && MBBI == MBB.end()))
271 return 0;
272
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000273 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
Craig Topper062a2ba2014-04-25 05:30:21 +0000274 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
275 : std::next(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000276 unsigned Opc = PI->getOpcode();
277 int Offset = 0;
278
279 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000280 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
281 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000282 PI->getOperand(0).getReg() == StackPtr){
283 Offset += PI->getOperand(2).getImm();
284 MBB.erase(PI);
285 if (!doMergeWithPrevious) MBBI = NI;
286 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
287 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
288 PI->getOperand(0).getReg() == StackPtr) {
289 Offset -= PI->getOperand(2).getImm();
290 MBB.erase(PI);
291 if (!doMergeWithPrevious) MBBI = NI;
292 }
293
294 return Offset;
295}
296
297static bool isEAXLiveIn(MachineFunction &MF) {
298 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
299 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
300 unsigned Reg = II->first;
301
302 if (Reg == X86::EAX || Reg == X86::AX ||
303 Reg == X86::AH || Reg == X86::AL)
304 return true;
305 }
306
307 return false;
308}
309
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000310void
311X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
312 MachineBasicBlock::iterator MBBI,
313 DebugLoc DL) const {
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000314 MachineFunction &MF = *MBB.getParent();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000315 MachineFrameInfo *MFI = MF.getFrameInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000316 MachineModuleInfo &MMI = MF.getMMI();
Bill Wendlingbc07a892013-06-18 07:20:20 +0000317 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
Eric Christopherd9134482014-08-04 21:25:23 +0000318 const TargetInstrInfo &TII =
319 *MF.getTarget().getSubtargetImpl()->getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000320
321 // Add callee saved registers to move list.
322 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
323 if (CSI.empty()) return;
324
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000325 // Calculate offsets.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000326 for (std::vector<CalleeSavedInfo>::const_iterator
327 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
328 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
329 unsigned Reg = I->getReg();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000330
Bill Wendlingbc07a892013-06-18 07:20:20 +0000331 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000332 unsigned CFIIndex =
Craig Topper062a2ba2014-04-25 05:30:21 +0000333 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
334 Offset));
Eric Christopher612bb692014-04-29 00:16:46 +0000335 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
336 .addCFIIndex(CFIIndex);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000337 }
338}
339
Nadav Rotem1bef5a02012-12-23 07:30:09 +0000340/// usesTheStack - This function checks if any of the users of EFLAGS
Nadav Rotemd5aae982012-12-21 23:48:49 +0000341/// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
342/// to use the stack, and if we don't adjust the stack we clobber the first
343/// frame index.
Nadav Rotem1bef5a02012-12-23 07:30:09 +0000344/// See X86InstrInfo::copyPhysReg.
Bill Wendling28519072013-08-15 18:46:14 +0000345static bool usesTheStack(const MachineFunction &MF) {
346 const MachineRegisterInfo &MRI = MF.getRegInfo();
Nadav Rotemd5aae982012-12-21 23:48:49 +0000347
Owen Anderson16c6bf42014-03-13 23:12:04 +0000348 for (MachineRegisterInfo::reg_instr_iterator
349 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
350 ri != re; ++ri)
Nadav Rotemd5aae982012-12-21 23:48:49 +0000351 if (ri->isCopy())
352 return true;
353
354 return false;
355}
356
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000357/// emitPrologue - Push callee-saved registers onto the stack, which
358/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
359/// space for local variables. Also emit labels used by the exception handler to
360/// generate the exception handling frames.
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000361
362/*
363 Here's a gist of what gets emitted:
364
365 ; Establish frame pointer, if needed
366 [if needs FP]
367 push %rbp
368 .cfi_def_cfa_offset 16
369 .cfi_offset %rbp, -16
370 .seh_pushreg %rpb
371 mov %rsp, %rbp
372 .cfi_def_cfa_register %rbp
373
374 ; Spill general-purpose registers
375 [for all callee-saved GPRs]
376 pushq %<reg>
377 [if not needs FP]
378 .cfi_def_cfa_offset (offset from RETADDR)
379 .seh_pushreg %<reg>
380
381 ; If the required stack alignment > default stack alignment
382 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
383 ; of unknown size in the stack frame.
384 [if stack needs re-alignment]
385 and $MASK, %rsp
386
387 ; Allocate space for locals
388 [if target is Windows and allocated space > 4096 bytes]
389 ; Windows needs special care for allocations larger
390 ; than one page.
391 mov $NNN, %rax
392 call ___chkstk_ms/___chkstk
393 sub %rax, %rsp
394 [else]
395 sub $NNN, %rsp
396
397 [if needs FP]
398 .seh_stackalloc (size of XMM spill slots)
399 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
400 [else]
401 .seh_stackalloc NNN
402
403 ; Spill XMMs
404 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
405 ; they may get spilled on any platform, if the current function
406 ; calls @llvm.eh.unwind.init
407 [if needs FP]
408 [for all callee-saved XMM registers]
409 movaps %<xmm reg>, -MMM(%rbp)
410 [for all callee-saved XMM registers]
411 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
412 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
413 [else]
414 [for all callee-saved XMM registers]
415 movaps %<xmm reg>, KKK(%rsp)
416 [for all callee-saved XMM registers]
417 .seh_savexmm %<xmm reg>, KKK
418
419 .seh_endprologue
420
421 [if needs base pointer]
422 mov %rsp, %rbx
423
424 ; Emit CFI info
425 [if needs FP]
426 [for all callee-saved registers]
427 .cfi_offset %<reg>, (offset from %rbp)
428 [else]
429 .cfi_def_cfa_offset (offset from RETADDR)
430 [for all callee-saved registers]
431 .cfi_offset %<reg>, (offset from %rsp)
432
433 Notes:
434 - .seh directives are emitted only for Windows 64 ABI
435 - .cfi directives are emitted for all other ABIs
436 - for 32-bit code, substitute %e?? registers for %r??
437*/
438
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000439void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000440 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
441 MachineBasicBlock::iterator MBBI = MBB.begin();
442 MachineFrameInfo *MFI = MF.getFrameInfo();
443 const Function *Fn = MF.getFunction();
Eric Christopherd9134482014-08-04 21:25:23 +0000444 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
445 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
446 const TargetInstrInfo &TII =
447 *MF.getTarget().getSubtargetImpl()->getInstrInfo();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000448 MachineModuleInfo &MMI = MF.getMMI();
449 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000450 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
451 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000452 bool HasFP = hasFP(MF);
Eric Christopherf4381642014-06-05 22:00:31 +0000453 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000454 bool Is64Bit = STI.is64Bit();
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000455 bool IsLP64 = STI.isTarget64BitLP64();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000456 bool IsWin64 = STI.isTargetWin64();
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000457 bool IsWinEH =
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000458 MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000459 ExceptionHandling::WinEH; // Not necessarily synonymous with IsWin64.
460 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000461 bool NeedsDwarfCFI =
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000462 !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000463 bool UseLEA = STI.useLeaForSP();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000464 unsigned StackAlign = getStackAlignment();
465 unsigned SlotSize = RegInfo->getSlotSize();
466 unsigned FramePtr = RegInfo->getFrameRegister(MF);
467 unsigned StackPtr = RegInfo->getStackRegister();
Chad Rosierbdb08ac2012-07-10 17:45:53 +0000468 unsigned BasePtr = RegInfo->getBaseRegister();
Bill Wendlingf27e3312013-09-10 00:20:27 +0000469 DebugLoc DL;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000470
471 // If we're forcing a stack realignment we can't rely on just the frame
472 // info, we need to know the ABI stack alignment as well in case we
473 // have a call out. Otherwise just make sure we have some alignment - we'll
474 // go with the minimum SlotSize.
475 if (ForceStackAlign) {
476 if (MFI->hasCalls())
477 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
478 else if (MaxAlign < SlotSize)
479 MaxAlign = SlotSize;
480 }
481
482 // Add RETADDR move area to callee saved frame size.
483 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
484 if (TailCallReturnAddrDelta < 0)
485 X86FI->setCalleeSavedFrameSize(
486 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
487
488 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
489 // function, and use up to 128 bytes of stack space, don't have a frame
490 // pointer, calls, or dynamic alloca then we do not need to adjust the
Nadav Rotemd5aae982012-12-21 23:48:49 +0000491 // stack pointer (we fit in the Red Zone). We also check that we don't
492 // push and pop from the stack.
Bill Wendling698e84f2012-12-30 10:32:01 +0000493 if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
494 Attribute::NoRedZone) &&
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000495 !RegInfo->needsStackRealignment(MF) &&
Nick Lewycky50f02cb2011-12-02 22:16:29 +0000496 !MFI->hasVarSizedObjects() && // No dynamic alloca.
497 !MFI->adjustsStack() && // No calls.
498 !IsWin64 && // Win64 has no Red Zone
Nadav Rotem1bef5a02012-12-23 07:30:09 +0000499 !usesTheStack(MF) && // Don't push and pop.
Reid Kleckner9c658212014-04-10 22:58:43 +0000500 !MF.shouldSplitStack()) { // Regular stack
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000501 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
502 if (HasFP) MinSize += SlotSize;
503 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
504 MFI->setStackSize(StackSize);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000505 }
506
507 // Insert stack pointer adjustment for later moving of return addr. Only
508 // applies to tail call optimized functions where the callee argument stack
509 // size is bigger than the callers.
510 if (TailCallReturnAddrDelta < 0) {
511 MachineInstr *MI =
512 BuildMI(MBB, MBBI, DL,
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000513 TII.get(getSUBriOpcode(IsLP64, -TailCallReturnAddrDelta)),
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000514 StackPtr)
515 .addReg(StackPtr)
Charles Davis7ed40cb2011-06-12 01:45:54 +0000516 .addImm(-TailCallReturnAddrDelta)
517 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000518 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
519 }
520
521 // Mapping for machine moves:
522 //
523 // DST: VirtualFP AND
524 // SRC: VirtualFP => DW_CFA_def_cfa_offset
525 // ELSE => DW_CFA_def_cfa
526 //
527 // SRC: VirtualFP AND
528 // DST: Register => DW_CFA_def_cfa_register
529 //
530 // ELSE
531 // OFFSET < 0 => DW_CFA_offset_extended_sf
532 // REG < 64 => DW_CFA_offset + Reg
533 // ELSE => DW_CFA_offset_extended
534
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000535 uint64_t NumBytes = 0;
Michael Liao6d810bd2012-10-25 06:29:14 +0000536 int stackGrowth = -SlotSize;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000537
538 if (HasFP) {
539 // Calculate required stack adjustment.
540 uint64_t FrameSize = StackSize - SlotSize;
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000541 if (RegInfo->needsStackRealignment(MF)) {
542 // Callee-saved registers are pushed on stack before the stack
543 // is realigned.
544 FrameSize -= X86FI->getCalleeSavedFrameSize();
545 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
546 } else {
547 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
548 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000549
550 // Get the offset of the stack slot for the EBP register, which is
551 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
552 // Update the frame offset adjustment.
553 MFI->setOffsetAdjustment(-NumBytes);
554
555 // Save EBP/RBP into the appropriate stack slot.
556 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
Charles Davis7ed40cb2011-06-12 01:45:54 +0000557 .addReg(FramePtr, RegState::Kill)
558 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000559
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000560 if (NeedsDwarfCFI) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000561 // Mark the place where EBP/RBP was saved.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000562 // Define the current CFA rule to use the provided offset.
Rafael Espindola84ee6c42013-05-15 22:27:35 +0000563 assert(StackSize);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000564 unsigned CFIIndex = MMI.addFrameInst(
Craig Topper062a2ba2014-04-25 05:30:21 +0000565 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
Eric Christopher612bb692014-04-29 00:16:46 +0000566 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000567 .addCFIIndex(CFIIndex);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000568
569 // Change the rule for the FramePtr to be an "offset" rule.
Rafael Espindolab08d2c22013-05-16 21:02:15 +0000570 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(FramePtr, true);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000571 CFIIndex = MMI.addFrameInst(
Craig Topper062a2ba2014-04-25 05:30:21 +0000572 MCCFIInstruction::createOffset(nullptr,
573 DwarfFramePtr, 2 * stackGrowth));
Eric Christopher612bb692014-04-29 00:16:46 +0000574 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000575 .addCFIIndex(CFIIndex);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000576 }
577
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000578 if (NeedsWinEH) {
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000579 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
580 .addImm(FramePtr)
581 .setMIFlag(MachineInstr::FrameSetup);
582 }
583
Bill Wendlingb97270d2011-07-25 18:00:28 +0000584 // Update EBP with the new base value.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000585 BuildMI(MBB, MBBI, DL,
586 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
Charles Davis7ed40cb2011-06-12 01:45:54 +0000587 .addReg(StackPtr)
588 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000589
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000590 if (NeedsDwarfCFI) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000591 // Mark effective beginning of when frame pointer becomes valid.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000592 // Define the current CFA to use the EBP/RBP register.
Rafael Espindolab08d2c22013-05-16 21:02:15 +0000593 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(FramePtr, true);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000594 unsigned CFIIndex = MMI.addFrameInst(
Craig Topper062a2ba2014-04-25 05:30:21 +0000595 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
Eric Christopher612bb692014-04-29 00:16:46 +0000596 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000597 .addCFIIndex(CFIIndex);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000598 }
599
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000600 // Mark the FramePtr as live-in in every block.
601 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000602 I->addLiveIn(FramePtr);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000603 } else {
604 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
605 }
606
607 // Skip the callee-saved push instructions.
608 bool PushedRegs = false;
609 int StackOffset = 2 * stackGrowth;
610
611 while (MBBI != MBB.end() &&
612 (MBBI->getOpcode() == X86::PUSH32r ||
613 MBBI->getOpcode() == X86::PUSH64r)) {
614 PushedRegs = true;
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000615 unsigned Reg = MBBI->getOperand(0).getReg();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000616 ++MBBI;
617
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000618 if (!HasFP && NeedsDwarfCFI) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000619 // Mark callee-saved push instruction.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000620 // Define the current CFA rule to use the provided offset.
Rafael Espindola72421862013-05-16 04:59:17 +0000621 assert(StackSize);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000622 unsigned CFIIndex = MMI.addFrameInst(
623 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
Eric Christopher612bb692014-04-29 00:16:46 +0000624 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000625 .addCFIIndex(CFIIndex);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000626 StackOffset += stackGrowth;
627 }
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000628
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000629 if (NeedsWinEH) {
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000630 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
631 MachineInstr::FrameSetup);
632 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000633 }
634
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000635 // Realign stack after we pushed callee-saved registers (so that we'll be
636 // able to calculate their offsets from the frame pointer).
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000637 if (RegInfo->needsStackRealignment(MF)) {
638 assert(HasFP && "There should be a frame pointer if stack is realigned.");
639 MachineInstr *MI =
640 BuildMI(MBB, MBBI, DL,
641 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
642 .addReg(StackPtr)
643 .addImm(-MaxAlign)
644 .setMIFlag(MachineInstr::FrameSetup);
645
646 // The EFLAGS implicit def is dead.
647 MI->getOperand(3).setIsDead();
648 }
649
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000650 // If there is an SUB32ri of ESP immediately before this instruction, merge
651 // the two. This can be the case when tail call elimination is enabled and
652 // the callee has more arguments then the caller.
653 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
654
655 // If there is an ADD32ri or SUB32ri of ESP immediately after this
656 // instruction, merge the two instructions.
657 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
658
659 // Adjust stack pointer: ESP -= numbytes.
660
661 // Windows and cygwin/mingw require a prologue helper routine when allocating
662 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
663 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
664 // stack and adjust the stack pointer in one go. The 64-bit version of
665 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
666 // responsible for adjusting the stack pointer. Touching the stack at 4K
667 // increments is necessary to ensure that the guard pages used by the OS
668 // virtual memory manager are allocated in correct sequence.
Tim Northover9653eb52013-12-10 16:57:43 +0000669 if (NumBytes >= 4096 && STI.isOSWindows() && !STI.isTargetMacho()) {
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000670 const char *StackProbeSymbol;
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000671
672 if (Is64Bit) {
Kai Nacke87b23ae2013-12-13 05:37:05 +0000673 if (STI.isTargetCygMing()) {
674 StackProbeSymbol = "___chkstk_ms";
675 } else {
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000676 StackProbeSymbol = "__chkstk";
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000677 }
678 } else if (STI.isTargetCygMing())
679 StackProbeSymbol = "_alloca";
680 else
681 StackProbeSymbol = "_chkstk";
682
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000683 // Check whether EAX is livein for this function.
684 bool isEAXAlive = isEAXLiveIn(MF);
685
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000686 if (isEAXAlive) {
687 // Sanity check that EAX is not livein for this function.
688 // It should not be, so throw an assert.
689 assert(!Is64Bit && "EAX is livein in x64 case!");
690
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000691 // Save EAX
692 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
Bill Wendling28b6e122011-07-21 00:44:56 +0000693 .addReg(X86::EAX, RegState::Kill)
694 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000695 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000696
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000697 if (Is64Bit) {
698 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
699 // Function prologue is responsible for adjusting the stack pointer.
700 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
Bill Wendling28b6e122011-07-21 00:44:56 +0000701 .addImm(NumBytes)
702 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000703 } else {
704 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
705 // We'll also use 4 already allocated bytes for EAX.
706 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
Bill Wendling28b6e122011-07-21 00:44:56 +0000707 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
708 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000709 }
710
711 BuildMI(MBB, MBBI, DL,
712 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
713 .addExternalSymbol(StackProbeSymbol)
714 .addReg(StackPtr, RegState::Define | RegState::Implicit)
Bill Wendling28b6e122011-07-21 00:44:56 +0000715 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
716 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000717
Kai Nacke87b23ae2013-12-13 05:37:05 +0000718 if (Is64Bit) {
719 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
720 // themself. It also does not clobber %rax so we can reuse it when
721 // adjusting %rsp.
Nico Rieck51969be2013-07-08 11:20:11 +0000722 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), StackPtr)
723 .addReg(StackPtr)
724 .addReg(X86::RAX)
725 .setMIFlag(MachineInstr::FrameSetup);
726 }
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000727 if (isEAXAlive) {
728 // Restore EAX
729 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
730 X86::EAX),
731 StackPtr, false, NumBytes - 4);
Bill Wendling28b6e122011-07-21 00:44:56 +0000732 MI->setFlag(MachineInstr::FrameSetup);
NAKAMURA Takumi521eb7c2011-03-24 07:07:00 +0000733 MBB.insert(MBBI, MI);
734 }
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000735 } else if (NumBytes) {
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000736 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, IsLP64,
Eric Christopherf4fba5c2012-10-03 08:10:01 +0000737 UseLEA, TII, *RegInfo);
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000738 }
739
740 int SEHFrameOffset = 0;
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000741 if (NeedsWinEH) {
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000742 if (HasFP) {
743 // We need to set frame base offset low enough such that all saved
744 // register offsets would be positive relative to it, but we can't
745 // just use NumBytes, because .seh_setframe offset must be <=240.
746 // So we pretend to have only allocated enough space to spill the
747 // non-volatile registers.
748 // We don't care about the rest of stack allocation, because unwinder
749 // will restore SP to (BP - SEHFrameOffset)
750 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
751 int offset = MFI->getObjectOffset(Info.getFrameIdx());
752 SEHFrameOffset = std::max(SEHFrameOffset, abs(offset));
753 }
754 SEHFrameOffset += SEHFrameOffset % 16; // ensure alignmant
755
756 // This only needs to account for XMM spill slots, GPR slots
Reid Klecknerb5dd9452014-07-01 00:42:47 +0000757 // are covered by the .seh_pushreg's emitted above.
758 unsigned Size = SEHFrameOffset - X86FI->getCalleeSavedFrameSize();
759 if (Size) {
760 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
761 .addImm(Size)
762 .setMIFlag(MachineInstr::FrameSetup);
763 }
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000764
765 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
766 .addImm(FramePtr)
767 .addImm(SEHFrameOffset)
768 .setMIFlag(MachineInstr::FrameSetup);
769 } else {
770 // SP will be the base register for restoring XMMs
771 if (NumBytes) {
772 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
773 .addImm(NumBytes)
774 .setMIFlag(MachineInstr::FrameSetup);
775 }
776 }
777 }
778
779 // Skip the rest of register spilling code
780 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
781 ++MBBI;
782
783 // Emit SEH info for non-GPRs
Saleem Abdulrasool67b54812014-06-29 21:43:47 +0000784 if (NeedsWinEH) {
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000785 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
786 unsigned Reg = Info.getReg();
787 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
788 continue;
789 assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
790
791 int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
792 Offset += SEHFrameOffset;
793
794 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
795 .addImm(Reg)
796 .addImm(Offset)
797 .setMIFlag(MachineInstr::FrameSetup);
798 }
799
800 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
801 .setMIFlag(MachineInstr::FrameSetup);
802 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000803
Chad Rosierbdb08ac2012-07-10 17:45:53 +0000804 // If we need a base pointer, set it up here. It's whatever the value
805 // of the stack pointer is at this point. Any variable size objects
806 // will be allocated after this, so we can still use the base pointer
807 // to reference locals.
808 if (RegInfo->hasBasePointer(MF)) {
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000809 // Update the base pointer with the current stack pointer.
Chad Rosierbdb08ac2012-07-10 17:45:53 +0000810 unsigned Opc = Is64Bit ? X86::MOV64rr : X86::MOV32rr;
811 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
812 .addReg(StackPtr)
813 .setMIFlag(MachineInstr::FrameSetup);
Chad Rosierbdb08ac2012-07-10 17:45:53 +0000814 }
815
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000816 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000817 // Mark end of stack pointer adjustment.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000818 if (!HasFP && NumBytes) {
819 // Define the current CFA rule to use the provided offset.
Rafael Espindola84ee6c42013-05-15 22:27:35 +0000820 assert(StackSize);
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000821 unsigned CFIIndex = MMI.addFrameInst(
Craig Topper062a2ba2014-04-25 05:30:21 +0000822 MCCFIInstruction::createDefCfaOffset(nullptr,
823 -StackSize + stackGrowth));
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000824
Eric Christopher612bb692014-04-29 00:16:46 +0000825 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
Rafael Espindolab1f25f12014-03-07 06:08:31 +0000826 .addCFIIndex(CFIIndex);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000827 }
828
829 // Emit DWARF info specifying the offsets of the callee-saved registers.
830 if (PushedRegs)
NAKAMURA Takumi1db59952014-06-25 12:41:52 +0000831 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000832 }
833}
834
Anton Korobeynikov2f931282011-01-10 12:39:04 +0000835void X86FrameLowering::emitEpilogue(MachineFunction &MF,
Nick Lewycky34a425b2011-06-14 03:23:52 +0000836 MachineBasicBlock &MBB) const {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000837 const MachineFrameInfo *MFI = MF.getFrameInfo();
838 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Eric Christopherd9134482014-08-04 21:25:23 +0000839 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
840 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
841 const TargetInstrInfo &TII =
842 *MF.getTarget().getSubtargetImpl()->getInstrInfo();
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000843 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
844 assert(MBBI != MBB.end() && "Returning block has no instructions");
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000845 unsigned RetOpcode = MBBI->getOpcode();
846 DebugLoc DL = MBBI->getDebugLoc();
Eric Christopherf4381642014-06-05 22:00:31 +0000847 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000848 bool Is64Bit = STI.is64Bit();
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000849 bool IsLP64 = STI.isTarget64BitLP64();
Evan Cheng1b81fdd2012-02-07 22:50:41 +0000850 bool UseLEA = STI.useLeaForSP();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000851 unsigned StackAlign = getStackAlignment();
852 unsigned SlotSize = RegInfo->getSlotSize();
853 unsigned FramePtr = RegInfo->getFrameRegister(MF);
854 unsigned StackPtr = RegInfo->getStackRegister();
855
Reid Klecknere7040102014-08-04 21:05:27 +0000856 bool IsWinEH =
857 MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
858 ExceptionHandling::WinEH;
859 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
860
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000861 switch (RetOpcode) {
862 default:
863 llvm_unreachable("Can only insert epilog into returning blocks");
David Woodhouse79dd5052014-01-08 12:58:07 +0000864 case X86::RETQ:
865 case X86::RETL:
David Woodhouse4e033b02014-01-13 14:05:59 +0000866 case X86::RETIL:
867 case X86::RETIQ:
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000868 case X86::TCRETURNdi:
869 case X86::TCRETURNri:
870 case X86::TCRETURNmi:
871 case X86::TCRETURNdi64:
872 case X86::TCRETURNri64:
873 case X86::TCRETURNmi64:
874 case X86::EH_RETURN:
875 case X86::EH_RETURN64:
876 break; // These are ok
877 }
878
879 // Get the number of bytes to allocate from the FrameInfo.
880 uint64_t StackSize = MFI->getStackSize();
881 uint64_t MaxAlign = MFI->getMaxAlignment();
882 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
883 uint64_t NumBytes = 0;
884
885 // If we're forcing a stack realignment we can't rely on just the frame
886 // info, we need to know the ABI stack alignment as well in case we
887 // have a call out. Otherwise just make sure we have some alignment - we'll
888 // go with the minimum.
889 if (ForceStackAlign) {
890 if (MFI->hasCalls())
891 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
892 else
893 MaxAlign = MaxAlign ? MaxAlign : 4;
894 }
895
Anton Korobeynikov0eecf5d2010-11-18 21:19:35 +0000896 if (hasFP(MF)) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000897 // Calculate required stack adjustment.
898 uint64_t FrameSize = StackSize - SlotSize;
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000899 if (RegInfo->needsStackRealignment(MF)) {
900 // Callee-saved registers were pushed on stack before the stack
901 // was realigned.
902 FrameSize -= CSSize;
903 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
904 } else {
905 NumBytes = FrameSize - CSSize;
906 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000907
908 // Pop EBP.
909 BuildMI(MBB, MBBI, DL,
910 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
911 } else {
912 NumBytes = StackSize - CSSize;
913 }
914
915 // Skip the callee-saved pop instructions.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000916 while (MBBI != MBB.begin()) {
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000917 MachineBasicBlock::iterator PI = std::prev(MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000918 unsigned Opc = PI->getOpcode();
919
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000920 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
Evan Cheng7f8e5632011-12-07 07:15:52 +0000921 !PI->isTerminator())
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000922 break;
923
924 --MBBI;
925 }
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000926 MachineBasicBlock::iterator FirstCSPop = MBBI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000927
928 DL = MBBI->getDebugLoc();
929
930 // If there is an ADD32ri or SUB32ri of ESP immediately before this
931 // instruction, merge the two instructions.
932 if (NumBytes || MFI->hasVarSizedObjects())
933 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
934
935 // If dynamic alloca is used, then reset esp to point to the last callee-saved
936 // slot before popping them off! Same applies for the case, when stack was
937 // realigned.
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000938 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
939 if (RegInfo->needsStackRealignment(MF))
940 MBBI = FirstCSPop;
941 if (CSSize != 0) {
Eli Benderskyef4558a2013-02-06 20:43:57 +0000942 unsigned Opc = getLEArOpcode(IsLP64);
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000943 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
944 FramePtr, false, -CSSize);
Reid Klecknere7040102014-08-04 21:05:27 +0000945 --MBBI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000946 } else {
Alexey Samsonovdcc12912012-07-16 06:54:09 +0000947 unsigned Opc = (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
948 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000949 .addReg(FramePtr);
Reid Klecknere7040102014-08-04 21:05:27 +0000950 --MBBI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000951 }
952 } else if (NumBytes) {
953 // Adjust stack pointer back: ESP += numbytes.
Eli Bendersky44a40ca2013-02-05 21:53:29 +0000954 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, IsLP64, UseLEA,
955 TII, *RegInfo);
Reid Klecknere7040102014-08-04 21:05:27 +0000956 --MBBI;
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000957 }
958
Reid Klecknere7040102014-08-04 21:05:27 +0000959 // Windows unwinder will not invoke function's exception handler if IP is
960 // either in prologue or in epilogue. This behavior causes a problem when a
961 // call immediately precedes an epilogue, because the return address points
962 // into the epilogue. To cope with that, we insert an epilogue marker here,
963 // then replace it with a 'nop' if it ends up immediately after a CALL in the
964 // final emitted code.
965 if (NeedsWinEH)
966 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
967
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000968 // We're returning from function via eh_return.
969 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +0000970 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000971 MachineOperand &DestAddr = MBBI->getOperand(0);
972 assert(DestAddr.isReg() && "Offset should be in register!");
973 BuildMI(MBB, MBBI, DL,
974 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
975 StackPtr).addReg(DestAddr.getReg());
976 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
977 RetOpcode == X86::TCRETURNmi ||
978 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
979 RetOpcode == X86::TCRETURNmi64) {
980 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
981 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesenbbb1a542011-01-13 22:47:43 +0000982 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000983 MachineOperand &JumpTarget = MBBI->getOperand(0);
984 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
985 assert(StackAdjust.isImm() && "Expecting immediate value.");
986
987 // Adjust stack pointer.
988 int StackAdj = StackAdjust.getImm();
989 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
990 int Offset = 0;
991 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
992
993 // Incoporate the retaddr area.
994 Offset = StackAdj-MaxTCDelta;
995 assert(Offset >= 0 && "Offset should never be negative");
996
997 if (Offset) {
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000998 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +0000999 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Eli Bendersky44a40ca2013-02-05 21:53:29 +00001000 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, IsLP64,
1001 UseLEA, TII, *RegInfo);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001002 }
1003
1004 // Jump to label or value in register.
1005 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
Evan Chengd4b08732010-11-30 23:55:39 +00001006 MachineInstrBuilder MIB =
1007 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1008 ? X86::TAILJMPd : X86::TAILJMPd64));
1009 if (JumpTarget.isGlobal())
1010 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1011 JumpTarget.getTargetFlags());
1012 else {
1013 assert(JumpTarget.isSymbol());
1014 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1015 JumpTarget.getTargetFlags());
1016 }
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001017 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1018 MachineInstrBuilder MIB =
1019 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1020 ? X86::TAILJMPm : X86::TAILJMPm64));
1021 for (unsigned i = 0; i != 5; ++i)
1022 MIB.addOperand(MBBI->getOperand(i));
1023 } else if (RetOpcode == X86::TCRETURNri64) {
1024 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1025 addReg(JumpTarget.getReg(), RegState::Kill);
1026 } else {
1027 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1028 addReg(JumpTarget.getReg(), RegState::Kill);
1029 }
1030
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001031 MachineInstr *NewMI = std::prev(MBBI);
Jakob Stoklund Olesen33f5d142012-12-20 22:54:02 +00001032 NewMI->copyImplicitOps(MF, MBBI);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001033
1034 // Delete the pseudo instruction TCRETURN.
1035 MBB.erase(MBBI);
David Woodhouse4e033b02014-01-13 14:05:59 +00001036 } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
1037 RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
1038 (X86FI->getTCReturnAddrDelta() < 0)) {
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001039 // Add the return addr area delta back since we are not tail calling.
1040 int delta = -1*X86FI->getTCReturnAddrDelta();
Jakob Stoklund Olesen4bc5e382011-01-13 21:28:52 +00001041 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001042
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00001043 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001044 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Eli Bendersky44a40ca2013-02-05 21:53:29 +00001045 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, IsLP64, UseLEA, TII,
1046 *RegInfo);
Anton Korobeynikovf7183ed2010-11-15 00:06:54 +00001047 }
1048}
Anton Korobeynikov14ee3442010-11-18 23:25:52 +00001049
Eric Christopher4237bf12014-04-29 00:16:33 +00001050int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1051 int FI) const {
Eric Christopherd9134482014-08-04 21:25:23 +00001052 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
1053 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
Anton Korobeynikov46877782010-11-20 15:59:32 +00001054 const MachineFrameInfo *MFI = MF.getFrameInfo();
1055 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1056 uint64_t StackSize = MFI->getStackSize();
1057
Chad Rosierbdb08ac2012-07-10 17:45:53 +00001058 if (RegInfo->hasBasePointer(MF)) {
1059 assert (hasFP(MF) && "VLAs and dynamic stack realign, but no FP?!");
1060 if (FI < 0) {
1061 // Skip the saved EBP.
1062 return Offset + RegInfo->getSlotSize();
1063 } else {
1064 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1065 return Offset + StackSize;
1066 }
1067 } else if (RegInfo->needsStackRealignment(MF)) {
Anton Korobeynikov46877782010-11-20 15:59:32 +00001068 if (FI < 0) {
1069 // Skip the saved EBP.
Chad Rosier20b79dc2012-05-23 23:45:10 +00001070 return Offset + RegInfo->getSlotSize();
Anton Korobeynikov46877782010-11-20 15:59:32 +00001071 } else {
Duncan Sandsd278d352011-10-18 12:44:00 +00001072 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
Anton Korobeynikov46877782010-11-20 15:59:32 +00001073 return Offset + StackSize;
1074 }
1075 // FIXME: Support tail calls
1076 } else {
1077 if (!hasFP(MF))
1078 return Offset + StackSize;
1079
1080 // Skip the saved EBP.
Chad Rosier20b79dc2012-05-23 23:45:10 +00001081 Offset += RegInfo->getSlotSize();
Anton Korobeynikov46877782010-11-20 15:59:32 +00001082
1083 // Skip the RETADDR move area
1084 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1085 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1086 if (TailCallReturnAddrDelta < 0)
1087 Offset -= TailCallReturnAddrDelta;
1088 }
1089
1090 return Offset;
1091}
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001092
Alexey Samsonovc4b3ad82012-05-01 15:16:06 +00001093int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1094 unsigned &FrameReg) const {
Eric Christopherd9134482014-08-04 21:25:23 +00001095 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
1096 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
Alexey Samsonovc4b3ad82012-05-01 15:16:06 +00001097 // We can't calculate offset from frame pointer if the stack is realigned,
Chad Rosierbdb08ac2012-07-10 17:45:53 +00001098 // so enforce usage of stack/base pointer. The base pointer is used when we
1099 // have dynamic allocas in addition to dynamic realignment.
1100 if (RegInfo->hasBasePointer(MF))
1101 FrameReg = RegInfo->getBaseRegister();
1102 else if (RegInfo->needsStackRealignment(MF))
1103 FrameReg = RegInfo->getStackRegister();
1104 else
1105 FrameReg = RegInfo->getFrameRegister(MF);
Alexey Samsonovc4b3ad82012-05-01 15:16:06 +00001106 return getFrameIndexOffset(MF, FI);
1107}
1108
NAKAMURA Takumi1db59952014-06-25 12:41:52 +00001109bool X86FrameLowering::assignCalleeSavedSpillSlots(
1110 MachineFunction &MF, const TargetRegisterInfo *TRI,
1111 std::vector<CalleeSavedInfo> &CSI) const {
1112 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +00001113 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
1114 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
NAKAMURA Takumi1db59952014-06-25 12:41:52 +00001115 unsigned SlotSize = RegInfo->getSlotSize();
1116 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001117
NAKAMURA Takumi1db59952014-06-25 12:41:52 +00001118 unsigned CalleeSavedFrameSize = 0;
1119 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1120
1121 if (hasFP(MF)) {
1122 // emitPrologue always spills frame register the first thing.
1123 SpillSlotOffset -= SlotSize;
1124 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1125
1126 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1127 // the frame register, we can delete it from CSI list and not have to worry
1128 // about avoiding it later.
1129 unsigned FPReg = RegInfo->getFrameRegister(MF);
1130 for (unsigned i = 0; i < CSI.size(); ++i) {
1131 if (CSI[i].getReg() == FPReg) {
1132 CSI.erase(CSI.begin() + i);
1133 break;
1134 }
1135 }
1136 }
1137
1138 // Assign slots for GPRs. It increases frame size.
1139 for (unsigned i = CSI.size(); i != 0; --i) {
1140 unsigned Reg = CSI[i - 1].getReg();
1141
1142 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1143 continue;
1144
1145 SpillSlotOffset -= SlotSize;
1146 CalleeSavedFrameSize += SlotSize;
1147
1148 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1149 CSI[i - 1].setFrameIdx(SlotIndex);
1150 }
1151
1152 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1153
1154 // Assign slots for XMMs.
1155 for (unsigned i = CSI.size(); i != 0; --i) {
1156 unsigned Reg = CSI[i - 1].getReg();
1157 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1158 continue;
1159
1160 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1161 // ensure alignment
1162 SpillSlotOffset -= abs(SpillSlotOffset) % RC->getAlignment();
1163 // spill into slot
1164 SpillSlotOffset -= RC->getSize();
1165 int SlotIndex =
1166 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1167 CSI[i - 1].setFrameIdx(SlotIndex);
1168 MFI->ensureMaxAlignment(RC->getAlignment());
1169 }
1170
1171 return true;
1172}
1173
1174bool X86FrameLowering::spillCalleeSavedRegisters(
1175 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1176 const std::vector<CalleeSavedInfo> &CSI,
1177 const TargetRegisterInfo *TRI) const {
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001178 DebugLoc DL = MBB.findDebugLoc(MI);
1179
1180 MachineFunction &MF = *MBB.getParent();
Eric Christopherd9134482014-08-04 21:25:23 +00001181 const TargetInstrInfo &TII =
1182 *MF.getTarget().getSubtargetImpl()->getInstrInfo();
Eric Christopherf4381642014-06-05 22:00:31 +00001183 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001184
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001185 // Push GPRs. It increases frame size.
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001186 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1187 for (unsigned i = CSI.size(); i != 0; --i) {
NAKAMURA Takumic403be12014-06-25 12:40:56 +00001188 unsigned Reg = CSI[i - 1].getReg();
1189
1190 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001191 continue;
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001192 // Add the callee-saved register as live-in. It's killed at the spill.
1193 MBB.addLiveIn(Reg);
NAKAMURA Takumi1db59952014-06-25 12:41:52 +00001194
Charles Davis7ed40cb2011-06-12 01:45:54 +00001195 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1196 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001197 }
1198
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001199 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1200 // It can be done by spilling XMMs to stack frame.
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001201 for (unsigned i = CSI.size(); i != 0; --i) {
1202 unsigned Reg = CSI[i-1].getReg();
1203 if (X86::GR64RegClass.contains(Reg) ||
1204 X86::GR32RegClass.contains(Reg))
1205 continue;
1206 // Add the callee-saved register as live-in. It's killed at the spill.
1207 MBB.addLiveIn(Reg);
1208 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
NAKAMURA Takumic403be12014-06-25 12:40:56 +00001209
1210 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1211 TRI);
NAKAMURA Takumi1db59952014-06-25 12:41:52 +00001212 --MI;
1213 MI->setFlag(MachineInstr::FrameSetup);
1214 ++MI;
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001215 }
1216
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001217 return true;
1218}
1219
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001220bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001221 MachineBasicBlock::iterator MI,
1222 const std::vector<CalleeSavedInfo> &CSI,
1223 const TargetRegisterInfo *TRI) const {
1224 if (CSI.empty())
1225 return false;
1226
1227 DebugLoc DL = MBB.findDebugLoc(MI);
1228
1229 MachineFunction &MF = *MBB.getParent();
Eric Christopherd9134482014-08-04 21:25:23 +00001230 const TargetInstrInfo &TII =
1231 *MF.getTarget().getSubtargetImpl()->getInstrInfo();
Eric Christopherf4381642014-06-05 22:00:31 +00001232 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001233
1234 // Reload XMMs from stack frame.
1235 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1236 unsigned Reg = CSI[i].getReg();
1237 if (X86::GR64RegClass.contains(Reg) ||
1238 X86::GR32RegClass.contains(Reg))
1239 continue;
NAKAMURA Takumic403be12014-06-25 12:40:56 +00001240
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001241 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
NAKAMURA Takumic403be12014-06-25 12:40:56 +00001242 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001243 }
1244
1245 // POP GPRs.
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001246 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1247 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1248 unsigned Reg = CSI[i].getReg();
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001249 if (!X86::GR64RegClass.contains(Reg) &&
1250 !X86::GR32RegClass.contains(Reg))
1251 continue;
NAKAMURA Takumi1db59952014-06-25 12:41:52 +00001252
NAKAMURA Takumid4e50032011-02-27 08:47:19 +00001253 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
Anton Korobeynikovd08fbd12010-11-27 23:05:03 +00001254 }
1255 return true;
1256}
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001257
1258void
Anton Korobeynikov2f931282011-01-10 12:39:04 +00001259X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Eric Christopher11b05cc2014-06-05 00:09:05 +00001260 RegScavenger *RS) const {
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001261 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +00001262 const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
1263 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001264 unsigned SlotSize = RegInfo->getSlotSize();
1265
1266 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Tim Northoverecc018c2013-08-04 09:35:57 +00001267 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001268
1269 if (TailCallReturnAddrDelta < 0) {
1270 // create RETURNADDR area
1271 // arg
1272 // arg
1273 // RETADDR
1274 // { ...
1275 // RETADDR area
1276 // ...
1277 // }
1278 // [EBP]
1279 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
Tim Northoverecc018c2013-08-04 09:35:57 +00001280 TailCallReturnAddrDelta - SlotSize, true);
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001281 }
1282
Chad Rosierbdb08ac2012-07-10 17:45:53 +00001283 // Spill the BasePtr if it's used.
1284 if (RegInfo->hasBasePointer(MF))
1285 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
Anton Korobeynikov7283b8d2010-11-27 23:05:25 +00001286}
Rafael Espindolac2174212011-08-30 19:39:58 +00001287
1288static bool
1289HasNestArgument(const MachineFunction *MF) {
1290 const Function *F = MF->getFunction();
1291 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1292 I != E; I++) {
1293 if (I->hasNestAttr())
1294 return true;
1295 }
1296 return false;
1297}
1298
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001299/// GetScratchRegister - Get a temp register for performing work in the
1300/// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1301/// and the properties of the function either one or two registers will be
1302/// needed. Set primary to true for the first register, false for the second.
Rafael Espindolac2174212011-08-30 19:39:58 +00001303static unsigned
Rafael Espindolad90466b2012-01-11 19:00:37 +00001304GetScratchRegister(bool Is64Bit, const MachineFunction &MF, bool Primary) {
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001305 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1306
1307 // Erlang stuff.
1308 if (CallingConvention == CallingConv::HiPE) {
1309 if (Is64Bit)
1310 return Primary ? X86::R14 : X86::R13;
1311 else
1312 return Primary ? X86::EBX : X86::EDI;
1313 }
1314
David Blaikie46a9f012012-01-20 21:51:11 +00001315 if (Is64Bit)
Rafael Espindolad90466b2012-01-11 19:00:37 +00001316 return Primary ? X86::R11 : X86::R12;
Rafael Espindolac2174212011-08-30 19:39:58 +00001317
David Blaikie46a9f012012-01-20 21:51:11 +00001318 bool IsNested = HasNestArgument(&MF);
1319
1320 if (CallingConvention == CallingConv::X86_FastCall ||
1321 CallingConvention == CallingConv::Fast) {
1322 if (IsNested)
1323 report_fatal_error("Segmented stacks does not support fastcall with "
1324 "nested function.");
1325 return Primary ? X86::EAX : X86::ECX;
Rafael Espindolac2174212011-08-30 19:39:58 +00001326 }
David Blaikie46a9f012012-01-20 21:51:11 +00001327 if (IsNested)
1328 return Primary ? X86::EDX : X86::EAX;
1329 return Primary ? X86::ECX : X86::EAX;
Rafael Espindolac2174212011-08-30 19:39:58 +00001330}
1331
Sanjoy Das006e43b2011-12-03 09:32:07 +00001332// The stack limit in the TCB is set to this many bytes above the actual stack
1333// limit.
1334static const uint64_t kSplitStackAvailable = 256;
1335
Rafael Espindolac2174212011-08-30 19:39:58 +00001336void
1337X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1338 MachineBasicBlock &prologueMBB = MF.front();
1339 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopherd9134482014-08-04 21:25:23 +00001340 const TargetInstrInfo &TII =
1341 *MF.getTarget().getSubtargetImpl()->getInstrInfo();
Rafael Espindolac2174212011-08-30 19:39:58 +00001342 uint64_t StackSize;
Eric Christopherf4381642014-06-05 22:00:31 +00001343 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
Rafael Espindolac2174212011-08-30 19:39:58 +00001344 bool Is64Bit = STI.is64Bit();
1345 unsigned TlsReg, TlsOffset;
1346 DebugLoc DL;
Rafael Espindolac2174212011-08-30 19:39:58 +00001347
Rafael Espindolad90466b2012-01-11 19:00:37 +00001348 unsigned ScratchReg = GetScratchRegister(Is64Bit, MF, true);
Rafael Espindolac2174212011-08-30 19:39:58 +00001349 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1350 "Scratch register is live-in");
1351
1352 if (MF.getFunction()->isVarArg())
1353 report_fatal_error("Segmented stacks do not support vararg functions.");
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001354 if (!STI.isTargetLinux() && !STI.isTargetDarwin() &&
Reid Kleckner10110272014-04-01 18:34:21 +00001355 !STI.isTargetWin32() && !STI.isTargetWin64() && !STI.isTargetFreeBSD())
Rafael Espindola00e861e2012-01-12 20:24:30 +00001356 report_fatal_error("Segmented stacks not supported on this platform.");
Rafael Espindolac2174212011-08-30 19:39:58 +00001357
Tim Northoverf9e798b2014-05-22 13:03:43 +00001358 // Eventually StackSize will be calculated by a link-time pass; which will
1359 // also decide whether checking code needs to be injected into this particular
1360 // prologue.
1361 StackSize = MFI->getStackSize();
1362
1363 // Do not generate a prologue for functions with a stack of size zero
1364 if (StackSize == 0)
1365 return;
1366
Rafael Espindolac2174212011-08-30 19:39:58 +00001367 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1368 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1369 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1370 bool IsNested = false;
1371
1372 // We need to know if the function has a nest argument only in 64 bit mode.
1373 if (Is64Bit)
1374 IsNested = HasNestArgument(&MF);
1375
Bill Wendling25f6d3e2011-10-13 08:24:19 +00001376 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1377 // allocMBB needs to be last (terminating) instruction.
Bill Wendling25f6d3e2011-10-13 08:24:19 +00001378
Rafael Espindolac2174212011-08-30 19:39:58 +00001379 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1380 e = prologueMBB.livein_end(); i != e; i++) {
1381 allocMBB->addLiveIn(*i);
1382 checkMBB->addLiveIn(*i);
1383 }
1384
1385 if (IsNested)
Rafael Espindola66393c12011-10-26 21:12:27 +00001386 allocMBB->addLiveIn(X86::R10);
1387
Rafael Espindolac2174212011-08-30 19:39:58 +00001388 MF.push_front(allocMBB);
1389 MF.push_front(checkMBB);
1390
Rafael Espindolad90466b2012-01-11 19:00:37 +00001391 // When the frame size is less than 256 we just compare the stack
1392 // boundary directly to the value of the stack pointer, per gcc.
1393 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1394
Rafael Espindolac2174212011-08-30 19:39:58 +00001395 // Read the limit off the current stacklet off the stack_guard location.
1396 if (Is64Bit) {
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001397 if (STI.isTargetLinux()) {
Rafael Espindolad90466b2012-01-11 19:00:37 +00001398 TlsReg = X86::FS;
1399 TlsOffset = 0x70;
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001400 } else if (STI.isTargetDarwin()) {
Rafael Espindolad90466b2012-01-11 19:00:37 +00001401 TlsReg = X86::GS;
1402 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
Reid Kleckner10110272014-04-01 18:34:21 +00001403 } else if (STI.isTargetWin64()) {
1404 TlsReg = X86::GS;
1405 TlsOffset = 0x28; // pvArbitrary, reserved for application use
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001406 } else if (STI.isTargetFreeBSD()) {
Rafael Espindola00e861e2012-01-12 20:24:30 +00001407 TlsReg = X86::FS;
1408 TlsOffset = 0x18;
Rafael Espindola10745d32012-01-12 20:22:08 +00001409 } else {
1410 report_fatal_error("Segmented stacks not supported on this platform.");
Rafael Espindolad90466b2012-01-11 19:00:37 +00001411 }
Rafael Espindolac2174212011-08-30 19:39:58 +00001412
Rafael Espindolad90466b2012-01-11 19:00:37 +00001413 if (CompareStackPointer)
Sanjoy Das006e43b2011-12-03 09:32:07 +00001414 ScratchReg = X86::RSP;
1415 else
1416 BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RSP)
Rafael Espindola6635ae12012-01-11 18:14:03 +00001417 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
Sanjoy Das006e43b2011-12-03 09:32:07 +00001418
Rafael Espindolac2174212011-08-30 19:39:58 +00001419 BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
Rafael Espindola6635ae12012-01-11 18:14:03 +00001420 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
Rafael Espindolac2174212011-08-30 19:39:58 +00001421 } else {
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001422 if (STI.isTargetLinux()) {
Rafael Espindola10745d32012-01-12 20:22:08 +00001423 TlsReg = X86::GS;
1424 TlsOffset = 0x30;
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001425 } else if (STI.isTargetDarwin()) {
Rafael Espindola10745d32012-01-12 20:22:08 +00001426 TlsReg = X86::GS;
1427 TlsOffset = 0x48 + 90*4;
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001428 } else if (STI.isTargetWin32()) {
Rafael Espindola10745d32012-01-12 20:22:08 +00001429 TlsReg = X86::FS;
1430 TlsOffset = 0x14; // pvArbitrary, reserved for application use
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001431 } else if (STI.isTargetFreeBSD()) {
Rafael Espindola00e861e2012-01-12 20:24:30 +00001432 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
Rafael Espindola10745d32012-01-12 20:22:08 +00001433 } else {
1434 report_fatal_error("Segmented stacks not supported on this platform.");
1435 }
Rafael Espindolac2174212011-08-30 19:39:58 +00001436
Rafael Espindolad90466b2012-01-11 19:00:37 +00001437 if (CompareStackPointer)
Sanjoy Das006e43b2011-12-03 09:32:07 +00001438 ScratchReg = X86::ESP;
1439 else
1440 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
Rafael Espindola6635ae12012-01-11 18:14:03 +00001441 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
Sanjoy Das006e43b2011-12-03 09:32:07 +00001442
Reid Kleckner10110272014-04-01 18:34:21 +00001443 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64()) {
Rafael Espindolad90466b2012-01-11 19:00:37 +00001444 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1445 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001446 } else if (STI.isTargetDarwin()) {
Rafael Espindolad90466b2012-01-11 19:00:37 +00001447
Eric Christopher4237bf12014-04-29 00:16:33 +00001448 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
Rafael Espindolad90466b2012-01-11 19:00:37 +00001449 unsigned ScratchReg2;
1450 bool SaveScratch2;
1451 if (CompareStackPointer) {
Eric Christopher4237bf12014-04-29 00:16:33 +00001452 // The primary scratch register is available for holding the TLS offset.
Rafael Espindolad90466b2012-01-11 19:00:37 +00001453 ScratchReg2 = GetScratchRegister(Is64Bit, MF, true);
1454 SaveScratch2 = false;
1455 } else {
1456 // Need to use a second register to hold the TLS offset
1457 ScratchReg2 = GetScratchRegister(Is64Bit, MF, false);
1458
Eric Christopher4237bf12014-04-29 00:16:33 +00001459 // Unfortunately, with fastcc the second scratch register may hold an
1460 // argument.
Rafael Espindolad90466b2012-01-11 19:00:37 +00001461 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1462 }
1463
Eric Christopher4237bf12014-04-29 00:16:33 +00001464 // If Scratch2 is live-in then it needs to be saved.
Rafael Espindolad90466b2012-01-11 19:00:37 +00001465 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1466 "Scratch register is live-in and not saved");
1467
1468 if (SaveScratch2)
1469 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1470 .addReg(ScratchReg2, RegState::Kill);
1471
1472 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1473 .addImm(TlsOffset);
1474 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1475 .addReg(ScratchReg)
1476 .addReg(ScratchReg2).addImm(1).addReg(0)
1477 .addImm(0)
1478 .addReg(TlsReg);
1479
1480 if (SaveScratch2)
1481 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1482 }
Rafael Espindolac2174212011-08-30 19:39:58 +00001483 }
1484
1485 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1486 // It jumps to normal execution of the function body.
Rafael Espindola2b894482012-01-11 18:23:35 +00001487 BuildMI(checkMBB, DL, TII.get(X86::JA_4)).addMBB(&prologueMBB);
Rafael Espindolac2174212011-08-30 19:39:58 +00001488
1489 // On 32 bit we first push the arguments size and then the frame size. On 64
1490 // bit, we pass the stack frame size in r10 and the argument size in r11.
1491 if (Is64Bit) {
1492 // Functions with nested arguments use R10, so it needs to be saved across
1493 // the call to _morestack
1494
1495 if (IsNested)
1496 BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::RAX).addReg(X86::R10);
1497
1498 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R10)
1499 .addImm(StackSize);
1500 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R11)
1501 .addImm(X86FI->getArgumentStackSize());
1502 MF.getRegInfo().setPhysRegUsed(X86::R10);
1503 MF.getRegInfo().setPhysRegUsed(X86::R11);
1504 } else {
Rafael Espindolac2174212011-08-30 19:39:58 +00001505 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1506 .addImm(X86FI->getArgumentStackSize());
1507 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1508 .addImm(StackSize);
1509 }
1510
1511 // __morestack is in libgcc
1512 if (Is64Bit)
1513 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1514 .addExternalSymbol("__morestack");
1515 else
1516 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1517 .addExternalSymbol("__morestack");
1518
Bill Wendling25f6d3e2011-10-13 08:24:19 +00001519 if (IsNested)
Rafael Espindola66393c12011-10-26 21:12:27 +00001520 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1521 else
1522 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
Bill Wendling25f6d3e2011-10-13 08:24:19 +00001523
Rafael Espindola66393c12011-10-26 21:12:27 +00001524 allocMBB->addSuccessor(&prologueMBB);
Bill Wendling25f6d3e2011-10-13 08:24:19 +00001525
Rafael Espindolac2174212011-08-30 19:39:58 +00001526 checkMBB->addSuccessor(allocMBB);
1527 checkMBB->addSuccessor(&prologueMBB);
1528
Jakob Stoklund Olesen55cf2ed2011-09-24 01:11:19 +00001529#ifdef XDEBUG
Rafael Espindolac2174212011-08-30 19:39:58 +00001530 MF.verify();
1531#endif
1532}
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001533
Yiannis Tsiourisd4842e52013-02-28 16:59:10 +00001534/// Erlang programs may need a special prologue to handle the stack size they
1535/// might need at runtime. That is because Erlang/OTP does not implement a C
1536/// stack but uses a custom implementation of hybrid stack/heap architecture.
1537/// (for more information see Eric Stenman's Ph.D. thesis:
1538/// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1539///
1540/// CheckStack:
Eric Christopher4237bf12014-04-29 00:16:33 +00001541/// temp0 = sp - MaxStack
1542/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
Yiannis Tsiourisd4842e52013-02-28 16:59:10 +00001543/// OldStart:
Eric Christopher4237bf12014-04-29 00:16:33 +00001544/// ...
Yiannis Tsiourisd4842e52013-02-28 16:59:10 +00001545/// IncStack:
Eric Christopher4237bf12014-04-29 00:16:33 +00001546/// call inc_stack # doubles the stack space
1547/// temp0 = sp - MaxStack
1548/// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001549void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
Eric Christopherd9134482014-08-04 21:25:23 +00001550 const TargetInstrInfo &TII =
1551 *MF.getTarget().getSubtargetImpl()->getInstrInfo();
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001552 MachineFrameInfo *MFI = MF.getFrameInfo();
Eric Christopher11b05cc2014-06-05 00:09:05 +00001553 const unsigned SlotSize =
Eric Christopherd9134482014-08-04 21:25:23 +00001554 static_cast<const X86RegisterInfo *>(
1555 MF.getTarget().getSubtargetImpl()->getRegisterInfo())->getSlotSize();
Eric Christopherf4381642014-06-05 22:00:31 +00001556 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001557 const bool Is64Bit = STI.is64Bit();
1558 DebugLoc DL;
1559 // HiPE-specific values
1560 const unsigned HipeLeafWords = 24;
1561 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1562 const unsigned Guaranteed = HipeLeafWords * SlotSize;
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001563 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1564 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1565 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001566
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001567 assert(STI.isTargetLinux() &&
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001568 "HiPE prologue is only supported on Linux operating systems.");
1569
1570 // Compute the largest caller's frame that is needed to fit the callees'
1571 // frames. This 'MaxStack' is computed from:
1572 //
1573 // a) the fixed frame size, which is the space needed for all spilled temps,
1574 // b) outgoing on-stack parameter areas, and
1575 // c) the minimum stack space this function needs to make available for the
1576 // functions it calls (a tunable ABI property).
1577 if (MFI->hasCalls()) {
1578 unsigned MoreStackForCalls = 0;
1579
1580 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1581 MBBI != MBBE; ++MBBI)
1582 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001583 MI != ME; ++MI) {
1584 if (!MI->isCall())
1585 continue;
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001586
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001587 // Get callee operand.
1588 const MachineOperand &MO = MI->getOperand(0);
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001589
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001590 // Only take account of global function calls (no closures etc.).
1591 if (!MO.isGlobal())
1592 continue;
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001593
Benjamin Kramer1cb826b2013-02-19 17:32:57 +00001594 const Function *F = dyn_cast<Function>(MO.getGlobal());
1595 if (!F)
1596 continue;
1597
1598 // Do not update 'MaxStack' for primitive and built-in functions
1599 // (encoded with names either starting with "erlang."/"bif_" or not
1600 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1601 // "_", such as the BIF "suspend_0") as they are executed on another
1602 // stack.
1603 if (F->getName().find("erlang.") != StringRef::npos ||
1604 F->getName().find("bif_") != StringRef::npos ||
1605 F->getName().find_first_of("._") == StringRef::npos)
1606 continue;
1607
1608 unsigned CalleeStkArity =
1609 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1610 if (HipeLeafWords - 1 > CalleeStkArity)
1611 MoreStackForCalls = std::max(MoreStackForCalls,
1612 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1613 }
Benjamin Kramer53bc37c2013-02-18 20:55:12 +00001614 MaxStack += MoreStackForCalls;
1615 }
1616
1617 // If the stack frame needed is larger than the guaranteed then runtime checks
1618 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1619 if (MaxStack > Guaranteed) {
1620 MachineBasicBlock &prologueMBB = MF.front();
1621 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1622 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1623
1624 for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
1625 E = prologueMBB.livein_end(); I != E; I++) {
1626 stackCheckMBB->addLiveIn(*I);
1627 incStackMBB->addLiveIn(*I);
1628 }
1629
1630 MF.push_front(incStackMBB);
1631 MF.push_front(stackCheckMBB);
1632
1633 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1634 unsigned LEAop, CMPop, CALLop;
1635 if (Is64Bit) {
1636 SPReg = X86::RSP;
1637 PReg = X86::RBP;
1638 LEAop = X86::LEA64r;
1639 CMPop = X86::CMP64rm;
1640 CALLop = X86::CALL64pcrel32;
1641 SPLimitOffset = 0x90;
1642 } else {
1643 SPReg = X86::ESP;
1644 PReg = X86::EBP;
1645 LEAop = X86::LEA32r;
1646 CMPop = X86::CMP32rm;
1647 CALLop = X86::CALLpcrel32;
1648 SPLimitOffset = 0x4c;
1649 }
1650
1651 ScratchReg = GetScratchRegister(Is64Bit, MF, true);
1652 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1653 "HiPE prologue scratch register is live-in");
1654
1655 // Create new MBB for StackCheck:
1656 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1657 SPReg, false, -MaxStack);
1658 // SPLimitOffset is in a fixed heap location (pointed by BP).
1659 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1660 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1661 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_4)).addMBB(&prologueMBB);
1662
1663 // Create new MBB for IncStack:
1664 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1665 addExternalSymbol("inc_stack_0");
1666 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1667 SPReg, false, -MaxStack);
1668 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1669 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1670 BuildMI(incStackMBB, DL, TII.get(X86::JLE_4)).addMBB(incStackMBB);
1671
1672 stackCheckMBB->addSuccessor(&prologueMBB, 99);
1673 stackCheckMBB->addSuccessor(incStackMBB, 1);
1674 incStackMBB->addSuccessor(&prologueMBB, 99);
1675 incStackMBB->addSuccessor(incStackMBB, 1);
1676 }
1677#ifdef XDEBUG
1678 MF.verify();
1679#endif
1680}
Eli Bendersky8da87162013-02-21 20:05:00 +00001681
1682void X86FrameLowering::
1683eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1684 MachineBasicBlock::iterator I) const {
Eric Christopherd9134482014-08-04 21:25:23 +00001685 const TargetInstrInfo &TII =
1686 *MF.getTarget().getSubtargetImpl()->getInstrInfo();
Eric Christopher11b05cc2014-06-05 00:09:05 +00001687 const X86RegisterInfo &RegInfo =
Eric Christopherd9134482014-08-04 21:25:23 +00001688 *static_cast<const X86RegisterInfo *>(
1689 MF.getTarget().getSubtargetImpl()->getRegisterInfo());
Eli Bendersky8da87162013-02-21 20:05:00 +00001690 unsigned StackPtr = RegInfo.getStackRegister();
1691 bool reseveCallFrame = hasReservedCallFrame(MF);
1692 int Opcode = I->getOpcode();
1693 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
Eric Christopherf4381642014-06-05 22:00:31 +00001694 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
Eli Bendersky8da87162013-02-21 20:05:00 +00001695 bool IsLP64 = STI.isTarget64BitLP64();
1696 DebugLoc DL = I->getDebugLoc();
1697 uint64_t Amount = !reseveCallFrame ? I->getOperand(0).getImm() : 0;
1698 uint64_t CalleeAmt = isDestroy ? I->getOperand(1).getImm() : 0;
1699 I = MBB.erase(I);
1700
1701 if (!reseveCallFrame) {
1702 // If the stack pointer can be changed after prologue, turn the
1703 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1704 // adjcallstackdown instruction into 'add ESP, <amt>'
1705 // TODO: consider using push / pop instead of sub + store / add
1706 if (Amount == 0)
1707 return;
1708
1709 // We need to keep the stack aligned properly. To do this, we round the
1710 // amount of space needed for the outgoing arguments up to the next
1711 // alignment boundary.
Eric Christopherd9134482014-08-04 21:25:23 +00001712 unsigned StackAlign = MF.getTarget()
1713 .getSubtargetImpl()
1714 ->getFrameLowering()
1715 ->getStackAlignment();
Eli Bendersky8da87162013-02-21 20:05:00 +00001716 Amount = (Amount + StackAlign - 1) / StackAlign * StackAlign;
1717
Craig Topper062a2ba2014-04-25 05:30:21 +00001718 MachineInstr *New = nullptr;
Eli Bendersky8da87162013-02-21 20:05:00 +00001719 if (Opcode == TII.getCallFrameSetupOpcode()) {
1720 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)),
1721 StackPtr)
1722 .addReg(StackPtr)
1723 .addImm(Amount);
1724 } else {
1725 assert(Opcode == TII.getCallFrameDestroyOpcode());
1726
1727 // Factor out the amount the callee already popped.
1728 Amount -= CalleeAmt;
1729
1730 if (Amount) {
1731 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1732 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1733 .addReg(StackPtr).addImm(Amount);
1734 }
1735 }
1736
1737 if (New) {
1738 // The EFLAGS implicit def is dead.
1739 New->getOperand(3).setIsDead();
1740
1741 // Replace the pseudo instruction with a new instruction.
1742 MBB.insert(I, New);
1743 }
1744
1745 return;
1746 }
1747
1748 if (Opcode == TII.getCallFrameDestroyOpcode() && CalleeAmt) {
1749 // If we are performing frame pointer elimination and if the callee pops
1750 // something off the stack pointer, add it back. We do this until we have
1751 // more advanced stack pointer tracking ability.
1752 unsigned Opc = getSUBriOpcode(IsLP64, CalleeAmt);
1753 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1754 .addReg(StackPtr).addImm(CalleeAmt);
1755
1756 // The EFLAGS implicit def is dead.
1757 New->getOperand(3).setIsDead();
1758
1759 // We are not tracking the stack pointer adjustment by the callee, so make
1760 // sure we restore the stack pointer immediately after the call, there may
1761 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1762 MachineBasicBlock::iterator B = MBB.begin();
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00001763 while (I != B && !std::prev(I)->isCall())
Eli Bendersky8da87162013-02-21 20:05:00 +00001764 --I;
1765 MBB.insert(I, New);
1766 }
1767}
1768