blob: 807079663a376d5bf04def5034b77113f32c6ac3 [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"
Anton Korobeynikovd9e33852010-11-18 23:25:52 +000018#include "X86TargetMachine.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000019#include "llvm/Function.h"
20#include "llvm/CodeGen/MachineFrameInfo.h"
21#include "llvm/CodeGen/MachineFunction.h"
22#include "llvm/CodeGen/MachineInstrBuilder.h"
23#include "llvm/CodeGen/MachineModuleInfo.h"
24#include "llvm/CodeGen/MachineRegisterInfo.h"
Rafael Espindolaf0adba92011-04-15 15:11:06 +000025#include "llvm/MC/MCAsmInfo.h"
Bill Wendling6a6b8c32011-07-07 00:54:13 +000026#include "llvm/MC/MCSymbol.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000027#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetOptions.h"
29#include "llvm/Support/CommandLine.h"
Evan Cheng7158e082011-01-03 22:53:22 +000030#include "llvm/ADT/SmallSet.h"
Anton Korobeynikov33464912010-11-15 00:06:54 +000031
32using namespace llvm;
33
34// FIXME: completely move here.
35extern cl::opt<bool> ForceStackAlign;
36
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000037bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000038 return !MF.getFrameInfo()->hasVarSizedObjects();
39}
40
41/// hasFP - Return true if the specified function should have a dedicated frame
42/// pointer register. This is true if the function has variable sized allocas
43/// or if frame pointer elimination is disabled.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000044bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000045 const MachineFrameInfo *MFI = MF.getFrameInfo();
46 const MachineModuleInfo &MMI = MF.getMMI();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +000047 const TargetRegisterInfo *RI = TM.getRegisterInfo();
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000048
49 return (DisableFramePointerElim(MF) ||
50 RI->needsStackRealignment(MF) ||
51 MFI->hasVarSizedObjects() ||
52 MFI->isFrameAddressTaken() ||
53 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
54 MMI.callsUnwindInit());
55}
56
Anton Korobeynikov33464912010-11-15 00:06:54 +000057static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
58 if (is64Bit) {
59 if (isInt<8>(Imm))
60 return X86::SUB64ri8;
61 return X86::SUB64ri32;
62 } else {
63 if (isInt<8>(Imm))
64 return X86::SUB32ri8;
65 return X86::SUB32ri;
66 }
67}
68
69static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
70 if (is64Bit) {
71 if (isInt<8>(Imm))
72 return X86::ADD64ri8;
73 return X86::ADD64ri32;
74 } else {
75 if (isInt<8>(Imm))
76 return X86::ADD32ri8;
77 return X86::ADD32ri;
78 }
79}
80
Evan Cheng7158e082011-01-03 22:53:22 +000081/// findDeadCallerSavedReg - Return a caller-saved register that isn't live
82/// when it reaches the "return" instruction. We can then pop a stack object
83/// to this register without worry about clobbering it.
84static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
85 MachineBasicBlock::iterator &MBBI,
86 const TargetRegisterInfo &TRI,
87 bool Is64Bit) {
88 const MachineFunction *MF = MBB.getParent();
89 const Function *F = MF->getFunction();
90 if (!F || MF->getMMI().callsEHReturn())
91 return 0;
92
93 static const unsigned CallerSavedRegs32Bit[] = {
94 X86::EAX, X86::EDX, X86::ECX
95 };
96
97 static const unsigned CallerSavedRegs64Bit[] = {
98 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
99 X86::R8, X86::R9, X86::R10, X86::R11
100 };
101
102 unsigned Opc = MBBI->getOpcode();
103 switch (Opc) {
104 default: return 0;
105 case X86::RET:
106 case X86::RETI:
107 case X86::TCRETURNdi:
108 case X86::TCRETURNri:
109 case X86::TCRETURNmi:
110 case X86::TCRETURNdi64:
111 case X86::TCRETURNri64:
112 case X86::TCRETURNmi64:
113 case X86::EH_RETURN:
114 case X86::EH_RETURN64: {
115 SmallSet<unsigned, 8> Uses;
116 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
117 MachineOperand &MO = MBBI->getOperand(i);
118 if (!MO.isReg() || MO.isDef())
119 continue;
120 unsigned Reg = MO.getReg();
121 if (!Reg)
122 continue;
123 for (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
124 Uses.insert(*AsI);
125 }
126
127 const unsigned *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
128 for (; *CS; ++CS)
129 if (!Uses.count(*CS))
130 return *CS;
131 }
132 }
133
134 return 0;
135}
136
137
Anton Korobeynikov33464912010-11-15 00:06:54 +0000138/// emitSPUpdate - Emit a series of instructions to increment / decrement the
139/// stack pointer by a constant value.
140static
141void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
Evan Cheng7158e082011-01-03 22:53:22 +0000142 unsigned StackPtr, int64_t NumBytes,
143 bool Is64Bit, const TargetInstrInfo &TII,
144 const TargetRegisterInfo &TRI) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000145 bool isSub = NumBytes < 0;
146 uint64_t Offset = isSub ? -NumBytes : NumBytes;
147 unsigned Opc = isSub ?
148 getSUBriOpcode(Is64Bit, Offset) :
149 getADDriOpcode(Is64Bit, Offset);
150 uint64_t Chunk = (1LL << 31) - 1;
151 DebugLoc DL = MBB.findDebugLoc(MBBI);
152
153 while (Offset) {
154 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
Evan Cheng7158e082011-01-03 22:53:22 +0000155 if (ThisVal == (Is64Bit ? 8 : 4)) {
156 // Use push / pop instead.
157 unsigned Reg = isSub
Dale Johannesen1e08cd12011-01-04 19:31:24 +0000158 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
Evan Cheng7158e082011-01-03 22:53:22 +0000159 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
160 if (Reg) {
161 Opc = isSub
162 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
163 : (Is64Bit ? X86::POP64r : X86::POP32r);
Charles Davisaff232a2011-06-12 01:45:54 +0000164 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
Evan Cheng7158e082011-01-03 22:53:22 +0000165 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
Charles Davisaff232a2011-06-12 01:45:54 +0000166 if (isSub)
167 MI->setFlag(MachineInstr::FrameSetup);
Evan Cheng7158e082011-01-03 22:53:22 +0000168 Offset -= ThisVal;
169 continue;
170 }
171 }
172
Anton Korobeynikov33464912010-11-15 00:06:54 +0000173 MachineInstr *MI =
174 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
Evan Cheng7158e082011-01-03 22:53:22 +0000175 .addReg(StackPtr)
176 .addImm(ThisVal);
Charles Davisaff232a2011-06-12 01:45:54 +0000177 if (isSub)
178 MI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000179 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
180 Offset -= ThisVal;
181 }
182}
183
184/// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
185static
186void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
187 unsigned StackPtr, uint64_t *NumBytes = NULL) {
188 if (MBBI == MBB.begin()) return;
189
190 MachineBasicBlock::iterator PI = prior(MBBI);
191 unsigned Opc = PI->getOpcode();
192 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
193 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
194 PI->getOperand(0).getReg() == StackPtr) {
195 if (NumBytes)
196 *NumBytes += PI->getOperand(2).getImm();
197 MBB.erase(PI);
198 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
199 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
200 PI->getOperand(0).getReg() == StackPtr) {
201 if (NumBytes)
202 *NumBytes -= PI->getOperand(2).getImm();
203 MBB.erase(PI);
204 }
205}
206
207/// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
208static
209void mergeSPUpdatesDown(MachineBasicBlock &MBB,
210 MachineBasicBlock::iterator &MBBI,
211 unsigned StackPtr, uint64_t *NumBytes = NULL) {
212 // FIXME: THIS ISN'T RUN!!!
213 return;
214
215 if (MBBI == MBB.end()) return;
216
217 MachineBasicBlock::iterator NI = llvm::next(MBBI);
218 if (NI == MBB.end()) return;
219
220 unsigned Opc = NI->getOpcode();
221 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
222 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
223 NI->getOperand(0).getReg() == StackPtr) {
224 if (NumBytes)
225 *NumBytes -= NI->getOperand(2).getImm();
226 MBB.erase(NI);
227 MBBI = NI;
228 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
229 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
230 NI->getOperand(0).getReg() == StackPtr) {
231 if (NumBytes)
232 *NumBytes += NI->getOperand(2).getImm();
233 MBB.erase(NI);
234 MBBI = NI;
235 }
236}
237
238/// mergeSPUpdates - Checks the instruction before/after the passed
239/// instruction. If it is an ADD/SUB instruction it is deleted argument and the
240/// stack adjustment is returned as a positive value for ADD and a negative for
241/// SUB.
242static int mergeSPUpdates(MachineBasicBlock &MBB,
243 MachineBasicBlock::iterator &MBBI,
244 unsigned StackPtr,
245 bool doMergeWithPrevious) {
246 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
247 (!doMergeWithPrevious && MBBI == MBB.end()))
248 return 0;
249
250 MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
251 MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
252 unsigned Opc = PI->getOpcode();
253 int Offset = 0;
254
255 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
256 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
257 PI->getOperand(0).getReg() == StackPtr){
258 Offset += PI->getOperand(2).getImm();
259 MBB.erase(PI);
260 if (!doMergeWithPrevious) MBBI = NI;
261 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
262 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
263 PI->getOperand(0).getReg() == StackPtr) {
264 Offset -= PI->getOperand(2).getImm();
265 MBB.erase(PI);
266 if (!doMergeWithPrevious) MBBI = NI;
267 }
268
269 return Offset;
270}
271
272static bool isEAXLiveIn(MachineFunction &MF) {
273 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
274 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
275 unsigned Reg = II->first;
276
277 if (Reg == X86::EAX || Reg == X86::AX ||
278 Reg == X86::AH || Reg == X86::AL)
279 return true;
280 }
281
282 return false;
283}
284
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000285void X86FrameLowering::emitCalleeSavedFrameMoves(MachineFunction &MF,
Anton Korobeynikov33464912010-11-15 00:06:54 +0000286 MCSymbol *Label,
287 unsigned FramePtr) const {
288 MachineFrameInfo *MFI = MF.getFrameInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000289 MachineModuleInfo &MMI = MF.getMMI();
290
291 // Add callee saved registers to move list.
292 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
293 if (CSI.empty()) return;
294
295 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000296 const TargetData *TD = TM.getTargetData();
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000297 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000298
299 // Calculate amount of bytes used for return address storing.
Anton Korobeynikove7499112011-01-14 21:57:58 +0000300 int stackGrowth = -TD->getPointerSize();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000301
302 // FIXME: This is dirty hack. The code itself is pretty mess right now.
303 // It should be rewritten from scratch and generalized sometimes.
304
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000305 // Determine maximum offset (minimum due to stack growth).
Anton Korobeynikov33464912010-11-15 00:06:54 +0000306 int64_t MaxOffset = 0;
307 for (std::vector<CalleeSavedInfo>::const_iterator
308 I = CSI.begin(), E = CSI.end(); I != E; ++I)
309 MaxOffset = std::min(MaxOffset,
310 MFI->getObjectOffset(I->getFrameIdx()));
311
312 // Calculate offsets.
313 int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
314 for (std::vector<CalleeSavedInfo>::const_iterator
315 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
316 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
317 unsigned Reg = I->getReg();
318 Offset = MaxOffset - Offset + saveAreaOffset;
319
320 // Don't output a new machine move if we're re-saving the frame
321 // pointer. This happens when the PrologEpilogInserter has inserted an extra
322 // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
323 // generates one when frame pointers are used. If we generate a "machine
324 // move" for this extra "PUSH", the linker will lose track of the fact that
325 // the frame pointer should have the value of the first "PUSH" when it's
326 // trying to unwind.
NAKAMURA Takumi27635382011-02-05 15:10:54 +0000327 //
Anton Korobeynikov33464912010-11-15 00:06:54 +0000328 // FIXME: This looks inelegant. It's possibly correct, but it's covering up
329 // another bug. I.e., one where we generate a prolog like this:
330 //
331 // pushl %ebp
332 // movl %esp, %ebp
333 // pushl %ebp
334 // pushl %esi
335 // ...
336 //
337 // The immediate re-push of EBP is unnecessary. At the least, it's an
338 // optimization bug. EBP can be used as a scratch register in certain
339 // cases, but probably not when we have a frame pointer.
340 if (HasFP && FramePtr == Reg)
341 continue;
342
343 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
344 MachineLocation CSSrc(Reg);
345 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
346 }
347}
348
349/// emitPrologue - Push callee-saved registers onto the stack, which
350/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
351/// space for local variables. Also emit labels used by the exception handler to
352/// generate the exception handling frames.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000353void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000354 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
355 MachineBasicBlock::iterator MBBI = MBB.begin();
356 MachineFrameInfo *MFI = MF.getFrameInfo();
357 const Function *Fn = MF.getFunction();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000358 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
359 const X86InstrInfo &TII = *TM.getInstrInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000360 MachineModuleInfo &MMI = MF.getMMI();
361 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
362 bool needsFrameMoves = MMI.hasDebugInfo() ||
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000363 Fn->needsUnwindTableEntry();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000364 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
365 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000366 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000367 bool Is64Bit = STI.is64Bit();
368 bool IsWin64 = STI.isTargetWin64();
369 unsigned StackAlign = getStackAlignment();
370 unsigned SlotSize = RegInfo->getSlotSize();
371 unsigned FramePtr = RegInfo->getFrameRegister(MF);
372 unsigned StackPtr = RegInfo->getStackRegister();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000373 DebugLoc DL;
374
375 // If we're forcing a stack realignment we can't rely on just the frame
376 // info, we need to know the ABI stack alignment as well in case we
377 // have a call out. Otherwise just make sure we have some alignment - we'll
378 // go with the minimum SlotSize.
379 if (ForceStackAlign) {
380 if (MFI->hasCalls())
381 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
382 else if (MaxAlign < SlotSize)
383 MaxAlign = SlotSize;
384 }
385
386 // Add RETADDR move area to callee saved frame size.
387 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
388 if (TailCallReturnAddrDelta < 0)
389 X86FI->setCalleeSavedFrameSize(
390 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
391
392 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
393 // function, and use up to 128 bytes of stack space, don't have a frame
394 // pointer, calls, or dynamic alloca then we do not need to adjust the
395 // stack pointer (we fit in the Red Zone).
396 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
397 !RegInfo->needsStackRealignment(MF) &&
398 !MFI->hasVarSizedObjects() && // No dynamic alloca.
399 !MFI->adjustsStack() && // No calls.
400 !IsWin64) { // Win64 has no Red Zone
401 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
402 if (HasFP) MinSize += SlotSize;
403 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
404 MFI->setStackSize(StackSize);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000405 }
406
407 // Insert stack pointer adjustment for later moving of return addr. Only
408 // applies to tail call optimized functions where the callee argument stack
409 // size is bigger than the callers.
410 if (TailCallReturnAddrDelta < 0) {
411 MachineInstr *MI =
412 BuildMI(MBB, MBBI, DL,
413 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
414 StackPtr)
415 .addReg(StackPtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000416 .addImm(-TailCallReturnAddrDelta)
417 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000418 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
419 }
420
421 // Mapping for machine moves:
422 //
423 // DST: VirtualFP AND
424 // SRC: VirtualFP => DW_CFA_def_cfa_offset
425 // ELSE => DW_CFA_def_cfa
426 //
427 // SRC: VirtualFP AND
428 // DST: Register => DW_CFA_def_cfa_register
429 //
430 // ELSE
431 // OFFSET < 0 => DW_CFA_offset_extended_sf
432 // REG < 64 => DW_CFA_offset + Reg
433 // ELSE => DW_CFA_offset_extended
434
435 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
436 const TargetData *TD = MF.getTarget().getTargetData();
437 uint64_t NumBytes = 0;
438 int stackGrowth = -TD->getPointerSize();
439
440 if (HasFP) {
441 // Calculate required stack adjustment.
442 uint64_t FrameSize = StackSize - SlotSize;
443 if (RegInfo->needsStackRealignment(MF))
444 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
445
446 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
447
448 // Get the offset of the stack slot for the EBP register, which is
449 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
450 // Update the frame offset adjustment.
451 MFI->setOffsetAdjustment(-NumBytes);
452
453 // Save EBP/RBP into the appropriate stack slot.
454 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
Charles Davisaff232a2011-06-12 01:45:54 +0000455 .addReg(FramePtr, RegState::Kill)
456 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000457
458 if (needsFrameMoves) {
459 // Mark the place where EBP/RBP was saved.
460 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000461 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
462 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000463
464 // Define the current CFA rule to use the provided offset.
465 if (StackSize) {
466 MachineLocation SPDst(MachineLocation::VirtualFP);
467 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
468 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
469 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000470 MachineLocation SPDst(StackPtr);
471 MachineLocation SPSrc(StackPtr, stackGrowth);
472 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
473 }
474
475 // Change the rule for the FramePtr to be an "offset" rule.
476 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
477 MachineLocation FPSrc(FramePtr);
478 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
479 }
480
481 // Update EBP with the new base value...
482 BuildMI(MBB, MBBI, DL,
483 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000484 .addReg(StackPtr)
485 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000486
487 if (needsFrameMoves) {
488 // Mark effective beginning of when frame pointer becomes valid.
489 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000490 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
491 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000492
493 // Define the current CFA to use the EBP/RBP register.
494 MachineLocation FPDst(FramePtr);
495 MachineLocation FPSrc(MachineLocation::VirtualFP);
496 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
497 }
498
499 // Mark the FramePtr as live-in in every block except the entry.
500 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
501 I != E; ++I)
502 I->addLiveIn(FramePtr);
503
504 // Realign stack
505 if (RegInfo->needsStackRealignment(MF)) {
506 MachineInstr *MI =
507 BuildMI(MBB, MBBI, DL,
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000508 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
509 .addReg(StackPtr)
510 .addImm(-MaxAlign)
511 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000512
513 // The EFLAGS implicit def is dead.
514 MI->getOperand(3).setIsDead();
515 }
516 } else {
517 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
518 }
519
520 // Skip the callee-saved push instructions.
521 bool PushedRegs = false;
522 int StackOffset = 2 * stackGrowth;
523
524 while (MBBI != MBB.end() &&
525 (MBBI->getOpcode() == X86::PUSH32r ||
526 MBBI->getOpcode() == X86::PUSH64r)) {
527 PushedRegs = true;
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000528 MBBI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000529 ++MBBI;
530
531 if (!HasFP && needsFrameMoves) {
532 // Mark callee-saved push instruction.
533 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
534 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
535
536 // Define the current CFA rule to use the provided offset.
537 unsigned Ptr = StackSize ?
538 MachineLocation::VirtualFP : StackPtr;
539 MachineLocation SPDst(Ptr);
540 MachineLocation SPSrc(Ptr, StackOffset);
541 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
542 StackOffset += stackGrowth;
543 }
544 }
545
546 DL = MBB.findDebugLoc(MBBI);
547
548 // If there is an SUB32ri of ESP immediately before this instruction, merge
549 // the two. This can be the case when tail call elimination is enabled and
550 // the callee has more arguments then the caller.
551 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
552
553 // If there is an ADD32ri or SUB32ri of ESP immediately after this
554 // instruction, merge the two instructions.
555 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
556
557 // Adjust stack pointer: ESP -= numbytes.
558
559 // Windows and cygwin/mingw require a prologue helper routine when allocating
560 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
561 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
562 // stack and adjust the stack pointer in one go. The 64-bit version of
563 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
564 // responsible for adjusting the stack pointer. Touching the stack at 4K
565 // increments is necessary to ensure that the guard pages used by the OS
566 // virtual memory manager are allocated in correct sequence.
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000567 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
568 const char *StackProbeSymbol;
569 bool isSPUpdateNeeded = false;
570
571 if (Is64Bit) {
572 if (STI.isTargetCygMing())
573 StackProbeSymbol = "___chkstk";
574 else {
575 StackProbeSymbol = "__chkstk";
576 isSPUpdateNeeded = true;
577 }
578 } else if (STI.isTargetCygMing())
579 StackProbeSymbol = "_alloca";
580 else
581 StackProbeSymbol = "_chkstk";
582
Anton Korobeynikov33464912010-11-15 00:06:54 +0000583 // Check whether EAX is livein for this function.
584 bool isEAXAlive = isEAXLiveIn(MF);
585
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000586 if (isEAXAlive) {
587 // Sanity check that EAX is not livein for this function.
588 // It should not be, so throw an assert.
589 assert(!Is64Bit && "EAX is livein in x64 case!");
590
Anton Korobeynikov33464912010-11-15 00:06:54 +0000591 // Save EAX
592 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000593 .addReg(X86::EAX, RegState::Kill)
594 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000595 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000596
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000597 if (Is64Bit) {
598 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
599 // Function prologue is responsible for adjusting the stack pointer.
600 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000601 .addImm(NumBytes)
602 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000603 } else {
604 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
605 // We'll also use 4 already allocated bytes for EAX.
606 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000607 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
608 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000609 }
610
611 BuildMI(MBB, MBBI, DL,
612 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
613 .addExternalSymbol(StackProbeSymbol)
614 .addReg(StackPtr, RegState::Define | RegState::Implicit)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000615 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
616 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000617
618 // MSVC x64's __chkstk needs to adjust %rsp.
619 // FIXME: %rax preserves the offset and should be available.
620 if (isSPUpdateNeeded)
621 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
622 TII, *RegInfo);
623
624 if (isEAXAlive) {
625 // Restore EAX
626 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
627 X86::EAX),
628 StackPtr, false, NumBytes - 4);
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000629 MI->setFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000630 MBB.insert(MBBI, MI);
631 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000632 } else if (NumBytes)
Evan Cheng7158e082011-01-03 22:53:22 +0000633 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
634 TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000635
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000636 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000637 // Mark end of stack pointer adjustment.
638 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000639 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
640 .addSym(Label);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000641
642 if (!HasFP && NumBytes) {
643 // Define the current CFA rule to use the provided offset.
644 if (StackSize) {
645 MachineLocation SPDst(MachineLocation::VirtualFP);
646 MachineLocation SPSrc(MachineLocation::VirtualFP,
647 -StackSize + stackGrowth);
648 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
649 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000650 MachineLocation SPDst(StackPtr);
651 MachineLocation SPSrc(StackPtr, stackGrowth);
652 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
653 }
654 }
655
656 // Emit DWARF info specifying the offsets of the callee-saved registers.
657 if (PushedRegs)
658 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
659 }
660}
661
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000662void X86FrameLowering::emitEpilogue(MachineFunction &MF,
Nick Lewycky3c2f0a12011-06-14 03:23:52 +0000663 MachineBasicBlock &MBB) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000664 const MachineFrameInfo *MFI = MF.getFrameInfo();
665 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000666 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
667 const X86InstrInfo &TII = *TM.getInstrInfo();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000668 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
669 assert(MBBI != MBB.end() && "Returning block has no instructions");
Anton Korobeynikov33464912010-11-15 00:06:54 +0000670 unsigned RetOpcode = MBBI->getOpcode();
671 DebugLoc DL = MBBI->getDebugLoc();
672 bool Is64Bit = STI.is64Bit();
673 unsigned StackAlign = getStackAlignment();
674 unsigned SlotSize = RegInfo->getSlotSize();
675 unsigned FramePtr = RegInfo->getFrameRegister(MF);
676 unsigned StackPtr = RegInfo->getStackRegister();
677
678 switch (RetOpcode) {
679 default:
680 llvm_unreachable("Can only insert epilog into returning blocks");
681 case X86::RET:
682 case X86::RETI:
683 case X86::TCRETURNdi:
684 case X86::TCRETURNri:
685 case X86::TCRETURNmi:
686 case X86::TCRETURNdi64:
687 case X86::TCRETURNri64:
688 case X86::TCRETURNmi64:
689 case X86::EH_RETURN:
690 case X86::EH_RETURN64:
691 break; // These are ok
692 }
693
694 // Get the number of bytes to allocate from the FrameInfo.
695 uint64_t StackSize = MFI->getStackSize();
696 uint64_t MaxAlign = MFI->getMaxAlignment();
697 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
698 uint64_t NumBytes = 0;
699
700 // If we're forcing a stack realignment we can't rely on just the frame
701 // info, we need to know the ABI stack alignment as well in case we
702 // have a call out. Otherwise just make sure we have some alignment - we'll
703 // go with the minimum.
704 if (ForceStackAlign) {
705 if (MFI->hasCalls())
706 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
707 else
708 MaxAlign = MaxAlign ? MaxAlign : 4;
709 }
710
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000711 if (hasFP(MF)) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000712 // Calculate required stack adjustment.
713 uint64_t FrameSize = StackSize - SlotSize;
714 if (RegInfo->needsStackRealignment(MF))
715 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
716
717 NumBytes = FrameSize - CSSize;
718
719 // Pop EBP.
720 BuildMI(MBB, MBBI, DL,
721 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
722 } else {
723 NumBytes = StackSize - CSSize;
724 }
725
726 // Skip the callee-saved pop instructions.
727 MachineBasicBlock::iterator LastCSPop = MBBI;
728 while (MBBI != MBB.begin()) {
729 MachineBasicBlock::iterator PI = prior(MBBI);
730 unsigned Opc = PI->getOpcode();
731
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000732 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
Anton Korobeynikov33464912010-11-15 00:06:54 +0000733 !PI->getDesc().isTerminator())
734 break;
735
736 --MBBI;
737 }
738
739 DL = MBBI->getDebugLoc();
740
741 // If there is an ADD32ri or SUB32ri of ESP immediately before this
742 // instruction, merge the two instructions.
743 if (NumBytes || MFI->hasVarSizedObjects())
744 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
745
746 // If dynamic alloca is used, then reset esp to point to the last callee-saved
747 // slot before popping them off! Same applies for the case, when stack was
748 // realigned.
749 if (RegInfo->needsStackRealignment(MF)) {
750 // We cannot use LEA here, because stack pointer was realigned. We need to
751 // deallocate local frame back.
752 if (CSSize) {
Evan Cheng7158e082011-01-03 22:53:22 +0000753 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000754 MBBI = prior(LastCSPop);
755 }
756
757 BuildMI(MBB, MBBI, DL,
758 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
759 StackPtr).addReg(FramePtr);
760 } else if (MFI->hasVarSizedObjects()) {
761 if (CSSize) {
762 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
763 MachineInstr *MI =
764 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
765 FramePtr, false, -CSSize);
766 MBB.insert(MBBI, MI);
767 } else {
768 BuildMI(MBB, MBBI, DL,
769 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
770 .addReg(FramePtr);
771 }
772 } else if (NumBytes) {
773 // Adjust stack pointer back: ESP += numbytes.
Evan Cheng7158e082011-01-03 22:53:22 +0000774 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000775 }
776
777 // We're returning from function via eh_return.
778 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000779 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000780 MachineOperand &DestAddr = MBBI->getOperand(0);
781 assert(DestAddr.isReg() && "Offset should be in register!");
782 BuildMI(MBB, MBBI, DL,
783 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
784 StackPtr).addReg(DestAddr.getReg());
785 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
786 RetOpcode == X86::TCRETURNmi ||
787 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
788 RetOpcode == X86::TCRETURNmi64) {
789 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
790 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesenf7ca9762011-01-13 22:47:43 +0000791 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000792 MachineOperand &JumpTarget = MBBI->getOperand(0);
793 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
794 assert(StackAdjust.isImm() && "Expecting immediate value.");
795
796 // Adjust stack pointer.
797 int StackAdj = StackAdjust.getImm();
798 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
799 int Offset = 0;
800 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
801
802 // Incoporate the retaddr area.
803 Offset = StackAdj-MaxTCDelta;
804 assert(Offset >= 0 && "Offset should never be negative");
805
806 if (Offset) {
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000807 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +0000808 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +0000809 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000810 }
811
812 // Jump to label or value in register.
813 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
Evan Cheng3d2125c2010-11-30 23:55:39 +0000814 MachineInstrBuilder MIB =
815 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
816 ? X86::TAILJMPd : X86::TAILJMPd64));
817 if (JumpTarget.isGlobal())
818 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
819 JumpTarget.getTargetFlags());
820 else {
821 assert(JumpTarget.isSymbol());
822 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
823 JumpTarget.getTargetFlags());
824 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000825 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
826 MachineInstrBuilder MIB =
827 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
828 ? X86::TAILJMPm : X86::TAILJMPm64));
829 for (unsigned i = 0; i != 5; ++i)
830 MIB.addOperand(MBBI->getOperand(i));
831 } else if (RetOpcode == X86::TCRETURNri64) {
832 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
833 addReg(JumpTarget.getReg(), RegState::Kill);
834 } else {
835 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
836 addReg(JumpTarget.getReg(), RegState::Kill);
837 }
838
839 MachineInstr *NewMI = prior(MBBI);
840 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
841 NewMI->addOperand(MBBI->getOperand(i));
842
843 // Delete the pseudo instruction TCRETURN.
844 MBB.erase(MBBI);
845 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
846 (X86FI->getTCReturnAddrDelta() < 0)) {
847 // Add the return addr area delta back since we are not tail calling.
848 int delta = -1*X86FI->getTCReturnAddrDelta();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000849 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000850
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000851 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +0000852 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +0000853 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000854 }
855}
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000856
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000857int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
Anton Korobeynikov82f58742010-11-20 15:59:32 +0000858 const X86RegisterInfo *RI =
859 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
860 const MachineFrameInfo *MFI = MF.getFrameInfo();
861 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
862 uint64_t StackSize = MFI->getStackSize();
863
864 if (RI->needsStackRealignment(MF)) {
865 if (FI < 0) {
866 // Skip the saved EBP.
867 Offset += RI->getSlotSize();
868 } else {
869 unsigned Align = MFI->getObjectAlignment(FI);
870 assert((-(Offset + StackSize)) % Align == 0);
871 Align = 0;
872 return Offset + StackSize;
873 }
874 // FIXME: Support tail calls
875 } else {
876 if (!hasFP(MF))
877 return Offset + StackSize;
878
879 // Skip the saved EBP.
880 Offset += RI->getSlotSize();
881
882 // Skip the RETADDR move area
883 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
884 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
885 if (TailCallReturnAddrDelta < 0)
886 Offset -= TailCallReturnAddrDelta;
887 }
888
889 return Offset;
890}
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000891
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000892bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000893 MachineBasicBlock::iterator MI,
894 const std::vector<CalleeSavedInfo> &CSI,
895 const TargetRegisterInfo *TRI) const {
896 if (CSI.empty())
897 return false;
898
899 DebugLoc DL = MBB.findDebugLoc(MI);
900
901 MachineFunction &MF = *MBB.getParent();
902
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000903 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
904 unsigned FPReg = TRI->getFrameRegister(MF);
905 unsigned CalleeFrameSize = 0;
906
907 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
908 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
909
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000910 // Push GPRs. It increases frame size.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000911 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
912 for (unsigned i = CSI.size(); i != 0; --i) {
913 unsigned Reg = CSI[i-1].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000914 if (!X86::GR64RegClass.contains(Reg) &&
915 !X86::GR32RegClass.contains(Reg))
916 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000917 // Add the callee-saved register as live-in. It's killed at the spill.
918 MBB.addLiveIn(Reg);
919 if (Reg == FPReg)
920 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
921 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000922 CalleeFrameSize += SlotSize;
Charles Davisaff232a2011-06-12 01:45:54 +0000923 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
924 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000925 }
926
927 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000928
929 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
930 // It can be done by spilling XMMs to stack frame.
931 // Note that only Win64 ABI might spill XMMs.
932 for (unsigned i = CSI.size(); i != 0; --i) {
933 unsigned Reg = CSI[i-1].getReg();
934 if (X86::GR64RegClass.contains(Reg) ||
935 X86::GR32RegClass.contains(Reg))
936 continue;
937 // Add the callee-saved register as live-in. It's killed at the spill.
938 MBB.addLiveIn(Reg);
939 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
940 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
941 RC, TRI);
942 }
943
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000944 return true;
945}
946
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000947bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000948 MachineBasicBlock::iterator MI,
949 const std::vector<CalleeSavedInfo> &CSI,
950 const TargetRegisterInfo *TRI) const {
951 if (CSI.empty())
952 return false;
953
954 DebugLoc DL = MBB.findDebugLoc(MI);
955
956 MachineFunction &MF = *MBB.getParent();
957 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000958
959 // Reload XMMs from stack frame.
960 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
961 unsigned Reg = CSI[i].getReg();
962 if (X86::GR64RegClass.contains(Reg) ||
963 X86::GR32RegClass.contains(Reg))
964 continue;
965 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
966 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
967 RC, TRI);
968 }
969
970 // POP GPRs.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000971 unsigned FPReg = TRI->getFrameRegister(MF);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000972 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
973 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
974 unsigned Reg = CSI[i].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000975 if (!X86::GR64RegClass.contains(Reg) &&
976 !X86::GR32RegClass.contains(Reg))
977 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000978 if (Reg == FPReg)
979 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
980 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000981 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000982 }
983 return true;
984}
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +0000985
986void
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000987X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +0000988 RegScavenger *RS) const {
989 MachineFrameInfo *MFI = MF.getFrameInfo();
990 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
991 unsigned SlotSize = RegInfo->getSlotSize();
992
993 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
994 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
995
996 if (TailCallReturnAddrDelta < 0) {
997 // create RETURNADDR area
998 // arg
999 // arg
1000 // RETADDR
1001 // { ...
1002 // RETADDR area
1003 // ...
1004 // }
1005 // [EBP]
1006 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1007 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1008 }
1009
1010 if (hasFP(MF)) {
1011 assert((TailCallReturnAddrDelta <= 0) &&
1012 "The Delta should always be zero or negative");
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001013 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001014
1015 // Create a frame entry for the EBP register that must be saved.
1016 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1017 -(int)SlotSize +
1018 TFI.getOffsetOfLocalArea() +
1019 TailCallReturnAddrDelta,
1020 true);
1021 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1022 "Slot for EBP register must be last in order to be found!");
1023 FrameIdx = 0;
1024 }
1025}