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