bdf1d2dfb077331ff3e79b7c10ab4cf6659a1d1f
[oota-llvm.git] / lib / Target / PowerPC / PPCRegisterInfo.cpp
1 //===-- PPCRegisterInfo.cpp - PowerPC Register Information ----------------===//
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 TargetRegisterInfo
11 // class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "reginfo"
16 #include "PPCRegisterInfo.h"
17 #include "PPC.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrBuilder.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCSubtarget.h"
22 #include "llvm/ADT/BitVector.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/RegisterScavenging.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetFrameLowering.h"
40 #include "llvm/Target/TargetInstrInfo.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include <cstdlib>
44
45 #define GET_REGINFO_TARGET_DESC
46 #include "PPCGenRegisterInfo.inc"
47
48 using namespace llvm;
49
50 static cl::opt<bool>
51 EnableBasePointer("ppc-use-base-pointer", cl::Hidden, cl::init(true),
52          cl::desc("Enable use of a base pointer for complex stack frames"));
53
54 static cl::opt<bool>
55 AlwaysBasePointer("ppc-always-use-base-pointer", cl::Hidden, cl::init(false),
56          cl::desc("Force the use of a base pointer in every function"));
57
58 PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST)
59   : PPCGenRegisterInfo(ST.isPPC64() ? PPC::LR8 : PPC::LR,
60                        ST.isPPC64() ? 0 : 1,
61                        ST.isPPC64() ? 0 : 1),
62     Subtarget(ST) {
63   ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
64   ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
65   ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
66   ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
67   ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
68   ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
69   ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
70   ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
71   ImmToIdxMap[PPC::LWA_32] = PPC::LWAX_32;
72
73   // 64-bit
74   ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
75   ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
76   ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
77   ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
78   ImmToIdxMap[PPC::ADDI8] = PPC::ADD8;
79 }
80
81 /// getPointerRegClass - Return the register class to use to hold pointers.
82 /// This is used for addressing modes.
83 const TargetRegisterClass *
84 PPCRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
85                                                                        const {
86   // Note that PPCInstrInfo::FoldImmediate also directly uses this Kind value
87   // when it checks for ZERO folding.
88   if (Kind == 1) {
89     if (Subtarget.isPPC64())
90       return &PPC::G8RC_NOX0RegClass;
91     return &PPC::GPRC_NOR0RegClass;
92   }
93
94   if (Subtarget.isPPC64())
95     return &PPC::G8RCRegClass;
96   return &PPC::GPRCRegClass;
97 }
98
99 const MCPhysReg*
100 PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
101   if (Subtarget.isDarwinABI())
102     return Subtarget.isPPC64() ? (Subtarget.hasAltivec() ?
103                                   CSR_Darwin64_Altivec_SaveList :
104                                   CSR_Darwin64_SaveList) :
105                                  (Subtarget.hasAltivec() ?
106                                   CSR_Darwin32_Altivec_SaveList :
107                                   CSR_Darwin32_SaveList);
108
109   return Subtarget.isPPC64() ? (Subtarget.hasAltivec() ?
110                                 CSR_SVR464_Altivec_SaveList :
111                                 CSR_SVR464_SaveList) :
112                                (Subtarget.hasAltivec() ?
113                                 CSR_SVR432_Altivec_SaveList :
114                                 CSR_SVR432_SaveList);
115 }
116
117 const uint32_t*
118 PPCRegisterInfo::getCallPreservedMask(CallingConv::ID CC) const {
119   if (Subtarget.isDarwinABI())
120     return Subtarget.isPPC64() ? (Subtarget.hasAltivec() ?
121                                   CSR_Darwin64_Altivec_RegMask :
122                                   CSR_Darwin64_RegMask) :
123                                  (Subtarget.hasAltivec() ?
124                                   CSR_Darwin32_Altivec_RegMask :
125                                   CSR_Darwin32_RegMask);
126
127   return Subtarget.isPPC64() ? (Subtarget.hasAltivec() ?
128                                 CSR_SVR464_Altivec_RegMask :
129                                 CSR_SVR464_RegMask) :
130                                (Subtarget.hasAltivec() ?
131                                 CSR_SVR432_Altivec_RegMask :
132                                 CSR_SVR432_RegMask);
133 }
134
135 const uint32_t*
136 PPCRegisterInfo::getNoPreservedMask() const {
137   return CSR_NoRegs_RegMask;
138 }
139
140 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
141   BitVector Reserved(getNumRegs());
142   const PPCFrameLowering *PPCFI =
143     static_cast<const PPCFrameLowering*>(MF.getTarget().getFrameLowering());
144
145   // The ZERO register is not really a register, but the representation of r0
146   // when used in instructions that treat r0 as the constant 0.
147   Reserved.set(PPC::ZERO);
148   Reserved.set(PPC::ZERO8);
149
150   // The FP register is also not really a register, but is the representation
151   // of the frame pointer register used by ISD::FRAMEADDR.
152   Reserved.set(PPC::FP);
153   Reserved.set(PPC::FP8);
154
155   // The BP register is also not really a register, but is the representation
156   // of the base pointer register used by setjmp.
157   Reserved.set(PPC::BP);
158   Reserved.set(PPC::BP8);
159
160   // The counter registers must be reserved so that counter-based loops can
161   // be correctly formed (and the mtctr instructions are not DCE'd).
162   Reserved.set(PPC::CTR);
163   Reserved.set(PPC::CTR8);
164
165   Reserved.set(PPC::R1);
166   Reserved.set(PPC::LR);
167   Reserved.set(PPC::LR8);
168   Reserved.set(PPC::RM);
169
170   if (!Subtarget.isDarwinABI() || !Subtarget.hasAltivec())
171     Reserved.set(PPC::VRSAVE);
172
173   // The SVR4 ABI reserves r2 and r13
174   if (Subtarget.isSVR4ABI()) {
175     Reserved.set(PPC::R2);  // System-reserved register
176     Reserved.set(PPC::R13); // Small Data Area pointer register
177   }
178   
179   // On PPC64, r13 is the thread pointer. Never allocate this register.
180   if (Subtarget.isPPC64()) {
181     Reserved.set(PPC::R13);
182
183     Reserved.set(PPC::X1);
184     Reserved.set(PPC::X13);
185
186     if (PPCFI->needsFP(MF))
187       Reserved.set(PPC::X31);
188
189     if (hasBasePointer(MF))
190       Reserved.set(PPC::X30);
191
192     // The 64-bit SVR4 ABI reserves r2 for the TOC pointer.
193     if (Subtarget.isSVR4ABI()) {
194       Reserved.set(PPC::X2);
195     }
196   }
197
198   if (PPCFI->needsFP(MF))
199     Reserved.set(PPC::R31);
200
201   if (hasBasePointer(MF))
202     Reserved.set(PPC::R30);
203
204   // Reserve Altivec registers when Altivec is unavailable.
205   if (!Subtarget.hasAltivec())
206     for (TargetRegisterClass::iterator I = PPC::VRRCRegClass.begin(),
207          IE = PPC::VRRCRegClass.end(); I != IE; ++I)
208       Reserved.set(*I);
209
210   return Reserved;
211 }
212
213 unsigned
214 PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
215                                          MachineFunction &MF) const {
216   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
217   const unsigned DefaultSafety = 1;
218
219   switch (RC->getID()) {
220   default:
221     return 0;
222   case PPC::G8RC_NOX0RegClassID:
223   case PPC::GPRC_NOR0RegClassID: 
224   case PPC::G8RCRegClassID:
225   case PPC::GPRCRegClassID: {
226     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
227     return 32 - FP - DefaultSafety;
228   }
229   case PPC::F8RCRegClassID:
230   case PPC::F4RCRegClassID:
231   case PPC::VRRCRegClassID:
232   case PPC::VFRCRegClassID:
233   case PPC::VSLRCRegClassID:
234   case PPC::VSHRCRegClassID:
235     return 32 - DefaultSafety;
236   case PPC::VSRCRegClassID:
237   case PPC::VSFRCRegClassID:
238     return 64 - DefaultSafety;
239   case PPC::CRRCRegClassID:
240     return 8 - DefaultSafety;
241   }
242 }
243
244 const TargetRegisterClass*
245 PPCRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC)const {
246   if (Subtarget.hasVSX()) {
247     // With VSX, we can inflate various sub-register classes to the full VSX
248     // register set.
249
250     if (RC == &PPC::F8RCRegClass)
251       return &PPC::VSFRCRegClass;
252     else if (RC == &PPC::VRRCRegClass)
253       return &PPC::VSRCRegClass;
254   }
255
256   return TargetRegisterInfo::getLargestLegalSuperClass(RC);
257 }
258
259 //===----------------------------------------------------------------------===//
260 // Stack Frame Processing methods
261 //===----------------------------------------------------------------------===//
262
263 /// lowerDynamicAlloc - Generate the code for allocating an object in the
264 /// current frame.  The sequence of code with be in the general form
265 ///
266 ///   addi   R0, SP, \#frameSize ; get the address of the previous frame
267 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
268 ///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
269 ///
270 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
271   // Get the instruction.
272   MachineInstr &MI = *II;
273   // Get the instruction's basic block.
274   MachineBasicBlock &MBB = *MI.getParent();
275   // Get the basic block's function.
276   MachineFunction &MF = *MBB.getParent();
277   // Get the frame info.
278   MachineFrameInfo *MFI = MF.getFrameInfo();
279   // Get the instruction info.
280   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
281   // Determine whether 64-bit pointers are used.
282   bool LP64 = Subtarget.isPPC64();
283   DebugLoc dl = MI.getDebugLoc();
284
285   // Get the maximum call stack size.
286   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
287   // Get the total frame size.
288   unsigned FrameSize = MFI->getStackSize();
289   
290   // Get stack alignments.
291   unsigned TargetAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
292   unsigned MaxAlign = MFI->getMaxAlignment();
293   assert((maxCallFrameSize & (MaxAlign-1)) == 0 &&
294          "Maximum call-frame size not sufficiently aligned");
295
296   // Determine the previous frame's address.  If FrameSize can't be
297   // represented as 16 bits or we need special alignment, then we load the
298   // previous frame's address from 0(SP).  Why not do an addis of the hi? 
299   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero. 
300   // Constructing the constant and adding would take 3 instructions. 
301   // Fortunately, a frame greater than 32K is rare.
302   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
303   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
304   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
305   
306   if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
307     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), Reg)
308       .addReg(PPC::R31)
309       .addImm(FrameSize);
310   } else if (LP64) {
311     BuildMI(MBB, II, dl, TII.get(PPC::LD), Reg)
312       .addImm(0)
313       .addReg(PPC::X1);
314   } else {
315     BuildMI(MBB, II, dl, TII.get(PPC::LWZ), Reg)
316       .addImm(0)
317       .addReg(PPC::R1);
318   }
319
320   bool KillNegSizeReg = MI.getOperand(1).isKill();
321   unsigned NegSizeReg = MI.getOperand(1).getReg();
322
323   // Grow the stack and update the stack pointer link, then determine the
324   // address of new allocated space.
325   if (LP64) {
326     if (MaxAlign > TargetAlign) {
327       unsigned UnalNegSizeReg = NegSizeReg;
328       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
329
330       // Unfortunately, there is no andi, only andi., and we can't insert that
331       // here because we might clobber cr0 while it is live.
332       BuildMI(MBB, II, dl, TII.get(PPC::LI8), NegSizeReg)
333         .addImm(~(MaxAlign-1));
334
335       unsigned NegSizeReg1 = NegSizeReg;
336       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
337       BuildMI(MBB, II, dl, TII.get(PPC::AND8), NegSizeReg)
338         .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
339         .addReg(NegSizeReg1, RegState::Kill);
340       KillNegSizeReg = true;
341     }
342
343     BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
344       .addReg(Reg, RegState::Kill)
345       .addReg(PPC::X1)
346       .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
347     BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
348       .addReg(PPC::X1)
349       .addImm(maxCallFrameSize);
350   } else {
351     if (MaxAlign > TargetAlign) {
352       unsigned UnalNegSizeReg = NegSizeReg;
353       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
354
355       // Unfortunately, there is no andi, only andi., and we can't insert that
356       // here because we might clobber cr0 while it is live.
357       BuildMI(MBB, II, dl, TII.get(PPC::LI), NegSizeReg)
358         .addImm(~(MaxAlign-1));
359
360       unsigned NegSizeReg1 = NegSizeReg;
361       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
362       BuildMI(MBB, II, dl, TII.get(PPC::AND), NegSizeReg)
363         .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
364         .addReg(NegSizeReg1, RegState::Kill);
365       KillNegSizeReg = true;
366     }
367
368     BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
369       .addReg(Reg, RegState::Kill)
370       .addReg(PPC::R1)
371       .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
372     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
373       .addReg(PPC::R1)
374       .addImm(maxCallFrameSize);
375   }
376   
377   // Discard the DYNALLOC instruction.
378   MBB.erase(II);
379 }
380
381 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
382 /// reserving a whole register (R0), we scrounge for one here. This generates
383 /// code like this:
384 ///
385 ///   mfcr rA                  ; Move the conditional register into GPR rA.
386 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
387 ///   stw rA, FI               ; Store rA to the frame.
388 ///
389 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
390                                       unsigned FrameIndex) const {
391   // Get the instruction.
392   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>
393   // Get the instruction's basic block.
394   MachineBasicBlock &MBB = *MI.getParent();
395   MachineFunction &MF = *MBB.getParent();
396   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
397   DebugLoc dl = MI.getDebugLoc();
398
399   bool LP64 = Subtarget.isPPC64();
400   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
401   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
402
403   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
404   unsigned SrcReg = MI.getOperand(0).getReg();
405
406   // We need to store the CR in the low 4-bits of the saved value. First, issue
407   // an MFOCRF to save all of the CRBits and, if needed, kill the SrcReg.
408   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
409           .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
410     
411   // If the saved register wasn't CR0, shift the bits left so that they are in
412   // CR0's slot.
413   if (SrcReg != PPC::CR0) {
414     unsigned Reg1 = Reg;
415     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
416
417     // rlwinm rA, rA, ShiftBits, 0, 31.
418     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
419       .addReg(Reg1, RegState::Kill)
420       .addImm(getEncodingValue(SrcReg) * 4)
421       .addImm(0)
422       .addImm(31);
423   }
424
425   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
426                     .addReg(Reg, RegState::Kill),
427                     FrameIndex);
428
429   // Discard the pseudo instruction.
430   MBB.erase(II);
431 }
432
433 void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
434                                       unsigned FrameIndex) const {
435   // Get the instruction.
436   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CR <offset>
437   // Get the instruction's basic block.
438   MachineBasicBlock &MBB = *MI.getParent();
439   MachineFunction &MF = *MBB.getParent();
440   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
441   DebugLoc dl = MI.getDebugLoc();
442
443   bool LP64 = Subtarget.isPPC64();
444   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
445   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
446
447   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
448   unsigned DestReg = MI.getOperand(0).getReg();
449   assert(MI.definesRegister(DestReg) &&
450     "RESTORE_CR does not define its destination");
451
452   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
453                               Reg), FrameIndex);
454
455   // If the reloaded register isn't CR0, shift the bits right so that they are
456   // in the right CR's slot.
457   if (DestReg != PPC::CR0) {
458     unsigned Reg1 = Reg;
459     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
460
461     unsigned ShiftBits = getEncodingValue(DestReg)*4;
462     // rlwinm r11, r11, 32-ShiftBits, 0, 31.
463     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
464              .addReg(Reg1, RegState::Kill).addImm(32-ShiftBits).addImm(0)
465              .addImm(31);
466   }
467
468   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF), DestReg)
469              .addReg(Reg, RegState::Kill);
470
471   // Discard the pseudo instruction.
472   MBB.erase(II);
473 }
474
475 static unsigned getCRFromCRBit(unsigned SrcReg) {
476   unsigned Reg = 0;
477   if (SrcReg == PPC::CR0LT || SrcReg == PPC::CR0GT ||
478       SrcReg == PPC::CR0EQ || SrcReg == PPC::CR0UN)
479     Reg = PPC::CR0;
480   else if (SrcReg == PPC::CR1LT || SrcReg == PPC::CR1GT ||
481            SrcReg == PPC::CR1EQ || SrcReg == PPC::CR1UN)
482     Reg = PPC::CR1;
483   else if (SrcReg == PPC::CR2LT || SrcReg == PPC::CR2GT ||
484            SrcReg == PPC::CR2EQ || SrcReg == PPC::CR2UN)
485     Reg = PPC::CR2;
486   else if (SrcReg == PPC::CR3LT || SrcReg == PPC::CR3GT ||
487            SrcReg == PPC::CR3EQ || SrcReg == PPC::CR3UN)
488     Reg = PPC::CR3;
489   else if (SrcReg == PPC::CR4LT || SrcReg == PPC::CR4GT ||
490            SrcReg == PPC::CR4EQ || SrcReg == PPC::CR4UN)
491     Reg = PPC::CR4;
492   else if (SrcReg == PPC::CR5LT || SrcReg == PPC::CR5GT ||
493            SrcReg == PPC::CR5EQ || SrcReg == PPC::CR5UN)
494     Reg = PPC::CR5;
495   else if (SrcReg == PPC::CR6LT || SrcReg == PPC::CR6GT ||
496            SrcReg == PPC::CR6EQ || SrcReg == PPC::CR6UN)
497     Reg = PPC::CR6;
498   else if (SrcReg == PPC::CR7LT || SrcReg == PPC::CR7GT ||
499            SrcReg == PPC::CR7EQ || SrcReg == PPC::CR7UN)
500     Reg = PPC::CR7;
501
502   assert(Reg != 0 && "Invalid CR bit register");
503   return Reg;
504 }
505
506 void PPCRegisterInfo::lowerCRBitSpilling(MachineBasicBlock::iterator II,
507                                          unsigned FrameIndex) const {
508   // Get the instruction.
509   MachineInstr &MI = *II;       // ; SPILL_CRBIT <SrcReg>, <offset>
510   // Get the instruction's basic block.
511   MachineBasicBlock &MBB = *MI.getParent();
512   MachineFunction &MF = *MBB.getParent();
513   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
514   DebugLoc dl = MI.getDebugLoc();
515
516   bool LP64 = Subtarget.isPPC64();
517   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
518   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
519
520   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
521   unsigned SrcReg = MI.getOperand(0).getReg();
522
523   BuildMI(MBB, II, dl, TII.get(TargetOpcode::KILL),
524           getCRFromCRBit(SrcReg))
525           .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
526
527   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
528           .addReg(getCRFromCRBit(SrcReg));
529     
530   // If the saved register wasn't CR0LT, shift the bits left so that the bit to
531   // store is the first one. Mask all but that bit.
532   unsigned Reg1 = Reg;
533   Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
534
535   // rlwinm rA, rA, ShiftBits, 0, 0.
536   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
537     .addReg(Reg1, RegState::Kill)
538     .addImm(getEncodingValue(SrcReg))
539     .addImm(0).addImm(0);
540
541   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
542                     .addReg(Reg, RegState::Kill),
543                     FrameIndex);
544
545   // Discard the pseudo instruction.
546   MBB.erase(II);
547 }
548
549 void PPCRegisterInfo::lowerCRBitRestore(MachineBasicBlock::iterator II,
550                                       unsigned FrameIndex) const {
551   // Get the instruction.
552   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CRBIT <offset>
553   // Get the instruction's basic block.
554   MachineBasicBlock &MBB = *MI.getParent();
555   MachineFunction &MF = *MBB.getParent();
556   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
557   DebugLoc dl = MI.getDebugLoc();
558
559   bool LP64 = Subtarget.isPPC64();
560   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
561   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
562
563   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
564   unsigned DestReg = MI.getOperand(0).getReg();
565   assert(MI.definesRegister(DestReg) &&
566     "RESTORE_CRBIT does not define its destination");
567
568   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
569                               Reg), FrameIndex);
570
571   BuildMI(MBB, II, dl, TII.get(TargetOpcode::IMPLICIT_DEF), DestReg);
572
573   unsigned RegO = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
574   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), RegO)
575           .addReg(getCRFromCRBit(DestReg));
576
577   unsigned ShiftBits = getEncodingValue(DestReg);
578   // rlwimi r11, r10, 32-ShiftBits, ..., ...
579   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWIMI8 : PPC::RLWIMI), RegO)
580            .addReg(RegO, RegState::Kill).addReg(Reg, RegState::Kill)
581            .addImm(ShiftBits ? 32-ShiftBits : 0)
582            .addImm(ShiftBits).addImm(ShiftBits);
583            
584   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF),
585           getCRFromCRBit(DestReg))
586             .addReg(RegO, RegState::Kill)
587             // Make sure we have a use dependency all the way through this
588             // sequence of instructions. We can't have the other bits in the CR
589             // modified in between the mfocrf and the mtocrf.
590             .addReg(getCRFromCRBit(DestReg), RegState::Implicit);
591
592   // Discard the pseudo instruction.
593   MBB.erase(II);
594 }
595
596 void PPCRegisterInfo::lowerVRSAVESpilling(MachineBasicBlock::iterator II,
597                                           unsigned FrameIndex) const {
598   // Get the instruction.
599   MachineInstr &MI = *II;       // ; SPILL_VRSAVE <SrcReg>, <offset>
600   // Get the instruction's basic block.
601   MachineBasicBlock &MBB = *MI.getParent();
602   MachineFunction &MF = *MBB.getParent();
603   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
604   DebugLoc dl = MI.getDebugLoc();
605
606   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
607   unsigned Reg = MF.getRegInfo().createVirtualRegister(GPRC);
608   unsigned SrcReg = MI.getOperand(0).getReg();
609
610   BuildMI(MBB, II, dl, TII.get(PPC::MFVRSAVEv), Reg)
611           .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
612     
613   addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::STW))
614                     .addReg(Reg, RegState::Kill),
615                     FrameIndex);
616
617   // Discard the pseudo instruction.
618   MBB.erase(II);
619 }
620
621 void PPCRegisterInfo::lowerVRSAVERestore(MachineBasicBlock::iterator II,
622                                          unsigned FrameIndex) const {
623   // Get the instruction.
624   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_VRSAVE <offset>
625   // Get the instruction's basic block.
626   MachineBasicBlock &MBB = *MI.getParent();
627   MachineFunction &MF = *MBB.getParent();
628   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
629   DebugLoc dl = MI.getDebugLoc();
630
631   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
632   unsigned Reg = MF.getRegInfo().createVirtualRegister(GPRC);
633   unsigned DestReg = MI.getOperand(0).getReg();
634   assert(MI.definesRegister(DestReg) &&
635     "RESTORE_VRSAVE does not define its destination");
636
637   addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::LWZ),
638                               Reg), FrameIndex);
639
640   BuildMI(MBB, II, dl, TII.get(PPC::MTVRSAVEv), DestReg)
641              .addReg(Reg, RegState::Kill);
642
643   // Discard the pseudo instruction.
644   MBB.erase(II);
645 }
646
647 bool
648 PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
649                                       unsigned Reg, int &FrameIdx) const {
650
651   // For the nonvolatile condition registers (CR2, CR3, CR4) in an SVR4
652   // ABI, return true to prevent allocating an additional frame slot.
653   // For 64-bit, the CR save area is at SP+8; the value of FrameIdx = 0
654   // is arbitrary and will be subsequently ignored.  For 32-bit, we have
655   // previously created the stack slot if needed, so return its FrameIdx.
656   if (Subtarget.isSVR4ABI() && PPC::CR2 <= Reg && Reg <= PPC::CR4) {
657     if (Subtarget.isPPC64())
658       FrameIdx = 0;
659     else {
660       const PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
661       FrameIdx = FI->getCRSpillFrameIndex();
662     }
663     return true;
664   }
665   return false;
666 }
667
668 // Figure out if the offset in the instruction must be a multiple of 4.
669 // This is true for instructions like "STD".
670 static bool usesIXAddr(const MachineInstr &MI) {
671   unsigned OpC = MI.getOpcode();
672
673   switch (OpC) {
674   default:
675     return false;
676   case PPC::LWA:
677   case PPC::LWA_32:
678   case PPC::LD:
679   case PPC::STD:
680     return true;
681   }
682 }
683
684 // Return the OffsetOperandNo given the FIOperandNum (and the instruction).
685 static unsigned getOffsetONFromFION(const MachineInstr &MI,
686                                     unsigned FIOperandNum) {
687   // Take into account whether it's an add or mem instruction
688   unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
689   if (MI.isInlineAsm())
690     OffsetOperandNo = FIOperandNum-1;
691
692   return OffsetOperandNo;
693 }
694
695 void
696 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
697                                      int SPAdj, unsigned FIOperandNum,
698                                      RegScavenger *RS) const {
699   assert(SPAdj == 0 && "Unexpected");
700
701   // Get the instruction.
702   MachineInstr &MI = *II;
703   // Get the instruction's basic block.
704   MachineBasicBlock &MBB = *MI.getParent();
705   // Get the basic block's function.
706   MachineFunction &MF = *MBB.getParent();
707   // Get the instruction info.
708   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
709   // Get the frame info.
710   MachineFrameInfo *MFI = MF.getFrameInfo();
711   DebugLoc dl = MI.getDebugLoc();
712
713   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
714
715   // Get the frame index.
716   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
717
718   // Get the frame pointer save index.  Users of this index are primarily
719   // DYNALLOC instructions.
720   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
721   int FPSI = FI->getFramePointerSaveIndex();
722   // Get the instruction opcode.
723   unsigned OpC = MI.getOpcode();
724   
725   // Special case for dynamic alloca.
726   if (FPSI && FrameIndex == FPSI &&
727       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
728     lowerDynamicAlloc(II);
729     return;
730   }
731
732   // Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
733   if (OpC == PPC::SPILL_CR) {
734     lowerCRSpilling(II, FrameIndex);
735     return;
736   } else if (OpC == PPC::RESTORE_CR) {
737     lowerCRRestore(II, FrameIndex);
738     return;
739   } else if (OpC == PPC::SPILL_CRBIT) {
740     lowerCRBitSpilling(II, FrameIndex);
741     return;
742   } else if (OpC == PPC::RESTORE_CRBIT) {
743     lowerCRBitRestore(II, FrameIndex);
744     return;
745   } else if (OpC == PPC::SPILL_VRSAVE) {
746     lowerVRSAVESpilling(II, FrameIndex);
747     return;
748   } else if (OpC == PPC::RESTORE_VRSAVE) {
749     lowerVRSAVERestore(II, FrameIndex);
750     return;
751   }
752
753   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
754   MI.getOperand(FIOperandNum).ChangeToRegister(
755     FrameIndex < 0 ? getBaseRegister(MF) : getFrameRegister(MF), false);
756
757   // Figure out if the offset in the instruction is shifted right two bits.
758   bool isIXAddr = usesIXAddr(MI);
759
760   // If the instruction is not present in ImmToIdxMap, then it has no immediate
761   // form (and must be r+r).
762   bool noImmForm = !MI.isInlineAsm() && !ImmToIdxMap.count(OpC);
763
764   // Now add the frame object offset to the offset from r1.
765   int Offset = MFI->getObjectOffset(FrameIndex);
766   Offset += MI.getOperand(OffsetOperandNo).getImm();
767
768   // If we're not using a Frame Pointer that has been set to the value of the
769   // SP before having the stack size subtracted from it, then add the stack size
770   // to Offset to get the correct offset.
771   // Naked functions have stack size 0, although getStackSize may not reflect that
772   // because we didn't call all the pieces that compute it for naked functions.
773   if (!MF.getFunction()->getAttributes().
774         hasAttribute(AttributeSet::FunctionIndex, Attribute::Naked)) {
775     if (!(hasBasePointer(MF) && FrameIndex < 0))
776       Offset += MFI->getStackSize();
777   }
778
779   // If we can, encode the offset directly into the instruction.  If this is a
780   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
781   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
782   // clear can be encoded.  This is extremely uncommon, because normally you
783   // only "std" to a stack slot that is at least 4-byte aligned, but it can
784   // happen in invalid code.
785   assert(OpC != PPC::DBG_VALUE &&
786          "This should be handle in a target independent way");
787   if (!noImmForm && isInt<16>(Offset) && (!isIXAddr || (Offset & 3) == 0)) {
788     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
789     return;
790   }
791
792   // The offset doesn't fit into a single register, scavenge one to build the
793   // offset in.
794
795   bool is64Bit = Subtarget.isPPC64();
796   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
797   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
798   const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
799   unsigned SRegHi = MF.getRegInfo().createVirtualRegister(RC),
800            SReg = MF.getRegInfo().createVirtualRegister(RC);
801
802   // Insert a set of rA with the full offset value before the ld, st, or add
803   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
804     .addImm(Offset >> 16);
805   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
806     .addReg(SRegHi, RegState::Kill)
807     .addImm(Offset);
808
809   // Convert into indexed form of the instruction:
810   // 
811   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
812   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
813   unsigned OperandBase;
814
815   if (noImmForm)
816     OperandBase = 1;
817   else if (OpC != TargetOpcode::INLINEASM) {
818     assert(ImmToIdxMap.count(OpC) &&
819            "No indexed form of load or store available!");
820     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
821     MI.setDesc(TII.get(NewOpcode));
822     OperandBase = 1;
823   } else {
824     OperandBase = OffsetOperandNo;
825   }
826
827   unsigned StackReg = MI.getOperand(FIOperandNum).getReg();
828   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
829   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
830 }
831
832 unsigned PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
833   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
834
835   if (!Subtarget.isPPC64())
836     return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
837   else
838     return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
839 }
840
841 unsigned PPCRegisterInfo::getBaseRegister(const MachineFunction &MF) const {
842   if (!hasBasePointer(MF))
843     return getFrameRegister(MF);
844
845   return Subtarget.isPPC64() ? PPC::X30 : PPC::R30;
846 }
847
848 bool PPCRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
849   if (!EnableBasePointer)
850     return false;
851   if (AlwaysBasePointer)
852     return true;
853
854   // If we need to realign the stack, then the stack pointer can no longer
855   // serve as an offset into the caller's stack space. As a result, we need a
856   // base pointer.
857   return needsStackRealignment(MF);
858 }
859
860 bool PPCRegisterInfo::canRealignStack(const MachineFunction &MF) const {
861   if (MF.getFunction()->hasFnAttribute("no-realign-stack"))
862     return false;
863
864   return true;
865 }
866
867 bool PPCRegisterInfo::needsStackRealignment(const MachineFunction &MF) const {
868   const MachineFrameInfo *MFI = MF.getFrameInfo();
869   const Function *F = MF.getFunction();
870   unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
871   bool requiresRealignment =
872     ((MFI->getMaxAlignment() > StackAlign) ||
873      F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
874                                      Attribute::StackAlignment));
875
876   return requiresRealignment && canRealignStack(MF);
877 }
878
879 /// Returns true if the instruction's frame index
880 /// reference would be better served by a base register other than FP
881 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
882 /// references it should create new base registers for.
883 bool PPCRegisterInfo::
884 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
885   assert(Offset < 0 && "Local offset must be negative");
886
887   unsigned FIOperandNum = 0;
888   while (!MI->getOperand(FIOperandNum).isFI()) {
889     ++FIOperandNum;
890     assert(FIOperandNum < MI->getNumOperands() &&
891            "Instr doesn't have FrameIndex operand!");
892   }
893
894   unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
895   Offset += MI->getOperand(OffsetOperandNo).getImm();
896
897   // It's the load/store FI references that cause issues, as it can be difficult
898   // to materialize the offset if it won't fit in the literal field. Estimate
899   // based on the size of the local frame and some conservative assumptions
900   // about the rest of the stack frame (note, this is pre-regalloc, so
901   // we don't know everything for certain yet) whether this offset is likely
902   // to be out of range of the immediate. Return true if so.
903
904   // We only generate virtual base registers for loads and stores that have
905   // an r+i form. Return false for everything else.
906   unsigned OpC = MI->getOpcode();
907   if (!ImmToIdxMap.count(OpC))
908     return false;
909
910   // Don't generate a new virtual base register just to add zero to it.
911   if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
912       MI->getOperand(2).getImm() == 0)
913     return false;
914
915   MachineBasicBlock &MBB = *MI->getParent();
916   MachineFunction &MF = *MBB.getParent();
917
918   const PPCFrameLowering *PPCFI =
919     static_cast<const PPCFrameLowering*>(MF.getTarget().getFrameLowering());
920   unsigned StackEst =
921     PPCFI->determineFrameLayout(MF, false, true);
922
923   // If we likely don't need a stack frame, then we probably don't need a
924   // virtual base register either.
925   if (!StackEst)
926     return false;
927
928   // Estimate an offset from the stack pointer.
929   // The incoming offset is relating to the SP at the start of the function,
930   // but when we access the local it'll be relative to the SP after local
931   // allocation, so adjust our SP-relative offset by that allocation size.
932   Offset += StackEst;
933
934   // The frame pointer will point to the end of the stack, so estimate the
935   // offset as the difference between the object offset and the FP location.
936   return !isFrameOffsetLegal(MI, Offset);
937 }
938
939 /// Insert defining instruction(s) for BaseReg to
940 /// be a pointer to FrameIdx at the beginning of the basic block.
941 void PPCRegisterInfo::
942 materializeFrameBaseRegister(MachineBasicBlock *MBB,
943                              unsigned BaseReg, int FrameIdx,
944                              int64_t Offset) const {
945   unsigned ADDriOpc = Subtarget.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
946
947   MachineBasicBlock::iterator Ins = MBB->begin();
948   DebugLoc DL;                  // Defaults to "unknown"
949   if (Ins != MBB->end())
950     DL = Ins->getDebugLoc();
951
952   const MachineFunction &MF = *MBB->getParent();
953   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
954   const MCInstrDesc &MCID = TII.get(ADDriOpc);
955   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
956   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
957
958   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
959     .addFrameIndex(FrameIdx).addImm(Offset);
960 }
961
962 void PPCRegisterInfo::resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
963                                         int64_t Offset) const {
964   unsigned FIOperandNum = 0;
965   while (!MI.getOperand(FIOperandNum).isFI()) {
966     ++FIOperandNum;
967     assert(FIOperandNum < MI.getNumOperands() &&
968            "Instr doesn't have FrameIndex operand!");
969   }
970
971   MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
972   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
973   Offset += MI.getOperand(OffsetOperandNo).getImm();
974   MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
975 }
976
977 bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
978                                          int64_t Offset) const {
979   return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
980          (isInt<16>(Offset) && (!usesIXAddr(*MI) || (Offset & 3) == 0));
981 }
982