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