xref: /llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp (revision fedc59734a44ef7b62c5f389b0cdffd02264b2a9)
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/CodeGen/VirtRegMap.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Type.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include <cstdlib>
44 
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "reginfo"
48 
49 #define GET_REGINFO_TARGET_DESC
50 #include "PPCGenRegisterInfo.inc"
51 
52 STATISTIC(InflateGPRC, "Number of gprc inputs for getLargestLegalClass");
53 STATISTIC(InflateGP8RC, "Number of g8rc inputs for getLargestLegalClass");
54 
55 static cl::opt<bool>
56 EnableBasePointer("ppc-use-base-pointer", cl::Hidden, cl::init(true),
57          cl::desc("Enable use of a base pointer for complex stack frames"));
58 
59 static cl::opt<bool>
60 AlwaysBasePointer("ppc-always-use-base-pointer", cl::Hidden, cl::init(false),
61          cl::desc("Force the use of a base pointer in every function"));
62 
63 static cl::opt<bool>
64 EnableGPRToVecSpills("ppc-enable-gpr-to-vsr-spills", cl::Hidden, cl::init(false),
65          cl::desc("Enable spills from gpr to vsr rather than stack"));
66 
67 static cl::opt<bool>
68 StackPtrConst("ppc-stack-ptr-caller-preserved",
69                 cl::desc("Consider R1 caller preserved so stack saves of "
70                          "caller preserved registers can be LICM candidates"),
71                 cl::init(true), cl::Hidden);
72 
73 static cl::opt<unsigned>
74 MaxCRBitSpillDist("ppc-max-crbit-spill-dist",
75                   cl::desc("Maximum search distance for definition of CR bit "
76                            "spill on ppc"),
77                   cl::Hidden, cl::init(100));
78 
79 // Copies/moves of physical accumulators are expensive operations
80 // that should be avoided whenever possible. MMA instructions are
81 // meant to be used in performance-sensitive computational kernels.
82 // This option is provided, at least for the time being, to give the
83 // user a tool to detect this expensive operation and either rework
84 // their code or report a compiler bug if that turns out to be the
85 // cause.
86 #ifndef NDEBUG
87 static cl::opt<bool>
88 ReportAccMoves("ppc-report-acc-moves",
89                cl::desc("Emit information about accumulator register spills "
90                         "and copies"),
91                cl::Hidden, cl::init(false));
92 #endif
93 
94 extern cl::opt<bool> DisableAutoPairedVecSt;
95 
96 static unsigned offsetMinAlignForOpcode(unsigned OpC);
97 
98 PPCRegisterInfo::PPCRegisterInfo(const PPCTargetMachine &TM)
99   : PPCGenRegisterInfo(TM.isPPC64() ? PPC::LR8 : PPC::LR,
100                        TM.isPPC64() ? 0 : 1,
101                        TM.isPPC64() ? 0 : 1),
102     TM(TM) {
103   ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
104   ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
105   ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
106   ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
107   ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
108   ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
109   ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
110   ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
111   ImmToIdxMap[PPC::LWA_32] = PPC::LWAX_32;
112 
113   // 64-bit
114   ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
115   ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
116   ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
117   ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
118   ImmToIdxMap[PPC::ADDI8] = PPC::ADD8;
119   ImmToIdxMap[PPC::LQ] = PPC::LQX_PSEUDO;
120   ImmToIdxMap[PPC::STQ] = PPC::STQX_PSEUDO;
121 
122   // VSX
123   ImmToIdxMap[PPC::DFLOADf32] = PPC::LXSSPX;
124   ImmToIdxMap[PPC::DFLOADf64] = PPC::LXSDX;
125   ImmToIdxMap[PPC::SPILLTOVSR_LD] = PPC::SPILLTOVSR_LDX;
126   ImmToIdxMap[PPC::SPILLTOVSR_ST] = PPC::SPILLTOVSR_STX;
127   ImmToIdxMap[PPC::DFSTOREf32] = PPC::STXSSPX;
128   ImmToIdxMap[PPC::DFSTOREf64] = PPC::STXSDX;
129   ImmToIdxMap[PPC::LXV] = PPC::LXVX;
130   ImmToIdxMap[PPC::LXSD] = PPC::LXSDX;
131   ImmToIdxMap[PPC::LXSSP] = PPC::LXSSPX;
132   ImmToIdxMap[PPC::STXV] = PPC::STXVX;
133   ImmToIdxMap[PPC::STXSD] = PPC::STXSDX;
134   ImmToIdxMap[PPC::STXSSP] = PPC::STXSSPX;
135 
136   // SPE
137   ImmToIdxMap[PPC::EVLDD] = PPC::EVLDDX;
138   ImmToIdxMap[PPC::EVSTDD] = PPC::EVSTDDX;
139   ImmToIdxMap[PPC::SPESTW] = PPC::SPESTWX;
140   ImmToIdxMap[PPC::SPELWZ] = PPC::SPELWZX;
141 
142   // Power10
143   ImmToIdxMap[PPC::PLBZ]   = PPC::LBZX; ImmToIdxMap[PPC::PLBZ8]   = PPC::LBZX8;
144   ImmToIdxMap[PPC::PLHZ]   = PPC::LHZX; ImmToIdxMap[PPC::PLHZ8]   = PPC::LHZX8;
145   ImmToIdxMap[PPC::PLHA]   = PPC::LHAX; ImmToIdxMap[PPC::PLHA8]   = PPC::LHAX8;
146   ImmToIdxMap[PPC::PLWZ]   = PPC::LWZX; ImmToIdxMap[PPC::PLWZ8]   = PPC::LWZX8;
147   ImmToIdxMap[PPC::PLWA]   = PPC::LWAX; ImmToIdxMap[PPC::PLWA8]   = PPC::LWAX;
148   ImmToIdxMap[PPC::PLD]    = PPC::LDX;  ImmToIdxMap[PPC::PSTD]   = PPC::STDX;
149 
150   ImmToIdxMap[PPC::PSTB]   = PPC::STBX; ImmToIdxMap[PPC::PSTB8]   = PPC::STBX8;
151   ImmToIdxMap[PPC::PSTH]   = PPC::STHX; ImmToIdxMap[PPC::PSTH8]   = PPC::STHX8;
152   ImmToIdxMap[PPC::PSTW]   = PPC::STWX; ImmToIdxMap[PPC::PSTW8]   = PPC::STWX8;
153 
154   ImmToIdxMap[PPC::PLFS]   = PPC::LFSX; ImmToIdxMap[PPC::PSTFS]   = PPC::STFSX;
155   ImmToIdxMap[PPC::PLFD]   = PPC::LFDX; ImmToIdxMap[PPC::PSTFD]   = PPC::STFDX;
156   ImmToIdxMap[PPC::PLXSSP] = PPC::LXSSPX; ImmToIdxMap[PPC::PSTXSSP] = PPC::STXSSPX;
157   ImmToIdxMap[PPC::PLXSD]  = PPC::LXSDX; ImmToIdxMap[PPC::PSTXSD]  = PPC::STXSDX;
158   ImmToIdxMap[PPC::PLXV]   = PPC::LXVX; ImmToIdxMap[PPC::PSTXV]  = PPC::STXVX;
159 
160   ImmToIdxMap[PPC::LXVP]   = PPC::LXVPX;
161   ImmToIdxMap[PPC::STXVP]  = PPC::STXVPX;
162   ImmToIdxMap[PPC::PLXVP]  = PPC::LXVPX;
163   ImmToIdxMap[PPC::PSTXVP] = PPC::STXVPX;
164 }
165 
166 /// getPointerRegClass - Return the register class to use to hold pointers.
167 /// This is used for addressing modes.
168 const TargetRegisterClass *
169 PPCRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
170                                                                        const {
171   // Note that PPCInstrInfo::FoldImmediate also directly uses this Kind value
172   // when it checks for ZERO folding.
173   if (Kind == 1) {
174     if (TM.isPPC64())
175       return &PPC::G8RC_NOX0RegClass;
176     return &PPC::GPRC_NOR0RegClass;
177   }
178 
179   if (TM.isPPC64())
180     return &PPC::G8RCRegClass;
181   return &PPC::GPRCRegClass;
182 }
183 
184 const MCPhysReg*
185 PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
186   const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>();
187   if (MF->getFunction().getCallingConv() == CallingConv::AnyReg) {
188     if (!TM.isPPC64() && Subtarget.isAIXABI())
189       report_fatal_error("AnyReg unimplemented on 32-bit AIX.");
190     if (Subtarget.hasVSX()) {
191       if (Subtarget.pairedVectorMemops())
192         return CSR_64_AllRegs_VSRP_SaveList;
193       if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI())
194         return CSR_64_AllRegs_AIX_Dflt_VSX_SaveList;
195       return CSR_64_AllRegs_VSX_SaveList;
196     }
197     if (Subtarget.hasAltivec()) {
198       if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI())
199         return CSR_64_AllRegs_AIX_Dflt_Altivec_SaveList;
200       return CSR_64_AllRegs_Altivec_SaveList;
201     }
202     return CSR_64_AllRegs_SaveList;
203   }
204 
205   // On PPC64, we might need to save r2 (but only if it is not reserved).
206   // We do not need to treat R2 as callee-saved when using PC-Relative calls
207   // because any direct uses of R2 will cause it to be reserved. If the function
208   // is a leaf or the only uses of R2 are implicit uses for calls, the calls
209   // will use the @notoc relocation which will cause this function to set the
210   // st_other bit to 1, thereby communicating to its caller that it arbitrarily
211   // clobbers the TOC.
212   bool SaveR2 = MF->getRegInfo().isAllocatable(PPC::X2) &&
213                 !Subtarget.isUsingPCRelativeCalls();
214 
215   // Cold calling convention CSRs.
216   if (MF->getFunction().getCallingConv() == CallingConv::Cold) {
217     if (Subtarget.isAIXABI())
218       report_fatal_error("Cold calling unimplemented on AIX.");
219     if (TM.isPPC64()) {
220       if (Subtarget.pairedVectorMemops())
221         return SaveR2 ? CSR_SVR64_ColdCC_R2_VSRP_SaveList
222                       : CSR_SVR64_ColdCC_VSRP_SaveList;
223       if (Subtarget.hasAltivec())
224         return SaveR2 ? CSR_SVR64_ColdCC_R2_Altivec_SaveList
225                       : CSR_SVR64_ColdCC_Altivec_SaveList;
226       return SaveR2 ? CSR_SVR64_ColdCC_R2_SaveList
227                     : CSR_SVR64_ColdCC_SaveList;
228     }
229     // 32-bit targets.
230     if (Subtarget.pairedVectorMemops())
231       return CSR_SVR32_ColdCC_VSRP_SaveList;
232     else if (Subtarget.hasAltivec())
233       return CSR_SVR32_ColdCC_Altivec_SaveList;
234     else if (Subtarget.hasSPE())
235       return CSR_SVR32_ColdCC_SPE_SaveList;
236     return CSR_SVR32_ColdCC_SaveList;
237   }
238   // Standard calling convention CSRs.
239   if (TM.isPPC64()) {
240     if (Subtarget.pairedVectorMemops())
241       return SaveR2 ? CSR_SVR464_R2_VSRP_SaveList : CSR_SVR464_VSRP_SaveList;
242     if (Subtarget.hasAltivec() &&
243         (!Subtarget.isAIXABI() || TM.getAIXExtendedAltivecABI())) {
244       return SaveR2 ? CSR_PPC64_R2_Altivec_SaveList
245                     : CSR_PPC64_Altivec_SaveList;
246     }
247     return SaveR2 ? CSR_PPC64_R2_SaveList : CSR_PPC64_SaveList;
248   }
249   // 32-bit targets.
250   if (Subtarget.isAIXABI()) {
251     if (Subtarget.hasAltivec())
252       return TM.getAIXExtendedAltivecABI() ? CSR_AIX32_Altivec_SaveList
253                                            : CSR_AIX32_SaveList;
254     return CSR_AIX32_SaveList;
255   }
256   if (Subtarget.pairedVectorMemops())
257     return CSR_SVR432_VSRP_SaveList;
258   if (Subtarget.hasAltivec())
259     return CSR_SVR432_Altivec_SaveList;
260   else if (Subtarget.hasSPE()) {
261     if (TM.isPositionIndependent() && !TM.isPPC64())
262       return CSR_SVR432_SPE_NO_S30_31_SaveList;
263     return CSR_SVR432_SPE_SaveList;
264    }
265   return CSR_SVR432_SaveList;
266 }
267 
268 const uint32_t *
269 PPCRegisterInfo::getCallPreservedMask(const MachineFunction &MF,
270                                       CallingConv::ID CC) const {
271   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
272   if (CC == CallingConv::AnyReg) {
273     if (Subtarget.hasVSX()) {
274       if (Subtarget.pairedVectorMemops())
275         return CSR_64_AllRegs_VSRP_RegMask;
276       if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI())
277         return CSR_64_AllRegs_AIX_Dflt_VSX_RegMask;
278       return CSR_64_AllRegs_VSX_RegMask;
279     }
280     if (Subtarget.hasAltivec()) {
281       if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI())
282         return CSR_64_AllRegs_AIX_Dflt_Altivec_RegMask;
283       return CSR_64_AllRegs_Altivec_RegMask;
284     }
285     return CSR_64_AllRegs_RegMask;
286   }
287 
288   if (Subtarget.isAIXABI()) {
289     return TM.isPPC64()
290                ? ((Subtarget.hasAltivec() && TM.getAIXExtendedAltivecABI())
291                       ? CSR_PPC64_Altivec_RegMask
292                       : CSR_PPC64_RegMask)
293                : ((Subtarget.hasAltivec() && TM.getAIXExtendedAltivecABI())
294                       ? CSR_AIX32_Altivec_RegMask
295                       : CSR_AIX32_RegMask);
296   }
297 
298   if (CC == CallingConv::Cold) {
299     if (TM.isPPC64())
300       return Subtarget.pairedVectorMemops()
301                  ? CSR_SVR64_ColdCC_VSRP_RegMask
302                  : (Subtarget.hasAltivec() ? CSR_SVR64_ColdCC_Altivec_RegMask
303                                            : CSR_SVR64_ColdCC_RegMask);
304     else
305       return Subtarget.pairedVectorMemops()
306                  ? CSR_SVR32_ColdCC_VSRP_RegMask
307                  : (Subtarget.hasAltivec()
308                         ? CSR_SVR32_ColdCC_Altivec_RegMask
309                         : (Subtarget.hasSPE() ? CSR_SVR32_ColdCC_SPE_RegMask
310                                               : CSR_SVR32_ColdCC_RegMask));
311   }
312 
313   if (TM.isPPC64())
314     return Subtarget.pairedVectorMemops()
315                ? CSR_SVR464_VSRP_RegMask
316                : (Subtarget.hasAltivec() ? CSR_PPC64_Altivec_RegMask
317                                          : CSR_PPC64_RegMask);
318   else
319     return Subtarget.pairedVectorMemops()
320                ? CSR_SVR432_VSRP_RegMask
321                : (Subtarget.hasAltivec()
322                       ? CSR_SVR432_Altivec_RegMask
323                       : (Subtarget.hasSPE()
324                              ? (TM.isPositionIndependent()
325                                      ? CSR_SVR432_SPE_NO_S30_31_RegMask
326                                      : CSR_SVR432_SPE_RegMask)
327                              : CSR_SVR432_RegMask));
328 }
329 
330 const uint32_t*
331 PPCRegisterInfo::getNoPreservedMask() const {
332   return CSR_NoRegs_RegMask;
333 }
334 
335 void PPCRegisterInfo::adjustStackMapLiveOutMask(uint32_t *Mask) const {
336   for (unsigned PseudoReg : {PPC::ZERO, PPC::ZERO8, PPC::RM})
337     Mask[PseudoReg / 32] &= ~(1u << (PseudoReg % 32));
338 }
339 
340 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
341   BitVector Reserved(getNumRegs());
342   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
343   const PPCFrameLowering *TFI = getFrameLowering(MF);
344 
345   // The ZERO register is not really a register, but the representation of r0
346   // when used in instructions that treat r0 as the constant 0.
347   markSuperRegs(Reserved, PPC::ZERO);
348 
349   // The FP register is also not really a register, but is the representation
350   // of the frame pointer register used by ISD::FRAMEADDR.
351   markSuperRegs(Reserved, PPC::FP);
352 
353   // The BP register is also not really a register, but is the representation
354   // of the base pointer register used by setjmp.
355   markSuperRegs(Reserved, PPC::BP);
356 
357   // The counter registers must be reserved so that counter-based loops can
358   // be correctly formed (and the mtctr instructions are not DCE'd).
359   markSuperRegs(Reserved, PPC::CTR);
360   markSuperRegs(Reserved, PPC::CTR8);
361 
362   markSuperRegs(Reserved, PPC::R1);
363   markSuperRegs(Reserved, PPC::LR);
364   markSuperRegs(Reserved, PPC::LR8);
365   markSuperRegs(Reserved, PPC::RM);
366 
367   markSuperRegs(Reserved, PPC::VRSAVE);
368 
369   // The SVR4 ABI reserves r2 and r13
370   if (Subtarget.isSVR4ABI()) {
371     // We only reserve r2 if we need to use the TOC pointer. If we have no
372     // explicit uses of the TOC pointer (meaning we're a leaf function with
373     // no constant-pool loads, etc.) and we have no potential uses inside an
374     // inline asm block, then we can treat r2 has an ordinary callee-saved
375     // register.
376     const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
377     if (!TM.isPPC64() || FuncInfo->usesTOCBasePtr() || MF.hasInlineAsm())
378       markSuperRegs(Reserved, PPC::R2);  // System-reserved register
379     markSuperRegs(Reserved, PPC::R13); // Small Data Area pointer register
380   }
381 
382   // Always reserve r2 on AIX for now.
383   // TODO: Make r2 allocatable on AIX/XCOFF for some leaf functions.
384   if (Subtarget.isAIXABI())
385     markSuperRegs(Reserved, PPC::R2);  // System-reserved register
386 
387   // On PPC64, r13 is the thread pointer. Never allocate this register.
388   if (TM.isPPC64())
389     markSuperRegs(Reserved, PPC::R13);
390 
391   if (TFI->needsFP(MF))
392     markSuperRegs(Reserved, PPC::R31);
393 
394   bool IsPositionIndependent = TM.isPositionIndependent();
395   if (hasBasePointer(MF)) {
396     if (Subtarget.is32BitELFABI() && IsPositionIndependent)
397       markSuperRegs(Reserved, PPC::R29);
398     else
399       markSuperRegs(Reserved, PPC::R30);
400   }
401 
402   if (Subtarget.is32BitELFABI() && IsPositionIndependent)
403     markSuperRegs(Reserved, PPC::R30);
404 
405   // Reserve Altivec registers when Altivec is unavailable.
406   if (!Subtarget.hasAltivec())
407     for (MCRegister Reg : PPC::VRRCRegClass)
408       markSuperRegs(Reserved, Reg);
409 
410   if (Subtarget.isAIXABI() && Subtarget.hasAltivec() &&
411       !TM.getAIXExtendedAltivecABI()) {
412     //  In the AIX default Altivec ABI, vector registers VR20-VR31 are reserved
413     //  and cannot be used.
414     for (auto Reg : CSR_Altivec_SaveList) {
415       if (Reg == 0)
416         break;
417       markSuperRegs(Reserved, Reg);
418       for (MCRegAliasIterator AS(Reg, this, true); AS.isValid(); ++AS) {
419         Reserved.set(*AS);
420       }
421     }
422   }
423 
424   assert(checkAllSuperRegsMarked(Reserved));
425   return Reserved;
426 }
427 
428 bool PPCRegisterInfo::isAsmClobberable(const MachineFunction &MF,
429                                        MCRegister PhysReg) const {
430   // We cannot use getReservedRegs() to find the registers that are not asm
431   // clobberable because there are some reserved registers which can be
432   // clobbered by inline asm. For example, when LR is clobbered, the register is
433   // saved and restored. We will hardcode the registers that are not asm
434   // cloberable in this function.
435 
436   // The stack pointer (R1/X1) is not clobberable by inline asm
437   return PhysReg != PPC::R1 && PhysReg != PPC::X1;
438 }
439 
440 bool PPCRegisterInfo::requiresFrameIndexScavenging(const MachineFunction &MF) const {
441   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
442   const PPCInstrInfo *InstrInfo =  Subtarget.getInstrInfo();
443   const MachineFrameInfo &MFI = MF.getFrameInfo();
444   const std::vector<CalleeSavedInfo> &Info = MFI.getCalleeSavedInfo();
445 
446   LLVM_DEBUG(dbgs() << "requiresFrameIndexScavenging for " << MF.getName()
447                     << ".\n");
448   // If the callee saved info is invalid we have to default to true for safety.
449   if (!MFI.isCalleeSavedInfoValid()) {
450     LLVM_DEBUG(dbgs() << "TRUE - Invalid callee saved info.\n");
451     return true;
452   }
453 
454   // We will require the use of X-Forms because the frame is larger than what
455   // can be represented in signed 16 bits that fit in the immediate of a D-Form.
456   // If we need an X-Form then we need a register to store the address offset.
457   unsigned FrameSize = MFI.getStackSize();
458   // Signed 16 bits means that the FrameSize cannot be more than 15 bits.
459   if (FrameSize & ~0x7FFF) {
460     LLVM_DEBUG(dbgs() << "TRUE - Frame size is too large for D-Form.\n");
461     return true;
462   }
463 
464   // The callee saved info is valid so it can be traversed.
465   // Checking for registers that need saving that do not have load or store
466   // forms where the address offset is an immediate.
467   for (const CalleeSavedInfo &CSI : Info) {
468     // If the spill is to a register no scavenging is required.
469     if (CSI.isSpilledToReg())
470       continue;
471 
472     int FrIdx = CSI.getFrameIdx();
473     Register Reg = CSI.getReg();
474 
475     const TargetRegisterClass *RC = getMinimalPhysRegClass(Reg);
476     unsigned Opcode = InstrInfo->getStoreOpcodeForSpill(RC);
477     if (!MFI.isFixedObjectIndex(FrIdx)) {
478       // This is not a fixed object. If it requires alignment then we may still
479       // need to use the XForm.
480       if (offsetMinAlignForOpcode(Opcode) > 1) {
481         LLVM_DEBUG(dbgs() << "Memory Operand: " << InstrInfo->getName(Opcode)
482                           << " for register " << printReg(Reg, this) << ".\n");
483         LLVM_DEBUG(dbgs() << "TRUE - Not fixed frame object that requires "
484                           << "alignment.\n");
485         return true;
486       }
487     }
488 
489     // This is eiher:
490     // 1) A fixed frame index object which we know are aligned so
491     // as long as we have a valid DForm/DSForm/DQForm (non XForm) we don't
492     // need to consider the alignment here.
493     // 2) A not fixed object but in that case we now know that the min required
494     // alignment is no more than 1 based on the previous check.
495     if (InstrInfo->isXFormMemOp(Opcode)) {
496       LLVM_DEBUG(dbgs() << "Memory Operand: " << InstrInfo->getName(Opcode)
497                         << " for register " << printReg(Reg, this) << ".\n");
498       LLVM_DEBUG(dbgs() << "TRUE - Memory operand is X-Form.\n");
499       return true;
500     }
501 
502     // This is a spill/restore of a quadword.
503     if ((Opcode == PPC::RESTORE_QUADWORD) || (Opcode == PPC::SPILL_QUADWORD)) {
504       LLVM_DEBUG(dbgs() << "Memory Operand: " << InstrInfo->getName(Opcode)
505                         << " for register " << printReg(Reg, this) << ".\n");
506       LLVM_DEBUG(dbgs() << "TRUE - Memory operand is a quadword.\n");
507       return true;
508     }
509   }
510   LLVM_DEBUG(dbgs() << "FALSE - Scavenging is not required.\n");
511   return false;
512 }
513 
514 bool PPCRegisterInfo::requiresVirtualBaseRegisters(
515     const MachineFunction &MF) const {
516   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
517   // Do not use virtual base registers when ROP protection is turned on.
518   // Virtual base registers break the layout of the local variable space and may
519   // push the ROP Hash location past the 512 byte range of the ROP store
520   // instruction.
521   return !Subtarget.hasROPProtect();
522 }
523 
524 bool PPCRegisterInfo::isCallerPreservedPhysReg(MCRegister PhysReg,
525                                                const MachineFunction &MF) const {
526   assert(Register::isPhysicalRegister(PhysReg));
527   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
528   const MachineFrameInfo &MFI = MF.getFrameInfo();
529 
530   if (!Subtarget.is64BitELFABI() && !Subtarget.isAIXABI())
531     return false;
532   if (PhysReg == Subtarget.getTOCPointerRegister())
533     // X2/R2 is guaranteed to be preserved within a function if it is reserved.
534     // The reason it's reserved is that it's the TOC pointer (and the function
535     // uses the TOC). In functions where it isn't reserved (i.e. leaf functions
536     // with no TOC access), we can't claim that it is preserved.
537     return (getReservedRegs(MF).test(PhysReg));
538   if (StackPtrConst && PhysReg == Subtarget.getStackPointerRegister() &&
539       !MFI.hasVarSizedObjects() && !MFI.hasOpaqueSPAdjustment())
540     // The value of the stack pointer does not change within a function after
541     // the prologue and before the epilogue if there are no dynamic allocations
542     // and no inline asm which clobbers X1/R1.
543     return true;
544   return false;
545 }
546 
547 bool PPCRegisterInfo::getRegAllocationHints(Register VirtReg,
548                                             ArrayRef<MCPhysReg> Order,
549                                             SmallVectorImpl<MCPhysReg> &Hints,
550                                             const MachineFunction &MF,
551                                             const VirtRegMap *VRM,
552                                             const LiveRegMatrix *Matrix) const {
553   const MachineRegisterInfo *MRI = &MF.getRegInfo();
554 
555   // Call the base implementation first to set any hints based on the usual
556   // heuristics and decide what the return value should be. We want to return
557   // the same value returned by the base implementation. If the base
558   // implementation decides to return true and force the allocation then we
559   // will leave it as such. On the other hand if the base implementation
560   // decides to return false the following code will not force the allocation
561   // as we are just looking to provide a hint.
562   bool BaseImplRetVal = TargetRegisterInfo::getRegAllocationHints(
563       VirtReg, Order, Hints, MF, VRM, Matrix);
564   // We are interested in instructions that copy values to ACC/UACC.
565   // The copy into UACC will be simply a COPY to a subreg so we
566   // want to allocate the corresponding physical subreg for the source.
567   // The copy into ACC will be a BUILD_UACC so we want to allocate
568   // the same number UACC for the source.
569   for (MachineInstr &Use : MRI->reg_nodbg_instructions(VirtReg)) {
570     const MachineOperand *ResultOp = nullptr;
571     Register ResultReg;
572     switch (Use.getOpcode()) {
573     case TargetOpcode::COPY: {
574       ResultOp = &Use.getOperand(0);
575       ResultReg = ResultOp->getReg();
576       if (Register::isVirtualRegister(ResultReg) &&
577           MRI->getRegClass(ResultReg)->contains(PPC::UACC0) &&
578           VRM->hasPhys(ResultReg)) {
579         Register UACCPhys = VRM->getPhys(ResultReg);
580         Register HintReg = getSubReg(UACCPhys, ResultOp->getSubReg());
581         // Ensure that the hint is a VSRp register.
582         if (HintReg >= PPC::VSRp0 && HintReg <= PPC::VSRp31)
583           Hints.push_back(HintReg);
584       }
585       break;
586     }
587     case PPC::BUILD_UACC: {
588       ResultOp = &Use.getOperand(0);
589       ResultReg = ResultOp->getReg();
590       if (MRI->getRegClass(ResultReg)->contains(PPC::ACC0) &&
591           VRM->hasPhys(ResultReg)) {
592         Register ACCPhys = VRM->getPhys(ResultReg);
593         assert((ACCPhys >= PPC::ACC0 && ACCPhys <= PPC::ACC7) &&
594                "Expecting an ACC register for BUILD_UACC.");
595         Register HintReg = PPC::UACC0 + (ACCPhys - PPC::ACC0);
596         Hints.push_back(HintReg);
597       }
598       break;
599     }
600     }
601   }
602   return BaseImplRetVal;
603 }
604 
605 unsigned PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
606                                               MachineFunction &MF) const {
607   const PPCFrameLowering *TFI = getFrameLowering(MF);
608   const unsigned DefaultSafety = 1;
609 
610   switch (RC->getID()) {
611   default:
612     return 0;
613   case PPC::G8RC_NOX0RegClassID:
614   case PPC::GPRC_NOR0RegClassID:
615   case PPC::SPERCRegClassID:
616   case PPC::G8RCRegClassID:
617   case PPC::GPRCRegClassID: {
618     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
619     return 32 - FP - DefaultSafety;
620   }
621   case PPC::F4RCRegClassID:
622   case PPC::F8RCRegClassID:
623   case PPC::VSLRCRegClassID:
624     return 32 - DefaultSafety;
625   case PPC::VFRCRegClassID:
626   case PPC::VRRCRegClassID: {
627     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
628     // Vector registers VR20-VR31 are reserved and cannot be used in the default
629     // Altivec ABI on AIX.
630     if (!TM.getAIXExtendedAltivecABI() && Subtarget.isAIXABI())
631       return 20 - DefaultSafety;
632   }
633     return 32 - DefaultSafety;
634   case PPC::VSFRCRegClassID:
635   case PPC::VSSRCRegClassID:
636   case PPC::VSRCRegClassID: {
637     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
638     if (!TM.getAIXExtendedAltivecABI() && Subtarget.isAIXABI())
639       // Vector registers VR20-VR31 are reserved and cannot be used in the
640       // default Altivec ABI on AIX.
641       return 52 - DefaultSafety;
642   }
643     return 64 - DefaultSafety;
644   case PPC::CRRCRegClassID:
645     return 8 - DefaultSafety;
646   }
647 }
648 
649 const TargetRegisterClass *
650 PPCRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC,
651                                            const MachineFunction &MF) const {
652   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
653   const auto *DefaultSuperclass =
654       TargetRegisterInfo::getLargestLegalSuperClass(RC, MF);
655   if (Subtarget.hasVSX()) {
656     // With VSX, we can inflate various sub-register classes to the full VSX
657     // register set.
658 
659     // For Power9 we allow the user to enable GPR to vector spills.
660     // FIXME: Currently limited to spilling GP8RC. A follow on patch will add
661     // support to spill GPRC.
662     if (TM.isELFv2ABI() || Subtarget.isAIXABI()) {
663       if (Subtarget.hasP9Vector() && EnableGPRToVecSpills &&
664           RC == &PPC::G8RCRegClass) {
665         InflateGP8RC++;
666         return &PPC::SPILLTOVSRRCRegClass;
667       }
668       if (RC == &PPC::GPRCRegClass && EnableGPRToVecSpills)
669         InflateGPRC++;
670     }
671 
672     for (const auto *I = RC->getSuperClasses(); *I; ++I) {
673       if (getRegSizeInBits(**I) != getRegSizeInBits(*RC))
674         continue;
675 
676       switch ((*I)->getID()) {
677       case PPC::VSSRCRegClassID:
678         return Subtarget.hasP8Vector() ? *I : DefaultSuperclass;
679       case PPC::VSFRCRegClassID:
680       case PPC::VSRCRegClassID:
681         return *I;
682       case PPC::VSRpRCRegClassID:
683         return Subtarget.pairedVectorMemops() ? *I : DefaultSuperclass;
684       case PPC::ACCRCRegClassID:
685       case PPC::UACCRCRegClassID:
686         return Subtarget.hasMMA() ? *I : DefaultSuperclass;
687       }
688     }
689   }
690 
691   return DefaultSuperclass;
692 }
693 
694 //===----------------------------------------------------------------------===//
695 // Stack Frame Processing methods
696 //===----------------------------------------------------------------------===//
697 
698 /// lowerDynamicAlloc - Generate the code for allocating an object in the
699 /// current frame.  The sequence of code will be in the general form
700 ///
701 ///   addi   R0, SP, \#frameSize ; get the address of the previous frame
702 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
703 ///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
704 ///
705 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
706   // Get the instruction.
707   MachineInstr &MI = *II;
708   // Get the instruction's basic block.
709   MachineBasicBlock &MBB = *MI.getParent();
710   // Get the basic block's function.
711   MachineFunction &MF = *MBB.getParent();
712   // Get the frame info.
713   MachineFrameInfo &MFI = MF.getFrameInfo();
714   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
715   // Get the instruction info.
716   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
717   // Determine whether 64-bit pointers are used.
718   bool LP64 = TM.isPPC64();
719   DebugLoc dl = MI.getDebugLoc();
720 
721   // Get the maximum call stack size.
722   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
723   Align MaxAlign = MFI.getMaxAlign();
724   assert(isAligned(MaxAlign, maxCallFrameSize) &&
725          "Maximum call-frame size not sufficiently aligned");
726   (void)MaxAlign;
727 
728   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
729   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
730   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
731   bool KillNegSizeReg = MI.getOperand(1).isKill();
732   Register NegSizeReg = MI.getOperand(1).getReg();
733 
734   prepareDynamicAlloca(II, NegSizeReg, KillNegSizeReg, Reg);
735   // Grow the stack and update the stack pointer link, then determine the
736   // address of new allocated space.
737   if (LP64) {
738     BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
739         .addReg(Reg, RegState::Kill)
740         .addReg(PPC::X1)
741         .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
742     BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
743         .addReg(PPC::X1)
744         .addImm(maxCallFrameSize);
745   } else {
746     BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
747         .addReg(Reg, RegState::Kill)
748         .addReg(PPC::R1)
749         .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
750     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
751         .addReg(PPC::R1)
752         .addImm(maxCallFrameSize);
753   }
754 
755   // Discard the DYNALLOC instruction.
756   MBB.erase(II);
757 }
758 
759 /// To accomplish dynamic stack allocation, we have to calculate exact size
760 /// subtracted from the stack pointer according alignment information and get
761 /// previous frame pointer.
762 void PPCRegisterInfo::prepareDynamicAlloca(MachineBasicBlock::iterator II,
763                                            Register &NegSizeReg,
764                                            bool &KillNegSizeReg,
765                                            Register &FramePointer) const {
766   // Get the instruction.
767   MachineInstr &MI = *II;
768   // Get the instruction's basic block.
769   MachineBasicBlock &MBB = *MI.getParent();
770   // Get the basic block's function.
771   MachineFunction &MF = *MBB.getParent();
772   // Get the frame info.
773   MachineFrameInfo &MFI = MF.getFrameInfo();
774   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
775   // Get the instruction info.
776   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
777   // Determine whether 64-bit pointers are used.
778   bool LP64 = TM.isPPC64();
779   DebugLoc dl = MI.getDebugLoc();
780   // Get the total frame size.
781   unsigned FrameSize = MFI.getStackSize();
782 
783   // Get stack alignments.
784   const PPCFrameLowering *TFI = getFrameLowering(MF);
785   Align TargetAlign = TFI->getStackAlign();
786   Align MaxAlign = MFI.getMaxAlign();
787 
788   // Determine the previous frame's address.  If FrameSize can't be
789   // represented as 16 bits or we need special alignment, then we load the
790   // previous frame's address from 0(SP).  Why not do an addis of the hi?
791   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
792   // Constructing the constant and adding would take 3 instructions.
793   // Fortunately, a frame greater than 32K is rare.
794   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
795   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
796 
797   if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
798     if (LP64)
799       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), FramePointer)
800           .addReg(PPC::X31)
801           .addImm(FrameSize);
802     else
803       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), FramePointer)
804           .addReg(PPC::R31)
805           .addImm(FrameSize);
806   } else if (LP64) {
807     BuildMI(MBB, II, dl, TII.get(PPC::LD), FramePointer)
808         .addImm(0)
809         .addReg(PPC::X1);
810   } else {
811     BuildMI(MBB, II, dl, TII.get(PPC::LWZ), FramePointer)
812         .addImm(0)
813         .addReg(PPC::R1);
814   }
815   // Determine the actual NegSizeReg according to alignment info.
816   if (LP64) {
817     if (MaxAlign > TargetAlign) {
818       unsigned UnalNegSizeReg = NegSizeReg;
819       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
820 
821       // Unfortunately, there is no andi, only andi., and we can't insert that
822       // here because we might clobber cr0 while it is live.
823       BuildMI(MBB, II, dl, TII.get(PPC::LI8), NegSizeReg)
824           .addImm(~(MaxAlign.value() - 1));
825 
826       unsigned NegSizeReg1 = NegSizeReg;
827       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
828       BuildMI(MBB, II, dl, TII.get(PPC::AND8), NegSizeReg)
829           .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
830           .addReg(NegSizeReg1, RegState::Kill);
831       KillNegSizeReg = true;
832     }
833   } else {
834     if (MaxAlign > TargetAlign) {
835       unsigned UnalNegSizeReg = NegSizeReg;
836       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
837 
838       // Unfortunately, there is no andi, only andi., and we can't insert that
839       // here because we might clobber cr0 while it is live.
840       BuildMI(MBB, II, dl, TII.get(PPC::LI), NegSizeReg)
841           .addImm(~(MaxAlign.value() - 1));
842 
843       unsigned NegSizeReg1 = NegSizeReg;
844       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
845       BuildMI(MBB, II, dl, TII.get(PPC::AND), NegSizeReg)
846           .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
847           .addReg(NegSizeReg1, RegState::Kill);
848       KillNegSizeReg = true;
849     }
850   }
851 }
852 
853 void PPCRegisterInfo::lowerPrepareProbedAlloca(
854     MachineBasicBlock::iterator II) const {
855   MachineInstr &MI = *II;
856   // Get the instruction's basic block.
857   MachineBasicBlock &MBB = *MI.getParent();
858   // Get the basic block's function.
859   MachineFunction &MF = *MBB.getParent();
860   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
861   // Get the instruction info.
862   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
863   // Determine whether 64-bit pointers are used.
864   bool LP64 = TM.isPPC64();
865   DebugLoc dl = MI.getDebugLoc();
866   Register FramePointer = MI.getOperand(0).getReg();
867   const Register ActualNegSizeReg = MI.getOperand(1).getReg();
868   bool KillNegSizeReg = MI.getOperand(2).isKill();
869   Register NegSizeReg = MI.getOperand(2).getReg();
870   const MCInstrDesc &CopyInst = TII.get(LP64 ? PPC::OR8 : PPC::OR);
871   // RegAllocator might allocate FramePointer and NegSizeReg in the same phyreg.
872   if (FramePointer == NegSizeReg) {
873     assert(KillNegSizeReg && "FramePointer is a def and NegSizeReg is an use, "
874                              "NegSizeReg should be killed");
875     // FramePointer is clobbered earlier than the use of NegSizeReg in
876     // prepareDynamicAlloca, save NegSizeReg in ActualNegSizeReg to avoid
877     // misuse.
878     BuildMI(MBB, II, dl, CopyInst, ActualNegSizeReg)
879         .addReg(NegSizeReg)
880         .addReg(NegSizeReg);
881     NegSizeReg = ActualNegSizeReg;
882     KillNegSizeReg = false;
883   }
884   prepareDynamicAlloca(II, NegSizeReg, KillNegSizeReg, FramePointer);
885   // NegSizeReg might be updated in prepareDynamicAlloca if MaxAlign >
886   // TargetAlign.
887   if (NegSizeReg != ActualNegSizeReg)
888     BuildMI(MBB, II, dl, CopyInst, ActualNegSizeReg)
889         .addReg(NegSizeReg)
890         .addReg(NegSizeReg);
891   MBB.erase(II);
892 }
893 
894 void PPCRegisterInfo::lowerDynamicAreaOffset(
895     MachineBasicBlock::iterator II) const {
896   // Get the instruction.
897   MachineInstr &MI = *II;
898   // Get the instruction's basic block.
899   MachineBasicBlock &MBB = *MI.getParent();
900   // Get the basic block's function.
901   MachineFunction &MF = *MBB.getParent();
902   // Get the frame info.
903   MachineFrameInfo &MFI = MF.getFrameInfo();
904   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
905   // Get the instruction info.
906   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
907 
908   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
909   bool is64Bit = TM.isPPC64();
910   DebugLoc dl = MI.getDebugLoc();
911   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI),
912           MI.getOperand(0).getReg())
913       .addImm(maxCallFrameSize);
914   MBB.erase(II);
915 }
916 
917 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
918 /// reserving a whole register (R0), we scrounge for one here. This generates
919 /// code like this:
920 ///
921 ///   mfcr rA                  ; Move the conditional register into GPR rA.
922 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
923 ///   stw rA, FI               ; Store rA to the frame.
924 ///
925 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
926                                       unsigned FrameIndex) const {
927   // Get the instruction.
928   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>
929   // Get the instruction's basic block.
930   MachineBasicBlock &MBB = *MI.getParent();
931   MachineFunction &MF = *MBB.getParent();
932   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
933   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
934   DebugLoc dl = MI.getDebugLoc();
935 
936   bool LP64 = TM.isPPC64();
937   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
938   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
939 
940   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
941   Register SrcReg = MI.getOperand(0).getReg();
942 
943   // We need to store the CR in the low 4-bits of the saved value. First, issue
944   // an MFOCRF to save all of the CRBits and, if needed, kill the SrcReg.
945   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
946       .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
947 
948   // If the saved register wasn't CR0, shift the bits left so that they are in
949   // CR0's slot.
950   if (SrcReg != PPC::CR0) {
951     Register Reg1 = Reg;
952     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
953 
954     // rlwinm rA, rA, ShiftBits, 0, 31.
955     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
956       .addReg(Reg1, RegState::Kill)
957       .addImm(getEncodingValue(SrcReg) * 4)
958       .addImm(0)
959       .addImm(31);
960   }
961 
962   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
963                     .addReg(Reg, RegState::Kill),
964                     FrameIndex);
965 
966   // Discard the pseudo instruction.
967   MBB.erase(II);
968 }
969 
970 void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
971                                       unsigned FrameIndex) const {
972   // Get the instruction.
973   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CR <offset>
974   // Get the instruction's basic block.
975   MachineBasicBlock &MBB = *MI.getParent();
976   MachineFunction &MF = *MBB.getParent();
977   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
978   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
979   DebugLoc dl = MI.getDebugLoc();
980 
981   bool LP64 = TM.isPPC64();
982   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
983   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
984 
985   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
986   Register DestReg = MI.getOperand(0).getReg();
987   assert(MI.definesRegister(DestReg) &&
988     "RESTORE_CR does not define its destination");
989 
990   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
991                               Reg), FrameIndex);
992 
993   // If the reloaded register isn't CR0, shift the bits right so that they are
994   // in the right CR's slot.
995   if (DestReg != PPC::CR0) {
996     Register Reg1 = Reg;
997     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
998 
999     unsigned ShiftBits = getEncodingValue(DestReg)*4;
1000     // rlwinm r11, r11, 32-ShiftBits, 0, 31.
1001     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
1002              .addReg(Reg1, RegState::Kill).addImm(32-ShiftBits).addImm(0)
1003              .addImm(31);
1004   }
1005 
1006   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF), DestReg)
1007              .addReg(Reg, RegState::Kill);
1008 
1009   // Discard the pseudo instruction.
1010   MBB.erase(II);
1011 }
1012 
1013 void PPCRegisterInfo::lowerCRBitSpilling(MachineBasicBlock::iterator II,
1014                                          unsigned FrameIndex) const {
1015   // Get the instruction.
1016   MachineInstr &MI = *II;       // ; SPILL_CRBIT <SrcReg>, <offset>
1017   // Get the instruction's basic block.
1018   MachineBasicBlock &MBB = *MI.getParent();
1019   MachineFunction &MF = *MBB.getParent();
1020   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1021   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1022   const TargetRegisterInfo* TRI = Subtarget.getRegisterInfo();
1023   DebugLoc dl = MI.getDebugLoc();
1024 
1025   bool LP64 = TM.isPPC64();
1026   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1027   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1028 
1029   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
1030   Register SrcReg = MI.getOperand(0).getReg();
1031 
1032   // Search up the BB to find the definition of the CR bit.
1033   MachineBasicBlock::reverse_iterator Ins = MI;
1034   MachineBasicBlock::reverse_iterator Rend = MBB.rend();
1035   ++Ins;
1036   unsigned CRBitSpillDistance = 0;
1037   bool SeenUse = false;
1038   for (; Ins != Rend; ++Ins) {
1039     // Definition found.
1040     if (Ins->modifiesRegister(SrcReg, TRI))
1041       break;
1042     // Use found.
1043     if (Ins->readsRegister(SrcReg, TRI))
1044       SeenUse = true;
1045     // Unable to find CR bit definition within maximum search distance.
1046     if (CRBitSpillDistance == MaxCRBitSpillDist) {
1047       Ins = MI;
1048       break;
1049     }
1050     // Skip debug instructions when counting CR bit spill distance.
1051     if (!Ins->isDebugInstr())
1052       CRBitSpillDistance++;
1053   }
1054 
1055   // Unable to find the definition of the CR bit in the MBB.
1056   if (Ins == MBB.rend())
1057     Ins = MI;
1058 
1059   bool SpillsKnownBit = false;
1060   // There is no need to extract the CR bit if its value is already known.
1061   switch (Ins->getOpcode()) {
1062   case PPC::CRUNSET:
1063     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LI8 : PPC::LI), Reg)
1064       .addImm(0);
1065     SpillsKnownBit = true;
1066     break;
1067   case PPC::CRSET:
1068     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LIS8 : PPC::LIS), Reg)
1069       .addImm(-32768);
1070     SpillsKnownBit = true;
1071     break;
1072   default:
1073     // On Power10, we can use SETNBC to spill all CR bits. SETNBC will set all
1074     // bits (specifically, it produces a -1 if the CR bit is set). Ultimately,
1075     // the bit that is of importance to us is bit 32 (bit 0 of a 32-bit
1076     // register), and SETNBC will set this.
1077     if (Subtarget.isISA3_1()) {
1078       BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::SETNBC8 : PPC::SETNBC), Reg)
1079           .addReg(SrcReg, RegState::Undef);
1080       break;
1081     }
1082 
1083     // On Power9, we can use SETB to extract the LT bit. This only works for
1084     // the LT bit since SETB produces -1/1/0 for LT/GT/<neither>. So the value
1085     // of the bit we care about (32-bit sign bit) will be set to the value of
1086     // the LT bit (regardless of the other bits in the CR field).
1087     if (Subtarget.isISA3_0()) {
1088       if (SrcReg == PPC::CR0LT || SrcReg == PPC::CR1LT ||
1089           SrcReg == PPC::CR2LT || SrcReg == PPC::CR3LT ||
1090           SrcReg == PPC::CR4LT || SrcReg == PPC::CR5LT ||
1091           SrcReg == PPC::CR6LT || SrcReg == PPC::CR7LT) {
1092         BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::SETB8 : PPC::SETB), Reg)
1093           .addReg(getCRFromCRBit(SrcReg), RegState::Undef);
1094         break;
1095       }
1096     }
1097 
1098     // We need to move the CR field that contains the CR bit we are spilling.
1099     // The super register may not be explicitly defined (i.e. it can be defined
1100     // by a CR-logical that only defines the subreg) so we state that the CR
1101     // field is undef. Also, in order to preserve the kill flag on the CR bit,
1102     // we add it as an implicit use.
1103     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
1104       .addReg(getCRFromCRBit(SrcReg), RegState::Undef)
1105       .addReg(SrcReg,
1106               RegState::Implicit | getKillRegState(MI.getOperand(0).isKill()));
1107 
1108     // If the saved register wasn't CR0LT, shift the bits left so that the bit
1109     // to store is the first one. Mask all but that bit.
1110     Register Reg1 = Reg;
1111     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
1112 
1113     // rlwinm rA, rA, ShiftBits, 0, 0.
1114     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
1115       .addReg(Reg1, RegState::Kill)
1116       .addImm(getEncodingValue(SrcReg))
1117       .addImm(0).addImm(0);
1118   }
1119   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
1120                     .addReg(Reg, RegState::Kill),
1121                     FrameIndex);
1122 
1123   bool KillsCRBit = MI.killsRegister(SrcReg, TRI);
1124   // Discard the pseudo instruction.
1125   MBB.erase(II);
1126   if (SpillsKnownBit && KillsCRBit && !SeenUse) {
1127     Ins->setDesc(TII.get(PPC::UNENCODED_NOP));
1128     Ins->removeOperand(0);
1129   }
1130 }
1131 
1132 void PPCRegisterInfo::lowerCRBitRestore(MachineBasicBlock::iterator II,
1133                                       unsigned FrameIndex) const {
1134   // Get the instruction.
1135   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CRBIT <offset>
1136   // Get the instruction's basic block.
1137   MachineBasicBlock &MBB = *MI.getParent();
1138   MachineFunction &MF = *MBB.getParent();
1139   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1140   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1141   DebugLoc dl = MI.getDebugLoc();
1142 
1143   bool LP64 = TM.isPPC64();
1144   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1145   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1146 
1147   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
1148   Register DestReg = MI.getOperand(0).getReg();
1149   assert(MI.definesRegister(DestReg) &&
1150     "RESTORE_CRBIT does not define its destination");
1151 
1152   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
1153                               Reg), FrameIndex);
1154 
1155   BuildMI(MBB, II, dl, TII.get(TargetOpcode::IMPLICIT_DEF), DestReg);
1156 
1157   Register RegO = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
1158   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), RegO)
1159           .addReg(getCRFromCRBit(DestReg));
1160 
1161   unsigned ShiftBits = getEncodingValue(DestReg);
1162   // rlwimi r11, r10, 32-ShiftBits, ..., ...
1163   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWIMI8 : PPC::RLWIMI), RegO)
1164       .addReg(RegO, RegState::Kill)
1165       .addReg(Reg, RegState::Kill)
1166       .addImm(ShiftBits ? 32 - ShiftBits : 0)
1167       .addImm(ShiftBits)
1168       .addImm(ShiftBits);
1169 
1170   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF),
1171           getCRFromCRBit(DestReg))
1172       .addReg(RegO, RegState::Kill)
1173       // Make sure we have a use dependency all the way through this
1174       // sequence of instructions. We can't have the other bits in the CR
1175       // modified in between the mfocrf and the mtocrf.
1176       .addReg(getCRFromCRBit(DestReg), RegState::Implicit);
1177 
1178   // Discard the pseudo instruction.
1179   MBB.erase(II);
1180 }
1181 
1182 void PPCRegisterInfo::emitAccCopyInfo(MachineBasicBlock &MBB,
1183                                       MCRegister DestReg, MCRegister SrcReg) {
1184 #ifdef NDEBUG
1185   return;
1186 #else
1187   if (ReportAccMoves) {
1188     std::string Dest = PPC::ACCRCRegClass.contains(DestReg) ? "acc" : "uacc";
1189     std::string Src = PPC::ACCRCRegClass.contains(SrcReg) ? "acc" : "uacc";
1190     dbgs() << "Emitting copy from " << Src << " to " << Dest << ":\n";
1191     MBB.dump();
1192   }
1193 #endif
1194 }
1195 
1196 static void emitAccSpillRestoreInfo(MachineBasicBlock &MBB, bool IsPrimed,
1197                                     bool IsRestore) {
1198 #ifdef NDEBUG
1199   return;
1200 #else
1201   if (ReportAccMoves) {
1202     dbgs() << "Emitting " << (IsPrimed ? "acc" : "uacc") << " register "
1203            << (IsRestore ? "restore" : "spill") << ":\n";
1204     MBB.dump();
1205   }
1206 #endif
1207 }
1208 
1209 static void spillRegPairs(MachineBasicBlock &MBB,
1210                           MachineBasicBlock::iterator II, DebugLoc DL,
1211                           const TargetInstrInfo &TII, Register SrcReg,
1212                           unsigned FrameIndex, bool IsLittleEndian,
1213                           bool IsKilled, bool TwoPairs) {
1214   unsigned Offset = 0;
1215   if (TwoPairs)
1216     Offset = IsLittleEndian ? 48 : 0;
1217   else
1218     Offset = IsLittleEndian ? 16 : 0;
1219   Register Reg = (SrcReg > PPC::VSRp15) ? PPC::V0 + (SrcReg - PPC::VSRp16) * 2
1220                                         : PPC::VSL0 + (SrcReg - PPC::VSRp0) * 2;
1221   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXV))
1222                         .addReg(Reg, getKillRegState(IsKilled)),
1223                     FrameIndex, Offset);
1224   Offset += IsLittleEndian ? -16 : 16;
1225   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXV))
1226                         .addReg(Reg + 1, getKillRegState(IsKilled)),
1227                     FrameIndex, Offset);
1228   if (TwoPairs) {
1229     Offset += IsLittleEndian ? -16 : 16;
1230     addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXV))
1231                           .addReg(Reg + 2, getKillRegState(IsKilled)),
1232                       FrameIndex, Offset);
1233     Offset += IsLittleEndian ? -16 : 16;
1234     addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXV))
1235                           .addReg(Reg + 3, getKillRegState(IsKilled)),
1236                       FrameIndex, Offset);
1237   }
1238 }
1239 
1240 /// Remove any STXVP[X] instructions and split them out into a pair of
1241 /// STXV[X] instructions if --disable-auto-paired-vec-st is specified on
1242 /// the command line.
1243 void PPCRegisterInfo::lowerOctWordSpilling(MachineBasicBlock::iterator II,
1244                                            unsigned FrameIndex) const {
1245   assert(DisableAutoPairedVecSt &&
1246          "Expecting to do this only if paired vector stores are disabled.");
1247   MachineInstr &MI = *II; // STXVP <SrcReg>, <offset>
1248   MachineBasicBlock &MBB = *MI.getParent();
1249   MachineFunction &MF = *MBB.getParent();
1250   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1251   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1252   DebugLoc DL = MI.getDebugLoc();
1253   Register SrcReg = MI.getOperand(0).getReg();
1254   bool IsLittleEndian = Subtarget.isLittleEndian();
1255   bool IsKilled = MI.getOperand(0).isKill();
1256   spillRegPairs(MBB, II, DL, TII, SrcReg, FrameIndex, IsLittleEndian, IsKilled,
1257                 /* TwoPairs */ false);
1258   // Discard the original instruction.
1259   MBB.erase(II);
1260 }
1261 
1262 /// lowerACCSpilling - Generate the code for spilling the accumulator register.
1263 /// Similarly to other spills/reloads that use pseudo-ops, we do not actually
1264 /// eliminate the FrameIndex here nor compute the stack offset. We simply
1265 /// create a real instruction with an FI and rely on eliminateFrameIndex to
1266 /// handle the FI elimination.
1267 void PPCRegisterInfo::lowerACCSpilling(MachineBasicBlock::iterator II,
1268                                        unsigned FrameIndex) const {
1269   MachineInstr &MI = *II; // SPILL_ACC <SrcReg>, <offset>
1270   MachineBasicBlock &MBB = *MI.getParent();
1271   MachineFunction &MF = *MBB.getParent();
1272   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1273   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1274   DebugLoc DL = MI.getDebugLoc();
1275   Register SrcReg = MI.getOperand(0).getReg();
1276   bool IsKilled = MI.getOperand(0).isKill();
1277 
1278   bool IsPrimed = PPC::ACCRCRegClass.contains(SrcReg);
1279   Register Reg =
1280       PPC::VSRp0 + (SrcReg - (IsPrimed ? PPC::ACC0 : PPC::UACC0)) * 2;
1281   bool IsLittleEndian = Subtarget.isLittleEndian();
1282 
1283   emitAccSpillRestoreInfo(MBB, IsPrimed, false);
1284 
1285   // De-prime the register being spilled, create two stores for the pair
1286   // subregisters accounting for endianness and then re-prime the register if
1287   // it isn't killed.  This uses the Offset parameter to addFrameReference() to
1288   // adjust the offset of the store that is within the 64-byte stack slot.
1289   if (IsPrimed)
1290     BuildMI(MBB, II, DL, TII.get(PPC::XXMFACC), SrcReg).addReg(SrcReg);
1291   if (DisableAutoPairedVecSt)
1292     spillRegPairs(MBB, II, DL, TII, Reg, FrameIndex, IsLittleEndian, IsKilled,
1293                   /* TwoPairs */ true);
1294   else {
1295     addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXVP))
1296                           .addReg(Reg, getKillRegState(IsKilled)),
1297                       FrameIndex, IsLittleEndian ? 32 : 0);
1298     addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXVP))
1299                           .addReg(Reg + 1, getKillRegState(IsKilled)),
1300                       FrameIndex, IsLittleEndian ? 0 : 32);
1301   }
1302   if (IsPrimed && !IsKilled)
1303     BuildMI(MBB, II, DL, TII.get(PPC::XXMTACC), SrcReg).addReg(SrcReg);
1304 
1305   // Discard the pseudo instruction.
1306   MBB.erase(II);
1307 }
1308 
1309 /// lowerACCRestore - Generate the code to restore the accumulator register.
1310 void PPCRegisterInfo::lowerACCRestore(MachineBasicBlock::iterator II,
1311                                       unsigned FrameIndex) const {
1312   MachineInstr &MI = *II; // <DestReg> = RESTORE_ACC <offset>
1313   MachineBasicBlock &MBB = *MI.getParent();
1314   MachineFunction &MF = *MBB.getParent();
1315   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1316   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1317   DebugLoc DL = MI.getDebugLoc();
1318 
1319   Register DestReg = MI.getOperand(0).getReg();
1320   assert(MI.definesRegister(DestReg) &&
1321          "RESTORE_ACC does not define its destination");
1322 
1323   bool IsPrimed = PPC::ACCRCRegClass.contains(DestReg);
1324   Register Reg =
1325       PPC::VSRp0 + (DestReg - (IsPrimed ? PPC::ACC0 : PPC::UACC0)) * 2;
1326   bool IsLittleEndian = Subtarget.isLittleEndian();
1327 
1328   emitAccSpillRestoreInfo(MBB, IsPrimed, true);
1329 
1330   // Create two loads for the pair subregisters accounting for endianness and
1331   // then prime the accumulator register being restored.
1332   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LXVP), Reg),
1333                     FrameIndex, IsLittleEndian ? 32 : 0);
1334   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LXVP), Reg + 1),
1335                     FrameIndex, IsLittleEndian ? 0 : 32);
1336   if (IsPrimed)
1337     BuildMI(MBB, II, DL, TII.get(PPC::XXMTACC), DestReg).addReg(DestReg);
1338 
1339   // Discard the pseudo instruction.
1340   MBB.erase(II);
1341 }
1342 
1343 /// lowerQuadwordSpilling - Generate code to spill paired general register.
1344 void PPCRegisterInfo::lowerQuadwordSpilling(MachineBasicBlock::iterator II,
1345                                             unsigned FrameIndex) const {
1346   MachineInstr &MI = *II;
1347   MachineBasicBlock &MBB = *MI.getParent();
1348   MachineFunction &MF = *MBB.getParent();
1349   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1350   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1351   DebugLoc DL = MI.getDebugLoc();
1352 
1353   Register SrcReg = MI.getOperand(0).getReg();
1354   bool IsKilled = MI.getOperand(0).isKill();
1355 
1356   Register Reg = PPC::X0 + (SrcReg - PPC::G8p0) * 2;
1357   bool IsLittleEndian = Subtarget.isLittleEndian();
1358 
1359   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STD))
1360                         .addReg(Reg, getKillRegState(IsKilled)),
1361                     FrameIndex, IsLittleEndian ? 8 : 0);
1362   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STD))
1363                         .addReg(Reg + 1, getKillRegState(IsKilled)),
1364                     FrameIndex, IsLittleEndian ? 0 : 8);
1365 
1366   // Discard the pseudo instruction.
1367   MBB.erase(II);
1368 }
1369 
1370 /// lowerQuadwordRestore - Generate code to restore paired general register.
1371 void PPCRegisterInfo::lowerQuadwordRestore(MachineBasicBlock::iterator II,
1372                                            unsigned FrameIndex) const {
1373   MachineInstr &MI = *II;
1374   MachineBasicBlock &MBB = *MI.getParent();
1375   MachineFunction &MF = *MBB.getParent();
1376   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1377   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1378   DebugLoc DL = MI.getDebugLoc();
1379 
1380   Register DestReg = MI.getOperand(0).getReg();
1381   assert(MI.definesRegister(DestReg) &&
1382          "RESTORE_QUADWORD does not define its destination");
1383 
1384   Register Reg = PPC::X0 + (DestReg - PPC::G8p0) * 2;
1385   bool IsLittleEndian = Subtarget.isLittleEndian();
1386 
1387   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LD), Reg), FrameIndex,
1388                     IsLittleEndian ? 8 : 0);
1389   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LD), Reg + 1), FrameIndex,
1390                     IsLittleEndian ? 0 : 8);
1391 
1392   // Discard the pseudo instruction.
1393   MBB.erase(II);
1394 }
1395 
1396 bool PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
1397                                            Register Reg, int &FrameIdx) const {
1398   // For the nonvolatile condition registers (CR2, CR3, CR4) return true to
1399   // prevent allocating an additional frame slot.
1400   // For 64-bit ELF and AIX, the CR save area is in the linkage area at SP+8,
1401   // for 32-bit AIX the CR save area is in the linkage area at SP+4.
1402   // We have created a FrameIndex to that spill slot to keep the CalleSaveInfos
1403   // valid.
1404   // For 32-bit ELF, we have previously created the stack slot if needed, so
1405   // return its FrameIdx.
1406   if (PPC::CR2 <= Reg && Reg <= PPC::CR4) {
1407     FrameIdx = MF.getInfo<PPCFunctionInfo>()->getCRSpillFrameIndex();
1408     return true;
1409   }
1410   return false;
1411 }
1412 
1413 // If the offset must be a multiple of some value, return what that value is.
1414 static unsigned offsetMinAlignForOpcode(unsigned OpC) {
1415   switch (OpC) {
1416   default:
1417     return 1;
1418   case PPC::LWA:
1419   case PPC::LWA_32:
1420   case PPC::LD:
1421   case PPC::LDU:
1422   case PPC::STD:
1423   case PPC::STDU:
1424   case PPC::DFLOADf32:
1425   case PPC::DFLOADf64:
1426   case PPC::DFSTOREf32:
1427   case PPC::DFSTOREf64:
1428   case PPC::LXSD:
1429   case PPC::LXSSP:
1430   case PPC::STXSD:
1431   case PPC::STXSSP:
1432   case PPC::STQ:
1433     return 4;
1434   case PPC::EVLDD:
1435   case PPC::EVSTDD:
1436     return 8;
1437   case PPC::LXV:
1438   case PPC::STXV:
1439   case PPC::LQ:
1440   case PPC::LXVP:
1441   case PPC::STXVP:
1442     return 16;
1443   }
1444 }
1445 
1446 // If the offset must be a multiple of some value, return what that value is.
1447 static unsigned offsetMinAlign(const MachineInstr &MI) {
1448   unsigned OpC = MI.getOpcode();
1449   return offsetMinAlignForOpcode(OpC);
1450 }
1451 
1452 // Return the OffsetOperandNo given the FIOperandNum (and the instruction).
1453 static unsigned getOffsetONFromFION(const MachineInstr &MI,
1454                                     unsigned FIOperandNum) {
1455   // Take into account whether it's an add or mem instruction
1456   unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
1457   if (MI.isInlineAsm())
1458     OffsetOperandNo = FIOperandNum - 1;
1459   else if (MI.getOpcode() == TargetOpcode::STACKMAP ||
1460            MI.getOpcode() == TargetOpcode::PATCHPOINT)
1461     OffsetOperandNo = FIOperandNum + 1;
1462 
1463   return OffsetOperandNo;
1464 }
1465 
1466 void
1467 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
1468                                      int SPAdj, unsigned FIOperandNum,
1469                                      RegScavenger *RS) const {
1470   assert(SPAdj == 0 && "Unexpected");
1471 
1472   // Get the instruction.
1473   MachineInstr &MI = *II;
1474   // Get the instruction's basic block.
1475   MachineBasicBlock &MBB = *MI.getParent();
1476   // Get the basic block's function.
1477   MachineFunction &MF = *MBB.getParent();
1478   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1479   // Get the instruction info.
1480   const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
1481   // Get the frame info.
1482   MachineFrameInfo &MFI = MF.getFrameInfo();
1483   DebugLoc dl = MI.getDebugLoc();
1484 
1485   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1486 
1487   // Get the frame index.
1488   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
1489 
1490   // Get the frame pointer save index.  Users of this index are primarily
1491   // DYNALLOC instructions.
1492   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1493   int FPSI = FI->getFramePointerSaveIndex();
1494   // Get the instruction opcode.
1495   unsigned OpC = MI.getOpcode();
1496 
1497   if ((OpC == PPC::DYNAREAOFFSET || OpC == PPC::DYNAREAOFFSET8)) {
1498     lowerDynamicAreaOffset(II);
1499     return;
1500   }
1501 
1502   // Special case for dynamic alloca.
1503   if (FPSI && FrameIndex == FPSI &&
1504       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
1505     lowerDynamicAlloc(II);
1506     return;
1507   }
1508 
1509   if (FPSI && FrameIndex == FPSI &&
1510       (OpC == PPC::PREPARE_PROBED_ALLOCA_64 ||
1511        OpC == PPC::PREPARE_PROBED_ALLOCA_32 ||
1512        OpC == PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 ||
1513        OpC == PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32)) {
1514     lowerPrepareProbedAlloca(II);
1515     return;
1516   }
1517 
1518   // Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
1519   if (OpC == PPC::SPILL_CR) {
1520     lowerCRSpilling(II, FrameIndex);
1521     return;
1522   } else if (OpC == PPC::RESTORE_CR) {
1523     lowerCRRestore(II, FrameIndex);
1524     return;
1525   } else if (OpC == PPC::SPILL_CRBIT) {
1526     lowerCRBitSpilling(II, FrameIndex);
1527     return;
1528   } else if (OpC == PPC::RESTORE_CRBIT) {
1529     lowerCRBitRestore(II, FrameIndex);
1530     return;
1531   } else if (OpC == PPC::SPILL_ACC || OpC == PPC::SPILL_UACC) {
1532     lowerACCSpilling(II, FrameIndex);
1533     return;
1534   } else if (OpC == PPC::RESTORE_ACC || OpC == PPC::RESTORE_UACC) {
1535     lowerACCRestore(II, FrameIndex);
1536     return;
1537   } else if (OpC == PPC::STXVP && DisableAutoPairedVecSt) {
1538     lowerOctWordSpilling(II, FrameIndex);
1539     return;
1540   } else if (OpC == PPC::SPILL_QUADWORD) {
1541     lowerQuadwordSpilling(II, FrameIndex);
1542     return;
1543   } else if (OpC == PPC::RESTORE_QUADWORD) {
1544     lowerQuadwordRestore(II, FrameIndex);
1545     return;
1546   }
1547 
1548   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
1549   MI.getOperand(FIOperandNum).ChangeToRegister(
1550     FrameIndex < 0 ? getBaseRegister(MF) : getFrameRegister(MF), false);
1551 
1552   // If the instruction is not present in ImmToIdxMap, then it has no immediate
1553   // form (and must be r+r).
1554   bool noImmForm = !MI.isInlineAsm() && OpC != TargetOpcode::STACKMAP &&
1555                    OpC != TargetOpcode::PATCHPOINT && !ImmToIdxMap.count(OpC);
1556 
1557   // Now add the frame object offset to the offset from r1.
1558   int64_t Offset = MFI.getObjectOffset(FrameIndex);
1559   Offset += MI.getOperand(OffsetOperandNo).getImm();
1560 
1561   // If we're not using a Frame Pointer that has been set to the value of the
1562   // SP before having the stack size subtracted from it, then add the stack size
1563   // to Offset to get the correct offset.
1564   // Naked functions have stack size 0, although getStackSize may not reflect
1565   // that because we didn't call all the pieces that compute it for naked
1566   // functions.
1567   if (!MF.getFunction().hasFnAttribute(Attribute::Naked)) {
1568     if (!(hasBasePointer(MF) && FrameIndex < 0))
1569       Offset += MFI.getStackSize();
1570   }
1571 
1572   // If we encounter an LXVP/STXVP with an offset that doesn't fit, we can
1573   // transform it to the prefixed version so we don't have to use the XForm.
1574   if ((OpC == PPC::LXVP || OpC == PPC::STXVP) &&
1575       (!isInt<16>(Offset) || (Offset % offsetMinAlign(MI)) != 0) &&
1576       Subtarget.hasPrefixInstrs()) {
1577     unsigned NewOpc = OpC == PPC::LXVP ? PPC::PLXVP : PPC::PSTXVP;
1578     MI.setDesc(TII.get(NewOpc));
1579     OpC = NewOpc;
1580   }
1581 
1582   // If we can, encode the offset directly into the instruction.  If this is a
1583   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
1584   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
1585   // clear can be encoded.  This is extremely uncommon, because normally you
1586   // only "std" to a stack slot that is at least 4-byte aligned, but it can
1587   // happen in invalid code.
1588   assert(OpC != PPC::DBG_VALUE &&
1589          "This should be handled in a target-independent way");
1590   // FIXME: This should be factored out to a separate function as prefixed
1591   // instructions add a number of opcodes for which we can use 34-bit imm.
1592   bool OffsetFitsMnemonic = (OpC == PPC::EVSTDD || OpC == PPC::EVLDD) ?
1593                             isUInt<8>(Offset) :
1594                             isInt<16>(Offset);
1595   if (TII.isPrefixed(MI.getOpcode()))
1596     OffsetFitsMnemonic = isInt<34>(Offset);
1597   if (!noImmForm && ((OffsetFitsMnemonic &&
1598                       ((Offset % offsetMinAlign(MI)) == 0)) ||
1599                      OpC == TargetOpcode::STACKMAP ||
1600                      OpC == TargetOpcode::PATCHPOINT)) {
1601     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1602     return;
1603   }
1604 
1605   // The offset doesn't fit into a single register, scavenge one to build the
1606   // offset in.
1607 
1608   bool is64Bit = TM.isPPC64();
1609   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1610   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1611   const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
1612   Register SRegHi = MF.getRegInfo().createVirtualRegister(RC),
1613            SReg = MF.getRegInfo().createVirtualRegister(RC);
1614   unsigned NewOpcode = 0u;
1615 
1616   // Insert a set of rA with the full offset value before the ld, st, or add
1617   if (isInt<16>(Offset))
1618     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI), SReg)
1619         .addImm(Offset);
1620   else if (isInt<32>(Offset)) {
1621     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
1622         .addImm(Offset >> 16);
1623     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
1624         .addReg(SRegHi, RegState::Kill)
1625         .addImm(Offset);
1626   } else {
1627     assert(is64Bit && "Huge stack is only supported on PPC64");
1628     TII.materializeImmPostRA(MBB, II, dl, SReg, Offset);
1629   }
1630 
1631   // Convert into indexed form of the instruction:
1632   //
1633   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
1634   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
1635   unsigned OperandBase;
1636 
1637   if (noImmForm)
1638     OperandBase = 1;
1639   else if (OpC != TargetOpcode::INLINEASM &&
1640            OpC != TargetOpcode::INLINEASM_BR) {
1641     assert(ImmToIdxMap.count(OpC) &&
1642            "No indexed form of load or store available!");
1643     NewOpcode = ImmToIdxMap.find(OpC)->second;
1644     MI.setDesc(TII.get(NewOpcode));
1645     OperandBase = 1;
1646   } else {
1647     OperandBase = OffsetOperandNo;
1648   }
1649 
1650   Register StackReg = MI.getOperand(FIOperandNum).getReg();
1651   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
1652   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
1653 
1654   // Since these are not real X-Form instructions, we must
1655   // add the registers and access 0(NewReg) rather than
1656   // emitting the X-Form pseudo.
1657   if (NewOpcode == PPC::LQX_PSEUDO || NewOpcode == PPC::STQX_PSEUDO) {
1658     assert(is64Bit && "Quadword loads/stores only supported in 64-bit mode");
1659     Register NewReg = MF.getRegInfo().createVirtualRegister(&PPC::G8RCRegClass);
1660     BuildMI(MBB, II, dl, TII.get(PPC::ADD8), NewReg)
1661         .addReg(SReg, RegState::Kill)
1662         .addReg(StackReg);
1663     MI.setDesc(TII.get(NewOpcode == PPC::LQX_PSEUDO ? PPC::LQ : PPC::STQ));
1664     MI.getOperand(OperandBase + 1).ChangeToRegister(NewReg, false);
1665     MI.getOperand(OperandBase).ChangeToImmediate(0);
1666   }
1667 }
1668 
1669 Register PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
1670   const PPCFrameLowering *TFI = getFrameLowering(MF);
1671 
1672   if (!TM.isPPC64())
1673     return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
1674   else
1675     return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
1676 }
1677 
1678 Register PPCRegisterInfo::getBaseRegister(const MachineFunction &MF) const {
1679   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1680   if (!hasBasePointer(MF))
1681     return getFrameRegister(MF);
1682 
1683   if (TM.isPPC64())
1684     return PPC::X30;
1685 
1686   if (Subtarget.isSVR4ABI() && TM.isPositionIndependent())
1687     return PPC::R29;
1688 
1689   return PPC::R30;
1690 }
1691 
1692 bool PPCRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
1693   if (!EnableBasePointer)
1694     return false;
1695   if (AlwaysBasePointer)
1696     return true;
1697 
1698   // If we need to realign the stack, then the stack pointer can no longer
1699   // serve as an offset into the caller's stack space. As a result, we need a
1700   // base pointer.
1701   return hasStackRealignment(MF);
1702 }
1703 
1704 /// Returns true if the instruction's frame index
1705 /// reference would be better served by a base register other than FP
1706 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
1707 /// references it should create new base registers for.
1708 bool PPCRegisterInfo::
1709 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
1710   assert(Offset < 0 && "Local offset must be negative");
1711 
1712   // It's the load/store FI references that cause issues, as it can be difficult
1713   // to materialize the offset if it won't fit in the literal field. Estimate
1714   // based on the size of the local frame and some conservative assumptions
1715   // about the rest of the stack frame (note, this is pre-regalloc, so
1716   // we don't know everything for certain yet) whether this offset is likely
1717   // to be out of range of the immediate. Return true if so.
1718 
1719   // We only generate virtual base registers for loads and stores that have
1720   // an r+i form. Return false for everything else.
1721   unsigned OpC = MI->getOpcode();
1722   if (!ImmToIdxMap.count(OpC))
1723     return false;
1724 
1725   // Don't generate a new virtual base register just to add zero to it.
1726   if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
1727       MI->getOperand(2).getImm() == 0)
1728     return false;
1729 
1730   MachineBasicBlock &MBB = *MI->getParent();
1731   MachineFunction &MF = *MBB.getParent();
1732   const PPCFrameLowering *TFI = getFrameLowering(MF);
1733   unsigned StackEst = TFI->determineFrameLayout(MF, true);
1734 
1735   // If we likely don't need a stack frame, then we probably don't need a
1736   // virtual base register either.
1737   if (!StackEst)
1738     return false;
1739 
1740   // Estimate an offset from the stack pointer.
1741   // The incoming offset is relating to the SP at the start of the function,
1742   // but when we access the local it'll be relative to the SP after local
1743   // allocation, so adjust our SP-relative offset by that allocation size.
1744   Offset += StackEst;
1745 
1746   // The frame pointer will point to the end of the stack, so estimate the
1747   // offset as the difference between the object offset and the FP location.
1748   return !isFrameOffsetLegal(MI, getBaseRegister(MF), Offset);
1749 }
1750 
1751 /// Insert defining instruction(s) for BaseReg to
1752 /// be a pointer to FrameIdx at the beginning of the basic block.
1753 Register PPCRegisterInfo::materializeFrameBaseRegister(MachineBasicBlock *MBB,
1754                                                        int FrameIdx,
1755                                                        int64_t Offset) const {
1756   unsigned ADDriOpc = TM.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
1757 
1758   MachineBasicBlock::iterator Ins = MBB->begin();
1759   DebugLoc DL;                  // Defaults to "unknown"
1760   if (Ins != MBB->end())
1761     DL = Ins->getDebugLoc();
1762 
1763   const MachineFunction &MF = *MBB->getParent();
1764   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1765   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1766   const MCInstrDesc &MCID = TII.get(ADDriOpc);
1767   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1768   const TargetRegisterClass *RC = getPointerRegClass(MF);
1769   Register BaseReg = MRI.createVirtualRegister(RC);
1770   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
1771 
1772   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
1773     .addFrameIndex(FrameIdx).addImm(Offset);
1774 
1775   return BaseReg;
1776 }
1777 
1778 void PPCRegisterInfo::resolveFrameIndex(MachineInstr &MI, Register BaseReg,
1779                                         int64_t Offset) const {
1780   unsigned FIOperandNum = 0;
1781   while (!MI.getOperand(FIOperandNum).isFI()) {
1782     ++FIOperandNum;
1783     assert(FIOperandNum < MI.getNumOperands() &&
1784            "Instr doesn't have FrameIndex operand!");
1785   }
1786 
1787   MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
1788   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1789   Offset += MI.getOperand(OffsetOperandNo).getImm();
1790   MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1791 
1792   MachineBasicBlock &MBB = *MI.getParent();
1793   MachineFunction &MF = *MBB.getParent();
1794   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1795   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1796   const MCInstrDesc &MCID = MI.getDesc();
1797   MachineRegisterInfo &MRI = MF.getRegInfo();
1798   MRI.constrainRegClass(BaseReg,
1799                         TII.getRegClass(MCID, FIOperandNum, this, MF));
1800 }
1801 
1802 bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
1803                                          Register BaseReg,
1804                                          int64_t Offset) const {
1805   unsigned FIOperandNum = 0;
1806   while (!MI->getOperand(FIOperandNum).isFI()) {
1807     ++FIOperandNum;
1808     assert(FIOperandNum < MI->getNumOperands() &&
1809            "Instr doesn't have FrameIndex operand!");
1810   }
1811 
1812   unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
1813   Offset += MI->getOperand(OffsetOperandNo).getImm();
1814 
1815   return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
1816          MI->getOpcode() == TargetOpcode::STACKMAP ||
1817          MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1818          (isInt<16>(Offset) && (Offset % offsetMinAlign(*MI)) == 0);
1819 }
1820