PPC: Implement base pointer and stack realignment
[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/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetFrameLowering.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetOptions.h"
44 #include <cstdlib>
45
46 #define GET_REGINFO_TARGET_DESC
47 #include "PPCGenRegisterInfo.inc"
48
49 using namespace llvm;
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
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 uint16_t*
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 counter registers must be reserved so that counter-based loops can
156   // be correctly formed (and the mtctr instructions are not DCE'd).
157   Reserved.set(PPC::CTR);
158   Reserved.set(PPC::CTR8);
159
160   Reserved.set(PPC::R1);
161   Reserved.set(PPC::LR);
162   Reserved.set(PPC::LR8);
163   Reserved.set(PPC::RM);
164
165   if (!Subtarget.isDarwinABI() || !Subtarget.hasAltivec())
166     Reserved.set(PPC::VRSAVE);
167
168   // The SVR4 ABI reserves r2 and r13
169   if (Subtarget.isSVR4ABI()) {
170     Reserved.set(PPC::R2);  // System-reserved register
171     Reserved.set(PPC::R13); // Small Data Area pointer register
172   }
173   
174   // On PPC64, r13 is the thread pointer. Never allocate this register.
175   if (Subtarget.isPPC64()) {
176     Reserved.set(PPC::R13);
177
178     Reserved.set(PPC::X1);
179     Reserved.set(PPC::X13);
180
181     if (PPCFI->needsFP(MF) || hasBasePointer(MF)) {
182       Reserved.set(PPC::X31);
183
184       // If we need a base pointer, and we also have a frame pointer, then use
185       // r30 as the base pointer.
186       if (PPCFI->needsFP(MF) && hasBasePointer(MF))
187         Reserved.set(PPC::X30);
188     }
189
190     // The 64-bit SVR4 ABI reserves r2 for the TOC pointer.
191     if (Subtarget.isSVR4ABI()) {
192       Reserved.set(PPC::X2);
193     }
194   }
195
196   if (PPCFI->needsFP(MF) || hasBasePointer(MF)) {
197     Reserved.set(PPC::R31);
198
199     if (PPCFI->needsFP(MF) && hasBasePointer(MF))
200       Reserved.set(PPC::R30);
201   }
202
203   // Reserve Altivec registers when Altivec is unavailable.
204   if (!Subtarget.hasAltivec())
205     for (TargetRegisterClass::iterator I = PPC::VRRCRegClass.begin(),
206          IE = PPC::VRRCRegClass.end(); I != IE; ++I)
207       Reserved.set(*I);
208
209   return Reserved;
210 }
211
212 unsigned
213 PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
214                                          MachineFunction &MF) const {
215   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
216   const unsigned DefaultSafety = 1;
217
218   switch (RC->getID()) {
219   default:
220     return 0;
221   case PPC::G8RC_NOX0RegClassID:
222   case PPC::GPRC_NOR0RegClassID: 
223   case PPC::G8RCRegClassID:
224   case PPC::GPRCRegClassID: {
225     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
226     return 32 - FP - DefaultSafety;
227   }
228   case PPC::F8RCRegClassID:
229   case PPC::F4RCRegClassID:
230   case PPC::VRRCRegClassID:
231     return 32 - DefaultSafety;
232   case PPC::CRRCRegClassID:
233     return 8 - DefaultSafety;
234   }
235 }
236
237 //===----------------------------------------------------------------------===//
238 // Stack Frame Processing methods
239 //===----------------------------------------------------------------------===//
240
241 /// lowerDynamicAlloc - Generate the code for allocating an object in the
242 /// current frame.  The sequence of code with be in the general form
243 ///
244 ///   addi   R0, SP, \#frameSize ; get the address of the previous frame
245 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
246 ///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
247 ///
248 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
249   // Get the instruction.
250   MachineInstr &MI = *II;
251   // Get the instruction's basic block.
252   MachineBasicBlock &MBB = *MI.getParent();
253   // Get the basic block's function.
254   MachineFunction &MF = *MBB.getParent();
255   // Get the frame info.
256   MachineFrameInfo *MFI = MF.getFrameInfo();
257   // Get the instruction info.
258   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
259   // Determine whether 64-bit pointers are used.
260   bool LP64 = Subtarget.isPPC64();
261   DebugLoc dl = MI.getDebugLoc();
262
263   // Get the maximum call stack size.
264   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
265   // Get the total frame size.
266   unsigned FrameSize = MFI->getStackSize();
267   
268   // Get stack alignments.
269   unsigned TargetAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
270   unsigned MaxAlign = MFI->getMaxAlignment();
271   if (MaxAlign > TargetAlign)
272     report_fatal_error("Dynamic alloca with large aligns not supported");
273
274   // Determine the previous frame's address.  If FrameSize can't be
275   // represented as 16 bits or we need special alignment, then we load the
276   // previous frame's address from 0(SP).  Why not do an addis of the hi? 
277   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero. 
278   // Constructing the constant and adding would take 3 instructions. 
279   // Fortunately, a frame greater than 32K is rare.
280   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
281   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
282   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
283   
284   if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
285     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), Reg)
286       .addReg(PPC::R31)
287       .addImm(FrameSize);
288   } else if (LP64) {
289     BuildMI(MBB, II, dl, TII.get(PPC::LD), Reg)
290       .addImm(0)
291       .addReg(PPC::X1);
292   } else {
293     BuildMI(MBB, II, dl, TII.get(PPC::LWZ), Reg)
294       .addImm(0)
295       .addReg(PPC::R1);
296   }
297   
298   // Grow the stack and update the stack pointer link, then determine the
299   // address of new allocated space.
300   if (LP64) {
301     BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
302       .addReg(Reg, RegState::Kill)
303       .addReg(PPC::X1)
304       .addReg(MI.getOperand(1).getReg());
305     if (!MI.getOperand(1).isKill())
306       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
307         .addReg(PPC::X1)
308         .addImm(maxCallFrameSize);
309     else
310       // Implicitly kill the register.
311       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
312         .addReg(PPC::X1)
313         .addImm(maxCallFrameSize)
314         .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
315   } else {
316     BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
317       .addReg(Reg, RegState::Kill)
318       .addReg(PPC::R1)
319       .addReg(MI.getOperand(1).getReg());
320
321     if (!MI.getOperand(1).isKill())
322       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
323         .addReg(PPC::R1)
324         .addImm(maxCallFrameSize);
325     else
326       // Implicitly kill the register.
327       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
328         .addReg(PPC::R1)
329         .addImm(maxCallFrameSize)
330         .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
331   }
332   
333   // Discard the DYNALLOC instruction.
334   MBB.erase(II);
335 }
336
337 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
338 /// reserving a whole register (R0), we scrounge for one here. This generates
339 /// code like this:
340 ///
341 ///   mfcr rA                  ; Move the conditional register into GPR rA.
342 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
343 ///   stw rA, FI               ; Store rA to the frame.
344 ///
345 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
346                                       unsigned FrameIndex) const {
347   // Get the instruction.
348   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>
349   // Get the instruction's basic block.
350   MachineBasicBlock &MBB = *MI.getParent();
351   MachineFunction &MF = *MBB.getParent();
352   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
353   DebugLoc dl = MI.getDebugLoc();
354
355   bool LP64 = Subtarget.isPPC64();
356   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
357   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
358
359   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
360   unsigned SrcReg = MI.getOperand(0).getReg();
361
362   // We need to store the CR in the low 4-bits of the saved value. First, issue
363   // an MFOCRF to save all of the CRBits and, if needed, kill the SrcReg.
364   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
365           .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
366     
367   // If the saved register wasn't CR0, shift the bits left so that they are in
368   // CR0's slot.
369   if (SrcReg != PPC::CR0) {
370     unsigned Reg1 = Reg;
371     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
372
373     // rlwinm rA, rA, ShiftBits, 0, 31.
374     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
375       .addReg(Reg1, RegState::Kill)
376       .addImm(getEncodingValue(SrcReg) * 4)
377       .addImm(0)
378       .addImm(31);
379   }
380
381   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
382                     .addReg(Reg, RegState::Kill),
383                     FrameIndex);
384
385   // Discard the pseudo instruction.
386   MBB.erase(II);
387 }
388
389 void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
390                                       unsigned FrameIndex) const {
391   // Get the instruction.
392   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CR <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 DestReg = MI.getOperand(0).getReg();
405   assert(MI.definesRegister(DestReg) &&
406     "RESTORE_CR does not define its destination");
407
408   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
409                               Reg), FrameIndex);
410
411   // If the reloaded register isn't CR0, shift the bits right so that they are
412   // in the right CR's slot.
413   if (DestReg != PPC::CR0) {
414     unsigned Reg1 = Reg;
415     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
416
417     unsigned ShiftBits = getEncodingValue(DestReg)*4;
418     // rlwinm r11, r11, 32-ShiftBits, 0, 31.
419     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
420              .addReg(Reg1, RegState::Kill).addImm(32-ShiftBits).addImm(0)
421              .addImm(31);
422   }
423
424   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF), DestReg)
425              .addReg(Reg, RegState::Kill);
426
427   // Discard the pseudo instruction.
428   MBB.erase(II);
429 }
430
431 void PPCRegisterInfo::lowerVRSAVESpilling(MachineBasicBlock::iterator II,
432                                           unsigned FrameIndex) const {
433   // Get the instruction.
434   MachineInstr &MI = *II;       // ; SPILL_VRSAVE <SrcReg>, <offset>
435   // Get the instruction's basic block.
436   MachineBasicBlock &MBB = *MI.getParent();
437   MachineFunction &MF = *MBB.getParent();
438   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
439   DebugLoc dl = MI.getDebugLoc();
440
441   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
442   unsigned Reg = MF.getRegInfo().createVirtualRegister(GPRC);
443   unsigned SrcReg = MI.getOperand(0).getReg();
444
445   BuildMI(MBB, II, dl, TII.get(PPC::MFVRSAVEv), Reg)
446           .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
447     
448   addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::STW))
449                     .addReg(Reg, RegState::Kill),
450                     FrameIndex);
451
452   // Discard the pseudo instruction.
453   MBB.erase(II);
454 }
455
456 void PPCRegisterInfo::lowerVRSAVERestore(MachineBasicBlock::iterator II,
457                                          unsigned FrameIndex) const {
458   // Get the instruction.
459   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_VRSAVE <offset>
460   // Get the instruction's basic block.
461   MachineBasicBlock &MBB = *MI.getParent();
462   MachineFunction &MF = *MBB.getParent();
463   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
464   DebugLoc dl = MI.getDebugLoc();
465
466   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
467   unsigned Reg = MF.getRegInfo().createVirtualRegister(GPRC);
468   unsigned DestReg = MI.getOperand(0).getReg();
469   assert(MI.definesRegister(DestReg) &&
470     "RESTORE_VRSAVE does not define its destination");
471
472   addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::LWZ),
473                               Reg), FrameIndex);
474
475   BuildMI(MBB, II, dl, TII.get(PPC::MTVRSAVEv), DestReg)
476              .addReg(Reg, RegState::Kill);
477
478   // Discard the pseudo instruction.
479   MBB.erase(II);
480 }
481
482 bool
483 PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
484                                       unsigned Reg, int &FrameIdx) const {
485
486   // For the nonvolatile condition registers (CR2, CR3, CR4) in an SVR4
487   // ABI, return true to prevent allocating an additional frame slot.
488   // For 64-bit, the CR save area is at SP+8; the value of FrameIdx = 0
489   // is arbitrary and will be subsequently ignored.  For 32-bit, we have
490   // previously created the stack slot if needed, so return its FrameIdx.
491   if (Subtarget.isSVR4ABI() && PPC::CR2 <= Reg && Reg <= PPC::CR4) {
492     if (Subtarget.isPPC64())
493       FrameIdx = 0;
494     else {
495       const PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
496       FrameIdx = FI->getCRSpillFrameIndex();
497     }
498     return true;
499   }
500   return false;
501 }
502
503 // Figure out if the offset in the instruction must be a multiple of 4.
504 // This is true for instructions like "STD".
505 static bool usesIXAddr(const MachineInstr &MI) {
506   unsigned OpC = MI.getOpcode();
507
508   switch (OpC) {
509   default:
510     return false;
511   case PPC::LWA:
512   case PPC::LD:
513   case PPC::STD:
514     return true;
515   }
516 }
517
518 // Return the OffsetOperandNo given the FIOperandNum (and the instruction).
519 static unsigned getOffsetONFromFION(const MachineInstr &MI,
520                                     unsigned FIOperandNum) {
521   // Take into account whether it's an add or mem instruction
522   unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
523   if (MI.isInlineAsm())
524     OffsetOperandNo = FIOperandNum-1;
525
526   return OffsetOperandNo;
527 }
528
529 void
530 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
531                                      int SPAdj, unsigned FIOperandNum,
532                                      RegScavenger *RS) const {
533   assert(SPAdj == 0 && "Unexpected");
534
535   // Get the instruction.
536   MachineInstr &MI = *II;
537   // Get the instruction's basic block.
538   MachineBasicBlock &MBB = *MI.getParent();
539   // Get the basic block's function.
540   MachineFunction &MF = *MBB.getParent();
541   // Get the instruction info.
542   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
543   // Get the frame info.
544   MachineFrameInfo *MFI = MF.getFrameInfo();
545   DebugLoc dl = MI.getDebugLoc();
546
547   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
548
549   // Get the frame index.
550   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
551
552   // Get the frame pointer save index.  Users of this index are primarily
553   // DYNALLOC instructions.
554   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
555   int FPSI = FI->getFramePointerSaveIndex();
556   // Get the instruction opcode.
557   unsigned OpC = MI.getOpcode();
558   
559   // Special case for dynamic alloca.
560   if (FPSI && FrameIndex == FPSI &&
561       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
562     lowerDynamicAlloc(II);
563     return;
564   }
565
566   // Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
567   if (OpC == PPC::SPILL_CR) {
568     lowerCRSpilling(II, FrameIndex);
569     return;
570   } else if (OpC == PPC::RESTORE_CR) {
571     lowerCRRestore(II, FrameIndex);
572     return;
573   } else if (OpC == PPC::SPILL_VRSAVE) {
574     lowerVRSAVESpilling(II, FrameIndex);
575     return;
576   } else if (OpC == PPC::RESTORE_VRSAVE) {
577     lowerVRSAVERestore(II, FrameIndex);
578     return;
579   }
580
581   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
582   MI.getOperand(FIOperandNum).ChangeToRegister(
583     FrameIndex < 0 ? getBaseRegister(MF) : getFrameRegister(MF), false);
584
585   // Figure out if the offset in the instruction is shifted right two bits.
586   bool isIXAddr = usesIXAddr(MI);
587
588   // If the instruction is not present in ImmToIdxMap, then it has no immediate
589   // form (and must be r+r).
590   bool noImmForm = !MI.isInlineAsm() && !ImmToIdxMap.count(OpC);
591
592   // Now add the frame object offset to the offset from r1.
593   int Offset = MFI->getObjectOffset(FrameIndex);
594   Offset += MI.getOperand(OffsetOperandNo).getImm();
595
596   // If we're not using a Frame Pointer that has been set to the value of the
597   // SP before having the stack size subtracted from it, then add the stack size
598   // to Offset to get the correct offset.
599   // Naked functions have stack size 0, although getStackSize may not reflect that
600   // because we didn't call all the pieces that compute it for naked functions.
601   if (!MF.getFunction()->getAttributes().
602         hasAttribute(AttributeSet::FunctionIndex, Attribute::Naked)) {
603     if (!(hasBasePointer(MF) && FrameIndex < 0))
604       Offset += MFI->getStackSize();
605   }
606
607   // If we can, encode the offset directly into the instruction.  If this is a
608   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
609   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
610   // clear can be encoded.  This is extremely uncommon, because normally you
611   // only "std" to a stack slot that is at least 4-byte aligned, but it can
612   // happen in invalid code.
613   assert(OpC != PPC::DBG_VALUE &&
614          "This should be handle in a target independent way");
615   if (!noImmForm && isInt<16>(Offset) && (!isIXAddr || (Offset & 3) == 0)) {
616     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
617     return;
618   }
619
620   // The offset doesn't fit into a single register, scavenge one to build the
621   // offset in.
622
623   bool is64Bit = Subtarget.isPPC64();
624   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
625   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
626   const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
627   unsigned SRegHi = MF.getRegInfo().createVirtualRegister(RC),
628            SReg = MF.getRegInfo().createVirtualRegister(RC);
629
630   // Insert a set of rA with the full offset value before the ld, st, or add
631   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
632     .addImm(Offset >> 16);
633   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
634     .addReg(SRegHi, RegState::Kill)
635     .addImm(Offset);
636
637   // Convert into indexed form of the instruction:
638   // 
639   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
640   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
641   unsigned OperandBase;
642
643   if (noImmForm)
644     OperandBase = 1;
645   else if (OpC != TargetOpcode::INLINEASM) {
646     assert(ImmToIdxMap.count(OpC) &&
647            "No indexed form of load or store available!");
648     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
649     MI.setDesc(TII.get(NewOpcode));
650     OperandBase = 1;
651   } else {
652     OperandBase = OffsetOperandNo;
653   }
654
655   unsigned StackReg = MI.getOperand(FIOperandNum).getReg();
656   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
657   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
658 }
659
660 unsigned PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
661   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
662
663   if (!Subtarget.isPPC64())
664     return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
665   else
666     return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
667 }
668
669 unsigned PPCRegisterInfo::getEHExceptionRegister() const {
670   return !Subtarget.isPPC64() ? PPC::R3 : PPC::X3;
671 }
672
673 unsigned PPCRegisterInfo::getEHHandlerRegister() const {
674   return !Subtarget.isPPC64() ? PPC::R4 : PPC::X4;
675 }
676
677 unsigned PPCRegisterInfo::getBaseRegister(const MachineFunction &MF) const {
678   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
679
680   if (!hasBasePointer(MF))
681     return getFrameRegister(MF);
682
683   if (!Subtarget.isPPC64())
684     return TFI->hasFP(MF) ? PPC::R30 : PPC::R31;
685   else
686     return TFI->hasFP(MF) ? PPC::X30 : PPC::X31;
687 }
688
689 bool PPCRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
690   if (!EnableBasePointer)
691     return false;
692   if (AlwaysBasePointer)
693     return true;
694
695   // If we need to realign the stack, then the stack pointer can no longer
696   // serve as an offset into the caller's stack space. As a result, we need a
697   // base pointer.
698   return needsStackRealignment(MF);
699 }
700
701 bool PPCRegisterInfo::canRealignStack(const MachineFunction &MF) const {
702   if (!MF.getTarget().Options.RealignStack)
703     return false;
704
705   return true;
706 }
707
708 bool PPCRegisterInfo::needsStackRealignment(const MachineFunction &MF) const {
709   const MachineFrameInfo *MFI = MF.getFrameInfo();
710   const Function *F = MF.getFunction();
711   unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
712   bool requiresRealignment =
713     ((MFI->getMaxAlignment() > StackAlign) ||
714      F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
715                                      Attribute::StackAlignment));
716
717   return requiresRealignment && canRealignStack(MF);
718 }
719
720 /// Returns true if the instruction's frame index
721 /// reference would be better served by a base register other than FP
722 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
723 /// references it should create new base registers for.
724 bool PPCRegisterInfo::
725 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
726   assert(Offset < 0 && "Local offset must be negative");
727
728   unsigned FIOperandNum = 0;
729   while (!MI->getOperand(FIOperandNum).isFI()) {
730     ++FIOperandNum;
731     assert(FIOperandNum < MI->getNumOperands() &&
732            "Instr doesn't have FrameIndex operand!");
733   }
734
735   unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
736   Offset += MI->getOperand(OffsetOperandNo).getImm();
737
738   // It's the load/store FI references that cause issues, as it can be difficult
739   // to materialize the offset if it won't fit in the literal field. Estimate
740   // based on the size of the local frame and some conservative assumptions
741   // about the rest of the stack frame (note, this is pre-regalloc, so
742   // we don't know everything for certain yet) whether this offset is likely
743   // to be out of range of the immediate. Return true if so.
744
745   // We only generate virtual base registers for loads and stores that have
746   // an r+i form. Return false for everything else.
747   unsigned OpC = MI->getOpcode();
748   if (!ImmToIdxMap.count(OpC))
749     return false;
750
751   // Don't generate a new virtual base register just to add zero to it.
752   if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
753       MI->getOperand(2).getImm() == 0)
754     return false;
755
756   MachineBasicBlock &MBB = *MI->getParent();
757   MachineFunction &MF = *MBB.getParent();
758
759   const PPCFrameLowering *PPCFI =
760     static_cast<const PPCFrameLowering*>(MF.getTarget().getFrameLowering());
761   unsigned StackEst =
762     PPCFI->determineFrameLayout(MF, false, true);
763
764   // If we likely don't need a stack frame, then we probably don't need a
765   // virtual base register either.
766   if (!StackEst)
767     return false;
768
769   // Estimate an offset from the stack pointer.
770   // The incoming offset is relating to the SP at the start of the function,
771   // but when we access the local it'll be relative to the SP after local
772   // allocation, so adjust our SP-relative offset by that allocation size.
773   Offset += StackEst;
774
775   // The frame pointer will point to the end of the stack, so estimate the
776   // offset as the difference between the object offset and the FP location.
777   return !isFrameOffsetLegal(MI, Offset);
778 }
779
780 /// Insert defining instruction(s) for BaseReg to
781 /// be a pointer to FrameIdx at the beginning of the basic block.
782 void PPCRegisterInfo::
783 materializeFrameBaseRegister(MachineBasicBlock *MBB,
784                              unsigned BaseReg, int FrameIdx,
785                              int64_t Offset) const {
786   unsigned ADDriOpc = Subtarget.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
787
788   MachineBasicBlock::iterator Ins = MBB->begin();
789   DebugLoc DL;                  // Defaults to "unknown"
790   if (Ins != MBB->end())
791     DL = Ins->getDebugLoc();
792
793   const MachineFunction &MF = *MBB->getParent();
794   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
795   const MCInstrDesc &MCID = TII.get(ADDriOpc);
796   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
797   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
798
799   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
800     .addFrameIndex(FrameIdx).addImm(Offset);
801 }
802
803 void
804 PPCRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
805                                    unsigned BaseReg, int64_t Offset) const {
806   MachineInstr &MI = *I;
807
808   unsigned FIOperandNum = 0;
809   while (!MI.getOperand(FIOperandNum).isFI()) {
810     ++FIOperandNum;
811     assert(FIOperandNum < MI.getNumOperands() &&
812            "Instr doesn't have FrameIndex operand!");
813   }
814
815   MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
816   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
817   Offset += MI.getOperand(OffsetOperandNo).getImm();
818   MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
819 }
820
821 bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
822                                          int64_t Offset) const {
823   return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
824          (isInt<16>(Offset) && (!usesIXAddr(*MI) || (Offset & 3) == 0));
825 }
826