blob: 19486f871f0c7b3d33b190eefdaa8e897c4edb80 [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
Bill Wendlingd199aa02011-09-02 18:15:04 +000038// FIXME: Remove once linker support is available. The feature exists only on
39// Darwin at the moment.
40static cl::opt<bool>
41GenerateCompactUnwind("gen-compact-unwind",
42 cl::desc("Generate compact unwind encoding"),
43 cl::Hidden);
44
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000045bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000046 return !MF.getFrameInfo()->hasVarSizedObjects();
47}
48
49/// hasFP - Return true if the specified function should have a dedicated frame
50/// pointer register. This is true if the function has variable sized allocas
51/// or if frame pointer elimination is disabled.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000052bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000053 const MachineFrameInfo *MFI = MF.getFrameInfo();
54 const MachineModuleInfo &MMI = MF.getMMI();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +000055 const TargetRegisterInfo *RI = TM.getRegisterInfo();
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000056
57 return (DisableFramePointerElim(MF) ||
58 RI->needsStackRealignment(MF) ||
59 MFI->hasVarSizedObjects() ||
60 MFI->isFrameAddressTaken() ||
61 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
62 MMI.callsUnwindInit());
63}
64
Anton Korobeynikov33464912010-11-15 00:06:54 +000065static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
66 if (is64Bit) {
67 if (isInt<8>(Imm))
68 return X86::SUB64ri8;
69 return X86::SUB64ri32;
70 } else {
71 if (isInt<8>(Imm))
72 return X86::SUB32ri8;
73 return X86::SUB32ri;
74 }
75}
76
77static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
78 if (is64Bit) {
79 if (isInt<8>(Imm))
80 return X86::ADD64ri8;
81 return X86::ADD64ri32;
82 } else {
83 if (isInt<8>(Imm))
84 return X86::ADD32ri8;
85 return X86::ADD32ri;
86 }
87}
88
Evan Cheng7158e082011-01-03 22:53:22 +000089/// findDeadCallerSavedReg - Return a caller-saved register that isn't live
90/// when it reaches the "return" instruction. We can then pop a stack object
91/// to this register without worry about clobbering it.
92static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
93 MachineBasicBlock::iterator &MBBI,
94 const TargetRegisterInfo &TRI,
95 bool Is64Bit) {
96 const MachineFunction *MF = MBB.getParent();
97 const Function *F = MF->getFunction();
98 if (!F || MF->getMMI().callsEHReturn())
99 return 0;
100
101 static const unsigned CallerSavedRegs32Bit[] = {
Andrew Trick32a183c2011-08-12 00:49:19 +0000102 X86::EAX, X86::EDX, X86::ECX, 0
Evan Cheng7158e082011-01-03 22:53:22 +0000103 };
104
105 static const unsigned CallerSavedRegs64Bit[] = {
106 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
Andrew Trick32a183c2011-08-12 00:49:19 +0000107 X86::R8, X86::R9, X86::R10, X86::R11, 0
Evan Cheng7158e082011-01-03 22:53:22 +0000108 };
109
110 unsigned Opc = MBBI->getOpcode();
111 switch (Opc) {
112 default: return 0;
113 case X86::RET:
114 case X86::RETI:
115 case X86::TCRETURNdi:
116 case X86::TCRETURNri:
117 case X86::TCRETURNmi:
118 case X86::TCRETURNdi64:
119 case X86::TCRETURNri64:
120 case X86::TCRETURNmi64:
121 case X86::EH_RETURN:
122 case X86::EH_RETURN64: {
123 SmallSet<unsigned, 8> Uses;
124 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
125 MachineOperand &MO = MBBI->getOperand(i);
126 if (!MO.isReg() || MO.isDef())
127 continue;
128 unsigned Reg = MO.getReg();
129 if (!Reg)
130 continue;
131 for (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
132 Uses.insert(*AsI);
133 }
134
135 const unsigned *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
136 for (; *CS; ++CS)
137 if (!Uses.count(*CS))
138 return *CS;
139 }
140 }
141
142 return 0;
143}
144
145
Anton Korobeynikov33464912010-11-15 00:06:54 +0000146/// emitSPUpdate - Emit a series of instructions to increment / decrement the
147/// stack pointer by a constant value.
148static
149void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
Evan Cheng7158e082011-01-03 22:53:22 +0000150 unsigned StackPtr, int64_t NumBytes,
151 bool Is64Bit, const TargetInstrInfo &TII,
152 const TargetRegisterInfo &TRI) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000153 bool isSub = NumBytes < 0;
154 uint64_t Offset = isSub ? -NumBytes : NumBytes;
155 unsigned Opc = isSub ?
156 getSUBriOpcode(Is64Bit, Offset) :
157 getADDriOpcode(Is64Bit, Offset);
158 uint64_t Chunk = (1LL << 31) - 1;
159 DebugLoc DL = MBB.findDebugLoc(MBBI);
160
161 while (Offset) {
162 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
Evan Cheng7158e082011-01-03 22:53:22 +0000163 if (ThisVal == (Is64Bit ? 8 : 4)) {
164 // Use push / pop instead.
165 unsigned Reg = isSub
Dale Johannesen1e08cd12011-01-04 19:31:24 +0000166 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
Evan Cheng7158e082011-01-03 22:53:22 +0000167 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
168 if (Reg) {
169 Opc = isSub
170 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
171 : (Is64Bit ? X86::POP64r : X86::POP32r);
Charles Davisaff232a2011-06-12 01:45:54 +0000172 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
Evan Cheng7158e082011-01-03 22:53:22 +0000173 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
Charles Davisaff232a2011-06-12 01:45:54 +0000174 if (isSub)
175 MI->setFlag(MachineInstr::FrameSetup);
Evan Cheng7158e082011-01-03 22:53:22 +0000176 Offset -= ThisVal;
177 continue;
178 }
179 }
180
Anton Korobeynikov33464912010-11-15 00:06:54 +0000181 MachineInstr *MI =
182 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
Evan Cheng7158e082011-01-03 22:53:22 +0000183 .addReg(StackPtr)
184 .addImm(ThisVal);
Charles Davisaff232a2011-06-12 01:45:54 +0000185 if (isSub)
186 MI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000187 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
188 Offset -= ThisVal;
189 }
190}
191
192/// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
193static
194void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
195 unsigned StackPtr, uint64_t *NumBytes = NULL) {
196 if (MBBI == MBB.begin()) return;
197
198 MachineBasicBlock::iterator PI = prior(MBBI);
199 unsigned Opc = PI->getOpcode();
200 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
201 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
202 PI->getOperand(0).getReg() == StackPtr) {
203 if (NumBytes)
204 *NumBytes += PI->getOperand(2).getImm();
205 MBB.erase(PI);
206 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
207 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
208 PI->getOperand(0).getReg() == StackPtr) {
209 if (NumBytes)
210 *NumBytes -= PI->getOperand(2).getImm();
211 MBB.erase(PI);
212 }
213}
214
215/// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
216static
217void mergeSPUpdatesDown(MachineBasicBlock &MBB,
218 MachineBasicBlock::iterator &MBBI,
219 unsigned StackPtr, uint64_t *NumBytes = NULL) {
220 // FIXME: THIS ISN'T RUN!!!
221 return;
222
223 if (MBBI == MBB.end()) return;
224
225 MachineBasicBlock::iterator NI = llvm::next(MBBI);
226 if (NI == MBB.end()) return;
227
228 unsigned Opc = NI->getOpcode();
229 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
230 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
231 NI->getOperand(0).getReg() == StackPtr) {
232 if (NumBytes)
233 *NumBytes -= NI->getOperand(2).getImm();
234 MBB.erase(NI);
235 MBBI = NI;
236 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
237 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
238 NI->getOperand(0).getReg() == StackPtr) {
239 if (NumBytes)
240 *NumBytes += NI->getOperand(2).getImm();
241 MBB.erase(NI);
242 MBBI = NI;
243 }
244}
245
246/// mergeSPUpdates - Checks the instruction before/after the passed
247/// instruction. If it is an ADD/SUB instruction it is deleted argument and the
248/// stack adjustment is returned as a positive value for ADD and a negative for
249/// SUB.
250static int mergeSPUpdates(MachineBasicBlock &MBB,
251 MachineBasicBlock::iterator &MBBI,
252 unsigned StackPtr,
253 bool doMergeWithPrevious) {
254 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
255 (!doMergeWithPrevious && MBBI == MBB.end()))
256 return 0;
257
258 MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
259 MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
260 unsigned Opc = PI->getOpcode();
261 int Offset = 0;
262
263 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
264 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
265 PI->getOperand(0).getReg() == StackPtr){
266 Offset += PI->getOperand(2).getImm();
267 MBB.erase(PI);
268 if (!doMergeWithPrevious) MBBI = NI;
269 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
270 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
271 PI->getOperand(0).getReg() == StackPtr) {
272 Offset -= PI->getOperand(2).getImm();
273 MBB.erase(PI);
274 if (!doMergeWithPrevious) MBBI = NI;
275 }
276
277 return Offset;
278}
279
280static bool isEAXLiveIn(MachineFunction &MF) {
281 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
282 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
283 unsigned Reg = II->first;
284
285 if (Reg == X86::EAX || Reg == X86::AX ||
286 Reg == X86::AH || Reg == X86::AL)
287 return true;
288 }
289
290 return false;
291}
292
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000293void X86FrameLowering::emitCalleeSavedFrameMoves(MachineFunction &MF,
Bill Wendling09b02c82011-07-25 18:00:28 +0000294 MCSymbol *Label,
295 unsigned FramePtr) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000296 MachineFrameInfo *MFI = MF.getFrameInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000297 MachineModuleInfo &MMI = MF.getMMI();
298
299 // Add callee saved registers to move list.
300 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
301 if (CSI.empty()) return;
302
303 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000304 const TargetData *TD = TM.getTargetData();
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000305 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000306
307 // Calculate amount of bytes used for return address storing.
Anton Korobeynikove7499112011-01-14 21:57:58 +0000308 int stackGrowth = -TD->getPointerSize();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000309
310 // FIXME: This is dirty hack. The code itself is pretty mess right now.
311 // It should be rewritten from scratch and generalized sometimes.
312
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000313 // Determine maximum offset (minimum due to stack growth).
Anton Korobeynikov33464912010-11-15 00:06:54 +0000314 int64_t MaxOffset = 0;
315 for (std::vector<CalleeSavedInfo>::const_iterator
316 I = CSI.begin(), E = CSI.end(); I != E; ++I)
317 MaxOffset = std::min(MaxOffset,
318 MFI->getObjectOffset(I->getFrameIdx()));
319
320 // Calculate offsets.
321 int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
322 for (std::vector<CalleeSavedInfo>::const_iterator
323 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
324 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
325 unsigned Reg = I->getReg();
326 Offset = MaxOffset - Offset + saveAreaOffset;
327
328 // Don't output a new machine move if we're re-saving the frame
329 // pointer. This happens when the PrologEpilogInserter has inserted an extra
330 // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
331 // generates one when frame pointers are used. If we generate a "machine
332 // move" for this extra "PUSH", the linker will lose track of the fact that
333 // the frame pointer should have the value of the first "PUSH" when it's
334 // trying to unwind.
NAKAMURA Takumi27635382011-02-05 15:10:54 +0000335 //
Anton Korobeynikov33464912010-11-15 00:06:54 +0000336 // FIXME: This looks inelegant. It's possibly correct, but it's covering up
337 // another bug. I.e., one where we generate a prolog like this:
338 //
339 // pushl %ebp
340 // movl %esp, %ebp
341 // pushl %ebp
342 // pushl %esi
343 // ...
344 //
345 // The immediate re-push of EBP is unnecessary. At the least, it's an
346 // optimization bug. EBP can be used as a scratch register in certain
347 // cases, but probably not when we have a frame pointer.
348 if (HasFP && FramePtr == Reg)
349 continue;
350
351 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
352 MachineLocation CSSrc(Reg);
353 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
354 }
355}
356
Bill Wendling09b02c82011-07-25 18:00:28 +0000357/// getCompactUnwindRegNum - Get the compact unwind number for a given
358/// register. The number corresponds to the enum lists in
359/// compact_unwind_encoding.h.
360static int getCompactUnwindRegNum(const unsigned *CURegs, unsigned Reg) {
361 int Idx = 1;
362 for (; *CURegs; ++CURegs, ++Idx)
363 if (*CURegs == Reg)
364 return Idx;
365
366 return -1;
367}
368
369/// encodeCompactUnwindRegistersWithoutFrame - Create the permutation encoding
370/// used with frameless stacks. It is passed the number of registers to be saved
371/// and an array of the registers saved.
372static uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned SavedRegs[6],
373 unsigned RegCount,
374 bool Is64Bit) {
375 // The saved registers are numbered from 1 to 6. In order to encode the order
376 // in which they were saved, we re-number them according to their place in the
377 // register order. The re-numbering is relative to the last re-numbered
378 // register. E.g., if we have registers {6, 2, 4, 5} saved in that order:
379 //
380 // Orig Re-Num
381 // ---- ------
382 // 6 6
383 // 2 2
384 // 4 3
385 // 5 3
386 //
387 static const unsigned CU32BitRegs[] = {
388 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
389 };
390 static const unsigned CU64BitRegs[] = {
391 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
392 };
393 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
394
395 uint32_t RenumRegs[6];
396 for (unsigned i = 6 - RegCount; i < 6; ++i) {
397 int CUReg = getCompactUnwindRegNum(CURegs, SavedRegs[i]);
398 if (CUReg == -1) return ~0U;
399 SavedRegs[i] = CUReg;
400
401 unsigned Countless = 0;
402 for (unsigned j = 6 - RegCount; j < i; ++j)
403 if (SavedRegs[j] < SavedRegs[i])
404 ++Countless;
405
406 RenumRegs[i] = SavedRegs[i] - Countless - 1;
407 }
408
409 // Take the renumbered values and encode them into a 10-bit number.
410 uint32_t permutationEncoding = 0;
411 switch (RegCount) {
412 case 6:
413 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
414 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
415 + RenumRegs[4];
416 break;
417 case 5:
418 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
419 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
420 + RenumRegs[5];
421 break;
422 case 4:
423 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
424 + 3 * RenumRegs[4] + RenumRegs[5];
425 break;
426 case 3:
427 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
428 + RenumRegs[5];
429 break;
430 case 2:
431 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
432 break;
433 case 1:
434 permutationEncoding |= RenumRegs[5];
435 break;
436 }
437
438 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
439 "Invalid compact register encoding!");
440 return permutationEncoding;
441}
442
443/// encodeCompactUnwindRegistersWithFrame - Return the registers encoded for a
444/// compact encoding with a frame pointer.
445static uint32_t encodeCompactUnwindRegistersWithFrame(unsigned SavedRegs[6],
446 bool Is64Bit) {
447 static const unsigned CU32BitRegs[] = {
448 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
449 };
450 static const unsigned CU64BitRegs[] = {
451 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
452 };
453 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
454
455 // Encode the registers in the order they were saved, 3-bits per register. The
456 // registers are numbered from 1 to 6.
457 uint32_t RegEnc = 0;
458 for (int I = 5; I >= 0; --I) {
459 unsigned Reg = SavedRegs[I];
460 if (Reg == 0) break;
461 int CURegNum = getCompactUnwindRegNum(CURegs, Reg);
462 if (CURegNum == -1)
463 return ~0U;
464 RegEnc |= (CURegNum & 0x7) << (5 - I);
465 }
466
467 assert((RegEnc & 0x7FFF) == RegEnc && "Invalid compact register encoding!");
468 return RegEnc;
469}
470
471uint32_t X86FrameLowering::getCompactUnwindEncoding(MachineFunction &MF) const {
472 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
473 unsigned FramePtr = RegInfo->getFrameRegister(MF);
474 unsigned StackPtr = RegInfo->getStackRegister();
475
476 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
477 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
478
479 bool Is64Bit = STI.is64Bit();
480 bool HasFP = hasFP(MF);
481
482 unsigned SavedRegs[6] = { 0, 0, 0, 0, 0, 0 };
483 int SavedRegIdx = 6;
484
485 unsigned OffsetSize = (Is64Bit ? 8 : 4);
486
487 unsigned PushInstr = (Is64Bit ? X86::PUSH64r : X86::PUSH32r);
488 unsigned PushInstrSize = 1;
489 unsigned MoveInstr = (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
490 unsigned MoveInstrSize = (Is64Bit ? 3 : 2);
491 unsigned SubtractInstr = getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta);
492 unsigned SubtractInstrIdx = (Is64Bit ? 3 : 2);
493
Bill Wendlingde770552011-07-26 08:03:49 +0000494 unsigned StackDivide = (Is64Bit ? 8 : 4);
495
Bill Wendling09b02c82011-07-25 18:00:28 +0000496 unsigned InstrOffset = 0;
497 unsigned CFAOffset = 0;
498 unsigned StackAdjust = 0;
499
500 MachineBasicBlock &MBB = MF.front(); // Prologue is in entry BB.
501 bool ExpectEnd = false;
502 for (MachineBasicBlock::iterator
503 MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ++MBBI) {
504 MachineInstr &MI = *MBBI;
505 unsigned Opc = MI.getOpcode();
506 if (Opc == X86::PROLOG_LABEL) continue;
507 if (!MI.getFlag(MachineInstr::FrameSetup)) break;
508
509 // We don't exect any more prolog instructions.
510 if (ExpectEnd) return 0;
511
512 if (Opc == PushInstr) {
513 // If there are too many saved registers, we cannot use compact encoding.
514 if (--SavedRegIdx < 0) return 0;
515
516 SavedRegs[SavedRegIdx] = MI.getOperand(0).getReg();
517 CFAOffset += OffsetSize;
518 InstrOffset += PushInstrSize;
519 } else if (Opc == MoveInstr) {
520 unsigned SrcReg = MI.getOperand(1).getReg();
521 unsigned DstReg = MI.getOperand(0).getReg();
522
523 if (DstReg != FramePtr || SrcReg != StackPtr)
524 return 0;
525
526 CFAOffset = 0;
527 memset(SavedRegs, 0, sizeof(SavedRegs));
528 InstrOffset += MoveInstrSize;
529 } else if (Opc == SubtractInstr) {
530 if (StackAdjust)
531 // We all ready have a stack pointer adjustment.
532 return 0;
533
534 if (!MI.getOperand(0).isReg() ||
535 MI.getOperand(0).getReg() != MI.getOperand(1).getReg() ||
536 MI.getOperand(0).getReg() != StackPtr || !MI.getOperand(2).isImm())
537 // We need this to be a stack adjustment pointer. Something like:
538 //
539 // %RSP<def> = SUB64ri8 %RSP, 48
540 return 0;
541
Bill Wendlingde770552011-07-26 08:03:49 +0000542 StackAdjust = MI.getOperand(2).getImm() / StackDivide;
Bill Wendling09b02c82011-07-25 18:00:28 +0000543 SubtractInstrIdx += InstrOffset;
544 ExpectEnd = true;
545 }
546 }
547
548 // Encode that we are using EBP/RBP as the frame pointer.
549 uint32_t CompactUnwindEncoding = 0;
Bill Wendlingde770552011-07-26 08:03:49 +0000550 CFAOffset /= StackDivide;
Bill Wendling09b02c82011-07-25 18:00:28 +0000551 if (HasFP) {
552 if ((CFAOffset & 0xFF) != CFAOffset)
553 // Offset was too big for compact encoding.
554 return 0;
555
556 // Get the encoding of the saved registers when we have a frame pointer.
557 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame(SavedRegs, Is64Bit);
558 if (RegEnc == ~0U)
559 return 0;
560
561 CompactUnwindEncoding |= 0x01000000;
562 CompactUnwindEncoding |= (CFAOffset & 0xFF) << 16;
563 CompactUnwindEncoding |= RegEnc & 0x7FFF;
564 } else {
565 unsigned FullOffset = CFAOffset + StackAdjust;
566 if ((FullOffset & 0xFF) == FullOffset) {
567 // Frameless stack.
568 CompactUnwindEncoding |= 0x02000000;
569 CompactUnwindEncoding |= (FullOffset & 0xFF) << 16;
570 } else {
571 if ((CFAOffset & 0x7) != CFAOffset)
572 // The extra stack adjustments are too big for us to handle.
573 return 0;
574
575 // Frameless stack with an offset too large for us to encode compactly.
576 CompactUnwindEncoding |= 0x03000000;
577
578 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
579 // instruction.
580 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
581
582 // Encode any extra stack stack changes (done via push instructions).
583 CompactUnwindEncoding |= (CFAOffset & 0x7) << 13;
584 }
585
586 // Get the encoding of the saved registers when we don't have a frame
587 // pointer.
588 uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegs,
589 6 - SavedRegIdx,
590 Is64Bit);
591 if (RegEnc == ~0U) return 0;
592 CompactUnwindEncoding |= RegEnc & 0x3FF;
593 }
594
595 return CompactUnwindEncoding;
596}
597
Anton Korobeynikov33464912010-11-15 00:06:54 +0000598/// emitPrologue - Push callee-saved registers onto the stack, which
599/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
600/// space for local variables. Also emit labels used by the exception handler to
601/// generate the exception handling frames.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000602void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000603 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
604 MachineBasicBlock::iterator MBBI = MBB.begin();
605 MachineFrameInfo *MFI = MF.getFrameInfo();
606 const Function *Fn = MF.getFunction();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000607 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
608 const X86InstrInfo &TII = *TM.getInstrInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000609 MachineModuleInfo &MMI = MF.getMMI();
610 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
611 bool needsFrameMoves = MMI.hasDebugInfo() ||
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000612 Fn->needsUnwindTableEntry();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000613 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
614 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000615 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000616 bool Is64Bit = STI.is64Bit();
617 bool IsWin64 = STI.isTargetWin64();
618 unsigned StackAlign = getStackAlignment();
619 unsigned SlotSize = RegInfo->getSlotSize();
620 unsigned FramePtr = RegInfo->getFrameRegister(MF);
621 unsigned StackPtr = RegInfo->getStackRegister();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000622 DebugLoc DL;
623
624 // If we're forcing a stack realignment we can't rely on just the frame
625 // info, we need to know the ABI stack alignment as well in case we
626 // have a call out. Otherwise just make sure we have some alignment - we'll
627 // go with the minimum SlotSize.
628 if (ForceStackAlign) {
629 if (MFI->hasCalls())
630 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
631 else if (MaxAlign < SlotSize)
632 MaxAlign = SlotSize;
633 }
634
635 // Add RETADDR move area to callee saved frame size.
636 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
637 if (TailCallReturnAddrDelta < 0)
638 X86FI->setCalleeSavedFrameSize(
639 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
640
641 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
642 // function, and use up to 128 bytes of stack space, don't have a frame
643 // pointer, calls, or dynamic alloca then we do not need to adjust the
644 // stack pointer (we fit in the Red Zone).
645 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
646 !RegInfo->needsStackRealignment(MF) &&
647 !MFI->hasVarSizedObjects() && // No dynamic alloca.
648 !MFI->adjustsStack() && // No calls.
Rafael Espindola76927d752011-08-30 19:39:58 +0000649 !IsWin64 && // Win64 has no Red Zone
650 !EnableSegmentedStacks) { // Regular stack
Anton Korobeynikov33464912010-11-15 00:06:54 +0000651 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
652 if (HasFP) MinSize += SlotSize;
653 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
654 MFI->setStackSize(StackSize);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000655 }
656
657 // Insert stack pointer adjustment for later moving of return addr. Only
658 // applies to tail call optimized functions where the callee argument stack
659 // size is bigger than the callers.
660 if (TailCallReturnAddrDelta < 0) {
661 MachineInstr *MI =
662 BuildMI(MBB, MBBI, DL,
663 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
664 StackPtr)
665 .addReg(StackPtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000666 .addImm(-TailCallReturnAddrDelta)
667 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000668 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
669 }
670
671 // Mapping for machine moves:
672 //
673 // DST: VirtualFP AND
674 // SRC: VirtualFP => DW_CFA_def_cfa_offset
675 // ELSE => DW_CFA_def_cfa
676 //
677 // SRC: VirtualFP AND
678 // DST: Register => DW_CFA_def_cfa_register
679 //
680 // ELSE
681 // OFFSET < 0 => DW_CFA_offset_extended_sf
682 // REG < 64 => DW_CFA_offset + Reg
683 // ELSE => DW_CFA_offset_extended
684
685 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
686 const TargetData *TD = MF.getTarget().getTargetData();
687 uint64_t NumBytes = 0;
688 int stackGrowth = -TD->getPointerSize();
689
690 if (HasFP) {
691 // Calculate required stack adjustment.
692 uint64_t FrameSize = StackSize - SlotSize;
693 if (RegInfo->needsStackRealignment(MF))
694 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
695
696 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
697
698 // Get the offset of the stack slot for the EBP register, which is
699 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
700 // Update the frame offset adjustment.
701 MFI->setOffsetAdjustment(-NumBytes);
702
703 // Save EBP/RBP into the appropriate stack slot.
704 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
Charles Davisaff232a2011-06-12 01:45:54 +0000705 .addReg(FramePtr, RegState::Kill)
706 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000707
708 if (needsFrameMoves) {
709 // Mark the place where EBP/RBP was saved.
710 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000711 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
712 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000713
714 // Define the current CFA rule to use the provided offset.
715 if (StackSize) {
716 MachineLocation SPDst(MachineLocation::VirtualFP);
717 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
718 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
719 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000720 MachineLocation SPDst(StackPtr);
721 MachineLocation SPSrc(StackPtr, stackGrowth);
722 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
723 }
724
725 // Change the rule for the FramePtr to be an "offset" rule.
726 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
727 MachineLocation FPSrc(FramePtr);
728 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
729 }
730
Bill Wendling09b02c82011-07-25 18:00:28 +0000731 // Update EBP with the new base value.
Anton Korobeynikov33464912010-11-15 00:06:54 +0000732 BuildMI(MBB, MBBI, DL,
733 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000734 .addReg(StackPtr)
735 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000736
737 if (needsFrameMoves) {
738 // Mark effective beginning of when frame pointer becomes valid.
739 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000740 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
741 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000742
743 // Define the current CFA to use the EBP/RBP register.
744 MachineLocation FPDst(FramePtr);
745 MachineLocation FPSrc(MachineLocation::VirtualFP);
746 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
747 }
748
749 // Mark the FramePtr as live-in in every block except the entry.
750 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
751 I != E; ++I)
752 I->addLiveIn(FramePtr);
753
754 // Realign stack
755 if (RegInfo->needsStackRealignment(MF)) {
756 MachineInstr *MI =
757 BuildMI(MBB, MBBI, DL,
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000758 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
759 .addReg(StackPtr)
760 .addImm(-MaxAlign)
761 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000762
763 // The EFLAGS implicit def is dead.
764 MI->getOperand(3).setIsDead();
765 }
766 } else {
767 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
768 }
769
770 // Skip the callee-saved push instructions.
771 bool PushedRegs = false;
772 int StackOffset = 2 * stackGrowth;
773
774 while (MBBI != MBB.end() &&
775 (MBBI->getOpcode() == X86::PUSH32r ||
776 MBBI->getOpcode() == X86::PUSH64r)) {
777 PushedRegs = true;
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000778 MBBI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000779 ++MBBI;
780
781 if (!HasFP && needsFrameMoves) {
782 // Mark callee-saved push instruction.
783 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
784 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
785
786 // Define the current CFA rule to use the provided offset.
Bill Wendling09b02c82011-07-25 18:00:28 +0000787 unsigned Ptr = StackSize ? MachineLocation::VirtualFP : StackPtr;
Anton Korobeynikov33464912010-11-15 00:06:54 +0000788 MachineLocation SPDst(Ptr);
789 MachineLocation SPSrc(Ptr, StackOffset);
790 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
791 StackOffset += stackGrowth;
792 }
793 }
794
795 DL = MBB.findDebugLoc(MBBI);
796
797 // If there is an SUB32ri of ESP immediately before this instruction, merge
798 // the two. This can be the case when tail call elimination is enabled and
799 // the callee has more arguments then the caller.
800 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
801
802 // If there is an ADD32ri or SUB32ri of ESP immediately after this
803 // instruction, merge the two instructions.
804 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
805
806 // Adjust stack pointer: ESP -= numbytes.
807
808 // Windows and cygwin/mingw require a prologue helper routine when allocating
809 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
810 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
811 // stack and adjust the stack pointer in one go. The 64-bit version of
812 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
813 // responsible for adjusting the stack pointer. Touching the stack at 4K
814 // increments is necessary to ensure that the guard pages used by the OS
815 // virtual memory manager are allocated in correct sequence.
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000816 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
817 const char *StackProbeSymbol;
818 bool isSPUpdateNeeded = false;
819
820 if (Is64Bit) {
821 if (STI.isTargetCygMing())
822 StackProbeSymbol = "___chkstk";
823 else {
824 StackProbeSymbol = "__chkstk";
825 isSPUpdateNeeded = true;
826 }
827 } else if (STI.isTargetCygMing())
828 StackProbeSymbol = "_alloca";
829 else
830 StackProbeSymbol = "_chkstk";
831
Anton Korobeynikov33464912010-11-15 00:06:54 +0000832 // Check whether EAX is livein for this function.
833 bool isEAXAlive = isEAXLiveIn(MF);
834
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000835 if (isEAXAlive) {
836 // Sanity check that EAX is not livein for this function.
837 // It should not be, so throw an assert.
838 assert(!Is64Bit && "EAX is livein in x64 case!");
839
Anton Korobeynikov33464912010-11-15 00:06:54 +0000840 // Save EAX
841 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000842 .addReg(X86::EAX, RegState::Kill)
843 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000844 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000845
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000846 if (Is64Bit) {
847 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
848 // Function prologue is responsible for adjusting the stack pointer.
849 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000850 .addImm(NumBytes)
851 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000852 } else {
853 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
854 // We'll also use 4 already allocated bytes for EAX.
855 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000856 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
857 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000858 }
859
860 BuildMI(MBB, MBBI, DL,
861 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
862 .addExternalSymbol(StackProbeSymbol)
863 .addReg(StackPtr, RegState::Define | RegState::Implicit)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000864 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
865 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000866
867 // MSVC x64's __chkstk needs to adjust %rsp.
868 // FIXME: %rax preserves the offset and should be available.
869 if (isSPUpdateNeeded)
870 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
871 TII, *RegInfo);
872
873 if (isEAXAlive) {
874 // Restore EAX
875 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
876 X86::EAX),
877 StackPtr, false, NumBytes - 4);
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000878 MI->setFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000879 MBB.insert(MBBI, MI);
880 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000881 } else if (NumBytes)
Evan Cheng7158e082011-01-03 22:53:22 +0000882 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
883 TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000884
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000885 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000886 // Mark end of stack pointer adjustment.
887 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000888 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
889 .addSym(Label);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000890
891 if (!HasFP && NumBytes) {
892 // Define the current CFA rule to use the provided offset.
893 if (StackSize) {
894 MachineLocation SPDst(MachineLocation::VirtualFP);
895 MachineLocation SPSrc(MachineLocation::VirtualFP,
896 -StackSize + stackGrowth);
897 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
898 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000899 MachineLocation SPDst(StackPtr);
900 MachineLocation SPSrc(StackPtr, stackGrowth);
901 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
902 }
903 }
904
905 // Emit DWARF info specifying the offsets of the callee-saved registers.
906 if (PushedRegs)
907 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
908 }
Bill Wendling09b02c82011-07-25 18:00:28 +0000909
910 // Darwin 10.7 and greater has support for compact unwind encoding.
Bill Wendlingd199aa02011-09-02 18:15:04 +0000911 if (GenerateCompactUnwind && STI.getTargetTriple().isMacOSX() &&
Eli Friedmanac86d432011-08-31 16:19:51 +0000912 !STI.getTargetTriple().isMacOSXVersionLT(10, 7))
Bill Wendling09b02c82011-07-25 18:00:28 +0000913 MMI.setCompactUnwindEncoding(getCompactUnwindEncoding(MF));
Anton Korobeynikov33464912010-11-15 00:06:54 +0000914}
915
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000916void X86FrameLowering::emitEpilogue(MachineFunction &MF,
Nick Lewycky3c2f0a12011-06-14 03:23:52 +0000917 MachineBasicBlock &MBB) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000918 const MachineFrameInfo *MFI = MF.getFrameInfo();
919 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000920 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
921 const X86InstrInfo &TII = *TM.getInstrInfo();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000922 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
923 assert(MBBI != MBB.end() && "Returning block has no instructions");
Anton Korobeynikov33464912010-11-15 00:06:54 +0000924 unsigned RetOpcode = MBBI->getOpcode();
925 DebugLoc DL = MBBI->getDebugLoc();
926 bool Is64Bit = STI.is64Bit();
927 unsigned StackAlign = getStackAlignment();
928 unsigned SlotSize = RegInfo->getSlotSize();
929 unsigned FramePtr = RegInfo->getFrameRegister(MF);
930 unsigned StackPtr = RegInfo->getStackRegister();
931
932 switch (RetOpcode) {
933 default:
934 llvm_unreachable("Can only insert epilog into returning blocks");
935 case X86::RET:
936 case X86::RETI:
937 case X86::TCRETURNdi:
938 case X86::TCRETURNri:
939 case X86::TCRETURNmi:
940 case X86::TCRETURNdi64:
941 case X86::TCRETURNri64:
942 case X86::TCRETURNmi64:
943 case X86::EH_RETURN:
944 case X86::EH_RETURN64:
945 break; // These are ok
946 }
947
948 // Get the number of bytes to allocate from the FrameInfo.
949 uint64_t StackSize = MFI->getStackSize();
950 uint64_t MaxAlign = MFI->getMaxAlignment();
951 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
952 uint64_t NumBytes = 0;
953
954 // If we're forcing a stack realignment we can't rely on just the frame
955 // info, we need to know the ABI stack alignment as well in case we
956 // have a call out. Otherwise just make sure we have some alignment - we'll
957 // go with the minimum.
958 if (ForceStackAlign) {
959 if (MFI->hasCalls())
960 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
961 else
962 MaxAlign = MaxAlign ? MaxAlign : 4;
963 }
964
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000965 if (hasFP(MF)) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000966 // Calculate required stack adjustment.
967 uint64_t FrameSize = StackSize - SlotSize;
968 if (RegInfo->needsStackRealignment(MF))
969 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
970
971 NumBytes = FrameSize - CSSize;
972
973 // Pop EBP.
974 BuildMI(MBB, MBBI, DL,
975 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
976 } else {
977 NumBytes = StackSize - CSSize;
978 }
979
980 // Skip the callee-saved pop instructions.
981 MachineBasicBlock::iterator LastCSPop = MBBI;
982 while (MBBI != MBB.begin()) {
983 MachineBasicBlock::iterator PI = prior(MBBI);
984 unsigned Opc = PI->getOpcode();
985
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000986 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
Anton Korobeynikov33464912010-11-15 00:06:54 +0000987 !PI->getDesc().isTerminator())
988 break;
989
990 --MBBI;
991 }
992
993 DL = MBBI->getDebugLoc();
994
995 // If there is an ADD32ri or SUB32ri of ESP immediately before this
996 // instruction, merge the two instructions.
997 if (NumBytes || MFI->hasVarSizedObjects())
998 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
999
1000 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1001 // slot before popping them off! Same applies for the case, when stack was
1002 // realigned.
1003 if (RegInfo->needsStackRealignment(MF)) {
1004 // We cannot use LEA here, because stack pointer was realigned. We need to
1005 // deallocate local frame back.
1006 if (CSSize) {
Evan Cheng7158e082011-01-03 22:53:22 +00001007 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001008 MBBI = prior(LastCSPop);
1009 }
1010
1011 BuildMI(MBB, MBBI, DL,
1012 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1013 StackPtr).addReg(FramePtr);
1014 } else if (MFI->hasVarSizedObjects()) {
1015 if (CSSize) {
1016 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
1017 MachineInstr *MI =
1018 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
1019 FramePtr, false, -CSSize);
1020 MBB.insert(MBBI, MI);
1021 } else {
1022 BuildMI(MBB, MBBI, DL,
1023 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
1024 .addReg(FramePtr);
1025 }
1026 } else if (NumBytes) {
1027 // Adjust stack pointer back: ESP += numbytes.
Evan Cheng7158e082011-01-03 22:53:22 +00001028 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001029 }
1030
1031 // We're returning from function via eh_return.
1032 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001033 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001034 MachineOperand &DestAddr = MBBI->getOperand(0);
1035 assert(DestAddr.isReg() && "Offset should be in register!");
1036 BuildMI(MBB, MBBI, DL,
1037 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1038 StackPtr).addReg(DestAddr.getReg());
1039 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1040 RetOpcode == X86::TCRETURNmi ||
1041 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1042 RetOpcode == X86::TCRETURNmi64) {
1043 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1044 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesenf7ca9762011-01-13 22:47:43 +00001045 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001046 MachineOperand &JumpTarget = MBBI->getOperand(0);
1047 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1048 assert(StackAdjust.isImm() && "Expecting immediate value.");
1049
1050 // Adjust stack pointer.
1051 int StackAdj = StackAdjust.getImm();
1052 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1053 int Offset = 0;
1054 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1055
1056 // Incoporate the retaddr area.
1057 Offset = StackAdj-MaxTCDelta;
1058 assert(Offset >= 0 && "Offset should never be negative");
1059
1060 if (Offset) {
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001061 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001062 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001063 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001064 }
1065
1066 // Jump to label or value in register.
1067 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
Evan Cheng3d2125c2010-11-30 23:55:39 +00001068 MachineInstrBuilder MIB =
1069 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1070 ? X86::TAILJMPd : X86::TAILJMPd64));
1071 if (JumpTarget.isGlobal())
1072 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1073 JumpTarget.getTargetFlags());
1074 else {
1075 assert(JumpTarget.isSymbol());
1076 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1077 JumpTarget.getTargetFlags());
1078 }
Anton Korobeynikov33464912010-11-15 00:06:54 +00001079 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1080 MachineInstrBuilder MIB =
1081 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1082 ? X86::TAILJMPm : X86::TAILJMPm64));
1083 for (unsigned i = 0; i != 5; ++i)
1084 MIB.addOperand(MBBI->getOperand(i));
1085 } else if (RetOpcode == X86::TCRETURNri64) {
1086 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1087 addReg(JumpTarget.getReg(), RegState::Kill);
1088 } else {
1089 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1090 addReg(JumpTarget.getReg(), RegState::Kill);
1091 }
1092
1093 MachineInstr *NewMI = prior(MBBI);
1094 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
1095 NewMI->addOperand(MBBI->getOperand(i));
1096
1097 // Delete the pseudo instruction TCRETURN.
1098 MBB.erase(MBBI);
1099 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
1100 (X86FI->getTCReturnAddrDelta() < 0)) {
1101 // Add the return addr area delta back since we are not tail calling.
1102 int delta = -1*X86FI->getTCReturnAddrDelta();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001103 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001104
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001105 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001106 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001107 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001108 }
1109}
Anton Korobeynikovd9e33852010-11-18 23:25:52 +00001110
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001111int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
Anton Korobeynikov82f58742010-11-20 15:59:32 +00001112 const X86RegisterInfo *RI =
1113 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
1114 const MachineFrameInfo *MFI = MF.getFrameInfo();
1115 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1116 uint64_t StackSize = MFI->getStackSize();
1117
1118 if (RI->needsStackRealignment(MF)) {
1119 if (FI < 0) {
1120 // Skip the saved EBP.
1121 Offset += RI->getSlotSize();
1122 } else {
1123 unsigned Align = MFI->getObjectAlignment(FI);
1124 assert((-(Offset + StackSize)) % Align == 0);
1125 Align = 0;
1126 return Offset + StackSize;
1127 }
1128 // FIXME: Support tail calls
1129 } else {
1130 if (!hasFP(MF))
1131 return Offset + StackSize;
1132
1133 // Skip the saved EBP.
1134 Offset += RI->getSlotSize();
1135
1136 // Skip the RETADDR move area
1137 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1138 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1139 if (TailCallReturnAddrDelta < 0)
1140 Offset -= TailCallReturnAddrDelta;
1141 }
1142
1143 return Offset;
1144}
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001145
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001146bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001147 MachineBasicBlock::iterator MI,
1148 const std::vector<CalleeSavedInfo> &CSI,
1149 const TargetRegisterInfo *TRI) const {
1150 if (CSI.empty())
1151 return false;
1152
1153 DebugLoc DL = MBB.findDebugLoc(MI);
1154
1155 MachineFunction &MF = *MBB.getParent();
1156
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001157 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
1158 unsigned FPReg = TRI->getFrameRegister(MF);
1159 unsigned CalleeFrameSize = 0;
1160
1161 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1162 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1163
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001164 // Push GPRs. It increases frame size.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001165 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1166 for (unsigned i = CSI.size(); i != 0; --i) {
1167 unsigned Reg = CSI[i-1].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001168 if (!X86::GR64RegClass.contains(Reg) &&
1169 !X86::GR32RegClass.contains(Reg))
1170 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001171 // Add the callee-saved register as live-in. It's killed at the spill.
1172 MBB.addLiveIn(Reg);
1173 if (Reg == FPReg)
1174 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
1175 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001176 CalleeFrameSize += SlotSize;
Charles Davisaff232a2011-06-12 01:45:54 +00001177 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1178 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001179 }
1180
1181 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001182
1183 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1184 // It can be done by spilling XMMs to stack frame.
1185 // Note that only Win64 ABI might spill XMMs.
1186 for (unsigned i = CSI.size(); i != 0; --i) {
1187 unsigned Reg = CSI[i-1].getReg();
1188 if (X86::GR64RegClass.contains(Reg) ||
1189 X86::GR32RegClass.contains(Reg))
1190 continue;
1191 // Add the callee-saved register as live-in. It's killed at the spill.
1192 MBB.addLiveIn(Reg);
1193 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1194 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
1195 RC, TRI);
1196 }
1197
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001198 return true;
1199}
1200
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001201bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001202 MachineBasicBlock::iterator MI,
1203 const std::vector<CalleeSavedInfo> &CSI,
1204 const TargetRegisterInfo *TRI) const {
1205 if (CSI.empty())
1206 return false;
1207
1208 DebugLoc DL = MBB.findDebugLoc(MI);
1209
1210 MachineFunction &MF = *MBB.getParent();
1211 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001212
1213 // Reload XMMs from stack frame.
1214 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1215 unsigned Reg = CSI[i].getReg();
1216 if (X86::GR64RegClass.contains(Reg) ||
1217 X86::GR32RegClass.contains(Reg))
1218 continue;
1219 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1220 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
1221 RC, TRI);
1222 }
1223
1224 // POP GPRs.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001225 unsigned FPReg = TRI->getFrameRegister(MF);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001226 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1227 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1228 unsigned Reg = CSI[i].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001229 if (!X86::GR64RegClass.contains(Reg) &&
1230 !X86::GR32RegClass.contains(Reg))
1231 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001232 if (Reg == FPReg)
1233 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
1234 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001235 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001236 }
1237 return true;
1238}
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001239
1240void
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001241X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001242 RegScavenger *RS) const {
1243 MachineFrameInfo *MFI = MF.getFrameInfo();
1244 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
1245 unsigned SlotSize = RegInfo->getSlotSize();
1246
1247 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1248 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1249
1250 if (TailCallReturnAddrDelta < 0) {
1251 // create RETURNADDR area
1252 // arg
1253 // arg
1254 // RETADDR
1255 // { ...
1256 // RETADDR area
1257 // ...
1258 // }
1259 // [EBP]
1260 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1261 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1262 }
1263
1264 if (hasFP(MF)) {
1265 assert((TailCallReturnAddrDelta <= 0) &&
1266 "The Delta should always be zero or negative");
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001267 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001268
1269 // Create a frame entry for the EBP register that must be saved.
1270 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1271 -(int)SlotSize +
1272 TFI.getOffsetOfLocalArea() +
1273 TailCallReturnAddrDelta,
1274 true);
1275 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1276 "Slot for EBP register must be last in order to be found!");
1277 FrameIdx = 0;
1278 }
1279}
Rafael Espindola76927d752011-08-30 19:39:58 +00001280
1281static bool
1282HasNestArgument(const MachineFunction *MF) {
1283 const Function *F = MF->getFunction();
1284 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1285 I != E; I++) {
1286 if (I->hasNestAttr())
1287 return true;
1288 }
1289 return false;
1290}
1291
1292static unsigned
1293GetScratchRegister(bool Is64Bit, const MachineFunction &MF) {
1294 if (Is64Bit) {
1295 return X86::R11;
1296 } else {
1297 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1298 bool IsNested = HasNestArgument(&MF);
1299
1300 if (CallingConvention == CallingConv::X86_FastCall) {
1301 if (IsNested) {
Rafael Espindolae81abfd2011-08-31 16:43:33 +00001302 report_fatal_error("Segmented stacks does not support fastcall with "
1303 "nested function.");
Rafael Espindola76927d752011-08-30 19:39:58 +00001304 return -1;
1305 } else {
1306 return X86::EAX;
1307 }
1308 } else {
1309 if (IsNested)
1310 return X86::EDX;
1311 else
1312 return X86::ECX;
1313 }
1314 }
1315}
1316
1317void
1318X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1319 MachineBasicBlock &prologueMBB = MF.front();
1320 MachineFrameInfo *MFI = MF.getFrameInfo();
1321 const X86InstrInfo &TII = *TM.getInstrInfo();
1322 uint64_t StackSize;
1323 bool Is64Bit = STI.is64Bit();
1324 unsigned TlsReg, TlsOffset;
1325 DebugLoc DL;
1326 const X86Subtarget *ST = &MF.getTarget().getSubtarget<X86Subtarget>();
1327
1328 unsigned ScratchReg = GetScratchRegister(Is64Bit, MF);
1329 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1330 "Scratch register is live-in");
1331
1332 if (MF.getFunction()->isVarArg())
1333 report_fatal_error("Segmented stacks do not support vararg functions.");
1334 if (!ST->isTargetLinux())
1335 report_fatal_error("Segmented stacks supported only on linux.");
1336
1337 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1338 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1339 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1340 bool IsNested = false;
1341
1342 // We need to know if the function has a nest argument only in 64 bit mode.
1343 if (Is64Bit)
1344 IsNested = HasNestArgument(&MF);
1345
1346 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1347 e = prologueMBB.livein_end(); i != e; i++) {
1348 allocMBB->addLiveIn(*i);
1349 checkMBB->addLiveIn(*i);
1350 }
1351
1352 if (IsNested)
1353 allocMBB->addLiveIn(X86::R10);
1354
1355 MF.push_front(allocMBB);
1356 MF.push_front(checkMBB);
1357
1358 // Eventually StackSize will be calculated by a link-time pass; which will
1359 // also decide whether checking code needs to be injected into this particular
1360 // prologue.
1361 StackSize = MFI->getStackSize();
1362
1363 // Read the limit off the current stacklet off the stack_guard location.
1364 if (Is64Bit) {
1365 TlsReg = X86::FS;
1366 TlsOffset = 0x70;
1367
1368 BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RSP)
1369 .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1370 BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
1371 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1372 } else {
1373 TlsReg = X86::GS;
1374 TlsOffset = 0x30;
1375
1376 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1377 .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1378 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1379 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1380 }
1381
1382 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1383 // It jumps to normal execution of the function body.
1384 BuildMI(checkMBB, DL, TII.get(X86::JG_4)).addMBB(&prologueMBB);
1385
1386 // On 32 bit we first push the arguments size and then the frame size. On 64
1387 // bit, we pass the stack frame size in r10 and the argument size in r11.
1388 if (Is64Bit) {
1389 // Functions with nested arguments use R10, so it needs to be saved across
1390 // the call to _morestack
1391
1392 if (IsNested)
1393 BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::RAX).addReg(X86::R10);
1394
1395 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R10)
1396 .addImm(StackSize);
1397 BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R11)
1398 .addImm(X86FI->getArgumentStackSize());
1399 MF.getRegInfo().setPhysRegUsed(X86::R10);
1400 MF.getRegInfo().setPhysRegUsed(X86::R11);
1401 } else {
1402 // Since we'll call __morestack, stack alignment needs to be preserved.
1403 BuildMI(allocMBB, DL, TII.get(X86::SUB32ri), X86::ESP).addReg(X86::ESP)
1404 .addImm(8);
1405 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1406 .addImm(X86FI->getArgumentStackSize());
1407 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1408 .addImm(StackSize);
1409 }
1410
1411 // __morestack is in libgcc
1412 if (Is64Bit)
1413 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1414 .addExternalSymbol("__morestack");
1415 else
1416 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1417 .addExternalSymbol("__morestack");
1418
1419 // __morestack only seems to remove 8 bytes off the stack. Add back the
1420 // additional 8 bytes we added before pushing the arguments.
1421 if (!Is64Bit)
1422 BuildMI(allocMBB, DL, TII.get(X86::ADD32ri), X86::ESP).addReg(X86::ESP)
1423 .addImm(8);
1424 BuildMI(allocMBB, DL, TII.get(X86::RET));
1425
1426 if (Is64Bit && IsNested)
1427 BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::R10).addReg(X86::RAX);
1428
1429 allocMBB->addSuccessor(&prologueMBB);
1430 checkMBB->addSuccessor(allocMBB);
1431 checkMBB->addSuccessor(&prologueMBB);
1432
1433#ifndef NDEBUG
1434 MF.verify();
1435#endif
1436}