blob: cdc83054aa03d7f2d409c536b1ed4de2a8abbbd8 [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
Bill Wendling39055b32011-07-25 20:15:15 +000037// FIXME: Remove once linker support is available. The feature exists only on
38// Darwin at the moment.
Bill Wendlingc57e7db2011-07-25 18:04:49 +000039static cl::opt<bool>
40GenerateCompactUnwind("gen-compact-unwind",
41 cl::desc("Generate compact unwind encoding"),
42 cl::Hidden);
43
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000044bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000045 return !MF.getFrameInfo()->hasVarSizedObjects();
46}
47
48/// hasFP - Return true if the specified function should have a dedicated frame
49/// pointer register. This is true if the function has variable sized allocas
50/// or if frame pointer elimination is disabled.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +000051bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000052 const MachineFrameInfo *MFI = MF.getFrameInfo();
53 const MachineModuleInfo &MMI = MF.getMMI();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +000054 const TargetRegisterInfo *RI = TM.getRegisterInfo();
Anton Korobeynikovd0c38172010-11-18 21:19:35 +000055
56 return (DisableFramePointerElim(MF) ||
57 RI->needsStackRealignment(MF) ||
58 MFI->hasVarSizedObjects() ||
59 MFI->isFrameAddressTaken() ||
60 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
61 MMI.callsUnwindInit());
62}
63
Anton Korobeynikov33464912010-11-15 00:06:54 +000064static unsigned getSUBriOpcode(unsigned is64Bit, int64_t Imm) {
65 if (is64Bit) {
66 if (isInt<8>(Imm))
67 return X86::SUB64ri8;
68 return X86::SUB64ri32;
69 } else {
70 if (isInt<8>(Imm))
71 return X86::SUB32ri8;
72 return X86::SUB32ri;
73 }
74}
75
76static unsigned getADDriOpcode(unsigned is64Bit, int64_t Imm) {
77 if (is64Bit) {
78 if (isInt<8>(Imm))
79 return X86::ADD64ri8;
80 return X86::ADD64ri32;
81 } else {
82 if (isInt<8>(Imm))
83 return X86::ADD32ri8;
84 return X86::ADD32ri;
85 }
86}
87
Evan Cheng7158e082011-01-03 22:53:22 +000088/// findDeadCallerSavedReg - Return a caller-saved register that isn't live
89/// when it reaches the "return" instruction. We can then pop a stack object
90/// to this register without worry about clobbering it.
91static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
92 MachineBasicBlock::iterator &MBBI,
93 const TargetRegisterInfo &TRI,
94 bool Is64Bit) {
95 const MachineFunction *MF = MBB.getParent();
96 const Function *F = MF->getFunction();
97 if (!F || MF->getMMI().callsEHReturn())
98 return 0;
99
100 static const unsigned CallerSavedRegs32Bit[] = {
101 X86::EAX, X86::EDX, X86::ECX
102 };
103
104 static const unsigned CallerSavedRegs64Bit[] = {
105 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
106 X86::R8, X86::R9, X86::R10, X86::R11
107 };
108
109 unsigned Opc = MBBI->getOpcode();
110 switch (Opc) {
111 default: return 0;
112 case X86::RET:
113 case X86::RETI:
114 case X86::TCRETURNdi:
115 case X86::TCRETURNri:
116 case X86::TCRETURNmi:
117 case X86::TCRETURNdi64:
118 case X86::TCRETURNri64:
119 case X86::TCRETURNmi64:
120 case X86::EH_RETURN:
121 case X86::EH_RETURN64: {
122 SmallSet<unsigned, 8> Uses;
123 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
124 MachineOperand &MO = MBBI->getOperand(i);
125 if (!MO.isReg() || MO.isDef())
126 continue;
127 unsigned Reg = MO.getReg();
128 if (!Reg)
129 continue;
130 for (const unsigned *AsI = TRI.getOverlaps(Reg); *AsI; ++AsI)
131 Uses.insert(*AsI);
132 }
133
134 const unsigned *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
135 for (; *CS; ++CS)
136 if (!Uses.count(*CS))
137 return *CS;
138 }
139 }
140
141 return 0;
142}
143
144
Anton Korobeynikov33464912010-11-15 00:06:54 +0000145/// emitSPUpdate - Emit a series of instructions to increment / decrement the
146/// stack pointer by a constant value.
147static
148void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
Evan Cheng7158e082011-01-03 22:53:22 +0000149 unsigned StackPtr, int64_t NumBytes,
150 bool Is64Bit, const TargetInstrInfo &TII,
151 const TargetRegisterInfo &TRI) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000152 bool isSub = NumBytes < 0;
153 uint64_t Offset = isSub ? -NumBytes : NumBytes;
154 unsigned Opc = isSub ?
155 getSUBriOpcode(Is64Bit, Offset) :
156 getADDriOpcode(Is64Bit, Offset);
157 uint64_t Chunk = (1LL << 31) - 1;
158 DebugLoc DL = MBB.findDebugLoc(MBBI);
159
160 while (Offset) {
161 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
Evan Cheng7158e082011-01-03 22:53:22 +0000162 if (ThisVal == (Is64Bit ? 8 : 4)) {
163 // Use push / pop instead.
164 unsigned Reg = isSub
Dale Johannesen1e08cd12011-01-04 19:31:24 +0000165 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
Evan Cheng7158e082011-01-03 22:53:22 +0000166 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
167 if (Reg) {
168 Opc = isSub
169 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
170 : (Is64Bit ? X86::POP64r : X86::POP32r);
Charles Davisaff232a2011-06-12 01:45:54 +0000171 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
Evan Cheng7158e082011-01-03 22:53:22 +0000172 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
Charles Davisaff232a2011-06-12 01:45:54 +0000173 if (isSub)
174 MI->setFlag(MachineInstr::FrameSetup);
Evan Cheng7158e082011-01-03 22:53:22 +0000175 Offset -= ThisVal;
176 continue;
177 }
178 }
179
Anton Korobeynikov33464912010-11-15 00:06:54 +0000180 MachineInstr *MI =
181 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
Evan Cheng7158e082011-01-03 22:53:22 +0000182 .addReg(StackPtr)
183 .addImm(ThisVal);
Charles Davisaff232a2011-06-12 01:45:54 +0000184 if (isSub)
185 MI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000186 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
187 Offset -= ThisVal;
188 }
189}
190
191/// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
192static
193void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
194 unsigned StackPtr, uint64_t *NumBytes = NULL) {
195 if (MBBI == MBB.begin()) return;
196
197 MachineBasicBlock::iterator PI = prior(MBBI);
198 unsigned Opc = PI->getOpcode();
199 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
200 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
201 PI->getOperand(0).getReg() == StackPtr) {
202 if (NumBytes)
203 *NumBytes += PI->getOperand(2).getImm();
204 MBB.erase(PI);
205 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
206 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
207 PI->getOperand(0).getReg() == StackPtr) {
208 if (NumBytes)
209 *NumBytes -= PI->getOperand(2).getImm();
210 MBB.erase(PI);
211 }
212}
213
214/// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower iterator.
215static
216void mergeSPUpdatesDown(MachineBasicBlock &MBB,
217 MachineBasicBlock::iterator &MBBI,
218 unsigned StackPtr, uint64_t *NumBytes = NULL) {
219 // FIXME: THIS ISN'T RUN!!!
220 return;
221
222 if (MBBI == MBB.end()) return;
223
224 MachineBasicBlock::iterator NI = llvm::next(MBBI);
225 if (NI == MBB.end()) return;
226
227 unsigned Opc = NI->getOpcode();
228 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
229 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
230 NI->getOperand(0).getReg() == StackPtr) {
231 if (NumBytes)
232 *NumBytes -= NI->getOperand(2).getImm();
233 MBB.erase(NI);
234 MBBI = NI;
235 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
236 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
237 NI->getOperand(0).getReg() == StackPtr) {
238 if (NumBytes)
239 *NumBytes += NI->getOperand(2).getImm();
240 MBB.erase(NI);
241 MBBI = NI;
242 }
243}
244
245/// mergeSPUpdates - Checks the instruction before/after the passed
246/// instruction. If it is an ADD/SUB instruction it is deleted argument and the
247/// stack adjustment is returned as a positive value for ADD and a negative for
248/// SUB.
249static int mergeSPUpdates(MachineBasicBlock &MBB,
250 MachineBasicBlock::iterator &MBBI,
251 unsigned StackPtr,
252 bool doMergeWithPrevious) {
253 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
254 (!doMergeWithPrevious && MBBI == MBB.end()))
255 return 0;
256
257 MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
258 MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : llvm::next(MBBI);
259 unsigned Opc = PI->getOpcode();
260 int Offset = 0;
261
262 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
263 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
264 PI->getOperand(0).getReg() == StackPtr){
265 Offset += PI->getOperand(2).getImm();
266 MBB.erase(PI);
267 if (!doMergeWithPrevious) MBBI = NI;
268 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
269 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
270 PI->getOperand(0).getReg() == StackPtr) {
271 Offset -= PI->getOperand(2).getImm();
272 MBB.erase(PI);
273 if (!doMergeWithPrevious) MBBI = NI;
274 }
275
276 return Offset;
277}
278
279static bool isEAXLiveIn(MachineFunction &MF) {
280 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
281 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
282 unsigned Reg = II->first;
283
284 if (Reg == X86::EAX || Reg == X86::AX ||
285 Reg == X86::AH || Reg == X86::AL)
286 return true;
287 }
288
289 return false;
290}
291
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000292void X86FrameLowering::emitCalleeSavedFrameMoves(MachineFunction &MF,
Bill Wendling09b02c82011-07-25 18:00:28 +0000293 MCSymbol *Label,
294 unsigned FramePtr) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000295 MachineFrameInfo *MFI = MF.getFrameInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000296 MachineModuleInfo &MMI = MF.getMMI();
297
298 // Add callee saved registers to move list.
299 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
300 if (CSI.empty()) return;
301
302 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000303 const TargetData *TD = TM.getTargetData();
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000304 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000305
306 // Calculate amount of bytes used for return address storing.
Anton Korobeynikove7499112011-01-14 21:57:58 +0000307 int stackGrowth = -TD->getPointerSize();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000308
309 // FIXME: This is dirty hack. The code itself is pretty mess right now.
310 // It should be rewritten from scratch and generalized sometimes.
311
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000312 // Determine maximum offset (minimum due to stack growth).
Anton Korobeynikov33464912010-11-15 00:06:54 +0000313 int64_t MaxOffset = 0;
314 for (std::vector<CalleeSavedInfo>::const_iterator
315 I = CSI.begin(), E = CSI.end(); I != E; ++I)
316 MaxOffset = std::min(MaxOffset,
317 MFI->getObjectOffset(I->getFrameIdx()));
318
319 // Calculate offsets.
320 int64_t saveAreaOffset = (HasFP ? 3 : 2) * stackGrowth;
321 for (std::vector<CalleeSavedInfo>::const_iterator
322 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
323 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
324 unsigned Reg = I->getReg();
325 Offset = MaxOffset - Offset + saveAreaOffset;
326
327 // Don't output a new machine move if we're re-saving the frame
328 // pointer. This happens when the PrologEpilogInserter has inserted an extra
329 // "PUSH" of the frame pointer -- the "emitPrologue" method automatically
330 // generates one when frame pointers are used. If we generate a "machine
331 // move" for this extra "PUSH", the linker will lose track of the fact that
332 // the frame pointer should have the value of the first "PUSH" when it's
333 // trying to unwind.
NAKAMURA Takumi27635382011-02-05 15:10:54 +0000334 //
Anton Korobeynikov33464912010-11-15 00:06:54 +0000335 // FIXME: This looks inelegant. It's possibly correct, but it's covering up
336 // another bug. I.e., one where we generate a prolog like this:
337 //
338 // pushl %ebp
339 // movl %esp, %ebp
340 // pushl %ebp
341 // pushl %esi
342 // ...
343 //
344 // The immediate re-push of EBP is unnecessary. At the least, it's an
345 // optimization bug. EBP can be used as a scratch register in certain
346 // cases, but probably not when we have a frame pointer.
347 if (HasFP && FramePtr == Reg)
348 continue;
349
350 MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
351 MachineLocation CSSrc(Reg);
352 Moves.push_back(MachineMove(Label, CSDst, CSSrc));
353 }
354}
355
Bill Wendling09b02c82011-07-25 18:00:28 +0000356/// getCompactUnwindRegNum - Get the compact unwind number for a given
357/// register. The number corresponds to the enum lists in
358/// compact_unwind_encoding.h.
359static int getCompactUnwindRegNum(const unsigned *CURegs, unsigned Reg) {
360 int Idx = 1;
361 for (; *CURegs; ++CURegs, ++Idx)
362 if (*CURegs == Reg)
363 return Idx;
364
365 return -1;
366}
367
368/// encodeCompactUnwindRegistersWithoutFrame - Create the permutation encoding
369/// used with frameless stacks. It is passed the number of registers to be saved
370/// and an array of the registers saved.
371static uint32_t encodeCompactUnwindRegistersWithoutFrame(unsigned SavedRegs[6],
372 unsigned RegCount,
373 bool Is64Bit) {
374 // The saved registers are numbered from 1 to 6. In order to encode the order
375 // in which they were saved, we re-number them according to their place in the
376 // register order. The re-numbering is relative to the last re-numbered
377 // register. E.g., if we have registers {6, 2, 4, 5} saved in that order:
378 //
379 // Orig Re-Num
380 // ---- ------
381 // 6 6
382 // 2 2
383 // 4 3
384 // 5 3
385 //
386 static const unsigned CU32BitRegs[] = {
387 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
388 };
389 static const unsigned CU64BitRegs[] = {
390 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
391 };
392 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
393
394 uint32_t RenumRegs[6];
395 for (unsigned i = 6 - RegCount; i < 6; ++i) {
396 int CUReg = getCompactUnwindRegNum(CURegs, SavedRegs[i]);
397 if (CUReg == -1) return ~0U;
398 SavedRegs[i] = CUReg;
399
400 unsigned Countless = 0;
401 for (unsigned j = 6 - RegCount; j < i; ++j)
402 if (SavedRegs[j] < SavedRegs[i])
403 ++Countless;
404
405 RenumRegs[i] = SavedRegs[i] - Countless - 1;
406 }
407
408 // Take the renumbered values and encode them into a 10-bit number.
409 uint32_t permutationEncoding = 0;
410 switch (RegCount) {
411 case 6:
412 permutationEncoding |= 120 * RenumRegs[0] + 24 * RenumRegs[1]
413 + 6 * RenumRegs[2] + 2 * RenumRegs[3]
414 + RenumRegs[4];
415 break;
416 case 5:
417 permutationEncoding |= 120 * RenumRegs[1] + 24 * RenumRegs[2]
418 + 6 * RenumRegs[3] + 2 * RenumRegs[4]
419 + RenumRegs[5];
420 break;
421 case 4:
422 permutationEncoding |= 60 * RenumRegs[2] + 12 * RenumRegs[3]
423 + 3 * RenumRegs[4] + RenumRegs[5];
424 break;
425 case 3:
426 permutationEncoding |= 20 * RenumRegs[3] + 4 * RenumRegs[4]
427 + RenumRegs[5];
428 break;
429 case 2:
430 permutationEncoding |= 5 * RenumRegs[4] + RenumRegs[5];
431 break;
432 case 1:
433 permutationEncoding |= RenumRegs[5];
434 break;
435 }
436
437 assert((permutationEncoding & 0x3FF) == permutationEncoding &&
438 "Invalid compact register encoding!");
439 return permutationEncoding;
440}
441
442/// encodeCompactUnwindRegistersWithFrame - Return the registers encoded for a
443/// compact encoding with a frame pointer.
444static uint32_t encodeCompactUnwindRegistersWithFrame(unsigned SavedRegs[6],
445 bool Is64Bit) {
446 static const unsigned CU32BitRegs[] = {
447 X86::EBX, X86::ECX, X86::EDX, X86::EDI, X86::ESI, X86::EBP, 0
448 };
449 static const unsigned CU64BitRegs[] = {
450 X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
451 };
452 const unsigned *CURegs = (Is64Bit ? CU64BitRegs : CU32BitRegs);
453
454 // Encode the registers in the order they were saved, 3-bits per register. The
455 // registers are numbered from 1 to 6.
456 uint32_t RegEnc = 0;
457 for (int I = 5; I >= 0; --I) {
458 unsigned Reg = SavedRegs[I];
459 if (Reg == 0) break;
460 int CURegNum = getCompactUnwindRegNum(CURegs, Reg);
461 if (CURegNum == -1)
462 return ~0U;
463 RegEnc |= (CURegNum & 0x7) << (5 - I);
464 }
465
466 assert((RegEnc & 0x7FFF) == RegEnc && "Invalid compact register encoding!");
467 return RegEnc;
468}
469
470uint32_t X86FrameLowering::getCompactUnwindEncoding(MachineFunction &MF) const {
471 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
472 unsigned FramePtr = RegInfo->getFrameRegister(MF);
473 unsigned StackPtr = RegInfo->getStackRegister();
474
475 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
476 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
477
478 bool Is64Bit = STI.is64Bit();
479 bool HasFP = hasFP(MF);
480
481 unsigned SavedRegs[6] = { 0, 0, 0, 0, 0, 0 };
482 int SavedRegIdx = 6;
483
484 unsigned OffsetSize = (Is64Bit ? 8 : 4);
485
486 unsigned PushInstr = (Is64Bit ? X86::PUSH64r : X86::PUSH32r);
487 unsigned PushInstrSize = 1;
488 unsigned MoveInstr = (Is64Bit ? X86::MOV64rr : X86::MOV32rr);
489 unsigned MoveInstrSize = (Is64Bit ? 3 : 2);
490 unsigned SubtractInstr = getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta);
491 unsigned SubtractInstrIdx = (Is64Bit ? 3 : 2);
492
493 unsigned InstrOffset = 0;
494 unsigned CFAOffset = 0;
495 unsigned StackAdjust = 0;
496
497 MachineBasicBlock &MBB = MF.front(); // Prologue is in entry BB.
498 bool ExpectEnd = false;
499 for (MachineBasicBlock::iterator
500 MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ++MBBI) {
501 MachineInstr &MI = *MBBI;
502 unsigned Opc = MI.getOpcode();
503 if (Opc == X86::PROLOG_LABEL) continue;
504 if (!MI.getFlag(MachineInstr::FrameSetup)) break;
505
506 // We don't exect any more prolog instructions.
507 if (ExpectEnd) return 0;
508
509 if (Opc == PushInstr) {
510 // If there are too many saved registers, we cannot use compact encoding.
511 if (--SavedRegIdx < 0) return 0;
512
513 SavedRegs[SavedRegIdx] = MI.getOperand(0).getReg();
514 CFAOffset += OffsetSize;
515 InstrOffset += PushInstrSize;
516 } else if (Opc == MoveInstr) {
517 unsigned SrcReg = MI.getOperand(1).getReg();
518 unsigned DstReg = MI.getOperand(0).getReg();
519
520 if (DstReg != FramePtr || SrcReg != StackPtr)
521 return 0;
522
523 CFAOffset = 0;
524 memset(SavedRegs, 0, sizeof(SavedRegs));
525 InstrOffset += MoveInstrSize;
526 } else if (Opc == SubtractInstr) {
527 if (StackAdjust)
528 // We all ready have a stack pointer adjustment.
529 return 0;
530
531 if (!MI.getOperand(0).isReg() ||
532 MI.getOperand(0).getReg() != MI.getOperand(1).getReg() ||
533 MI.getOperand(0).getReg() != StackPtr || !MI.getOperand(2).isImm())
534 // We need this to be a stack adjustment pointer. Something like:
535 //
536 // %RSP<def> = SUB64ri8 %RSP, 48
537 return 0;
538
539 StackAdjust = MI.getOperand(2).getImm() / 4;
540 SubtractInstrIdx += InstrOffset;
541 ExpectEnd = true;
542 }
543 }
544
545 // Encode that we are using EBP/RBP as the frame pointer.
546 uint32_t CompactUnwindEncoding = 0;
547 CFAOffset /= 4;
548 if (HasFP) {
549 if ((CFAOffset & 0xFF) != CFAOffset)
550 // Offset was too big for compact encoding.
551 return 0;
552
553 // Get the encoding of the saved registers when we have a frame pointer.
554 uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame(SavedRegs, Is64Bit);
555 if (RegEnc == ~0U)
556 return 0;
557
558 CompactUnwindEncoding |= 0x01000000;
559 CompactUnwindEncoding |= (CFAOffset & 0xFF) << 16;
560 CompactUnwindEncoding |= RegEnc & 0x7FFF;
561 } else {
562 unsigned FullOffset = CFAOffset + StackAdjust;
563 if ((FullOffset & 0xFF) == FullOffset) {
564 // Frameless stack.
565 CompactUnwindEncoding |= 0x02000000;
566 CompactUnwindEncoding |= (FullOffset & 0xFF) << 16;
567 } else {
568 if ((CFAOffset & 0x7) != CFAOffset)
569 // The extra stack adjustments are too big for us to handle.
570 return 0;
571
572 // Frameless stack with an offset too large for us to encode compactly.
573 CompactUnwindEncoding |= 0x03000000;
574
575 // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
576 // instruction.
577 CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
578
579 // Encode any extra stack stack changes (done via push instructions).
580 CompactUnwindEncoding |= (CFAOffset & 0x7) << 13;
581 }
582
583 // Get the encoding of the saved registers when we don't have a frame
584 // pointer.
585 uint32_t RegEnc = encodeCompactUnwindRegistersWithoutFrame(SavedRegs,
586 6 - SavedRegIdx,
587 Is64Bit);
588 if (RegEnc == ~0U) return 0;
589 CompactUnwindEncoding |= RegEnc & 0x3FF;
590 }
591
592 return CompactUnwindEncoding;
593}
594
Anton Korobeynikov33464912010-11-15 00:06:54 +0000595/// emitPrologue - Push callee-saved registers onto the stack, which
596/// automatically adjust the stack pointer. Adjust the stack pointer to allocate
597/// space for local variables. Also emit labels used by the exception handler to
598/// generate the exception handling frames.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000599void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000600 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
601 MachineBasicBlock::iterator MBBI = MBB.begin();
602 MachineFrameInfo *MFI = MF.getFrameInfo();
603 const Function *Fn = MF.getFunction();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000604 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
605 const X86InstrInfo &TII = *TM.getInstrInfo();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000606 MachineModuleInfo &MMI = MF.getMMI();
607 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
608 bool needsFrameMoves = MMI.hasDebugInfo() ||
Rafael Espindolafc2bb8c2011-05-25 03:44:17 +0000609 Fn->needsUnwindTableEntry();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000610 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
611 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000612 bool HasFP = hasFP(MF);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000613 bool Is64Bit = STI.is64Bit();
614 bool IsWin64 = STI.isTargetWin64();
615 unsigned StackAlign = getStackAlignment();
616 unsigned SlotSize = RegInfo->getSlotSize();
617 unsigned FramePtr = RegInfo->getFrameRegister(MF);
618 unsigned StackPtr = RegInfo->getStackRegister();
Anton Korobeynikov33464912010-11-15 00:06:54 +0000619 DebugLoc DL;
620
621 // If we're forcing a stack realignment we can't rely on just the frame
622 // info, we need to know the ABI stack alignment as well in case we
623 // have a call out. Otherwise just make sure we have some alignment - we'll
624 // go with the minimum SlotSize.
625 if (ForceStackAlign) {
626 if (MFI->hasCalls())
627 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
628 else if (MaxAlign < SlotSize)
629 MaxAlign = SlotSize;
630 }
631
632 // Add RETADDR move area to callee saved frame size.
633 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
634 if (TailCallReturnAddrDelta < 0)
635 X86FI->setCalleeSavedFrameSize(
636 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
637
638 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
639 // function, and use up to 128 bytes of stack space, don't have a frame
640 // pointer, calls, or dynamic alloca then we do not need to adjust the
641 // stack pointer (we fit in the Red Zone).
642 if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
643 !RegInfo->needsStackRealignment(MF) &&
644 !MFI->hasVarSizedObjects() && // No dynamic alloca.
645 !MFI->adjustsStack() && // No calls.
646 !IsWin64) { // Win64 has no Red Zone
647 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
648 if (HasFP) MinSize += SlotSize;
649 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
650 MFI->setStackSize(StackSize);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000651 }
652
653 // Insert stack pointer adjustment for later moving of return addr. Only
654 // applies to tail call optimized functions where the callee argument stack
655 // size is bigger than the callers.
656 if (TailCallReturnAddrDelta < 0) {
657 MachineInstr *MI =
658 BuildMI(MBB, MBBI, DL,
659 TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
660 StackPtr)
661 .addReg(StackPtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000662 .addImm(-TailCallReturnAddrDelta)
663 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000664 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
665 }
666
667 // Mapping for machine moves:
668 //
669 // DST: VirtualFP AND
670 // SRC: VirtualFP => DW_CFA_def_cfa_offset
671 // ELSE => DW_CFA_def_cfa
672 //
673 // SRC: VirtualFP AND
674 // DST: Register => DW_CFA_def_cfa_register
675 //
676 // ELSE
677 // OFFSET < 0 => DW_CFA_offset_extended_sf
678 // REG < 64 => DW_CFA_offset + Reg
679 // ELSE => DW_CFA_offset_extended
680
681 std::vector<MachineMove> &Moves = MMI.getFrameMoves();
682 const TargetData *TD = MF.getTarget().getTargetData();
683 uint64_t NumBytes = 0;
684 int stackGrowth = -TD->getPointerSize();
685
686 if (HasFP) {
687 // Calculate required stack adjustment.
688 uint64_t FrameSize = StackSize - SlotSize;
689 if (RegInfo->needsStackRealignment(MF))
690 FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
691
692 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
693
694 // Get the offset of the stack slot for the EBP register, which is
695 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
696 // Update the frame offset adjustment.
697 MFI->setOffsetAdjustment(-NumBytes);
698
699 // Save EBP/RBP into the appropriate stack slot.
700 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
Charles Davisaff232a2011-06-12 01:45:54 +0000701 .addReg(FramePtr, RegState::Kill)
702 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000703
704 if (needsFrameMoves) {
705 // Mark the place where EBP/RBP was saved.
706 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000707 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
708 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000709
710 // Define the current CFA rule to use the provided offset.
711 if (StackSize) {
712 MachineLocation SPDst(MachineLocation::VirtualFP);
713 MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
714 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
715 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000716 MachineLocation SPDst(StackPtr);
717 MachineLocation SPSrc(StackPtr, stackGrowth);
718 Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
719 }
720
721 // Change the rule for the FramePtr to be an "offset" rule.
722 MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
723 MachineLocation FPSrc(FramePtr);
724 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
725 }
726
Bill Wendling09b02c82011-07-25 18:00:28 +0000727 // Update EBP with the new base value.
Anton Korobeynikov33464912010-11-15 00:06:54 +0000728 BuildMI(MBB, MBBI, DL,
729 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
Charles Davisaff232a2011-06-12 01:45:54 +0000730 .addReg(StackPtr)
731 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000732
733 if (needsFrameMoves) {
734 // Mark effective beginning of when frame pointer becomes valid.
735 MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000736 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
737 .addSym(FrameLabel);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000738
739 // Define the current CFA to use the EBP/RBP register.
740 MachineLocation FPDst(FramePtr);
741 MachineLocation FPSrc(MachineLocation::VirtualFP);
742 Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
743 }
744
745 // Mark the FramePtr as live-in in every block except the entry.
746 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
747 I != E; ++I)
748 I->addLiveIn(FramePtr);
749
750 // Realign stack
751 if (RegInfo->needsStackRealignment(MF)) {
752 MachineInstr *MI =
753 BuildMI(MBB, MBBI, DL,
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000754 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
755 .addReg(StackPtr)
756 .addImm(-MaxAlign)
757 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000758
759 // The EFLAGS implicit def is dead.
760 MI->getOperand(3).setIsDead();
761 }
762 } else {
763 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
764 }
765
766 // Skip the callee-saved push instructions.
767 bool PushedRegs = false;
768 int StackOffset = 2 * stackGrowth;
769
770 while (MBBI != MBB.end() &&
771 (MBBI->getOpcode() == X86::PUSH32r ||
772 MBBI->getOpcode() == X86::PUSH64r)) {
773 PushedRegs = true;
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000774 MBBI->setFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000775 ++MBBI;
776
777 if (!HasFP && needsFrameMoves) {
778 // Mark callee-saved push instruction.
779 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
780 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
781
782 // Define the current CFA rule to use the provided offset.
Bill Wendling09b02c82011-07-25 18:00:28 +0000783 unsigned Ptr = StackSize ? MachineLocation::VirtualFP : StackPtr;
Anton Korobeynikov33464912010-11-15 00:06:54 +0000784 MachineLocation SPDst(Ptr);
785 MachineLocation SPSrc(Ptr, StackOffset);
786 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
787 StackOffset += stackGrowth;
788 }
789 }
790
791 DL = MBB.findDebugLoc(MBBI);
792
793 // If there is an SUB32ri of ESP immediately before this instruction, merge
794 // the two. This can be the case when tail call elimination is enabled and
795 // the callee has more arguments then the caller.
796 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
797
798 // If there is an ADD32ri or SUB32ri of ESP immediately after this
799 // instruction, merge the two instructions.
800 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
801
802 // Adjust stack pointer: ESP -= numbytes.
803
804 // Windows and cygwin/mingw require a prologue helper routine when allocating
805 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
806 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
807 // stack and adjust the stack pointer in one go. The 64-bit version of
808 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
809 // responsible for adjusting the stack pointer. Touching the stack at 4K
810 // increments is necessary to ensure that the guard pages used by the OS
811 // virtual memory manager are allocated in correct sequence.
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000812 if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
813 const char *StackProbeSymbol;
814 bool isSPUpdateNeeded = false;
815
816 if (Is64Bit) {
817 if (STI.isTargetCygMing())
818 StackProbeSymbol = "___chkstk";
819 else {
820 StackProbeSymbol = "__chkstk";
821 isSPUpdateNeeded = true;
822 }
823 } else if (STI.isTargetCygMing())
824 StackProbeSymbol = "_alloca";
825 else
826 StackProbeSymbol = "_chkstk";
827
Anton Korobeynikov33464912010-11-15 00:06:54 +0000828 // Check whether EAX is livein for this function.
829 bool isEAXAlive = isEAXLiveIn(MF);
830
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000831 if (isEAXAlive) {
832 // Sanity check that EAX is not livein for this function.
833 // It should not be, so throw an assert.
834 assert(!Is64Bit && "EAX is livein in x64 case!");
835
Anton Korobeynikov33464912010-11-15 00:06:54 +0000836 // Save EAX
837 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000838 .addReg(X86::EAX, RegState::Kill)
839 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000840 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000841
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000842 if (Is64Bit) {
843 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
844 // Function prologue is responsible for adjusting the stack pointer.
845 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000846 .addImm(NumBytes)
847 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000848 } else {
849 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
850 // We'll also use 4 already allocated bytes for EAX.
851 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000852 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
853 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000854 }
855
856 BuildMI(MBB, MBBI, DL,
857 TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
858 .addExternalSymbol(StackProbeSymbol)
859 .addReg(StackPtr, RegState::Define | RegState::Implicit)
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000860 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
861 .setMIFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000862
863 // MSVC x64's __chkstk needs to adjust %rsp.
864 // FIXME: %rax preserves the offset and should be available.
865 if (isSPUpdateNeeded)
866 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
867 TII, *RegInfo);
868
869 if (isEAXAlive) {
870 // Restore EAX
871 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
872 X86::EAX),
873 StackPtr, false, NumBytes - 4);
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000874 MI->setFlag(MachineInstr::FrameSetup);
NAKAMURA Takumia2e07622011-03-24 07:07:00 +0000875 MBB.insert(MBBI, MI);
876 }
Anton Korobeynikov33464912010-11-15 00:06:54 +0000877 } else if (NumBytes)
Evan Cheng7158e082011-01-03 22:53:22 +0000878 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
879 TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000880
Rafael Espindolaf0adba92011-04-15 15:11:06 +0000881 if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000882 // Mark end of stack pointer adjustment.
883 MCSymbol *Label = MMI.getContext().CreateTempSymbol();
Bill Wendlingfb4eb162011-07-21 00:44:56 +0000884 BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
885 .addSym(Label);
Anton Korobeynikov33464912010-11-15 00:06:54 +0000886
887 if (!HasFP && NumBytes) {
888 // Define the current CFA rule to use the provided offset.
889 if (StackSize) {
890 MachineLocation SPDst(MachineLocation::VirtualFP);
891 MachineLocation SPSrc(MachineLocation::VirtualFP,
892 -StackSize + stackGrowth);
893 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
894 } else {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000895 MachineLocation SPDst(StackPtr);
896 MachineLocation SPSrc(StackPtr, stackGrowth);
897 Moves.push_back(MachineMove(Label, SPDst, SPSrc));
898 }
899 }
900
901 // Emit DWARF info specifying the offsets of the callee-saved registers.
902 if (PushedRegs)
903 emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
904 }
Bill Wendling09b02c82011-07-25 18:00:28 +0000905
906 // Darwin 10.7 and greater has support for compact unwind encoding.
Bill Wendlingc57e7db2011-07-25 18:04:49 +0000907 if (GenerateCompactUnwind &&
Bill Wendling09b02c82011-07-25 18:00:28 +0000908 STI.isTargetDarwin() && !STI.getTargetTriple().isMacOSXVersionLT(10, 6))
909 MMI.setCompactUnwindEncoding(getCompactUnwindEncoding(MF));
Anton Korobeynikov33464912010-11-15 00:06:54 +0000910}
911
Anton Korobeynikov16c29b52011-01-10 12:39:04 +0000912void X86FrameLowering::emitEpilogue(MachineFunction &MF,
Nick Lewycky3c2f0a12011-06-14 03:23:52 +0000913 MachineBasicBlock &MBB) const {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000914 const MachineFrameInfo *MFI = MF.getFrameInfo();
915 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
Anton Korobeynikovd9e33852010-11-18 23:25:52 +0000916 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
917 const X86InstrInfo &TII = *TM.getInstrInfo();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000918 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
919 assert(MBBI != MBB.end() && "Returning block has no instructions");
Anton Korobeynikov33464912010-11-15 00:06:54 +0000920 unsigned RetOpcode = MBBI->getOpcode();
921 DebugLoc DL = MBBI->getDebugLoc();
922 bool Is64Bit = STI.is64Bit();
923 unsigned StackAlign = getStackAlignment();
924 unsigned SlotSize = RegInfo->getSlotSize();
925 unsigned FramePtr = RegInfo->getFrameRegister(MF);
926 unsigned StackPtr = RegInfo->getStackRegister();
927
928 switch (RetOpcode) {
929 default:
930 llvm_unreachable("Can only insert epilog into returning blocks");
931 case X86::RET:
932 case X86::RETI:
933 case X86::TCRETURNdi:
934 case X86::TCRETURNri:
935 case X86::TCRETURNmi:
936 case X86::TCRETURNdi64:
937 case X86::TCRETURNri64:
938 case X86::TCRETURNmi64:
939 case X86::EH_RETURN:
940 case X86::EH_RETURN64:
941 break; // These are ok
942 }
943
944 // Get the number of bytes to allocate from the FrameInfo.
945 uint64_t StackSize = MFI->getStackSize();
946 uint64_t MaxAlign = MFI->getMaxAlignment();
947 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
948 uint64_t NumBytes = 0;
949
950 // If we're forcing a stack realignment we can't rely on just the frame
951 // info, we need to know the ABI stack alignment as well in case we
952 // have a call out. Otherwise just make sure we have some alignment - we'll
953 // go with the minimum.
954 if (ForceStackAlign) {
955 if (MFI->hasCalls())
956 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
957 else
958 MaxAlign = MaxAlign ? MaxAlign : 4;
959 }
960
Anton Korobeynikovd0c38172010-11-18 21:19:35 +0000961 if (hasFP(MF)) {
Anton Korobeynikov33464912010-11-15 00:06:54 +0000962 // Calculate required stack adjustment.
963 uint64_t FrameSize = StackSize - SlotSize;
964 if (RegInfo->needsStackRealignment(MF))
965 FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
966
967 NumBytes = FrameSize - CSSize;
968
969 // Pop EBP.
970 BuildMI(MBB, MBBI, DL,
971 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
972 } else {
973 NumBytes = StackSize - CSSize;
974 }
975
976 // Skip the callee-saved pop instructions.
977 MachineBasicBlock::iterator LastCSPop = MBBI;
978 while (MBBI != MBB.begin()) {
979 MachineBasicBlock::iterator PI = prior(MBBI);
980 unsigned Opc = PI->getOpcode();
981
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +0000982 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
Anton Korobeynikov33464912010-11-15 00:06:54 +0000983 !PI->getDesc().isTerminator())
984 break;
985
986 --MBBI;
987 }
988
989 DL = MBBI->getDebugLoc();
990
991 // If there is an ADD32ri or SUB32ri of ESP immediately before this
992 // instruction, merge the two instructions.
993 if (NumBytes || MFI->hasVarSizedObjects())
994 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
995
996 // If dynamic alloca is used, then reset esp to point to the last callee-saved
997 // slot before popping them off! Same applies for the case, when stack was
998 // realigned.
999 if (RegInfo->needsStackRealignment(MF)) {
1000 // We cannot use LEA here, because stack pointer was realigned. We need to
1001 // deallocate local frame back.
1002 if (CSSize) {
Evan Cheng7158e082011-01-03 22:53:22 +00001003 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001004 MBBI = prior(LastCSPop);
1005 }
1006
1007 BuildMI(MBB, MBBI, DL,
1008 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1009 StackPtr).addReg(FramePtr);
1010 } else if (MFI->hasVarSizedObjects()) {
1011 if (CSSize) {
1012 unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
1013 MachineInstr *MI =
1014 addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
1015 FramePtr, false, -CSSize);
1016 MBB.insert(MBBI, MI);
1017 } else {
1018 BuildMI(MBB, MBBI, DL,
1019 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
1020 .addReg(FramePtr);
1021 }
1022 } else if (NumBytes) {
1023 // Adjust stack pointer back: ESP += numbytes.
Evan Cheng7158e082011-01-03 22:53:22 +00001024 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001025 }
1026
1027 // We're returning from function via eh_return.
1028 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001029 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001030 MachineOperand &DestAddr = MBBI->getOperand(0);
1031 assert(DestAddr.isReg() && "Offset should be in register!");
1032 BuildMI(MBB, MBBI, DL,
1033 TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1034 StackPtr).addReg(DestAddr.getReg());
1035 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1036 RetOpcode == X86::TCRETURNmi ||
1037 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1038 RetOpcode == X86::TCRETURNmi64) {
1039 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1040 // Tail call return: adjust the stack pointer and jump to callee.
Jakob Stoklund Olesenf7ca9762011-01-13 22:47:43 +00001041 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001042 MachineOperand &JumpTarget = MBBI->getOperand(0);
1043 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1044 assert(StackAdjust.isImm() && "Expecting immediate value.");
1045
1046 // Adjust stack pointer.
1047 int StackAdj = StackAdjust.getImm();
1048 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1049 int Offset = 0;
1050 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1051
1052 // Incoporate the retaddr area.
1053 Offset = StackAdj-MaxTCDelta;
1054 assert(Offset >= 0 && "Offset should never be negative");
1055
1056 if (Offset) {
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001057 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001058 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001059 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001060 }
1061
1062 // Jump to label or value in register.
1063 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
Evan Cheng3d2125c2010-11-30 23:55:39 +00001064 MachineInstrBuilder MIB =
1065 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1066 ? X86::TAILJMPd : X86::TAILJMPd64));
1067 if (JumpTarget.isGlobal())
1068 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1069 JumpTarget.getTargetFlags());
1070 else {
1071 assert(JumpTarget.isSymbol());
1072 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1073 JumpTarget.getTargetFlags());
1074 }
Anton Korobeynikov33464912010-11-15 00:06:54 +00001075 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1076 MachineInstrBuilder MIB =
1077 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1078 ? X86::TAILJMPm : X86::TAILJMPm64));
1079 for (unsigned i = 0; i != 5; ++i)
1080 MIB.addOperand(MBBI->getOperand(i));
1081 } else if (RetOpcode == X86::TCRETURNri64) {
1082 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1083 addReg(JumpTarget.getReg(), RegState::Kill);
1084 } else {
1085 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1086 addReg(JumpTarget.getReg(), RegState::Kill);
1087 }
1088
1089 MachineInstr *NewMI = prior(MBBI);
1090 for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
1091 NewMI->addOperand(MBBI->getOperand(i));
1092
1093 // Delete the pseudo instruction TCRETURN.
1094 MBB.erase(MBBI);
1095 } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
1096 (X86FI->getTCReturnAddrDelta() < 0)) {
1097 // Add the return addr area delta back since we are not tail calling.
1098 int delta = -1*X86FI->getTCReturnAddrDelta();
Jakob Stoklund Olesen4f28c1c2011-01-13 21:28:52 +00001099 MBBI = MBB.getLastNonDebugInstr();
Anton Korobeynikov33464912010-11-15 00:06:54 +00001100
Chris Lattner7a2bdde2011-04-15 05:18:47 +00001101 // Check for possible merge with preceding ADD instruction.
Anton Korobeynikov33464912010-11-15 00:06:54 +00001102 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
Evan Cheng7158e082011-01-03 22:53:22 +00001103 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
Anton Korobeynikov33464912010-11-15 00:06:54 +00001104 }
1105}
Anton Korobeynikovd9e33852010-11-18 23:25:52 +00001106
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001107int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
Anton Korobeynikov82f58742010-11-20 15:59:32 +00001108 const X86RegisterInfo *RI =
1109 static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
1110 const MachineFrameInfo *MFI = MF.getFrameInfo();
1111 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1112 uint64_t StackSize = MFI->getStackSize();
1113
1114 if (RI->needsStackRealignment(MF)) {
1115 if (FI < 0) {
1116 // Skip the saved EBP.
1117 Offset += RI->getSlotSize();
1118 } else {
1119 unsigned Align = MFI->getObjectAlignment(FI);
1120 assert((-(Offset + StackSize)) % Align == 0);
1121 Align = 0;
1122 return Offset + StackSize;
1123 }
1124 // FIXME: Support tail calls
1125 } else {
1126 if (!hasFP(MF))
1127 return Offset + StackSize;
1128
1129 // Skip the saved EBP.
1130 Offset += RI->getSlotSize();
1131
1132 // Skip the RETADDR move area
1133 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1134 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1135 if (TailCallReturnAddrDelta < 0)
1136 Offset -= TailCallReturnAddrDelta;
1137 }
1138
1139 return Offset;
1140}
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001141
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001142bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001143 MachineBasicBlock::iterator MI,
1144 const std::vector<CalleeSavedInfo> &CSI,
1145 const TargetRegisterInfo *TRI) const {
1146 if (CSI.empty())
1147 return false;
1148
1149 DebugLoc DL = MBB.findDebugLoc(MI);
1150
1151 MachineFunction &MF = *MBB.getParent();
1152
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001153 unsigned SlotSize = STI.is64Bit() ? 8 : 4;
1154 unsigned FPReg = TRI->getFrameRegister(MF);
1155 unsigned CalleeFrameSize = 0;
1156
1157 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1158 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1159
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001160 // Push GPRs. It increases frame size.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001161 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1162 for (unsigned i = CSI.size(); i != 0; --i) {
1163 unsigned Reg = CSI[i-1].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001164 if (!X86::GR64RegClass.contains(Reg) &&
1165 !X86::GR32RegClass.contains(Reg))
1166 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001167 // Add the callee-saved register as live-in. It's killed at the spill.
1168 MBB.addLiveIn(Reg);
1169 if (Reg == FPReg)
1170 // X86RegisterInfo::emitPrologue will handle spilling of frame register.
1171 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001172 CalleeFrameSize += SlotSize;
Charles Davisaff232a2011-06-12 01:45:54 +00001173 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1174 .setMIFlag(MachineInstr::FrameSetup);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001175 }
1176
1177 X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001178
1179 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1180 // It can be done by spilling XMMs to stack frame.
1181 // Note that only Win64 ABI might spill XMMs.
1182 for (unsigned i = CSI.size(); i != 0; --i) {
1183 unsigned Reg = CSI[i-1].getReg();
1184 if (X86::GR64RegClass.contains(Reg) ||
1185 X86::GR32RegClass.contains(Reg))
1186 continue;
1187 // Add the callee-saved register as live-in. It's killed at the spill.
1188 MBB.addLiveIn(Reg);
1189 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1190 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
1191 RC, TRI);
1192 }
1193
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001194 return true;
1195}
1196
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001197bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001198 MachineBasicBlock::iterator MI,
1199 const std::vector<CalleeSavedInfo> &CSI,
1200 const TargetRegisterInfo *TRI) const {
1201 if (CSI.empty())
1202 return false;
1203
1204 DebugLoc DL = MBB.findDebugLoc(MI);
1205
1206 MachineFunction &MF = *MBB.getParent();
1207 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001208
1209 // Reload XMMs from stack frame.
1210 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1211 unsigned Reg = CSI[i].getReg();
1212 if (X86::GR64RegClass.contains(Reg) ||
1213 X86::GR32RegClass.contains(Reg))
1214 continue;
1215 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1216 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
1217 RC, TRI);
1218 }
1219
1220 // POP GPRs.
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001221 unsigned FPReg = TRI->getFrameRegister(MF);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001222 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1223 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1224 unsigned Reg = CSI[i].getReg();
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001225 if (!X86::GR64RegClass.contains(Reg) &&
1226 !X86::GR32RegClass.contains(Reg))
1227 continue;
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001228 if (Reg == FPReg)
1229 // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
1230 continue;
NAKAMURA Takumi419f2322011-02-27 08:47:19 +00001231 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
Anton Korobeynikovcd775ce2010-11-27 23:05:03 +00001232 }
1233 return true;
1234}
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001235
1236void
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001237X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001238 RegScavenger *RS) const {
1239 MachineFrameInfo *MFI = MF.getFrameInfo();
1240 const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
1241 unsigned SlotSize = RegInfo->getSlotSize();
1242
1243 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1244 int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1245
1246 if (TailCallReturnAddrDelta < 0) {
1247 // create RETURNADDR area
1248 // arg
1249 // arg
1250 // RETADDR
1251 // { ...
1252 // RETADDR area
1253 // ...
1254 // }
1255 // [EBP]
1256 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1257 (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1258 }
1259
1260 if (hasFP(MF)) {
1261 assert((TailCallReturnAddrDelta <= 0) &&
1262 "The Delta should always be zero or negative");
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00001263 const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
Anton Korobeynikov94c5ae02010-11-27 23:05:25 +00001264
1265 // Create a frame entry for the EBP register that must be saved.
1266 int FrameIdx = MFI->CreateFixedObject(SlotSize,
1267 -(int)SlotSize +
1268 TFI.getOffsetOfLocalArea() +
1269 TailCallReturnAddrDelta,
1270 true);
1271 assert(FrameIdx == MFI->getObjectIndexBegin() &&
1272 "Slot for EBP register must be last in order to be found!");
1273 FrameIdx = 0;
1274 }
1275}