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