blob: e5f67526143d6191bf0893428e9a5d6ca5e51366 [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) {
Bill Wendling10e412e2011-12-14 23:53:24 +0000354 for (int Idx = 1; *CURegs; ++CURegs, ++Idx)
Bill Wendling09b02c82011-07-25 18:00:28 +0000355 if (*CURegs == Reg)
356 return Idx;
357
358 return -1;
359}
360
Bill Wendling57a3cd22011-12-06 21:23:42 +0000361// Number of registers that can be saved in a compact unwind encoding.
362#define CU_NUM_SAVED_REGS 6
363
Bill Wendling09b02c82011-07-25 18:00:28 +0000364/// encodeCompactUnwindRegistersWithoutFrame - Create the permutation encoding
365/// used with frameless stacks. It is passed the number of registers to be saved
366/// and an array of the registers saved.
Bill Wendling57a3cd22011-12-06 21:23:42 +0000367static uint32_t
368encodeCompactUnwindRegistersWithoutFrame(unsigned SavedRegs[CU_NUM_SAVED_REGS],
369 unsigned RegCount, bool Is64Bit) {
Bill Wendling09b02c82011-07-25 18:00:28 +0000370 // The saved registers are numbered from 1 to 6. In order to encode the order
371 // in which they were saved, we re-number them according to their place in the
372 // register order. The re-numbering is relative to the last re-numbered
373 // register. E.g., if we have registers {6, 2, 4, 5} saved in that order:
374 //
375 // Orig Re-Num
376 // ---- ------
377 // 6 6
378 // 2 2
379 // 4 3
380 // 5 3
381 //
382 static const unsigned CU32BitRegs[] = {
383 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
384 };
385 static const unsigned CU64BitRegs[] = {
386 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
387 };
388 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
389
Bill Wendling10e412e2011-12-14 23:53:24 +0000390 for (unsigned i = 0; i != CU_NUM_SAVED_REGS; ++i) {
Bill Wendling09b02c82011-07-25 18:00:28 +0000391 int CUReg = getCompactUnwindRegNum(CURegs, SavedRegs[i]);
392 if (CUReg == -1) return ~0U;
393 SavedRegs[i] = CUReg;
Bill Wendling79df9862011-12-06 01:26:14 +0000394 }
Bill Wendling09b02c82011-07-25 18:00:28 +0000395
Bill Wendling10e412e2011-12-14 23:53:24 +0000396 // Reverse the list.
397 std::swap(SavedRegs[0], SavedRegs[5]);
398 std::swap(SavedRegs[1], SavedRegs[4]);
399 std::swap(SavedRegs[2], SavedRegs[3]);
400
Bill Wendling57a3cd22011-12-06 21:23:42 +0000401 uint32_t RenumRegs[CU_NUM_SAVED_REGS];
402 for (unsigned i = CU_NUM_SAVED_REGS - RegCount; i < CU_NUM_SAVED_REGS; ++i) {
Bill Wendling09b02c82011-07-25 18:00:28 +0000403 unsigned Countless = 0;
Bill Wendling57a3cd22011-12-06 21:23:42 +0000404 for (unsigned j = CU_NUM_SAVED_REGS - RegCount; j < i; ++j)
Bill Wendling09b02c82011-07-25 18:00:28 +0000405 if (SavedRegs[j] < SavedRegs[i])
406 ++Countless;
407
408 RenumRegs[i] = SavedRegs[i] - Countless - 1;
409 }
410
411 // Take the renumbered values and encode them into a 10-bit number.
412 uint32_t permutationEncoding = 0;
413 switch (RegCount) {
414 case 6:
415 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
416 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
417 + RenumRegs[4];
418 break;
419 case 5:
420 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
421 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
422 + RenumRegs[5];
423 break;
424 case 4:
425 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
426 + 3 * RenumRegs[4] + RenumRegs[5];
427 break;
428 case 3:
429 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
430 + RenumRegs[5];
431 break;
432 case 2:
433 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
434 break;
435 case 1:
436 permutationEncoding |= RenumRegs[5];
437 break;
438 }
439
440 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
441 "Invalid compact register encoding!");
442 return permutationEncoding;
443}
444
445/// encodeCompactUnwindRegistersWithFrame - Return the registers encoded for a
446/// compact encoding with a frame pointer.
Bill Wendling57a3cd22011-12-06 21:23:42 +0000447static uint32_t
448encodeCompactUnwindRegistersWithFrame(unsigned SavedRegs[CU_NUM_SAVED_REGS],
449 bool Is64Bit) {
Bill Wendling09b02c82011-07-25 18:00:28 +0000450 static const unsigned CU32BitRegs[] = {
451 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
452 };
453 static const unsigned CU64BitRegs[] = {
454 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
455 };
456 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
457
Benjamin Kramere2eb9252012-01-12 17:37:18 +0000458 // FIXME: The code below is WRONG and breaks tests on i386, see
459 // SingleSource/Regression/C++/EH/ctor_dtor_count.exec
460 // SingleSource/Regression/C++/EH/exception_spec_test.exec
461 // SingleSource/Regression/C++/EH/function_try_block.exec
462 // SingleSource/Regression/C++/EH/throw_rethrow_test.exec
463 return ~0U;
464
Bill Wendling09b02c82011-07-25 18:00:28 +0000465 // Encode the registers in the order they were saved, 3-bits per register. The
466 // registers are numbered from 1 to 6.
467 uint32_t RegEnc = 0;
Jakob Stoklund Olesendec1f992012-01-11 09:08:04 +0000468 for (int I = 0; I != 6; ++I) {
Bill Wendling09b02c82011-07-25 18:00:28 +0000469 unsigned Reg = SavedRegs[I];
470 if (Reg == 0) break;
471 int CURegNum = getCompactUnwindRegNum(CURegs, Reg);
472 if (CURegNum == -1)
473 return ~0U;
Bill Wendling80caf9c2011-12-06 01:57:48 +0000474
475 // Encode the 3-bit register number in order, skipping over 3-bits for each
476 // register.
Bill Wendling79df9862011-12-06 01:26:14 +0000477 RegEnc |= (CURegNum & 0x7) << ((5 - I) * 3);
Bill Wendling09b02c82011-07-25 18:00:28 +0000478 }
479
Jakob Stoklund Olesendec1f992012-01-11 09:08:04 +0000480 assert((RegEnc & 0x3FFFF) == RegEnc && "Invalid compact register encoding!");
Bill Wendling09b02c82011-07-25 18:00:28 +0000481 return RegEnc;
482}
483
484uint32_t X86FrameLowering::getCompactUnwindEncoding(MachineFunction &MF) const {
485 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
486 unsigned FramePtr = RegInfo->getFrameRegister(MF);
487 unsigned StackPtr = RegInfo->getStackRegister();
488
Bill Wendling09b02c82011-07-25 18:00:28 +0000489 bool Is64Bit = STI.is64Bit();
490 bool HasFP = hasFP(MF);
491
Bill Wendling57a3cd22011-12-06 21:23:42 +0000492 unsigned SavedRegs[CU_NUM_SAVED_REGS] = { 0, 0, 0, 0, 0, 0 };
Bill Wendling10e412e2011-12-14 23:53:24 +0000493 unsigned SavedRegIdx = 0;
Bill Wendling09b02c82011-07-25 18:00:28 +0000494
495 unsigned OffsetSize = (Is64Bit ? 8 : 4);
496
497 unsigned PushInstr = (Is64Bit ? X86::PUSH64r : X86::PUSH32r);
498 unsigned PushInstrSize = 1;
499 unsigned MoveInstr = (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
500 unsigned MoveInstrSize = (Is64Bit ? 3 : 2);
Bill Wendling09b02c82011-07-25 18:00:28 +0000501 unsigned SubtractInstrIdx = (Is64Bit ? 3 : 2);
502
Bill Wendlingde770552011-07-26 08:03:49 +0000503 unsigned StackDivide = (Is64Bit ? 8 : 4);
504
Bill Wendling09b02c82011-07-25 18:00:28 +0000505 unsigned InstrOffset = 0;
Bill Wendling09b02c82011-07-25 18:00:28 +0000506 unsigned StackAdjust = 0;
Bill Wendling57a3cd22011-12-06 21:23:42 +0000507 unsigned StackSize = 0;
Bill Wendling09b02c82011-07-25 18:00:28 +0000508
509 MachineBasicBlock &MBB = MF.front(); // Prologue is in entry BB.
510 bool ExpectEnd = false;
511 for (MachineBasicBlock::iterator
512 MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ++MBBI) {
513 MachineInstr &MI = *MBBI;
514 unsigned Opc = MI.getOpcode();
515 if (Opc == X86::PROLOG_LABEL) continue;
516 if (!MI.getFlag(MachineInstr::FrameSetup)) break;
517
518 // We don't exect any more prolog instructions.
519 if (ExpectEnd) return 0;
520
521 if (Opc == PushInstr) {
522 // If there are too many saved registers, we cannot use compact encoding.
Bill Wendling10e412e2011-12-14 23:53:24 +0000523 if (SavedRegIdx >= CU_NUM_SAVED_REGS) return 0;
Bill Wendling09b02c82011-07-25 18:00:28 +0000524
Bill Wendling10e412e2011-12-14 23:53:24 +0000525 SavedRegs[SavedRegIdx++] = MI.getOperand(0).getReg();
Bill Wendling57a3cd22011-12-06 21:23:42 +0000526 StackAdjust += OffsetSize;
Bill Wendling09b02c82011-07-25 18:00:28 +0000527 InstrOffset += PushInstrSize;
528 } else if (Opc == MoveInstr) {
529 unsigned SrcReg = MI.getOperand(1).getReg();
530 unsigned DstReg = MI.getOperand(0).getReg();
531
532 if (DstReg != FramePtr || SrcReg != StackPtr)
533 return 0;
534
Bill Wendling57a3cd22011-12-06 21:23:42 +0000535 StackAdjust = 0;
Bill Wendling09b02c82011-07-25 18:00:28 +0000536 memset(SavedRegs, 0, sizeof(SavedRegs));
Bill Wendling10e412e2011-12-14 23:53:24 +0000537 SavedRegIdx = 0;
Bill Wendling09b02c82011-07-25 18:00:28 +0000538 InstrOffset += MoveInstrSize;
Bill Wendling84d518a2011-12-06 22:14:27 +0000539 } else if (Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
540 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) {
Bill Wendling57a3cd22011-12-06 21:23:42 +0000541 if (StackSize)
542 // We already have a stack size.
Bill Wendling09b02c82011-07-25 18:00:28 +0000543 return 0;
544
545 if (!MI.getOperand(0).isReg() ||
546 MI.getOperand(0).getReg() != MI.getOperand(1).getReg() ||
547 MI.getOperand(0).getReg() != StackPtr || !MI.getOperand(2).isImm())
548 // We need this to be a stack adjustment pointer. Something like:
549 //
550 // %RSP<def> = SUB64ri8 %RSP, 48
551 return 0;
552
Bill Wendling57a3cd22011-12-06 21:23:42 +0000553 StackSize = MI.getOperand(2).getImm() / StackDivide;
Bill Wendling09b02c82011-07-25 18:00:28 +0000554 SubtractInstrIdx += InstrOffset;
555 ExpectEnd = true;
556 }
557 }
558
559 // Encode that we are using EBP/RBP as the frame pointer.
560 uint32_t CompactUnwindEncoding = 0;
Bill Wendling57a3cd22011-12-06 21:23:42 +0000561 StackAdjust /= StackDivide;
Bill Wendling09b02c82011-07-25 18:00:28 +0000562 if (HasFP) {
Bill Wendling57a3cd22011-12-06 21:23:42 +0000563 if ((StackAdjust & 0xFF) != StackAdjust)
Bill Wendling09b02c82011-07-25 18:00:28 +0000564 // Offset was too big for compact encoding.
565 return 0;
566
567 // Get the encoding of the saved registers when we have a frame pointer.
568 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame(SavedRegs, Is64Bit);
Bill Wendling5b2c4972011-12-06 19:16:17 +0000569 if (RegEnc == ~0U) return 0;
Bill Wendling09b02c82011-07-25 18:00:28 +0000570
571 CompactUnwindEncoding |= 0x01000000;
Bill Wendling57a3cd22011-12-06 21:23:42 +0000572 CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
Bill Wendling09b02c82011-07-25 18:00:28 +0000573 CompactUnwindEncoding |= RegEnc & 0x7FFF;
574 } else {
Bill Wendlingb3ec3292011-12-07 07:58:55 +0000575 ++StackAdjust;
576 uint32_t TotalStackSize = StackAdjust + StackSize;
Bill Wendling581ac272011-12-06 21:34:01 +0000577 if ((TotalStackSize & 0xFF) == TotalStackSize) {
Bill Wendling5b2c4972011-12-06 19:16:17 +0000578 // Frameless stack with a small stack size.
Bill Wendling09b02c82011-07-25 18:00:28 +0000579 CompactUnwindEncoding |= 0x02000000;
Bill Wendling5b2c4972011-12-06 19:16:17 +0000580
581 // Encode the stack size.
Bill Wendling581ac272011-12-06 21:34:01 +0000582 CompactUnwindEncoding |= (TotalStackSize & 0xFF) << 16;
Bill Wendling09b02c82011-07-25 18:00:28 +0000583 } else {
Bill Wendling57a3cd22011-12-06 21:23:42 +0000584 if ((StackAdjust & 0x7) != StackAdjust)
Bill Wendling09b02c82011-07-25 18:00:28 +0000585 // The extra stack adjustments are too big for us to handle.
586 return 0;
587
588 // Frameless stack with an offset too large for us to encode compactly.
589 CompactUnwindEncoding |= 0x03000000;
590
591 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
592 // instruction.
593 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
594
Bill Wendling57a3cd22011-12-06 21:23:42 +0000595 // Encode any extra stack stack adjustments (done via push instructions).
596 CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
Bill Wendling09b02c82011-07-25 18:00:28 +0000597 }
598
Bill Wendling5b2c4972011-12-06 19:16:17 +0000599 // Encode the number of registers saved.
Bill Wendling10e412e2011-12-14 23:53:24 +0000600 CompactUnwindEncoding |= (SavedRegIdx & 0x7) << 10;
Bill Wendling75e14e02011-12-06 19:09:06 +0000601
Bill Wendling09b02c82011-07-25 18:00:28 +0000602 // Get the encoding of the saved registers when we don't have a frame
603 // pointer.
Bill Wendling57a3cd22011-12-06 21:23:42 +0000604 uint32_t RegEnc =
Bill Wendling10e412e2011-12-14 23:53:24 +0000605 encodeCompactUnwindRegistersWithoutFrame(SavedRegs, SavedRegIdx,
Bill Wendling57a3cd22011-12-06 21:23:42 +0000606 Is64Bit);
Bill Wendling09b02c82011-07-25 18:00:28 +0000607 if (RegEnc == ~0U) return 0;
Bill Wendling5b2c4972011-12-06 19:16:17 +0000608
609 // Encode the register encoding.
Bill Wendling09b02c82011-07-25 18:00:28 +0000610 CompactUnwindEncoding |= RegEnc & 0x3FF;
611 }
612
613 return CompactUnwindEncoding;
614}
615
Anton Korobeynikov33464912010-11-15 00:06:54 +0000616/// emitPrologue - Push callee-saved registers onto the stack, which
617/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
618/// space for local variables. Also emit labels used by the exception handler to
619/// generate the exception handling frames.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000620void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000621 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
622 MachineBasicBlock::iterator MBBI = MBB.begin();
623 MachineFrameInfo *MFI = MF.getFrameInfo();
624 const Function *Fn = MF.getFunction();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000625 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
626 const X86InstrInfo &TII = *TM.getInstrInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000627 MachineModuleInfo &MMI = MF.getMMI();
628 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
629 bool needsFrameMoves = MMI.hasDebugInfo() ||
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000630 Fn->needsUnwindTableEntry();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000631 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
632 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000633 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000634 bool Is64Bit = STI.is64Bit();
635 bool IsWin64 = STI.isTargetWin64();
636 unsigned StackAlign = getStackAlignment();
637 unsigned SlotSize = RegInfo->getSlotSize();
638 unsigned FramePtr = RegInfo->getFrameRegister(MF);
639 unsigned StackPtr = RegInfo->getStackRegister();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000640 DebugLoc DL;
641
642 // If we're forcing a stack realignment we can't rely on just the frame
643 // info, we need to know the ABI stack alignment as well in case we
644 // have a call out. Otherwise just make sure we have some alignment - we'll
645 // go with the minimum SlotSize.
646 if (ForceStackAlign) {
647 if (MFI->hasCalls())
648 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
649 else if (MaxAlign < SlotSize)
650 MaxAlign = SlotSize;
651 }
652
653 // Add RETADDR move area to callee saved frame size.
654 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
655 if (TailCallReturnAddrDelta < 0)
656 X86FI->setCalleeSavedFrameSize(
657 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
658
659 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
660 // function, and use up to 128 bytes of stack space, don't have a frame
661 // pointer, calls, or dynamic alloca then we do not need to adjust the
662 // stack pointer (we fit in the Red Zone).
663 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
664 !RegInfo->needsStackRealignment(MF) &&
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000665 !MFI->hasVarSizedObjects() && // No dynamic alloca.
666 !MFI->adjustsStack() && // No calls.
667 !IsWin64 && // Win64 has no Red Zone
668 !MF.getTarget().Options.EnableSegmentedStacks) { // Regular stack
Anton Korobeynikov33464912010-11-15 00:06:54 +0000669 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
670 if (HasFP) MinSize += SlotSize;
671 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
672 MFI->setStackSize(StackSize);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000673 }
674
675 // Insert stack pointer adjustment for later moving of return addr. Only
676 // applies to tail call optimized functions where the callee argument stack
677 // size is bigger than the callers.
678 if (TailCallReturnAddrDelta < 0) {
679 MachineInstr *MI =
680 BuildMI(MBB, MBBI, DL,
681 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
682 StackPtr)
683 .addReg(StackPtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000684 .addImm(-TailCallReturnAddrDelta)
685 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000686 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
687 }
688
689 // Mapping for machine moves:
690 //
691 // DST: VirtualFP AND
692 // SRC: VirtualFP => DW_CFA_def_cfa_offset
693 // ELSE => DW_CFA_def_cfa
694 //
695 // SRC: VirtualFP AND
696 // DST: Register => DW_CFA_def_cfa_register
697 //
698 // ELSE
699 // OFFSET < 0 => DW_CFA_offset_extended_sf
700 // REG < 64 => DW_CFA_offset + Reg
701 // ELSE => DW_CFA_offset_extended
702
703 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
704 const TargetData *TD = MF.getTarget().getTargetData();
705 uint64_t NumBytes = 0;
706 int stackGrowth = -TD->getPointerSize();
707
708 if (HasFP) {
709 // Calculate required stack adjustment.
710 uint64_t FrameSize = StackSize - SlotSize;
711 if (RegInfo->needsStackRealignment(MF))
712 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
713
714 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
715
716 // Get the offset of the stack slot for the EBP register, which is
717 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
718 // Update the frame offset adjustment.
719 MFI->setOffsetAdjustment(-NumBytes);
720
721 // Save EBP/RBP into the appropriate stack slot.
722 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
Charles Davisaff232a2011-06-12 01:45:54 +0000723 .addReg(FramePtr, RegState::Kill)
724 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000725
726 if (needsFrameMoves) {
727 // Mark the place where EBP/RBP was saved.
728 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000729 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
730 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000731
732 // Define the current CFA rule to use the provided offset.
733 if (StackSize) {
734 MachineLocation SPDst(MachineLocation::VirtualFP);
735 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
736 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
737 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000738 MachineLocation SPDst(StackPtr);
739 MachineLocation SPSrc(StackPtr, stackGrowth);
740 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
741 }
742
743 // Change the rule for the FramePtr to be an "offset" rule.
744 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
745 MachineLocation FPSrc(FramePtr);
746 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
747 }
748
Bill Wendling09b02c82011-07-25 18:00:28 +0000749 // Update EBP with the new base value.
Anton Korobeynikov33464912010-11-15 00:06:54 +0000750 BuildMI(MBB, MBBI, DL,
751 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000752 .addReg(StackPtr)
753 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000754
755 if (needsFrameMoves) {
756 // Mark effective beginning of when frame pointer becomes valid.
757 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000758 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
759 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000760
761 // Define the current CFA to use the EBP/RBP register.
762 MachineLocation FPDst(FramePtr);
763 MachineLocation FPSrc(MachineLocation::VirtualFP);
764 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
765 }
766
767 // Mark the FramePtr as live-in in every block except the entry.
768 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
769 I != E; ++I)
770 I->addLiveIn(FramePtr);
771
772 // Realign stack
773 if (RegInfo->needsStackRealignment(MF)) {
774 MachineInstr *MI =
775 BuildMI(MBB, MBBI, DL,
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000776 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
777 .addReg(StackPtr)
778 .addImm(-MaxAlign)
779 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000780
781 // The EFLAGS implicit def is dead.
782 MI->getOperand(3).setIsDead();
783 }
784 } else {
785 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
786 }
787
788 // Skip the callee-saved push instructions.
789 bool PushedRegs = false;
790 int StackOffset = 2 * stackGrowth;
791
792 while (MBBI != MBB.end() &&
793 (MBBI->getOpcode() == X86::PUSH32r ||
794 MBBI->getOpcode() == X86::PUSH64r)) {
795 PushedRegs = true;
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000796 MBBI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000797 ++MBBI;
798
799 if (!HasFP && needsFrameMoves) {
800 // Mark callee-saved push instruction.
801 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
802 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
803
804 // Define the current CFA rule to use the provided offset.
Bill Wendling09b02c82011-07-25 18:00:28 +0000805 unsigned Ptr = StackSize ? MachineLocation::VirtualFP : StackPtr;
Anton Korobeynikov33464912010-11-15 00:06:54 +0000806 MachineLocation SPDst(Ptr);
807 MachineLocation SPSrc(Ptr, StackOffset);
808 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
809 StackOffset += stackGrowth;
810 }
811 }
812
813 DL = MBB.findDebugLoc(MBBI);
814
815 // If there is an SUB32ri of ESP immediately before this instruction, merge
816 // the two. This can be the case when tail call elimination is enabled and
817 // the callee has more arguments then the caller.
818 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
819
820 // If there is an ADD32ri or SUB32ri of ESP immediately after this
821 // instruction, merge the two instructions.
822 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
823
824 // Adjust stack pointer: ESP -= numbytes.
825
826 // Windows and cygwin/mingw require a prologue helper routine when allocating
827 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
828 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
829 // stack and adjust the stack pointer in one go. The 64-bit version of
830 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
831 // responsible for adjusting the stack pointer. Touching the stack at 4K
832 // increments is necessary to ensure that the guard pages used by the OS
833 // virtual memory manager are allocated in correct sequence.
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000834 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
835 const char *StackProbeSymbol;
836 bool isSPUpdateNeeded = false;
837
838 if (Is64Bit) {
839 if (STI.isTargetCygMing())
840 StackProbeSymbol = "___chkstk";
841 else {
842 StackProbeSymbol = "__chkstk";
843 isSPUpdateNeeded = true;
844 }
845 } else if (STI.isTargetCygMing())
846 StackProbeSymbol = "_alloca";
847 else
848 StackProbeSymbol = "_chkstk";
849
Anton Korobeynikov33464912010-11-15 00:06:54 +0000850 // Check whether EAX is livein for this function.
851 bool isEAXAlive = isEAXLiveIn(MF);
852
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000853 if (isEAXAlive) {
854 // Sanity check that EAX is not livein for this function.
855 // It should not be, so throw an assert.
856 assert(!Is64Bit && "EAX is livein in x64 case!");
857
Anton Korobeynikov33464912010-11-15 00:06:54 +0000858 // Save EAX
859 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000860 .addReg(X86::EAX, RegState::Kill)
861 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000862 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000863
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000864 if (Is64Bit) {
865 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
866 // Function prologue is responsible for adjusting the stack pointer.
867 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000868 .addImm(NumBytes)
869 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000870 } else {
871 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
872 // We'll also use 4 already allocated bytes for EAX.
873 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000874 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
875 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000876 }
877
878 BuildMI(MBB, MBBI, DL,
879 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
880 .addExternalSymbol(StackProbeSymbol)
881 .addReg(StackPtr, RegState::Define | RegState::Implicit)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000882 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
883 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000884
885 // MSVC x64's __chkstk needs to adjust %rsp.
886 // FIXME: %rax preserves the offset and should be available.
887 if (isSPUpdateNeeded)
888 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
889 TII, *RegInfo);
890
891 if (isEAXAlive) {
892 // Restore EAX
893 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
894 X86::EAX),
895 StackPtr, false, NumBytes - 4);
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000896 MI->setFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000897 MBB.insert(MBBI, MI);
898 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000899 } else if (NumBytes)
Evan Cheng7158e082011-01-03 22:53:22 +0000900 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
901 TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000902
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000903 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000904 // Mark end of stack pointer adjustment.
905 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000906 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
907 .addSym(Label);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000908
909 if (!HasFP && NumBytes) {
910 // Define the current CFA rule to use the provided offset.
911 if (StackSize) {
912 MachineLocation SPDst(MachineLocation::VirtualFP);
913 MachineLocation SPSrc(MachineLocation::VirtualFP,
914 -StackSize + stackGrowth);
915 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
916 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000917 MachineLocation SPDst(StackPtr);
918 MachineLocation SPSrc(StackPtr, stackGrowth);
919 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
920 }
921 }
922
923 // Emit DWARF info specifying the offsets of the callee-saved registers.
924 if (PushedRegs)
925 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
926 }
Bill Wendling09b02c82011-07-25 18:00:28 +0000927
928 // Darwin 10.7 and greater has support for compact unwind encoding.
Bill Wendlingc8725d12011-09-06 23:47:14 +0000929 if (STI.getTargetTriple().isMacOSX() &&
Eli Friedmanac86d432011-08-31 16:19:51 +0000930 !STI.getTargetTriple().isMacOSXVersionLT(10, 7))
Bill Wendling09b02c82011-07-25 18:00:28 +0000931 MMI.setCompactUnwindEncoding(getCompactUnwindEncoding(MF));
Anton Korobeynikov33464912010-11-15 00:06:54 +0000932}
933
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000934void X86FrameLowering::emitEpilogue(MachineFunction &MF,
Nick Lewycky3c2f0a12011-06-14 03:23:52 +0000935 MachineBasicBlock &MBB) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000936 const MachineFrameInfo *MFI = MF.getFrameInfo();
937 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000938 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
939 const X86InstrInfo &TII = *TM.getInstrInfo();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000940 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
941 assert(MBBI != MBB.end() && "Returning block has no instructions");
Anton Korobeynikov33464912010-11-15 00:06:54 +0000942 unsigned RetOpcode = MBBI->getOpcode();
943 DebugLoc DL = MBBI->getDebugLoc();
944 bool Is64Bit = STI.is64Bit();
945 unsigned StackAlign = getStackAlignment();
946 unsigned SlotSize = RegInfo->getSlotSize();
947 unsigned FramePtr = RegInfo->getFrameRegister(MF);
948 unsigned StackPtr = RegInfo->getStackRegister();
949
950 switch (RetOpcode) {
951 default:
952 llvm_unreachable("Can only insert epilog into returning blocks");
953 case X86::RET:
954 case X86::RETI:
955 case X86::TCRETURNdi:
956 case X86::TCRETURNri:
957 case X86::TCRETURNmi:
958 case X86::TCRETURNdi64:
959 case X86::TCRETURNri64:
960 case X86::TCRETURNmi64:
961 case X86::EH_RETURN:
962 case X86::EH_RETURN64:
963 break; // These are ok
964 }
965
966 // Get the number of bytes to allocate from the FrameInfo.
967 uint64_t StackSize = MFI->getStackSize();
968 uint64_t MaxAlign = MFI->getMaxAlignment();
969 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
970 uint64_t NumBytes = 0;
971
972 // If we're forcing a stack realignment we can't rely on just the frame
973 // info, we need to know the ABI stack alignment as well in case we
974 // have a call out. Otherwise just make sure we have some alignment - we'll
975 // go with the minimum.
976 if (ForceStackAlign) {
977 if (MFI->hasCalls())
978 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
979 else
980 MaxAlign = MaxAlign ? MaxAlign : 4;
981 }
982
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000983 if (hasFP(MF)) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000984 // Calculate required stack adjustment.
985 uint64_t FrameSize = StackSize - SlotSize;
986 if (RegInfo->needsStackRealignment(MF))
987 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
988
989 NumBytes = FrameSize - CSSize;
990
991 // Pop EBP.
992 BuildMI(MBB, MBBI, DL,
993 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
994 } else {
995 NumBytes = StackSize - CSSize;
996 }
997
998 // Skip the callee-saved pop instructions.
999 MachineBasicBlock::iterator LastCSPop = MBBI;
1000 while (MBBI != MBB.begin()) {
1001 MachineBasicBlock::iterator PI = prior(MBBI);
1002 unsigned Opc = PI->getOpcode();
1003
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001004 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001005 !PI->isTerminator())
Anton Korobeynikov33464912010-11-15 00:06:54 +00001006 break;
1007
1008 --MBBI;
1009 }
1010
1011 DL = MBBI->getDebugLoc();
1012
1013 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1014 // instruction, merge the two instructions.
1015 if (NumBytes || MFI->hasVarSizedObjects())
1016 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1017
1018 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1019 // slot before popping them off! Same applies for the case, when stack was
1020 // realigned.
1021 if (RegInfo->needsStackRealignment(MF)) {
1022 // We cannot use LEA here, because stack pointer was realigned. We need to
1023 // deallocate local frame back.
1024 if (CSSize) {
Evan Cheng7158e082011-01-03 22:53:22 +00001025 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001026 MBBI = prior(LastCSPop);
1027 }
1028
1029 BuildMI(MBB, MBBI, DL,
1030 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1031 StackPtr).addReg(FramePtr);
1032 } else if (MFI->hasVarSizedObjects()) {
1033 if (CSSize) {
1034 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
1035 MachineInstr *MI =
1036 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
1037 FramePtr, false, -CSSize);
1038 MBB.insert(MBBI, MI);
1039 } else {
1040 BuildMI(MBB, MBBI, DL,
1041 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
1042 .addReg(FramePtr);
1043 }
1044 } else if (NumBytes) {
1045 // Adjust stack pointer back: ESP += numbytes.
Evan Cheng7158e082011-01-03 22:53:22 +00001046 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001047 }
1048
1049 // We're returning from function via eh_return.
1050 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001051 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001052 MachineOperand &DestAddr = MBBI->getOperand(0);
1053 assert(DestAddr.isReg() && "Offset should be in register!");
1054 BuildMI(MBB, MBBI, DL,
1055 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1056 StackPtr).addReg(DestAddr.getReg());
1057 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1058 RetOpcode == X86::TCRETURNmi ||
1059 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1060 RetOpcode == X86::TCRETURNmi64) {
1061 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1062 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesenf7ca9762011-01-13 22:47:43 +00001063 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001064 MachineOperand &JumpTarget = MBBI->getOperand(0);
1065 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1066 assert(StackAdjust.isImm() && "Expecting immediate value.");
1067
1068 // Adjust stack pointer.
1069 int StackAdj = StackAdjust.getImm();
1070 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1071 int Offset = 0;
1072 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1073
1074 // Incoporate the retaddr area.
1075 Offset = StackAdj-MaxTCDelta;
1076 assert(Offset >= 0 && "Offset should never be negative");
1077
1078 if (Offset) {
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001079 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001080 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001081 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001082 }
1083
1084 // Jump to label or value in register.
1085 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
Evan Cheng3d2125c2010-11-30 23:55:39 +00001086 MachineInstrBuilder MIB =
1087 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1088 ? X86::TAILJMPd : X86::TAILJMPd64));
1089 if (JumpTarget.isGlobal())
1090 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1091 JumpTarget.getTargetFlags());
1092 else {
1093 assert(JumpTarget.isSymbol());
1094 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1095 JumpTarget.getTargetFlags());
1096 }
Anton Korobeynikov33464912010-11-15 00:06:54 +00001097 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1098 MachineInstrBuilder MIB =
1099 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1100 ? X86::TAILJMPm : X86::TAILJMPm64));
1101 for (unsigned i = 0; i != 5; ++i)
1102 MIB.addOperand(MBBI->getOperand(i));
1103 } else if (RetOpcode == X86::TCRETURNri64) {
1104 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1105 addReg(JumpTarget.getReg(), RegState::Kill);
1106 } else {
1107 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1108 addReg(JumpTarget.getReg(), RegState::Kill);
1109 }
1110
1111 MachineInstr *NewMI = prior(MBBI);
1112 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
1113 NewMI->addOperand(MBBI->getOperand(i));
1114
1115 // Delete the pseudo instruction TCRETURN.
1116 MBB.erase(MBBI);
1117 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
1118 (X86FI->getTCReturnAddrDelta() < 0)) {
1119 // Add the return addr area delta back since we are not tail calling.
1120 int delta = -1*X86FI->getTCReturnAddrDelta();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001121 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001122
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001123 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001124 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001125 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001126 }
1127}
Anton Korobeynikovd9e33852010-11-18 23:25:52 +00001128
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001129int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
Anton Korobeynikov82f58742010-11-20 15:59:32 +00001130 const X86RegisterInfo *RI =
1131 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
1132 const MachineFrameInfo *MFI = MF.getFrameInfo();
1133 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1134 uint64_t StackSize = MFI->getStackSize();
1135
1136 if (RI->needsStackRealignment(MF)) {
1137 if (FI < 0) {
1138 // Skip the saved EBP.
1139 Offset += RI->getSlotSize();
1140 } else {
Duncan Sands17001ce2011-10-18 12:44:00 +00001141 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
Anton Korobeynikov82f58742010-11-20 15:59:32 +00001142 return Offset + StackSize;
1143 }
1144 // FIXME: Support tail calls
1145 } else {
1146 if (!hasFP(MF))
1147 return Offset + StackSize;
1148
1149 // Skip the saved EBP.
1150 Offset += RI->getSlotSize();
1151
1152 // Skip the RETADDR move area
1153 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1154 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1155 if (TailCallReturnAddrDelta < 0)
1156 Offset -= TailCallReturnAddrDelta;
1157 }
1158
1159 return Offset;
1160}
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001161
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001162bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001163 MachineBasicBlock::iterator MI,
1164 const std::vector<CalleeSavedInfo> &CSI,
1165 const TargetRegisterInfo *TRI) const {
1166 if (CSI.empty())
1167 return false;
1168
1169 DebugLoc DL = MBB.findDebugLoc(MI);
1170
1171 MachineFunction &MF = *MBB.getParent();
1172
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001173 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
1174 unsigned FPReg = TRI->getFrameRegister(MF);
1175 unsigned CalleeFrameSize = 0;
1176
1177 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1178 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1179
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001180 // Push GPRs. It increases frame size.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001181 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1182 for (unsigned i = CSI.size(); i != 0; --i) {
1183 unsigned Reg = CSI[i-1].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001184 if (!X86::GR64RegClass.contains(Reg) &&
1185 !X86::GR32RegClass.contains(Reg))
1186 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001187 // Add the callee-saved register as live-in. It's killed at the spill.
1188 MBB.addLiveIn(Reg);
1189 if (Reg == FPReg)
1190 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
1191 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001192 CalleeFrameSize += SlotSize;
Charles Davisaff232a2011-06-12 01:45:54 +00001193 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1194 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001195 }
1196
1197 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001198
1199 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1200 // It can be done by spilling XMMs to stack frame.
1201 // Note that only Win64 ABI might spill XMMs.
1202 for (unsigned i = CSI.size(); i != 0; --i) {
1203 unsigned Reg = CSI[i-1].getReg();
1204 if (X86::GR64RegClass.contains(Reg) ||
1205 X86::GR32RegClass.contains(Reg))
1206 continue;
1207 // Add the callee-saved register as live-in. It's killed at the spill.
1208 MBB.addLiveIn(Reg);
1209 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1210 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
1211 RC, TRI);
1212 }
1213
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001214 return true;
1215}
1216
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001217bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001218 MachineBasicBlock::iterator MI,
1219 const std::vector<CalleeSavedInfo> &CSI,
1220 const TargetRegisterInfo *TRI) const {
1221 if (CSI.empty())
1222 return false;
1223
1224 DebugLoc DL = MBB.findDebugLoc(MI);
1225
1226 MachineFunction &MF = *MBB.getParent();
1227 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001228
1229 // Reload XMMs from stack frame.
1230 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1231 unsigned Reg = CSI[i].getReg();
1232 if (X86::GR64RegClass.contains(Reg) ||
1233 X86::GR32RegClass.contains(Reg))
1234 continue;
1235 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1236 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
1237 RC, TRI);
1238 }
1239
1240 // POP GPRs.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001241 unsigned FPReg = TRI->getFrameRegister(MF);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001242 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1243 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1244 unsigned Reg = CSI[i].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001245 if (!X86::GR64RegClass.contains(Reg) &&
1246 !X86::GR32RegClass.contains(Reg))
1247 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001248 if (Reg == FPReg)
1249 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
1250 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001251 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001252 }
1253 return true;
1254}
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001255
1256void
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001257X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001258 RegScavenger *RS) const {
1259 MachineFrameInfo *MFI = MF.getFrameInfo();
1260 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
1261 unsigned SlotSize = RegInfo->getSlotSize();
1262
1263 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1264 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1265
1266 if (TailCallReturnAddrDelta < 0) {
1267 // create RETURNADDR area
1268 // arg
1269 // arg
1270 // RETADDR
1271 // { ...
1272 // RETADDR area
1273 // ...
1274 // }
1275 // [EBP]
1276 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1277 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1278 }
1279
1280 if (hasFP(MF)) {
1281 assert((TailCallReturnAddrDelta <= 0) &&
1282 "The Delta should always be zero or negative");
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001283 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001284
1285 // Create a frame entry for the EBP register that must be saved.
1286 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1287 -(int)SlotSize +
1288 TFI.getOffsetOfLocalArea() +
1289 TailCallReturnAddrDelta,
1290 true);
1291 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1292 "Slot for EBP register must be last in order to be found!");
Duncan Sands17001ce2011-10-18 12:44:00 +00001293 (void)FrameIdx;
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001294 }
1295}
Rafael Espindola76927d752011-08-30 19:39:58 +00001296
1297static bool
1298HasNestArgument(const MachineFunction *MF) {
1299 const Function *F = MF->getFunction();
1300 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1301 I != E; I++) {
1302 if (I->hasNestAttr())
1303 return true;
1304 }
1305 return false;
1306}
1307
Rafael Espindola2028b792012-01-11 19:00:37 +00001308
1309/// GetScratchRegister - Get a register for performing work in the segmented
1310/// stack prologue. Depending on platform and the properties of the function
1311/// either one or two registers will be needed. Set primary to true for
1312/// the first register, false for the second.
Rafael Espindola76927d752011-08-30 19:39:58 +00001313static unsigned
Rafael Espindola2028b792012-01-11 19:00:37 +00001314GetScratchRegister(bool Is64Bit, const MachineFunction &MF, bool Primary) {
Rafael Espindola76927d752011-08-30 19:39:58 +00001315 if (Is64Bit) {
Rafael Espindola2028b792012-01-11 19:00:37 +00001316 return Primary ? X86::R11 : X86::R12;
Rafael Espindola76927d752011-08-30 19:39:58 +00001317 } else {
1318 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1319 bool IsNested = HasNestArgument(&MF);
1320
Rafael Espindola25cd4ff2012-01-11 18:41:19 +00001321 if (CallingConvention == CallingConv::X86_FastCall ||
1322 CallingConvention == CallingConv::Fast) {
Rafael Espindola76927d752011-08-30 19:39:58 +00001323 if (IsNested) {
Rafael Espindolae81abfd2011-08-31 16:43:33 +00001324 report_fatal_error("Segmented stacks does not support fastcall with "
1325 "nested function.");
Rafael Espindola76927d752011-08-30 19:39:58 +00001326 return -1;
1327 } else {
Rafael Espindola2028b792012-01-11 19:00:37 +00001328 return Primary ? X86::EAX : X86::ECX;
Rafael Espindola76927d752011-08-30 19:39:58 +00001329 }
1330 } else {
1331 if (IsNested)
Rafael Espindola2028b792012-01-11 19:00:37 +00001332 return Primary ? X86::EDX : X86::EAX;
Rafael Espindola76927d752011-08-30 19:39:58 +00001333 else
Rafael Espindola2028b792012-01-11 19:00:37 +00001334 return Primary ? X86::ECX : X86::EAX;
Rafael Espindola76927d752011-08-30 19:39:58 +00001335 }
1336 }
1337}
1338
Sanjoy Das199ce332011-12-03 09:32:07 +00001339// The stack limit in the TCB is set to this many bytes above the actual stack
1340// limit.
1341static const uint64_t kSplitStackAvailable = 256;
1342
Rafael Espindola76927d752011-08-30 19:39:58 +00001343void
1344X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1345 MachineBasicBlock &prologueMBB = MF.front();
1346 MachineFrameInfo *MFI = MF.getFrameInfo();
1347 const X86InstrInfo &TII = *TM.getInstrInfo();
1348 uint64_t StackSize;
1349 bool Is64Bit = STI.is64Bit();
1350 unsigned TlsReg, TlsOffset;
1351 DebugLoc DL;
1352 const X86Subtarget *ST = &MF.getTarget().getSubtarget<X86Subtarget>();
1353
Rafael Espindola2028b792012-01-11 19:00:37 +00001354 unsigned ScratchReg = GetScratchRegister(Is64Bit, MF, true);
Rafael Espindola76927d752011-08-30 19:39:58 +00001355 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1356 "Scratch register is live-in");
1357
1358 if (MF.getFunction()->isVarArg())
1359 report_fatal_error("Segmented stacks do not support vararg functions.");
Rafael Espindola85b9d432012-01-12 20:24:30 +00001360 if (!ST->isTargetLinux() && !ST->isTargetDarwin() &&
1361 !ST->isTargetWin32() && !ST->isTargetFreeBSD())
1362 report_fatal_error("Segmented stacks not supported on this platform.");
Rafael Espindola76927d752011-08-30 19:39:58 +00001363
1364 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1365 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1366 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1367 bool IsNested = false;
1368
1369 // We need to know if the function has a nest argument only in 64 bit mode.
1370 if (Is64Bit)
1371 IsNested = HasNestArgument(&MF);
1372
Bill Wendling4e680542011-10-13 08:24:19 +00001373 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1374 // allocMBB needs to be last (terminating) instruction.
Bill Wendling4e680542011-10-13 08:24:19 +00001375
Rafael Espindola76927d752011-08-30 19:39:58 +00001376 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1377 e = prologueMBB.livein_end(); i != e; i++) {
1378 allocMBB->addLiveIn(*i);
1379 checkMBB->addLiveIn(*i);
1380 }
1381
1382 if (IsNested)
Rafael Espindolae840e882011-10-26 21:12:27 +00001383 allocMBB->addLiveIn(X86::R10);
1384
Rafael Espindola76927d752011-08-30 19:39:58 +00001385 MF.push_front(allocMBB);
1386 MF.push_front(checkMBB);
1387
1388 // Eventually StackSize will be calculated by a link-time pass; which will
1389 // also decide whether checking code needs to be injected into this particular
1390 // prologue.
1391 StackSize = MFI->getStackSize();
1392
Rafael Espindola2028b792012-01-11 19:00:37 +00001393 // When the frame size is less than 256 we just compare the stack
1394 // boundary directly to the value of the stack pointer, per gcc.
1395 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1396
Rafael Espindola76927d752011-08-30 19:39:58 +00001397 // Read the limit off the current stacklet off the stack_guard location.
1398 if (Is64Bit) {
Rafael Espindola2028b792012-01-11 19:00:37 +00001399 if (ST->isTargetLinux()) {
1400 TlsReg = X86::FS;
1401 TlsOffset = 0x70;
1402 } else if (ST->isTargetDarwin()) {
1403 TlsReg = X86::GS;
1404 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
Rafael Espindola85b9d432012-01-12 20:24:30 +00001405 } else if (ST->isTargetFreeBSD()) {
1406 TlsReg = X86::FS;
1407 TlsOffset = 0x18;
Rafael Espindolae4d18de2012-01-12 20:22:08 +00001408 } else {
1409 report_fatal_error("Segmented stacks not supported on this platform.");
Rafael Espindola2028b792012-01-11 19:00:37 +00001410 }
Rafael Espindola76927d752011-08-30 19:39:58 +00001411
Rafael Espindola2028b792012-01-11 19:00:37 +00001412 if (CompareStackPointer)
Sanjoy Das199ce332011-12-03 09:32:07 +00001413 ScratchReg = X86::RSP;
1414 else
1415 BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RSP)
Rafael Espindola014f7a32012-01-11 18:14:03 +00001416 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
Sanjoy Das199ce332011-12-03 09:32:07 +00001417
Rafael Espindola76927d752011-08-30 19:39:58 +00001418 BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
Rafael Espindola014f7a32012-01-11 18:14:03 +00001419 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
Rafael Espindola76927d752011-08-30 19:39:58 +00001420 } else {
Rafael Espindolae4d18de2012-01-12 20:22:08 +00001421 if (ST->isTargetLinux()) {
1422 TlsReg = X86::GS;
1423 TlsOffset = 0x30;
1424 } else if (ST->isTargetDarwin()) {
1425 TlsReg = X86::GS;
1426 TlsOffset = 0x48 + 90*4;
1427 } else if (ST->isTargetWin32()) {
1428 TlsReg = X86::FS;
1429 TlsOffset = 0x14; // pvArbitrary, reserved for application use
Rafael Espindola85b9d432012-01-12 20:24:30 +00001430 } else if (ST->isTargetFreeBSD()) {
1431 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
Rafael Espindolae4d18de2012-01-12 20:22:08 +00001432 } else {
1433 report_fatal_error("Segmented stacks not supported on this platform.");
1434 }
Rafael Espindola76927d752011-08-30 19:39:58 +00001435
Rafael Espindola2028b792012-01-11 19:00:37 +00001436 if (CompareStackPointer)
Sanjoy Das199ce332011-12-03 09:32:07 +00001437 ScratchReg = X86::ESP;
1438 else
1439 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
Rafael Espindola014f7a32012-01-11 18:14:03 +00001440 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
Sanjoy Das199ce332011-12-03 09:32:07 +00001441
Rafael Espindolae4d18de2012-01-12 20:22:08 +00001442 if (ST->isTargetLinux() || ST->isTargetWin32()) {
Rafael Espindola2028b792012-01-11 19:00:37 +00001443 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1444 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1445 } else if (ST->isTargetDarwin()) {
Rafael Espindola2028b792012-01-11 19:00:37 +00001446
1447 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register
1448 unsigned ScratchReg2;
1449 bool SaveScratch2;
1450 if (CompareStackPointer) {
1451 // The primary scratch register is available for holding the TLS offset
1452 ScratchReg2 = GetScratchRegister(Is64Bit, MF, true);
1453 SaveScratch2 = false;
1454 } else {
1455 // Need to use a second register to hold the TLS offset
1456 ScratchReg2 = GetScratchRegister(Is64Bit, MF, false);
1457
1458 // Unfortunately, with fastcc the second scratch register may hold an arg
1459 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1460 }
1461
1462 // If Scratch2 is live-in then it needs to be saved
1463 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1464 "Scratch register is live-in and not saved");
1465
1466 if (SaveScratch2)
1467 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1468 .addReg(ScratchReg2, RegState::Kill);
1469
1470 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1471 .addImm(TlsOffset);
1472 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1473 .addReg(ScratchReg)
1474 .addReg(ScratchReg2).addImm(1).addReg(0)
1475 .addImm(0)
1476 .addReg(TlsReg);
1477
1478 if (SaveScratch2)
1479 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1480 }
Rafael Espindola76927d752011-08-30 19:39:58 +00001481 }
1482
1483 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1484 // It jumps to normal execution of the function body.
Rafael Espindola313c7032012-01-11 18:23:35 +00001485 BuildMI(checkMBB, DL, TII.get(X86::JA_4)).addMBB(&prologueMBB);
Rafael Espindola76927d752011-08-30 19:39:58 +00001486
1487 // On 32 bit we first push the arguments size and then the frame size. On 64
1488 // bit, we pass the stack frame size in r10 and the argument size in r11.
1489 if (Is64Bit) {
1490 // Functions with nested arguments use R10, so it needs to be saved across
1491 // the call to _morestack
1492
1493 if (IsNested)
1494 BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::RAX).addReg(X86::R10);
1495
1496 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R10)
1497 .addImm(StackSize);
1498 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R11)
1499 .addImm(X86FI->getArgumentStackSize());
1500 MF.getRegInfo().setPhysRegUsed(X86::R10);
1501 MF.getRegInfo().setPhysRegUsed(X86::R11);
1502 } else {
Rafael Espindola76927d752011-08-30 19:39:58 +00001503 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1504 .addImm(X86FI->getArgumentStackSize());
1505 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1506 .addImm(StackSize);
1507 }
1508
1509 // __morestack is in libgcc
1510 if (Is64Bit)
1511 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1512 .addExternalSymbol("__morestack");
1513 else
1514 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1515 .addExternalSymbol("__morestack");
1516
Bill Wendling4e680542011-10-13 08:24:19 +00001517 if (IsNested)
Rafael Espindolae840e882011-10-26 21:12:27 +00001518 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1519 else
1520 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
Bill Wendling4e680542011-10-13 08:24:19 +00001521
Rafael Espindolae840e882011-10-26 21:12:27 +00001522 allocMBB->addSuccessor(&prologueMBB);
Bill Wendling4e680542011-10-13 08:24:19 +00001523
Rafael Espindola76927d752011-08-30 19:39:58 +00001524 checkMBB->addSuccessor(allocMBB);
1525 checkMBB->addSuccessor(&prologueMBB);
1526
Jakob Stoklund Olesen51f0c762011-09-24 01:11:19 +00001527#ifdef XDEBUG
Rafael Espindola76927d752011-08-30 19:39:58 +00001528 MF.verify();
1529#endif
1530}