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   bool Is64Bit = STI.is64Bit();
479   bool HasFP = hasFP(MF);
480 
481   unsigned SavedRegs[CU_NUM_SAVED_REGS] = { 0, 0, 0, 0, 0, 0 };
482   int SavedRegIdx = CU_NUM_SAVED_REGS;
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 SubtractInstrIdx = (Is64Bit ? 3 : 2);
491 
492   unsigned StackDivide = (Is64Bit ? 8 : 4);
493 
494   unsigned InstrOffset = 0;
495   unsigned StackAdjust = 0;
496   unsigned StackSize = 0;
497 
498   MachineBasicBlock &MBB = MF.front(); // Prologue is in entry BB.
499   bool ExpectEnd = false;
500   for (MachineBasicBlock::iterator
501          MBBI = MBB.begin(), MBBE = MBB.end(); MBBI != MBBE; ++MBBI) {
502     MachineInstr &MI = *MBBI;
503     unsigned Opc = MI.getOpcode();
504     if (Opc == X86::PROLOG_LABEL) continue;
505     if (!MI.getFlag(MachineInstr::FrameSetup)) break;
506 
507     // We don't exect any more prolog instructions.
508     if (ExpectEnd) return 0;
509 
510     if (Opc == PushInstr) {
511       // If there are too many saved registers, we cannot use compact encoding.
512       if (--SavedRegIdx < 0) return 0;
513 
514       SavedRegs[SavedRegIdx] = MI.getOperand(0).getReg();
515       StackAdjust += OffsetSize;
516       InstrOffset += PushInstrSize;
517     } else if (Opc == MoveInstr) {
518       unsigned SrcReg = MI.getOperand(1).getReg();
519       unsigned DstReg = MI.getOperand(0).getReg();
520 
521       if (DstReg != FramePtr || SrcReg != StackPtr)
522         return 0;
523 
524       StackAdjust = 0;
525       memset(SavedRegs, 0, sizeof(SavedRegs));
526       SavedRegIdx = CU_NUM_SAVED_REGS;
527       InstrOffset += MoveInstrSize;
528     } else if (Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
529                Opc == X86::SUB32ri || Opc == X86::SUB32ri8) {
530       if (StackSize)
531         // We already have a stack size.
532         return 0;
533 
534       if (!MI.getOperand(0).isReg() ||
535           MI.getOperand(0).getReg() != MI.getOperand(1).getReg() ||
536           MI.getOperand(0).getReg() != StackPtr || !MI.getOperand(2).isImm())
537         // We need this to be a stack adjustment pointer. Something like:
538         //
539         //   %RSP<def> = SUB64ri8 %RSP, 48
540         return 0;
541 
542       StackSize = MI.getOperand(2).getImm() / StackDivide;
543       SubtractInstrIdx += InstrOffset;
544       ExpectEnd = true;
545     }
546   }
547 
548   // Encode that we are using EBP/RBP as the frame pointer.
549   uint32_t CompactUnwindEncoding = 0;
550   StackAdjust /= StackDivide;
551   if (HasFP) {
552     if ((StackAdjust & 0xFF) != StackAdjust)
553       // Offset was too big for compact encoding.
554       return 0;
555 
556     // Get the encoding of the saved registers when we have a frame pointer.
557     uint32_t RegEnc = encodeCompactUnwindRegistersWithFrame(SavedRegs, Is64Bit);
558     if (RegEnc == ~0U) return 0;
559 
560     CompactUnwindEncoding |= 0x01000000;
561     CompactUnwindEncoding |= (StackAdjust & 0xFF) << 16;
562     CompactUnwindEncoding |= RegEnc & 0x7FFF;
563   } else {
564     ++StackAdjust;
565     uint32_t TotalStackSize = StackAdjust + StackSize;
566     if ((TotalStackSize & 0xFF) == TotalStackSize) {
567       // Frameless stack with a small stack size.
568       CompactUnwindEncoding |= 0x02000000;
569 
570       // Encode the stack size.
571       CompactUnwindEncoding |= (TotalStackSize & 0xFF) << 16;
572     } else {
573       if ((StackAdjust & 0x7) != StackAdjust)
574         // The extra stack adjustments are too big for us to handle.
575         return 0;
576 
577       // Frameless stack with an offset too large for us to encode compactly.
578       CompactUnwindEncoding |= 0x03000000;
579 
580       // Encode the offset to the nnnnnn value in the 'subl $nnnnnn, ESP'
581       // instruction.
582       CompactUnwindEncoding |= (SubtractInstrIdx & 0xFF) << 16;
583 
584       // Encode any extra stack stack adjustments (done via push instructions).
585       CompactUnwindEncoding |= (StackAdjust & 0x7) << 13;
586     }
587 
588     // Encode the number of registers saved.
589     CompactUnwindEncoding |= ((CU_NUM_SAVED_REGS - SavedRegIdx) & 0x7) << 10;
590 
591     // Get the encoding of the saved registers when we don't have a frame
592     // pointer.
593     uint32_t RegEnc =
594       encodeCompactUnwindRegistersWithoutFrame(SavedRegs,
595                                                CU_NUM_SAVED_REGS - SavedRegIdx,
596                                                Is64Bit);
597     if (RegEnc == ~0U) return 0;
598 
599     // Encode the register encoding.
600     CompactUnwindEncoding |= RegEnc & 0x3FF;
601   }
602 
603   return CompactUnwindEncoding;
604 }
605 
606 /// emitPrologue - Push callee-saved registers onto the stack, which
607 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
608 /// space for local variables. Also emit labels used by the exception handler to
609 /// generate the exception handling frames.
610 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
611   MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
612   MachineBasicBlock::iterator MBBI = MBB.begin();
613   MachineFrameInfo *MFI = MF.getFrameInfo();
614   const Function *Fn = MF.getFunction();
615   const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
616   const X86InstrInfo &TII = *TM.getInstrInfo();
617   MachineModuleInfo &MMI = MF.getMMI();
618   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
619   bool needsFrameMoves = MMI.hasDebugInfo() ||
620     Fn->needsUnwindTableEntry();
621   uint64_t MaxAlign  = MFI->getMaxAlignment(); // Desired stack alignment.
622   uint64_t StackSize = MFI->getStackSize();    // Number of bytes to allocate.
623   bool HasFP = hasFP(MF);
624   bool Is64Bit = STI.is64Bit();
625   bool IsWin64 = STI.isTargetWin64();
626   unsigned StackAlign = getStackAlignment();
627   unsigned SlotSize = RegInfo->getSlotSize();
628   unsigned FramePtr = RegInfo->getFrameRegister(MF);
629   unsigned StackPtr = RegInfo->getStackRegister();
630   DebugLoc DL;
631 
632   // If we're forcing a stack realignment we can't rely on just the frame
633   // info, we need to know the ABI stack alignment as well in case we
634   // have a call out.  Otherwise just make sure we have some alignment - we'll
635   // go with the minimum SlotSize.
636   if (ForceStackAlign) {
637     if (MFI->hasCalls())
638       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
639     else if (MaxAlign < SlotSize)
640       MaxAlign = SlotSize;
641   }
642 
643   // Add RETADDR move area to callee saved frame size.
644   int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
645   if (TailCallReturnAddrDelta < 0)
646     X86FI->setCalleeSavedFrameSize(
647       X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
648 
649   // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
650   // function, and use up to 128 bytes of stack space, don't have a frame
651   // pointer, calls, or dynamic alloca then we do not need to adjust the
652   // stack pointer (we fit in the Red Zone).
653   if (Is64Bit && !Fn->hasFnAttr(Attribute::NoRedZone) &&
654       !RegInfo->needsStackRealignment(MF) &&
655       !MFI->hasVarSizedObjects() &&                     // No dynamic alloca.
656       !MFI->adjustsStack() &&                           // No calls.
657       !IsWin64 &&                                       // Win64 has no Red Zone
658       !MF.getTarget().Options.EnableSegmentedStacks) {  // Regular stack
659     uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
660     if (HasFP) MinSize += SlotSize;
661     StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
662     MFI->setStackSize(StackSize);
663   }
664 
665   // Insert stack pointer adjustment for later moving of return addr.  Only
666   // applies to tail call optimized functions where the callee argument stack
667   // size is bigger than the callers.
668   if (TailCallReturnAddrDelta < 0) {
669     MachineInstr *MI =
670       BuildMI(MBB, MBBI, DL,
671               TII.get(getSUBriOpcode(Is64Bit, -TailCallReturnAddrDelta)),
672               StackPtr)
673         .addReg(StackPtr)
674         .addImm(-TailCallReturnAddrDelta)
675         .setMIFlag(MachineInstr::FrameSetup);
676     MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
677   }
678 
679   // Mapping for machine moves:
680   //
681   //   DST: VirtualFP AND
682   //        SRC: VirtualFP              => DW_CFA_def_cfa_offset
683   //        ELSE                        => DW_CFA_def_cfa
684   //
685   //   SRC: VirtualFP AND
686   //        DST: Register               => DW_CFA_def_cfa_register
687   //
688   //   ELSE
689   //        OFFSET < 0                  => DW_CFA_offset_extended_sf
690   //        REG < 64                    => DW_CFA_offset + Reg
691   //        ELSE                        => DW_CFA_offset_extended
692 
693   std::vector<MachineMove> &Moves = MMI.getFrameMoves();
694   const TargetData *TD = MF.getTarget().getTargetData();
695   uint64_t NumBytes = 0;
696   int stackGrowth = -TD->getPointerSize();
697 
698   if (HasFP) {
699     // Calculate required stack adjustment.
700     uint64_t FrameSize = StackSize - SlotSize;
701     if (RegInfo->needsStackRealignment(MF))
702       FrameSize = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
703 
704     NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
705 
706     // Get the offset of the stack slot for the EBP register, which is
707     // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
708     // Update the frame offset adjustment.
709     MFI->setOffsetAdjustment(-NumBytes);
710 
711     // Save EBP/RBP into the appropriate stack slot.
712     BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
713       .addReg(FramePtr, RegState::Kill)
714       .setMIFlag(MachineInstr::FrameSetup);
715 
716     if (needsFrameMoves) {
717       // Mark the place where EBP/RBP was saved.
718       MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
719       BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
720         .addSym(FrameLabel);
721 
722       // Define the current CFA rule to use the provided offset.
723       if (StackSize) {
724         MachineLocation SPDst(MachineLocation::VirtualFP);
725         MachineLocation SPSrc(MachineLocation::VirtualFP, 2 * stackGrowth);
726         Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
727       } else {
728         MachineLocation SPDst(StackPtr);
729         MachineLocation SPSrc(StackPtr, stackGrowth);
730         Moves.push_back(MachineMove(FrameLabel, SPDst, SPSrc));
731       }
732 
733       // Change the rule for the FramePtr to be an "offset" rule.
734       MachineLocation FPDst(MachineLocation::VirtualFP, 2 * stackGrowth);
735       MachineLocation FPSrc(FramePtr);
736       Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
737     }
738 
739     // Update EBP with the new base value.
740     BuildMI(MBB, MBBI, DL,
741             TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
742         .addReg(StackPtr)
743         .setMIFlag(MachineInstr::FrameSetup);
744 
745     if (needsFrameMoves) {
746       // Mark effective beginning of when frame pointer becomes valid.
747       MCSymbol *FrameLabel = MMI.getContext().CreateTempSymbol();
748       BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
749         .addSym(FrameLabel);
750 
751       // Define the current CFA to use the EBP/RBP register.
752       MachineLocation FPDst(FramePtr);
753       MachineLocation FPSrc(MachineLocation::VirtualFP);
754       Moves.push_back(MachineMove(FrameLabel, FPDst, FPSrc));
755     }
756 
757     // Mark the FramePtr as live-in in every block except the entry.
758     for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
759          I != E; ++I)
760       I->addLiveIn(FramePtr);
761 
762     // Realign stack
763     if (RegInfo->needsStackRealignment(MF)) {
764       MachineInstr *MI =
765         BuildMI(MBB, MBBI, DL,
766                 TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri), StackPtr)
767         .addReg(StackPtr)
768         .addImm(-MaxAlign)
769         .setMIFlag(MachineInstr::FrameSetup);
770 
771       // The EFLAGS implicit def is dead.
772       MI->getOperand(3).setIsDead();
773     }
774   } else {
775     NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
776   }
777 
778   // Skip the callee-saved push instructions.
779   bool PushedRegs = false;
780   int StackOffset = 2 * stackGrowth;
781 
782   while (MBBI != MBB.end() &&
783          (MBBI->getOpcode() == X86::PUSH32r ||
784           MBBI->getOpcode() == X86::PUSH64r)) {
785     PushedRegs = true;
786     MBBI->setFlag(MachineInstr::FrameSetup);
787     ++MBBI;
788 
789     if (!HasFP && needsFrameMoves) {
790       // Mark callee-saved push instruction.
791       MCSymbol *Label = MMI.getContext().CreateTempSymbol();
792       BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL)).addSym(Label);
793 
794       // Define the current CFA rule to use the provided offset.
795       unsigned Ptr = StackSize ? MachineLocation::VirtualFP : StackPtr;
796       MachineLocation SPDst(Ptr);
797       MachineLocation SPSrc(Ptr, StackOffset);
798       Moves.push_back(MachineMove(Label, SPDst, SPSrc));
799       StackOffset += stackGrowth;
800     }
801   }
802 
803   DL = MBB.findDebugLoc(MBBI);
804 
805   // If there is an SUB32ri of ESP immediately before this instruction, merge
806   // the two. This can be the case when tail call elimination is enabled and
807   // the callee has more arguments then the caller.
808   NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
809 
810   // If there is an ADD32ri or SUB32ri of ESP immediately after this
811   // instruction, merge the two instructions.
812   mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
813 
814   // Adjust stack pointer: ESP -= numbytes.
815 
816   // Windows and cygwin/mingw require a prologue helper routine when allocating
817   // more than 4K bytes on the stack.  Windows uses __chkstk and cygwin/mingw
818   // uses __alloca.  __alloca and the 32-bit version of __chkstk will probe the
819   // stack and adjust the stack pointer in one go.  The 64-bit version of
820   // __chkstk is only responsible for probing the stack.  The 64-bit prologue is
821   // responsible for adjusting the stack pointer.  Touching the stack at 4K
822   // increments is necessary to ensure that the guard pages used by the OS
823   // virtual memory manager are allocated in correct sequence.
824   if (NumBytes >= 4096 && STI.isTargetCOFF() && !STI.isTargetEnvMacho()) {
825     const char *StackProbeSymbol;
826     bool isSPUpdateNeeded = false;
827 
828     if (Is64Bit) {
829       if (STI.isTargetCygMing())
830         StackProbeSymbol = "___chkstk";
831       else {
832         StackProbeSymbol = "__chkstk";
833         isSPUpdateNeeded = true;
834       }
835     } else if (STI.isTargetCygMing())
836       StackProbeSymbol = "_alloca";
837     else
838       StackProbeSymbol = "_chkstk";
839 
840     // Check whether EAX is livein for this function.
841     bool isEAXAlive = isEAXLiveIn(MF);
842 
843     if (isEAXAlive) {
844       // Sanity check that EAX is not livein for this function.
845       // It should not be, so throw an assert.
846       assert(!Is64Bit && "EAX is livein in x64 case!");
847 
848       // Save EAX
849       BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
850         .addReg(X86::EAX, RegState::Kill)
851         .setMIFlag(MachineInstr::FrameSetup);
852     }
853 
854     if (Is64Bit) {
855       // Handle the 64-bit Windows ABI case where we need to call __chkstk.
856       // Function prologue is responsible for adjusting the stack pointer.
857       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
858         .addImm(NumBytes)
859         .setMIFlag(MachineInstr::FrameSetup);
860     } else {
861       // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
862       // We'll also use 4 already allocated bytes for EAX.
863       BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
864         .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
865         .setMIFlag(MachineInstr::FrameSetup);
866     }
867 
868     BuildMI(MBB, MBBI, DL,
869             TII.get(Is64Bit ? X86::W64ALLOCA : X86::CALLpcrel32))
870       .addExternalSymbol(StackProbeSymbol)
871       .addReg(StackPtr,    RegState::Define | RegState::Implicit)
872       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
873       .setMIFlag(MachineInstr::FrameSetup);
874 
875     // MSVC x64's __chkstk needs to adjust %rsp.
876     // FIXME: %rax preserves the offset and should be available.
877     if (isSPUpdateNeeded)
878       emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
879                    TII, *RegInfo);
880 
881     if (isEAXAlive) {
882         // Restore EAX
883         MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
884                                                 X86::EAX),
885                                         StackPtr, false, NumBytes - 4);
886         MI->setFlag(MachineInstr::FrameSetup);
887         MBB.insert(MBBI, MI);
888     }
889   } else if (NumBytes)
890     emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit,
891                  TII, *RegInfo);
892 
893   if (( (!HasFP && NumBytes) || PushedRegs) && needsFrameMoves) {
894     // Mark end of stack pointer adjustment.
895     MCSymbol *Label = MMI.getContext().CreateTempSymbol();
896     BuildMI(MBB, MBBI, DL, TII.get(X86::PROLOG_LABEL))
897       .addSym(Label);
898 
899     if (!HasFP && NumBytes) {
900       // Define the current CFA rule to use the provided offset.
901       if (StackSize) {
902         MachineLocation SPDst(MachineLocation::VirtualFP);
903         MachineLocation SPSrc(MachineLocation::VirtualFP,
904                               -StackSize + stackGrowth);
905         Moves.push_back(MachineMove(Label, SPDst, SPSrc));
906       } else {
907         MachineLocation SPDst(StackPtr);
908         MachineLocation SPSrc(StackPtr, stackGrowth);
909         Moves.push_back(MachineMove(Label, SPDst, SPSrc));
910       }
911     }
912 
913     // Emit DWARF info specifying the offsets of the callee-saved registers.
914     if (PushedRegs)
915       emitCalleeSavedFrameMoves(MF, Label, HasFP ? FramePtr : StackPtr);
916   }
917 
918   // Darwin 10.7 and greater has support for compact unwind encoding.
919   if (STI.getTargetTriple().isMacOSX() &&
920       !STI.getTargetTriple().isMacOSXVersionLT(10, 7))
921     MMI.setCompactUnwindEncoding(getCompactUnwindEncoding(MF));
922 }
923 
924 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
925                                     MachineBasicBlock &MBB) const {
926   const MachineFrameInfo *MFI = MF.getFrameInfo();
927   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
928   const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
929   const X86InstrInfo &TII = *TM.getInstrInfo();
930   MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
931   assert(MBBI != MBB.end() && "Returning block has no instructions");
932   unsigned RetOpcode = MBBI->getOpcode();
933   DebugLoc DL = MBBI->getDebugLoc();
934   bool Is64Bit = STI.is64Bit();
935   unsigned StackAlign = getStackAlignment();
936   unsigned SlotSize = RegInfo->getSlotSize();
937   unsigned FramePtr = RegInfo->getFrameRegister(MF);
938   unsigned StackPtr = RegInfo->getStackRegister();
939 
940   switch (RetOpcode) {
941   default:
942     llvm_unreachable("Can only insert epilog into returning blocks");
943   case X86::RET:
944   case X86::RETI:
945   case X86::TCRETURNdi:
946   case X86::TCRETURNri:
947   case X86::TCRETURNmi:
948   case X86::TCRETURNdi64:
949   case X86::TCRETURNri64:
950   case X86::TCRETURNmi64:
951   case X86::EH_RETURN:
952   case X86::EH_RETURN64:
953     break;  // These are ok
954   }
955 
956   // Get the number of bytes to allocate from the FrameInfo.
957   uint64_t StackSize = MFI->getStackSize();
958   uint64_t MaxAlign  = MFI->getMaxAlignment();
959   unsigned CSSize = X86FI->getCalleeSavedFrameSize();
960   uint64_t NumBytes = 0;
961 
962   // If we're forcing a stack realignment we can't rely on just the frame
963   // info, we need to know the ABI stack alignment as well in case we
964   // have a call out.  Otherwise just make sure we have some alignment - we'll
965   // go with the minimum.
966   if (ForceStackAlign) {
967     if (MFI->hasCalls())
968       MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
969     else
970       MaxAlign = MaxAlign ? MaxAlign : 4;
971   }
972 
973   if (hasFP(MF)) {
974     // Calculate required stack adjustment.
975     uint64_t FrameSize = StackSize - SlotSize;
976     if (RegInfo->needsStackRealignment(MF))
977       FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
978 
979     NumBytes = FrameSize - CSSize;
980 
981     // Pop EBP.
982     BuildMI(MBB, MBBI, DL,
983             TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
984   } else {
985     NumBytes = StackSize - CSSize;
986   }
987 
988   // Skip the callee-saved pop instructions.
989   MachineBasicBlock::iterator LastCSPop = MBBI;
990   while (MBBI != MBB.begin()) {
991     MachineBasicBlock::iterator PI = prior(MBBI);
992     unsigned Opc = PI->getOpcode();
993 
994     if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
995         !PI->isTerminator())
996       break;
997 
998     --MBBI;
999   }
1000 
1001   DL = MBBI->getDebugLoc();
1002 
1003   // If there is an ADD32ri or SUB32ri of ESP immediately before this
1004   // instruction, merge the two instructions.
1005   if (NumBytes || MFI->hasVarSizedObjects())
1006     mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1007 
1008   // If dynamic alloca is used, then reset esp to point to the last callee-saved
1009   // slot before popping them off! Same applies for the case, when stack was
1010   // realigned.
1011   if (RegInfo->needsStackRealignment(MF)) {
1012     // We cannot use LEA here, because stack pointer was realigned. We need to
1013     // deallocate local frame back.
1014     if (CSSize) {
1015       emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
1016       MBBI = prior(LastCSPop);
1017     }
1018 
1019     BuildMI(MBB, MBBI, DL,
1020             TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1021             StackPtr).addReg(FramePtr);
1022   } else if (MFI->hasVarSizedObjects()) {
1023     if (CSSize) {
1024       unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
1025       MachineInstr *MI =
1026         addRegOffset(BuildMI(MF, DL, TII.get(Opc), StackPtr),
1027                      FramePtr, false, -CSSize);
1028       MBB.insert(MBBI, MI);
1029     } else {
1030       BuildMI(MBB, MBBI, DL,
1031               TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), StackPtr)
1032         .addReg(FramePtr);
1033     }
1034   } else if (NumBytes) {
1035     // Adjust stack pointer back: ESP += numbytes.
1036     emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII, *RegInfo);
1037   }
1038 
1039   // We're returning from function via eh_return.
1040   if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
1041     MBBI = MBB.getLastNonDebugInstr();
1042     MachineOperand &DestAddr  = MBBI->getOperand(0);
1043     assert(DestAddr.isReg() && "Offset should be in register!");
1044     BuildMI(MBB, MBBI, DL,
1045             TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
1046             StackPtr).addReg(DestAddr.getReg());
1047   } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
1048              RetOpcode == X86::TCRETURNmi ||
1049              RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
1050              RetOpcode == X86::TCRETURNmi64) {
1051     bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
1052     // Tail call return: adjust the stack pointer and jump to callee.
1053     MBBI = MBB.getLastNonDebugInstr();
1054     MachineOperand &JumpTarget = MBBI->getOperand(0);
1055     MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1056     assert(StackAdjust.isImm() && "Expecting immediate value.");
1057 
1058     // Adjust stack pointer.
1059     int StackAdj = StackAdjust.getImm();
1060     int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1061     int Offset = 0;
1062     assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1063 
1064     // Incoporate the retaddr area.
1065     Offset = StackAdj-MaxTCDelta;
1066     assert(Offset >= 0 && "Offset should never be negative");
1067 
1068     if (Offset) {
1069       // Check for possible merge with preceding ADD instruction.
1070       Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1071       emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII, *RegInfo);
1072     }
1073 
1074     // Jump to label or value in register.
1075     if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1076       MachineInstrBuilder MIB =
1077         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1078                                        ? X86::TAILJMPd : X86::TAILJMPd64));
1079       if (JumpTarget.isGlobal())
1080         MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1081                              JumpTarget.getTargetFlags());
1082       else {
1083         assert(JumpTarget.isSymbol());
1084         MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1085                               JumpTarget.getTargetFlags());
1086       }
1087     } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1088       MachineInstrBuilder MIB =
1089         BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1090                                        ? X86::TAILJMPm : X86::TAILJMPm64));
1091       for (unsigned i = 0; i != 5; ++i)
1092         MIB.addOperand(MBBI->getOperand(i));
1093     } else if (RetOpcode == X86::TCRETURNri64) {
1094       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1095         addReg(JumpTarget.getReg(), RegState::Kill);
1096     } else {
1097       BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1098         addReg(JumpTarget.getReg(), RegState::Kill);
1099     }
1100 
1101     MachineInstr *NewMI = prior(MBBI);
1102     for (unsigned i = 2, e = MBBI->getNumOperands(); i != e; ++i)
1103       NewMI->addOperand(MBBI->getOperand(i));
1104 
1105     // Delete the pseudo instruction TCRETURN.
1106     MBB.erase(MBBI);
1107   } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
1108              (X86FI->getTCReturnAddrDelta() < 0)) {
1109     // Add the return addr area delta back since we are not tail calling.
1110     int delta = -1*X86FI->getTCReturnAddrDelta();
1111     MBBI = MBB.getLastNonDebugInstr();
1112 
1113     // Check for possible merge with preceding ADD instruction.
1114     delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1115     emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII, *RegInfo);
1116   }
1117 }
1118 
1119 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF, int FI) const {
1120   const X86RegisterInfo *RI =
1121     static_cast<const X86RegisterInfo*>(MF.getTarget().getRegisterInfo());
1122   const MachineFrameInfo *MFI = MF.getFrameInfo();
1123   int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1124   uint64_t StackSize = MFI->getStackSize();
1125 
1126   if (RI->needsStackRealignment(MF)) {
1127     if (FI < 0) {
1128       // Skip the saved EBP.
1129       Offset += RI->getSlotSize();
1130     } else {
1131       assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1132       return Offset + StackSize;
1133     }
1134     // FIXME: Support tail calls
1135   } else {
1136     if (!hasFP(MF))
1137       return Offset + StackSize;
1138 
1139     // Skip the saved EBP.
1140     Offset += RI->getSlotSize();
1141 
1142     // Skip the RETADDR move area
1143     const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1144     int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1145     if (TailCallReturnAddrDelta < 0)
1146       Offset -= TailCallReturnAddrDelta;
1147   }
1148 
1149   return Offset;
1150 }
1151 
1152 bool X86FrameLowering::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
1153                                              MachineBasicBlock::iterator MI,
1154                                         const std::vector<CalleeSavedInfo> &CSI,
1155                                           const TargetRegisterInfo *TRI) const {
1156   if (CSI.empty())
1157     return false;
1158 
1159   DebugLoc DL = MBB.findDebugLoc(MI);
1160 
1161   MachineFunction &MF = *MBB.getParent();
1162 
1163   unsigned SlotSize = STI.is64Bit() ? 8 : 4;
1164   unsigned FPReg = TRI->getFrameRegister(MF);
1165   unsigned CalleeFrameSize = 0;
1166 
1167   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1168   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1169 
1170   // Push GPRs. It increases frame size.
1171   unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1172   for (unsigned i = CSI.size(); i != 0; --i) {
1173     unsigned Reg = CSI[i-1].getReg();
1174     if (!X86::GR64RegClass.contains(Reg) &&
1175         !X86::GR32RegClass.contains(Reg))
1176       continue;
1177     // Add the callee-saved register as live-in. It's killed at the spill.
1178     MBB.addLiveIn(Reg);
1179     if (Reg == FPReg)
1180       // X86RegisterInfo::emitPrologue will handle spilling of frame register.
1181       continue;
1182     CalleeFrameSize += SlotSize;
1183     BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1184       .setMIFlag(MachineInstr::FrameSetup);
1185   }
1186 
1187   X86FI->setCalleeSavedFrameSize(CalleeFrameSize);
1188 
1189   // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1190   // It can be done by spilling XMMs to stack frame.
1191   // Note that only Win64 ABI might spill XMMs.
1192   for (unsigned i = CSI.size(); i != 0; --i) {
1193     unsigned Reg = CSI[i-1].getReg();
1194     if (X86::GR64RegClass.contains(Reg) ||
1195         X86::GR32RegClass.contains(Reg))
1196       continue;
1197     // Add the callee-saved register as live-in. It's killed at the spill.
1198     MBB.addLiveIn(Reg);
1199     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1200     TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i-1].getFrameIdx(),
1201                             RC, TRI);
1202   }
1203 
1204   return true;
1205 }
1206 
1207 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1208                                                MachineBasicBlock::iterator MI,
1209                                         const std::vector<CalleeSavedInfo> &CSI,
1210                                           const TargetRegisterInfo *TRI) const {
1211   if (CSI.empty())
1212     return false;
1213 
1214   DebugLoc DL = MBB.findDebugLoc(MI);
1215 
1216   MachineFunction &MF = *MBB.getParent();
1217   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
1218 
1219   // Reload XMMs from stack frame.
1220   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1221     unsigned Reg = CSI[i].getReg();
1222     if (X86::GR64RegClass.contains(Reg) ||
1223         X86::GR32RegClass.contains(Reg))
1224       continue;
1225     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1226     TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(),
1227                              RC, TRI);
1228   }
1229 
1230   // POP GPRs.
1231   unsigned FPReg = TRI->getFrameRegister(MF);
1232   unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1233   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1234     unsigned Reg = CSI[i].getReg();
1235     if (!X86::GR64RegClass.contains(Reg) &&
1236         !X86::GR32RegClass.contains(Reg))
1237       continue;
1238     if (Reg == FPReg)
1239       // X86RegisterInfo::emitEpilogue will handle restoring of frame register.
1240       continue;
1241     BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1242   }
1243   return true;
1244 }
1245 
1246 void
1247 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1248                                                    RegScavenger *RS) const {
1249   MachineFrameInfo *MFI = MF.getFrameInfo();
1250   const X86RegisterInfo *RegInfo = TM.getRegisterInfo();
1251   unsigned SlotSize = RegInfo->getSlotSize();
1252 
1253   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1254   int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1255 
1256   if (TailCallReturnAddrDelta < 0) {
1257     // create RETURNADDR area
1258     //   arg
1259     //   arg
1260     //   RETADDR
1261     //   { ...
1262     //     RETADDR area
1263     //     ...
1264     //   }
1265     //   [EBP]
1266     MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1267                            (-1U*SlotSize)+TailCallReturnAddrDelta, true);
1268   }
1269 
1270   if (hasFP(MF)) {
1271     assert((TailCallReturnAddrDelta <= 0) &&
1272            "The Delta should always be zero or negative");
1273     const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
1274 
1275     // Create a frame entry for the EBP register that must be saved.
1276     int FrameIdx = MFI->CreateFixedObject(SlotSize,
1277                                           -(int)SlotSize +
1278                                           TFI.getOffsetOfLocalArea() +
1279                                           TailCallReturnAddrDelta,
1280                                           true);
1281     assert(FrameIdx == MFI->getObjectIndexBegin() &&
1282            "Slot for EBP register must be last in order to be found!");
1283     (void)FrameIdx;
1284   }
1285 }
1286 
1287 static bool
1288 HasNestArgument(const MachineFunction *MF) {
1289   const Function *F = MF->getFunction();
1290   for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1291        I != E; I++) {
1292     if (I->hasNestAttr())
1293       return true;
1294   }
1295   return false;
1296 }
1297 
1298 static unsigned
1299 GetScratchRegister(bool Is64Bit, const MachineFunction &MF) {
1300   if (Is64Bit) {
1301     return X86::R11;
1302   } else {
1303     CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1304     bool IsNested = HasNestArgument(&MF);
1305 
1306     if (CallingConvention == CallingConv::X86_FastCall) {
1307       if (IsNested) {
1308         report_fatal_error("Segmented stacks does not support fastcall with "
1309                            "nested function.");
1310         return -1;
1311       } else {
1312         return X86::EAX;
1313       }
1314     } else {
1315       if (IsNested)
1316         return X86::EDX;
1317       else
1318         return X86::ECX;
1319     }
1320   }
1321 }
1322 
1323 // The stack limit in the TCB is set to this many bytes above the actual stack
1324 // limit.
1325 static const uint64_t kSplitStackAvailable = 256;
1326 
1327 void
1328 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1329   MachineBasicBlock &prologueMBB = MF.front();
1330   MachineFrameInfo *MFI = MF.getFrameInfo();
1331   const X86InstrInfo &TII = *TM.getInstrInfo();
1332   uint64_t StackSize;
1333   bool Is64Bit = STI.is64Bit();
1334   unsigned TlsReg, TlsOffset;
1335   DebugLoc DL;
1336   const X86Subtarget *ST = &MF.getTarget().getSubtarget<X86Subtarget>();
1337 
1338   unsigned ScratchReg = GetScratchRegister(Is64Bit, MF);
1339   assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1340          "Scratch register is live-in");
1341 
1342   if (MF.getFunction()->isVarArg())
1343     report_fatal_error("Segmented stacks do not support vararg functions.");
1344   if (!ST->isTargetLinux())
1345     report_fatal_error("Segmented stacks supported only on linux.");
1346 
1347   MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1348   MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1349   X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1350   bool IsNested = false;
1351 
1352   // We need to know if the function has a nest argument only in 64 bit mode.
1353   if (Is64Bit)
1354     IsNested = HasNestArgument(&MF);
1355 
1356   // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1357   // allocMBB needs to be last (terminating) instruction.
1358 
1359   for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1360          e = prologueMBB.livein_end(); i != e; i++) {
1361     allocMBB->addLiveIn(*i);
1362     checkMBB->addLiveIn(*i);
1363   }
1364 
1365   if (IsNested)
1366     allocMBB->addLiveIn(X86::R10);
1367 
1368   MF.push_front(allocMBB);
1369   MF.push_front(checkMBB);
1370 
1371   // Eventually StackSize will be calculated by a link-time pass; which will
1372   // also decide whether checking code needs to be injected into this particular
1373   // prologue.
1374   StackSize = MFI->getStackSize();
1375 
1376   // Read the limit off the current stacklet off the stack_guard location.
1377   if (Is64Bit) {
1378     TlsReg = X86::FS;
1379     TlsOffset = 0x70;
1380 
1381     if (StackSize < kSplitStackAvailable)
1382       ScratchReg = X86::RSP;
1383     else
1384       BuildMI(checkMBB, DL, TII.get(X86::LEA64r), ScratchReg).addReg(X86::RSP)
1385         .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1386 
1387     BuildMI(checkMBB, DL, TII.get(X86::CMP64rm)).addReg(ScratchReg)
1388       .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1389   } else {
1390     TlsReg = X86::GS;
1391     TlsOffset = 0x30;
1392 
1393     if (StackSize < kSplitStackAvailable)
1394       ScratchReg = X86::ESP;
1395     else
1396       BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1397         .addImm(0).addReg(0).addImm(-StackSize).addReg(0);
1398 
1399     BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1400       .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1401   }
1402 
1403   // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1404   // It jumps to normal execution of the function body.
1405   BuildMI(checkMBB, DL, TII.get(X86::JG_4)).addMBB(&prologueMBB);
1406 
1407   // On 32 bit we first push the arguments size and then the frame size. On 64
1408   // bit, we pass the stack frame size in r10 and the argument size in r11.
1409   if (Is64Bit) {
1410     // Functions with nested arguments use R10, so it needs to be saved across
1411     // the call to _morestack
1412 
1413     if (IsNested)
1414       BuildMI(allocMBB, DL, TII.get(X86::MOV64rr), X86::RAX).addReg(X86::R10);
1415 
1416     BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R10)
1417       .addImm(StackSize);
1418     BuildMI(allocMBB, DL, TII.get(X86::MOV64ri), X86::R11)
1419       .addImm(X86FI->getArgumentStackSize());
1420     MF.getRegInfo().setPhysRegUsed(X86::R10);
1421     MF.getRegInfo().setPhysRegUsed(X86::R11);
1422   } else {
1423     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1424       .addImm(X86FI->getArgumentStackSize());
1425     BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1426       .addImm(StackSize);
1427   }
1428 
1429   // __morestack is in libgcc
1430   if (Is64Bit)
1431     BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1432       .addExternalSymbol("__morestack");
1433   else
1434     BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1435       .addExternalSymbol("__morestack");
1436 
1437   if (IsNested)
1438     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1439   else
1440     BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1441 
1442   allocMBB->addSuccessor(&prologueMBB);
1443 
1444   checkMBB->addSuccessor(allocMBB);
1445   checkMBB->addSuccessor(&prologueMBB);
1446 
1447 #ifdef XDEBUG
1448   MF.verify();
1449 #endif
1450 }
1451