blob: 17c87e87f9fa59c141cc17159276143c7bce7d4e [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();
461 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
462
463 // Define the current CFA rule to use the provided offset.
464 if (StackSize) {
465 MachineLocation SPDst(MachineLocation::VirtualFP);
466 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
467 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
468 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000469 MachineLocation SPDst(StackPtr);
470 MachineLocation SPSrc(StackPtr, stackGrowth);
471 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
472 }
473
474 // Change the rule for the FramePtr to be an "offset" rule.
475 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
476 MachineLocation FPSrc(FramePtr);
477 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
478 }
479
480 // Update EBP with the new base value...
481 BuildMI(MBB, MBBI, DL,
482 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000483 .addReg(StackPtr)
484 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000485
486 if (needsFrameMoves) {
487 // Mark effective beginning of when frame pointer becomes valid.
488 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
489 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(FrameLabel);
490
491 // Define the current CFA to use the EBP/RBP register.
492 MachineLocation FPDst(FramePtr);
493 MachineLocation FPSrc(MachineLocation::VirtualFP);
494 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
495 }
496
497 // Mark the FramePtr as live-in in every block except the entry.
498 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
499 I != E; ++I)
500 I->addLiveIn(FramePtr);
501
502 // Realign stack
503 if (RegInfo->needsStackRealignment(MF)) {
504 MachineInstr *MI =
505 BuildMI(MBB, MBBI, DL,
506 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri),
507 StackPtr).addReg(StackPtr).addImm(-MaxAlign);
508
509 // The EFLAGS implicit def is dead.
510 MI->getOperand(3).setIsDead();
511 }
512 } else {
513 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
514 }
515
516 // Skip the callee-saved push instructions.
517 bool PushedRegs = false;
518 int StackOffset = 2 * stackGrowth;
519
520 while (MBBI != MBB.end() &&
521 (MBBI->getOpcode() == X86::PUSH32r ||
522 MBBI->getOpcode() == X86::PUSH64r)) {
523 PushedRegs = true;
524 ++MBBI;
525
526 if (!HasFP && needsFrameMoves) {
527 // Mark callee-saved push instruction.
528 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
529 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
530
531 // Define the current CFA rule to use the provided offset.
532 unsigned Ptr = StackSize ?
533 MachineLocation::VirtualFP : StackPtr;
534 MachineLocation SPDst(Ptr);
535 MachineLocation SPSrc(Ptr, StackOffset);
536 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
537 StackOffset += stackGrowth;
538 }
539 }
540
541 DL = MBB.findDebugLoc(MBBI);
542
543 // If there is an SUB32ri of ESP immediately before this instruction, merge
544 // the two. This can be the case when tail call elimination is enabled and
545 // the callee has more arguments then the caller.
546 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
547
548 // If there is an ADD32ri or SUB32ri of ESP immediately after this
549 // instruction, merge the two instructions.
550 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
551
552 // Adjust stack pointer: ESP -= numbytes.
553
554 // Windows and cygwin/mingw require a prologue helper routine when allocating
555 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
556 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
557 // stack and adjust the stack pointer in one go. The 64-bit version of
558 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
559 // responsible for adjusting the stack pointer. Touching the stack at 4K
560 // increments is necessary to ensure that the guard pages used by the OS
561 // virtual memory manager are allocated in correct sequence.
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000562 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
563 const char *StackProbeSymbol;
564 bool isSPUpdateNeeded = false;
565
566 if (Is64Bit) {
567 if (STI.isTargetCygMing())
568 StackProbeSymbol = "___chkstk";
569 else {
570 StackProbeSymbol = "__chkstk";
571 isSPUpdateNeeded = true;
572 }
573 } else if (STI.isTargetCygMing())
574 StackProbeSymbol = "_alloca";
575 else
576 StackProbeSymbol = "_chkstk";
577
Anton Korobeynikov33464912010-11-15 00:06:54 +0000578 // Check whether EAX is livein for this function.
579 bool isEAXAlive = isEAXLiveIn(MF);
580
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000581 if (isEAXAlive) {
582 // Sanity check that EAX is not livein for this function.
583 // It should not be, so throw an assert.
584 assert(!Is64Bit && "EAX is livein in x64 case!");
585
Anton Korobeynikov33464912010-11-15 00:06:54 +0000586 // Save EAX
587 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
588 .addReg(X86::EAX, RegState::Kill);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000589 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000590
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000591 if (Is64Bit) {
592 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
593 // Function prologue is responsible for adjusting the stack pointer.
594 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
595 .addImm(NumBytes);
596 } else {
597 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
598 // We'll also use 4 already allocated bytes for EAX.
599 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
600 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes);
601 }
602
603 BuildMI(MBB, MBBI, DL,
604 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
605 .addExternalSymbol(StackProbeSymbol)
606 .addReg(StackPtr, RegState::Define | RegState::Implicit)
607 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
608
609 // MSVC x64's __chkstk needs to adjust %rsp.
610 // FIXME: %rax preserves the offset and should be available.
611 if (isSPUpdateNeeded)
612 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
613 TII, *RegInfo);
614
615 if (isEAXAlive) {
616 // Restore EAX
617 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
618 X86::EAX),
619 StackPtr, false, NumBytes - 4);
620 MBB.insert(MBBI, MI);
621 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000622 } else if (NumBytes)
Evan Cheng7158e082011-01-03 22:53:22 +0000623 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
624 TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000625
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000626 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000627 // Mark end of stack pointer adjustment.
628 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
629 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
630
631 if (!HasFP && NumBytes) {
632 // Define the current CFA rule to use the provided offset.
633 if (StackSize) {
634 MachineLocation SPDst(MachineLocation::VirtualFP);
635 MachineLocation SPSrc(MachineLocation::VirtualFP,
636 -StackSize + stackGrowth);
637 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
638 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000639 MachineLocation SPDst(StackPtr);
640 MachineLocation SPSrc(StackPtr, stackGrowth);
641 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
642 }
643 }
644
645 // Emit DWARF info specifying the offsets of the callee-saved registers.
646 if (PushedRegs)
647 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
648 }
649}
650
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000651void X86FrameLowering::emitEpilogue(MachineFunction &MF,
Nick Lewycky3c2f0a12011-06-14 03:23:52 +0000652 MachineBasicBlock &MBB) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000653 const MachineFrameInfo *MFI = MF.getFrameInfo();
654 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000655 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
656 const X86InstrInfo &TII = *TM.getInstrInfo();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000657 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
658 assert(MBBI != MBB.end() && "Returning block has no instructions");
Anton Korobeynikov33464912010-11-15 00:06:54 +0000659 unsigned RetOpcode = MBBI->getOpcode();
660 DebugLoc DL = MBBI->getDebugLoc();
661 bool Is64Bit = STI.is64Bit();
662 unsigned StackAlign = getStackAlignment();
663 unsigned SlotSize = RegInfo->getSlotSize();
664 unsigned FramePtr = RegInfo->getFrameRegister(MF);
665 unsigned StackPtr = RegInfo->getStackRegister();
666
667 switch (RetOpcode) {
668 default:
669 llvm_unreachable("Can only insert epilog into returning blocks");
670 case X86::RET:
671 case X86::RETI:
672 case X86::TCRETURNdi:
673 case X86::TCRETURNri:
674 case X86::TCRETURNmi:
675 case X86::TCRETURNdi64:
676 case X86::TCRETURNri64:
677 case X86::TCRETURNmi64:
678 case X86::EH_RETURN:
679 case X86::EH_RETURN64:
680 break; // These are ok
681 }
682
683 // Get the number of bytes to allocate from the FrameInfo.
684 uint64_t StackSize = MFI->getStackSize();
685 uint64_t MaxAlign = MFI->getMaxAlignment();
686 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
687 uint64_t NumBytes = 0;
688
689 // If we're forcing a stack realignment we can't rely on just the frame
690 // info, we need to know the ABI stack alignment as well in case we
691 // have a call out. Otherwise just make sure we have some alignment - we'll
692 // go with the minimum.
693 if (ForceStackAlign) {
694 if (MFI->hasCalls())
695 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
696 else
697 MaxAlign = MaxAlign ? MaxAlign : 4;
698 }
699
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000700 if (hasFP(MF)) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000701 // Calculate required stack adjustment.
702 uint64_t FrameSize = StackSize - SlotSize;
703 if (RegInfo->needsStackRealignment(MF))
704 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
705
706 NumBytes = FrameSize - CSSize;
707
708 // Pop EBP.
709 BuildMI(MBB, MBBI, DL,
710 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
711 } else {
712 NumBytes = StackSize - CSSize;
713 }
714
715 // Skip the callee-saved pop instructions.
716 MachineBasicBlock::iterator LastCSPop = MBBI;
717 while (MBBI != MBB.begin()) {
718 MachineBasicBlock::iterator PI = prior(MBBI);
719 unsigned Opc = PI->getOpcode();
720
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000721 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
Anton Korobeynikov33464912010-11-15 00:06:54 +0000722 !PI->getDesc().isTerminator())
723 break;
724
725 --MBBI;
726 }
727
728 DL = MBBI->getDebugLoc();
729
730 // If there is an ADD32ri or SUB32ri of ESP immediately before this
731 // instruction, merge the two instructions.
732 if (NumBytes || MFI->hasVarSizedObjects())
733 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
734
735 // If dynamic alloca is used, then reset esp to point to the last callee-saved
736 // slot before popping them off! Same applies for the case, when stack was
737 // realigned.
738 if (RegInfo->needsStackRealignment(MF)) {
739 // We cannot use LEA here, because stack pointer was realigned. We need to
740 // deallocate local frame back.
741 if (CSSize) {
Evan Cheng7158e082011-01-03 22:53:22 +0000742 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000743 MBBI = prior(LastCSPop);
744 }
745
746 BuildMI(MBB, MBBI, DL,
747 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
748 StackPtr).addReg(FramePtr);
749 } else if (MFI->hasVarSizedObjects()) {
750 if (CSSize) {
751 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
752 MachineInstr *MI =
753 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
754 FramePtr, false, -CSSize);
755 MBB.insert(MBBI, MI);
756 } else {
757 BuildMI(MBB, MBBI, DL,
758 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
759 .addReg(FramePtr);
760 }
761 } else if (NumBytes) {
762 // Adjust stack pointer back: ESP += numbytes.
Evan Cheng7158e082011-01-03 22:53:22 +0000763 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000764 }
765
766 // We're returning from function via eh_return.
767 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000768 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000769 MachineOperand &DestAddr = MBBI->getOperand(0);
770 assert(DestAddr.isReg() && "Offset should be in register!");
771 BuildMI(MBB, MBBI, DL,
772 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
773 StackPtr).addReg(DestAddr.getReg());
774 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
775 RetOpcode == X86::TCRETURNmi ||
776 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
777 RetOpcode == X86::TCRETURNmi64) {
778 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
779 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesenf7ca9762011-01-13 22:47:43 +0000780 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000781 MachineOperand &JumpTarget = MBBI->getOperand(0);
782 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
783 assert(StackAdjust.isImm() && "Expecting immediate value.");
784
785 // Adjust stack pointer.
786 int StackAdj = StackAdjust.getImm();
787 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
788 int Offset = 0;
789 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
790
791 // Incoporate the retaddr area.
792 Offset = StackAdj-MaxTCDelta;
793 assert(Offset >= 0 && "Offset should never be negative");
794
795 if (Offset) {
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000796 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +0000797 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +0000798 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000799 }
800
801 // Jump to label or value in register.
802 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
Evan Cheng3d2125c2010-11-30 23:55:39 +0000803 MachineInstrBuilder MIB =
804 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
805 ? X86::TAILJMPd : X86::TAILJMPd64));
806 if (JumpTarget.isGlobal())
807 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
808 JumpTarget.getTargetFlags());
809 else {
810 assert(JumpTarget.isSymbol());
811 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
812 JumpTarget.getTargetFlags());
813 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000814 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
815 MachineInstrBuilder MIB =
816 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
817 ? X86::TAILJMPm : X86::TAILJMPm64));
818 for (unsigned i = 0; i != 5; ++i)
819 MIB.addOperand(MBBI->getOperand(i));
820 } else if (RetOpcode == X86::TCRETURNri64) {
821 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
822 addReg(JumpTarget.getReg(), RegState::Kill);
823 } else {
824 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
825 addReg(JumpTarget.getReg(), RegState::Kill);
826 }
827
828 MachineInstr *NewMI = prior(MBBI);
829 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
830 NewMI->addOperand(MBBI->getOperand(i));
831
832 // Delete the pseudo instruction TCRETURN.
833 MBB.erase(MBBI);
834 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
835 (X86FI->getTCReturnAddrDelta() < 0)) {
836 // Add the return addr area delta back since we are not tail calling.
837 int delta = -1*X86FI->getTCReturnAddrDelta();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000838 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000839
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000840 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +0000841 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +0000842 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000843 }
844}
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000845
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000846int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
Anton Korobeynikov82f58742010-11-20 15:59:32 +0000847 const X86RegisterInfo *RI =
848 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
849 const MachineFrameInfo *MFI = MF.getFrameInfo();
850 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
851 uint64_t StackSize = MFI->getStackSize();
852
853 if (RI->needsStackRealignment(MF)) {
854 if (FI < 0) {
855 // Skip the saved EBP.
856 Offset += RI->getSlotSize();
857 } else {
858 unsigned Align = MFI->getObjectAlignment(FI);
859 assert((-(Offset + StackSize)) % Align == 0);
860 Align = 0;
861 return Offset + StackSize;
862 }
863 // FIXME: Support tail calls
864 } else {
865 if (!hasFP(MF))
866 return Offset + StackSize;
867
868 // Skip the saved EBP.
869 Offset += RI->getSlotSize();
870
871 // Skip the RETADDR move area
872 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
873 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
874 if (TailCallReturnAddrDelta < 0)
875 Offset -= TailCallReturnAddrDelta;
876 }
877
878 return Offset;
879}
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000880
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000881bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000882 MachineBasicBlock::iterator MI,
883 const std::vector<CalleeSavedInfo> &CSI,
884 const TargetRegisterInfo *TRI) const {
885 if (CSI.empty())
886 return false;
887
888 DebugLoc DL = MBB.findDebugLoc(MI);
889
890 MachineFunction &MF = *MBB.getParent();
891
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000892 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
893 unsigned FPReg = TRI->getFrameRegister(MF);
894 unsigned CalleeFrameSize = 0;
895
896 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
897 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
898
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000899 // Push GPRs. It increases frame size.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000900 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
901 for (unsigned i = CSI.size(); i != 0; --i) {
902 unsigned Reg = CSI[i-1].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000903 if (!X86::GR64RegClass.contains(Reg) &&
904 !X86::GR32RegClass.contains(Reg))
905 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000906 // Add the callee-saved register as live-in. It's killed at the spill.
907 MBB.addLiveIn(Reg);
908 if (Reg == FPReg)
909 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
910 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000911 CalleeFrameSize += SlotSize;
Charles Davisaff232a2011-06-12 01:45:54 +0000912 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
913 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000914 }
915
916 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000917
918 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
919 // It can be done by spilling XMMs to stack frame.
920 // Note that only Win64 ABI might spill XMMs.
921 for (unsigned i = CSI.size(); i != 0; --i) {
922 unsigned Reg = CSI[i-1].getReg();
923 if (X86::GR64RegClass.contains(Reg) ||
924 X86::GR32RegClass.contains(Reg))
925 continue;
926 // Add the callee-saved register as live-in. It's killed at the spill.
927 MBB.addLiveIn(Reg);
928 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
929 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
930 RC, TRI);
931 }
932
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000933 return true;
934}
935
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000936bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000937 MachineBasicBlock::iterator MI,
938 const std::vector<CalleeSavedInfo> &CSI,
939 const TargetRegisterInfo *TRI) const {
940 if (CSI.empty())
941 return false;
942
943 DebugLoc DL = MBB.findDebugLoc(MI);
944
945 MachineFunction &MF = *MBB.getParent();
946 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000947
948 // Reload XMMs from stack frame.
949 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
950 unsigned Reg = CSI[i].getReg();
951 if (X86::GR64RegClass.contains(Reg) ||
952 X86::GR32RegClass.contains(Reg))
953 continue;
954 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
955 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
956 RC, TRI);
957 }
958
959 // POP GPRs.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000960 unsigned FPReg = TRI->getFrameRegister(MF);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000961 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
962 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
963 unsigned Reg = CSI[i].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000964 if (!X86::GR64RegClass.contains(Reg) &&
965 !X86::GR32RegClass.contains(Reg))
966 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000967 if (Reg == FPReg)
968 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
969 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +0000970 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +0000971 }
972 return true;
973}
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +0000974
975void
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000976X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +0000977 RegScavenger *RS) const {
978 MachineFrameInfo *MFI = MF.getFrameInfo();
979 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
980 unsigned SlotSize = RegInfo->getSlotSize();
981
982 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
983 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
984
985 if (TailCallReturnAddrDelta < 0) {
986 // create RETURNADDR area
987 // arg
988 // arg
989 // RETADDR
990 // { ...
991 // RETADDR area
992 // ...
993 // }
994 // [EBP]
995 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
996 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
997 }
998
999 if (hasFP(MF)) {
1000 assert((TailCallReturnAddrDelta <= 0) &&
1001 "The Delta should always be zero or negative");
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001002 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001003
1004 // Create a frame entry for the EBP register that must be saved.
1005 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1006 -(int)SlotSize +
1007 TFI.getOffsetOfLocalArea() +
1008 TailCallReturnAddrDelta,
1009 true);
1010 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1011 "Slot for EBP register must be last in order to be found!");
1012 FrameIdx = 0;
1013 }
1014}