Cleanup PPC Altivec registers in CSR lists and improve VRSAVE handling
[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 PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST)
52   : PPCGenRegisterInfo(ST.isPPC64() ? PPC::LR8 : PPC::LR,
53                        ST.isPPC64() ? 0 : 1,
54                        ST.isPPC64() ? 0 : 1),
55     Subtarget(ST) {
56   ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
57   ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
58   ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
59   ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
60   ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
61   ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
62   ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
63   ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
64
65   // 64-bit
66   ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
67   ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
68   ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
69   ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
70   ImmToIdxMap[PPC::ADDI8] = PPC::ADD8;
71 }
72
73 /// getPointerRegClass - Return the register class to use to hold pointers.
74 /// This is used for addressing modes.
75 const TargetRegisterClass *
76 PPCRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
77                                                                        const {
78   // Note that PPCInstrInfo::FoldImmediate also directly uses this Kind value
79   // when it checks for ZERO folding.
80   if (Kind == 1) {
81     if (Subtarget.isPPC64())
82       return &PPC::G8RC_NOX0RegClass;
83     return &PPC::GPRC_NOR0RegClass;
84   }
85
86   if (Subtarget.isPPC64())
87     return &PPC::G8RCRegClass;
88   return &PPC::GPRCRegClass;
89 }
90
91 const uint16_t*
92 PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
93   if (Subtarget.isDarwinABI())
94     return Subtarget.isPPC64() ? (Subtarget.hasAltivec() ?
95                                   CSR_Darwin64_Altivec_SaveList :
96                                   CSR_Darwin64_SaveList) :
97                                  (Subtarget.hasAltivec() ?
98                                   CSR_Darwin32_Altivec_SaveList :
99                                   CSR_Darwin32_SaveList);
100
101   return Subtarget.isPPC64() ? (Subtarget.hasAltivec() ?
102                                 CSR_SVR464_Altivec_SaveList :
103                                 CSR_SVR464_SaveList) :
104                                (Subtarget.hasAltivec() ?
105                                 CSR_SVR432_Altivec_SaveList :
106                                 CSR_SVR432_SaveList);
107 }
108
109 const uint32_t*
110 PPCRegisterInfo::getCallPreservedMask(CallingConv::ID CC) const {
111   if (Subtarget.isDarwinABI())
112     return Subtarget.isPPC64() ? (Subtarget.hasAltivec() ?
113                                   CSR_Darwin64_Altivec_RegMask :
114                                   CSR_Darwin64_RegMask) :
115                                  (Subtarget.hasAltivec() ?
116                                   CSR_Darwin32_Altivec_RegMask :
117                                   CSR_Darwin32_RegMask);
118
119   return Subtarget.isPPC64() ? (Subtarget.hasAltivec() ?
120                                 CSR_SVR464_Altivec_RegMask :
121                                 CSR_SVR464_RegMask) :
122                                (Subtarget.hasAltivec() ?
123                                 CSR_SVR432_Altivec_RegMask :
124                                 CSR_SVR432_RegMask);
125 }
126
127 const uint32_t*
128 PPCRegisterInfo::getNoPreservedMask() const {
129   return CSR_NoRegs_RegMask;
130 }
131
132 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
133   BitVector Reserved(getNumRegs());
134   const PPCFrameLowering *PPCFI =
135     static_cast<const PPCFrameLowering*>(MF.getTarget().getFrameLowering());
136
137   // The ZERO register is not really a register, but the representation of r0
138   // when used in instructions that treat r0 as the constant 0.
139   Reserved.set(PPC::ZERO);
140   Reserved.set(PPC::ZERO8);
141
142   // The FP register is also not really a register, but is the representation
143   // of the frame pointer register used by ISD::FRAMEADDR.
144   Reserved.set(PPC::FP);
145   Reserved.set(PPC::FP8);
146
147   // The counter registers must be reserved so that counter-based loops can
148   // be correctly formed (and the mtctr instructions are not DCE'd).
149   Reserved.set(PPC::CTR);
150   Reserved.set(PPC::CTR8);
151
152   Reserved.set(PPC::R1);
153   Reserved.set(PPC::LR);
154   Reserved.set(PPC::LR8);
155   Reserved.set(PPC::RM);
156
157   if (!Subtarget.isDarwinABI() || !Subtarget.hasAltivec())
158     Reserved.set(PPC::VRSAVE);
159
160   // The SVR4 ABI reserves r2 and r13
161   if (Subtarget.isSVR4ABI()) {
162     Reserved.set(PPC::R2);  // System-reserved register
163     Reserved.set(PPC::R13); // Small Data Area pointer register
164   }
165   
166   // On PPC64, r13 is the thread pointer. Never allocate this register.
167   if (Subtarget.isPPC64()) {
168     Reserved.set(PPC::R13);
169
170     Reserved.set(PPC::X1);
171     Reserved.set(PPC::X13);
172
173     if (PPCFI->needsFP(MF))
174       Reserved.set(PPC::X31);
175
176     // The 64-bit SVR4 ABI reserves r2 for the TOC pointer.
177     if (Subtarget.isSVR4ABI()) {
178       Reserved.set(PPC::X2);
179     }
180   }
181
182   if (PPCFI->needsFP(MF))
183     Reserved.set(PPC::R31);
184
185   // Reserve Altivec registers when Altivec is unavailable.
186   if (!Subtarget.hasAltivec())
187     for (TargetRegisterClass::iterator I = PPC::VRRCRegClass.begin(),
188          IE = PPC::VRRCRegClass.end(); I != IE; ++I)
189       Reserved.set(*I);
190
191   return Reserved;
192 }
193
194 unsigned
195 PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
196                                          MachineFunction &MF) const {
197   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
198   const unsigned DefaultSafety = 1;
199
200   switch (RC->getID()) {
201   default:
202     return 0;
203   case PPC::G8RC_NOX0RegClassID:
204   case PPC::GPRC_NOR0RegClassID: 
205   case PPC::G8RCRegClassID:
206   case PPC::GPRCRegClassID: {
207     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
208     return 32 - FP - DefaultSafety;
209   }
210   case PPC::F8RCRegClassID:
211   case PPC::F4RCRegClassID:
212   case PPC::VRRCRegClassID:
213     return 32 - DefaultSafety;
214   case PPC::CRRCRegClassID:
215     return 8 - DefaultSafety;
216   }
217 }
218
219 //===----------------------------------------------------------------------===//
220 // Stack Frame Processing methods
221 //===----------------------------------------------------------------------===//
222
223 /// lowerDynamicAlloc - Generate the code for allocating an object in the
224 /// current frame.  The sequence of code with be in the general form
225 ///
226 ///   addi   R0, SP, \#frameSize ; get the address of the previous frame
227 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
228 ///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
229 ///
230 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
231   // Get the instruction.
232   MachineInstr &MI = *II;
233   // Get the instruction's basic block.
234   MachineBasicBlock &MBB = *MI.getParent();
235   // Get the basic block's function.
236   MachineFunction &MF = *MBB.getParent();
237   // Get the frame info.
238   MachineFrameInfo *MFI = MF.getFrameInfo();
239   // Get the instruction info.
240   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
241   // Determine whether 64-bit pointers are used.
242   bool LP64 = Subtarget.isPPC64();
243   DebugLoc dl = MI.getDebugLoc();
244
245   // Get the maximum call stack size.
246   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
247   // Get the total frame size.
248   unsigned FrameSize = MFI->getStackSize();
249   
250   // Get stack alignments.
251   unsigned TargetAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
252   unsigned MaxAlign = MFI->getMaxAlignment();
253   if (MaxAlign > TargetAlign)
254     report_fatal_error("Dynamic alloca with large aligns not supported");
255
256   // Determine the previous frame's address.  If FrameSize can't be
257   // represented as 16 bits or we need special alignment, then we load the
258   // previous frame's address from 0(SP).  Why not do an addis of the hi? 
259   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero. 
260   // Constructing the constant and adding would take 3 instructions. 
261   // Fortunately, a frame greater than 32K is rare.
262   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
263   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
264   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
265   
266   if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
267     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), Reg)
268       .addReg(PPC::R31)
269       .addImm(FrameSize);
270   } else if (LP64) {
271     BuildMI(MBB, II, dl, TII.get(PPC::LD), Reg)
272       .addImm(0)
273       .addReg(PPC::X1);
274   } else {
275     BuildMI(MBB, II, dl, TII.get(PPC::LWZ), Reg)
276       .addImm(0)
277       .addReg(PPC::R1);
278   }
279   
280   // Grow the stack and update the stack pointer link, then determine the
281   // address of new allocated space.
282   if (LP64) {
283     BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
284       .addReg(Reg, RegState::Kill)
285       .addReg(PPC::X1)
286       .addReg(MI.getOperand(1).getReg());
287     if (!MI.getOperand(1).isKill())
288       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
289         .addReg(PPC::X1)
290         .addImm(maxCallFrameSize);
291     else
292       // Implicitly kill the register.
293       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
294         .addReg(PPC::X1)
295         .addImm(maxCallFrameSize)
296         .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
297   } else {
298     BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
299       .addReg(Reg, RegState::Kill)
300       .addReg(PPC::R1)
301       .addReg(MI.getOperand(1).getReg());
302
303     if (!MI.getOperand(1).isKill())
304       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
305         .addReg(PPC::R1)
306         .addImm(maxCallFrameSize);
307     else
308       // Implicitly kill the register.
309       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
310         .addReg(PPC::R1)
311         .addImm(maxCallFrameSize)
312         .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
313   }
314   
315   // Discard the DYNALLOC instruction.
316   MBB.erase(II);
317 }
318
319 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
320 /// reserving a whole register (R0), we scrounge for one here. This generates
321 /// code like this:
322 ///
323 ///   mfcr rA                  ; Move the conditional register into GPR rA.
324 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
325 ///   stw rA, FI               ; Store rA to the frame.
326 ///
327 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
328                                       unsigned FrameIndex) const {
329   // Get the instruction.
330   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>
331   // Get the instruction's basic block.
332   MachineBasicBlock &MBB = *MI.getParent();
333   MachineFunction &MF = *MBB.getParent();
334   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
335   DebugLoc dl = MI.getDebugLoc();
336
337   bool LP64 = Subtarget.isPPC64();
338   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
339   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
340
341   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
342   unsigned SrcReg = MI.getOperand(0).getReg();
343
344   // We need to store the CR in the low 4-bits of the saved value. First, issue
345   // an MFCRpsued to save all of the CRBits and, if needed, kill the SrcReg.
346   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFCR8pseud : PPC::MFCRpseud), Reg)
347           .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
348     
349   // If the saved register wasn't CR0, shift the bits left so that they are in
350   // CR0's slot.
351   if (SrcReg != PPC::CR0) {
352     unsigned Reg1 = Reg;
353     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
354
355     // rlwinm rA, rA, ShiftBits, 0, 31.
356     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
357       .addReg(Reg1, RegState::Kill)
358       .addImm(getEncodingValue(SrcReg) * 4)
359       .addImm(0)
360       .addImm(31);
361   }
362
363   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
364                     .addReg(Reg, RegState::Kill),
365                     FrameIndex);
366
367   // Discard the pseudo instruction.
368   MBB.erase(II);
369 }
370
371 void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
372                                       unsigned FrameIndex) const {
373   // Get the instruction.
374   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CR <offset>
375   // Get the instruction's basic block.
376   MachineBasicBlock &MBB = *MI.getParent();
377   MachineFunction &MF = *MBB.getParent();
378   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
379   DebugLoc dl = MI.getDebugLoc();
380
381   bool LP64 = Subtarget.isPPC64();
382   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
383   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
384
385   unsigned Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
386   unsigned DestReg = MI.getOperand(0).getReg();
387   assert(MI.definesRegister(DestReg) &&
388     "RESTORE_CR does not define its destination");
389
390   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
391                               Reg), FrameIndex);
392
393   // If the reloaded register isn't CR0, shift the bits right so that they are
394   // in the right CR's slot.
395   if (DestReg != PPC::CR0) {
396     unsigned Reg1 = Reg;
397     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
398
399     unsigned ShiftBits = getEncodingValue(DestReg)*4;
400     // rlwinm r11, r11, 32-ShiftBits, 0, 31.
401     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
402              .addReg(Reg1, RegState::Kill).addImm(32-ShiftBits).addImm(0)
403              .addImm(31);
404   }
405
406   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTCRF8 : PPC::MTCRF), DestReg)
407              .addReg(Reg, RegState::Kill);
408
409   // Discard the pseudo instruction.
410   MBB.erase(II);
411 }
412
413 void PPCRegisterInfo::lowerVRSAVESpilling(MachineBasicBlock::iterator II,
414                                           unsigned FrameIndex) const {
415   // Get the instruction.
416   MachineInstr &MI = *II;       // ; SPILL_VRSAVE <SrcReg>, <offset>
417   // Get the instruction's basic block.
418   MachineBasicBlock &MBB = *MI.getParent();
419   MachineFunction &MF = *MBB.getParent();
420   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
421   DebugLoc dl = MI.getDebugLoc();
422
423   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
424   unsigned Reg = MF.getRegInfo().createVirtualRegister(GPRC);
425   unsigned SrcReg = MI.getOperand(0).getReg();
426
427   BuildMI(MBB, II, dl, TII.get(PPC::MFVRSAVEv), Reg)
428           .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
429     
430   addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::STW))
431                     .addReg(Reg, RegState::Kill),
432                     FrameIndex);
433
434   // Discard the pseudo instruction.
435   MBB.erase(II);
436 }
437
438 void PPCRegisterInfo::lowerVRSAVERestore(MachineBasicBlock::iterator II,
439                                          unsigned FrameIndex) const {
440   // Get the instruction.
441   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_VRSAVE <offset>
442   // Get the instruction's basic block.
443   MachineBasicBlock &MBB = *MI.getParent();
444   MachineFunction &MF = *MBB.getParent();
445   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
446   DebugLoc dl = MI.getDebugLoc();
447
448   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
449   unsigned Reg = MF.getRegInfo().createVirtualRegister(GPRC);
450   unsigned DestReg = MI.getOperand(0).getReg();
451   assert(MI.definesRegister(DestReg) &&
452     "RESTORE_VRSAVE does not define its destination");
453
454   addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::LWZ),
455                               Reg), FrameIndex);
456
457   BuildMI(MBB, II, dl, TII.get(PPC::MTVRSAVEv), DestReg)
458              .addReg(Reg, RegState::Kill);
459
460   // Discard the pseudo instruction.
461   MBB.erase(II);
462 }
463
464 bool
465 PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
466                                       unsigned Reg, int &FrameIdx) const {
467
468   // For the nonvolatile condition registers (CR2, CR3, CR4) in an SVR4
469   // ABI, return true to prevent allocating an additional frame slot.
470   // For 64-bit, the CR save area is at SP+8; the value of FrameIdx = 0
471   // is arbitrary and will be subsequently ignored.  For 32-bit, we have
472   // previously created the stack slot if needed, so return its FrameIdx.
473   if (Subtarget.isSVR4ABI() && PPC::CR2 <= Reg && Reg <= PPC::CR4) {
474     if (Subtarget.isPPC64())
475       FrameIdx = 0;
476     else {
477       const PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
478       FrameIdx = FI->getCRSpillFrameIndex();
479     }
480     return true;
481   }
482   return false;
483 }
484
485 // Figure out if the offset in the instruction must be a multiple of 4.
486 // This is true for instructions like "STD".
487 static bool usesIXAddr(const MachineInstr &MI) {
488   unsigned OpC = MI.getOpcode();
489
490   switch (OpC) {
491   default:
492     return false;
493   case PPC::LWA:
494   case PPC::LD:
495   case PPC::STD:
496     return true;
497   }
498 }
499
500 // Return the OffsetOperandNo given the FIOperandNum (and the instruction).
501 static unsigned getOffsetONFromFION(const MachineInstr &MI,
502                                     unsigned FIOperandNum) {
503   // Take into account whether it's an add or mem instruction
504   unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
505   if (MI.isInlineAsm())
506     OffsetOperandNo = FIOperandNum-1;
507
508   return OffsetOperandNo;
509 }
510
511 void
512 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
513                                      int SPAdj, unsigned FIOperandNum,
514                                      RegScavenger *RS) const {
515   assert(SPAdj == 0 && "Unexpected");
516
517   // Get the instruction.
518   MachineInstr &MI = *II;
519   // Get the instruction's basic block.
520   MachineBasicBlock &MBB = *MI.getParent();
521   // Get the basic block's function.
522   MachineFunction &MF = *MBB.getParent();
523   // Get the instruction info.
524   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
525   // Get the frame info.
526   MachineFrameInfo *MFI = MF.getFrameInfo();
527   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
528   DebugLoc dl = MI.getDebugLoc();
529
530   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
531
532   // Get the frame index.
533   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
534
535   // Get the frame pointer save index.  Users of this index are primarily
536   // DYNALLOC instructions.
537   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
538   int FPSI = FI->getFramePointerSaveIndex();
539   // Get the instruction opcode.
540   unsigned OpC = MI.getOpcode();
541   
542   // Special case for dynamic alloca.
543   if (FPSI && FrameIndex == FPSI &&
544       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
545     lowerDynamicAlloc(II);
546     return;
547   }
548
549   // Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
550   if (OpC == PPC::SPILL_CR) {
551     lowerCRSpilling(II, FrameIndex);
552     return;
553   } else if (OpC == PPC::RESTORE_CR) {
554     lowerCRRestore(II, FrameIndex);
555     return;
556   } else if (OpC == PPC::SPILL_VRSAVE) {
557     lowerVRSAVESpilling(II, FrameIndex);
558     return;
559   } else if (OpC == PPC::RESTORE_VRSAVE) {
560     lowerVRSAVERestore(II, FrameIndex);
561     return;
562   }
563
564   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
565
566   bool is64Bit = Subtarget.isPPC64();
567   MI.getOperand(FIOperandNum).ChangeToRegister(TFI->hasFP(MF) ?
568                                               (is64Bit ? PPC::X31 : PPC::R31) :
569                                                 (is64Bit ? PPC::X1 : PPC::R1),
570                                               false);
571
572   // Figure out if the offset in the instruction is shifted right two bits.
573   bool isIXAddr = usesIXAddr(MI);
574
575   // If the instruction is not present in ImmToIdxMap, then it has no immediate
576   // form (and must be r+r).
577   bool noImmForm = !MI.isInlineAsm() && !ImmToIdxMap.count(OpC);
578
579   // Now add the frame object offset to the offset from r1.
580   int Offset = MFI->getObjectOffset(FrameIndex);
581   Offset += MI.getOperand(OffsetOperandNo).getImm();
582
583   // If we're not using a Frame Pointer that has been set to the value of the
584   // SP before having the stack size subtracted from it, then add the stack size
585   // to Offset to get the correct offset.
586   // Naked functions have stack size 0, although getStackSize may not reflect that
587   // because we didn't call all the pieces that compute it for naked functions.
588   if (!MF.getFunction()->getAttributes().
589         hasAttribute(AttributeSet::FunctionIndex, Attribute::Naked))
590     Offset += MFI->getStackSize();
591
592   // If we can, encode the offset directly into the instruction.  If this is a
593   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
594   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
595   // clear can be encoded.  This is extremely uncommon, because normally you
596   // only "std" to a stack slot that is at least 4-byte aligned, but it can
597   // happen in invalid code.
598   assert(OpC != PPC::DBG_VALUE &&
599          "This should be handle in a target independent way");
600   if (!noImmForm && isInt<16>(Offset) && (!isIXAddr || (Offset & 3) == 0)) {
601     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
602     return;
603   }
604
605   // The offset doesn't fit into a single register, scavenge one to build the
606   // offset in.
607
608   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
609   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
610   const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
611   unsigned SRegHi = MF.getRegInfo().createVirtualRegister(RC),
612            SReg = MF.getRegInfo().createVirtualRegister(RC);
613
614   // Insert a set of rA with the full offset value before the ld, st, or add
615   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
616     .addImm(Offset >> 16);
617   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
618     .addReg(SRegHi, RegState::Kill)
619     .addImm(Offset);
620
621   // Convert into indexed form of the instruction:
622   // 
623   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
624   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
625   unsigned OperandBase;
626
627   if (noImmForm)
628     OperandBase = 1;
629   else if (OpC != TargetOpcode::INLINEASM) {
630     assert(ImmToIdxMap.count(OpC) &&
631            "No indexed form of load or store available!");
632     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
633     MI.setDesc(TII.get(NewOpcode));
634     OperandBase = 1;
635   } else {
636     OperandBase = OffsetOperandNo;
637   }
638
639   unsigned StackReg = MI.getOperand(FIOperandNum).getReg();
640   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
641   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
642 }
643
644 unsigned PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
645   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
646
647   if (!Subtarget.isPPC64())
648     return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
649   else
650     return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
651 }
652
653 unsigned PPCRegisterInfo::getEHExceptionRegister() const {
654   return !Subtarget.isPPC64() ? PPC::R3 : PPC::X3;
655 }
656
657 unsigned PPCRegisterInfo::getEHHandlerRegister() const {
658   return !Subtarget.isPPC64() ? PPC::R4 : PPC::X4;
659 }
660
661 /// Returns true if the instruction's frame index
662 /// reference would be better served by a base register other than FP
663 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
664 /// references it should create new base registers for.
665 bool PPCRegisterInfo::
666 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
667   assert(Offset < 0 && "Local offset must be negative");
668
669   unsigned FIOperandNum = 0;
670   while (!MI->getOperand(FIOperandNum).isFI()) {
671     ++FIOperandNum;
672     assert(FIOperandNum < MI->getNumOperands() &&
673            "Instr doesn't have FrameIndex operand!");
674   }
675
676   unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
677   Offset += MI->getOperand(OffsetOperandNo).getImm();
678
679   // It's the load/store FI references that cause issues, as it can be difficult
680   // to materialize the offset if it won't fit in the literal field. Estimate
681   // based on the size of the local frame and some conservative assumptions
682   // about the rest of the stack frame (note, this is pre-regalloc, so
683   // we don't know everything for certain yet) whether this offset is likely
684   // to be out of range of the immediate. Return true if so.
685
686   // We only generate virtual base registers for loads and stores that have
687   // an r+i form. Return false for everything else.
688   unsigned OpC = MI->getOpcode();
689   if (!ImmToIdxMap.count(OpC))
690     return false;
691
692   // Don't generate a new virtual base register just to add zero to it.
693   if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
694       MI->getOperand(2).getImm() == 0)
695     return false;
696
697   MachineBasicBlock &MBB = *MI->getParent();
698   MachineFunction &MF = *MBB.getParent();
699
700   const PPCFrameLowering *PPCFI =
701     static_cast<const PPCFrameLowering*>(MF.getTarget().getFrameLowering());
702   unsigned StackEst =
703     PPCFI->determineFrameLayout(MF, false, true);
704
705   // If we likely don't need a stack frame, then we probably don't need a
706   // virtual base register either.
707   if (!StackEst)
708     return false;
709
710   // Estimate an offset from the stack pointer.
711   // The incoming offset is relating to the SP at the start of the function,
712   // but when we access the local it'll be relative to the SP after local
713   // allocation, so adjust our SP-relative offset by that allocation size.
714   Offset += StackEst;
715
716   // The frame pointer will point to the end of the stack, so estimate the
717   // offset as the difference between the object offset and the FP location.
718   return !isFrameOffsetLegal(MI, Offset);
719 }
720
721 /// Insert defining instruction(s) for BaseReg to
722 /// be a pointer to FrameIdx at the beginning of the basic block.
723 void PPCRegisterInfo::
724 materializeFrameBaseRegister(MachineBasicBlock *MBB,
725                              unsigned BaseReg, int FrameIdx,
726                              int64_t Offset) const {
727   unsigned ADDriOpc = Subtarget.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
728
729   MachineBasicBlock::iterator Ins = MBB->begin();
730   DebugLoc DL;                  // Defaults to "unknown"
731   if (Ins != MBB->end())
732     DL = Ins->getDebugLoc();
733
734   const MachineFunction &MF = *MBB->getParent();
735   const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
736   const MCInstrDesc &MCID = TII.get(ADDriOpc);
737   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
738   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
739
740   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
741     .addFrameIndex(FrameIdx).addImm(Offset);
742 }
743
744 void
745 PPCRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
746                                    unsigned BaseReg, int64_t Offset) const {
747   MachineInstr &MI = *I;
748
749   unsigned FIOperandNum = 0;
750   while (!MI.getOperand(FIOperandNum).isFI()) {
751     ++FIOperandNum;
752     assert(FIOperandNum < MI.getNumOperands() &&
753            "Instr doesn't have FrameIndex operand!");
754   }
755
756   MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
757   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
758   Offset += MI.getOperand(OffsetOperandNo).getImm();
759   MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
760 }
761
762 bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
763                                          int64_t Offset) const {
764   return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
765          (isInt<16>(Offset) && (!usesIXAddr(*MI) || (Offset & 3) == 0));
766 }
767