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