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