Add new shorter predicates for testing machine operands for various types:
[oota-llvm.git] / lib / Target / PowerPC / PPCRegisterInfo.cpp
1 //===- PPCRegisterInfo.cpp - PowerPC 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 PowerPC implementation of the MRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "reginfo"
15 #include "PPC.h"
16 #include "PPCInstrBuilder.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCRegisterInfo.h"
19 #include "PPCFrameInfo.h"
20 #include "PPCSubtarget.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Type.h"
23 #include "llvm/CodeGen/ValueTypes.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineLocation.h"
29 #include "llvm/CodeGen/SelectionDAGNodes.h"
30 #include "llvm/Target/TargetFrameInfo.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/ADT/BitVector.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include <cstdlib>
40 using namespace llvm;
41
42 /// getRegisterNumbering - Given the enum value for some register, e.g.
43 /// PPC::F14, return the number that it corresponds to (e.g. 14).
44 unsigned PPCRegisterInfo::getRegisterNumbering(unsigned RegEnum) {
45   using namespace PPC;
46   switch (RegEnum) {
47   case R0 :  case X0 :  case F0 :  case V0 : case CR0:  return  0;
48   case R1 :  case X1 :  case F1 :  case V1 : case CR1:  return  1;
49   case R2 :  case X2 :  case F2 :  case V2 : case CR2:  return  2;
50   case R3 :  case X3 :  case F3 :  case V3 : case CR3:  return  3;
51   case R4 :  case X4 :  case F4 :  case V4 : case CR4:  return  4;
52   case R5 :  case X5 :  case F5 :  case V5 : case CR5:  return  5;
53   case R6 :  case X6 :  case F6 :  case V6 : case CR6:  return  6;
54   case R7 :  case X7 :  case F7 :  case V7 : case CR7:  return  7;
55   case R8 :  case X8 :  case F8 :  case V8 : return  8;
56   case R9 :  case X9 :  case F9 :  case V9 : return  9;
57   case R10:  case X10:  case F10:  case V10: return 10;
58   case R11:  case X11:  case F11:  case V11: return 11;
59   case R12:  case X12:  case F12:  case V12: return 12;
60   case R13:  case X13:  case F13:  case V13: return 13;
61   case R14:  case X14:  case F14:  case V14: return 14;
62   case R15:  case X15:  case F15:  case V15: return 15;
63   case R16:  case X16:  case F16:  case V16: return 16;
64   case R17:  case X17:  case F17:  case V17: return 17;
65   case R18:  case X18:  case F18:  case V18: return 18;
66   case R19:  case X19:  case F19:  case V19: return 19;
67   case R20:  case X20:  case F20:  case V20: return 20;
68   case R21:  case X21:  case F21:  case V21: return 21;
69   case R22:  case X22:  case F22:  case V22: return 22;
70   case R23:  case X23:  case F23:  case V23: return 23;
71   case R24:  case X24:  case F24:  case V24: return 24;
72   case R25:  case X25:  case F25:  case V25: return 25;
73   case R26:  case X26:  case F26:  case V26: return 26;
74   case R27:  case X27:  case F27:  case V27: return 27;
75   case R28:  case X28:  case F28:  case V28: return 28;
76   case R29:  case X29:  case F29:  case V29: return 29;
77   case R30:  case X30:  case F30:  case V30: return 30;
78   case R31:  case X31:  case F31:  case V31: return 31;
79   default:
80     cerr << "Unhandled reg in PPCRegisterInfo::getRegisterNumbering!\n";
81     abort();
82   }
83 }
84
85 PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST,
86                                  const TargetInstrInfo &tii)
87   : PPCGenRegisterInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
88     Subtarget(ST), TII(tii) {
89   ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
90   ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
91   ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
92   ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
93   ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
94   ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
95   ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
96   ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
97
98   // 64-bit
99   ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
100   ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
101   ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
102   ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
103   ImmToIdxMap[PPC::ADDI8] = PPC::ADD8; ImmToIdxMap[PPC::STD_32] = PPC::STDX_32;
104 }
105
106 static void StoreRegToStackSlot(const TargetInstrInfo &TII,
107                                 unsigned SrcReg, bool isKill, int FrameIdx,
108                                 const TargetRegisterClass *RC,
109                                 SmallVectorImpl<MachineInstr*> &NewMIs) {
110   if (RC == PPC::GPRCRegisterClass) {
111     if (SrcReg != PPC::LR) {
112       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STW))
113                                 .addReg(SrcReg, false, false, isKill), FrameIdx));
114     } else {
115       // FIXME: this spills LR immediately to memory in one step.  To do this,
116       // we use R11, which we know cannot be used in the prolog/epilog.  This is
117       // a hack.
118       NewMIs.push_back(BuildMI(TII.get(PPC::MFLR), PPC::R11));
119       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STW))
120                               .addReg(PPC::R11, false, false, isKill), FrameIdx));
121     }
122   } else if (RC == PPC::G8RCRegisterClass) {
123     if (SrcReg != PPC::LR8) {
124       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STD))
125                                 .addReg(SrcReg, false, false, isKill), FrameIdx));
126     } else {
127       // FIXME: this spills LR immediately to memory in one step.  To do this,
128       // we use R11, which we know cannot be used in the prolog/epilog.  This is
129       // a hack.
130       NewMIs.push_back(BuildMI(TII.get(PPC::MFLR8), PPC::X11));
131       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STD))
132                               .addReg(PPC::X11, false, false, isKill), FrameIdx));
133     }
134   } else if (RC == PPC::F8RCRegisterClass) {
135     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STFD))
136                                 .addReg(SrcReg, false, false, isKill), FrameIdx));
137   } else if (RC == PPC::F4RCRegisterClass) {
138     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STFS))
139                                 .addReg(SrcReg, false, false, isKill), FrameIdx));
140   } else if (RC == PPC::CRRCRegisterClass) {
141     // FIXME: We use R0 here, because it isn't available for RA.
142     // We need to store the CR in the low 4-bits of the saved value.  First,
143     // issue a MFCR to save all of the CRBits.
144     NewMIs.push_back(BuildMI(TII.get(PPC::MFCR), PPC::R0));
145     
146     // If the saved register wasn't CR0, shift the bits left so that they are in
147     // CR0's slot.
148     if (SrcReg != PPC::CR0) {
149       unsigned ShiftBits = PPCRegisterInfo::getRegisterNumbering(SrcReg)*4;
150       // rlwinm r0, r0, ShiftBits, 0, 31.
151       NewMIs.push_back(BuildMI(TII.get(PPC::RLWINM), PPC::R0)
152                        .addReg(PPC::R0).addImm(ShiftBits).addImm(0).addImm(31));
153     }
154     
155     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::STW))
156                                .addReg(PPC::R0, false, false, isKill), FrameIdx));
157   } else if (RC == PPC::VRRCRegisterClass) {
158     // We don't have indexed addressing for vector loads.  Emit:
159     // R0 = ADDI FI#
160     // STVX VAL, 0, R0
161     // 
162     // FIXME: We use R0 here, because it isn't available for RA.
163     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::ADDI), PPC::R0),
164                                        FrameIdx, 0, 0));
165     NewMIs.push_back(BuildMI(TII.get(PPC::STVX))
166            .addReg(SrcReg, false, false, isKill).addReg(PPC::R0).addReg(PPC::R0));
167   } else {
168     assert(0 && "Unknown regclass!");
169     abort();
170   }
171 }
172
173 void
174 PPCRegisterInfo::storeRegToStackSlot(MachineBasicBlock &MBB,
175                                      MachineBasicBlock::iterator MI,
176                                      unsigned SrcReg, bool isKill, int FrameIdx,
177                                      const TargetRegisterClass *RC) const {
178   SmallVector<MachineInstr*, 4> NewMIs;
179   StoreRegToStackSlot(TII, SrcReg, isKill, FrameIdx, RC, NewMIs);
180   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
181     MBB.insert(MI, NewMIs[i]);
182 }
183
184 void PPCRegisterInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
185                                      bool isKill,
186                                      SmallVectorImpl<MachineOperand> &Addr,
187                                      const TargetRegisterClass *RC,
188                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
189   if (Addr[0].isFrameIndex()) {
190     StoreRegToStackSlot(TII, SrcReg, isKill, Addr[0].getIndex(), RC, NewMIs);
191     return;
192   }
193
194   unsigned Opc = 0;
195   if (RC == PPC::GPRCRegisterClass) {
196     Opc = PPC::STW;
197   } else if (RC == PPC::G8RCRegisterClass) {
198     Opc = PPC::STD;
199   } else if (RC == PPC::F8RCRegisterClass) {
200     Opc = PPC::STFD;
201   } else if (RC == PPC::F4RCRegisterClass) {
202     Opc = PPC::STFS;
203   } else if (RC == PPC::VRRCRegisterClass) {
204     Opc = PPC::STVX;
205   } else {
206     assert(0 && "Unknown regclass!");
207     abort();
208   }
209   MachineInstrBuilder MIB = BuildMI(TII.get(Opc))
210     .addReg(SrcReg, false, false, isKill);
211   for (unsigned i = 0, e = Addr.size(); i != e; ++i) {
212     MachineOperand &MO = Addr[i];
213     if (MO.isRegister())
214       MIB.addReg(MO.getReg());
215     else if (MO.isImmediate())
216       MIB.addImm(MO.getImm());
217     else
218       MIB.addFrameIndex(MO.getIndex());
219   }
220   NewMIs.push_back(MIB);
221   return;
222 }
223
224 static void LoadRegFromStackSlot(const TargetInstrInfo &TII,
225                                  unsigned DestReg, int FrameIdx,
226                                  const TargetRegisterClass *RC,
227                                  SmallVectorImpl<MachineInstr*> &NewMIs) {
228   if (RC == PPC::GPRCRegisterClass) {
229     if (DestReg != PPC::LR) {
230       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LWZ), DestReg),
231                                          FrameIdx));
232     } else {
233       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LWZ), PPC::R11),
234                                          FrameIdx));
235       NewMIs.push_back(BuildMI(TII.get(PPC::MTLR)).addReg(PPC::R11));
236     }
237   } else if (RC == PPC::G8RCRegisterClass) {
238     if (DestReg != PPC::LR8) {
239       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LD), DestReg),
240                                          FrameIdx));
241     } else {
242       NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LD), PPC::R11),
243                                          FrameIdx));
244       NewMIs.push_back(BuildMI(TII.get(PPC::MTLR8)).addReg(PPC::R11));
245     }
246   } else if (RC == PPC::F8RCRegisterClass) {
247     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LFD), DestReg),
248                                        FrameIdx));
249   } else if (RC == PPC::F4RCRegisterClass) {
250     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LFS), DestReg),
251                                        FrameIdx));
252   } else if (RC == PPC::CRRCRegisterClass) {
253     // FIXME: We use R0 here, because it isn't available for RA.
254     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::LWZ), PPC::R0),
255                                        FrameIdx));
256     
257     // If the reloaded register isn't CR0, shift the bits right so that they are
258     // in the right CR's slot.
259     if (DestReg != PPC::CR0) {
260       unsigned ShiftBits = PPCRegisterInfo::getRegisterNumbering(DestReg)*4;
261       // rlwinm r11, r11, 32-ShiftBits, 0, 31.
262       NewMIs.push_back(BuildMI(TII.get(PPC::RLWINM), PPC::R0)
263                     .addReg(PPC::R0).addImm(32-ShiftBits).addImm(0).addImm(31));
264     }
265     
266     NewMIs.push_back(BuildMI(TII.get(PPC::MTCRF), DestReg).addReg(PPC::R0));
267   } else if (RC == PPC::VRRCRegisterClass) {
268     // We don't have indexed addressing for vector loads.  Emit:
269     // R0 = ADDI FI#
270     // Dest = LVX 0, R0
271     // 
272     // FIXME: We use R0 here, because it isn't available for RA.
273     NewMIs.push_back(addFrameReference(BuildMI(TII.get(PPC::ADDI), PPC::R0),
274                                        FrameIdx, 0, 0));
275     NewMIs.push_back(BuildMI(TII.get(PPC::LVX),DestReg).addReg(PPC::R0)
276                      .addReg(PPC::R0));
277   } else {
278     assert(0 && "Unknown regclass!");
279     abort();
280   }
281 }
282
283 void
284 PPCRegisterInfo::loadRegFromStackSlot(MachineBasicBlock &MBB,
285                                       MachineBasicBlock::iterator MI,
286                                       unsigned DestReg, int FrameIdx,
287                                       const TargetRegisterClass *RC) const {
288   SmallVector<MachineInstr*, 4> NewMIs;
289   LoadRegFromStackSlot(TII, DestReg, FrameIdx, RC, NewMIs);
290   for (unsigned i = 0, e = NewMIs.size(); i != e; ++i)
291     MBB.insert(MI, NewMIs[i]);
292 }
293
294 void PPCRegisterInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
295                                       SmallVectorImpl<MachineOperand> &Addr,
296                                       const TargetRegisterClass *RC,
297                                   SmallVectorImpl<MachineInstr*> &NewMIs) const{
298   if (Addr[0].isFrameIndex()) {
299     LoadRegFromStackSlot(TII, DestReg, Addr[0].getIndex(), RC, NewMIs);
300     return;
301   }
302
303   unsigned Opc = 0;
304   if (RC == PPC::GPRCRegisterClass) {
305     assert(DestReg != PPC::LR && "Can't handle this yet!");
306     Opc = PPC::LWZ;
307   } else if (RC == PPC::G8RCRegisterClass) {
308     assert(DestReg != PPC::LR8 && "Can't handle this yet!");
309     Opc = PPC::LD;
310   } else if (RC == PPC::F8RCRegisterClass) {
311     Opc = PPC::LFD;
312   } else if (RC == PPC::F4RCRegisterClass) {
313     Opc = PPC::LFS;
314   } else if (RC == PPC::VRRCRegisterClass) {
315     Opc = PPC::LVX;
316   } else {
317     assert(0 && "Unknown regclass!");
318     abort();
319   }
320   MachineInstrBuilder MIB = BuildMI(TII.get(Opc), DestReg);
321   for (unsigned i = 0, e = Addr.size(); i != e; ++i) {
322     MachineOperand &MO = Addr[i];
323     if (MO.isRegister())
324       MIB.addReg(MO.getReg());
325     else if (MO.isImmediate())
326       MIB.addImm(MO.getImm());
327     else
328       MIB.addFrameIndex(MO.getIndex());
329   }
330   NewMIs.push_back(MIB);
331   return;
332 }
333
334 void PPCRegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
335                                    MachineBasicBlock::iterator MI,
336                                    unsigned DestReg, unsigned SrcReg,
337                                    const TargetRegisterClass *DestRC,
338                                    const TargetRegisterClass *SrcRC) const {
339   if (DestRC != SrcRC) {
340     cerr << "Not yet supported!";
341     abort();
342   }
343
344   if (DestRC == PPC::GPRCRegisterClass) {
345     BuildMI(MBB, MI, TII.get(PPC::OR), DestReg).addReg(SrcReg).addReg(SrcReg);
346   } else if (DestRC == PPC::G8RCRegisterClass) {
347     BuildMI(MBB, MI, TII.get(PPC::OR8), DestReg).addReg(SrcReg).addReg(SrcReg);
348   } else if (DestRC == PPC::F4RCRegisterClass) {
349     BuildMI(MBB, MI, TII.get(PPC::FMRS), DestReg).addReg(SrcReg);
350   } else if (DestRC == PPC::F8RCRegisterClass) {
351     BuildMI(MBB, MI, TII.get(PPC::FMRD), DestReg).addReg(SrcReg);
352   } else if (DestRC == PPC::CRRCRegisterClass) {
353     BuildMI(MBB, MI, TII.get(PPC::MCRF), DestReg).addReg(SrcReg);
354   } else if (DestRC == PPC::VRRCRegisterClass) {
355     BuildMI(MBB, MI, TII.get(PPC::VOR), DestReg).addReg(SrcReg).addReg(SrcReg);
356   } else {
357     cerr << "Attempt to copy register that is not GPR or FPR";
358     abort();
359   }
360 }
361
362 void PPCRegisterInfo::reMaterialize(MachineBasicBlock &MBB,
363                                     MachineBasicBlock::iterator I,
364                                     unsigned DestReg,
365                                     const MachineInstr *Orig) const {
366   MachineInstr *MI = Orig->clone();
367   MI->getOperand(0).setReg(DestReg);
368   MBB.insert(I, MI);
369 }
370
371 const unsigned*
372 PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
373   // 32-bit Darwin calling convention. 
374   static const unsigned Macho32_CalleeSavedRegs[] = {
375               PPC::R13, PPC::R14, PPC::R15,
376     PPC::R16, PPC::R17, PPC::R18, PPC::R19,
377     PPC::R20, PPC::R21, PPC::R22, PPC::R23,
378     PPC::R24, PPC::R25, PPC::R26, PPC::R27,
379     PPC::R28, PPC::R29, PPC::R30, PPC::R31,
380
381     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
382     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
383     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
384     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
385     PPC::F30, PPC::F31,
386     
387     PPC::CR2, PPC::CR3, PPC::CR4,
388     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
389     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
390     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
391     
392     PPC::LR,  0
393   };
394   
395   static const unsigned ELF32_CalleeSavedRegs[] = {
396               PPC::R13, PPC::R14, PPC::R15,
397     PPC::R16, PPC::R17, PPC::R18, PPC::R19,
398     PPC::R20, PPC::R21, PPC::R22, PPC::R23,
399     PPC::R24, PPC::R25, PPC::R26, PPC::R27,
400     PPC::R28, PPC::R29, PPC::R30, PPC::R31,
401
402                                   PPC::F9,
403     PPC::F10, PPC::F11, PPC::F12, PPC::F13,
404     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
405     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
406     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
407     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
408     PPC::F30, PPC::F31,
409     
410     PPC::CR2, PPC::CR3, PPC::CR4,
411     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
412     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
413     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
414     
415     PPC::LR,  0
416   };
417   // 64-bit Darwin calling convention. 
418   static const unsigned Macho64_CalleeSavedRegs[] = {
419     PPC::X14, PPC::X15,
420     PPC::X16, PPC::X17, PPC::X18, PPC::X19,
421     PPC::X20, PPC::X21, PPC::X22, PPC::X23,
422     PPC::X24, PPC::X25, PPC::X26, PPC::X27,
423     PPC::X28, PPC::X29, PPC::X30, PPC::X31,
424     
425     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
426     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
427     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
428     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
429     PPC::F30, PPC::F31,
430     
431     PPC::CR2, PPC::CR3, PPC::CR4,
432     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
433     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
434     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
435     
436     PPC::LR8,  0
437   };
438   
439   if (Subtarget.isMachoABI())
440     return Subtarget.isPPC64() ? Macho64_CalleeSavedRegs :
441                                  Macho32_CalleeSavedRegs;
442   
443   // ELF 32.
444   return ELF32_CalleeSavedRegs;
445 }
446
447 const TargetRegisterClass* const*
448 PPCRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
449   // 32-bit Macho calling convention. 
450   static const TargetRegisterClass * const Macho32_CalleeSavedRegClasses[] = {
451                        &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
452     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
453     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
454     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
455     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
456
457     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
458     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
459     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
460     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
461     &PPC::F8RCRegClass,&PPC::F8RCRegClass,
462     
463     &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
464     
465     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
466     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
467     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
468     
469     &PPC::GPRCRegClass, 0
470   };
471   
472   static const TargetRegisterClass * const ELF32_CalleeSavedRegClasses[] = {
473                        &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
474     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
475     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
476     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
477     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
478
479                                                              &PPC::F8RCRegClass,
480     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
481     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
482     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
483     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
484     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
485     &PPC::F8RCRegClass,&PPC::F8RCRegClass,
486     
487     &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
488     
489     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
490     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
491     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
492     
493     &PPC::GPRCRegClass, 0
494   };
495   
496   // 64-bit Macho calling convention. 
497   static const TargetRegisterClass * const Macho64_CalleeSavedRegClasses[] = {
498     &PPC::G8RCRegClass,&PPC::G8RCRegClass,
499     &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
500     &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
501     &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
502     &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
503     
504     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
505     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
506     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
507     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
508     &PPC::F8RCRegClass,&PPC::F8RCRegClass,
509     
510     &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
511     
512     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
513     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
514     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
515     
516     &PPC::G8RCRegClass, 0
517   };
518   
519   if (Subtarget.isMachoABI())
520     return Subtarget.isPPC64() ? Macho64_CalleeSavedRegClasses :
521                                  Macho32_CalleeSavedRegClasses;
522   
523   // ELF 32.
524   return ELF32_CalleeSavedRegClasses;
525 }
526
527 // needsFP - Return true if the specified function should have a dedicated frame
528 // pointer register.  This is true if the function has variable sized allocas or
529 // if frame pointer elimination is disabled.
530 //
531 static bool needsFP(const MachineFunction &MF) {
532   const MachineFrameInfo *MFI = MF.getFrameInfo();
533   return NoFramePointerElim || MFI->hasVarSizedObjects();
534 }
535
536 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
537   BitVector Reserved(getNumRegs());
538   Reserved.set(PPC::R0);
539   Reserved.set(PPC::R1);
540   Reserved.set(PPC::LR);
541   // In Linux, r2 is reserved for the OS.
542   if (!Subtarget.isDarwin())
543     Reserved.set(PPC::R2);
544   // On PPC64, r13 is the thread pointer.  Never allocate this register.
545   // Note that this is overconservative, as it also prevents allocation of
546   // R31 when the FP is not needed.
547   if (Subtarget.isPPC64()) {
548     Reserved.set(PPC::R13);
549     Reserved.set(PPC::R31);
550   }
551   if (needsFP(MF))
552     Reserved.set(PPC::R31);
553   return Reserved;
554 }
555
556 /// foldMemoryOperand - PowerPC (like most RISC's) can only fold spills into
557 /// copy instructions, turning them into load/store instructions.
558 MachineInstr *PPCRegisterInfo::foldMemoryOperand(MachineInstr *MI,
559                                               SmallVectorImpl<unsigned> &Ops,
560                                               int FrameIndex) const {
561   if (Ops.size() != 1) return NULL;
562
563   // Make sure this is a reg-reg copy.  Note that we can't handle MCRF, because
564   // it takes more than one instruction to store it.
565   unsigned Opc = MI->getOpcode();
566   unsigned OpNum = Ops[0];
567
568   MachineInstr *NewMI = NULL;
569   if ((Opc == PPC::OR &&
570        MI->getOperand(1).getReg() == MI->getOperand(2).getReg())) {
571     if (OpNum == 0) {  // move -> store
572       unsigned InReg = MI->getOperand(1).getReg();
573       NewMI = addFrameReference(BuildMI(TII.get(PPC::STW)).addReg(InReg),
574                                 FrameIndex);
575     } else {           // move -> load
576       unsigned OutReg = MI->getOperand(0).getReg();
577       NewMI = addFrameReference(BuildMI(TII.get(PPC::LWZ), OutReg),
578                                 FrameIndex);
579     }
580   } else if ((Opc == PPC::OR8 &&
581               MI->getOperand(1).getReg() == MI->getOperand(2).getReg())) {
582     if (OpNum == 0) {  // move -> store
583       unsigned InReg = MI->getOperand(1).getReg();
584       NewMI = addFrameReference(BuildMI(TII.get(PPC::STD)).addReg(InReg),
585                                 FrameIndex);
586     } else {           // move -> load
587       unsigned OutReg = MI->getOperand(0).getReg();
588       NewMI = addFrameReference(BuildMI(TII.get(PPC::LD), OutReg), FrameIndex);
589     }
590   } else if (Opc == PPC::FMRD) {
591     if (OpNum == 0) {  // move -> store
592       unsigned InReg = MI->getOperand(1).getReg();
593       NewMI = addFrameReference(BuildMI(TII.get(PPC::STFD)).addReg(InReg),
594                                 FrameIndex);
595     } else {           // move -> load
596       unsigned OutReg = MI->getOperand(0).getReg();
597       NewMI = addFrameReference(BuildMI(TII.get(PPC::LFD), OutReg), FrameIndex);
598     }
599   } else if (Opc == PPC::FMRS) {
600     if (OpNum == 0) {  // move -> store
601       unsigned InReg = MI->getOperand(1).getReg();
602       NewMI = addFrameReference(BuildMI(TII.get(PPC::STFS)).addReg(InReg),
603                                 FrameIndex);
604     } else {           // move -> load
605       unsigned OutReg = MI->getOperand(0).getReg();
606       NewMI = addFrameReference(BuildMI(TII.get(PPC::LFS), OutReg), FrameIndex);
607     }
608   }
609
610   if (NewMI)
611     NewMI->copyKillDeadInfo(MI);
612   return NewMI;
613 }
614
615 bool PPCRegisterInfo::canFoldMemoryOperand(MachineInstr *MI,
616                                          SmallVectorImpl<unsigned> &Ops) const {
617   if (Ops.size() != 1) return false;
618
619   // Make sure this is a reg-reg copy.  Note that we can't handle MCRF, because
620   // it takes more than one instruction to store it.
621   unsigned Opc = MI->getOpcode();
622
623   if ((Opc == PPC::OR &&
624        MI->getOperand(1).getReg() == MI->getOperand(2).getReg()))
625     return true;
626   else if ((Opc == PPC::OR8 &&
627               MI->getOperand(1).getReg() == MI->getOperand(2).getReg()))
628     return true;
629   else if (Opc == PPC::FMRD || Opc == PPC::FMRS)
630     return true;
631
632   return false;
633 }
634
635 //===----------------------------------------------------------------------===//
636 // Stack Frame Processing methods
637 //===----------------------------------------------------------------------===//
638
639 // hasFP - Return true if the specified function actually has a dedicated frame
640 // pointer register.  This is true if the function needs a frame pointer and has
641 // a non-zero stack size.
642 bool PPCRegisterInfo::hasFP(const MachineFunction &MF) const {
643   const MachineFrameInfo *MFI = MF.getFrameInfo();
644   return MFI->getStackSize() && needsFP(MF);
645 }
646
647 /// MustSaveLR - Return true if this function requires that we save the LR
648 /// register onto the stack in the prolog and restore it in the epilog of the
649 /// function.
650 static bool MustSaveLR(const MachineFunction &MF) {
651   const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
652   
653   // We need an save/restore of LR if there is any use/def of LR explicitly, or
654   // if there is some use of the LR stack slot (e.g. for builtin_return_address.
655   return MFI->usesLR() || MFI->isLRStoreRequired() ||
656          // FIXME: Anything that has a call should clobber the LR register,
657          // isn't this redundant??
658          MF.getFrameInfo()->hasCalls();
659 }
660
661 void PPCRegisterInfo::
662 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
663                               MachineBasicBlock::iterator I) const {
664   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
665   MBB.erase(I);
666 }
667
668 /// LowerDynamicAlloc - Generate the code for allocating an object in the
669 /// current frame.  The sequence of code with be in the general form
670 ///
671 ///   addi   R0, SP, #frameSize ; get the address of the previous frame
672 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
673 ///   addi   Rnew, SP, #maxCalFrameSize ; get the top of the allocation
674 ///
675 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
676   // Get the instruction.
677   MachineInstr &MI = *II;
678   // Get the instruction's basic block.
679   MachineBasicBlock &MBB = *MI.getParent();
680   // Get the basic block's function.
681   MachineFunction &MF = *MBB.getParent();
682   // Get the frame info.
683   MachineFrameInfo *MFI = MF.getFrameInfo();
684   // Determine whether 64-bit pointers are used.
685   bool LP64 = Subtarget.isPPC64();
686
687   // Get the maximum call stack size.
688   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
689   // Get the total frame size.
690   unsigned FrameSize = MFI->getStackSize();
691   
692   // Get stack alignments.
693   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
694   unsigned MaxAlign = MFI->getMaxAlignment();
695   assert(MaxAlign <= TargetAlign &&
696          "Dynamic alloca with large aligns not supported");
697
698   // Determine the previous frame's address.  If FrameSize can't be
699   // represented as 16 bits or we need special alignment, then we load the
700   // previous frame's address from 0(SP).  Why not do an addis of the hi? 
701   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero. 
702   // Constructing the constant and adding would take 3 instructions. 
703   // Fortunately, a frame greater than 32K is rare.
704   if (MaxAlign < TargetAlign && isInt16(FrameSize)) {
705     BuildMI(MBB, II, TII.get(PPC::ADDI), PPC::R0)
706       .addReg(PPC::R31)
707       .addImm(FrameSize);
708   } else if (LP64) {
709     BuildMI(MBB, II, TII.get(PPC::LD), PPC::X0)
710       .addImm(0)
711       .addReg(PPC::X1);
712   } else {
713     BuildMI(MBB, II, TII.get(PPC::LWZ), PPC::R0)
714       .addImm(0)
715       .addReg(PPC::R1);
716   }
717   
718   // Grow the stack and update the stack pointer link, then
719   // determine the address of new allocated space.
720   if (LP64) {
721     BuildMI(MBB, II, TII.get(PPC::STDUX))
722       .addReg(PPC::X0)
723       .addReg(PPC::X1)
724       .addReg(MI.getOperand(1).getReg());
725     BuildMI(MBB, II, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
726       .addReg(PPC::X1)
727       .addImm(maxCallFrameSize);
728   } else {
729     BuildMI(MBB, II, TII.get(PPC::STWUX))
730       .addReg(PPC::R0)
731       .addReg(PPC::R1)
732       .addReg(MI.getOperand(1).getReg());
733     BuildMI(MBB, II, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
734       .addReg(PPC::R1)
735       .addImm(maxCallFrameSize);
736   }
737   
738   // Discard the DYNALLOC instruction.
739   MBB.erase(II);
740 }
741
742 void PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
743                                           int SPAdj, RegScavenger *RS) const {
744   assert(SPAdj == 0 && "Unexpected");
745
746   // Get the instruction.
747   MachineInstr &MI = *II;
748   // Get the instruction's basic block.
749   MachineBasicBlock &MBB = *MI.getParent();
750   // Get the basic block's function.
751   MachineFunction &MF = *MBB.getParent();
752   // Get the frame info.
753   MachineFrameInfo *MFI = MF.getFrameInfo();
754
755   // Find out which operand is the frame index.
756   unsigned FIOperandNo = 0;
757   while (!MI.getOperand(FIOperandNo).isFrameIndex()) {
758     ++FIOperandNo;
759     assert(FIOperandNo != MI.getNumOperands() &&
760            "Instr doesn't have FrameIndex operand!");
761   }
762   // Take into account whether it's an add or mem instruction
763   unsigned OffsetOperandNo = (FIOperandNo == 2) ? 1 : 2;
764   if (MI.getOpcode() == TargetInstrInfo::INLINEASM)
765     OffsetOperandNo = FIOperandNo-1;
766       
767   // Get the frame index.
768   int FrameIndex = MI.getOperand(FIOperandNo).getIndex();
769   
770   // Get the frame pointer save index.  Users of this index are primarily
771   // DYNALLOC instructions.
772   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
773   int FPSI = FI->getFramePointerSaveIndex();
774   // Get the instruction opcode.
775   unsigned OpC = MI.getOpcode();
776   
777   // Special case for dynamic alloca.
778   if (FPSI && FrameIndex == FPSI &&
779       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
780     lowerDynamicAlloc(II);
781     return;
782   }
783
784   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
785   MI.getOperand(FIOperandNo).ChangeToRegister(hasFP(MF) ? PPC::R31 : PPC::R1,
786                                               false);
787
788   // Figure out if the offset in the instruction is shifted right two bits. This
789   // is true for instructions like "STD", which the machine implicitly adds two
790   // low zeros to.
791   bool isIXAddr = false;
792   switch (OpC) {
793   case PPC::LWA:
794   case PPC::LD:
795   case PPC::STD:
796   case PPC::STD_32:
797     isIXAddr = true;
798     break;
799   }
800   
801   // Now add the frame object offset to the offset from r1.
802   int Offset = MFI->getObjectOffset(FrameIndex);
803   if (!isIXAddr)
804     Offset += MI.getOperand(OffsetOperandNo).getImm();
805   else
806     Offset += MI.getOperand(OffsetOperandNo).getImm() << 2;
807
808   // If we're not using a Frame Pointer that has been set to the value of the
809   // SP before having the stack size subtracted from it, then add the stack size
810   // to Offset to get the correct offset.
811   Offset += MFI->getStackSize();
812
813   // If we can, encode the offset directly into the instruction.  If this is a
814   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
815   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
816   // clear can be encoded.  This is extremely uncommon, because normally you
817   // only "std" to a stack slot that is at least 4-byte aligned, but it can
818   // happen in invalid code.
819   if (isInt16(Offset) && (!isIXAddr || (Offset & 3) == 0)) {
820     if (isIXAddr)
821       Offset >>= 2;    // The actual encoded value has the low two bits zero.
822     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
823     return;
824   }
825   
826   // Insert a set of r0 with the full offset value before the ld, st, or add
827   BuildMI(MBB, II, TII.get(PPC::LIS), PPC::R0).addImm(Offset >> 16);
828   BuildMI(MBB, II, TII.get(PPC::ORI), PPC::R0).addReg(PPC::R0).addImm(Offset);
829   
830   // Convert into indexed form of the instruction
831   // sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
832   // addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
833   unsigned OperandBase;
834   if (OpC != TargetInstrInfo::INLINEASM) {
835     assert(ImmToIdxMap.count(OpC) &&
836            "No indexed form of load or store available!");
837     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
838     MI.setInstrDescriptor(TII.get(NewOpcode));
839     OperandBase = 1;
840   } else {
841     OperandBase = OffsetOperandNo;
842   }
843     
844   unsigned StackReg = MI.getOperand(FIOperandNo).getReg();
845   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
846   MI.getOperand(OperandBase+1).ChangeToRegister(PPC::R0, false);
847 }
848
849 /// VRRegNo - Map from a numbered VR register to its enum value.
850 ///
851 static const unsigned short VRRegNo[] = {
852  PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
853  PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
854  PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
855  PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
856 };
857
858 /// RemoveVRSaveCode - We have found that this function does not need any code
859 /// to manipulate the VRSAVE register, even though it uses vector registers.
860 /// This can happen when the only registers used are known to be live in or out
861 /// of the function.  Remove all of the VRSAVE related code from the function.
862 static void RemoveVRSaveCode(MachineInstr *MI) {
863   MachineBasicBlock *Entry = MI->getParent();
864   MachineFunction *MF = Entry->getParent();
865
866   // We know that the MTVRSAVE instruction immediately follows MI.  Remove it.
867   MachineBasicBlock::iterator MBBI = MI;
868   ++MBBI;
869   assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
870   MBBI->eraseFromParent();
871   
872   bool RemovedAllMTVRSAVEs = true;
873   // See if we can find and remove the MTVRSAVE instruction from all of the
874   // epilog blocks.
875   const TargetInstrInfo &TII = *MF->getTarget().getInstrInfo();
876   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
877     // If last instruction is a return instruction, add an epilogue
878     if (!I->empty() && TII.isReturn(I->back().getOpcode())) {
879       bool FoundIt = false;
880       for (MBBI = I->end(); MBBI != I->begin(); ) {
881         --MBBI;
882         if (MBBI->getOpcode() == PPC::MTVRSAVE) {
883           MBBI->eraseFromParent();  // remove it.
884           FoundIt = true;
885           break;
886         }
887       }
888       RemovedAllMTVRSAVEs &= FoundIt;
889     }
890   }
891
892   // If we found and removed all MTVRSAVE instructions, remove the read of
893   // VRSAVE as well.
894   if (RemovedAllMTVRSAVEs) {
895     MBBI = MI;
896     assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
897     --MBBI;
898     assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
899     MBBI->eraseFromParent();
900   }
901   
902   // Finally, nuke the UPDATE_VRSAVE.
903   MI->eraseFromParent();
904 }
905
906 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
907 // instruction selector.  Based on the vector registers that have been used,
908 // transform this into the appropriate ORI instruction.
909 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
910   MachineFunction *MF = MI->getParent()->getParent();
911
912   unsigned UsedRegMask = 0;
913   for (unsigned i = 0; i != 32; ++i)
914     if (MF->isPhysRegUsed(VRRegNo[i]))
915       UsedRegMask |= 1 << (31-i);
916   
917   // Live in and live out values already must be in the mask, so don't bother
918   // marking them.
919   for (MachineFunction::livein_iterator I = 
920        MF->livein_begin(), E = MF->livein_end(); I != E; ++I) {
921     unsigned RegNo = PPCRegisterInfo::getRegisterNumbering(I->first);
922     if (VRRegNo[RegNo] == I->first)        // If this really is a vector reg.
923       UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
924   }
925   for (MachineFunction::liveout_iterator I = 
926        MF->liveout_begin(), E = MF->liveout_end(); I != E; ++I) {
927     unsigned RegNo = PPCRegisterInfo::getRegisterNumbering(*I);
928     if (VRRegNo[RegNo] == *I)              // If this really is a vector reg.
929       UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
930   }
931   
932   unsigned SrcReg = MI->getOperand(1).getReg();
933   unsigned DstReg = MI->getOperand(0).getReg();
934   // If no registers are used, turn this into a copy.
935   if (UsedRegMask == 0) {
936     // Remove all VRSAVE code.
937     RemoveVRSaveCode(MI);
938     return;
939   } else if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
940     BuildMI(*MI->getParent(), MI, TII.get(PPC::ORI), DstReg)
941         .addReg(SrcReg).addImm(UsedRegMask);
942   } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
943     BuildMI(*MI->getParent(), MI, TII.get(PPC::ORIS), DstReg)
944         .addReg(SrcReg).addImm(UsedRegMask >> 16);
945   } else {
946     BuildMI(*MI->getParent(), MI, TII.get(PPC::ORIS), DstReg)
947        .addReg(SrcReg).addImm(UsedRegMask >> 16);
948     BuildMI(*MI->getParent(), MI, TII.get(PPC::ORI), DstReg)
949       .addReg(DstReg).addImm(UsedRegMask & 0xFFFF);
950   }
951   
952   // Remove the old UPDATE_VRSAVE instruction.
953   MI->eraseFromParent();
954 }
955
956 /// determineFrameLayout - Determine the size of the frame and maximum call
957 /// frame size.
958 void PPCRegisterInfo::determineFrameLayout(MachineFunction &MF) const {
959   MachineFrameInfo *MFI = MF.getFrameInfo();
960
961   // Get the number of bytes to allocate from the FrameInfo
962   unsigned FrameSize = MFI->getStackSize();
963   
964   // Get the alignments provided by the target, and the maximum alignment
965   // (if any) of the fixed frame objects.
966   unsigned MaxAlign = MFI->getMaxAlignment();
967   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
968   unsigned AlignMask = TargetAlign - 1;  //
969
970   // If we are a leaf function, and use up to 224 bytes of stack space,
971   // don't have a frame pointer, calls, or dynamic alloca then we do not need
972   // to adjust the stack pointer (we fit in the Red Zone).
973   if (FrameSize <= 224 &&             // Fits in red zone.
974       !MFI->hasVarSizedObjects() &&   // No dynamic alloca.
975       !MFI->hasCalls() &&             // No calls.
976       MaxAlign <= TargetAlign) {      // No special alignment.
977     // No need for frame
978     MFI->setStackSize(0);
979     return;
980   }
981   
982   // Get the maximum call frame size of all the calls.
983   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
984   
985   // Maximum call frame needs to be at least big enough for linkage and 8 args.
986   unsigned minCallFrameSize =
987     PPCFrameInfo::getMinCallFrameSize(Subtarget.isPPC64(), 
988                                       Subtarget.isMachoABI());
989   maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
990
991   // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
992   // that allocations will be aligned.
993   if (MFI->hasVarSizedObjects())
994     maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
995   
996   // Update maximum call frame size.
997   MFI->setMaxCallFrameSize(maxCallFrameSize);
998   
999   // Include call frame size in total.
1000   FrameSize += maxCallFrameSize;
1001   
1002   // Make sure the frame is aligned.
1003   FrameSize = (FrameSize + AlignMask) & ~AlignMask;
1004
1005   // Update frame info.
1006   MFI->setStackSize(FrameSize);
1007 }
1008
1009 void PPCRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1010                                                            RegScavenger *RS)
1011   const {
1012   //  Save and clear the LR state.
1013   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1014   unsigned LR = getRARegister();
1015   FI->setUsesLR(MF.isPhysRegUsed(LR));
1016   MF.setPhysRegUnused(LR);
1017
1018   //  Save R31 if necessary
1019   int FPSI = FI->getFramePointerSaveIndex();
1020   bool IsPPC64 = Subtarget.isPPC64();
1021   bool IsELF32_ABI = Subtarget.isELF32_ABI();
1022   bool IsMachoABI  = Subtarget.isMachoABI();
1023   const MachineFrameInfo *MFI = MF.getFrameInfo();
1024  
1025   // If the frame pointer save index hasn't been defined yet.
1026   if (!FPSI &&  (NoFramePointerElim || MFI->hasVarSizedObjects()) 
1027                                                   && IsELF32_ABI) {
1028     // Find out what the fix offset of the frame pointer save area.
1029     int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64,
1030                                                            IsMachoABI);
1031     // Allocate the frame index for frame pointer save area.
1032     FPSI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, FPOffset);
1033     // Save the result.
1034     FI->setFramePointerSaveIndex(FPSI);                      
1035   }
1036
1037 }
1038
1039 void PPCRegisterInfo::emitPrologue(MachineFunction &MF) const {
1040   MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
1041   MachineBasicBlock::iterator MBBI = MBB.begin();
1042   MachineFrameInfo *MFI = MF.getFrameInfo();
1043   MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
1044   
1045   // Prepare for frame info.
1046   unsigned FrameLabelId = 0;
1047   
1048   // Scan the prolog, looking for an UPDATE_VRSAVE instruction.  If we find it,
1049   // process it.
1050   for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
1051     if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
1052       HandleVRSaveUpdate(MBBI, TII);
1053       break;
1054     }
1055   }
1056   
1057   // Move MBBI back to the beginning of the function.
1058   MBBI = MBB.begin();
1059   
1060   // Work out frame sizes.
1061   determineFrameLayout(MF);
1062   unsigned FrameSize = MFI->getStackSize();
1063   
1064   int NegFrameSize = -FrameSize;
1065   
1066   // Get processor type.
1067   bool IsPPC64 = Subtarget.isPPC64();
1068   // Get operating system
1069   bool IsMachoABI = Subtarget.isMachoABI();
1070   // Check if the link register (LR) has been used.
1071   bool UsesLR = MustSaveLR(MF);
1072   // Do we have a frame pointer for this function?
1073   bool HasFP = hasFP(MF) && FrameSize;
1074   
1075   int LROffset = PPCFrameInfo::getReturnSaveOffset(IsPPC64, IsMachoABI);
1076   int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, IsMachoABI);
1077   
1078   if (IsPPC64) {
1079     if (UsesLR)
1080       BuildMI(MBB, MBBI, TII.get(PPC::MFLR8), PPC::X0);
1081       
1082     if (HasFP)
1083       BuildMI(MBB, MBBI, TII.get(PPC::STD))
1084          .addReg(PPC::X31).addImm(FPOffset/4).addReg(PPC::X1);
1085     
1086     if (UsesLR)
1087       BuildMI(MBB, MBBI, TII.get(PPC::STD))
1088          .addReg(PPC::X0).addImm(LROffset/4).addReg(PPC::X1);
1089   } else {
1090     if (UsesLR)
1091       BuildMI(MBB, MBBI, TII.get(PPC::MFLR), PPC::R0);
1092       
1093     if (HasFP)
1094       BuildMI(MBB, MBBI, TII.get(PPC::STW))
1095         .addReg(PPC::R31).addImm(FPOffset).addReg(PPC::R1);
1096
1097     if (UsesLR)
1098       BuildMI(MBB, MBBI, TII.get(PPC::STW))
1099         .addReg(PPC::R0).addImm(LROffset).addReg(PPC::R1);
1100   }
1101   
1102   // Skip if a leaf routine.
1103   if (!FrameSize) return;
1104   
1105   // Get stack alignments.
1106   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1107   unsigned MaxAlign = MFI->getMaxAlignment();
1108
1109   if (MMI && MMI->needsFrameInfo()) {
1110     // Mark effective beginning of when frame pointer becomes valid.
1111     FrameLabelId = MMI->NextLabelID();
1112     BuildMI(MBB, MBBI, TII.get(PPC::LABEL)).addImm(FrameLabelId);
1113   }
1114   
1115   // Adjust stack pointer: r1 += NegFrameSize.
1116   // If there is a preferred stack alignment, align R1 now
1117   if (!IsPPC64) {
1118     // PPC32.
1119     if (MaxAlign > TargetAlign) {
1120       assert(isPowerOf2_32(MaxAlign)&&isInt16(MaxAlign)&&"Invalid alignment!");
1121       assert(isInt16(NegFrameSize) && "Unhandled stack size and alignment!");
1122       BuildMI(MBB, MBBI, TII.get(PPC::RLWINM), PPC::R0)
1123         .addReg(PPC::R1).addImm(0).addImm(32-Log2_32(MaxAlign)).addImm(31);
1124       BuildMI(MBB, MBBI, TII.get(PPC::SUBFIC) ,PPC::R0).addReg(PPC::R0)
1125         .addImm(NegFrameSize);
1126       BuildMI(MBB, MBBI, TII.get(PPC::STWUX))
1127         .addReg(PPC::R1).addReg(PPC::R1).addReg(PPC::R0);
1128     } else if (isInt16(NegFrameSize)) {
1129       BuildMI(MBB, MBBI, TII.get(PPC::STWU),
1130               PPC::R1).addReg(PPC::R1).addImm(NegFrameSize).addReg(PPC::R1);
1131     } else {
1132       BuildMI(MBB, MBBI, TII.get(PPC::LIS), PPC::R0).addImm(NegFrameSize >> 16);
1133       BuildMI(MBB, MBBI, TII.get(PPC::ORI), PPC::R0).addReg(PPC::R0)
1134         .addImm(NegFrameSize & 0xFFFF);
1135       BuildMI(MBB, MBBI, TII.get(PPC::STWUX)).addReg(PPC::R1).addReg(PPC::R1)
1136         .addReg(PPC::R0);
1137     }
1138   } else {    // PPC64.
1139     if (MaxAlign > TargetAlign) {
1140       assert(isPowerOf2_32(MaxAlign)&&isInt16(MaxAlign)&&"Invalid alignment!");
1141       assert(isInt16(NegFrameSize) && "Unhandled stack size and alignment!");
1142       BuildMI(MBB, MBBI, TII.get(PPC::RLDICL), PPC::X0)
1143         .addReg(PPC::X1).addImm(0).addImm(64-Log2_32(MaxAlign));
1144       BuildMI(MBB, MBBI, TII.get(PPC::SUBFIC8), PPC::X0).addReg(PPC::X0)
1145         .addImm(NegFrameSize);
1146       BuildMI(MBB, MBBI, TII.get(PPC::STDUX))
1147         .addReg(PPC::X1).addReg(PPC::X1).addReg(PPC::X0);
1148     } else if (isInt16(NegFrameSize)) {
1149       BuildMI(MBB, MBBI, TII.get(PPC::STDU), PPC::X1)
1150              .addReg(PPC::X1).addImm(NegFrameSize/4).addReg(PPC::X1);
1151     } else {
1152       BuildMI(MBB, MBBI, TII.get(PPC::LIS8), PPC::X0).addImm(NegFrameSize >>16);
1153       BuildMI(MBB, MBBI, TII.get(PPC::ORI8), PPC::X0).addReg(PPC::X0)
1154         .addImm(NegFrameSize & 0xFFFF);
1155       BuildMI(MBB, MBBI, TII.get(PPC::STDUX)).addReg(PPC::X1).addReg(PPC::X1)
1156         .addReg(PPC::X0);
1157     }
1158   }
1159   
1160   if (MMI && MMI->needsFrameInfo()) {
1161     std::vector<MachineMove> &Moves = MMI->getFrameMoves();
1162     
1163     if (NegFrameSize) {
1164       // Show update of SP.
1165       MachineLocation SPDst(MachineLocation::VirtualFP);
1166       MachineLocation SPSrc(MachineLocation::VirtualFP, NegFrameSize);
1167       Moves.push_back(MachineMove(FrameLabelId, SPDst, SPSrc));
1168     } else {
1169       MachineLocation SP(IsPPC64 ? PPC::X31 : PPC::R31);
1170       Moves.push_back(MachineMove(FrameLabelId, SP, SP));
1171     }
1172     
1173     if (HasFP) {
1174       MachineLocation FPDst(MachineLocation::VirtualFP, FPOffset);
1175       MachineLocation FPSrc(IsPPC64 ? PPC::X31 : PPC::R31);
1176       Moves.push_back(MachineMove(FrameLabelId, FPDst, FPSrc));
1177     }
1178
1179     // Add callee saved registers to move list.
1180     const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1181     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
1182       int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
1183       unsigned Reg = CSI[I].getReg();
1184       if (Reg == PPC::LR || Reg == PPC::LR8) continue;
1185       MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
1186       MachineLocation CSSrc(Reg);
1187       Moves.push_back(MachineMove(FrameLabelId, CSDst, CSSrc));
1188     }
1189     
1190     MachineLocation LRDst(MachineLocation::VirtualFP, LROffset);
1191     MachineLocation LRSrc(IsPPC64 ? PPC::LR8 : PPC::LR);
1192     Moves.push_back(MachineMove(FrameLabelId, LRDst, LRSrc));
1193     
1194     // Mark effective beginning of when frame pointer is ready.
1195     unsigned ReadyLabelId = MMI->NextLabelID();
1196     BuildMI(MBB, MBBI, TII.get(PPC::LABEL)).addImm(ReadyLabelId);
1197     
1198     MachineLocation FPDst(HasFP ? (IsPPC64 ? PPC::X31 : PPC::R31) :
1199                                   (IsPPC64 ? PPC::X1 : PPC::R1));
1200     MachineLocation FPSrc(MachineLocation::VirtualFP);
1201     Moves.push_back(MachineMove(ReadyLabelId, FPDst, FPSrc));
1202   }
1203
1204   // If there is a frame pointer, copy R1 into R31
1205   if (HasFP) {
1206     if (!IsPPC64) {
1207       BuildMI(MBB, MBBI, TII.get(PPC::OR), PPC::R31).addReg(PPC::R1)
1208         .addReg(PPC::R1);
1209     } else {
1210       BuildMI(MBB, MBBI, TII.get(PPC::OR8), PPC::X31).addReg(PPC::X1)
1211         .addReg(PPC::X1);
1212     }
1213   }
1214 }
1215
1216 void PPCRegisterInfo::emitEpilogue(MachineFunction &MF,
1217                                    MachineBasicBlock &MBB) const {
1218   MachineBasicBlock::iterator MBBI = prior(MBB.end());
1219   assert(MBBI->getOpcode() == PPC::BLR &&
1220          "Can only insert epilog into returning blocks");
1221
1222   // Get alignment info so we know how to restore r1
1223   const MachineFrameInfo *MFI = MF.getFrameInfo();
1224   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1225   unsigned MaxAlign = MFI->getMaxAlignment();
1226
1227   // Get the number of bytes allocated from the FrameInfo.
1228   unsigned FrameSize = MFI->getStackSize();
1229
1230   // Get processor type.
1231   bool IsPPC64 = Subtarget.isPPC64();
1232   // Get operating system
1233   bool IsMachoABI = Subtarget.isMachoABI();
1234   // Check if the link register (LR) has been used.
1235   bool UsesLR = MustSaveLR(MF);
1236   // Do we have a frame pointer for this function?
1237   bool HasFP = hasFP(MF) && FrameSize;
1238   
1239   int LROffset = PPCFrameInfo::getReturnSaveOffset(IsPPC64, IsMachoABI);
1240   int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, IsMachoABI);
1241   
1242   if (FrameSize) {
1243     // The loaded (or persistent) stack pointer value is offset by the 'stwu'
1244     // on entry to the function.  Add this offset back now.
1245     if (!Subtarget.isPPC64()) {
1246       if (isInt16(FrameSize) && TargetAlign >= MaxAlign &&
1247             !MFI->hasVarSizedObjects()) {
1248           BuildMI(MBB, MBBI, TII.get(PPC::ADDI), PPC::R1)
1249               .addReg(PPC::R1).addImm(FrameSize);
1250       } else {
1251         BuildMI(MBB, MBBI, TII.get(PPC::LWZ),PPC::R1).addImm(0).addReg(PPC::R1);
1252       }
1253     } else {
1254       if (isInt16(FrameSize) && TargetAlign >= MaxAlign &&
1255             !MFI->hasVarSizedObjects()) {
1256         BuildMI(MBB, MBBI, TII.get(PPC::ADDI8), PPC::X1)
1257            .addReg(PPC::X1).addImm(FrameSize);
1258       } else {
1259         BuildMI(MBB, MBBI, TII.get(PPC::LD), PPC::X1).addImm(0).addReg(PPC::X1);
1260       }
1261     }
1262   }
1263
1264   if (IsPPC64) {
1265     if (UsesLR)
1266       BuildMI(MBB, MBBI, TII.get(PPC::LD), PPC::X0)
1267         .addImm(LROffset/4).addReg(PPC::X1);
1268         
1269     if (HasFP)
1270       BuildMI(MBB, MBBI, TII.get(PPC::LD), PPC::X31)
1271         .addImm(FPOffset/4).addReg(PPC::X1);
1272         
1273     if (UsesLR)
1274       BuildMI(MBB, MBBI, TII.get(PPC::MTLR8)).addReg(PPC::X0);
1275   } else {
1276     if (UsesLR)
1277       BuildMI(MBB, MBBI, TII.get(PPC::LWZ), PPC::R0)
1278           .addImm(LROffset).addReg(PPC::R1);
1279         
1280     if (HasFP)
1281       BuildMI(MBB, MBBI, TII.get(PPC::LWZ), PPC::R31)
1282           .addImm(FPOffset).addReg(PPC::R1);
1283           
1284     if (UsesLR)
1285       BuildMI(MBB, MBBI, TII.get(PPC::MTLR)).addReg(PPC::R0);
1286   }
1287 }
1288
1289 unsigned PPCRegisterInfo::getRARegister() const {
1290   return !Subtarget.isPPC64() ? PPC::LR : PPC::LR8;
1291 }
1292
1293 unsigned PPCRegisterInfo::getFrameRegister(MachineFunction &MF) const {
1294   if (!Subtarget.isPPC64())
1295     return hasFP(MF) ? PPC::R31 : PPC::R1;
1296   else
1297     return hasFP(MF) ? PPC::X31 : PPC::X1;
1298 }
1299
1300 void PPCRegisterInfo::getInitialFrameState(std::vector<MachineMove> &Moves)
1301                                                                          const {
1302   // Initial state of the frame pointer is R1.
1303   MachineLocation Dst(MachineLocation::VirtualFP);
1304   MachineLocation Src(PPC::R1, 0);
1305   Moves.push_back(MachineMove(0, Dst, Src));
1306 }
1307
1308 unsigned PPCRegisterInfo::getEHExceptionRegister() const {
1309   return !Subtarget.isPPC64() ? PPC::R3 : PPC::X3;
1310 }
1311
1312 unsigned PPCRegisterInfo::getEHHandlerRegister() const {
1313   return !Subtarget.isPPC64() ? PPC::R4 : PPC::X4;
1314 }
1315
1316 int PPCRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
1317   // FIXME: Most probably dwarf numbers differs for Linux and Darwin
1318   return PPCGenRegisterInfo::getDwarfRegNumFull(RegNum, 0);
1319 }
1320
1321 #include "PPCGenRegisterInfo.inc"
1322