blob: fe3754587f5c7f5de14e465d658f87e86b7aa0a9 [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
362/// encodeCompactUnwindRegistersWithoutFrame - Create the permutation encoding
363/// used with frameless stacks. It is passed the number of registers to be saved
364/// and an array of the registers saved.
365static uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned SavedRegs[6],
366 unsigned RegCount,
367 bool Is64Bit) {
368 // The saved registers are numbered from 1 to 6. In order to encode the order
369 // in which they were saved, we re-number them according to their place in the
370 // register order. The re-numbering is relative to the last re-numbered
371 // register. E.g., if we have registers {6, 2, 4, 5} saved in that order:
372 //
373 // Orig Re-Num
374 // ---- ------
375 // 6 6
376 // 2 2
377 // 4 3
378 // 5 3
379 //
380 static const unsigned CU32BitRegs[] = {
381 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
382 };
383 static const unsigned CU64BitRegs[] = {
384 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
385 };
386 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
387
Bill Wendling09b02c82011-07-25 18:00:28 +0000388 for (unsigned i = 6 - RegCount; i < 6; ++i) {
389 int CUReg = getCompactUnwindRegNum(CURegs, SavedRegs[i]);
390 if (CUReg == -1) return ~0U;
391 SavedRegs[i] = CUReg;
Bill Wendling79df9862011-12-06 01:26:14 +0000392 }
Bill Wendling09b02c82011-07-25 18:00:28 +0000393
Bill Wendling79df9862011-12-06 01:26:14 +0000394 uint32_t RenumRegs[6];
395 for (unsigned i = 6 - RegCount; i < 6; ++i) {
Bill Wendling09b02c82011-07-25 18:00:28 +0000396 unsigned Countless = 0;
397 for (unsigned j = 6 - RegCount; j < i; ++j)
398 if (SavedRegs[j] < SavedRegs[i])
399 ++Countless;
400
401 RenumRegs[i] = SavedRegs[i] - Countless - 1;
402 }
403
404 // Take the renumbered values and encode them into a 10-bit number.
405 uint32_t permutationEncoding = 0;
406 switch (RegCount) {
407 case 6:
408 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
409 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
410 + RenumRegs[4];
411 break;
412 case 5:
413 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
414 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
415 + RenumRegs[5];
416 break;
417 case 4:
418 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
419 + 3 * RenumRegs[4] + RenumRegs[5];
420 break;
421 case 3:
422 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
423 + RenumRegs[5];
424 break;
425 case 2:
426 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
427 break;
428 case 1:
429 permutationEncoding |= RenumRegs[5];
430 break;
431 }
432
433 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
434 "Invalid compact register encoding!");
435 return permutationEncoding;
436}
437
438/// encodeCompactUnwindRegistersWithFrame - Return the registers encoded for a
439/// compact encoding with a frame pointer.
440static uint32_t encodeCompactUnwindRegistersWithFrame(unsigned SavedRegs[6],
441 bool Is64Bit) {
442 static const unsigned CU32BitRegs[] = {
443 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
444 };
445 static const unsigned CU64BitRegs[] = {
446 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
447 };
448 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
449
450 // Encode the registers in the order they were saved, 3-bits per register. The
451 // registers are numbered from 1 to 6.
452 uint32_t RegEnc = 0;
453 for (int I = 5; I >= 0; --I) {
454 unsigned Reg = SavedRegs[I];
455 if (Reg == 0) break;
456 int CURegNum = getCompactUnwindRegNum(CURegs, Reg);
457 if (CURegNum == -1)
458 return ~0U;
Bill Wendling80caf9c2011-12-06 01:57:48 +0000459
460 // Encode the 3-bit register number in order, skipping over 3-bits for each
461 // register.
Bill Wendling79df9862011-12-06 01:26:14 +0000462 RegEnc |= (CURegNum & 0x7) << ((5 - I) * 3);
Bill Wendling09b02c82011-07-25 18:00:28 +0000463 }
464
465 assert((RegEnc & 0x7FFF) == RegEnc && "Invalid compact register encoding!");
466 return RegEnc;
467}
468
469uint32_t X86FrameLowering::getCompactUnwindEncoding(MachineFunction &MF) const {
470 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
471 unsigned FramePtr = RegInfo->getFrameRegister(MF);
472 unsigned StackPtr = RegInfo->getStackRegister();
473
474 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
475 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
476
477 bool Is64Bit = STI.is64Bit();
478 bool HasFP = hasFP(MF);
479
480 unsigned SavedRegs[6] = { 0, 0, 0, 0, 0, 0 };
481 int SavedRegIdx = 6;
482
483 unsigned OffsetSize = (Is64Bit ? 8 : 4);
484
485 unsigned PushInstr = (Is64Bit ? X86::PUSH64r : X86::PUSH32r);
486 unsigned PushInstrSize = 1;
487 unsigned MoveInstr = (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
488 unsigned MoveInstrSize = (Is64Bit ? 3 : 2);
489 unsigned SubtractInstr = getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta);
490 unsigned SubtractInstrIdx = (Is64Bit ? 3 : 2);
491
Bill Wendlingde770552011-07-26 08:03:49 +0000492 unsigned StackDivide = (Is64Bit ? 8 : 4);
493
Bill Wendling09b02c82011-07-25 18:00:28 +0000494 unsigned InstrOffset = 0;
495 unsigned CFAOffset = 0;
496 unsigned StackAdjust = 0;
497
498 MachineBasicBlock &MBB = MF.front(); // Prologue is in entry BB.
499 bool ExpectEnd = false;
500 for (MachineBasicBlock::iterator
501 MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ++MBBI) {
502 MachineInstr &MI = *MBBI;
503 unsigned Opc = MI.getOpcode();
504 if (Opc == X86::PROLOG_LABEL) continue;
505 if (!MI.getFlag(MachineInstr::FrameSetup)) break;
506
507 // We don't exect any more prolog instructions.
508 if (ExpectEnd) return 0;
509
510 if (Opc == PushInstr) {
511 // If there are too many saved registers, we cannot use compact encoding.
512 if (--SavedRegIdx < 0) return 0;
513
514 SavedRegs[SavedRegIdx] = MI.getOperand(0).getReg();
515 CFAOffset += OffsetSize;
516 InstrOffset += PushInstrSize;
517 } else if (Opc == MoveInstr) {
518 unsigned SrcReg = MI.getOperand(1).getReg();
519 unsigned DstReg = MI.getOperand(0).getReg();
520
521 if (DstReg != FramePtr || SrcReg != StackPtr)
522 return 0;
523
524 CFAOffset = 0;
525 memset(SavedRegs, 0, sizeof(SavedRegs));
Bill Wendlingc7395772011-11-11 00:59:14 +0000526 SavedRegIdx = 6;
Bill Wendling09b02c82011-07-25 18:00:28 +0000527 InstrOffset += MoveInstrSize;
528 } else if (Opc == SubtractInstr) {
529 if (StackAdjust)
530 // We all ready have a stack pointer adjustment.
531 return 0;
532
533 if (!MI.getOperand(0).isReg() ||
534 MI.getOperand(0).getReg() != MI.getOperand(1).getReg() ||
535 MI.getOperand(0).getReg() != StackPtr || !MI.getOperand(2).isImm())
536 // We need this to be a stack adjustment pointer. Something like:
537 //
538 // %RSP<def> = SUB64ri8 %RSP, 48
539 return 0;
540
Bill Wendlingde770552011-07-26 08:03:49 +0000541 StackAdjust = MI.getOperand(2).getImm() / StackDivide;
Bill Wendling09b02c82011-07-25 18:00:28 +0000542 SubtractInstrIdx += InstrOffset;
543 ExpectEnd = true;
544 }
545 }
546
547 // Encode that we are using EBP/RBP as the frame pointer.
548 uint32_t CompactUnwindEncoding = 0;
Bill Wendlingde770552011-07-26 08:03:49 +0000549 CFAOffset /= StackDivide;
Bill Wendling09b02c82011-07-25 18:00:28 +0000550 if (HasFP) {
551 if ((CFAOffset & 0xFF) != CFAOffset)
552 // Offset was too big for compact encoding.
553 return 0;
554
555 // Get the encoding of the saved registers when we have a frame pointer.
556 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame(SavedRegs, Is64Bit);
Bill Wendling5b2c4972011-12-06 19:16:17 +0000557 if (RegEnc == ~0U) return 0;
Bill Wendling09b02c82011-07-25 18:00:28 +0000558
559 CompactUnwindEncoding |= 0x01000000;
560 CompactUnwindEncoding |= (CFAOffset & 0xFF) << 16;
561 CompactUnwindEncoding |= RegEnc & 0x7FFF;
562 } else {
Bill Wendling5b2c4972011-12-06 19:16:17 +0000563 if ((CFAOffset & 0xFF) == CFAOffset) {
564 // Frameless stack with a small stack size.
Bill Wendling09b02c82011-07-25 18:00:28 +0000565 CompactUnwindEncoding |= 0x02000000;
Bill Wendling5b2c4972011-12-06 19:16:17 +0000566
567 // Encode the stack size.
Bill Wendling75e14e02011-12-06 19:09:06 +0000568 CompactUnwindEncoding |= (CFAOffset & 0xFF) << 16;
Bill Wendling09b02c82011-07-25 18:00:28 +0000569 } else {
570 if ((CFAOffset & 0x7) != CFAOffset)
571 // The extra stack adjustments are too big for us to handle.
572 return 0;
573
574 // Frameless stack with an offset too large for us to encode compactly.
575 CompactUnwindEncoding |= 0x03000000;
576
577 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
578 // instruction.
579 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
580
581 // Encode any extra stack stack changes (done via push instructions).
582 CompactUnwindEncoding |= (CFAOffset & 0x7) << 13;
583 }
584
Bill Wendling5b2c4972011-12-06 19:16:17 +0000585 // Encode the number of registers saved.
Bill Wendling75e14e02011-12-06 19:09:06 +0000586 CompactUnwindEncoding |= ((6 - SavedRegIdx) & 0x7) << 10;
587
Bill Wendling09b02c82011-07-25 18:00:28 +0000588 // Get the encoding of the saved registers when we don't have a frame
589 // pointer.
590 uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegs,
591 6 - SavedRegIdx,
592 Is64Bit);
593 if (RegEnc == ~0U) return 0;
Bill Wendling5b2c4972011-12-06 19:16:17 +0000594
595 // Encode the register encoding.
Bill Wendling09b02c82011-07-25 18:00:28 +0000596 CompactUnwindEncoding |= RegEnc & 0x3FF;
597 }
598
599 return CompactUnwindEncoding;
600}
601
Anton Korobeynikov33464912010-11-15 00:06:54 +0000602/// emitPrologue - Push callee-saved registers onto the stack, which
603/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
604/// space for local variables. Also emit labels used by the exception handler to
605/// generate the exception handling frames.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000606void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000607 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
608 MachineBasicBlock::iterator MBBI = MBB.begin();
609 MachineFrameInfo *MFI = MF.getFrameInfo();
610 const Function *Fn = MF.getFunction();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000611 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
612 const X86InstrInfo &TII = *TM.getInstrInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000613 MachineModuleInfo &MMI = MF.getMMI();
614 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
615 bool needsFrameMoves = MMI.hasDebugInfo() ||
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000616 Fn->needsUnwindTableEntry();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000617 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
618 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000619 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000620 bool Is64Bit = STI.is64Bit();
621 bool IsWin64 = STI.isTargetWin64();
622 unsigned StackAlign = getStackAlignment();
623 unsigned SlotSize = RegInfo->getSlotSize();
624 unsigned FramePtr = RegInfo->getFrameRegister(MF);
625 unsigned StackPtr = RegInfo->getStackRegister();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000626 DebugLoc DL;
627
628 // If we're forcing a stack realignment we can't rely on just the frame
629 // info, we need to know the ABI stack alignment as well in case we
630 // have a call out. Otherwise just make sure we have some alignment - we'll
631 // go with the minimum SlotSize.
632 if (ForceStackAlign) {
633 if (MFI->hasCalls())
634 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
635 else if (MaxAlign < SlotSize)
636 MaxAlign = SlotSize;
637 }
638
639 // Add RETADDR move area to callee saved frame size.
640 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
641 if (TailCallReturnAddrDelta < 0)
642 X86FI->setCalleeSavedFrameSize(
643 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
644
645 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
646 // function, and use up to 128 bytes of stack space, don't have a frame
647 // pointer, calls, or dynamic alloca then we do not need to adjust the
648 // stack pointer (we fit in the Red Zone).
649 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
650 !RegInfo->needsStackRealignment(MF) &&
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000651 !MFI->hasVarSizedObjects() && // No dynamic alloca.
652 !MFI->adjustsStack() && // No calls.
653 !IsWin64 && // Win64 has no Red Zone
654 !MF.getTarget().Options.EnableSegmentedStacks) { // Regular stack
Anton Korobeynikov33464912010-11-15 00:06:54 +0000655 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
656 if (HasFP) MinSize += SlotSize;
657 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
658 MFI->setStackSize(StackSize);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000659 }
660
661 // Insert stack pointer adjustment for later moving of return addr. Only
662 // applies to tail call optimized functions where the callee argument stack
663 // size is bigger than the callers.
664 if (TailCallReturnAddrDelta < 0) {
665 MachineInstr *MI =
666 BuildMI(MBB, MBBI, DL,
667 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
668 StackPtr)
669 .addReg(StackPtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000670 .addImm(-TailCallReturnAddrDelta)
671 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000672 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
673 }
674
675 // Mapping for machine moves:
676 //
677 // DST: VirtualFP AND
678 // SRC: VirtualFP => DW_CFA_def_cfa_offset
679 // ELSE => DW_CFA_def_cfa
680 //
681 // SRC: VirtualFP AND
682 // DST: Register => DW_CFA_def_cfa_register
683 //
684 // ELSE
685 // OFFSET < 0 => DW_CFA_offset_extended_sf
686 // REG < 64 => DW_CFA_offset + Reg
687 // ELSE => DW_CFA_offset_extended
688
689 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
690 const TargetData *TD = MF.getTarget().getTargetData();
691 uint64_t NumBytes = 0;
692 int stackGrowth = -TD->getPointerSize();
693
694 if (HasFP) {
695 // Calculate required stack adjustment.
696 uint64_t FrameSize = StackSize - SlotSize;
697 if (RegInfo->needsStackRealignment(MF))
698 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
699
700 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
701
702 // Get the offset of the stack slot for the EBP register, which is
703 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
704 // Update the frame offset adjustment.
705 MFI->setOffsetAdjustment(-NumBytes);
706
707 // Save EBP/RBP into the appropriate stack slot.
708 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
Charles Davisaff232a2011-06-12 01:45:54 +0000709 .addReg(FramePtr, RegState::Kill)
710 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000711
712 if (needsFrameMoves) {
713 // Mark the place where EBP/RBP was saved.
714 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000715 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
716 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000717
718 // Define the current CFA rule to use the provided offset.
719 if (StackSize) {
720 MachineLocation SPDst(MachineLocation::VirtualFP);
721 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
722 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
723 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000724 MachineLocation SPDst(StackPtr);
725 MachineLocation SPSrc(StackPtr, stackGrowth);
726 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
727 }
728
729 // Change the rule for the FramePtr to be an "offset" rule.
730 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
731 MachineLocation FPSrc(FramePtr);
732 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
733 }
734
Bill Wendling09b02c82011-07-25 18:00:28 +0000735 // Update EBP with the new base value.
Anton Korobeynikov33464912010-11-15 00:06:54 +0000736 BuildMI(MBB, MBBI, DL,
737 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000738 .addReg(StackPtr)
739 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000740
741 if (needsFrameMoves) {
742 // Mark effective beginning of when frame pointer becomes valid.
743 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000744 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
745 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000746
747 // Define the current CFA to use the EBP/RBP register.
748 MachineLocation FPDst(FramePtr);
749 MachineLocation FPSrc(MachineLocation::VirtualFP);
750 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
751 }
752
753 // Mark the FramePtr as live-in in every block except the entry.
754 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
755 I != E; ++I)
756 I->addLiveIn(FramePtr);
757
758 // Realign stack
759 if (RegInfo->needsStackRealignment(MF)) {
760 MachineInstr *MI =
761 BuildMI(MBB, MBBI, DL,
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000762 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
763 .addReg(StackPtr)
764 .addImm(-MaxAlign)
765 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000766
767 // The EFLAGS implicit def is dead.
768 MI->getOperand(3).setIsDead();
769 }
770 } else {
771 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
772 }
773
774 // Skip the callee-saved push instructions.
775 bool PushedRegs = false;
776 int StackOffset = 2 * stackGrowth;
777
778 while (MBBI != MBB.end() &&
779 (MBBI->getOpcode() == X86::PUSH32r ||
780 MBBI->getOpcode() == X86::PUSH64r)) {
781 PushedRegs = true;
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000782 MBBI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000783 ++MBBI;
784
785 if (!HasFP && needsFrameMoves) {
786 // Mark callee-saved push instruction.
787 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
788 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
789
790 // Define the current CFA rule to use the provided offset.
Bill Wendling09b02c82011-07-25 18:00:28 +0000791 unsigned Ptr = StackSize ? MachineLocation::VirtualFP : StackPtr;
Anton Korobeynikov33464912010-11-15 00:06:54 +0000792 MachineLocation SPDst(Ptr);
793 MachineLocation SPSrc(Ptr, StackOffset);
794 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
795 StackOffset += stackGrowth;
796 }
797 }
798
799 DL = MBB.findDebugLoc(MBBI);
800
801 // If there is an SUB32ri of ESP immediately before this instruction, merge
802 // the two. This can be the case when tail call elimination is enabled and
803 // the callee has more arguments then the caller.
804 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
805
806 // If there is an ADD32ri or SUB32ri of ESP immediately after this
807 // instruction, merge the two instructions.
808 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
809
810 // Adjust stack pointer: ESP -= numbytes.
811
812 // Windows and cygwin/mingw require a prologue helper routine when allocating
813 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
814 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
815 // stack and adjust the stack pointer in one go. The 64-bit version of
816 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
817 // responsible for adjusting the stack pointer. Touching the stack at 4K
818 // increments is necessary to ensure that the guard pages used by the OS
819 // virtual memory manager are allocated in correct sequence.
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000820 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
821 const char *StackProbeSymbol;
822 bool isSPUpdateNeeded = false;
823
824 if (Is64Bit) {
825 if (STI.isTargetCygMing())
826 StackProbeSymbol = "___chkstk";
827 else {
828 StackProbeSymbol = "__chkstk";
829 isSPUpdateNeeded = true;
830 }
831 } else if (STI.isTargetCygMing())
832 StackProbeSymbol = "_alloca";
833 else
834 StackProbeSymbol = "_chkstk";
835
Anton Korobeynikov33464912010-11-15 00:06:54 +0000836 // Check whether EAX is livein for this function.
837 bool isEAXAlive = isEAXLiveIn(MF);
838
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000839 if (isEAXAlive) {
840 // Sanity check that EAX is not livein for this function.
841 // It should not be, so throw an assert.
842 assert(!Is64Bit && "EAX is livein in x64 case!");
843
Anton Korobeynikov33464912010-11-15 00:06:54 +0000844 // Save EAX
845 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000846 .addReg(X86::EAX, RegState::Kill)
847 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000848 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000849
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000850 if (Is64Bit) {
851 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
852 // Function prologue is responsible for adjusting the stack pointer.
853 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000854 .addImm(NumBytes)
855 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000856 } else {
857 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
858 // We'll also use 4 already allocated bytes for EAX.
859 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000860 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
861 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000862 }
863
864 BuildMI(MBB, MBBI, DL,
865 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
866 .addExternalSymbol(StackProbeSymbol)
867 .addReg(StackPtr, RegState::Define | RegState::Implicit)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000868 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
869 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000870
871 // MSVC x64's __chkstk needs to adjust %rsp.
872 // FIXME: %rax preserves the offset and should be available.
873 if (isSPUpdateNeeded)
874 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
875 TII, *RegInfo);
876
877 if (isEAXAlive) {
878 // Restore EAX
879 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
880 X86::EAX),
881 StackPtr, false, NumBytes - 4);
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000882 MI->setFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000883 MBB.insert(MBBI, MI);
884 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000885 } else if (NumBytes)
Evan Cheng7158e082011-01-03 22:53:22 +0000886 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
887 TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000888
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000889 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000890 // Mark end of stack pointer adjustment.
891 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000892 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
893 .addSym(Label);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000894
895 if (!HasFP && NumBytes) {
896 // Define the current CFA rule to use the provided offset.
897 if (StackSize) {
898 MachineLocation SPDst(MachineLocation::VirtualFP);
899 MachineLocation SPSrc(MachineLocation::VirtualFP,
900 -StackSize + stackGrowth);
901 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
902 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000903 MachineLocation SPDst(StackPtr);
904 MachineLocation SPSrc(StackPtr, stackGrowth);
905 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
906 }
907 }
908
909 // Emit DWARF info specifying the offsets of the callee-saved registers.
910 if (PushedRegs)
911 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
912 }
Bill Wendling09b02c82011-07-25 18:00:28 +0000913
914 // Darwin 10.7 and greater has support for compact unwind encoding.
Bill Wendlingc8725d12011-09-06 23:47:14 +0000915 if (STI.getTargetTriple().isMacOSX() &&
Eli Friedmanac86d432011-08-31 16:19:51 +0000916 !STI.getTargetTriple().isMacOSXVersionLT(10, 7))
Bill Wendling09b02c82011-07-25 18:00:28 +0000917 MMI.setCompactUnwindEncoding(getCompactUnwindEncoding(MF));
Anton Korobeynikov33464912010-11-15 00:06:54 +0000918}
919
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000920void X86FrameLowering::emitEpilogue(MachineFunction &MF,
Nick Lewycky3c2f0a12011-06-14 03:23:52 +0000921 MachineBasicBlock &MBB) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000922 const MachineFrameInfo *MFI = MF.getFrameInfo();
923 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000924 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
925 const X86InstrInfo &TII = *TM.getInstrInfo();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000926 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
927 assert(MBBI != MBB.end() && "Returning block has no instructions");
Anton Korobeynikov33464912010-11-15 00:06:54 +0000928 unsigned RetOpcode = MBBI->getOpcode();
929 DebugLoc DL = MBBI->getDebugLoc();
930 bool Is64Bit = STI.is64Bit();
931 unsigned StackAlign = getStackAlignment();
932 unsigned SlotSize = RegInfo->getSlotSize();
933 unsigned FramePtr = RegInfo->getFrameRegister(MF);
934 unsigned StackPtr = RegInfo->getStackRegister();
935
936 switch (RetOpcode) {
937 default:
938 llvm_unreachable("Can only insert epilog into returning blocks");
939 case X86::RET:
940 case X86::RETI:
941 case X86::TCRETURNdi:
942 case X86::TCRETURNri:
943 case X86::TCRETURNmi:
944 case X86::TCRETURNdi64:
945 case X86::TCRETURNri64:
946 case X86::TCRETURNmi64:
947 case X86::EH_RETURN:
948 case X86::EH_RETURN64:
949 break; // These are ok
950 }
951
952 // Get the number of bytes to allocate from the FrameInfo.
953 uint64_t StackSize = MFI->getStackSize();
954 uint64_t MaxAlign = MFI->getMaxAlignment();
955 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
956 uint64_t NumBytes = 0;
957
958 // If we're forcing a stack realignment we can't rely on just the frame
959 // info, we need to know the ABI stack alignment as well in case we
960 // have a call out. Otherwise just make sure we have some alignment - we'll
961 // go with the minimum.
962 if (ForceStackAlign) {
963 if (MFI->hasCalls())
964 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
965 else
966 MaxAlign = MaxAlign ? MaxAlign : 4;
967 }
968
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000969 if (hasFP(MF)) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000970 // Calculate required stack adjustment.
971 uint64_t FrameSize = StackSize - SlotSize;
972 if (RegInfo->needsStackRealignment(MF))
973 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
974
975 NumBytes = FrameSize - CSSize;
976
977 // Pop EBP.
978 BuildMI(MBB, MBBI, DL,
979 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
980 } else {
981 NumBytes = StackSize - CSSize;
982 }
983
984 // Skip the callee-saved pop instructions.
985 MachineBasicBlock::iterator LastCSPop = MBBI;
986 while (MBBI != MBB.begin()) {
987 MachineBasicBlock::iterator PI = prior(MBBI);
988 unsigned Opc = PI->getOpcode();
989
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000990 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
Anton Korobeynikov33464912010-11-15 00:06:54 +0000991 !PI->getDesc().isTerminator())
992 break;
993
994 --MBBI;
995 }
996
997 DL = MBBI->getDebugLoc();
998
999 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1000 // instruction, merge the two instructions.
1001 if (NumBytes || MFI->hasVarSizedObjects())
1002 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1003
1004 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1005 // slot before popping them off! Same applies for the case, when stack was
1006 // realigned.
1007 if (RegInfo->needsStackRealignment(MF)) {
1008 // We cannot use LEA here, because stack pointer was realigned. We need to
1009 // deallocate local frame back.
1010 if (CSSize) {
Evan Cheng7158e082011-01-03 22:53:22 +00001011 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001012 MBBI = prior(LastCSPop);
1013 }
1014
1015 BuildMI(MBB, MBBI, DL,
1016 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1017 StackPtr).addReg(FramePtr);
1018 } else if (MFI->hasVarSizedObjects()) {
1019 if (CSSize) {
1020 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
1021 MachineInstr *MI =
1022 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
1023 FramePtr, false, -CSSize);
1024 MBB.insert(MBBI, MI);
1025 } else {
1026 BuildMI(MBB, MBBI, DL,
1027 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
1028 .addReg(FramePtr);
1029 }
1030 } else if (NumBytes) {
1031 // Adjust stack pointer back: ESP += numbytes.
Evan Cheng7158e082011-01-03 22:53:22 +00001032 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001033 }
1034
1035 // We're returning from function via eh_return.
1036 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001037 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001038 MachineOperand &DestAddr = MBBI->getOperand(0);
1039 assert(DestAddr.isReg() && "Offset should be in register!");
1040 BuildMI(MBB, MBBI, DL,
1041 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1042 StackPtr).addReg(DestAddr.getReg());
1043 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1044 RetOpcode == X86::TCRETURNmi ||
1045 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1046 RetOpcode == X86::TCRETURNmi64) {
1047 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1048 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesenf7ca9762011-01-13 22:47:43 +00001049 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001050 MachineOperand &JumpTarget = MBBI->getOperand(0);
1051 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1052 assert(StackAdjust.isImm() && "Expecting immediate value.");
1053
1054 // Adjust stack pointer.
1055 int StackAdj = StackAdjust.getImm();
1056 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1057 int Offset = 0;
1058 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1059
1060 // Incoporate the retaddr area.
1061 Offset = StackAdj-MaxTCDelta;
1062 assert(Offset >= 0 && "Offset should never be negative");
1063
1064 if (Offset) {
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001065 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001066 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001067 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001068 }
1069
1070 // Jump to label or value in register.
1071 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
Evan Cheng3d2125c2010-11-30 23:55:39 +00001072 MachineInstrBuilder MIB =
1073 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1074 ? X86::TAILJMPd : X86::TAILJMPd64));
1075 if (JumpTarget.isGlobal())
1076 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1077 JumpTarget.getTargetFlags());
1078 else {
1079 assert(JumpTarget.isSymbol());
1080 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1081 JumpTarget.getTargetFlags());
1082 }
Anton Korobeynikov33464912010-11-15 00:06:54 +00001083 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1084 MachineInstrBuilder MIB =
1085 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1086 ? X86::TAILJMPm : X86::TAILJMPm64));
1087 for (unsigned i = 0; i != 5; ++i)
1088 MIB.addOperand(MBBI->getOperand(i));
1089 } else if (RetOpcode == X86::TCRETURNri64) {
1090 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1091 addReg(JumpTarget.getReg(), RegState::Kill);
1092 } else {
1093 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1094 addReg(JumpTarget.getReg(), RegState::Kill);
1095 }
1096
1097 MachineInstr *NewMI = prior(MBBI);
1098 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
1099 NewMI->addOperand(MBBI->getOperand(i));
1100
1101 // Delete the pseudo instruction TCRETURN.
1102 MBB.erase(MBBI);
1103 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
1104 (X86FI->getTCReturnAddrDelta() < 0)) {
1105 // Add the return addr area delta back since we are not tail calling.
1106 int delta = -1*X86FI->getTCReturnAddrDelta();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001107 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001108
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001109 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001110 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001111 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001112 }
1113}
Anton Korobeynikovd9e33852010-11-18 23:25:52 +00001114
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001115int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
Anton Korobeynikov82f58742010-11-20 15:59:32 +00001116 const X86RegisterInfo *RI =
1117 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
1118 const MachineFrameInfo *MFI = MF.getFrameInfo();
1119 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1120 uint64_t StackSize = MFI->getStackSize();
1121
1122 if (RI->needsStackRealignment(MF)) {
1123 if (FI < 0) {
1124 // Skip the saved EBP.
1125 Offset += RI->getSlotSize();
1126 } else {
Duncan Sands17001ce2011-10-18 12:44:00 +00001127 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
Anton Korobeynikov82f58742010-11-20 15:59:32 +00001128 return Offset + StackSize;
1129 }
1130 // FIXME: Support tail calls
1131 } else {
1132 if (!hasFP(MF))
1133 return Offset + StackSize;
1134
1135 // Skip the saved EBP.
1136 Offset += RI->getSlotSize();
1137
1138 // Skip the RETADDR move area
1139 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1140 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1141 if (TailCallReturnAddrDelta < 0)
1142 Offset -= TailCallReturnAddrDelta;
1143 }
1144
1145 return Offset;
1146}
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001147
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001148bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001149 MachineBasicBlock::iterator MI,
1150 const std::vector<CalleeSavedInfo> &CSI,
1151 const TargetRegisterInfo *TRI) const {
1152 if (CSI.empty())
1153 return false;
1154
1155 DebugLoc DL = MBB.findDebugLoc(MI);
1156
1157 MachineFunction &MF = *MBB.getParent();
1158
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001159 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
1160 unsigned FPReg = TRI->getFrameRegister(MF);
1161 unsigned CalleeFrameSize = 0;
1162
1163 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1164 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1165
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001166 // Push GPRs. It increases frame size.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001167 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1168 for (unsigned i = CSI.size(); i != 0; --i) {
1169 unsigned Reg = CSI[i-1].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001170 if (!X86::GR64RegClass.contains(Reg) &&
1171 !X86::GR32RegClass.contains(Reg))
1172 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001173 // Add the callee-saved register as live-in. It's killed at the spill.
1174 MBB.addLiveIn(Reg);
1175 if (Reg == FPReg)
1176 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
1177 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001178 CalleeFrameSize += SlotSize;
Charles Davisaff232a2011-06-12 01:45:54 +00001179 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1180 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001181 }
1182
1183 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001184
1185 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1186 // It can be done by spilling XMMs to stack frame.
1187 // Note that only Win64 ABI might spill XMMs.
1188 for (unsigned i = CSI.size(); i != 0; --i) {
1189 unsigned Reg = CSI[i-1].getReg();
1190 if (X86::GR64RegClass.contains(Reg) ||
1191 X86::GR32RegClass.contains(Reg))
1192 continue;
1193 // Add the callee-saved register as live-in. It's killed at the spill.
1194 MBB.addLiveIn(Reg);
1195 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1196 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
1197 RC, TRI);
1198 }
1199
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001200 return true;
1201}
1202
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001203bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001204 MachineBasicBlock::iterator MI,
1205 const std::vector<CalleeSavedInfo> &CSI,
1206 const TargetRegisterInfo *TRI) const {
1207 if (CSI.empty())
1208 return false;
1209
1210 DebugLoc DL = MBB.findDebugLoc(MI);
1211
1212 MachineFunction &MF = *MBB.getParent();
1213 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001214
1215 // Reload XMMs from stack frame.
1216 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1217 unsigned Reg = CSI[i].getReg();
1218 if (X86::GR64RegClass.contains(Reg) ||
1219 X86::GR32RegClass.contains(Reg))
1220 continue;
1221 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1222 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
1223 RC, TRI);
1224 }
1225
1226 // POP GPRs.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001227 unsigned FPReg = TRI->getFrameRegister(MF);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001228 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1229 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1230 unsigned Reg = CSI[i].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001231 if (!X86::GR64RegClass.contains(Reg) &&
1232 !X86::GR32RegClass.contains(Reg))
1233 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001234 if (Reg == FPReg)
1235 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
1236 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001237 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001238 }
1239 return true;
1240}
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001241
1242void
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001243X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001244 RegScavenger *RS) const {
1245 MachineFrameInfo *MFI = MF.getFrameInfo();
1246 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
1247 unsigned SlotSize = RegInfo->getSlotSize();
1248
1249 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1250 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1251
1252 if (TailCallReturnAddrDelta < 0) {
1253 // create RETURNADDR area
1254 // arg
1255 // arg
1256 // RETADDR
1257 // { ...
1258 // RETADDR area
1259 // ...
1260 // }
1261 // [EBP]
1262 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1263 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1264 }
1265
1266 if (hasFP(MF)) {
1267 assert((TailCallReturnAddrDelta <= 0) &&
1268 "The Delta should always be zero or negative");
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001269 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001270
1271 // Create a frame entry for the EBP register that must be saved.
1272 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1273 -(int)SlotSize +
1274 TFI.getOffsetOfLocalArea() +
1275 TailCallReturnAddrDelta,
1276 true);
1277 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1278 "Slot for EBP register must be last in order to be found!");
Duncan Sands17001ce2011-10-18 12:44:00 +00001279 (void)FrameIdx;
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001280 }
1281}
Rafael Espindola76927d752011-08-30 19:39:58 +00001282
1283static bool
1284HasNestArgument(const MachineFunction *MF) {
1285 const Function *F = MF->getFunction();
1286 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1287 I != E; I++) {
1288 if (I->hasNestAttr())
1289 return true;
1290 }
1291 return false;
1292}
1293
1294static unsigned
1295GetScratchRegister(bool Is64Bit, const MachineFunction &MF) {
1296 if (Is64Bit) {
1297 return X86::R11;
1298 } else {
1299 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1300 bool IsNested = HasNestArgument(&MF);
1301
1302 if (CallingConvention == CallingConv::X86_FastCall) {
1303 if (IsNested) {
Rafael Espindolae81abfd2011-08-31 16:43:33 +00001304 report_fatal_error("Segmented stacks does not support fastcall with "
1305 "nested function.");
Rafael Espindola76927d752011-08-30 19:39:58 +00001306 return -1;
1307 } else {
1308 return X86::EAX;
1309 }
1310 } else {
1311 if (IsNested)
1312 return X86::EDX;
1313 else
1314 return X86::ECX;
1315 }
1316 }
1317}
1318
Sanjoy Das199ce332011-12-03 09:32:07 +00001319// The stack limit in the TCB is set to this many bytes above the actual stack
1320// limit.
1321static const uint64_t kSplitStackAvailable = 256;
1322
Rafael Espindola76927d752011-08-30 19:39:58 +00001323void
1324X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1325 MachineBasicBlock &prologueMBB = MF.front();
1326 MachineFrameInfo *MFI = MF.getFrameInfo();
1327 const X86InstrInfo &TII = *TM.getInstrInfo();
1328 uint64_t StackSize;
1329 bool Is64Bit = STI.is64Bit();
1330 unsigned TlsReg, TlsOffset;
1331 DebugLoc DL;
1332 const X86Subtarget *ST = &MF.getTarget().getSubtarget<X86Subtarget>();
1333
1334 unsigned ScratchReg = GetScratchRegister(Is64Bit, MF);
1335 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1336 "Scratch register is live-in");
1337
1338 if (MF.getFunction()->isVarArg())
1339 report_fatal_error("Segmented stacks do not support vararg functions.");
1340 if (!ST->isTargetLinux())
1341 report_fatal_error("Segmented stacks supported only on linux.");
1342
1343 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1344 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1345 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1346 bool IsNested = false;
1347
1348 // We need to know if the function has a nest argument only in 64 bit mode.
1349 if (Is64Bit)
1350 IsNested = HasNestArgument(&MF);
1351
Bill Wendling4e680542011-10-13 08:24:19 +00001352 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1353 // allocMBB needs to be last (terminating) instruction.
Bill Wendling4e680542011-10-13 08:24:19 +00001354
Rafael Espindola76927d752011-08-30 19:39:58 +00001355 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1356 e = prologueMBB.livein_end(); i != e; i++) {
1357 allocMBB->addLiveIn(*i);
1358 checkMBB->addLiveIn(*i);
1359 }
1360
1361 if (IsNested)
Rafael Espindolae840e882011-10-26 21:12:27 +00001362 allocMBB->addLiveIn(X86::R10);
1363
Rafael Espindola76927d752011-08-30 19:39:58 +00001364 MF.push_front(allocMBB);
1365 MF.push_front(checkMBB);
1366
1367 // Eventually StackSize will be calculated by a link-time pass; which will
1368 // also decide whether checking code needs to be injected into this particular
1369 // prologue.
1370 StackSize = MFI->getStackSize();
1371
1372 // Read the limit off the current stacklet off the stack_guard location.
1373 if (Is64Bit) {
1374 TlsReg = X86::FS;
1375 TlsOffset = 0x70;
1376
Sanjoy Das199ce332011-12-03 09:32:07 +00001377 if (StackSize < kSplitStackAvailable)
1378 ScratchReg = X86::RSP;
1379 else
1380 BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RSP)
1381 .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1382
Rafael Espindola76927d752011-08-30 19:39:58 +00001383 BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
1384 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1385 } else {
1386 TlsReg = X86::GS;
1387 TlsOffset = 0x30;
1388
Sanjoy Das199ce332011-12-03 09:32:07 +00001389 if (StackSize < kSplitStackAvailable)
1390 ScratchReg = X86::ESP;
1391 else
1392 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1393 .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1394
Rafael Espindola76927d752011-08-30 19:39:58 +00001395 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1396 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1397 }
1398
1399 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1400 // It jumps to normal execution of the function body.
1401 BuildMI(checkMBB, DL, TII.get(X86::JG_4)).addMBB(&prologueMBB);
1402
1403 // On 32 bit we first push the arguments size and then the frame size. On 64
1404 // bit, we pass the stack frame size in r10 and the argument size in r11.
1405 if (Is64Bit) {
1406 // Functions with nested arguments use R10, so it needs to be saved across
1407 // the call to _morestack
1408
1409 if (IsNested)
1410 BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::RAX).addReg(X86::R10);
1411
1412 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R10)
1413 .addImm(StackSize);
1414 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R11)
1415 .addImm(X86FI->getArgumentStackSize());
1416 MF.getRegInfo().setPhysRegUsed(X86::R10);
1417 MF.getRegInfo().setPhysRegUsed(X86::R11);
1418 } else {
Rafael Espindola76927d752011-08-30 19:39:58 +00001419 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1420 .addImm(X86FI->getArgumentStackSize());
1421 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1422 .addImm(StackSize);
1423 }
1424
1425 // __morestack is in libgcc
1426 if (Is64Bit)
1427 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1428 .addExternalSymbol("__morestack");
1429 else
1430 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1431 .addExternalSymbol("__morestack");
1432
Bill Wendling4e680542011-10-13 08:24:19 +00001433 if (IsNested)
Rafael Espindolae840e882011-10-26 21:12:27 +00001434 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1435 else
1436 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
Bill Wendling4e680542011-10-13 08:24:19 +00001437
Rafael Espindolae840e882011-10-26 21:12:27 +00001438 allocMBB->addSuccessor(&prologueMBB);
Bill Wendling4e680542011-10-13 08:24:19 +00001439
Rafael Espindola76927d752011-08-30 19:39:58 +00001440 checkMBB->addSuccessor(allocMBB);
1441 checkMBB->addSuccessor(&prologueMBB);
1442
Jakob Stoklund Olesen51f0c762011-09-24 01:11:19 +00001443#ifdef XDEBUG
Rafael Espindola76927d752011-08-30 19:39:58 +00001444 MF.verify();
1445#endif
1446}