xref: /llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp (revision 30d639180f6715f2fafcac5b4893d8ffbc61733f)
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   const TargetRegisterClass *RegClass = MRI->getRegClass(VirtReg);
570   for (MachineInstr &Use : MRI->reg_nodbg_instructions(VirtReg)) {
571     const MachineOperand *ResultOp = nullptr;
572     Register ResultReg;
573     switch (Use.getOpcode()) {
574     case TargetOpcode::COPY: {
575       ResultOp = &Use.getOperand(0);
576       ResultReg = ResultOp->getReg();
577       if (Register::isVirtualRegister(ResultReg) &&
578           MRI->getRegClass(ResultReg)->contains(PPC::UACC0) &&
579           VRM->hasPhys(ResultReg)) {
580         Register UACCPhys = VRM->getPhys(ResultReg);
581         Register HintReg;
582         if (RegClass->contains(PPC::VSRp0)) {
583           HintReg = getSubReg(UACCPhys, ResultOp->getSubReg());
584           // Ensure that the hint is a VSRp register.
585           if (HintReg >= PPC::VSRp0 && HintReg <= PPC::VSRp31)
586             Hints.push_back(HintReg);
587         } else if (RegClass->contains(PPC::ACC0)) {
588           HintReg = PPC::ACC0 + (UACCPhys - PPC::UACC0);
589           if (HintReg >= PPC::ACC0 && HintReg <= PPC::ACC7)
590             Hints.push_back(HintReg);
591         }
592       }
593       break;
594     }
595     case PPC::BUILD_UACC: {
596       ResultOp = &Use.getOperand(0);
597       ResultReg = ResultOp->getReg();
598       if (MRI->getRegClass(ResultReg)->contains(PPC::ACC0) &&
599           VRM->hasPhys(ResultReg)) {
600         Register ACCPhys = VRM->getPhys(ResultReg);
601         assert((ACCPhys >= PPC::ACC0 && ACCPhys <= PPC::ACC7) &&
602                "Expecting an ACC register for BUILD_UACC.");
603         Register HintReg = PPC::UACC0 + (ACCPhys - PPC::ACC0);
604         Hints.push_back(HintReg);
605       }
606       break;
607     }
608     }
609   }
610   return BaseImplRetVal;
611 }
612 
613 unsigned PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
614                                               MachineFunction &MF) const {
615   const PPCFrameLowering *TFI = getFrameLowering(MF);
616   const unsigned DefaultSafety = 1;
617 
618   switch (RC->getID()) {
619   default:
620     return 0;
621   case PPC::G8RC_NOX0RegClassID:
622   case PPC::GPRC_NOR0RegClassID:
623   case PPC::SPERCRegClassID:
624   case PPC::G8RCRegClassID:
625   case PPC::GPRCRegClassID: {
626     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
627     return 32 - FP - DefaultSafety;
628   }
629   case PPC::F4RCRegClassID:
630   case PPC::F8RCRegClassID:
631   case PPC::VSLRCRegClassID:
632     return 32 - DefaultSafety;
633   case PPC::VFRCRegClassID:
634   case PPC::VRRCRegClassID: {
635     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
636     // Vector registers VR20-VR31 are reserved and cannot be used in the default
637     // Altivec ABI on AIX.
638     if (!TM.getAIXExtendedAltivecABI() && Subtarget.isAIXABI())
639       return 20 - DefaultSafety;
640   }
641     return 32 - DefaultSafety;
642   case PPC::VSFRCRegClassID:
643   case PPC::VSSRCRegClassID:
644   case PPC::VSRCRegClassID: {
645     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
646     if (!TM.getAIXExtendedAltivecABI() && Subtarget.isAIXABI())
647       // Vector registers VR20-VR31 are reserved and cannot be used in the
648       // default Altivec ABI on AIX.
649       return 52 - DefaultSafety;
650   }
651     return 64 - DefaultSafety;
652   case PPC::CRRCRegClassID:
653     return 8 - DefaultSafety;
654   }
655 }
656 
657 const TargetRegisterClass *
658 PPCRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC,
659                                            const MachineFunction &MF) const {
660   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
661   const auto *DefaultSuperclass =
662       TargetRegisterInfo::getLargestLegalSuperClass(RC, MF);
663   if (Subtarget.hasVSX()) {
664     // With VSX, we can inflate various sub-register classes to the full VSX
665     // register set.
666 
667     // For Power9 we allow the user to enable GPR to vector spills.
668     // FIXME: Currently limited to spilling GP8RC. A follow on patch will add
669     // support to spill GPRC.
670     if (TM.isELFv2ABI() || Subtarget.isAIXABI()) {
671       if (Subtarget.hasP9Vector() && EnableGPRToVecSpills &&
672           RC == &PPC::G8RCRegClass) {
673         InflateGP8RC++;
674         return &PPC::SPILLTOVSRRCRegClass;
675       }
676       if (RC == &PPC::GPRCRegClass && EnableGPRToVecSpills)
677         InflateGPRC++;
678     }
679 
680     for (const auto *I = RC->getSuperClasses(); *I; ++I) {
681       if (getRegSizeInBits(**I) != getRegSizeInBits(*RC))
682         continue;
683 
684       switch ((*I)->getID()) {
685       case PPC::VSSRCRegClassID:
686         return Subtarget.hasP8Vector() ? *I : DefaultSuperclass;
687       case PPC::VSFRCRegClassID:
688       case PPC::VSRCRegClassID:
689         return *I;
690       case PPC::VSRpRCRegClassID:
691         return Subtarget.pairedVectorMemops() ? *I : DefaultSuperclass;
692       case PPC::ACCRCRegClassID:
693       case PPC::UACCRCRegClassID:
694         return Subtarget.hasMMA() ? *I : DefaultSuperclass;
695       }
696     }
697   }
698 
699   return DefaultSuperclass;
700 }
701 
702 //===----------------------------------------------------------------------===//
703 // Stack Frame Processing methods
704 //===----------------------------------------------------------------------===//
705 
706 /// lowerDynamicAlloc - Generate the code for allocating an object in the
707 /// current frame.  The sequence of code will be in the general form
708 ///
709 ///   addi   R0, SP, \#frameSize ; get the address of the previous frame
710 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
711 ///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
712 ///
713 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
714   // Get the instruction.
715   MachineInstr &MI = *II;
716   // Get the instruction's basic block.
717   MachineBasicBlock &MBB = *MI.getParent();
718   // Get the basic block's function.
719   MachineFunction &MF = *MBB.getParent();
720   // Get the frame info.
721   MachineFrameInfo &MFI = MF.getFrameInfo();
722   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
723   // Get the instruction info.
724   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
725   // Determine whether 64-bit pointers are used.
726   bool LP64 = TM.isPPC64();
727   DebugLoc dl = MI.getDebugLoc();
728 
729   // Get the maximum call stack size.
730   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
731   Align MaxAlign = MFI.getMaxAlign();
732   assert(isAligned(MaxAlign, maxCallFrameSize) &&
733          "Maximum call-frame size not sufficiently aligned");
734   (void)MaxAlign;
735 
736   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
737   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
738   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
739   bool KillNegSizeReg = MI.getOperand(1).isKill();
740   Register NegSizeReg = MI.getOperand(1).getReg();
741 
742   prepareDynamicAlloca(II, NegSizeReg, KillNegSizeReg, Reg);
743   // Grow the stack and update the stack pointer link, then determine the
744   // address of new allocated space.
745   if (LP64) {
746     BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
747         .addReg(Reg, RegState::Kill)
748         .addReg(PPC::X1)
749         .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
750     BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
751         .addReg(PPC::X1)
752         .addImm(maxCallFrameSize);
753   } else {
754     BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
755         .addReg(Reg, RegState::Kill)
756         .addReg(PPC::R1)
757         .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
758     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
759         .addReg(PPC::R1)
760         .addImm(maxCallFrameSize);
761   }
762 
763   // Discard the DYNALLOC instruction.
764   MBB.erase(II);
765 }
766 
767 /// To accomplish dynamic stack allocation, we have to calculate exact size
768 /// subtracted from the stack pointer according alignment information and get
769 /// previous frame pointer.
770 void PPCRegisterInfo::prepareDynamicAlloca(MachineBasicBlock::iterator II,
771                                            Register &NegSizeReg,
772                                            bool &KillNegSizeReg,
773                                            Register &FramePointer) const {
774   // Get the instruction.
775   MachineInstr &MI = *II;
776   // Get the instruction's basic block.
777   MachineBasicBlock &MBB = *MI.getParent();
778   // Get the basic block's function.
779   MachineFunction &MF = *MBB.getParent();
780   // Get the frame info.
781   MachineFrameInfo &MFI = MF.getFrameInfo();
782   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
783   // Get the instruction info.
784   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
785   // Determine whether 64-bit pointers are used.
786   bool LP64 = TM.isPPC64();
787   DebugLoc dl = MI.getDebugLoc();
788   // Get the total frame size.
789   unsigned FrameSize = MFI.getStackSize();
790 
791   // Get stack alignments.
792   const PPCFrameLowering *TFI = getFrameLowering(MF);
793   Align TargetAlign = TFI->getStackAlign();
794   Align MaxAlign = MFI.getMaxAlign();
795 
796   // Determine the previous frame's address.  If FrameSize can't be
797   // represented as 16 bits or we need special alignment, then we load the
798   // previous frame's address from 0(SP).  Why not do an addis of the hi?
799   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
800   // Constructing the constant and adding would take 3 instructions.
801   // Fortunately, a frame greater than 32K is rare.
802   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
803   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
804 
805   if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
806     if (LP64)
807       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), FramePointer)
808           .addReg(PPC::X31)
809           .addImm(FrameSize);
810     else
811       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), FramePointer)
812           .addReg(PPC::R31)
813           .addImm(FrameSize);
814   } else if (LP64) {
815     BuildMI(MBB, II, dl, TII.get(PPC::LD), FramePointer)
816         .addImm(0)
817         .addReg(PPC::X1);
818   } else {
819     BuildMI(MBB, II, dl, TII.get(PPC::LWZ), FramePointer)
820         .addImm(0)
821         .addReg(PPC::R1);
822   }
823   // Determine the actual NegSizeReg according to alignment info.
824   if (LP64) {
825     if (MaxAlign > TargetAlign) {
826       unsigned UnalNegSizeReg = NegSizeReg;
827       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
828 
829       // Unfortunately, there is no andi, only andi., and we can't insert that
830       // here because we might clobber cr0 while it is live.
831       BuildMI(MBB, II, dl, TII.get(PPC::LI8), NegSizeReg)
832           .addImm(~(MaxAlign.value() - 1));
833 
834       unsigned NegSizeReg1 = NegSizeReg;
835       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
836       BuildMI(MBB, II, dl, TII.get(PPC::AND8), NegSizeReg)
837           .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
838           .addReg(NegSizeReg1, RegState::Kill);
839       KillNegSizeReg = true;
840     }
841   } else {
842     if (MaxAlign > TargetAlign) {
843       unsigned UnalNegSizeReg = NegSizeReg;
844       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
845 
846       // Unfortunately, there is no andi, only andi., and we can't insert that
847       // here because we might clobber cr0 while it is live.
848       BuildMI(MBB, II, dl, TII.get(PPC::LI), NegSizeReg)
849           .addImm(~(MaxAlign.value() - 1));
850 
851       unsigned NegSizeReg1 = NegSizeReg;
852       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
853       BuildMI(MBB, II, dl, TII.get(PPC::AND), NegSizeReg)
854           .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
855           .addReg(NegSizeReg1, RegState::Kill);
856       KillNegSizeReg = true;
857     }
858   }
859 }
860 
861 void PPCRegisterInfo::lowerPrepareProbedAlloca(
862     MachineBasicBlock::iterator II) const {
863   MachineInstr &MI = *II;
864   // Get the instruction's basic block.
865   MachineBasicBlock &MBB = *MI.getParent();
866   // Get the basic block's function.
867   MachineFunction &MF = *MBB.getParent();
868   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
869   // Get the instruction info.
870   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
871   // Determine whether 64-bit pointers are used.
872   bool LP64 = TM.isPPC64();
873   DebugLoc dl = MI.getDebugLoc();
874   Register FramePointer = MI.getOperand(0).getReg();
875   const Register ActualNegSizeReg = MI.getOperand(1).getReg();
876   bool KillNegSizeReg = MI.getOperand(2).isKill();
877   Register NegSizeReg = MI.getOperand(2).getReg();
878   const MCInstrDesc &CopyInst = TII.get(LP64 ? PPC::OR8 : PPC::OR);
879   // RegAllocator might allocate FramePointer and NegSizeReg in the same phyreg.
880   if (FramePointer == NegSizeReg) {
881     assert(KillNegSizeReg && "FramePointer is a def and NegSizeReg is an use, "
882                              "NegSizeReg should be killed");
883     // FramePointer is clobbered earlier than the use of NegSizeReg in
884     // prepareDynamicAlloca, save NegSizeReg in ActualNegSizeReg to avoid
885     // misuse.
886     BuildMI(MBB, II, dl, CopyInst, ActualNegSizeReg)
887         .addReg(NegSizeReg)
888         .addReg(NegSizeReg);
889     NegSizeReg = ActualNegSizeReg;
890     KillNegSizeReg = false;
891   }
892   prepareDynamicAlloca(II, NegSizeReg, KillNegSizeReg, FramePointer);
893   // NegSizeReg might be updated in prepareDynamicAlloca if MaxAlign >
894   // TargetAlign.
895   if (NegSizeReg != ActualNegSizeReg)
896     BuildMI(MBB, II, dl, CopyInst, ActualNegSizeReg)
897         .addReg(NegSizeReg)
898         .addReg(NegSizeReg);
899   MBB.erase(II);
900 }
901 
902 void PPCRegisterInfo::lowerDynamicAreaOffset(
903     MachineBasicBlock::iterator II) const {
904   // Get the instruction.
905   MachineInstr &MI = *II;
906   // Get the instruction's basic block.
907   MachineBasicBlock &MBB = *MI.getParent();
908   // Get the basic block's function.
909   MachineFunction &MF = *MBB.getParent();
910   // Get the frame info.
911   MachineFrameInfo &MFI = MF.getFrameInfo();
912   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
913   // Get the instruction info.
914   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
915 
916   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
917   bool is64Bit = TM.isPPC64();
918   DebugLoc dl = MI.getDebugLoc();
919   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI),
920           MI.getOperand(0).getReg())
921       .addImm(maxCallFrameSize);
922   MBB.erase(II);
923 }
924 
925 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
926 /// reserving a whole register (R0), we scrounge for one here. This generates
927 /// code like this:
928 ///
929 ///   mfcr rA                  ; Move the conditional register into GPR rA.
930 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
931 ///   stw rA, FI               ; Store rA to the frame.
932 ///
933 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
934                                       unsigned FrameIndex) const {
935   // Get the instruction.
936   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>
937   // Get the instruction's basic block.
938   MachineBasicBlock &MBB = *MI.getParent();
939   MachineFunction &MF = *MBB.getParent();
940   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
941   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
942   DebugLoc dl = MI.getDebugLoc();
943 
944   bool LP64 = TM.isPPC64();
945   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
946   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
947 
948   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
949   Register SrcReg = MI.getOperand(0).getReg();
950 
951   // We need to store the CR in the low 4-bits of the saved value. First, issue
952   // an MFOCRF to save all of the CRBits and, if needed, kill the SrcReg.
953   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
954       .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
955 
956   // If the saved register wasn't CR0, shift the bits left so that they are in
957   // CR0's slot.
958   if (SrcReg != PPC::CR0) {
959     Register Reg1 = Reg;
960     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
961 
962     // rlwinm rA, rA, ShiftBits, 0, 31.
963     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
964       .addReg(Reg1, RegState::Kill)
965       .addImm(getEncodingValue(SrcReg) * 4)
966       .addImm(0)
967       .addImm(31);
968   }
969 
970   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
971                     .addReg(Reg, RegState::Kill),
972                     FrameIndex);
973 
974   // Discard the pseudo instruction.
975   MBB.erase(II);
976 }
977 
978 void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
979                                       unsigned FrameIndex) const {
980   // Get the instruction.
981   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CR <offset>
982   // Get the instruction's basic block.
983   MachineBasicBlock &MBB = *MI.getParent();
984   MachineFunction &MF = *MBB.getParent();
985   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
986   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
987   DebugLoc dl = MI.getDebugLoc();
988 
989   bool LP64 = TM.isPPC64();
990   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
991   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
992 
993   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
994   Register DestReg = MI.getOperand(0).getReg();
995   assert(MI.definesRegister(DestReg) &&
996     "RESTORE_CR does not define its destination");
997 
998   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
999                               Reg), FrameIndex);
1000 
1001   // If the reloaded register isn't CR0, shift the bits right so that they are
1002   // in the right CR's slot.
1003   if (DestReg != PPC::CR0) {
1004     Register Reg1 = Reg;
1005     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
1006 
1007     unsigned ShiftBits = getEncodingValue(DestReg)*4;
1008     // rlwinm r11, r11, 32-ShiftBits, 0, 31.
1009     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
1010              .addReg(Reg1, RegState::Kill).addImm(32-ShiftBits).addImm(0)
1011              .addImm(31);
1012   }
1013 
1014   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF), DestReg)
1015              .addReg(Reg, RegState::Kill);
1016 
1017   // Discard the pseudo instruction.
1018   MBB.erase(II);
1019 }
1020 
1021 void PPCRegisterInfo::lowerCRBitSpilling(MachineBasicBlock::iterator II,
1022                                          unsigned FrameIndex) const {
1023   // Get the instruction.
1024   MachineInstr &MI = *II;       // ; SPILL_CRBIT <SrcReg>, <offset>
1025   // Get the instruction's basic block.
1026   MachineBasicBlock &MBB = *MI.getParent();
1027   MachineFunction &MF = *MBB.getParent();
1028   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1029   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1030   const TargetRegisterInfo* TRI = Subtarget.getRegisterInfo();
1031   DebugLoc dl = MI.getDebugLoc();
1032 
1033   bool LP64 = TM.isPPC64();
1034   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1035   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1036 
1037   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
1038   Register SrcReg = MI.getOperand(0).getReg();
1039 
1040   // Search up the BB to find the definition of the CR bit.
1041   MachineBasicBlock::reverse_iterator Ins = MI;
1042   MachineBasicBlock::reverse_iterator Rend = MBB.rend();
1043   ++Ins;
1044   unsigned CRBitSpillDistance = 0;
1045   bool SeenUse = false;
1046   for (; Ins != Rend; ++Ins) {
1047     // Definition found.
1048     if (Ins->modifiesRegister(SrcReg, TRI))
1049       break;
1050     // Use found.
1051     if (Ins->readsRegister(SrcReg, TRI))
1052       SeenUse = true;
1053     // Unable to find CR bit definition within maximum search distance.
1054     if (CRBitSpillDistance == MaxCRBitSpillDist) {
1055       Ins = MI;
1056       break;
1057     }
1058     // Skip debug instructions when counting CR bit spill distance.
1059     if (!Ins->isDebugInstr())
1060       CRBitSpillDistance++;
1061   }
1062 
1063   // Unable to find the definition of the CR bit in the MBB.
1064   if (Ins == MBB.rend())
1065     Ins = MI;
1066 
1067   bool SpillsKnownBit = false;
1068   // There is no need to extract the CR bit if its value is already known.
1069   switch (Ins->getOpcode()) {
1070   case PPC::CRUNSET:
1071     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LI8 : PPC::LI), Reg)
1072       .addImm(0);
1073     SpillsKnownBit = true;
1074     break;
1075   case PPC::CRSET:
1076     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LIS8 : PPC::LIS), Reg)
1077       .addImm(-32768);
1078     SpillsKnownBit = true;
1079     break;
1080   default:
1081     // On Power10, we can use SETNBC to spill all CR bits. SETNBC will set all
1082     // bits (specifically, it produces a -1 if the CR bit is set). Ultimately,
1083     // the bit that is of importance to us is bit 32 (bit 0 of a 32-bit
1084     // register), and SETNBC will set this.
1085     if (Subtarget.isISA3_1()) {
1086       BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::SETNBC8 : PPC::SETNBC), Reg)
1087           .addReg(SrcReg, RegState::Undef);
1088       break;
1089     }
1090 
1091     // On Power9, we can use SETB to extract the LT bit. This only works for
1092     // the LT bit since SETB produces -1/1/0 for LT/GT/<neither>. So the value
1093     // of the bit we care about (32-bit sign bit) will be set to the value of
1094     // the LT bit (regardless of the other bits in the CR field).
1095     if (Subtarget.isISA3_0()) {
1096       if (SrcReg == PPC::CR0LT || SrcReg == PPC::CR1LT ||
1097           SrcReg == PPC::CR2LT || SrcReg == PPC::CR3LT ||
1098           SrcReg == PPC::CR4LT || SrcReg == PPC::CR5LT ||
1099           SrcReg == PPC::CR6LT || SrcReg == PPC::CR7LT) {
1100         BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::SETB8 : PPC::SETB), Reg)
1101           .addReg(getCRFromCRBit(SrcReg), RegState::Undef);
1102         break;
1103       }
1104     }
1105 
1106     // We need to move the CR field that contains the CR bit we are spilling.
1107     // The super register may not be explicitly defined (i.e. it can be defined
1108     // by a CR-logical that only defines the subreg) so we state that the CR
1109     // field is undef. Also, in order to preserve the kill flag on the CR bit,
1110     // we add it as an implicit use.
1111     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
1112       .addReg(getCRFromCRBit(SrcReg), RegState::Undef)
1113       .addReg(SrcReg,
1114               RegState::Implicit | getKillRegState(MI.getOperand(0).isKill()));
1115 
1116     // If the saved register wasn't CR0LT, shift the bits left so that the bit
1117     // to store is the first one. Mask all but that bit.
1118     Register Reg1 = Reg;
1119     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
1120 
1121     // rlwinm rA, rA, ShiftBits, 0, 0.
1122     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
1123       .addReg(Reg1, RegState::Kill)
1124       .addImm(getEncodingValue(SrcReg))
1125       .addImm(0).addImm(0);
1126   }
1127   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
1128                     .addReg(Reg, RegState::Kill),
1129                     FrameIndex);
1130 
1131   bool KillsCRBit = MI.killsRegister(SrcReg, TRI);
1132   // Discard the pseudo instruction.
1133   MBB.erase(II);
1134   if (SpillsKnownBit && KillsCRBit && !SeenUse) {
1135     Ins->setDesc(TII.get(PPC::UNENCODED_NOP));
1136     Ins->removeOperand(0);
1137   }
1138 }
1139 
1140 void PPCRegisterInfo::lowerCRBitRestore(MachineBasicBlock::iterator II,
1141                                       unsigned FrameIndex) const {
1142   // Get the instruction.
1143   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CRBIT <offset>
1144   // Get the instruction's basic block.
1145   MachineBasicBlock &MBB = *MI.getParent();
1146   MachineFunction &MF = *MBB.getParent();
1147   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1148   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1149   DebugLoc dl = MI.getDebugLoc();
1150 
1151   bool LP64 = TM.isPPC64();
1152   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1153   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1154 
1155   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
1156   Register DestReg = MI.getOperand(0).getReg();
1157   assert(MI.definesRegister(DestReg) &&
1158     "RESTORE_CRBIT does not define its destination");
1159 
1160   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
1161                               Reg), FrameIndex);
1162 
1163   BuildMI(MBB, II, dl, TII.get(TargetOpcode::IMPLICIT_DEF), DestReg);
1164 
1165   Register RegO = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
1166   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), RegO)
1167           .addReg(getCRFromCRBit(DestReg));
1168 
1169   unsigned ShiftBits = getEncodingValue(DestReg);
1170   // rlwimi r11, r10, 32-ShiftBits, ..., ...
1171   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWIMI8 : PPC::RLWIMI), RegO)
1172       .addReg(RegO, RegState::Kill)
1173       .addReg(Reg, RegState::Kill)
1174       .addImm(ShiftBits ? 32 - ShiftBits : 0)
1175       .addImm(ShiftBits)
1176       .addImm(ShiftBits);
1177 
1178   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF),
1179           getCRFromCRBit(DestReg))
1180       .addReg(RegO, RegState::Kill)
1181       // Make sure we have a use dependency all the way through this
1182       // sequence of instructions. We can't have the other bits in the CR
1183       // modified in between the mfocrf and the mtocrf.
1184       .addReg(getCRFromCRBit(DestReg), RegState::Implicit);
1185 
1186   // Discard the pseudo instruction.
1187   MBB.erase(II);
1188 }
1189 
1190 void PPCRegisterInfo::emitAccCopyInfo(MachineBasicBlock &MBB,
1191                                       MCRegister DestReg, MCRegister SrcReg) {
1192 #ifdef NDEBUG
1193   return;
1194 #else
1195   if (ReportAccMoves) {
1196     std::string Dest = PPC::ACCRCRegClass.contains(DestReg) ? "acc" : "uacc";
1197     std::string Src = PPC::ACCRCRegClass.contains(SrcReg) ? "acc" : "uacc";
1198     dbgs() << "Emitting copy from " << Src << " to " << Dest << ":\n";
1199     MBB.dump();
1200   }
1201 #endif
1202 }
1203 
1204 static void emitAccSpillRestoreInfo(MachineBasicBlock &MBB, bool IsPrimed,
1205                                     bool IsRestore) {
1206 #ifdef NDEBUG
1207   return;
1208 #else
1209   if (ReportAccMoves) {
1210     dbgs() << "Emitting " << (IsPrimed ? "acc" : "uacc") << " register "
1211            << (IsRestore ? "restore" : "spill") << ":\n";
1212     MBB.dump();
1213   }
1214 #endif
1215 }
1216 
1217 static void spillRegPairs(MachineBasicBlock &MBB,
1218                           MachineBasicBlock::iterator II, DebugLoc DL,
1219                           const TargetInstrInfo &TII, Register SrcReg,
1220                           unsigned FrameIndex, bool IsLittleEndian,
1221                           bool IsKilled, bool TwoPairs) {
1222   unsigned Offset = 0;
1223   if (TwoPairs)
1224     Offset = IsLittleEndian ? 48 : 0;
1225   else
1226     Offset = IsLittleEndian ? 16 : 0;
1227   Register Reg = (SrcReg > PPC::VSRp15) ? PPC::V0 + (SrcReg - PPC::VSRp16) * 2
1228                                         : PPC::VSL0 + (SrcReg - PPC::VSRp0) * 2;
1229   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXV))
1230                         .addReg(Reg, getKillRegState(IsKilled)),
1231                     FrameIndex, Offset);
1232   Offset += IsLittleEndian ? -16 : 16;
1233   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXV))
1234                         .addReg(Reg + 1, getKillRegState(IsKilled)),
1235                     FrameIndex, Offset);
1236   if (TwoPairs) {
1237     Offset += IsLittleEndian ? -16 : 16;
1238     addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXV))
1239                           .addReg(Reg + 2, getKillRegState(IsKilled)),
1240                       FrameIndex, Offset);
1241     Offset += IsLittleEndian ? -16 : 16;
1242     addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXV))
1243                           .addReg(Reg + 3, getKillRegState(IsKilled)),
1244                       FrameIndex, Offset);
1245   }
1246 }
1247 
1248 /// Remove any STXVP[X] instructions and split them out into a pair of
1249 /// STXV[X] instructions if --disable-auto-paired-vec-st is specified on
1250 /// the command line.
1251 void PPCRegisterInfo::lowerOctWordSpilling(MachineBasicBlock::iterator II,
1252                                            unsigned FrameIndex) const {
1253   assert(DisableAutoPairedVecSt &&
1254          "Expecting to do this only if paired vector stores are disabled.");
1255   MachineInstr &MI = *II; // STXVP <SrcReg>, <offset>
1256   MachineBasicBlock &MBB = *MI.getParent();
1257   MachineFunction &MF = *MBB.getParent();
1258   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1259   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1260   DebugLoc DL = MI.getDebugLoc();
1261   Register SrcReg = MI.getOperand(0).getReg();
1262   bool IsLittleEndian = Subtarget.isLittleEndian();
1263   bool IsKilled = MI.getOperand(0).isKill();
1264   spillRegPairs(MBB, II, DL, TII, SrcReg, FrameIndex, IsLittleEndian, IsKilled,
1265                 /* TwoPairs */ false);
1266   // Discard the original instruction.
1267   MBB.erase(II);
1268 }
1269 
1270 /// lowerACCSpilling - Generate the code for spilling the accumulator register.
1271 /// Similarly to other spills/reloads that use pseudo-ops, we do not actually
1272 /// eliminate the FrameIndex here nor compute the stack offset. We simply
1273 /// create a real instruction with an FI and rely on eliminateFrameIndex to
1274 /// handle the FI elimination.
1275 void PPCRegisterInfo::lowerACCSpilling(MachineBasicBlock::iterator II,
1276                                        unsigned FrameIndex) const {
1277   MachineInstr &MI = *II; // SPILL_ACC <SrcReg>, <offset>
1278   MachineBasicBlock &MBB = *MI.getParent();
1279   MachineFunction &MF = *MBB.getParent();
1280   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1281   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1282   DebugLoc DL = MI.getDebugLoc();
1283   Register SrcReg = MI.getOperand(0).getReg();
1284   bool IsKilled = MI.getOperand(0).isKill();
1285 
1286   bool IsPrimed = PPC::ACCRCRegClass.contains(SrcReg);
1287   Register Reg =
1288       PPC::VSRp0 + (SrcReg - (IsPrimed ? PPC::ACC0 : PPC::UACC0)) * 2;
1289   bool IsLittleEndian = Subtarget.isLittleEndian();
1290 
1291   emitAccSpillRestoreInfo(MBB, IsPrimed, false);
1292 
1293   // De-prime the register being spilled, create two stores for the pair
1294   // subregisters accounting for endianness and then re-prime the register if
1295   // it isn't killed.  This uses the Offset parameter to addFrameReference() to
1296   // adjust the offset of the store that is within the 64-byte stack slot.
1297   if (IsPrimed)
1298     BuildMI(MBB, II, DL, TII.get(PPC::XXMFACC), SrcReg).addReg(SrcReg);
1299   if (DisableAutoPairedVecSt)
1300     spillRegPairs(MBB, II, DL, TII, Reg, FrameIndex, IsLittleEndian, IsKilled,
1301                   /* TwoPairs */ true);
1302   else {
1303     addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXVP))
1304                           .addReg(Reg, getKillRegState(IsKilled)),
1305                       FrameIndex, IsLittleEndian ? 32 : 0);
1306     addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXVP))
1307                           .addReg(Reg + 1, getKillRegState(IsKilled)),
1308                       FrameIndex, IsLittleEndian ? 0 : 32);
1309   }
1310   if (IsPrimed && !IsKilled)
1311     BuildMI(MBB, II, DL, TII.get(PPC::XXMTACC), SrcReg).addReg(SrcReg);
1312 
1313   // Discard the pseudo instruction.
1314   MBB.erase(II);
1315 }
1316 
1317 /// lowerACCRestore - Generate the code to restore the accumulator register.
1318 void PPCRegisterInfo::lowerACCRestore(MachineBasicBlock::iterator II,
1319                                       unsigned FrameIndex) const {
1320   MachineInstr &MI = *II; // <DestReg> = RESTORE_ACC <offset>
1321   MachineBasicBlock &MBB = *MI.getParent();
1322   MachineFunction &MF = *MBB.getParent();
1323   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1324   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1325   DebugLoc DL = MI.getDebugLoc();
1326 
1327   Register DestReg = MI.getOperand(0).getReg();
1328   assert(MI.definesRegister(DestReg) &&
1329          "RESTORE_ACC does not define its destination");
1330 
1331   bool IsPrimed = PPC::ACCRCRegClass.contains(DestReg);
1332   Register Reg =
1333       PPC::VSRp0 + (DestReg - (IsPrimed ? PPC::ACC0 : PPC::UACC0)) * 2;
1334   bool IsLittleEndian = Subtarget.isLittleEndian();
1335 
1336   emitAccSpillRestoreInfo(MBB, IsPrimed, true);
1337 
1338   // Create two loads for the pair subregisters accounting for endianness and
1339   // then prime the accumulator register being restored.
1340   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LXVP), Reg),
1341                     FrameIndex, IsLittleEndian ? 32 : 0);
1342   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LXVP), Reg + 1),
1343                     FrameIndex, IsLittleEndian ? 0 : 32);
1344   if (IsPrimed)
1345     BuildMI(MBB, II, DL, TII.get(PPC::XXMTACC), DestReg).addReg(DestReg);
1346 
1347   // Discard the pseudo instruction.
1348   MBB.erase(II);
1349 }
1350 
1351 /// lowerQuadwordSpilling - Generate code to spill paired general register.
1352 void PPCRegisterInfo::lowerQuadwordSpilling(MachineBasicBlock::iterator II,
1353                                             unsigned FrameIndex) const {
1354   MachineInstr &MI = *II;
1355   MachineBasicBlock &MBB = *MI.getParent();
1356   MachineFunction &MF = *MBB.getParent();
1357   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1358   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1359   DebugLoc DL = MI.getDebugLoc();
1360 
1361   Register SrcReg = MI.getOperand(0).getReg();
1362   bool IsKilled = MI.getOperand(0).isKill();
1363 
1364   Register Reg = PPC::X0 + (SrcReg - PPC::G8p0) * 2;
1365   bool IsLittleEndian = Subtarget.isLittleEndian();
1366 
1367   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STD))
1368                         .addReg(Reg, getKillRegState(IsKilled)),
1369                     FrameIndex, IsLittleEndian ? 8 : 0);
1370   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STD))
1371                         .addReg(Reg + 1, getKillRegState(IsKilled)),
1372                     FrameIndex, IsLittleEndian ? 0 : 8);
1373 
1374   // Discard the pseudo instruction.
1375   MBB.erase(II);
1376 }
1377 
1378 /// lowerQuadwordRestore - Generate code to restore paired general register.
1379 void PPCRegisterInfo::lowerQuadwordRestore(MachineBasicBlock::iterator II,
1380                                            unsigned FrameIndex) const {
1381   MachineInstr &MI = *II;
1382   MachineBasicBlock &MBB = *MI.getParent();
1383   MachineFunction &MF = *MBB.getParent();
1384   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1385   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1386   DebugLoc DL = MI.getDebugLoc();
1387 
1388   Register DestReg = MI.getOperand(0).getReg();
1389   assert(MI.definesRegister(DestReg) &&
1390          "RESTORE_QUADWORD does not define its destination");
1391 
1392   Register Reg = PPC::X0 + (DestReg - PPC::G8p0) * 2;
1393   bool IsLittleEndian = Subtarget.isLittleEndian();
1394 
1395   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LD), Reg), FrameIndex,
1396                     IsLittleEndian ? 8 : 0);
1397   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LD), Reg + 1), FrameIndex,
1398                     IsLittleEndian ? 0 : 8);
1399 
1400   // Discard the pseudo instruction.
1401   MBB.erase(II);
1402 }
1403 
1404 bool PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
1405                                            Register Reg, int &FrameIdx) const {
1406   // For the nonvolatile condition registers (CR2, CR3, CR4) return true to
1407   // prevent allocating an additional frame slot.
1408   // For 64-bit ELF and AIX, the CR save area is in the linkage area at SP+8,
1409   // for 32-bit AIX the CR save area is in the linkage area at SP+4.
1410   // We have created a FrameIndex to that spill slot to keep the CalleSaveInfos
1411   // valid.
1412   // For 32-bit ELF, we have previously created the stack slot if needed, so
1413   // return its FrameIdx.
1414   if (PPC::CR2 <= Reg && Reg <= PPC::CR4) {
1415     FrameIdx = MF.getInfo<PPCFunctionInfo>()->getCRSpillFrameIndex();
1416     return true;
1417   }
1418   return false;
1419 }
1420 
1421 // If the offset must be a multiple of some value, return what that value is.
1422 static unsigned offsetMinAlignForOpcode(unsigned OpC) {
1423   switch (OpC) {
1424   default:
1425     return 1;
1426   case PPC::LWA:
1427   case PPC::LWA_32:
1428   case PPC::LD:
1429   case PPC::LDU:
1430   case PPC::STD:
1431   case PPC::STDU:
1432   case PPC::DFLOADf32:
1433   case PPC::DFLOADf64:
1434   case PPC::DFSTOREf32:
1435   case PPC::DFSTOREf64:
1436   case PPC::LXSD:
1437   case PPC::LXSSP:
1438   case PPC::STXSD:
1439   case PPC::STXSSP:
1440   case PPC::STQ:
1441     return 4;
1442   case PPC::EVLDD:
1443   case PPC::EVSTDD:
1444     return 8;
1445   case PPC::LXV:
1446   case PPC::STXV:
1447   case PPC::LQ:
1448   case PPC::LXVP:
1449   case PPC::STXVP:
1450     return 16;
1451   }
1452 }
1453 
1454 // If the offset must be a multiple of some value, return what that value is.
1455 static unsigned offsetMinAlign(const MachineInstr &MI) {
1456   unsigned OpC = MI.getOpcode();
1457   return offsetMinAlignForOpcode(OpC);
1458 }
1459 
1460 // Return the OffsetOperandNo given the FIOperandNum (and the instruction).
1461 static unsigned getOffsetONFromFION(const MachineInstr &MI,
1462                                     unsigned FIOperandNum) {
1463   // Take into account whether it's an add or mem instruction
1464   unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
1465   if (MI.isInlineAsm())
1466     OffsetOperandNo = FIOperandNum - 1;
1467   else if (MI.getOpcode() == TargetOpcode::STACKMAP ||
1468            MI.getOpcode() == TargetOpcode::PATCHPOINT)
1469     OffsetOperandNo = FIOperandNum + 1;
1470 
1471   return OffsetOperandNo;
1472 }
1473 
1474 void
1475 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
1476                                      int SPAdj, unsigned FIOperandNum,
1477                                      RegScavenger *RS) const {
1478   assert(SPAdj == 0 && "Unexpected");
1479 
1480   // Get the instruction.
1481   MachineInstr &MI = *II;
1482   // Get the instruction's basic block.
1483   MachineBasicBlock &MBB = *MI.getParent();
1484   // Get the basic block's function.
1485   MachineFunction &MF = *MBB.getParent();
1486   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1487   // Get the instruction info.
1488   const PPCInstrInfo &TII = *Subtarget.getInstrInfo();
1489   // Get the frame info.
1490   MachineFrameInfo &MFI = MF.getFrameInfo();
1491   DebugLoc dl = MI.getDebugLoc();
1492 
1493   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1494 
1495   // Get the frame index.
1496   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
1497 
1498   // Get the frame pointer save index.  Users of this index are primarily
1499   // DYNALLOC instructions.
1500   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1501   int FPSI = FI->getFramePointerSaveIndex();
1502   // Get the instruction opcode.
1503   unsigned OpC = MI.getOpcode();
1504 
1505   if ((OpC == PPC::DYNAREAOFFSET || OpC == PPC::DYNAREAOFFSET8)) {
1506     lowerDynamicAreaOffset(II);
1507     return;
1508   }
1509 
1510   // Special case for dynamic alloca.
1511   if (FPSI && FrameIndex == FPSI &&
1512       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
1513     lowerDynamicAlloc(II);
1514     return;
1515   }
1516 
1517   if (FPSI && FrameIndex == FPSI &&
1518       (OpC == PPC::PREPARE_PROBED_ALLOCA_64 ||
1519        OpC == PPC::PREPARE_PROBED_ALLOCA_32 ||
1520        OpC == PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 ||
1521        OpC == PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32)) {
1522     lowerPrepareProbedAlloca(II);
1523     return;
1524   }
1525 
1526   // Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
1527   if (OpC == PPC::SPILL_CR) {
1528     lowerCRSpilling(II, FrameIndex);
1529     return;
1530   } else if (OpC == PPC::RESTORE_CR) {
1531     lowerCRRestore(II, FrameIndex);
1532     return;
1533   } else if (OpC == PPC::SPILL_CRBIT) {
1534     lowerCRBitSpilling(II, FrameIndex);
1535     return;
1536   } else if (OpC == PPC::RESTORE_CRBIT) {
1537     lowerCRBitRestore(II, FrameIndex);
1538     return;
1539   } else if (OpC == PPC::SPILL_ACC || OpC == PPC::SPILL_UACC) {
1540     lowerACCSpilling(II, FrameIndex);
1541     return;
1542   } else if (OpC == PPC::RESTORE_ACC || OpC == PPC::RESTORE_UACC) {
1543     lowerACCRestore(II, FrameIndex);
1544     return;
1545   } else if (OpC == PPC::STXVP && DisableAutoPairedVecSt) {
1546     lowerOctWordSpilling(II, FrameIndex);
1547     return;
1548   } else if (OpC == PPC::SPILL_QUADWORD) {
1549     lowerQuadwordSpilling(II, FrameIndex);
1550     return;
1551   } else if (OpC == PPC::RESTORE_QUADWORD) {
1552     lowerQuadwordRestore(II, FrameIndex);
1553     return;
1554   }
1555 
1556   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
1557   MI.getOperand(FIOperandNum).ChangeToRegister(
1558     FrameIndex < 0 ? getBaseRegister(MF) : getFrameRegister(MF), false);
1559 
1560   // If the instruction is not present in ImmToIdxMap, then it has no immediate
1561   // form (and must be r+r).
1562   bool noImmForm = !MI.isInlineAsm() && OpC != TargetOpcode::STACKMAP &&
1563                    OpC != TargetOpcode::PATCHPOINT && !ImmToIdxMap.count(OpC);
1564 
1565   // Now add the frame object offset to the offset from r1.
1566   int64_t Offset = MFI.getObjectOffset(FrameIndex);
1567   Offset += MI.getOperand(OffsetOperandNo).getImm();
1568 
1569   // If we're not using a Frame Pointer that has been set to the value of the
1570   // SP before having the stack size subtracted from it, then add the stack size
1571   // to Offset to get the correct offset.
1572   // Naked functions have stack size 0, although getStackSize may not reflect
1573   // that because we didn't call all the pieces that compute it for naked
1574   // functions.
1575   if (!MF.getFunction().hasFnAttribute(Attribute::Naked)) {
1576     if (!(hasBasePointer(MF) && FrameIndex < 0))
1577       Offset += MFI.getStackSize();
1578   }
1579 
1580   // If we encounter an LXVP/STXVP with an offset that doesn't fit, we can
1581   // transform it to the prefixed version so we don't have to use the XForm.
1582   if ((OpC == PPC::LXVP || OpC == PPC::STXVP) &&
1583       (!isInt<16>(Offset) || (Offset % offsetMinAlign(MI)) != 0) &&
1584       Subtarget.hasPrefixInstrs()) {
1585     unsigned NewOpc = OpC == PPC::LXVP ? PPC::PLXVP : PPC::PSTXVP;
1586     MI.setDesc(TII.get(NewOpc));
1587     OpC = NewOpc;
1588   }
1589 
1590   // If we can, encode the offset directly into the instruction.  If this is a
1591   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
1592   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
1593   // clear can be encoded.  This is extremely uncommon, because normally you
1594   // only "std" to a stack slot that is at least 4-byte aligned, but it can
1595   // happen in invalid code.
1596   assert(OpC != PPC::DBG_VALUE &&
1597          "This should be handled in a target-independent way");
1598   // FIXME: This should be factored out to a separate function as prefixed
1599   // instructions add a number of opcodes for which we can use 34-bit imm.
1600   bool OffsetFitsMnemonic = (OpC == PPC::EVSTDD || OpC == PPC::EVLDD) ?
1601                             isUInt<8>(Offset) :
1602                             isInt<16>(Offset);
1603   if (TII.isPrefixed(MI.getOpcode()))
1604     OffsetFitsMnemonic = isInt<34>(Offset);
1605   if (!noImmForm && ((OffsetFitsMnemonic &&
1606                       ((Offset % offsetMinAlign(MI)) == 0)) ||
1607                      OpC == TargetOpcode::STACKMAP ||
1608                      OpC == TargetOpcode::PATCHPOINT)) {
1609     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1610     return;
1611   }
1612 
1613   // The offset doesn't fit into a single register, scavenge one to build the
1614   // offset in.
1615 
1616   bool is64Bit = TM.isPPC64();
1617   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1618   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1619   const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
1620   Register SRegHi = MF.getRegInfo().createVirtualRegister(RC),
1621            SReg = MF.getRegInfo().createVirtualRegister(RC);
1622   unsigned NewOpcode = 0u;
1623 
1624   // Insert a set of rA with the full offset value before the ld, st, or add
1625   if (isInt<16>(Offset))
1626     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI), SReg)
1627         .addImm(Offset);
1628   else if (isInt<32>(Offset)) {
1629     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
1630         .addImm(Offset >> 16);
1631     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
1632         .addReg(SRegHi, RegState::Kill)
1633         .addImm(Offset);
1634   } else {
1635     assert(is64Bit && "Huge stack is only supported on PPC64");
1636     TII.materializeImmPostRA(MBB, II, dl, SReg, Offset);
1637   }
1638 
1639   // Convert into indexed form of the instruction:
1640   //
1641   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
1642   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
1643   unsigned OperandBase;
1644 
1645   if (noImmForm)
1646     OperandBase = 1;
1647   else if (OpC != TargetOpcode::INLINEASM &&
1648            OpC != TargetOpcode::INLINEASM_BR) {
1649     assert(ImmToIdxMap.count(OpC) &&
1650            "No indexed form of load or store available!");
1651     NewOpcode = ImmToIdxMap.find(OpC)->second;
1652     MI.setDesc(TII.get(NewOpcode));
1653     OperandBase = 1;
1654   } else {
1655     OperandBase = OffsetOperandNo;
1656   }
1657 
1658   Register StackReg = MI.getOperand(FIOperandNum).getReg();
1659   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
1660   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
1661 
1662   // Since these are not real X-Form instructions, we must
1663   // add the registers and access 0(NewReg) rather than
1664   // emitting the X-Form pseudo.
1665   if (NewOpcode == PPC::LQX_PSEUDO || NewOpcode == PPC::STQX_PSEUDO) {
1666     assert(is64Bit && "Quadword loads/stores only supported in 64-bit mode");
1667     Register NewReg = MF.getRegInfo().createVirtualRegister(&PPC::G8RCRegClass);
1668     BuildMI(MBB, II, dl, TII.get(PPC::ADD8), NewReg)
1669         .addReg(SReg, RegState::Kill)
1670         .addReg(StackReg);
1671     MI.setDesc(TII.get(NewOpcode == PPC::LQX_PSEUDO ? PPC::LQ : PPC::STQ));
1672     MI.getOperand(OperandBase + 1).ChangeToRegister(NewReg, false);
1673     MI.getOperand(OperandBase).ChangeToImmediate(0);
1674   }
1675 }
1676 
1677 Register PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
1678   const PPCFrameLowering *TFI = getFrameLowering(MF);
1679 
1680   if (!TM.isPPC64())
1681     return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
1682   else
1683     return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
1684 }
1685 
1686 Register PPCRegisterInfo::getBaseRegister(const MachineFunction &MF) const {
1687   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1688   if (!hasBasePointer(MF))
1689     return getFrameRegister(MF);
1690 
1691   if (TM.isPPC64())
1692     return PPC::X30;
1693 
1694   if (Subtarget.isSVR4ABI() && TM.isPositionIndependent())
1695     return PPC::R29;
1696 
1697   return PPC::R30;
1698 }
1699 
1700 bool PPCRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
1701   if (!EnableBasePointer)
1702     return false;
1703   if (AlwaysBasePointer)
1704     return true;
1705 
1706   // If we need to realign the stack, then the stack pointer can no longer
1707   // serve as an offset into the caller's stack space. As a result, we need a
1708   // base pointer.
1709   return hasStackRealignment(MF);
1710 }
1711 
1712 /// Returns true if the instruction's frame index
1713 /// reference would be better served by a base register other than FP
1714 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
1715 /// references it should create new base registers for.
1716 bool PPCRegisterInfo::
1717 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
1718   assert(Offset < 0 && "Local offset must be negative");
1719 
1720   // It's the load/store FI references that cause issues, as it can be difficult
1721   // to materialize the offset if it won't fit in the literal field. Estimate
1722   // based on the size of the local frame and some conservative assumptions
1723   // about the rest of the stack frame (note, this is pre-regalloc, so
1724   // we don't know everything for certain yet) whether this offset is likely
1725   // to be out of range of the immediate. Return true if so.
1726 
1727   // We only generate virtual base registers for loads and stores that have
1728   // an r+i form. Return false for everything else.
1729   unsigned OpC = MI->getOpcode();
1730   if (!ImmToIdxMap.count(OpC))
1731     return false;
1732 
1733   // Don't generate a new virtual base register just to add zero to it.
1734   if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
1735       MI->getOperand(2).getImm() == 0)
1736     return false;
1737 
1738   MachineBasicBlock &MBB = *MI->getParent();
1739   MachineFunction &MF = *MBB.getParent();
1740   const PPCFrameLowering *TFI = getFrameLowering(MF);
1741   unsigned StackEst = TFI->determineFrameLayout(MF, true);
1742 
1743   // If we likely don't need a stack frame, then we probably don't need a
1744   // virtual base register either.
1745   if (!StackEst)
1746     return false;
1747 
1748   // Estimate an offset from the stack pointer.
1749   // The incoming offset is relating to the SP at the start of the function,
1750   // but when we access the local it'll be relative to the SP after local
1751   // allocation, so adjust our SP-relative offset by that allocation size.
1752   Offset += StackEst;
1753 
1754   // The frame pointer will point to the end of the stack, so estimate the
1755   // offset as the difference between the object offset and the FP location.
1756   return !isFrameOffsetLegal(MI, getBaseRegister(MF), Offset);
1757 }
1758 
1759 /// Insert defining instruction(s) for BaseReg to
1760 /// be a pointer to FrameIdx at the beginning of the basic block.
1761 Register PPCRegisterInfo::materializeFrameBaseRegister(MachineBasicBlock *MBB,
1762                                                        int FrameIdx,
1763                                                        int64_t Offset) const {
1764   unsigned ADDriOpc = TM.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
1765 
1766   MachineBasicBlock::iterator Ins = MBB->begin();
1767   DebugLoc DL;                  // Defaults to "unknown"
1768   if (Ins != MBB->end())
1769     DL = Ins->getDebugLoc();
1770 
1771   const MachineFunction &MF = *MBB->getParent();
1772   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1773   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1774   const MCInstrDesc &MCID = TII.get(ADDriOpc);
1775   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1776   const TargetRegisterClass *RC = getPointerRegClass(MF);
1777   Register BaseReg = MRI.createVirtualRegister(RC);
1778   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
1779 
1780   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
1781     .addFrameIndex(FrameIdx).addImm(Offset);
1782 
1783   return BaseReg;
1784 }
1785 
1786 void PPCRegisterInfo::resolveFrameIndex(MachineInstr &MI, Register BaseReg,
1787                                         int64_t Offset) const {
1788   unsigned FIOperandNum = 0;
1789   while (!MI.getOperand(FIOperandNum).isFI()) {
1790     ++FIOperandNum;
1791     assert(FIOperandNum < MI.getNumOperands() &&
1792            "Instr doesn't have FrameIndex operand!");
1793   }
1794 
1795   MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
1796   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1797   Offset += MI.getOperand(OffsetOperandNo).getImm();
1798   MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1799 
1800   MachineBasicBlock &MBB = *MI.getParent();
1801   MachineFunction &MF = *MBB.getParent();
1802   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1803   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1804   const MCInstrDesc &MCID = MI.getDesc();
1805   MachineRegisterInfo &MRI = MF.getRegInfo();
1806   MRI.constrainRegClass(BaseReg,
1807                         TII.getRegClass(MCID, FIOperandNum, this, MF));
1808 }
1809 
1810 bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
1811                                          Register BaseReg,
1812                                          int64_t Offset) const {
1813   unsigned FIOperandNum = 0;
1814   while (!MI->getOperand(FIOperandNum).isFI()) {
1815     ++FIOperandNum;
1816     assert(FIOperandNum < MI->getNumOperands() &&
1817            "Instr doesn't have FrameIndex operand!");
1818   }
1819 
1820   unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
1821   Offset += MI->getOperand(OffsetOperandNo).getImm();
1822 
1823   return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
1824          MI->getOpcode() == TargetOpcode::STACKMAP ||
1825          MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1826          (isInt<16>(Offset) && (Offset % offsetMinAlign(*MI)) == 0);
1827 }
1828