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