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