X86RegisterInfo.cpp revision f6a9988ceab0ca660fa4f4e89d8d683f487118eb
1//===- X86RegisterInfo.cpp - X86 Register 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 the TargetRegisterInfo class.
11// This file is responsible for the frame pointer elimination optimization
12// on X86.
13//
14//===----------------------------------------------------------------------===//
15
16#include "X86.h"
17#include "X86RegisterInfo.h"
18#include "X86InstrBuilder.h"
19#include "X86MachineFunctionInfo.h"
20#include "X86Subtarget.h"
21#include "X86TargetMachine.h"
22#include "llvm/Constants.h"
23#include "llvm/Function.h"
24#include "llvm/Type.h"
25#include "llvm/CodeGen/ValueTypes.h"
26#include "llvm/CodeGen/MachineInstrBuilder.h"
27#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFunctionPass.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineLocation.h"
31#include "llvm/CodeGen/MachineModuleInfo.h"
32#include "llvm/CodeGen/MachineRegisterInfo.h"
33#include "llvm/Target/TargetAsmInfo.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetMachine.h"
37#include "llvm/Target/TargetOptions.h"
38#include "llvm/ADT/BitVector.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/Support/Compiler.h"
41using namespace llvm;
42
43X86RegisterInfo::X86RegisterInfo(X86TargetMachine &tm,
44                                 const TargetInstrInfo &tii)
45  : X86GenRegisterInfo(tm.getSubtarget<X86Subtarget>().is64Bit() ?
46                         X86::ADJCALLSTACKDOWN64 :
47                         X86::ADJCALLSTACKDOWN32,
48                       tm.getSubtarget<X86Subtarget>().is64Bit() ?
49                         X86::ADJCALLSTACKUP64 :
50                         X86::ADJCALLSTACKUP32),
51    TM(tm), TII(tii) {
52  // Cache some information.
53  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
54  Is64Bit = Subtarget->is64Bit();
55  IsWin64 = Subtarget->isTargetWin64();
56  StackAlign = TM.getFrameInfo()->getStackAlignment();
57  if (Is64Bit) {
58    SlotSize = 8;
59    StackPtr = X86::RSP;
60    FramePtr = X86::RBP;
61  } else {
62    SlotSize = 4;
63    StackPtr = X86::ESP;
64    FramePtr = X86::EBP;
65  }
66}
67
68// getDwarfRegNum - This function maps LLVM register identifiers to the
69// Dwarf specific numbering, used in debug info and exception tables.
70
71int X86RegisterInfo::getDwarfRegNum(unsigned RegNo, bool isEH) const {
72  const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
73  unsigned Flavour = DWARFFlavour::X86_64;
74  if (!Subtarget->is64Bit()) {
75    if (Subtarget->isTargetDarwin()) {
76      if (isEH)
77        Flavour = DWARFFlavour::X86_32_DarwinEH;
78      else
79        Flavour = DWARFFlavour::X86_32_Generic;
80    } else if (Subtarget->isTargetCygMing()) {
81      // Unsupported by now, just quick fallback
82      Flavour = DWARFFlavour::X86_32_Generic;
83    } else {
84      Flavour = DWARFFlavour::X86_32_Generic;
85    }
86  }
87
88  return X86GenRegisterInfo::getDwarfRegNumFull(RegNo, Flavour);
89}
90
91// getX86RegNum - This function maps LLVM register identifiers to their X86
92// specific numbering, which is used in various places encoding instructions.
93//
94unsigned X86RegisterInfo::getX86RegNum(unsigned RegNo) {
95  switch(RegNo) {
96  case X86::RAX: case X86::EAX: case X86::AX: case X86::AL: return N86::EAX;
97  case X86::RCX: case X86::ECX: case X86::CX: case X86::CL: return N86::ECX;
98  case X86::RDX: case X86::EDX: case X86::DX: case X86::DL: return N86::EDX;
99  case X86::RBX: case X86::EBX: case X86::BX: case X86::BL: return N86::EBX;
100  case X86::RSP: case X86::ESP: case X86::SP: case X86::SPL: case X86::AH:
101    return N86::ESP;
102  case X86::RBP: case X86::EBP: case X86::BP: case X86::BPL: case X86::CH:
103    return N86::EBP;
104  case X86::RSI: case X86::ESI: case X86::SI: case X86::SIL: case X86::DH:
105    return N86::ESI;
106  case X86::RDI: case X86::EDI: case X86::DI: case X86::DIL: case X86::BH:
107    return N86::EDI;
108
109  case X86::R8:  case X86::R8D:  case X86::R8W:  case X86::R8B:
110    return N86::EAX;
111  case X86::R9:  case X86::R9D:  case X86::R9W:  case X86::R9B:
112    return N86::ECX;
113  case X86::R10: case X86::R10D: case X86::R10W: case X86::R10B:
114    return N86::EDX;
115  case X86::R11: case X86::R11D: case X86::R11W: case X86::R11B:
116    return N86::EBX;
117  case X86::R12: case X86::R12D: case X86::R12W: case X86::R12B:
118    return N86::ESP;
119  case X86::R13: case X86::R13D: case X86::R13W: case X86::R13B:
120    return N86::EBP;
121  case X86::R14: case X86::R14D: case X86::R14W: case X86::R14B:
122    return N86::ESI;
123  case X86::R15: case X86::R15D: case X86::R15W: case X86::R15B:
124    return N86::EDI;
125
126  case X86::ST0: case X86::ST1: case X86::ST2: case X86::ST3:
127  case X86::ST4: case X86::ST5: case X86::ST6: case X86::ST7:
128    return RegNo-X86::ST0;
129
130  case X86::XMM0: case X86::XMM8: case X86::MM0:
131    return 0;
132  case X86::XMM1: case X86::XMM9: case X86::MM1:
133    return 1;
134  case X86::XMM2: case X86::XMM10: case X86::MM2:
135    return 2;
136  case X86::XMM3: case X86::XMM11: case X86::MM3:
137    return 3;
138  case X86::XMM4: case X86::XMM12: case X86::MM4:
139    return 4;
140  case X86::XMM5: case X86::XMM13: case X86::MM5:
141    return 5;
142  case X86::XMM6: case X86::XMM14: case X86::MM6:
143    return 6;
144  case X86::XMM7: case X86::XMM15: case X86::MM7:
145    return 7;
146
147  default:
148    assert(isVirtualRegister(RegNo) && "Unknown physical register!");
149    assert(0 && "Register allocator hasn't allocated reg correctly yet!");
150    return 0;
151  }
152}
153
154const TargetRegisterClass *
155X86RegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
156  if (RC == &X86::CCRRegClass) {
157    if (Is64Bit)
158      return &X86::GR64RegClass;
159    else
160      return &X86::GR32RegClass;
161  }
162  return NULL;
163}
164
165const unsigned *
166X86RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
167  bool callsEHReturn = false;
168
169  if (MF) {
170    const MachineFrameInfo *MFI = MF->getFrameInfo();
171    const MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
172    callsEHReturn = (MMI ? MMI->callsEHReturn() : false);
173  }
174
175  static const unsigned CalleeSavedRegs32Bit[] = {
176    X86::ESI, X86::EDI, X86::EBX, X86::EBP,  0
177  };
178
179  static const unsigned CalleeSavedRegs32EHRet[] = {
180    X86::EAX, X86::EDX, X86::ESI, X86::EDI, X86::EBX, X86::EBP,  0
181  };
182
183  static const unsigned CalleeSavedRegs64Bit[] = {
184    X86::RBX, X86::R12, X86::R13, X86::R14, X86::R15, X86::RBP, 0
185  };
186
187  static const unsigned CalleeSavedRegs64EHRet[] = {
188    X86::RAX, X86::RDX, X86::RBX, X86::R12,
189    X86::R13, X86::R14, X86::R15, X86::RBP, 0
190  };
191
192  static const unsigned CalleeSavedRegsWin64[] = {
193    X86::RBX,   X86::RBP,   X86::RDI,   X86::RSI,
194    X86::R12,   X86::R13,   X86::R14,   X86::R15,
195    X86::XMM6,  X86::XMM7,  X86::XMM8,  X86::XMM9,
196    X86::XMM10, X86::XMM11, X86::XMM12, X86::XMM13,
197    X86::XMM14, X86::XMM15, 0
198  };
199
200  if (Is64Bit) {
201    if (IsWin64)
202      return CalleeSavedRegsWin64;
203    else
204      return (callsEHReturn ? CalleeSavedRegs64EHRet : CalleeSavedRegs64Bit);
205  } else {
206    return (callsEHReturn ? CalleeSavedRegs32EHRet : CalleeSavedRegs32Bit);
207  }
208}
209
210const TargetRegisterClass* const*
211X86RegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
212  bool callsEHReturn = false;
213
214  if (MF) {
215    const MachineFrameInfo *MFI = MF->getFrameInfo();
216    const MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
217    callsEHReturn = (MMI ? MMI->callsEHReturn() : false);
218  }
219
220  static const TargetRegisterClass * const CalleeSavedRegClasses32Bit[] = {
221    &X86::GR32RegClass, &X86::GR32RegClass,
222    &X86::GR32RegClass, &X86::GR32RegClass,  0
223  };
224  static const TargetRegisterClass * const CalleeSavedRegClasses32EHRet[] = {
225    &X86::GR32RegClass, &X86::GR32RegClass,
226    &X86::GR32RegClass, &X86::GR32RegClass,
227    &X86::GR32RegClass, &X86::GR32RegClass,  0
228  };
229  static const TargetRegisterClass * const CalleeSavedRegClasses64Bit[] = {
230    &X86::GR64RegClass, &X86::GR64RegClass,
231    &X86::GR64RegClass, &X86::GR64RegClass,
232    &X86::GR64RegClass, &X86::GR64RegClass, 0
233  };
234  static const TargetRegisterClass * const CalleeSavedRegClasses64EHRet[] = {
235    &X86::GR64RegClass, &X86::GR64RegClass,
236    &X86::GR64RegClass, &X86::GR64RegClass,
237    &X86::GR64RegClass, &X86::GR64RegClass,
238    &X86::GR64RegClass, &X86::GR64RegClass, 0
239  };
240  static const TargetRegisterClass * const CalleeSavedRegClassesWin64[] = {
241    &X86::GR64RegClass,  &X86::GR64RegClass,
242    &X86::GR64RegClass,  &X86::GR64RegClass,
243    &X86::GR64RegClass,  &X86::GR64RegClass,
244    &X86::GR64RegClass,  &X86::GR64RegClass,
245    &X86::VR128RegClass, &X86::VR128RegClass,
246    &X86::VR128RegClass, &X86::VR128RegClass,
247    &X86::VR128RegClass, &X86::VR128RegClass,
248    &X86::VR128RegClass, &X86::VR128RegClass,
249    &X86::VR128RegClass, &X86::VR128RegClass, 0
250  };
251
252  if (Is64Bit) {
253    if (IsWin64)
254      return CalleeSavedRegClassesWin64;
255    else
256      return (callsEHReturn ?
257              CalleeSavedRegClasses64EHRet : CalleeSavedRegClasses64Bit);
258  } else {
259    return (callsEHReturn ?
260            CalleeSavedRegClasses32EHRet : CalleeSavedRegClasses32Bit);
261  }
262}
263
264BitVector X86RegisterInfo::getReservedRegs(const MachineFunction &MF) const {
265  BitVector Reserved(getNumRegs());
266  Reserved.set(X86::RSP);
267  Reserved.set(X86::ESP);
268  Reserved.set(X86::SP);
269  Reserved.set(X86::SPL);
270  if (hasFP(MF)) {
271    Reserved.set(X86::RBP);
272    Reserved.set(X86::EBP);
273    Reserved.set(X86::BP);
274    Reserved.set(X86::BPL);
275  }
276  return Reserved;
277}
278
279//===----------------------------------------------------------------------===//
280// Stack Frame Processing methods
281//===----------------------------------------------------------------------===//
282
283static unsigned calculateMaxStackAlignment(const MachineFrameInfo *FFI) {
284  unsigned MaxAlign = 0;
285  for (int i = FFI->getObjectIndexBegin(),
286         e = FFI->getObjectIndexEnd(); i != e; ++i) {
287    if (FFI->isDeadObjectIndex(i))
288      continue;
289    unsigned Align = FFI->getObjectAlignment(i);
290    MaxAlign = std::max(MaxAlign, Align);
291  }
292
293  return MaxAlign;
294}
295
296// hasFP - Return true if the specified function should have a dedicated frame
297// pointer register.  This is true if the function has variable sized allocas or
298// if frame pointer elimination is disabled.
299//
300bool X86RegisterInfo::hasFP(const MachineFunction &MF) const {
301  const MachineFrameInfo *MFI = MF.getFrameInfo();
302  const MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
303
304  return (NoFramePointerElim ||
305          needsStackRealignment(MF) ||
306          MFI->hasVarSizedObjects() ||
307          MFI->isFrameAddressTaken() ||
308          MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
309          (MMI && MMI->callsUnwindInit()));
310}
311
312bool X86RegisterInfo::needsStackRealignment(const MachineFunction &MF) const {
313  const MachineFrameInfo *MFI = MF.getFrameInfo();;
314
315  // FIXME: Currently we don't support stack realignment for functions with
316  // variable-sized allocas
317  return (RealignStack &&
318          (MFI->getMaxAlignment() > StackAlign &&
319           !MFI->hasVarSizedObjects()));
320}
321
322bool X86RegisterInfo::hasReservedCallFrame(MachineFunction &MF) const {
323  return !MF.getFrameInfo()->hasVarSizedObjects();
324}
325
326int
327X86RegisterInfo::getFrameIndexOffset(MachineFunction &MF, int FI) const {
328  int Offset = MF.getFrameInfo()->getObjectOffset(FI) + SlotSize;
329  uint64_t StackSize = MF.getFrameInfo()->getStackSize();
330
331  if (needsStackRealignment(MF)) {
332    if (FI < 0)
333      // Skip the saved EBP
334      Offset += SlotSize;
335    else {
336      unsigned Align = MF.getFrameInfo()->getObjectAlignment(FI);
337      assert( (-(Offset + StackSize)) % Align == 0);
338      return Offset + StackSize;
339    }
340
341    // FIXME: Support tail calls
342  } else {
343    if (!hasFP(MF))
344      return Offset + StackSize;
345
346    // Skip the saved EBP
347    Offset += SlotSize;
348
349    // Skip the RETADDR move area
350    X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
351    int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
352    if (TailCallReturnAddrDelta < 0) Offset -= TailCallReturnAddrDelta;
353  }
354
355  return Offset;
356}
357
358void X86RegisterInfo::
359eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
360                              MachineBasicBlock::iterator I) const {
361  if (!hasReservedCallFrame(MF)) {
362    // If the stack pointer can be changed after prologue, turn the
363    // adjcallstackup instruction into a 'sub ESP, <amt>' and the
364    // adjcallstackdown instruction into 'add ESP, <amt>'
365    // TODO: consider using push / pop instead of sub + store / add
366    MachineInstr *Old = I;
367    uint64_t Amount = Old->getOperand(0).getImm();
368    if (Amount != 0) {
369      // We need to keep the stack aligned properly.  To do this, we round the
370      // amount of space needed for the outgoing arguments up to the next
371      // alignment boundary.
372      Amount = (Amount+StackAlign-1)/StackAlign*StackAlign;
373
374      MachineInstr *New = 0;
375      if (Old->getOpcode() == getCallFrameSetupOpcode()) {
376        New = BuildMI(MF, TII.get(Is64Bit ? X86::SUB64ri32 : X86::SUB32ri),
377                      StackPtr).addReg(StackPtr).addImm(Amount);
378      } else {
379        assert(Old->getOpcode() == getCallFrameDestroyOpcode());
380        // factor out the amount the callee already popped.
381        uint64_t CalleeAmt = Old->getOperand(1).getImm();
382        Amount -= CalleeAmt;
383        if (Amount) {
384          unsigned Opc = (Amount < 128) ?
385            (Is64Bit ? X86::ADD64ri8 : X86::ADD32ri8) :
386            (Is64Bit ? X86::ADD64ri32 : X86::ADD32ri);
387          New = BuildMI(MF, TII.get(Opc), StackPtr)
388            .addReg(StackPtr).addImm(Amount);
389        }
390      }
391
392      // Replace the pseudo instruction with a new instruction...
393      if (New) MBB.insert(I, New);
394    }
395  } else if (I->getOpcode() == getCallFrameDestroyOpcode()) {
396    // If we are performing frame pointer elimination and if the callee pops
397    // something off the stack pointer, add it back.  We do this until we have
398    // more advanced stack pointer tracking ability.
399    if (uint64_t CalleeAmt = I->getOperand(1).getImm()) {
400      unsigned Opc = (CalleeAmt < 128) ?
401        (Is64Bit ? X86::SUB64ri8 : X86::SUB32ri8) :
402        (Is64Bit ? X86::SUB64ri32 : X86::SUB32ri);
403      MachineInstr *New =
404        BuildMI(MF, TII.get(Opc), StackPtr).addReg(StackPtr).addImm(CalleeAmt);
405      MBB.insert(I, New);
406    }
407  }
408
409  MBB.erase(I);
410}
411
412void X86RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
413                                          int SPAdj, RegScavenger *RS) const{
414  assert(SPAdj == 0 && "Unexpected");
415
416  unsigned i = 0;
417  MachineInstr &MI = *II;
418  MachineFunction &MF = *MI.getParent()->getParent();
419  while (!MI.getOperand(i).isFI()) {
420    ++i;
421    assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
422  }
423
424  int FrameIndex = MI.getOperand(i).getIndex();
425
426  unsigned BasePtr;
427  if (needsStackRealignment(MF))
428    BasePtr = (FrameIndex < 0 ? FramePtr : StackPtr);
429  else
430    BasePtr = (hasFP(MF) ? FramePtr : StackPtr);
431
432  // This must be part of a four operand memory reference.  Replace the
433  // FrameIndex with base register with EBP.  Add an offset to the offset.
434  MI.getOperand(i).ChangeToRegister(BasePtr, false);
435
436  // Now add the frame object offset to the offset from EBP. Offset is a
437  // 32-bit integer.
438  int Offset = getFrameIndexOffset(MF, FrameIndex) +
439    (int)(MI.getOperand(i+3).getImm());
440
441  MI.getOperand(i+3).ChangeToImmediate(Offset);
442}
443
444void
445X86RegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
446                                                      RegScavenger *RS) const {
447  MachineFrameInfo *FFI = MF.getFrameInfo();
448
449  // Calculate and set max stack object alignment early, so we can decide
450  // whether we will need stack realignment (and thus FP).
451  unsigned MaxAlign = std::max(FFI->getMaxAlignment(),
452                               calculateMaxStackAlignment(FFI));
453
454  FFI->setMaxAlignment(MaxAlign);
455}
456
457void
458X86RegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF) const{
459  X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
460  int32_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
461  if (TailCallReturnAddrDelta < 0) {
462    // create RETURNADDR area
463    //   arg
464    //   arg
465    //   RETADDR
466    //   { ...
467    //     RETADDR area
468    //     ...
469    //   }
470    //   [EBP]
471    MF.getFrameInfo()->
472      CreateFixedObject(-TailCallReturnAddrDelta,
473                        (-1*SlotSize)+TailCallReturnAddrDelta);
474  }
475  if (hasFP(MF)) {
476    assert((TailCallReturnAddrDelta <= 0) &&
477           "The Delta should always be zero or negative");
478    // Create a frame entry for the EBP register that must be saved.
479    int FrameIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize,
480                                                        (int)SlotSize * -2+
481                                                       TailCallReturnAddrDelta);
482    assert(FrameIdx == MF.getFrameInfo()->getObjectIndexBegin() &&
483           "Slot for EBP register must be last in order to be found!");
484  }
485}
486
487/// emitSPUpdate - Emit a series of instructions to increment / decrement the
488/// stack pointer by a constant value.
489static
490void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
491                  unsigned StackPtr, int64_t NumBytes, bool Is64Bit,
492                  const TargetInstrInfo &TII) {
493  bool isSub = NumBytes < 0;
494  uint64_t Offset = isSub ? -NumBytes : NumBytes;
495  unsigned Opc = isSub
496    ? ((Offset < 128) ?
497       (Is64Bit ? X86::SUB64ri8 : X86::SUB32ri8) :
498       (Is64Bit ? X86::SUB64ri32 : X86::SUB32ri))
499    : ((Offset < 128) ?
500       (Is64Bit ? X86::ADD64ri8 : X86::ADD32ri8) :
501       (Is64Bit ? X86::ADD64ri32 : X86::ADD32ri));
502  uint64_t Chunk = (1LL << 31) - 1;
503
504  while (Offset) {
505    uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
506    BuildMI(MBB, MBBI, TII.get(Opc), StackPtr).addReg(StackPtr).addImm(ThisVal);
507    Offset -= ThisVal;
508  }
509}
510
511// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
512static
513void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
514                      unsigned StackPtr, uint64_t *NumBytes = NULL) {
515  if (MBBI == MBB.begin()) return;
516
517  MachineBasicBlock::iterator PI = prior(MBBI);
518  unsigned Opc = PI->getOpcode();
519  if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
520       Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
521      PI->getOperand(0).getReg() == StackPtr) {
522    if (NumBytes)
523      *NumBytes += PI->getOperand(2).getImm();
524    MBB.erase(PI);
525  } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
526              Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
527             PI->getOperand(0).getReg() == StackPtr) {
528    if (NumBytes)
529      *NumBytes -= PI->getOperand(2).getImm();
530    MBB.erase(PI);
531  }
532}
533
534// mergeSPUpdatesUp - Merge two stack-manipulating instructions lower iterator.
535static
536void mergeSPUpdatesDown(MachineBasicBlock &MBB,
537                        MachineBasicBlock::iterator &MBBI,
538                        unsigned StackPtr, uint64_t *NumBytes = NULL) {
539  return;
540
541  if (MBBI == MBB.end()) return;
542
543  MachineBasicBlock::iterator NI = next(MBBI);
544  if (NI == MBB.end()) return;
545
546  unsigned Opc = NI->getOpcode();
547  if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
548       Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
549      NI->getOperand(0).getReg() == StackPtr) {
550    if (NumBytes)
551      *NumBytes -= NI->getOperand(2).getImm();
552    MBB.erase(NI);
553    MBBI = NI;
554  } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
555              Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
556             NI->getOperand(0).getReg() == StackPtr) {
557    if (NumBytes)
558      *NumBytes += NI->getOperand(2).getImm();
559    MBB.erase(NI);
560    MBBI = NI;
561  }
562}
563
564/// mergeSPUpdates - Checks the instruction before/after the passed
565/// instruction. If it is an ADD/SUB instruction it is deleted
566/// argument and the stack adjustment is returned as a positive value for ADD
567/// and a negative for SUB.
568static int mergeSPUpdates(MachineBasicBlock &MBB,
569                           MachineBasicBlock::iterator &MBBI,
570                           unsigned StackPtr,
571                           bool doMergeWithPrevious) {
572
573  if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
574      (!doMergeWithPrevious && MBBI == MBB.end()))
575    return 0;
576
577  int Offset = 0;
578
579  MachineBasicBlock::iterator PI = doMergeWithPrevious ? prior(MBBI) : MBBI;
580  MachineBasicBlock::iterator NI = doMergeWithPrevious ? 0 : next(MBBI);
581  unsigned Opc = PI->getOpcode();
582  if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
583       Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
584      PI->getOperand(0).getReg() == StackPtr){
585    Offset += PI->getOperand(2).getImm();
586    MBB.erase(PI);
587    if (!doMergeWithPrevious) MBBI = NI;
588  } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
589              Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
590             PI->getOperand(0).getReg() == StackPtr) {
591    Offset -= PI->getOperand(2).getImm();
592    MBB.erase(PI);
593    if (!doMergeWithPrevious) MBBI = NI;
594  }
595
596  return Offset;
597}
598
599void X86RegisterInfo::emitFrameMoves(MachineFunction &MF,
600                                     unsigned FrameLabelId,
601                                     unsigned ReadyLabelId) const {
602  MachineFrameInfo *MFI = MF.getFrameInfo();
603  MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
604  if (!MMI)
605    return;
606
607  uint64_t StackSize = MFI->getStackSize();
608  std::vector<MachineMove> &Moves = MMI->getFrameMoves();
609  const TargetData *TD = MF.getTarget().getTargetData();
610
611  // Calculate amount of bytes used for return address storing
612  int stackGrowth =
613    (MF.getTarget().getFrameInfo()->getStackGrowthDirection() ==
614     TargetFrameInfo::StackGrowsUp ?
615     TD->getPointerSize() : -TD->getPointerSize());
616
617  if (StackSize) {
618    // Show update of SP.
619    if (hasFP(MF)) {
620      // Adjust SP
621      MachineLocation SPDst(MachineLocation::VirtualFP);
622      MachineLocation SPSrc(MachineLocation::VirtualFP, 2*stackGrowth);
623      Moves.push_back(MachineMove(FrameLabelId, SPDst, SPSrc));
624    } else {
625      MachineLocation SPDst(MachineLocation::VirtualFP);
626      MachineLocation SPSrc(MachineLocation::VirtualFP,
627                            -StackSize+stackGrowth);
628      Moves.push_back(MachineMove(FrameLabelId, SPDst, SPSrc));
629    }
630  } else {
631    //FIXME: Verify & implement for FP
632    MachineLocation SPDst(StackPtr);
633    MachineLocation SPSrc(StackPtr, stackGrowth);
634    Moves.push_back(MachineMove(FrameLabelId, SPDst, SPSrc));
635  }
636
637  // Add callee saved registers to move list.
638  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
639
640  // FIXME: This is dirty hack. The code itself is pretty mess right now.
641  // It should be rewritten from scratch and generalized sometimes.
642
643  // Determine maximum offset (minumum due to stack growth)
644  int64_t MaxOffset = 0;
645  for (unsigned I = 0, E = CSI.size(); I!=E; ++I)
646    MaxOffset = std::min(MaxOffset,
647                         MFI->getObjectOffset(CSI[I].getFrameIdx()));
648
649  // Calculate offsets
650  int64_t saveAreaOffset = (hasFP(MF) ? 3 : 2)*stackGrowth;
651  for (unsigned I = 0, E = CSI.size(); I!=E; ++I) {
652    int64_t Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
653    unsigned Reg = CSI[I].getReg();
654    Offset = (MaxOffset-Offset+saveAreaOffset);
655    MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
656    MachineLocation CSSrc(Reg);
657    Moves.push_back(MachineMove(FrameLabelId, CSDst, CSSrc));
658  }
659
660  if (hasFP(MF)) {
661    // Save FP
662    MachineLocation FPDst(MachineLocation::VirtualFP, 2*stackGrowth);
663    MachineLocation FPSrc(FramePtr);
664    Moves.push_back(MachineMove(ReadyLabelId, FPDst, FPSrc));
665  }
666
667  MachineLocation FPDst(hasFP(MF) ? FramePtr : StackPtr);
668  MachineLocation FPSrc(MachineLocation::VirtualFP);
669  Moves.push_back(MachineMove(ReadyLabelId, FPDst, FPSrc));
670}
671
672
673void X86RegisterInfo::emitPrologue(MachineFunction &MF) const {
674  MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
675  MachineFrameInfo *MFI = MF.getFrameInfo();
676  const Function* Fn = MF.getFunction();
677  const X86Subtarget* Subtarget = &MF.getTarget().getSubtarget<X86Subtarget>();
678  MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
679  X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
680  MachineBasicBlock::iterator MBBI = MBB.begin();
681  bool needsFrameMoves = (MMI && MMI->hasDebugInfo()) ||
682                          !Fn->doesNotThrow() ||
683                          UnwindTablesMandatory;
684  // Prepare for frame info.
685  unsigned FrameLabelId = 0;
686
687  // Get the number of bytes to allocate from the FrameInfo.
688  uint64_t StackSize = MFI->getStackSize();
689  // Get desired stack alignment
690  uint64_t MaxAlign  = MFI->getMaxAlignment();
691
692  // Add RETADDR move area to callee saved frame size.
693  int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
694  if (TailCallReturnAddrDelta < 0)
695    X86FI->setCalleeSavedFrameSize(
696          X86FI->getCalleeSavedFrameSize() +(-TailCallReturnAddrDelta));
697
698  // Insert stack pointer adjustment for later moving of return addr.  Only
699  // applies to tail call optimized functions where the callee argument stack
700  // size is bigger than the callers.
701  if (TailCallReturnAddrDelta < 0) {
702    BuildMI(MBB, MBBI, TII.get(Is64Bit? X86::SUB64ri32 : X86::SUB32ri),
703            StackPtr).addReg(StackPtr).addImm(-TailCallReturnAddrDelta);
704  }
705
706  uint64_t NumBytes = 0;
707  if (hasFP(MF)) {
708    // Calculate required stack adjustment
709    uint64_t FrameSize = StackSize - SlotSize;
710    if (needsStackRealignment(MF))
711      FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
712
713    NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
714
715    // Get the offset of the stack slot for the EBP register... which is
716    // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
717    // Update the frame offset adjustment.
718    MFI->setOffsetAdjustment(-NumBytes);
719
720    // Save EBP into the appropriate stack slot...
721    BuildMI(MBB, MBBI, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
722      .addReg(FramePtr);
723
724    if (needsFrameMoves) {
725      // Mark effective beginning of when frame pointer becomes valid.
726      FrameLabelId = MMI->NextLabelID();
727      BuildMI(MBB, MBBI, TII.get(X86::DBG_LABEL)).addImm(FrameLabelId);
728    }
729
730    // Update EBP with the new base value...
731    BuildMI(MBB, MBBI, TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr), FramePtr)
732      .addReg(StackPtr);
733
734    // Realign stack
735    if (needsStackRealignment(MF))
736      BuildMI(MBB, MBBI,
737              TII.get(Is64Bit ? X86::AND64ri32 : X86::AND32ri),
738              StackPtr).addReg(StackPtr).addImm(-MaxAlign);
739  } else
740    NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
741
742  unsigned ReadyLabelId = 0;
743  if (needsFrameMoves) {
744    // Mark effective beginning of when frame pointer is ready.
745    ReadyLabelId = MMI->NextLabelID();
746    BuildMI(MBB, MBBI, TII.get(X86::DBG_LABEL)).addImm(ReadyLabelId);
747  }
748
749  // Skip the callee-saved push instructions.
750  while (MBBI != MBB.end() &&
751         (MBBI->getOpcode() == X86::PUSH32r ||
752          MBBI->getOpcode() == X86::PUSH64r))
753    ++MBBI;
754
755  if (NumBytes) {   // adjust stack pointer: ESP -= numbytes
756    if (NumBytes >= 4096 && Subtarget->isTargetCygMing()) {
757      // Check, whether EAX is livein for this function
758      bool isEAXAlive = false;
759      for (MachineRegisterInfo::livein_iterator
760           II = MF.getRegInfo().livein_begin(),
761           EE = MF.getRegInfo().livein_end(); (II != EE) && !isEAXAlive; ++II) {
762        unsigned Reg = II->first;
763        isEAXAlive = (Reg == X86::EAX || Reg == X86::AX ||
764                      Reg == X86::AH || Reg == X86::AL);
765      }
766
767      // Function prologue calls _alloca to probe the stack when allocating
768      // more than 4k bytes in one go. Touching the stack at 4K increments is
769      // necessary to ensure that the guard pages used by the OS virtual memory
770      // manager are allocated in correct sequence.
771      if (!isEAXAlive) {
772        BuildMI(MBB, MBBI, TII.get(X86::MOV32ri), X86::EAX).addImm(NumBytes);
773        BuildMI(MBB, MBBI, TII.get(X86::CALLpcrel32))
774          .addExternalSymbol("_alloca");
775      } else {
776        // Save EAX
777        BuildMI(MBB, MBBI, TII.get(X86::PUSH32r), X86::EAX);
778        // Allocate NumBytes-4 bytes on stack. We'll also use 4 already
779        // allocated bytes for EAX.
780        BuildMI(MBB, MBBI, TII.get(X86::MOV32ri), X86::EAX).addImm(NumBytes-4);
781        BuildMI(MBB, MBBI, TII.get(X86::CALLpcrel32))
782          .addExternalSymbol("_alloca");
783        // Restore EAX
784        MachineInstr *MI = addRegOffset(BuildMI(MF, TII.get(X86::MOV32rm),X86::EAX),
785                                        StackPtr, false, NumBytes-4);
786        MBB.insert(MBBI, MI);
787      }
788    } else {
789      // If there is an SUB32ri of ESP immediately before this instruction,
790      // merge the two. This can be the case when tail call elimination is
791      // enabled and the callee has more arguments then the caller.
792      NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
793      // If there is an ADD32ri or SUB32ri of ESP immediately after this
794      // instruction, merge the two instructions.
795      mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
796
797      if (NumBytes)
798        emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, TII);
799    }
800  }
801
802  if (needsFrameMoves)
803    emitFrameMoves(MF, FrameLabelId, ReadyLabelId);
804}
805
806void X86RegisterInfo::emitEpilogue(MachineFunction &MF,
807                                   MachineBasicBlock &MBB) const {
808  const MachineFrameInfo *MFI = MF.getFrameInfo();
809  X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
810  MachineBasicBlock::iterator MBBI = prior(MBB.end());
811  unsigned RetOpcode = MBBI->getOpcode();
812
813  switch (RetOpcode) {
814  case X86::RET:
815  case X86::RETI:
816  case X86::TCRETURNdi:
817  case X86::TCRETURNri:
818  case X86::TCRETURNri64:
819  case X86::TCRETURNdi64:
820  case X86::EH_RETURN:
821  case X86::EH_RETURN64:
822  case X86::TAILJMPd:
823  case X86::TAILJMPr:
824  case X86::TAILJMPm: break;  // These are ok
825  default:
826    assert(0 && "Can only insert epilog into returning blocks");
827  }
828
829  // Get the number of bytes to allocate from the FrameInfo
830  uint64_t StackSize = MFI->getStackSize();
831  uint64_t MaxAlign  = MFI->getMaxAlignment();
832  unsigned CSSize = X86FI->getCalleeSavedFrameSize();
833  uint64_t NumBytes = 0;
834
835  if (hasFP(MF)) {
836    // Calculate required stack adjustment
837    uint64_t FrameSize = StackSize - SlotSize;
838    if (needsStackRealignment(MF))
839      FrameSize = (FrameSize + MaxAlign - 1)/MaxAlign*MaxAlign;
840
841    NumBytes = FrameSize - CSSize;
842
843    // pop EBP.
844    BuildMI(MBB, MBBI, TII.get(Is64Bit ? X86::POP64r : X86::POP32r), FramePtr);
845  } else
846    NumBytes = StackSize - CSSize;
847
848  // Skip the callee-saved pop instructions.
849  MachineBasicBlock::iterator LastCSPop = MBBI;
850  while (MBBI != MBB.begin()) {
851    MachineBasicBlock::iterator PI = prior(MBBI);
852    unsigned Opc = PI->getOpcode();
853    if (Opc != X86::POP32r && Opc != X86::POP64r && !PI->getDesc().isReturn())
854      break;
855    --MBBI;
856  }
857
858  // If there is an ADD32ri or SUB32ri of ESP immediately before this
859  // instruction, merge the two instructions.
860  if (NumBytes || MFI->hasVarSizedObjects())
861    mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
862
863  // If dynamic alloca is used, then reset esp to point to the last callee-saved
864  // slot before popping them off! Same applies for the case, when stack was
865  // realigned
866  if (needsStackRealignment(MF)) {
867    // We cannot use LEA here, because stack pointer was realigned. We need to
868    // deallocate local frame back
869    if (CSSize) {
870      emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII);
871      MBBI = prior(LastCSPop);
872    }
873
874    BuildMI(MBB, MBBI,
875            TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
876            StackPtr).addReg(FramePtr);
877  } else if (MFI->hasVarSizedObjects()) {
878    if (CSSize) {
879      unsigned Opc = Is64Bit ? X86::LEA64r : X86::LEA32r;
880      MachineInstr *MI = addRegOffset(BuildMI(MF, TII.get(Opc), StackPtr),
881                                      FramePtr, false, -CSSize);
882      MBB.insert(MBBI, MI);
883    } else
884      BuildMI(MBB, MBBI, TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
885              StackPtr).addReg(FramePtr);
886
887  } else {
888    // adjust stack pointer back: ESP += numbytes
889    if (NumBytes)
890      emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, TII);
891  }
892
893  // We're returning from function via eh_return.
894  if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
895    MBBI = prior(MBB.end());
896    MachineOperand &DestAddr  = MBBI->getOperand(0);
897    assert(DestAddr.isReg() && "Offset should be in register!");
898    BuildMI(MBB, MBBI,
899            TII.get(Is64Bit ? X86::MOV64rr : X86::MOV32rr),
900            StackPtr).addReg(DestAddr.getReg());
901  // Tail call return: adjust the stack pointer and jump to callee
902  } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
903             RetOpcode== X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64) {
904    MBBI = prior(MBB.end());
905    MachineOperand &JumpTarget = MBBI->getOperand(0);
906    MachineOperand &StackAdjust = MBBI->getOperand(1);
907    assert(StackAdjust.isImm() && "Expecting immediate value.");
908
909    // Adjust stack pointer.
910    int StackAdj = StackAdjust.getImm();
911    int MaxTCDelta = X86FI->getTCReturnAddrDelta();
912    int Offset = 0;
913    assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
914    // Incoporate the retaddr area.
915    Offset = StackAdj-MaxTCDelta;
916    assert(Offset >= 0 && "Offset should never be negative");
917    if (Offset) {
918      // Check for possible merge with preceeding ADD instruction.
919      Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
920      emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, TII);
921    }
922    // Jump to label or value in register.
923    if (RetOpcode == X86::TCRETURNdi|| RetOpcode == X86::TCRETURNdi64)
924      BuildMI(MBB, MBBI, TII.get(X86::TAILJMPd)).
925        addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
926    else if (RetOpcode== X86::TCRETURNri64) {
927      BuildMI(MBB, MBBI, TII.get(X86::TAILJMPr64), JumpTarget.getReg());
928    } else
929       BuildMI(MBB, MBBI, TII.get(X86::TAILJMPr), JumpTarget.getReg());
930    // Delete the pseudo instruction TCRETURN.
931    MBB.erase(MBBI);
932  } else if ((RetOpcode == X86::RET || RetOpcode == X86::RETI) &&
933             (X86FI->getTCReturnAddrDelta() < 0)) {
934    // Add the return addr area delta back since we are not tail calling.
935    int delta = -1*X86FI->getTCReturnAddrDelta();
936    MBBI = prior(MBB.end());
937    // Check for possible merge with preceeding ADD instruction.
938    delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
939    emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, TII);
940  }
941}
942
943unsigned X86RegisterInfo::getRARegister() const {
944  if (Is64Bit)
945    return X86::RIP;  // Should have dwarf #16
946  else
947    return X86::EIP;  // Should have dwarf #8
948}
949
950unsigned X86RegisterInfo::getFrameRegister(MachineFunction &MF) const {
951  return hasFP(MF) ? FramePtr : StackPtr;
952}
953
954void X86RegisterInfo::getInitialFrameState(std::vector<MachineMove> &Moves)
955                                                                         const {
956  // Calculate amount of bytes used for return address storing
957  int stackGrowth = (Is64Bit ? -8 : -4);
958
959  // Initial state of the frame pointer is esp+4.
960  MachineLocation Dst(MachineLocation::VirtualFP);
961  MachineLocation Src(StackPtr, stackGrowth);
962  Moves.push_back(MachineMove(0, Dst, Src));
963
964  // Add return address to move list
965  MachineLocation CSDst(StackPtr, stackGrowth);
966  MachineLocation CSSrc(getRARegister());
967  Moves.push_back(MachineMove(0, CSDst, CSSrc));
968}
969
970unsigned X86RegisterInfo::getEHExceptionRegister() const {
971  assert(0 && "What is the exception register");
972  return 0;
973}
974
975unsigned X86RegisterInfo::getEHHandlerRegister() const {
976  assert(0 && "What is the exception handler register");
977  return 0;
978}
979
980namespace llvm {
981unsigned getX86SubSuperRegister(unsigned Reg, MVT VT, bool High) {
982  switch (VT.getSimpleVT()) {
983  default: return Reg;
984  case MVT::i8:
985    if (High) {
986      switch (Reg) {
987      default: return 0;
988      case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
989        return X86::AH;
990      case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
991        return X86::DH;
992      case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
993        return X86::CH;
994      case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
995        return X86::BH;
996      }
997    } else {
998      switch (Reg) {
999      default: return 0;
1000      case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
1001        return X86::AL;
1002      case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
1003        return X86::DL;
1004      case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
1005        return X86::CL;
1006      case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
1007        return X86::BL;
1008      case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
1009        return X86::SIL;
1010      case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
1011        return X86::DIL;
1012      case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
1013        return X86::BPL;
1014      case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
1015        return X86::SPL;
1016      case X86::R8B: case X86::R8W: case X86::R8D: case X86::R8:
1017        return X86::R8B;
1018      case X86::R9B: case X86::R9W: case X86::R9D: case X86::R9:
1019        return X86::R9B;
1020      case X86::R10B: case X86::R10W: case X86::R10D: case X86::R10:
1021        return X86::R10B;
1022      case X86::R11B: case X86::R11W: case X86::R11D: case X86::R11:
1023        return X86::R11B;
1024      case X86::R12B: case X86::R12W: case X86::R12D: case X86::R12:
1025        return X86::R12B;
1026      case X86::R13B: case X86::R13W: case X86::R13D: case X86::R13:
1027        return X86::R13B;
1028      case X86::R14B: case X86::R14W: case X86::R14D: case X86::R14:
1029        return X86::R14B;
1030      case X86::R15B: case X86::R15W: case X86::R15D: case X86::R15:
1031        return X86::R15B;
1032      }
1033    }
1034  case MVT::i16:
1035    switch (Reg) {
1036    default: return Reg;
1037    case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
1038      return X86::AX;
1039    case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
1040      return X86::DX;
1041    case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
1042      return X86::CX;
1043    case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
1044      return X86::BX;
1045    case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
1046      return X86::SI;
1047    case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
1048      return X86::DI;
1049    case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
1050      return X86::BP;
1051    case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
1052      return X86::SP;
1053    case X86::R8B: case X86::R8W: case X86::R8D: case X86::R8:
1054      return X86::R8W;
1055    case X86::R9B: case X86::R9W: case X86::R9D: case X86::R9:
1056      return X86::R9W;
1057    case X86::R10B: case X86::R10W: case X86::R10D: case X86::R10:
1058      return X86::R10W;
1059    case X86::R11B: case X86::R11W: case X86::R11D: case X86::R11:
1060      return X86::R11W;
1061    case X86::R12B: case X86::R12W: case X86::R12D: case X86::R12:
1062      return X86::R12W;
1063    case X86::R13B: case X86::R13W: case X86::R13D: case X86::R13:
1064      return X86::R13W;
1065    case X86::R14B: case X86::R14W: case X86::R14D: case X86::R14:
1066      return X86::R14W;
1067    case X86::R15B: case X86::R15W: case X86::R15D: case X86::R15:
1068      return X86::R15W;
1069    }
1070  case MVT::i32:
1071    switch (Reg) {
1072    default: return Reg;
1073    case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
1074      return X86::EAX;
1075    case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
1076      return X86::EDX;
1077    case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
1078      return X86::ECX;
1079    case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
1080      return X86::EBX;
1081    case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
1082      return X86::ESI;
1083    case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
1084      return X86::EDI;
1085    case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
1086      return X86::EBP;
1087    case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
1088      return X86::ESP;
1089    case X86::R8B: case X86::R8W: case X86::R8D: case X86::R8:
1090      return X86::R8D;
1091    case X86::R9B: case X86::R9W: case X86::R9D: case X86::R9:
1092      return X86::R9D;
1093    case X86::R10B: case X86::R10W: case X86::R10D: case X86::R10:
1094      return X86::R10D;
1095    case X86::R11B: case X86::R11W: case X86::R11D: case X86::R11:
1096      return X86::R11D;
1097    case X86::R12B: case X86::R12W: case X86::R12D: case X86::R12:
1098      return X86::R12D;
1099    case X86::R13B: case X86::R13W: case X86::R13D: case X86::R13:
1100      return X86::R13D;
1101    case X86::R14B: case X86::R14W: case X86::R14D: case X86::R14:
1102      return X86::R14D;
1103    case X86::R15B: case X86::R15W: case X86::R15D: case X86::R15:
1104      return X86::R15D;
1105    }
1106  case MVT::i64:
1107    switch (Reg) {
1108    default: return Reg;
1109    case X86::AH: case X86::AL: case X86::AX: case X86::EAX: case X86::RAX:
1110      return X86::RAX;
1111    case X86::DH: case X86::DL: case X86::DX: case X86::EDX: case X86::RDX:
1112      return X86::RDX;
1113    case X86::CH: case X86::CL: case X86::CX: case X86::ECX: case X86::RCX:
1114      return X86::RCX;
1115    case X86::BH: case X86::BL: case X86::BX: case X86::EBX: case X86::RBX:
1116      return X86::RBX;
1117    case X86::SIL: case X86::SI: case X86::ESI: case X86::RSI:
1118      return X86::RSI;
1119    case X86::DIL: case X86::DI: case X86::EDI: case X86::RDI:
1120      return X86::RDI;
1121    case X86::BPL: case X86::BP: case X86::EBP: case X86::RBP:
1122      return X86::RBP;
1123    case X86::SPL: case X86::SP: case X86::ESP: case X86::RSP:
1124      return X86::RSP;
1125    case X86::R8B: case X86::R8W: case X86::R8D: case X86::R8:
1126      return X86::R8;
1127    case X86::R9B: case X86::R9W: case X86::R9D: case X86::R9:
1128      return X86::R9;
1129    case X86::R10B: case X86::R10W: case X86::R10D: case X86::R10:
1130      return X86::R10;
1131    case X86::R11B: case X86::R11W: case X86::R11D: case X86::R11:
1132      return X86::R11;
1133    case X86::R12B: case X86::R12W: case X86::R12D: case X86::R12:
1134      return X86::R12;
1135    case X86::R13B: case X86::R13W: case X86::R13D: case X86::R13:
1136      return X86::R13;
1137    case X86::R14B: case X86::R14W: case X86::R14D: case X86::R14:
1138      return X86::R14;
1139    case X86::R15B: case X86::R15W: case X86::R15D: case X86::R15:
1140      return X86::R15;
1141    }
1142  }
1143
1144  return Reg;
1145}
1146}
1147
1148#include "X86GenRegisterInfo.inc"
1149
1150namespace {
1151  struct VISIBILITY_HIDDEN MSAC : public MachineFunctionPass {
1152    static char ID;
1153    MSAC() : MachineFunctionPass(&ID) {}
1154
1155    virtual bool runOnMachineFunction(MachineFunction &MF) {
1156      MachineFrameInfo *FFI = MF.getFrameInfo();
1157      MachineRegisterInfo &RI = MF.getRegInfo();
1158
1159      // Calculate max stack alignment of all already allocated stack objects.
1160      unsigned MaxAlign = calculateMaxStackAlignment(FFI);
1161
1162      // Be over-conservative: scan over all vreg defs and find, whether vector
1163      // registers are used. If yes - there is probability, that vector register
1164      // will be spilled and thus stack needs to be aligned properly.
1165      for (unsigned RegNum = TargetRegisterInfo::FirstVirtualRegister;
1166           RegNum < RI.getLastVirtReg(); ++RegNum)
1167        MaxAlign = std::max(MaxAlign, RI.getRegClass(RegNum)->getAlignment());
1168
1169      FFI->setMaxAlignment(MaxAlign);
1170
1171      return false;
1172    }
1173
1174    virtual const char *getPassName() const {
1175      return "X86 Maximal Stack Alignment Calculator";
1176    }
1177  };
1178
1179  char MSAC::ID = 0;
1180}
1181
1182FunctionPass*
1183llvm::createX86MaxStackAlignmentCalculatorPass() { return new MSAC(); }
1184