]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp
Merge ^/vendor/libc++/dist up to its last change, and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / lib / Target / PowerPC / PPCRegisterInfo.cpp
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;
751   unsigned CRBitSpillDistance = 0;
752   for (Ins = MI; Ins != MBB.rend(); Ins++) {
753     // Definition found.
754     if (Ins->modifiesRegister(SrcReg, TRI))
755       break;
756     // Unable to find CR bit definition within maximum search distance.
757     if (CRBitSpillDistance == MaxCRBitSpillDist) {
758       Ins = MI;
759       break;
760     }
761     // Skip debug instructions when counting CR bit spill distance.
762     if (!Ins->isDebugInstr())
763       CRBitSpillDistance++;
764   }
765
766   // Unable to find the definition of the CR bit in the MBB.
767   if (Ins == MBB.rend())
768     Ins = MI;
769
770   // There is no need to extract the CR bit if its value is already known.
771   switch (Ins->getOpcode()) {
772   case PPC::CRUNSET:
773     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LI8 : PPC::LI), Reg)
774       .addImm(0);
775     break;
776   case PPC::CRSET:
777     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LIS8 : PPC::LIS), Reg)
778       .addImm(-32768);
779     break;
780   default:
781     // We need to move the CR field that contains the CR bit we are spilling.
782     // The super register may not be explicitly defined (i.e. it can be defined
783     // by a CR-logical that only defines the subreg) so we state that the CR
784     // field is undef. Also, in order to preserve the kill flag on the CR bit,
785     // we add it as an implicit use.
786     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
787       .addReg(getCRFromCRBit(SrcReg), RegState::Undef)
788       .addReg(SrcReg,
789               RegState::Implicit | getKillRegState(MI.getOperand(0).isKill()));
790
791     // If the saved register wasn't CR0LT, shift the bits left so that the bit
792     // to store is the first one. Mask all but that bit.
793     unsigned Reg1 = Reg;
794     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
795
796     // rlwinm rA, rA, ShiftBits, 0, 0.
797     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
798       .addReg(Reg1, RegState::Kill)
799       .addImm(getEncodingValue(SrcReg))
800       .addImm(0).addImm(0);
801   }
802   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
803                     .addReg(Reg, RegState::Kill),
804                     FrameIndex);
805
806   // Discard the pseudo instruction.
807   MBB.erase(II);
808 }
809
810 void PPCRegisterInfo::lowerCRBitRestore(MachineBasicBlock::iterator II,
811                                       unsigned FrameIndex) const {
812   // Get the instruction.
813   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CRBIT <offset>
814   // Get the instruction's basic block.
815   MachineBasicBlock &MBB = *MI.getParent();
816   MachineFunction &MF = *MBB.getParent();
817   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
818   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
819   DebugLoc dl = MI.getDebugLoc();
820
821   bool LP64 = TM.isPPC64();
822   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
823   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
824
825   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
826   Register DestReg = MI.getOperand(0).getReg();
827   assert(MI.definesRegister(DestReg) &&
828     "RESTORE_CRBIT does not define its destination");
829
830   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
831                               Reg), FrameIndex);
832
833   BuildMI(MBB, II, dl, TII.get(TargetOpcode::IMPLICIT_DEF), DestReg);
834
835   Register RegO = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
836   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), RegO)
837           .addReg(getCRFromCRBit(DestReg));
838
839   unsigned ShiftBits = getEncodingValue(DestReg);
840   // rlwimi r11, r10, 32-ShiftBits, ..., ...
841   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWIMI8 : PPC::RLWIMI), RegO)
842       .addReg(RegO, RegState::Kill)
843       .addReg(Reg, RegState::Kill)
844       .addImm(ShiftBits ? 32 - ShiftBits : 0)
845       .addImm(ShiftBits)
846       .addImm(ShiftBits);
847
848   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF),
849           getCRFromCRBit(DestReg))
850       .addReg(RegO, RegState::Kill)
851       // Make sure we have a use dependency all the way through this
852       // sequence of instructions. We can't have the other bits in the CR
853       // modified in between the mfocrf and the mtocrf.
854       .addReg(getCRFromCRBit(DestReg), RegState::Implicit);
855
856   // Discard the pseudo instruction.
857   MBB.erase(II);
858 }
859
860 void PPCRegisterInfo::lowerVRSAVESpilling(MachineBasicBlock::iterator II,
861                                           unsigned FrameIndex) const {
862   // Get the instruction.
863   MachineInstr &MI = *II;       // ; SPILL_VRSAVE <SrcReg>, <offset>
864   // Get the instruction's basic block.
865   MachineBasicBlock &MBB = *MI.getParent();
866   MachineFunction &MF = *MBB.getParent();
867   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
868   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
869   DebugLoc dl = MI.getDebugLoc();
870
871   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
872   Register Reg = MF.getRegInfo().createVirtualRegister(GPRC);
873   Register SrcReg = MI.getOperand(0).getReg();
874
875   BuildMI(MBB, II, dl, TII.get(PPC::MFVRSAVEv), Reg)
876       .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
877
878   addFrameReference(
879       BuildMI(MBB, II, dl, TII.get(PPC::STW)).addReg(Reg, RegState::Kill),
880       FrameIndex);
881
882   // Discard the pseudo instruction.
883   MBB.erase(II);
884 }
885
886 void PPCRegisterInfo::lowerVRSAVERestore(MachineBasicBlock::iterator II,
887                                          unsigned FrameIndex) const {
888   // Get the instruction.
889   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_VRSAVE <offset>
890   // Get the instruction's basic block.
891   MachineBasicBlock &MBB = *MI.getParent();
892   MachineFunction &MF = *MBB.getParent();
893   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
894   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
895   DebugLoc dl = MI.getDebugLoc();
896
897   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
898   Register Reg = MF.getRegInfo().createVirtualRegister(GPRC);
899   Register DestReg = MI.getOperand(0).getReg();
900   assert(MI.definesRegister(DestReg) &&
901     "RESTORE_VRSAVE does not define its destination");
902
903   addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::LWZ),
904                               Reg), FrameIndex);
905
906   BuildMI(MBB, II, dl, TII.get(PPC::MTVRSAVEv), DestReg)
907              .addReg(Reg, RegState::Kill);
908
909   // Discard the pseudo instruction.
910   MBB.erase(II);
911 }
912
913 bool PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
914                                            unsigned Reg, int &FrameIdx) const {
915   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
916   // For the nonvolatile condition registers (CR2, CR3, CR4) in an SVR4
917   // ABI, return true to prevent allocating an additional frame slot.
918   // For 64-bit, the CR save area is at SP+8; the value of FrameIdx = 0
919   // is arbitrary and will be subsequently ignored.  For 32-bit, we have
920   // previously created the stack slot if needed, so return its FrameIdx.
921   if (Subtarget.isSVR4ABI() && PPC::CR2 <= Reg && Reg <= PPC::CR4) {
922     if (TM.isPPC64())
923       FrameIdx = 0;
924     else {
925       const PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
926       FrameIdx = FI->getCRSpillFrameIndex();
927     }
928     return true;
929   }
930   return false;
931 }
932
933 // If the offset must be a multiple of some value, return what that value is.
934 static unsigned offsetMinAlignForOpcode(unsigned OpC) {
935   switch (OpC) {
936   default:
937     return 1;
938   case PPC::LWA:
939   case PPC::LWA_32:
940   case PPC::LD:
941   case PPC::LDU:
942   case PPC::STD:
943   case PPC::STDU:
944   case PPC::DFLOADf32:
945   case PPC::DFLOADf64:
946   case PPC::DFSTOREf32:
947   case PPC::DFSTOREf64:
948   case PPC::LXSD:
949   case PPC::LXSSP:
950   case PPC::STXSD:
951   case PPC::STXSSP:
952     return 4;
953   case PPC::EVLDD:
954   case PPC::EVSTDD:
955     return 8;
956   case PPC::LXV:
957   case PPC::STXV:
958     return 16;
959   }
960 }
961
962 // If the offset must be a multiple of some value, return what that value is.
963 static unsigned offsetMinAlign(const MachineInstr &MI) {
964   unsigned OpC = MI.getOpcode();
965   return offsetMinAlignForOpcode(OpC);
966 }
967
968 // Return the OffsetOperandNo given the FIOperandNum (and the instruction).
969 static unsigned getOffsetONFromFION(const MachineInstr &MI,
970                                     unsigned FIOperandNum) {
971   // Take into account whether it's an add or mem instruction
972   unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
973   if (MI.isInlineAsm())
974     OffsetOperandNo = FIOperandNum - 1;
975   else if (MI.getOpcode() == TargetOpcode::STACKMAP ||
976            MI.getOpcode() == TargetOpcode::PATCHPOINT)
977     OffsetOperandNo = FIOperandNum + 1;
978
979   return OffsetOperandNo;
980 }
981
982 void
983 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
984                                      int SPAdj, unsigned FIOperandNum,
985                                      RegScavenger *RS) const {
986   assert(SPAdj == 0 && "Unexpected");
987
988   // Get the instruction.
989   MachineInstr &MI = *II;
990   // Get the instruction's basic block.
991   MachineBasicBlock &MBB = *MI.getParent();
992   // Get the basic block's function.
993   MachineFunction &MF = *MBB.getParent();
994   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
995   // Get the instruction info.
996   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
997   // Get the frame info.
998   MachineFrameInfo &MFI = MF.getFrameInfo();
999   DebugLoc dl = MI.getDebugLoc();
1000
1001   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1002
1003   // Get the frame index.
1004   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
1005
1006   // Get the frame pointer save index.  Users of this index are primarily
1007   // DYNALLOC instructions.
1008   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1009   int FPSI = FI->getFramePointerSaveIndex();
1010   // Get the instruction opcode.
1011   unsigned OpC = MI.getOpcode();
1012
1013   if ((OpC == PPC::DYNAREAOFFSET || OpC == PPC::DYNAREAOFFSET8)) {
1014     lowerDynamicAreaOffset(II);
1015     return;
1016   }
1017
1018   // Special case for dynamic alloca.
1019   if (FPSI && FrameIndex == FPSI &&
1020       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
1021     lowerDynamicAlloc(II);
1022     return;
1023   }
1024
1025   // Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
1026   if (OpC == PPC::SPILL_CR) {
1027     lowerCRSpilling(II, FrameIndex);
1028     return;
1029   } else if (OpC == PPC::RESTORE_CR) {
1030     lowerCRRestore(II, FrameIndex);
1031     return;
1032   } else if (OpC == PPC::SPILL_CRBIT) {
1033     lowerCRBitSpilling(II, FrameIndex);
1034     return;
1035   } else if (OpC == PPC::RESTORE_CRBIT) {
1036     lowerCRBitRestore(II, FrameIndex);
1037     return;
1038   } else if (OpC == PPC::SPILL_VRSAVE) {
1039     lowerVRSAVESpilling(II, FrameIndex);
1040     return;
1041   } else if (OpC == PPC::RESTORE_VRSAVE) {
1042     lowerVRSAVERestore(II, FrameIndex);
1043     return;
1044   }
1045
1046   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
1047   MI.getOperand(FIOperandNum).ChangeToRegister(
1048     FrameIndex < 0 ? getBaseRegister(MF) : getFrameRegister(MF), false);
1049
1050   // If the instruction is not present in ImmToIdxMap, then it has no immediate
1051   // form (and must be r+r).
1052   bool noImmForm = !MI.isInlineAsm() && OpC != TargetOpcode::STACKMAP &&
1053                    OpC != TargetOpcode::PATCHPOINT && !ImmToIdxMap.count(OpC);
1054
1055   // Now add the frame object offset to the offset from r1.
1056   int Offset = MFI.getObjectOffset(FrameIndex);
1057   Offset += MI.getOperand(OffsetOperandNo).getImm();
1058
1059   // If we're not using a Frame Pointer that has been set to the value of the
1060   // SP before having the stack size subtracted from it, then add the stack size
1061   // to Offset to get the correct offset.
1062   // Naked functions have stack size 0, although getStackSize may not reflect
1063   // that because we didn't call all the pieces that compute it for naked
1064   // functions.
1065   if (!MF.getFunction().hasFnAttribute(Attribute::Naked)) {
1066     if (!(hasBasePointer(MF) && FrameIndex < 0))
1067       Offset += MFI.getStackSize();
1068   }
1069
1070   // If we can, encode the offset directly into the instruction.  If this is a
1071   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
1072   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
1073   // clear can be encoded.  This is extremely uncommon, because normally you
1074   // only "std" to a stack slot that is at least 4-byte aligned, but it can
1075   // happen in invalid code.
1076   assert(OpC != PPC::DBG_VALUE &&
1077          "This should be handled in a target-independent way");
1078   bool OffsetFitsMnemonic = (OpC == PPC::EVSTDD || OpC == PPC::EVLDD) ?
1079                             isUInt<8>(Offset) :
1080                             isInt<16>(Offset);
1081   if (!noImmForm && ((OffsetFitsMnemonic &&
1082                       ((Offset % offsetMinAlign(MI)) == 0)) ||
1083                      OpC == TargetOpcode::STACKMAP ||
1084                      OpC == TargetOpcode::PATCHPOINT)) {
1085     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1086     return;
1087   }
1088
1089   // The offset doesn't fit into a single register, scavenge one to build the
1090   // offset in.
1091
1092   bool is64Bit = TM.isPPC64();
1093   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1094   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1095   const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
1096   unsigned SRegHi = MF.getRegInfo().createVirtualRegister(RC),
1097            SReg = MF.getRegInfo().createVirtualRegister(RC);
1098
1099   // Insert a set of rA with the full offset value before the ld, st, or add
1100   if (isInt<16>(Offset))
1101     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI), SReg)
1102       .addImm(Offset);
1103   else {
1104     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
1105       .addImm(Offset >> 16);
1106     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
1107       .addReg(SRegHi, RegState::Kill)
1108       .addImm(Offset);
1109   }
1110
1111   // Convert into indexed form of the instruction:
1112   //
1113   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
1114   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
1115   unsigned OperandBase;
1116
1117   if (noImmForm)
1118     OperandBase = 1;
1119   else if (OpC != TargetOpcode::INLINEASM &&
1120            OpC != TargetOpcode::INLINEASM_BR) {
1121     assert(ImmToIdxMap.count(OpC) &&
1122            "No indexed form of load or store available!");
1123     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
1124     MI.setDesc(TII.get(NewOpcode));
1125     OperandBase = 1;
1126   } else {
1127     OperandBase = OffsetOperandNo;
1128   }
1129
1130   Register StackReg = MI.getOperand(FIOperandNum).getReg();
1131   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
1132   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
1133 }
1134
1135 Register PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
1136   const PPCFrameLowering *TFI = getFrameLowering(MF);
1137
1138   if (!TM.isPPC64())
1139     return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
1140   else
1141     return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
1142 }
1143
1144 Register PPCRegisterInfo::getBaseRegister(const MachineFunction &MF) const {
1145   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1146   if (!hasBasePointer(MF))
1147     return getFrameRegister(MF);
1148
1149   if (TM.isPPC64())
1150     return PPC::X30;
1151
1152   if (Subtarget.isSVR4ABI() && TM.isPositionIndependent())
1153     return PPC::R29;
1154
1155   return PPC::R30;
1156 }
1157
1158 bool PPCRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
1159   if (!EnableBasePointer)
1160     return false;
1161   if (AlwaysBasePointer)
1162     return true;
1163
1164   // If we need to realign the stack, then the stack pointer can no longer
1165   // serve as an offset into the caller's stack space. As a result, we need a
1166   // base pointer.
1167   return needsStackRealignment(MF);
1168 }
1169
1170 /// Returns true if the instruction's frame index
1171 /// reference would be better served by a base register other than FP
1172 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
1173 /// references it should create new base registers for.
1174 bool PPCRegisterInfo::
1175 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
1176   assert(Offset < 0 && "Local offset must be negative");
1177
1178   // It's the load/store FI references that cause issues, as it can be difficult
1179   // to materialize the offset if it won't fit in the literal field. Estimate
1180   // based on the size of the local frame and some conservative assumptions
1181   // about the rest of the stack frame (note, this is pre-regalloc, so
1182   // we don't know everything for certain yet) whether this offset is likely
1183   // to be out of range of the immediate. Return true if so.
1184
1185   // We only generate virtual base registers for loads and stores that have
1186   // an r+i form. Return false for everything else.
1187   unsigned OpC = MI->getOpcode();
1188   if (!ImmToIdxMap.count(OpC))
1189     return false;
1190
1191   // Don't generate a new virtual base register just to add zero to it.
1192   if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
1193       MI->getOperand(2).getImm() == 0)
1194     return false;
1195
1196   MachineBasicBlock &MBB = *MI->getParent();
1197   MachineFunction &MF = *MBB.getParent();
1198   const PPCFrameLowering *TFI = getFrameLowering(MF);
1199   unsigned StackEst = TFI->determineFrameLayout(MF, true);
1200
1201   // If we likely don't need a stack frame, then we probably don't need a
1202   // virtual base register either.
1203   if (!StackEst)
1204     return false;
1205
1206   // Estimate an offset from the stack pointer.
1207   // The incoming offset is relating to the SP at the start of the function,
1208   // but when we access the local it'll be relative to the SP after local
1209   // allocation, so adjust our SP-relative offset by that allocation size.
1210   Offset += StackEst;
1211
1212   // The frame pointer will point to the end of the stack, so estimate the
1213   // offset as the difference between the object offset and the FP location.
1214   return !isFrameOffsetLegal(MI, getBaseRegister(MF), Offset);
1215 }
1216
1217 /// Insert defining instruction(s) for BaseReg to
1218 /// be a pointer to FrameIdx at the beginning of the basic block.
1219 void PPCRegisterInfo::
1220 materializeFrameBaseRegister(MachineBasicBlock *MBB,
1221                              unsigned BaseReg, int FrameIdx,
1222                              int64_t Offset) const {
1223   unsigned ADDriOpc = TM.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
1224
1225   MachineBasicBlock::iterator Ins = MBB->begin();
1226   DebugLoc DL;                  // Defaults to "unknown"
1227   if (Ins != MBB->end())
1228     DL = Ins->getDebugLoc();
1229
1230   const MachineFunction &MF = *MBB->getParent();
1231   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1232   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1233   const MCInstrDesc &MCID = TII.get(ADDriOpc);
1234   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1235   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
1236
1237   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
1238     .addFrameIndex(FrameIdx).addImm(Offset);
1239 }
1240
1241 void PPCRegisterInfo::resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
1242                                         int64_t Offset) const {
1243   unsigned FIOperandNum = 0;
1244   while (!MI.getOperand(FIOperandNum).isFI()) {
1245     ++FIOperandNum;
1246     assert(FIOperandNum < MI.getNumOperands() &&
1247            "Instr doesn't have FrameIndex operand!");
1248   }
1249
1250   MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
1251   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1252   Offset += MI.getOperand(OffsetOperandNo).getImm();
1253   MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1254
1255   MachineBasicBlock &MBB = *MI.getParent();
1256   MachineFunction &MF = *MBB.getParent();
1257   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1258   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1259   const MCInstrDesc &MCID = MI.getDesc();
1260   MachineRegisterInfo &MRI = MF.getRegInfo();
1261   MRI.constrainRegClass(BaseReg,
1262                         TII.getRegClass(MCID, FIOperandNum, this, MF));
1263 }
1264
1265 bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
1266                                          unsigned BaseReg,
1267                                          int64_t Offset) const {
1268   unsigned FIOperandNum = 0;
1269   while (!MI->getOperand(FIOperandNum).isFI()) {
1270     ++FIOperandNum;
1271     assert(FIOperandNum < MI->getNumOperands() &&
1272            "Instr doesn't have FrameIndex operand!");
1273   }
1274
1275   unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
1276   Offset += MI->getOperand(OffsetOperandNo).getImm();
1277
1278   return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
1279          MI->getOpcode() == TargetOpcode::STACKMAP ||
1280          MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1281          (isInt<16>(Offset) && (Offset % offsetMinAlign(*MI)) == 0);
1282 }