blob: 6e2b3df7a4a9b31d6cd20c74abfa56f5e8261e2c [file] [log] [blame]
Nick Lewycky3c2f0a12011-06-14 03:23:52 +00001//=======- X86FrameLowering.cpp - X86 Frame Information --------*- C++ -*-====//
Anton Korobeynikov33464912010-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 Korobeynikov16c29b52011-01-10 12:39:04 +000010// This file contains the X86 implementation of TargetFrameLowering class.
Anton Korobeynikov33464912010-11-15 00:06:54 +000011//
12//===----------------------------------------------------------------------===//
13
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000014#include "X86FrameLowering.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000015#include "X86InstrBuilder.h"
16#include "X86InstrInfo.h"
17#include "X86MachineFunctionInfo.h"
Rafael Espindola76927d752011-08-30 19:39:58 +000018#include "X86Subtarget.h"
Anton Korobeynikovd9e33852010-11-18 23:25:52 +000019#include "X86TargetMachine.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000020#include "llvm/Function.h"
21#include "llvm/CodeGen/MachineFrameInfo.h"
22#include "llvm/CodeGen/MachineFunction.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachineModuleInfo.h"
25#include "llvm/CodeGen/MachineRegisterInfo.h"
Rafael Espindolaf0adba92011-04-15 15:11:06 +000026#include "llvm/MC/MCAsmInfo.h"
Bill Wendling6a6b8c32011-07-07 00:54:13 +000027#include "llvm/MC/MCSymbol.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000028#include "llvm/Target/TargetData.h"
29#include "llvm/Target/TargetOptions.h"
30#include "llvm/Support/CommandLine.h"
Evan Cheng7158e082011-01-03 22:53:22 +000031#include "llvm/ADT/SmallSet.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000032
33using namespace llvm;
34
35// FIXME: completely move here.
36extern cl::opt<bool> ForceStackAlign;
37
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000038bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000039 return !MF.getFrameInfo()->hasVarSizedObjects();
40}
41
42/// hasFP - Return true if the specified function should have a dedicated frame
43/// pointer register. This is true if the function has variable sized allocas
44/// or if frame pointer elimination is disabled.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000045bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000046 const MachineFrameInfo *MFI = MF.getFrameInfo();
47 const MachineModuleInfo &MMI = MF.getMMI();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +000048 const TargetRegisterInfo *RI = TM.getRegisterInfo();
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000049
Nick Lewycky8a8d4792011-12-02 22:16:29 +000050 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000051 RI->needsStackRealignment(MF) ||
52 MFI->hasVarSizedObjects() ||
53 MFI->isFrameAddressTaken() ||
54 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
55 MMI.callsUnwindInit());
56}
57
Anton Korobeynikov33464912010-11-15 00:06:54 +000058static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
59 if (is64Bit) {
60 if (isInt<8>(Imm))
61 return X86::SUB64ri8;
62 return X86::SUB64ri32;
63 } else {
64 if (isInt<8>(Imm))
65 return X86::SUB32ri8;
66 return X86::SUB32ri;
67 }
68}
69
70static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
71 if (is64Bit) {
72 if (isInt<8>(Imm))
73 return X86::ADD64ri8;
74 return X86::ADD64ri32;
75 } else {
76 if (isInt<8>(Imm))
77 return X86::ADD32ri8;
78 return X86::ADD32ri;
79 }
80}
81
Evan Cheng7158e082011-01-03 22:53:22 +000082/// findDeadCallerSavedReg - Return a caller-saved register that isn't live
83/// when it reaches the "return" instruction. We can then pop a stack object
84/// to this register without worry about clobbering it.
85static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
86 MachineBasicBlock::iterator &MBBI,
87 const TargetRegisterInfo &TRI,
88 bool Is64Bit) {
89 const MachineFunction *MF = MBB.getParent();
90 const Function *F = MF->getFunction();
91 if (!F || MF->getMMI().callsEHReturn())
92 return 0;
93
94 static const unsigned CallerSavedRegs32Bit[] = {
Andrew Trick32a183c2011-08-12 00:49:19 +000095 X86::EAX, X86::EDX, X86::ECX, 0
Evan Cheng7158e082011-01-03 22:53:22 +000096 };
97
98 static const unsigned CallerSavedRegs64Bit[] = {
99 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
Andrew Trick32a183c2011-08-12 00:49:19 +0000100 X86::R8, X86::R9, X86::R10, X86::R11, 0
Evan Cheng7158e082011-01-03 22:53:22 +0000101 };
102
103 unsigned Opc = MBBI->getOpcode();
104 switch (Opc) {
105 default: return 0;
106 case X86::RET:
107 case X86::RETI:
108 case X86::TCRETURNdi:
109 case X86::TCRETURNri:
110 case X86::TCRETURNmi:
111 case X86::TCRETURNdi64:
112 case X86::TCRETURNri64:
113 case X86::TCRETURNmi64:
114 case X86::EH_RETURN:
115 case X86::EH_RETURN64: {
116 SmallSet<unsigned, 8> Uses;
117 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
118 MachineOperand &MO = MBBI->getOperand(i);
119 if (!MO.isReg() || MO.isDef())
120 continue;
121 unsigned Reg = MO.getReg();
122 if (!Reg)
123 continue;
124 for (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
125 Uses.insert(*AsI);
126 }
127
128 const unsigned *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
129 for (; *CS; ++CS)
130 if (!Uses.count(*CS))
131 return *CS;
132 }
133 }
134
135 return 0;
136}
137
138
Anton Korobeynikov33464912010-11-15 00:06:54 +0000139/// emitSPUpdate - Emit a series of instructions to increment / decrement the
140/// stack pointer by a constant value.
141static
142void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
Evan Cheng7158e082011-01-03 22:53:22 +0000143 unsigned StackPtr, int64_t NumBytes,
144 bool Is64Bit, const TargetInstrInfo &TII,
145 const TargetRegisterInfo &TRI) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000146 bool isSub = NumBytes < 0;
147 uint64_t Offset = isSub ? -NumBytes : NumBytes;
148 unsigned Opc = isSub ?
149 getSUBriOpcode(Is64Bit, Offset) :
150 getADDriOpcode(Is64Bit, Offset);
151 uint64_t Chunk = (1LL << 31) - 1;
152 DebugLoc DL = MBB.findDebugLoc(MBBI);
153
154 while (Offset) {
155 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
Evan Cheng7158e082011-01-03 22:53:22 +0000156 if (ThisVal == (Is64Bit ? 8 : 4)) {
157 // Use push / pop instead.
158 unsigned Reg = isSub
Dale Johannesen1e08cd12011-01-04 19:31:24 +0000159 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
Evan Cheng7158e082011-01-03 22:53:22 +0000160 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
161 if (Reg) {
162 Opc = isSub
163 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
164 : (Is64Bit ? X86::POP64r : X86::POP32r);
Charles Davisaff232a2011-06-12 01:45:54 +0000165 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
Evan Cheng7158e082011-01-03 22:53:22 +0000166 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
Charles Davisaff232a2011-06-12 01:45:54 +0000167 if (isSub)
168 MI->setFlag(MachineInstr::FrameSetup);
Evan Cheng7158e082011-01-03 22:53:22 +0000169 Offset -= ThisVal;
170 continue;
171 }
172 }
173
Anton Korobeynikov33464912010-11-15 00:06:54 +0000174 MachineInstr *MI =
175 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
Evan Cheng7158e082011-01-03 22:53:22 +0000176 .addReg(StackPtr)
177 .addImm(ThisVal);
Charles Davisaff232a2011-06-12 01:45:54 +0000178 if (isSub)
179 MI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000180 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
181 Offset -= ThisVal;
182 }
183}
184
185/// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
186static
187void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
188 unsigned StackPtr, uint64_t *NumBytes = NULL) {
189 if (MBBI == MBB.begin()) return;
190
191 MachineBasicBlock::iterator PI = prior(MBBI);
192 unsigned Opc = PI->getOpcode();
193 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
194 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
195 PI->getOperand(0).getReg() == StackPtr) {
196 if (NumBytes)
197 *NumBytes += PI->getOperand(2).getImm();
198 MBB.erase(PI);
199 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
200 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
201 PI->getOperand(0).getReg() == StackPtr) {
202 if (NumBytes)
203 *NumBytes -= PI->getOperand(2).getImm();
204 MBB.erase(PI);
205 }
206}
207
208/// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
209static
210void mergeSPUpdatesDown(MachineBasicBlock &MBB,
211 MachineBasicBlock::iterator &MBBI,
212 unsigned StackPtr, uint64_t *NumBytes = NULL) {
Sanjoy Dasfc926122011-12-01 19:15:08 +0000213 // FIXME: THIS ISN'T RUN!!!
Anton Korobeynikov33464912010-11-15 00:06:54 +0000214 return;
215
216 if (MBBI == MBB.end()) return;
217
218 MachineBasicBlock::iterator NI = llvm::next(MBBI);
219 if (NI == MBB.end()) return;
220
221 unsigned Opc = NI->getOpcode();
222 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
223 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
224 NI->getOperand(0).getReg() == StackPtr) {
225 if (NumBytes)
226 *NumBytes -= NI->getOperand(2).getImm();
227 MBB.erase(NI);
228 MBBI = NI;
229 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
230 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
231 NI->getOperand(0).getReg() == StackPtr) {
232 if (NumBytes)
233 *NumBytes += NI->getOperand(2).getImm();
234 MBB.erase(NI);
235 MBBI = NI;
236 }
237}
238
239/// mergeSPUpdates - Checks the instruction before/after the passed
240/// instruction. If it is an ADD/SUB instruction it is deleted argument and the
241/// stack adjustment is returned as a positive value for ADD and a negative for
242/// SUB.
243static int mergeSPUpdates(MachineBasicBlock &MBB,
244 MachineBasicBlock::iterator &MBBI,
245 unsigned StackPtr,
246 bool doMergeWithPrevious) {
247 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
248 (!doMergeWithPrevious && MBBI == MBB.end()))
249 return 0;
250
251 MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
252 MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
253 unsigned Opc = PI->getOpcode();
254 int Offset = 0;
255
256 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
257 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
258 PI->getOperand(0).getReg() == StackPtr){
259 Offset += PI->getOperand(2).getImm();
260 MBB.erase(PI);
261 if (!doMergeWithPrevious) MBBI = NI;
262 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
263 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
264 PI->getOperand(0).getReg() == StackPtr) {
265 Offset -= PI->getOperand(2).getImm();
266 MBB.erase(PI);
267 if (!doMergeWithPrevious) MBBI = NI;
268 }
269
270 return Offset;
271}
272
273static bool isEAXLiveIn(MachineFunction &MF) {
274 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
275 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
276 unsigned Reg = II->first;
277
278 if (Reg == X86::EAX || Reg == X86::AX ||
279 Reg == X86::AH || Reg == X86::AL)
280 return true;
281 }
282
283 return false;
284}
285
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000286void X86FrameLowering::emitCalleeSavedFrameMoves(MachineFunction &MF,
Bill Wendling09b02c82011-07-25 18:00:28 +0000287 MCSymbol *Label,
288 unsigned FramePtr) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000289 MachineFrameInfo *MFI = MF.getFrameInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000290 MachineModuleInfo &MMI = MF.getMMI();
291
292 // Add callee saved registers to move list.
293 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
294 if (CSI.empty()) return;
295
296 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000297 const TargetData *TD = TM.getTargetData();
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000298 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000299
300 // Calculate amount of bytes used for return address storing.
Anton Korobeynikove7499112011-01-14 21:57:58 +0000301 int stackGrowth = -TD->getPointerSize();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000302
303 // FIXME: This is dirty hack. The code itself is pretty mess right now.
304 // It should be rewritten from scratch and generalized sometimes.
305
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000306 // Determine maximum offset (minimum due to stack growth).
Anton Korobeynikov33464912010-11-15 00:06:54 +0000307 int64_t MaxOffset = 0;
308 for (std::vector<CalleeSavedInfo>::const_iterator
309 I = CSI.begin(), E = CSI.end(); I != E; ++I)
310 MaxOffset = std::min(MaxOffset,
311 MFI->getObjectOffset(I->getFrameIdx()));
312
313 // Calculate offsets.
314 int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
315 for (std::vector<CalleeSavedInfo>::const_iterator
316 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
317 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
318 unsigned Reg = I->getReg();
319 Offset = MaxOffset - Offset + saveAreaOffset;
320
321 // Don't output a new machine move if we're re-saving the frame
322 // pointer. This happens when the PrologEpilogInserter has inserted an extra
323 // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
324 // generates one when frame pointers are used. If we generate a "machine
325 // move" for this extra "PUSH", the linker will lose track of the fact that
326 // the frame pointer should have the value of the first "PUSH" when it's
327 // trying to unwind.
NAKAMURA Takumi27635382011-02-05 15:10:54 +0000328 //
Anton Korobeynikov33464912010-11-15 00:06:54 +0000329 // FIXME: This looks inelegant. It's possibly correct, but it's covering up
330 // another bug. I.e., one where we generate a prolog like this:
331 //
332 // pushl %ebp
333 // movl %esp, %ebp
334 // pushl %ebp
335 // pushl %esi
336 // ...
337 //
338 // The immediate re-push of EBP is unnecessary. At the least, it's an
339 // optimization bug. EBP can be used as a scratch register in certain
340 // cases, but probably not when we have a frame pointer.
341 if (HasFP && FramePtr == Reg)
342 continue;
343
344 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
345 MachineLocation CSSrc(Reg);
346 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
347 }
348}
349
Bill Wendling09b02c82011-07-25 18:00:28 +0000350/// getCompactUnwindRegNum - Get the compact unwind number for a given
351/// register. The number corresponds to the enum lists in
352/// compact_unwind_encoding.h.
353static int getCompactUnwindRegNum(const unsigned *CURegs, unsigned Reg) {
354 int Idx = 1;
355 for (; *CURegs; ++CURegs, ++Idx)
356 if (*CURegs == Reg)
357 return Idx;
358
359 return -1;
360}
361
Bill Wendling57a3cd22011-12-06 21:23:42 +0000362// Number of registers that can be saved in a compact unwind encoding.
363#define CU_NUM_SAVED_REGS 6
364
Bill Wendling09b02c82011-07-25 18:00:28 +0000365/// encodeCompactUnwindRegistersWithoutFrame - Create the permutation encoding
366/// used with frameless stacks. It is passed the number of registers to be saved
367/// and an array of the registers saved.
Bill Wendling57a3cd22011-12-06 21:23:42 +0000368static uint32_t
369encodeCompactUnwindRegistersWithoutFrame(unsigned SavedRegs[CU_NUM_SAVED_REGS],
370 unsigned RegCount, bool Is64Bit) {
Bill Wendling09b02c82011-07-25 18:00:28 +0000371 // The saved registers are numbered from 1 to 6. In order to encode the order
372 // in which they were saved, we re-number them according to their place in the
373 // register order. The re-numbering is relative to the last re-numbered
374 // register. E.g., if we have registers {6, 2, 4, 5} saved in that order:
375 //
376 // Orig Re-Num
377 // ---- ------
378 // 6 6
379 // 2 2
380 // 4 3
381 // 5 3
382 //
383 static const unsigned CU32BitRegs[] = {
384 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
385 };
386 static const unsigned CU64BitRegs[] = {
387 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
388 };
389 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
390
Bill Wendling57a3cd22011-12-06 21:23:42 +0000391 for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i) {
Bill Wendling09b02c82011-07-25 18:00:28 +0000392 int CUReg = getCompactUnwindRegNum(CURegs, SavedRegs[i]);
393 if (CUReg == -1) return ~0U;
394 SavedRegs[i] = CUReg;
Bill Wendling79df9862011-12-06 01:26:14 +0000395 }
Bill Wendling09b02c82011-07-25 18:00:28 +0000396
Bill Wendling57a3cd22011-12-06 21:23:42 +0000397 uint32_t RenumRegs[CU_NUM_SAVED_REGS];
398 for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i) {
Bill Wendling09b02c82011-07-25 18:00:28 +0000399 unsigned Countless = 0;
Bill Wendling57a3cd22011-12-06 21:23:42 +0000400 for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
Bill Wendling09b02c82011-07-25 18:00:28 +0000401 if (SavedRegs[j] < SavedRegs[i])
402 ++Countless;
403
404 RenumRegs[i] = SavedRegs[i] - Countless - 1;
405 }
406
407 // Take the renumbered values and encode them into a 10-bit number.
408 uint32_t permutationEncoding = 0;
409 switch (RegCount) {
410 case 6:
411 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
412 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
413 + RenumRegs[4];
414 break;
415 case 5:
416 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
417 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
418 + RenumRegs[5];
419 break;
420 case 4:
421 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
422 + 3 * RenumRegs[4] + RenumRegs[5];
423 break;
424 case 3:
425 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
426 + RenumRegs[5];
427 break;
428 case 2:
429 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
430 break;
431 case 1:
432 permutationEncoding |= RenumRegs[5];
433 break;
434 }
435
436 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
437 "Invalid compact register encoding!");
438 return permutationEncoding;
439}
440
441/// encodeCompactUnwindRegistersWithFrame - Return the registers encoded for a
442/// compact encoding with a frame pointer.
Bill Wendling57a3cd22011-12-06 21:23:42 +0000443static uint32_t
444encodeCompactUnwindRegistersWithFrame(unsigned SavedRegs[CU_NUM_SAVED_REGS],
445 bool Is64Bit) {
Bill Wendling09b02c82011-07-25 18:00:28 +0000446 static const unsigned CU32BitRegs[] = {
447 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
448 };
449 static const unsigned CU64BitRegs[] = {
450 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
451 };
452 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
453
454 // Encode the registers in the order they were saved, 3-bits per register. The
455 // registers are numbered from 1 to 6.
456 uint32_t RegEnc = 0;
457 for (int I = 5; I >= 0; --I) {
458 unsigned Reg = SavedRegs[I];
459 if (Reg == 0) break;
460 int CURegNum = getCompactUnwindRegNum(CURegs, Reg);
461 if (CURegNum == -1)
462 return ~0U;
Bill Wendling80caf9c2011-12-06 01:57:48 +0000463
464 // Encode the 3-bit register number in order, skipping over 3-bits for each
465 // register.
Bill Wendling79df9862011-12-06 01:26:14 +0000466 RegEnc |= (CURegNum & 0x7) << ((5 - I) * 3);
Bill Wendling09b02c82011-07-25 18:00:28 +0000467 }
468
469 assert((RegEnc & 0x7FFF) == RegEnc && "Invalid compact register encoding!");
470 return RegEnc;
471}
472
473uint32_t X86FrameLowering::getCompactUnwindEncoding(MachineFunction &MF) const {
474 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
475 unsigned FramePtr = RegInfo->getFrameRegister(MF);
476 unsigned StackPtr = RegInfo->getStackRegister();
477
478 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
479 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
480
481 bool Is64Bit = STI.is64Bit();
482 bool HasFP = hasFP(MF);
483
Bill Wendling57a3cd22011-12-06 21:23:42 +0000484 unsigned SavedRegs[CU_NUM_SAVED_REGS] = { 0, 0, 0, 0, 0, 0 };
485 int SavedRegIdx = CU_NUM_SAVED_REGS;
Bill Wendling09b02c82011-07-25 18:00:28 +0000486
487 unsigned OffsetSize = (Is64Bit ? 8 : 4);
488
489 unsigned PushInstr = (Is64Bit ? X86::PUSH64r : X86::PUSH32r);
490 unsigned PushInstrSize = 1;
491 unsigned MoveInstr = (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
492 unsigned MoveInstrSize = (Is64Bit ? 3 : 2);
493 unsigned SubtractInstr = getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta);
494 unsigned SubtractInstrIdx = (Is64Bit ? 3 : 2);
495
Bill Wendlingde770552011-07-26 08:03:49 +0000496 unsigned StackDivide = (Is64Bit ? 8 : 4);
497
Bill Wendling09b02c82011-07-25 18:00:28 +0000498 unsigned InstrOffset = 0;
Bill Wendling09b02c82011-07-25 18:00:28 +0000499 unsigned StackAdjust = 0;
Bill Wendling57a3cd22011-12-06 21:23:42 +0000500 unsigned StackSize = 0;
Bill Wendling09b02c82011-07-25 18:00:28 +0000501
502 MachineBasicBlock &MBB = MF.front(); // Prologue is in entry BB.
503 bool ExpectEnd = false;
504 for (MachineBasicBlock::iterator
505 MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ++MBBI) {
506 MachineInstr &MI = *MBBI;
507 unsigned Opc = MI.getOpcode();
508 if (Opc == X86::PROLOG_LABEL) continue;
509 if (!MI.getFlag(MachineInstr::FrameSetup)) break;
510
511 // We don't exect any more prolog instructions.
512 if (ExpectEnd) return 0;
513
514 if (Opc == PushInstr) {
515 // If there are too many saved registers, we cannot use compact encoding.
516 if (--SavedRegIdx < 0) return 0;
517
518 SavedRegs[SavedRegIdx] = MI.getOperand(0).getReg();
Bill Wendling57a3cd22011-12-06 21:23:42 +0000519 StackAdjust += OffsetSize;
Bill Wendling09b02c82011-07-25 18:00:28 +0000520 InstrOffset += PushInstrSize;
521 } else if (Opc == MoveInstr) {
522 unsigned SrcReg = MI.getOperand(1).getReg();
523 unsigned DstReg = MI.getOperand(0).getReg();
524
525 if (DstReg != FramePtr || SrcReg != StackPtr)
526 return 0;
527
Bill Wendling57a3cd22011-12-06 21:23:42 +0000528 StackAdjust = 0;
Bill Wendling09b02c82011-07-25 18:00:28 +0000529 memset(SavedRegs, 0, sizeof(SavedRegs));
Bill Wendling57a3cd22011-12-06 21:23:42 +0000530 SavedRegIdx = CU_NUM_SAVED_REGS;
Bill Wendling09b02c82011-07-25 18:00:28 +0000531 InstrOffset += MoveInstrSize;
532 } else if (Opc == SubtractInstr) {
Bill Wendling57a3cd22011-12-06 21:23:42 +0000533 if (StackSize)
534 // We already have a stack size.
Bill Wendling09b02c82011-07-25 18:00:28 +0000535 return 0;
536
537 if (!MI.getOperand(0).isReg() ||
538 MI.getOperand(0).getReg() != MI.getOperand(1).getReg() ||
539 MI.getOperand(0).getReg() != StackPtr || !MI.getOperand(2).isImm())
540 // We need this to be a stack adjustment pointer. Something like:
541 //
542 // %RSP<def> = SUB64ri8 %RSP, 48
543 return 0;
544
Bill Wendling57a3cd22011-12-06 21:23:42 +0000545 StackSize = MI.getOperand(2).getImm() / StackDivide;
Bill Wendling09b02c82011-07-25 18:00:28 +0000546 SubtractInstrIdx += InstrOffset;
547 ExpectEnd = true;
548 }
549 }
550
551 // Encode that we are using EBP/RBP as the frame pointer.
552 uint32_t CompactUnwindEncoding = 0;
Bill Wendling57a3cd22011-12-06 21:23:42 +0000553 StackAdjust /= StackDivide;
Bill Wendling09b02c82011-07-25 18:00:28 +0000554 if (HasFP) {
Bill Wendling57a3cd22011-12-06 21:23:42 +0000555 if ((StackAdjust & 0xFF) != StackAdjust)
Bill Wendling09b02c82011-07-25 18:00:28 +0000556 // Offset was too big for compact encoding.
557 return 0;
558
559 // Get the encoding of the saved registers when we have a frame pointer.
560 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame(SavedRegs, Is64Bit);
Bill Wendling5b2c4972011-12-06 19:16:17 +0000561 if (RegEnc == ~0U) return 0;
Bill Wendling09b02c82011-07-25 18:00:28 +0000562
563 CompactUnwindEncoding |= 0x01000000;
Bill Wendling57a3cd22011-12-06 21:23:42 +0000564 CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
Bill Wendling09b02c82011-07-25 18:00:28 +0000565 CompactUnwindEncoding |= RegEnc & 0x7FFF;
566 } else {
Bill Wendling581ac272011-12-06 21:34:01 +0000567 uint32_t TotalStackSize = StackAdjust + StackSize;
568 if ((TotalStackSize & 0xFF) == TotalStackSize) {
Bill Wendling5b2c4972011-12-06 19:16:17 +0000569 // Frameless stack with a small stack size.
Bill Wendling09b02c82011-07-25 18:00:28 +0000570 CompactUnwindEncoding |= 0x02000000;
Bill Wendling5b2c4972011-12-06 19:16:17 +0000571
572 // Encode the stack size.
Bill Wendling581ac272011-12-06 21:34:01 +0000573 CompactUnwindEncoding |= (TotalStackSize & 0xFF) << 16;
Bill Wendling09b02c82011-07-25 18:00:28 +0000574 } else {
Bill Wendling57a3cd22011-12-06 21:23:42 +0000575 if ((StackAdjust & 0x7) != StackAdjust)
Bill Wendling09b02c82011-07-25 18:00:28 +0000576 // The extra stack adjustments are too big for us to handle.
577 return 0;
578
579 // Frameless stack with an offset too large for us to encode compactly.
580 CompactUnwindEncoding |= 0x03000000;
581
582 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
583 // instruction.
584 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
585
Bill Wendling57a3cd22011-12-06 21:23:42 +0000586 // Encode any extra stack stack adjustments (done via push instructions).
587 CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
Bill Wendling09b02c82011-07-25 18:00:28 +0000588 }
589
Bill Wendling5b2c4972011-12-06 19:16:17 +0000590 // Encode the number of registers saved.
Bill Wendling57a3cd22011-12-06 21:23:42 +0000591 CompactUnwindEncoding |= ((CU_NUM_SAVED_REGS - SavedRegIdx) & 0x7) << 10;
Bill Wendling75e14e02011-12-06 19:09:06 +0000592
Bill Wendling09b02c82011-07-25 18:00:28 +0000593 // Get the encoding of the saved registers when we don't have a frame
594 // pointer.
Bill Wendling57a3cd22011-12-06 21:23:42 +0000595 uint32_t RegEnc =
596 encodeCompactUnwindRegistersWithoutFrame(SavedRegs,
597 CU_NUM_SAVED_REGS - SavedRegIdx,
598 Is64Bit);
Bill Wendling09b02c82011-07-25 18:00:28 +0000599 if (RegEnc == ~0U) return 0;
Bill Wendling5b2c4972011-12-06 19:16:17 +0000600
601 // Encode the register encoding.
Bill Wendling09b02c82011-07-25 18:00:28 +0000602 CompactUnwindEncoding |= RegEnc & 0x3FF;
603 }
604
605 return CompactUnwindEncoding;
606}
607
Anton Korobeynikov33464912010-11-15 00:06:54 +0000608/// emitPrologue - Push callee-saved registers onto the stack, which
609/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
610/// space for local variables. Also emit labels used by the exception handler to
611/// generate the exception handling frames.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000612void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000613 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
614 MachineBasicBlock::iterator MBBI = MBB.begin();
615 MachineFrameInfo *MFI = MF.getFrameInfo();
616 const Function *Fn = MF.getFunction();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000617 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
618 const X86InstrInfo &TII = *TM.getInstrInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000619 MachineModuleInfo &MMI = MF.getMMI();
620 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
621 bool needsFrameMoves = MMI.hasDebugInfo() ||
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000622 Fn->needsUnwindTableEntry();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000623 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
624 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000625 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000626 bool Is64Bit = STI.is64Bit();
627 bool IsWin64 = STI.isTargetWin64();
628 unsigned StackAlign = getStackAlignment();
629 unsigned SlotSize = RegInfo->getSlotSize();
630 unsigned FramePtr = RegInfo->getFrameRegister(MF);
631 unsigned StackPtr = RegInfo->getStackRegister();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000632 DebugLoc DL;
633
634 // If we're forcing a stack realignment we can't rely on just the frame
635 // info, we need to know the ABI stack alignment as well in case we
636 // have a call out. Otherwise just make sure we have some alignment - we'll
637 // go with the minimum SlotSize.
638 if (ForceStackAlign) {
639 if (MFI->hasCalls())
640 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
641 else if (MaxAlign < SlotSize)
642 MaxAlign = SlotSize;
643 }
644
645 // Add RETADDR move area to callee saved frame size.
646 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
647 if (TailCallReturnAddrDelta < 0)
648 X86FI->setCalleeSavedFrameSize(
649 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
650
651 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
652 // function, and use up to 128 bytes of stack space, don't have a frame
653 // pointer, calls, or dynamic alloca then we do not need to adjust the
654 // stack pointer (we fit in the Red Zone).
655 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
656 !RegInfo->needsStackRealignment(MF) &&
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000657 !MFI->hasVarSizedObjects() && // No dynamic alloca.
658 !MFI->adjustsStack() && // No calls.
659 !IsWin64 && // Win64 has no Red Zone
660 !MF.getTarget().Options.EnableSegmentedStacks) { // Regular stack
Anton Korobeynikov33464912010-11-15 00:06:54 +0000661 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
662 if (HasFP) MinSize += SlotSize;
663 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
664 MFI->setStackSize(StackSize);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000665 }
666
667 // Insert stack pointer adjustment for later moving of return addr. Only
668 // applies to tail call optimized functions where the callee argument stack
669 // size is bigger than the callers.
670 if (TailCallReturnAddrDelta < 0) {
671 MachineInstr *MI =
672 BuildMI(MBB, MBBI, DL,
673 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
674 StackPtr)
675 .addReg(StackPtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000676 .addImm(-TailCallReturnAddrDelta)
677 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000678 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
679 }
680
681 // Mapping for machine moves:
682 //
683 // DST: VirtualFP AND
684 // SRC: VirtualFP => DW_CFA_def_cfa_offset
685 // ELSE => DW_CFA_def_cfa
686 //
687 // SRC: VirtualFP AND
688 // DST: Register => DW_CFA_def_cfa_register
689 //
690 // ELSE
691 // OFFSET < 0 => DW_CFA_offset_extended_sf
692 // REG < 64 => DW_CFA_offset + Reg
693 // ELSE => DW_CFA_offset_extended
694
695 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
696 const TargetData *TD = MF.getTarget().getTargetData();
697 uint64_t NumBytes = 0;
698 int stackGrowth = -TD->getPointerSize();
699
700 if (HasFP) {
701 // Calculate required stack adjustment.
702 uint64_t FrameSize = StackSize - SlotSize;
703 if (RegInfo->needsStackRealignment(MF))
704 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
705
706 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
707
708 // Get the offset of the stack slot for the EBP register, which is
709 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
710 // Update the frame offset adjustment.
711 MFI->setOffsetAdjustment(-NumBytes);
712
713 // Save EBP/RBP into the appropriate stack slot.
714 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
Charles Davisaff232a2011-06-12 01:45:54 +0000715 .addReg(FramePtr, RegState::Kill)
716 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000717
718 if (needsFrameMoves) {
719 // Mark the place where EBP/RBP was saved.
720 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000721 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
722 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000723
724 // Define the current CFA rule to use the provided offset.
725 if (StackSize) {
726 MachineLocation SPDst(MachineLocation::VirtualFP);
727 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
728 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
729 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000730 MachineLocation SPDst(StackPtr);
731 MachineLocation SPSrc(StackPtr, stackGrowth);
732 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
733 }
734
735 // Change the rule for the FramePtr to be an "offset" rule.
736 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
737 MachineLocation FPSrc(FramePtr);
738 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
739 }
740
Bill Wendling09b02c82011-07-25 18:00:28 +0000741 // Update EBP with the new base value.
Anton Korobeynikov33464912010-11-15 00:06:54 +0000742 BuildMI(MBB, MBBI, DL,
743 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000744 .addReg(StackPtr)
745 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000746
747 if (needsFrameMoves) {
748 // Mark effective beginning of when frame pointer becomes valid.
749 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000750 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
751 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000752
753 // Define the current CFA to use the EBP/RBP register.
754 MachineLocation FPDst(FramePtr);
755 MachineLocation FPSrc(MachineLocation::VirtualFP);
756 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
757 }
758
759 // Mark the FramePtr as live-in in every block except the entry.
760 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
761 I != E; ++I)
762 I->addLiveIn(FramePtr);
763
764 // Realign stack
765 if (RegInfo->needsStackRealignment(MF)) {
766 MachineInstr *MI =
767 BuildMI(MBB, MBBI, DL,
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000768 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
769 .addReg(StackPtr)
770 .addImm(-MaxAlign)
771 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000772
773 // The EFLAGS implicit def is dead.
774 MI->getOperand(3).setIsDead();
775 }
776 } else {
777 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
778 }
779
780 // Skip the callee-saved push instructions.
781 bool PushedRegs = false;
782 int StackOffset = 2 * stackGrowth;
783
784 while (MBBI != MBB.end() &&
785 (MBBI->getOpcode() == X86::PUSH32r ||
786 MBBI->getOpcode() == X86::PUSH64r)) {
787 PushedRegs = true;
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000788 MBBI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000789 ++MBBI;
790
791 if (!HasFP && needsFrameMoves) {
792 // Mark callee-saved push instruction.
793 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
794 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
795
796 // Define the current CFA rule to use the provided offset.
Bill Wendling09b02c82011-07-25 18:00:28 +0000797 unsigned Ptr = StackSize ? MachineLocation::VirtualFP : StackPtr;
Anton Korobeynikov33464912010-11-15 00:06:54 +0000798 MachineLocation SPDst(Ptr);
799 MachineLocation SPSrc(Ptr, StackOffset);
800 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
801 StackOffset += stackGrowth;
802 }
803 }
804
805 DL = MBB.findDebugLoc(MBBI);
806
807 // If there is an SUB32ri of ESP immediately before this instruction, merge
808 // the two. This can be the case when tail call elimination is enabled and
809 // the callee has more arguments then the caller.
810 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
811
812 // If there is an ADD32ri or SUB32ri of ESP immediately after this
813 // instruction, merge the two instructions.
814 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
815
816 // Adjust stack pointer: ESP -= numbytes.
817
818 // Windows and cygwin/mingw require a prologue helper routine when allocating
819 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
820 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
821 // stack and adjust the stack pointer in one go. The 64-bit version of
822 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
823 // responsible for adjusting the stack pointer. Touching the stack at 4K
824 // increments is necessary to ensure that the guard pages used by the OS
825 // virtual memory manager are allocated in correct sequence.
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000826 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
827 const char *StackProbeSymbol;
828 bool isSPUpdateNeeded = false;
829
830 if (Is64Bit) {
831 if (STI.isTargetCygMing())
832 StackProbeSymbol = "___chkstk";
833 else {
834 StackProbeSymbol = "__chkstk";
835 isSPUpdateNeeded = true;
836 }
837 } else if (STI.isTargetCygMing())
838 StackProbeSymbol = "_alloca";
839 else
840 StackProbeSymbol = "_chkstk";
841
Anton Korobeynikov33464912010-11-15 00:06:54 +0000842 // Check whether EAX is livein for this function.
843 bool isEAXAlive = isEAXLiveIn(MF);
844
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000845 if (isEAXAlive) {
846 // Sanity check that EAX is not livein for this function.
847 // It should not be, so throw an assert.
848 assert(!Is64Bit && "EAX is livein in x64 case!");
849
Anton Korobeynikov33464912010-11-15 00:06:54 +0000850 // Save EAX
851 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000852 .addReg(X86::EAX, RegState::Kill)
853 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000854 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000855
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000856 if (Is64Bit) {
857 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
858 // Function prologue is responsible for adjusting the stack pointer.
859 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000860 .addImm(NumBytes)
861 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000862 } else {
863 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
864 // We'll also use 4 already allocated bytes for EAX.
865 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000866 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
867 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000868 }
869
870 BuildMI(MBB, MBBI, DL,
871 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
872 .addExternalSymbol(StackProbeSymbol)
873 .addReg(StackPtr, RegState::Define | RegState::Implicit)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000874 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
875 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000876
877 // MSVC x64's __chkstk needs to adjust %rsp.
878 // FIXME: %rax preserves the offset and should be available.
879 if (isSPUpdateNeeded)
880 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
881 TII, *RegInfo);
882
883 if (isEAXAlive) {
884 // Restore EAX
885 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
886 X86::EAX),
887 StackPtr, false, NumBytes - 4);
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000888 MI->setFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000889 MBB.insert(MBBI, MI);
890 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000891 } else if (NumBytes)
Evan Cheng7158e082011-01-03 22:53:22 +0000892 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
893 TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000894
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000895 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000896 // Mark end of stack pointer adjustment.
897 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000898 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
899 .addSym(Label);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000900
901 if (!HasFP && NumBytes) {
902 // Define the current CFA rule to use the provided offset.
903 if (StackSize) {
904 MachineLocation SPDst(MachineLocation::VirtualFP);
905 MachineLocation SPSrc(MachineLocation::VirtualFP,
906 -StackSize + stackGrowth);
907 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
908 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000909 MachineLocation SPDst(StackPtr);
910 MachineLocation SPSrc(StackPtr, stackGrowth);
911 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
912 }
913 }
914
915 // Emit DWARF info specifying the offsets of the callee-saved registers.
916 if (PushedRegs)
917 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
918 }
Bill Wendling09b02c82011-07-25 18:00:28 +0000919
920 // Darwin 10.7 and greater has support for compact unwind encoding.
Bill Wendlingc8725d12011-09-06 23:47:14 +0000921 if (STI.getTargetTriple().isMacOSX() &&
Eli Friedmanac86d432011-08-31 16:19:51 +0000922 !STI.getTargetTriple().isMacOSXVersionLT(10, 7))
Bill Wendling09b02c82011-07-25 18:00:28 +0000923 MMI.setCompactUnwindEncoding(getCompactUnwindEncoding(MF));
Anton Korobeynikov33464912010-11-15 00:06:54 +0000924}
925
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000926void X86FrameLowering::emitEpilogue(MachineFunction &MF,
Nick Lewycky3c2f0a12011-06-14 03:23:52 +0000927 MachineBasicBlock &MBB) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000928 const MachineFrameInfo *MFI = MF.getFrameInfo();
929 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000930 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
931 const X86InstrInfo &TII = *TM.getInstrInfo();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000932 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
933 assert(MBBI != MBB.end() && "Returning block has no instructions");
Anton Korobeynikov33464912010-11-15 00:06:54 +0000934 unsigned RetOpcode = MBBI->getOpcode();
935 DebugLoc DL = MBBI->getDebugLoc();
936 bool Is64Bit = STI.is64Bit();
937 unsigned StackAlign = getStackAlignment();
938 unsigned SlotSize = RegInfo->getSlotSize();
939 unsigned FramePtr = RegInfo->getFrameRegister(MF);
940 unsigned StackPtr = RegInfo->getStackRegister();
941
942 switch (RetOpcode) {
943 default:
944 llvm_unreachable("Can only insert epilog into returning blocks");
945 case X86::RET:
946 case X86::RETI:
947 case X86::TCRETURNdi:
948 case X86::TCRETURNri:
949 case X86::TCRETURNmi:
950 case X86::TCRETURNdi64:
951 case X86::TCRETURNri64:
952 case X86::TCRETURNmi64:
953 case X86::EH_RETURN:
954 case X86::EH_RETURN64:
955 break; // These are ok
956 }
957
958 // Get the number of bytes to allocate from the FrameInfo.
959 uint64_t StackSize = MFI->getStackSize();
960 uint64_t MaxAlign = MFI->getMaxAlignment();
961 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
962 uint64_t NumBytes = 0;
963
964 // If we're forcing a stack realignment we can't rely on just the frame
965 // info, we need to know the ABI stack alignment as well in case we
966 // have a call out. Otherwise just make sure we have some alignment - we'll
967 // go with the minimum.
968 if (ForceStackAlign) {
969 if (MFI->hasCalls())
970 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
971 else
972 MaxAlign = MaxAlign ? MaxAlign : 4;
973 }
974
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000975 if (hasFP(MF)) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000976 // Calculate required stack adjustment.
977 uint64_t FrameSize = StackSize - SlotSize;
978 if (RegInfo->needsStackRealignment(MF))
979 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
980
981 NumBytes = FrameSize - CSSize;
982
983 // Pop EBP.
984 BuildMI(MBB, MBBI, DL,
985 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
986 } else {
987 NumBytes = StackSize - CSSize;
988 }
989
990 // Skip the callee-saved pop instructions.
991 MachineBasicBlock::iterator LastCSPop = MBBI;
992 while (MBBI != MBB.begin()) {
993 MachineBasicBlock::iterator PI = prior(MBBI);
994 unsigned Opc = PI->getOpcode();
995
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000996 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
Anton Korobeynikov33464912010-11-15 00:06:54 +0000997 !PI->getDesc().isTerminator())
998 break;
999
1000 --MBBI;
1001 }
1002
1003 DL = MBBI->getDebugLoc();
1004
1005 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1006 // instruction, merge the two instructions.
1007 if (NumBytes || MFI->hasVarSizedObjects())
1008 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1009
1010 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1011 // slot before popping them off! Same applies for the case, when stack was
1012 // realigned.
1013 if (RegInfo->needsStackRealignment(MF)) {
1014 // We cannot use LEA here, because stack pointer was realigned. We need to
1015 // deallocate local frame back.
1016 if (CSSize) {
Evan Cheng7158e082011-01-03 22:53:22 +00001017 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001018 MBBI = prior(LastCSPop);
1019 }
1020
1021 BuildMI(MBB, MBBI, DL,
1022 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1023 StackPtr).addReg(FramePtr);
1024 } else if (MFI->hasVarSizedObjects()) {
1025 if (CSSize) {
1026 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
1027 MachineInstr *MI =
1028 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
1029 FramePtr, false, -CSSize);
1030 MBB.insert(MBBI, MI);
1031 } else {
1032 BuildMI(MBB, MBBI, DL,
1033 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
1034 .addReg(FramePtr);
1035 }
1036 } else if (NumBytes) {
1037 // Adjust stack pointer back: ESP += numbytes.
Evan Cheng7158e082011-01-03 22:53:22 +00001038 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001039 }
1040
1041 // We're returning from function via eh_return.
1042 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001043 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001044 MachineOperand &DestAddr = MBBI->getOperand(0);
1045 assert(DestAddr.isReg() && "Offset should be in register!");
1046 BuildMI(MBB, MBBI, DL,
1047 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1048 StackPtr).addReg(DestAddr.getReg());
1049 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1050 RetOpcode == X86::TCRETURNmi ||
1051 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1052 RetOpcode == X86::TCRETURNmi64) {
1053 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1054 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesenf7ca9762011-01-13 22:47:43 +00001055 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001056 MachineOperand &JumpTarget = MBBI->getOperand(0);
1057 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1058 assert(StackAdjust.isImm() && "Expecting immediate value.");
1059
1060 // Adjust stack pointer.
1061 int StackAdj = StackAdjust.getImm();
1062 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1063 int Offset = 0;
1064 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1065
1066 // Incoporate the retaddr area.
1067 Offset = StackAdj-MaxTCDelta;
1068 assert(Offset >= 0 && "Offset should never be negative");
1069
1070 if (Offset) {
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001071 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001072 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001073 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001074 }
1075
1076 // Jump to label or value in register.
1077 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
Evan Cheng3d2125c2010-11-30 23:55:39 +00001078 MachineInstrBuilder MIB =
1079 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1080 ? X86::TAILJMPd : X86::TAILJMPd64));
1081 if (JumpTarget.isGlobal())
1082 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1083 JumpTarget.getTargetFlags());
1084 else {
1085 assert(JumpTarget.isSymbol());
1086 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1087 JumpTarget.getTargetFlags());
1088 }
Anton Korobeynikov33464912010-11-15 00:06:54 +00001089 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1090 MachineInstrBuilder MIB =
1091 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1092 ? X86::TAILJMPm : X86::TAILJMPm64));
1093 for (unsigned i = 0; i != 5; ++i)
1094 MIB.addOperand(MBBI->getOperand(i));
1095 } else if (RetOpcode == X86::TCRETURNri64) {
1096 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1097 addReg(JumpTarget.getReg(), RegState::Kill);
1098 } else {
1099 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1100 addReg(JumpTarget.getReg(), RegState::Kill);
1101 }
1102
1103 MachineInstr *NewMI = prior(MBBI);
1104 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
1105 NewMI->addOperand(MBBI->getOperand(i));
1106
1107 // Delete the pseudo instruction TCRETURN.
1108 MBB.erase(MBBI);
1109 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
1110 (X86FI->getTCReturnAddrDelta() < 0)) {
1111 // Add the return addr area delta back since we are not tail calling.
1112 int delta = -1*X86FI->getTCReturnAddrDelta();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001113 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001114
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001115 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001116 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001117 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001118 }
1119}
Anton Korobeynikovd9e33852010-11-18 23:25:52 +00001120
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001121int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
Anton Korobeynikov82f58742010-11-20 15:59:32 +00001122 const X86RegisterInfo *RI =
1123 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
1124 const MachineFrameInfo *MFI = MF.getFrameInfo();
1125 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1126 uint64_t StackSize = MFI->getStackSize();
1127
1128 if (RI->needsStackRealignment(MF)) {
1129 if (FI < 0) {
1130 // Skip the saved EBP.
1131 Offset += RI->getSlotSize();
1132 } else {
Duncan Sands17001ce2011-10-18 12:44:00 +00001133 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
Anton Korobeynikov82f58742010-11-20 15:59:32 +00001134 return Offset + StackSize;
1135 }
1136 // FIXME: Support tail calls
1137 } else {
1138 if (!hasFP(MF))
1139 return Offset + StackSize;
1140
1141 // Skip the saved EBP.
1142 Offset += RI->getSlotSize();
1143
1144 // Skip the RETADDR move area
1145 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1146 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1147 if (TailCallReturnAddrDelta < 0)
1148 Offset -= TailCallReturnAddrDelta;
1149 }
1150
1151 return Offset;
1152}
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001153
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001154bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001155 MachineBasicBlock::iterator MI,
1156 const std::vector<CalleeSavedInfo> &CSI,
1157 const TargetRegisterInfo *TRI) const {
1158 if (CSI.empty())
1159 return false;
1160
1161 DebugLoc DL = MBB.findDebugLoc(MI);
1162
1163 MachineFunction &MF = *MBB.getParent();
1164
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001165 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
1166 unsigned FPReg = TRI->getFrameRegister(MF);
1167 unsigned CalleeFrameSize = 0;
1168
1169 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1170 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1171
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001172 // Push GPRs. It increases frame size.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001173 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1174 for (unsigned i = CSI.size(); i != 0; --i) {
1175 unsigned Reg = CSI[i-1].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001176 if (!X86::GR64RegClass.contains(Reg) &&
1177 !X86::GR32RegClass.contains(Reg))
1178 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001179 // Add the callee-saved register as live-in. It's killed at the spill.
1180 MBB.addLiveIn(Reg);
1181 if (Reg == FPReg)
1182 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
1183 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001184 CalleeFrameSize += SlotSize;
Charles Davisaff232a2011-06-12 01:45:54 +00001185 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1186 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001187 }
1188
1189 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001190
1191 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1192 // It can be done by spilling XMMs to stack frame.
1193 // Note that only Win64 ABI might spill XMMs.
1194 for (unsigned i = CSI.size(); i != 0; --i) {
1195 unsigned Reg = CSI[i-1].getReg();
1196 if (X86::GR64RegClass.contains(Reg) ||
1197 X86::GR32RegClass.contains(Reg))
1198 continue;
1199 // Add the callee-saved register as live-in. It's killed at the spill.
1200 MBB.addLiveIn(Reg);
1201 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1202 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
1203 RC, TRI);
1204 }
1205
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001206 return true;
1207}
1208
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001209bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001210 MachineBasicBlock::iterator MI,
1211 const std::vector<CalleeSavedInfo> &CSI,
1212 const TargetRegisterInfo *TRI) const {
1213 if (CSI.empty())
1214 return false;
1215
1216 DebugLoc DL = MBB.findDebugLoc(MI);
1217
1218 MachineFunction &MF = *MBB.getParent();
1219 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001220
1221 // Reload XMMs from stack frame.
1222 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1223 unsigned Reg = CSI[i].getReg();
1224 if (X86::GR64RegClass.contains(Reg) ||
1225 X86::GR32RegClass.contains(Reg))
1226 continue;
1227 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1228 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
1229 RC, TRI);
1230 }
1231
1232 // POP GPRs.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001233 unsigned FPReg = TRI->getFrameRegister(MF);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001234 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1235 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1236 unsigned Reg = CSI[i].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001237 if (!X86::GR64RegClass.contains(Reg) &&
1238 !X86::GR32RegClass.contains(Reg))
1239 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001240 if (Reg == FPReg)
1241 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
1242 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001243 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001244 }
1245 return true;
1246}
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001247
1248void
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001249X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001250 RegScavenger *RS) const {
1251 MachineFrameInfo *MFI = MF.getFrameInfo();
1252 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
1253 unsigned SlotSize = RegInfo->getSlotSize();
1254
1255 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1256 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1257
1258 if (TailCallReturnAddrDelta < 0) {
1259 // create RETURNADDR area
1260 // arg
1261 // arg
1262 // RETADDR
1263 // { ...
1264 // RETADDR area
1265 // ...
1266 // }
1267 // [EBP]
1268 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1269 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1270 }
1271
1272 if (hasFP(MF)) {
1273 assert((TailCallReturnAddrDelta <= 0) &&
1274 "The Delta should always be zero or negative");
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001275 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001276
1277 // Create a frame entry for the EBP register that must be saved.
1278 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1279 -(int)SlotSize +
1280 TFI.getOffsetOfLocalArea() +
1281 TailCallReturnAddrDelta,
1282 true);
1283 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1284 "Slot for EBP register must be last in order to be found!");
Duncan Sands17001ce2011-10-18 12:44:00 +00001285 (void)FrameIdx;
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001286 }
1287}
Rafael Espindola76927d752011-08-30 19:39:58 +00001288
1289static bool
1290HasNestArgument(const MachineFunction *MF) {
1291 const Function *F = MF->getFunction();
1292 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1293 I != E; I++) {
1294 if (I->hasNestAttr())
1295 return true;
1296 }
1297 return false;
1298}
1299
1300static unsigned
1301GetScratchRegister(bool Is64Bit, const MachineFunction &MF) {
1302 if (Is64Bit) {
1303 return X86::R11;
1304 } else {
1305 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1306 bool IsNested = HasNestArgument(&MF);
1307
1308 if (CallingConvention == CallingConv::X86_FastCall) {
1309 if (IsNested) {
Rafael Espindolae81abfd2011-08-31 16:43:33 +00001310 report_fatal_error("Segmented stacks does not support fastcall with "
1311 "nested function.");
Rafael Espindola76927d752011-08-30 19:39:58 +00001312 return -1;
1313 } else {
1314 return X86::EAX;
1315 }
1316 } else {
1317 if (IsNested)
1318 return X86::EDX;
1319 else
1320 return X86::ECX;
1321 }
1322 }
1323}
1324
Sanjoy Das199ce332011-12-03 09:32:07 +00001325// The stack limit in the TCB is set to this many bytes above the actual stack
1326// limit.
1327static const uint64_t kSplitStackAvailable = 256;
1328
Rafael Espindola76927d752011-08-30 19:39:58 +00001329void
1330X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1331 MachineBasicBlock &prologueMBB = MF.front();
1332 MachineFrameInfo *MFI = MF.getFrameInfo();
1333 const X86InstrInfo &TII = *TM.getInstrInfo();
1334 uint64_t StackSize;
1335 bool Is64Bit = STI.is64Bit();
1336 unsigned TlsReg, TlsOffset;
1337 DebugLoc DL;
1338 const X86Subtarget *ST = &MF.getTarget().getSubtarget<X86Subtarget>();
1339
1340 unsigned ScratchReg = GetScratchRegister(Is64Bit, MF);
1341 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1342 "Scratch register is live-in");
1343
1344 if (MF.getFunction()->isVarArg())
1345 report_fatal_error("Segmented stacks do not support vararg functions.");
1346 if (!ST->isTargetLinux())
1347 report_fatal_error("Segmented stacks supported only on linux.");
1348
1349 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1350 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1351 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1352 bool IsNested = false;
1353
1354 // We need to know if the function has a nest argument only in 64 bit mode.
1355 if (Is64Bit)
1356 IsNested = HasNestArgument(&MF);
1357
Bill Wendling4e680542011-10-13 08:24:19 +00001358 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1359 // allocMBB needs to be last (terminating) instruction.
Bill Wendling4e680542011-10-13 08:24:19 +00001360
Rafael Espindola76927d752011-08-30 19:39:58 +00001361 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1362 e = prologueMBB.livein_end(); i != e; i++) {
1363 allocMBB->addLiveIn(*i);
1364 checkMBB->addLiveIn(*i);
1365 }
1366
1367 if (IsNested)
Rafael Espindolae840e882011-10-26 21:12:27 +00001368 allocMBB->addLiveIn(X86::R10);
1369
Rafael Espindola76927d752011-08-30 19:39:58 +00001370 MF.push_front(allocMBB);
1371 MF.push_front(checkMBB);
1372
1373 // Eventually StackSize will be calculated by a link-time pass; which will
1374 // also decide whether checking code needs to be injected into this particular
1375 // prologue.
1376 StackSize = MFI->getStackSize();
1377
1378 // Read the limit off the current stacklet off the stack_guard location.
1379 if (Is64Bit) {
1380 TlsReg = X86::FS;
1381 TlsOffset = 0x70;
1382
Sanjoy Das199ce332011-12-03 09:32:07 +00001383 if (StackSize < kSplitStackAvailable)
1384 ScratchReg = X86::RSP;
1385 else
1386 BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RSP)
1387 .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1388
Rafael Espindola76927d752011-08-30 19:39:58 +00001389 BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
1390 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1391 } else {
1392 TlsReg = X86::GS;
1393 TlsOffset = 0x30;
1394
Sanjoy Das199ce332011-12-03 09:32:07 +00001395 if (StackSize < kSplitStackAvailable)
1396 ScratchReg = X86::ESP;
1397 else
1398 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1399 .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1400
Rafael Espindola76927d752011-08-30 19:39:58 +00001401 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1402 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1403 }
1404
1405 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1406 // It jumps to normal execution of the function body.
1407 BuildMI(checkMBB, DL, TII.get(X86::JG_4)).addMBB(&prologueMBB);
1408
1409 // On 32 bit we first push the arguments size and then the frame size. On 64
1410 // bit, we pass the stack frame size in r10 and the argument size in r11.
1411 if (Is64Bit) {
1412 // Functions with nested arguments use R10, so it needs to be saved across
1413 // the call to _morestack
1414
1415 if (IsNested)
1416 BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::RAX).addReg(X86::R10);
1417
1418 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R10)
1419 .addImm(StackSize);
1420 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R11)
1421 .addImm(X86FI->getArgumentStackSize());
1422 MF.getRegInfo().setPhysRegUsed(X86::R10);
1423 MF.getRegInfo().setPhysRegUsed(X86::R11);
1424 } else {
Rafael Espindola76927d752011-08-30 19:39:58 +00001425 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1426 .addImm(X86FI->getArgumentStackSize());
1427 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1428 .addImm(StackSize);
1429 }
1430
1431 // __morestack is in libgcc
1432 if (Is64Bit)
1433 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1434 .addExternalSymbol("__morestack");
1435 else
1436 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1437 .addExternalSymbol("__morestack");
1438
Bill Wendling4e680542011-10-13 08:24:19 +00001439 if (IsNested)
Rafael Espindolae840e882011-10-26 21:12:27 +00001440 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1441 else
1442 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
Bill Wendling4e680542011-10-13 08:24:19 +00001443
Rafael Espindolae840e882011-10-26 21:12:27 +00001444 allocMBB->addSuccessor(&prologueMBB);
Bill Wendling4e680542011-10-13 08:24:19 +00001445
Rafael Espindola76927d752011-08-30 19:39:58 +00001446 checkMBB->addSuccessor(allocMBB);
1447 checkMBB->addSuccessor(&prologueMBB);
1448
Jakob Stoklund Olesen51f0c762011-09-24 01:11:19 +00001449#ifdef XDEBUG
Rafael Espindola76927d752011-08-30 19:39:58 +00001450 MF.verify();
1451#endif
1452}