xref: /llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp (revision 6215f49b8f2fa479535ec27a0f029081ac394100)
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 
138 /// getPointerRegClass - Return the register class to use to hold pointers.
139 /// This is used for addressing modes.
140 const TargetRegisterClass *
141 PPCRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
142                                                                        const {
143   // Note that PPCInstrInfo::FoldImmediate also directly uses this Kind value
144   // when it checks for ZERO folding.
145   if (Kind == 1) {
146     if (TM.isPPC64())
147       return &PPC::G8RC_NOX0RegClass;
148     return &PPC::GPRC_NOR0RegClass;
149   }
150 
151   if (TM.isPPC64())
152     return &PPC::G8RCRegClass;
153   return &PPC::GPRCRegClass;
154 }
155 
156 const MCPhysReg*
157 PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
158   const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>();
159   if (MF->getFunction().getCallingConv() == CallingConv::AnyReg) {
160     if (!TM.isPPC64() && Subtarget.isAIXABI())
161       report_fatal_error("AnyReg unimplemented on 32-bit AIX.");
162     if (Subtarget.hasVSX()) {
163       if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI())
164         return CSR_64_AllRegs_AIX_Dflt_VSX_SaveList;
165       return CSR_64_AllRegs_VSX_SaveList;
166     }
167     if (Subtarget.hasAltivec()) {
168       if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI())
169         return CSR_64_AllRegs_AIX_Dflt_Altivec_SaveList;
170       return CSR_64_AllRegs_Altivec_SaveList;
171     }
172     return CSR_64_AllRegs_SaveList;
173   }
174 
175   // On PPC64, we might need to save r2 (but only if it is not reserved).
176   // We do not need to treat R2 as callee-saved when using PC-Relative calls
177   // because any direct uses of R2 will cause it to be reserved. If the function
178   // is a leaf or the only uses of R2 are implicit uses for calls, the calls
179   // will use the @notoc relocation which will cause this function to set the
180   // st_other bit to 1, thereby communicating to its caller that it arbitrarily
181   // clobbers the TOC.
182   bool SaveR2 = MF->getRegInfo().isAllocatable(PPC::X2) &&
183                 !Subtarget.isUsingPCRelativeCalls();
184 
185   // Cold calling convention CSRs.
186   if (MF->getFunction().getCallingConv() == CallingConv::Cold) {
187     if (Subtarget.isAIXABI())
188       report_fatal_error("Cold calling unimplemented on AIX.");
189     if (TM.isPPC64()) {
190       if (Subtarget.hasAltivec())
191         return SaveR2 ? CSR_SVR64_ColdCC_R2_Altivec_SaveList
192                       : CSR_SVR64_ColdCC_Altivec_SaveList;
193       return SaveR2 ? CSR_SVR64_ColdCC_R2_SaveList
194                     : CSR_SVR64_ColdCC_SaveList;
195     }
196     // 32-bit targets.
197     if (Subtarget.hasAltivec())
198       return CSR_SVR32_ColdCC_Altivec_SaveList;
199     else if (Subtarget.hasSPE())
200       return CSR_SVR32_ColdCC_SPE_SaveList;
201     return CSR_SVR32_ColdCC_SaveList;
202   }
203   // Standard calling convention CSRs.
204   if (TM.isPPC64()) {
205     if (Subtarget.hasAltivec() &&
206         (!Subtarget.isAIXABI() || TM.getAIXExtendedAltivecABI())) {
207       return SaveR2 ? CSR_PPC64_R2_Altivec_SaveList
208                     : CSR_PPC64_Altivec_SaveList;
209     }
210     return SaveR2 ? CSR_PPC64_R2_SaveList : CSR_PPC64_SaveList;
211   }
212   // 32-bit targets.
213   if (Subtarget.isAIXABI()) {
214     if (Subtarget.hasAltivec())
215       return TM.getAIXExtendedAltivecABI() ? CSR_AIX32_Altivec_SaveList
216                                            : CSR_AIX32_SaveList;
217     return CSR_AIX32_SaveList;
218   }
219   if (Subtarget.hasAltivec())
220     return CSR_SVR432_Altivec_SaveList;
221   else if (Subtarget.hasSPE())
222     return CSR_SVR432_SPE_SaveList;
223   return CSR_SVR432_SaveList;
224 }
225 
226 const uint32_t *
227 PPCRegisterInfo::getCallPreservedMask(const MachineFunction &MF,
228                                       CallingConv::ID CC) const {
229   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
230   if (CC == CallingConv::AnyReg) {
231     if (Subtarget.hasVSX()) {
232       if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI())
233         return CSR_64_AllRegs_AIX_Dflt_VSX_RegMask;
234       return CSR_64_AllRegs_VSX_RegMask;
235     }
236     if (Subtarget.hasAltivec()) {
237       if (Subtarget.isAIXABI() && !TM.getAIXExtendedAltivecABI())
238         return CSR_64_AllRegs_AIX_Dflt_Altivec_RegMask;
239       return CSR_64_AllRegs_Altivec_RegMask;
240     }
241     return CSR_64_AllRegs_RegMask;
242   }
243 
244   if (Subtarget.isAIXABI()) {
245     return TM.isPPC64()
246                ? ((Subtarget.hasAltivec() && TM.getAIXExtendedAltivecABI())
247                       ? CSR_PPC64_Altivec_RegMask
248                       : CSR_PPC64_RegMask)
249                : ((Subtarget.hasAltivec() && TM.getAIXExtendedAltivecABI())
250                       ? CSR_AIX32_Altivec_RegMask
251                       : CSR_AIX32_RegMask);
252   }
253 
254   if (CC == CallingConv::Cold) {
255     return TM.isPPC64() ? (Subtarget.hasAltivec() ? CSR_SVR64_ColdCC_Altivec_RegMask
256                                                   : CSR_SVR64_ColdCC_RegMask)
257                         : (Subtarget.hasAltivec() ? CSR_SVR32_ColdCC_Altivec_RegMask
258                                                   : (Subtarget.hasSPE()
259                                                   ? CSR_SVR32_ColdCC_SPE_RegMask
260                                                   : CSR_SVR32_ColdCC_RegMask));
261   }
262 
263   return TM.isPPC64() ? (Subtarget.hasAltivec() ? CSR_PPC64_Altivec_RegMask
264                                                 : CSR_PPC64_RegMask)
265                       : (Subtarget.hasAltivec()
266                              ? CSR_SVR432_Altivec_RegMask
267                              : (Subtarget.hasSPE() ? CSR_SVR432_SPE_RegMask
268                                                    : CSR_SVR432_RegMask));
269 }
270 
271 const uint32_t*
272 PPCRegisterInfo::getNoPreservedMask() const {
273   return CSR_NoRegs_RegMask;
274 }
275 
276 void PPCRegisterInfo::adjustStackMapLiveOutMask(uint32_t *Mask) const {
277   for (unsigned PseudoReg : {PPC::ZERO, PPC::ZERO8, PPC::RM})
278     Mask[PseudoReg / 32] &= ~(1u << (PseudoReg % 32));
279 }
280 
281 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
282   BitVector Reserved(getNumRegs());
283   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
284   const PPCFrameLowering *TFI = getFrameLowering(MF);
285 
286   // The ZERO register is not really a register, but the representation of r0
287   // when used in instructions that treat r0 as the constant 0.
288   markSuperRegs(Reserved, PPC::ZERO);
289 
290   // The FP register is also not really a register, but is the representation
291   // of the frame pointer register used by ISD::FRAMEADDR.
292   markSuperRegs(Reserved, PPC::FP);
293 
294   // The BP register is also not really a register, but is the representation
295   // of the base pointer register used by setjmp.
296   markSuperRegs(Reserved, PPC::BP);
297 
298   // The counter registers must be reserved so that counter-based loops can
299   // be correctly formed (and the mtctr instructions are not DCE'd).
300   markSuperRegs(Reserved, PPC::CTR);
301   markSuperRegs(Reserved, PPC::CTR8);
302 
303   markSuperRegs(Reserved, PPC::R1);
304   markSuperRegs(Reserved, PPC::LR);
305   markSuperRegs(Reserved, PPC::LR8);
306   markSuperRegs(Reserved, PPC::RM);
307 
308   markSuperRegs(Reserved, PPC::VRSAVE);
309 
310   // The SVR4 ABI reserves r2 and r13
311   if (Subtarget.isSVR4ABI()) {
312     // We only reserve r2 if we need to use the TOC pointer. If we have no
313     // explicit uses of the TOC pointer (meaning we're a leaf function with
314     // no constant-pool loads, etc.) and we have no potential uses inside an
315     // inline asm block, then we can treat r2 has an ordinary callee-saved
316     // register.
317     const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
318     if (!TM.isPPC64() || FuncInfo->usesTOCBasePtr() || MF.hasInlineAsm())
319       markSuperRegs(Reserved, PPC::R2);  // System-reserved register
320     markSuperRegs(Reserved, PPC::R13); // Small Data Area pointer register
321   }
322 
323   // Always reserve r2 on AIX for now.
324   // TODO: Make r2 allocatable on AIX/XCOFF for some leaf functions.
325   if (Subtarget.isAIXABI())
326     markSuperRegs(Reserved, PPC::R2);  // System-reserved register
327 
328   // On PPC64, r13 is the thread pointer. Never allocate this register.
329   if (TM.isPPC64())
330     markSuperRegs(Reserved, PPC::R13);
331 
332   if (TFI->needsFP(MF))
333     markSuperRegs(Reserved, PPC::R31);
334 
335   bool IsPositionIndependent = TM.isPositionIndependent();
336   if (hasBasePointer(MF)) {
337     if (Subtarget.is32BitELFABI() && IsPositionIndependent)
338       markSuperRegs(Reserved, PPC::R29);
339     else
340       markSuperRegs(Reserved, PPC::R30);
341   }
342 
343   if (Subtarget.is32BitELFABI() && IsPositionIndependent)
344     markSuperRegs(Reserved, PPC::R30);
345 
346   // Reserve Altivec registers when Altivec is unavailable.
347   if (!Subtarget.hasAltivec())
348     for (TargetRegisterClass::iterator I = PPC::VRRCRegClass.begin(),
349          IE = PPC::VRRCRegClass.end(); I != IE; ++I)
350       markSuperRegs(Reserved, *I);
351 
352   if (Subtarget.isAIXABI() && Subtarget.hasAltivec() &&
353       !TM.getAIXExtendedAltivecABI()) {
354     //  In the AIX default Altivec ABI, vector registers VR20-VR31 are reserved
355     //  and cannot be used.
356     for (auto Reg : CSR_Altivec_SaveList) {
357       if (Reg == 0)
358         break;
359       markSuperRegs(Reserved, Reg);
360       for (MCRegAliasIterator AS(Reg, this, true); AS.isValid(); ++AS) {
361         Reserved.set(*AS);
362       }
363     }
364   }
365 
366   assert(checkAllSuperRegsMarked(Reserved));
367   return Reserved;
368 }
369 
370 bool PPCRegisterInfo::requiresFrameIndexScavenging(const MachineFunction &MF) const {
371   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
372   const PPCInstrInfo *InstrInfo =  Subtarget.getInstrInfo();
373   const MachineFrameInfo &MFI = MF.getFrameInfo();
374   const std::vector<CalleeSavedInfo> &Info = MFI.getCalleeSavedInfo();
375 
376   LLVM_DEBUG(dbgs() << "requiresFrameIndexScavenging for " << MF.getName()
377                     << ".\n");
378   // If the callee saved info is invalid we have to default to true for safety.
379   if (!MFI.isCalleeSavedInfoValid()) {
380     LLVM_DEBUG(dbgs() << "TRUE - Invalid callee saved info.\n");
381     return true;
382   }
383 
384   // We will require the use of X-Forms because the frame is larger than what
385   // can be represented in signed 16 bits that fit in the immediate of a D-Form.
386   // If we need an X-Form then we need a register to store the address offset.
387   unsigned FrameSize = MFI.getStackSize();
388   // Signed 16 bits means that the FrameSize cannot be more than 15 bits.
389   if (FrameSize & ~0x7FFF) {
390     LLVM_DEBUG(dbgs() << "TRUE - Frame size is too large for D-Form.\n");
391     return true;
392   }
393 
394   // The callee saved info is valid so it can be traversed.
395   // Checking for registers that need saving that do not have load or store
396   // forms where the address offset is an immediate.
397   for (unsigned i = 0; i < Info.size(); i++) {
398     // If the spill is to a register no scavenging is required.
399     if (Info[i].isSpilledToReg())
400       continue;
401 
402     int FrIdx = Info[i].getFrameIdx();
403     unsigned Reg = Info[i].getReg();
404 
405     const TargetRegisterClass *RC = getMinimalPhysRegClass(Reg);
406     unsigned Opcode = InstrInfo->getStoreOpcodeForSpill(RC);
407     if (!MFI.isFixedObjectIndex(FrIdx)) {
408       // This is not a fixed object. If it requires alignment then we may still
409       // need to use the XForm.
410       if (offsetMinAlignForOpcode(Opcode) > 1) {
411         LLVM_DEBUG(dbgs() << "Memory Operand: " << InstrInfo->getName(Opcode)
412                           << " for register " << printReg(Reg, this) << ".\n");
413         LLVM_DEBUG(dbgs() << "TRUE - Not fixed frame object that requires "
414                           << "alignment.\n");
415         return true;
416       }
417     }
418 
419     // This is eiher:
420     // 1) A fixed frame index object which we know are aligned so
421     // as long as we have a valid DForm/DSForm/DQForm (non XForm) we don't
422     // need to consider the alignment here.
423     // 2) A not fixed object but in that case we now know that the min required
424     // alignment is no more than 1 based on the previous check.
425     if (InstrInfo->isXFormMemOp(Opcode)) {
426       LLVM_DEBUG(dbgs() << "Memory Operand: " << InstrInfo->getName(Opcode)
427                         << " for register " << printReg(Reg, this) << ".\n");
428       LLVM_DEBUG(dbgs() << "TRUE - Memory operand is X-Form.\n");
429       return true;
430     }
431   }
432   LLVM_DEBUG(dbgs() << "FALSE - Scavenging is not required.\n");
433   return false;
434 }
435 
436 bool PPCRegisterInfo::isCallerPreservedPhysReg(MCRegister PhysReg,
437                                                const MachineFunction &MF) const {
438   assert(Register::isPhysicalRegister(PhysReg));
439   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
440   const MachineFrameInfo &MFI = MF.getFrameInfo();
441 
442   if (!Subtarget.is64BitELFABI() && !Subtarget.isAIXABI())
443     return false;
444   if (PhysReg == Subtarget.getTOCPointerRegister())
445     // X2/R2 is guaranteed to be preserved within a function if it is reserved.
446     // The reason it's reserved is that it's the TOC pointer (and the function
447     // uses the TOC). In functions where it isn't reserved (i.e. leaf functions
448     // with no TOC access), we can't claim that it is preserved.
449     return (getReservedRegs(MF).test(PhysReg));
450   if (StackPtrConst && PhysReg == Subtarget.getStackPointerRegister() &&
451       !MFI.hasVarSizedObjects() && !MFI.hasOpaqueSPAdjustment())
452     // The value of the stack pointer does not change within a function after
453     // the prologue and before the epilogue if there are no dynamic allocations
454     // and no inline asm which clobbers X1/R1.
455     return true;
456   return false;
457 }
458 
459 unsigned PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
460                                               MachineFunction &MF) const {
461   const PPCFrameLowering *TFI = getFrameLowering(MF);
462   const unsigned DefaultSafety = 1;
463 
464   switch (RC->getID()) {
465   default:
466     return 0;
467   case PPC::G8RC_NOX0RegClassID:
468   case PPC::GPRC_NOR0RegClassID:
469   case PPC::SPERCRegClassID:
470   case PPC::G8RCRegClassID:
471   case PPC::GPRCRegClassID: {
472     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
473     return 32 - FP - DefaultSafety;
474   }
475   case PPC::F4RCRegClassID:
476   case PPC::F8RCRegClassID:
477   case PPC::VSLRCRegClassID:
478     return 32 - DefaultSafety;
479   case PPC::VFRCRegClassID:
480   case PPC::VRRCRegClassID: {
481     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
482     // Vector registers VR20-VR31 are reserved and cannot be used in the default
483     // Altivec ABI on AIX.
484     if (!TM.getAIXExtendedAltivecABI() && Subtarget.isAIXABI())
485       return 20 - DefaultSafety;
486   }
487     return 32 - DefaultSafety;
488   case PPC::VSFRCRegClassID:
489   case PPC::VSSRCRegClassID:
490   case PPC::VSRCRegClassID: {
491     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
492     if (!TM.getAIXExtendedAltivecABI() && Subtarget.isAIXABI())
493       // Vector registers VR20-VR31 are reserved and cannot be used in the
494       // default Altivec ABI on AIX.
495       return 52 - DefaultSafety;
496   }
497     return 64 - DefaultSafety;
498   case PPC::CRRCRegClassID:
499     return 8 - DefaultSafety;
500   }
501 }
502 
503 const TargetRegisterClass *
504 PPCRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC,
505                                            const MachineFunction &MF) const {
506   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
507   if (Subtarget.hasVSX()) {
508     // With VSX, we can inflate various sub-register classes to the full VSX
509     // register set.
510 
511     // For Power9 we allow the user to enable GPR to vector spills.
512     // FIXME: Currently limited to spilling GP8RC. A follow on patch will add
513     // support to spill GPRC.
514     if (TM.isELFv2ABI() || Subtarget.isAIXABI()) {
515       if (Subtarget.hasP9Vector() && EnableGPRToVecSpills &&
516           RC == &PPC::G8RCRegClass) {
517         InflateGP8RC++;
518         return &PPC::SPILLTOVSRRCRegClass;
519       }
520       if (RC == &PPC::GPRCRegClass && EnableGPRToVecSpills)
521         InflateGPRC++;
522     }
523     if (RC == &PPC::F8RCRegClass)
524       return &PPC::VSFRCRegClass;
525     else if (RC == &PPC::VRRCRegClass)
526       return &PPC::VSRCRegClass;
527     else if (RC == &PPC::F4RCRegClass && Subtarget.hasP8Vector())
528       return &PPC::VSSRCRegClass;
529   }
530 
531   return TargetRegisterInfo::getLargestLegalSuperClass(RC, MF);
532 }
533 
534 //===----------------------------------------------------------------------===//
535 // Stack Frame Processing methods
536 //===----------------------------------------------------------------------===//
537 
538 /// lowerDynamicAlloc - Generate the code for allocating an object in the
539 /// current frame.  The sequence of code will be in the general form
540 ///
541 ///   addi   R0, SP, \#frameSize ; get the address of the previous frame
542 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
543 ///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
544 ///
545 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
546   // Get the instruction.
547   MachineInstr &MI = *II;
548   // Get the instruction's basic block.
549   MachineBasicBlock &MBB = *MI.getParent();
550   // Get the basic block's function.
551   MachineFunction &MF = *MBB.getParent();
552   // Get the frame info.
553   MachineFrameInfo &MFI = MF.getFrameInfo();
554   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
555   // Get the instruction info.
556   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
557   // Determine whether 64-bit pointers are used.
558   bool LP64 = TM.isPPC64();
559   DebugLoc dl = MI.getDebugLoc();
560 
561   // Get the maximum call stack size.
562   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
563   Align MaxAlign = MFI.getMaxAlign();
564   assert(isAligned(MaxAlign, maxCallFrameSize) &&
565          "Maximum call-frame size not sufficiently aligned");
566   (void)MaxAlign;
567 
568   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
569   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
570   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
571   bool KillNegSizeReg = MI.getOperand(1).isKill();
572   Register NegSizeReg = MI.getOperand(1).getReg();
573 
574   prepareDynamicAlloca(II, NegSizeReg, KillNegSizeReg, Reg);
575   // Grow the stack and update the stack pointer link, then determine the
576   // address of new allocated space.
577   if (LP64) {
578     BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
579         .addReg(Reg, RegState::Kill)
580         .addReg(PPC::X1)
581         .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
582     BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
583         .addReg(PPC::X1)
584         .addImm(maxCallFrameSize);
585   } else {
586     BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
587         .addReg(Reg, RegState::Kill)
588         .addReg(PPC::R1)
589         .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
590     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
591         .addReg(PPC::R1)
592         .addImm(maxCallFrameSize);
593   }
594 
595   // Discard the DYNALLOC instruction.
596   MBB.erase(II);
597 }
598 
599 /// To accomplish dynamic stack allocation, we have to calculate exact size
600 /// subtracted from the stack pointer according alignment information and get
601 /// previous frame pointer.
602 void PPCRegisterInfo::prepareDynamicAlloca(MachineBasicBlock::iterator II,
603                                            Register &NegSizeReg,
604                                            bool &KillNegSizeReg,
605                                            Register &FramePointer) const {
606   // Get the instruction.
607   MachineInstr &MI = *II;
608   // Get the instruction's basic block.
609   MachineBasicBlock &MBB = *MI.getParent();
610   // Get the basic block's function.
611   MachineFunction &MF = *MBB.getParent();
612   // Get the frame info.
613   MachineFrameInfo &MFI = MF.getFrameInfo();
614   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
615   // Get the instruction info.
616   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
617   // Determine whether 64-bit pointers are used.
618   bool LP64 = TM.isPPC64();
619   DebugLoc dl = MI.getDebugLoc();
620   // Get the total frame size.
621   unsigned FrameSize = MFI.getStackSize();
622 
623   // Get stack alignments.
624   const PPCFrameLowering *TFI = getFrameLowering(MF);
625   Align TargetAlign = TFI->getStackAlign();
626   Align MaxAlign = MFI.getMaxAlign();
627 
628   // Determine the previous frame's address.  If FrameSize can't be
629   // represented as 16 bits or we need special alignment, then we load the
630   // previous frame's address from 0(SP).  Why not do an addis of the hi?
631   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
632   // Constructing the constant and adding would take 3 instructions.
633   // Fortunately, a frame greater than 32K is rare.
634   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
635   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
636 
637   if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
638     if (LP64)
639       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), FramePointer)
640           .addReg(PPC::X31)
641           .addImm(FrameSize);
642     else
643       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), FramePointer)
644           .addReg(PPC::R31)
645           .addImm(FrameSize);
646   } else if (LP64) {
647     BuildMI(MBB, II, dl, TII.get(PPC::LD), FramePointer)
648         .addImm(0)
649         .addReg(PPC::X1);
650   } else {
651     BuildMI(MBB, II, dl, TII.get(PPC::LWZ), FramePointer)
652         .addImm(0)
653         .addReg(PPC::R1);
654   }
655   // Determine the actual NegSizeReg according to alignment info.
656   if (LP64) {
657     if (MaxAlign > TargetAlign) {
658       unsigned UnalNegSizeReg = NegSizeReg;
659       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
660 
661       // Unfortunately, there is no andi, only andi., and we can't insert that
662       // here because we might clobber cr0 while it is live.
663       BuildMI(MBB, II, dl, TII.get(PPC::LI8), NegSizeReg)
664           .addImm(~(MaxAlign.value() - 1));
665 
666       unsigned NegSizeReg1 = NegSizeReg;
667       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
668       BuildMI(MBB, II, dl, TII.get(PPC::AND8), NegSizeReg)
669           .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
670           .addReg(NegSizeReg1, RegState::Kill);
671       KillNegSizeReg = true;
672     }
673   } else {
674     if (MaxAlign > TargetAlign) {
675       unsigned UnalNegSizeReg = NegSizeReg;
676       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
677 
678       // Unfortunately, there is no andi, only andi., and we can't insert that
679       // here because we might clobber cr0 while it is live.
680       BuildMI(MBB, II, dl, TII.get(PPC::LI), NegSizeReg)
681           .addImm(~(MaxAlign.value() - 1));
682 
683       unsigned NegSizeReg1 = NegSizeReg;
684       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
685       BuildMI(MBB, II, dl, TII.get(PPC::AND), NegSizeReg)
686           .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
687           .addReg(NegSizeReg1, RegState::Kill);
688       KillNegSizeReg = true;
689     }
690   }
691 }
692 
693 void PPCRegisterInfo::lowerPrepareProbedAlloca(
694     MachineBasicBlock::iterator II) const {
695   MachineInstr &MI = *II;
696   // Get the instruction's basic block.
697   MachineBasicBlock &MBB = *MI.getParent();
698   // Get the basic block's function.
699   MachineFunction &MF = *MBB.getParent();
700   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
701   // Get the instruction info.
702   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
703   // Determine whether 64-bit pointers are used.
704   bool LP64 = TM.isPPC64();
705   DebugLoc dl = MI.getDebugLoc();
706   Register FramePointer = MI.getOperand(0).getReg();
707   const Register ActualNegSizeReg = MI.getOperand(1).getReg();
708   bool KillNegSizeReg = MI.getOperand(2).isKill();
709   Register NegSizeReg = MI.getOperand(2).getReg();
710   const MCInstrDesc &CopyInst = TII.get(LP64 ? PPC::OR8 : PPC::OR);
711   // RegAllocator might allocate FramePointer and NegSizeReg in the same phyreg.
712   if (FramePointer == NegSizeReg) {
713     assert(KillNegSizeReg && "FramePointer is a def and NegSizeReg is an use, "
714                              "NegSizeReg should be killed");
715     // FramePointer is clobbered earlier than the use of NegSizeReg in
716     // prepareDynamicAlloca, save NegSizeReg in ActualNegSizeReg to avoid
717     // misuse.
718     BuildMI(MBB, II, dl, CopyInst, ActualNegSizeReg)
719         .addReg(NegSizeReg)
720         .addReg(NegSizeReg);
721     NegSizeReg = ActualNegSizeReg;
722     KillNegSizeReg = false;
723   }
724   prepareDynamicAlloca(II, NegSizeReg, KillNegSizeReg, FramePointer);
725   // NegSizeReg might be updated in prepareDynamicAlloca if MaxAlign >
726   // TargetAlign.
727   if (NegSizeReg != ActualNegSizeReg)
728     BuildMI(MBB, II, dl, CopyInst, ActualNegSizeReg)
729         .addReg(NegSizeReg)
730         .addReg(NegSizeReg);
731   MBB.erase(II);
732 }
733 
734 void PPCRegisterInfo::lowerDynamicAreaOffset(
735     MachineBasicBlock::iterator II) const {
736   // Get the instruction.
737   MachineInstr &MI = *II;
738   // Get the instruction's basic block.
739   MachineBasicBlock &MBB = *MI.getParent();
740   // Get the basic block's function.
741   MachineFunction &MF = *MBB.getParent();
742   // Get the frame info.
743   MachineFrameInfo &MFI = MF.getFrameInfo();
744   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
745   // Get the instruction info.
746   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
747 
748   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
749   bool is64Bit = TM.isPPC64();
750   DebugLoc dl = MI.getDebugLoc();
751   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI),
752           MI.getOperand(0).getReg())
753       .addImm(maxCallFrameSize);
754   MBB.erase(II);
755 }
756 
757 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
758 /// reserving a whole register (R0), we scrounge for one here. This generates
759 /// code like this:
760 ///
761 ///   mfcr rA                  ; Move the conditional register into GPR rA.
762 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
763 ///   stw rA, FI               ; Store rA to the frame.
764 ///
765 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
766                                       unsigned FrameIndex) const {
767   // Get the instruction.
768   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>
769   // Get the instruction's basic block.
770   MachineBasicBlock &MBB = *MI.getParent();
771   MachineFunction &MF = *MBB.getParent();
772   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
773   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
774   DebugLoc dl = MI.getDebugLoc();
775 
776   bool LP64 = TM.isPPC64();
777   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
778   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
779 
780   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
781   Register SrcReg = MI.getOperand(0).getReg();
782 
783   // We need to store the CR in the low 4-bits of the saved value. First, issue
784   // an MFOCRF to save all of the CRBits and, if needed, kill the SrcReg.
785   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
786       .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
787 
788   // If the saved register wasn't CR0, shift the bits left so that they are in
789   // CR0's slot.
790   if (SrcReg != PPC::CR0) {
791     Register Reg1 = Reg;
792     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
793 
794     // rlwinm rA, rA, ShiftBits, 0, 31.
795     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
796       .addReg(Reg1, RegState::Kill)
797       .addImm(getEncodingValue(SrcReg) * 4)
798       .addImm(0)
799       .addImm(31);
800   }
801 
802   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
803                     .addReg(Reg, RegState::Kill),
804                     FrameIndex);
805 
806   // Discard the pseudo instruction.
807   MBB.erase(II);
808 }
809 
810 void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
811                                       unsigned FrameIndex) const {
812   // Get the instruction.
813   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CR <offset>
814   // Get the instruction's basic block.
815   MachineBasicBlock &MBB = *MI.getParent();
816   MachineFunction &MF = *MBB.getParent();
817   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
818   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
819   DebugLoc dl = MI.getDebugLoc();
820 
821   bool LP64 = TM.isPPC64();
822   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
823   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
824 
825   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
826   Register DestReg = MI.getOperand(0).getReg();
827   assert(MI.definesRegister(DestReg) &&
828     "RESTORE_CR does not define its destination");
829 
830   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
831                               Reg), FrameIndex);
832 
833   // If the reloaded register isn't CR0, shift the bits right so that they are
834   // in the right CR's slot.
835   if (DestReg != PPC::CR0) {
836     Register Reg1 = Reg;
837     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
838 
839     unsigned ShiftBits = getEncodingValue(DestReg)*4;
840     // rlwinm r11, r11, 32-ShiftBits, 0, 31.
841     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
842              .addReg(Reg1, RegState::Kill).addImm(32-ShiftBits).addImm(0)
843              .addImm(31);
844   }
845 
846   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF), DestReg)
847              .addReg(Reg, RegState::Kill);
848 
849   // Discard the pseudo instruction.
850   MBB.erase(II);
851 }
852 
853 void PPCRegisterInfo::lowerCRBitSpilling(MachineBasicBlock::iterator II,
854                                          unsigned FrameIndex) const {
855   // Get the instruction.
856   MachineInstr &MI = *II;       // ; SPILL_CRBIT <SrcReg>, <offset>
857   // Get the instruction's basic block.
858   MachineBasicBlock &MBB = *MI.getParent();
859   MachineFunction &MF = *MBB.getParent();
860   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
861   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
862   const TargetRegisterInfo* TRI = Subtarget.getRegisterInfo();
863   DebugLoc dl = MI.getDebugLoc();
864 
865   bool LP64 = TM.isPPC64();
866   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
867   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
868 
869   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
870   Register SrcReg = MI.getOperand(0).getReg();
871 
872   // Search up the BB to find the definition of the CR bit.
873   MachineBasicBlock::reverse_iterator Ins = MI;
874   MachineBasicBlock::reverse_iterator Rend = MBB.rend();
875   ++Ins;
876   unsigned CRBitSpillDistance = 0;
877   bool SeenUse = false;
878   for (; Ins != Rend; ++Ins) {
879     // Definition found.
880     if (Ins->modifiesRegister(SrcReg, TRI))
881       break;
882     // Use found.
883     if (Ins->readsRegister(SrcReg, TRI))
884       SeenUse = true;
885     // Unable to find CR bit definition within maximum search distance.
886     if (CRBitSpillDistance == MaxCRBitSpillDist) {
887       Ins = MI;
888       break;
889     }
890     // Skip debug instructions when counting CR bit spill distance.
891     if (!Ins->isDebugInstr())
892       CRBitSpillDistance++;
893   }
894 
895   // Unable to find the definition of the CR bit in the MBB.
896   if (Ins == MBB.rend())
897     Ins = MI;
898 
899   bool SpillsKnownBit = false;
900   // There is no need to extract the CR bit if its value is already known.
901   switch (Ins->getOpcode()) {
902   case PPC::CRUNSET:
903     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LI8 : PPC::LI), Reg)
904       .addImm(0);
905     SpillsKnownBit = true;
906     break;
907   case PPC::CRSET:
908     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LIS8 : PPC::LIS), Reg)
909       .addImm(-32768);
910     SpillsKnownBit = true;
911     break;
912   default:
913     // On Power10, we can use SETNBC to spill all CR bits. SETNBC will set all
914     // bits (specifically, it produces a -1 if the CR bit is set). Ultimately,
915     // the bit that is of importance to us is bit 32 (bit 0 of a 32-bit
916     // register), and SETNBC will set this.
917     if (Subtarget.isISA3_1()) {
918       BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::SETNBC8 : PPC::SETNBC), Reg)
919           .addReg(SrcReg, RegState::Undef);
920       break;
921     }
922 
923     // On Power9, we can use SETB to extract the LT bit. This only works for
924     // the LT bit since SETB produces -1/1/0 for LT/GT/<neither>. So the value
925     // of the bit we care about (32-bit sign bit) will be set to the value of
926     // the LT bit (regardless of the other bits in the CR field).
927     if (Subtarget.isISA3_0()) {
928       if (SrcReg == PPC::CR0LT || SrcReg == PPC::CR1LT ||
929           SrcReg == PPC::CR2LT || SrcReg == PPC::CR3LT ||
930           SrcReg == PPC::CR4LT || SrcReg == PPC::CR5LT ||
931           SrcReg == PPC::CR6LT || SrcReg == PPC::CR7LT) {
932         BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::SETB8 : PPC::SETB), Reg)
933           .addReg(getCRFromCRBit(SrcReg), RegState::Undef);
934         break;
935       }
936     }
937 
938     // We need to move the CR field that contains the CR bit we are spilling.
939     // The super register may not be explicitly defined (i.e. it can be defined
940     // by a CR-logical that only defines the subreg) so we state that the CR
941     // field is undef. Also, in order to preserve the kill flag on the CR bit,
942     // we add it as an implicit use.
943     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
944       .addReg(getCRFromCRBit(SrcReg), RegState::Undef)
945       .addReg(SrcReg,
946               RegState::Implicit | getKillRegState(MI.getOperand(0).isKill()));
947 
948     // If the saved register wasn't CR0LT, shift the bits left so that the bit
949     // to store is the first one. Mask all but that bit.
950     Register Reg1 = Reg;
951     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
952 
953     // rlwinm rA, rA, ShiftBits, 0, 0.
954     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
955       .addReg(Reg1, RegState::Kill)
956       .addImm(getEncodingValue(SrcReg))
957       .addImm(0).addImm(0);
958   }
959   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
960                     .addReg(Reg, RegState::Kill),
961                     FrameIndex);
962 
963   bool KillsCRBit = MI.killsRegister(SrcReg, TRI);
964   // Discard the pseudo instruction.
965   MBB.erase(II);
966   if (SpillsKnownBit && KillsCRBit && !SeenUse) {
967     Ins->setDesc(TII.get(PPC::UNENCODED_NOP));
968     Ins->RemoveOperand(0);
969   }
970 }
971 
972 void PPCRegisterInfo::lowerCRBitRestore(MachineBasicBlock::iterator II,
973                                       unsigned FrameIndex) const {
974   // Get the instruction.
975   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CRBIT <offset>
976   // Get the instruction's basic block.
977   MachineBasicBlock &MBB = *MI.getParent();
978   MachineFunction &MF = *MBB.getParent();
979   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
980   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
981   DebugLoc dl = MI.getDebugLoc();
982 
983   bool LP64 = TM.isPPC64();
984   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
985   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
986 
987   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
988   Register DestReg = MI.getOperand(0).getReg();
989   assert(MI.definesRegister(DestReg) &&
990     "RESTORE_CRBIT does not define its destination");
991 
992   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
993                               Reg), FrameIndex);
994 
995   BuildMI(MBB, II, dl, TII.get(TargetOpcode::IMPLICIT_DEF), DestReg);
996 
997   Register RegO = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
998   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), RegO)
999           .addReg(getCRFromCRBit(DestReg));
1000 
1001   unsigned ShiftBits = getEncodingValue(DestReg);
1002   // rlwimi r11, r10, 32-ShiftBits, ..., ...
1003   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWIMI8 : PPC::RLWIMI), RegO)
1004       .addReg(RegO, RegState::Kill)
1005       .addReg(Reg, RegState::Kill)
1006       .addImm(ShiftBits ? 32 - ShiftBits : 0)
1007       .addImm(ShiftBits)
1008       .addImm(ShiftBits);
1009 
1010   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF),
1011           getCRFromCRBit(DestReg))
1012       .addReg(RegO, RegState::Kill)
1013       // Make sure we have a use dependency all the way through this
1014       // sequence of instructions. We can't have the other bits in the CR
1015       // modified in between the mfocrf and the mtocrf.
1016       .addReg(getCRFromCRBit(DestReg), RegState::Implicit);
1017 
1018   // Discard the pseudo instruction.
1019   MBB.erase(II);
1020 }
1021 
1022 void PPCRegisterInfo::emitAccCopyInfo(MachineBasicBlock &MBB,
1023                                       MCRegister DestReg, MCRegister SrcReg) {
1024 #ifdef NDEBUG
1025   return;
1026 #else
1027   if (ReportAccMoves) {
1028     std::string Dest = PPC::ACCRCRegClass.contains(DestReg) ? "acc" : "uacc";
1029     std::string Src = PPC::ACCRCRegClass.contains(SrcReg) ? "acc" : "uacc";
1030     dbgs() << "Emitting copy from " << Src << " to " << Dest << ":\n";
1031     MBB.dump();
1032   }
1033 #endif
1034 }
1035 
1036 static void emitAccSpillRestoreInfo(MachineBasicBlock &MBB, bool IsPrimed,
1037                                     bool IsRestore) {
1038 #ifdef NDEBUG
1039   return;
1040 #else
1041   if (ReportAccMoves) {
1042     dbgs() << "Emitting " << (IsPrimed ? "acc" : "uacc") << " register "
1043            << (IsRestore ? "restore" : "spill") << ":\n";
1044     MBB.dump();
1045   }
1046 #endif
1047 }
1048 
1049 /// lowerACCSpilling - Generate the code for spilling the accumulator register.
1050 /// Similarly to other spills/reloads that use pseudo-ops, we do not actually
1051 /// eliminate the FrameIndex here nor compute the stack offset. We simply
1052 /// create a real instruction with an FI and rely on eliminateFrameIndex to
1053 /// handle the FI elimination.
1054 void PPCRegisterInfo::lowerACCSpilling(MachineBasicBlock::iterator II,
1055                                        unsigned FrameIndex) const {
1056   MachineInstr &MI = *II; // SPILL_ACC <SrcReg>, <offset>
1057   MachineBasicBlock &MBB = *MI.getParent();
1058   MachineFunction &MF = *MBB.getParent();
1059   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1060   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1061   DebugLoc DL = MI.getDebugLoc();
1062   Register SrcReg = MI.getOperand(0).getReg();
1063   bool IsKilled = MI.getOperand(0).isKill();
1064 
1065   bool IsPrimed = PPC::ACCRCRegClass.contains(SrcReg);
1066   Register Reg =
1067       PPC::VSRp0 + (SrcReg - (IsPrimed ? PPC::ACC0 : PPC::UACC0)) * 2;
1068   bool IsLittleEndian = Subtarget.isLittleEndian();
1069 
1070   emitAccSpillRestoreInfo(MBB, IsPrimed, false);
1071 
1072   // De-prime the register being spilled, create two stores for the pair
1073   // subregisters accounting for endianness and then re-prime the register if
1074   // it isn't killed.  This uses the Offset parameter to addFrameReference() to
1075   // adjust the offset of the store that is within the 64-byte stack slot.
1076   if (IsPrimed)
1077     BuildMI(MBB, II, DL, TII.get(PPC::XXMFACC), SrcReg).addReg(SrcReg);
1078   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXVP))
1079                         .addReg(Reg, getKillRegState(IsKilled)),
1080                     FrameIndex, IsLittleEndian ? 32 : 0);
1081   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::STXVP))
1082                         .addReg(Reg + 1, getKillRegState(IsKilled)),
1083                     FrameIndex, IsLittleEndian ? 0 : 32);
1084   if (IsPrimed && !IsKilled)
1085     BuildMI(MBB, II, DL, TII.get(PPC::XXMTACC), SrcReg).addReg(SrcReg);
1086 
1087   // Discard the pseudo instruction.
1088   MBB.erase(II);
1089 }
1090 
1091 /// lowerACCRestore - Generate the code to restore the accumulator register.
1092 void PPCRegisterInfo::lowerACCRestore(MachineBasicBlock::iterator II,
1093                                       unsigned FrameIndex) const {
1094   MachineInstr &MI = *II; // <DestReg> = RESTORE_ACC <offset>
1095   MachineBasicBlock &MBB = *MI.getParent();
1096   MachineFunction &MF = *MBB.getParent();
1097   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1098   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1099   DebugLoc DL = MI.getDebugLoc();
1100 
1101   Register DestReg = MI.getOperand(0).getReg();
1102   assert(MI.definesRegister(DestReg) &&
1103          "RESTORE_ACC does not define its destination");
1104 
1105   bool IsPrimed = PPC::ACCRCRegClass.contains(DestReg);
1106   Register Reg =
1107       PPC::VSRp0 + (DestReg - (IsPrimed ? PPC::ACC0 : PPC::UACC0)) * 2;
1108   bool IsLittleEndian = Subtarget.isLittleEndian();
1109 
1110   emitAccSpillRestoreInfo(MBB, IsPrimed, true);
1111 
1112   // Create two loads for the pair subregisters accounting for endianness and
1113   // then prime the accumulator register being restored.
1114   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LXVP), Reg),
1115                     FrameIndex, IsLittleEndian ? 32 : 0);
1116   addFrameReference(BuildMI(MBB, II, DL, TII.get(PPC::LXVP), Reg + 1),
1117                     FrameIndex, IsLittleEndian ? 0 : 32);
1118   if (IsPrimed)
1119     BuildMI(MBB, II, DL, TII.get(PPC::XXMTACC), DestReg).addReg(DestReg);
1120 
1121   // Discard the pseudo instruction.
1122   MBB.erase(II);
1123 }
1124 
1125 bool PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
1126                                            Register Reg, int &FrameIdx) const {
1127   // For the nonvolatile condition registers (CR2, CR3, CR4) return true to
1128   // prevent allocating an additional frame slot.
1129   // For 64-bit ELF and AIX, the CR save area is in the linkage area at SP+8,
1130   // for 32-bit AIX the CR save area is in the linkage area at SP+4.
1131   // We have created a FrameIndex to that spill slot to keep the CalleSaveInfos
1132   // valid.
1133   // For 32-bit ELF, we have previously created the stack slot if needed, so
1134   // return its FrameIdx.
1135   if (PPC::CR2 <= Reg && Reg <= PPC::CR4) {
1136     FrameIdx = MF.getInfo<PPCFunctionInfo>()->getCRSpillFrameIndex();
1137     return true;
1138   }
1139   return false;
1140 }
1141 
1142 // If the offset must be a multiple of some value, return what that value is.
1143 static unsigned offsetMinAlignForOpcode(unsigned OpC) {
1144   switch (OpC) {
1145   default:
1146     return 1;
1147   case PPC::LWA:
1148   case PPC::LWA_32:
1149   case PPC::LD:
1150   case PPC::LDU:
1151   case PPC::STD:
1152   case PPC::STDU:
1153   case PPC::DFLOADf32:
1154   case PPC::DFLOADf64:
1155   case PPC::DFSTOREf32:
1156   case PPC::DFSTOREf64:
1157   case PPC::LXSD:
1158   case PPC::LXSSP:
1159   case PPC::STXSD:
1160   case PPC::STXSSP:
1161     return 4;
1162   case PPC::EVLDD:
1163   case PPC::EVSTDD:
1164     return 8;
1165   case PPC::LXV:
1166   case PPC::STXV:
1167     return 16;
1168   }
1169 }
1170 
1171 // If the offset must be a multiple of some value, return what that value is.
1172 static unsigned offsetMinAlign(const MachineInstr &MI) {
1173   unsigned OpC = MI.getOpcode();
1174   return offsetMinAlignForOpcode(OpC);
1175 }
1176 
1177 // Return the OffsetOperandNo given the FIOperandNum (and the instruction).
1178 static unsigned getOffsetONFromFION(const MachineInstr &MI,
1179                                     unsigned FIOperandNum) {
1180   // Take into account whether it's an add or mem instruction
1181   unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
1182   if (MI.isInlineAsm())
1183     OffsetOperandNo = FIOperandNum - 1;
1184   else if (MI.getOpcode() == TargetOpcode::STACKMAP ||
1185            MI.getOpcode() == TargetOpcode::PATCHPOINT)
1186     OffsetOperandNo = FIOperandNum + 1;
1187 
1188   return OffsetOperandNo;
1189 }
1190 
1191 void
1192 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
1193                                      int SPAdj, unsigned FIOperandNum,
1194                                      RegScavenger *RS) const {
1195   assert(SPAdj == 0 && "Unexpected");
1196 
1197   // Get the instruction.
1198   MachineInstr &MI = *II;
1199   // Get the instruction's basic block.
1200   MachineBasicBlock &MBB = *MI.getParent();
1201   // Get the basic block's function.
1202   MachineFunction &MF = *MBB.getParent();
1203   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1204   // Get the instruction info.
1205   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1206   // Get the frame info.
1207   MachineFrameInfo &MFI = MF.getFrameInfo();
1208   DebugLoc dl = MI.getDebugLoc();
1209 
1210   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1211 
1212   // Get the frame index.
1213   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
1214 
1215   // Get the frame pointer save index.  Users of this index are primarily
1216   // DYNALLOC instructions.
1217   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1218   int FPSI = FI->getFramePointerSaveIndex();
1219   // Get the instruction opcode.
1220   unsigned OpC = MI.getOpcode();
1221 
1222   if ((OpC == PPC::DYNAREAOFFSET || OpC == PPC::DYNAREAOFFSET8)) {
1223     lowerDynamicAreaOffset(II);
1224     return;
1225   }
1226 
1227   // Special case for dynamic alloca.
1228   if (FPSI && FrameIndex == FPSI &&
1229       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
1230     lowerDynamicAlloc(II);
1231     return;
1232   }
1233 
1234   if (FPSI && FrameIndex == FPSI &&
1235       (OpC == PPC::PREPARE_PROBED_ALLOCA_64 ||
1236        OpC == PPC::PREPARE_PROBED_ALLOCA_32 ||
1237        OpC == PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64 ||
1238        OpC == PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32)) {
1239     lowerPrepareProbedAlloca(II);
1240     return;
1241   }
1242 
1243   // Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
1244   if (OpC == PPC::SPILL_CR) {
1245     lowerCRSpilling(II, FrameIndex);
1246     return;
1247   } else if (OpC == PPC::RESTORE_CR) {
1248     lowerCRRestore(II, FrameIndex);
1249     return;
1250   } else if (OpC == PPC::SPILL_CRBIT) {
1251     lowerCRBitSpilling(II, FrameIndex);
1252     return;
1253   } else if (OpC == PPC::RESTORE_CRBIT) {
1254     lowerCRBitRestore(II, FrameIndex);
1255     return;
1256   } else if (OpC == PPC::SPILL_ACC || OpC == PPC::SPILL_UACC) {
1257     lowerACCSpilling(II, FrameIndex);
1258     return;
1259   } else if (OpC == PPC::RESTORE_ACC || OpC == PPC::RESTORE_UACC) {
1260     lowerACCRestore(II, FrameIndex);
1261     return;
1262   }
1263 
1264   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
1265   MI.getOperand(FIOperandNum).ChangeToRegister(
1266     FrameIndex < 0 ? getBaseRegister(MF) : getFrameRegister(MF), false);
1267 
1268   // If the instruction is not present in ImmToIdxMap, then it has no immediate
1269   // form (and must be r+r).
1270   bool noImmForm = !MI.isInlineAsm() && OpC != TargetOpcode::STACKMAP &&
1271                    OpC != TargetOpcode::PATCHPOINT && !ImmToIdxMap.count(OpC);
1272 
1273   // Now add the frame object offset to the offset from r1.
1274   int Offset = MFI.getObjectOffset(FrameIndex);
1275   Offset += MI.getOperand(OffsetOperandNo).getImm();
1276 
1277   // If we're not using a Frame Pointer that has been set to the value of the
1278   // SP before having the stack size subtracted from it, then add the stack size
1279   // to Offset to get the correct offset.
1280   // Naked functions have stack size 0, although getStackSize may not reflect
1281   // that because we didn't call all the pieces that compute it for naked
1282   // functions.
1283   if (!MF.getFunction().hasFnAttribute(Attribute::Naked)) {
1284     if (!(hasBasePointer(MF) && FrameIndex < 0))
1285       Offset += MFI.getStackSize();
1286   }
1287 
1288   // If we can, encode the offset directly into the instruction.  If this is a
1289   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
1290   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
1291   // clear can be encoded.  This is extremely uncommon, because normally you
1292   // only "std" to a stack slot that is at least 4-byte aligned, but it can
1293   // happen in invalid code.
1294   assert(OpC != PPC::DBG_VALUE &&
1295          "This should be handled in a target-independent way");
1296   bool OffsetFitsMnemonic = (OpC == PPC::EVSTDD || OpC == PPC::EVLDD) ?
1297                             isUInt<8>(Offset) :
1298                             isInt<16>(Offset);
1299   if (!noImmForm && ((OffsetFitsMnemonic &&
1300                       ((Offset % offsetMinAlign(MI)) == 0)) ||
1301                      OpC == TargetOpcode::STACKMAP ||
1302                      OpC == TargetOpcode::PATCHPOINT)) {
1303     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1304     return;
1305   }
1306 
1307   // The offset doesn't fit into a single register, scavenge one to build the
1308   // offset in.
1309 
1310   bool is64Bit = TM.isPPC64();
1311   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1312   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1313   const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
1314   Register SRegHi = MF.getRegInfo().createVirtualRegister(RC),
1315            SReg = MF.getRegInfo().createVirtualRegister(RC);
1316 
1317   // Insert a set of rA with the full offset value before the ld, st, or add
1318   if (isInt<16>(Offset))
1319     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI), SReg)
1320       .addImm(Offset);
1321   else {
1322     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
1323       .addImm(Offset >> 16);
1324     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
1325       .addReg(SRegHi, RegState::Kill)
1326       .addImm(Offset);
1327   }
1328 
1329   // Convert into indexed form of the instruction:
1330   //
1331   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
1332   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
1333   unsigned OperandBase;
1334 
1335   if (noImmForm)
1336     OperandBase = 1;
1337   else if (OpC != TargetOpcode::INLINEASM &&
1338            OpC != TargetOpcode::INLINEASM_BR) {
1339     assert(ImmToIdxMap.count(OpC) &&
1340            "No indexed form of load or store available!");
1341     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
1342     MI.setDesc(TII.get(NewOpcode));
1343     OperandBase = 1;
1344   } else {
1345     OperandBase = OffsetOperandNo;
1346   }
1347 
1348   Register StackReg = MI.getOperand(FIOperandNum).getReg();
1349   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
1350   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
1351 }
1352 
1353 Register PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
1354   const PPCFrameLowering *TFI = getFrameLowering(MF);
1355 
1356   if (!TM.isPPC64())
1357     return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
1358   else
1359     return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
1360 }
1361 
1362 Register PPCRegisterInfo::getBaseRegister(const MachineFunction &MF) const {
1363   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1364   if (!hasBasePointer(MF))
1365     return getFrameRegister(MF);
1366 
1367   if (TM.isPPC64())
1368     return PPC::X30;
1369 
1370   if (Subtarget.isSVR4ABI() && TM.isPositionIndependent())
1371     return PPC::R29;
1372 
1373   return PPC::R30;
1374 }
1375 
1376 bool PPCRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
1377   if (!EnableBasePointer)
1378     return false;
1379   if (AlwaysBasePointer)
1380     return true;
1381 
1382   // If we need to realign the stack, then the stack pointer can no longer
1383   // serve as an offset into the caller's stack space. As a result, we need a
1384   // base pointer.
1385   return hasStackRealignment(MF);
1386 }
1387 
1388 /// Returns true if the instruction's frame index
1389 /// reference would be better served by a base register other than FP
1390 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
1391 /// references it should create new base registers for.
1392 bool PPCRegisterInfo::
1393 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
1394   assert(Offset < 0 && "Local offset must be negative");
1395 
1396   // It's the load/store FI references that cause issues, as it can be difficult
1397   // to materialize the offset if it won't fit in the literal field. Estimate
1398   // based on the size of the local frame and some conservative assumptions
1399   // about the rest of the stack frame (note, this is pre-regalloc, so
1400   // we don't know everything for certain yet) whether this offset is likely
1401   // to be out of range of the immediate. Return true if so.
1402 
1403   // We only generate virtual base registers for loads and stores that have
1404   // an r+i form. Return false for everything else.
1405   unsigned OpC = MI->getOpcode();
1406   if (!ImmToIdxMap.count(OpC))
1407     return false;
1408 
1409   // Don't generate a new virtual base register just to add zero to it.
1410   if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
1411       MI->getOperand(2).getImm() == 0)
1412     return false;
1413 
1414   MachineBasicBlock &MBB = *MI->getParent();
1415   MachineFunction &MF = *MBB.getParent();
1416   const PPCFrameLowering *TFI = getFrameLowering(MF);
1417   unsigned StackEst = TFI->determineFrameLayout(MF, true);
1418 
1419   // If we likely don't need a stack frame, then we probably don't need a
1420   // virtual base register either.
1421   if (!StackEst)
1422     return false;
1423 
1424   // Estimate an offset from the stack pointer.
1425   // The incoming offset is relating to the SP at the start of the function,
1426   // but when we access the local it'll be relative to the SP after local
1427   // allocation, so adjust our SP-relative offset by that allocation size.
1428   Offset += StackEst;
1429 
1430   // The frame pointer will point to the end of the stack, so estimate the
1431   // offset as the difference between the object offset and the FP location.
1432   return !isFrameOffsetLegal(MI, getBaseRegister(MF), Offset);
1433 }
1434 
1435 /// Insert defining instruction(s) for BaseReg to
1436 /// be a pointer to FrameIdx at the beginning of the basic block.
1437 Register PPCRegisterInfo::materializeFrameBaseRegister(MachineBasicBlock *MBB,
1438                                                        int FrameIdx,
1439                                                        int64_t Offset) const {
1440   unsigned ADDriOpc = TM.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
1441 
1442   MachineBasicBlock::iterator Ins = MBB->begin();
1443   DebugLoc DL;                  // Defaults to "unknown"
1444   if (Ins != MBB->end())
1445     DL = Ins->getDebugLoc();
1446 
1447   const MachineFunction &MF = *MBB->getParent();
1448   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1449   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1450   const MCInstrDesc &MCID = TII.get(ADDriOpc);
1451   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1452   const TargetRegisterClass *RC = getPointerRegClass(MF);
1453   Register BaseReg = MRI.createVirtualRegister(RC);
1454   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
1455 
1456   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
1457     .addFrameIndex(FrameIdx).addImm(Offset);
1458 
1459   return BaseReg;
1460 }
1461 
1462 void PPCRegisterInfo::resolveFrameIndex(MachineInstr &MI, Register BaseReg,
1463                                         int64_t Offset) const {
1464   unsigned FIOperandNum = 0;
1465   while (!MI.getOperand(FIOperandNum).isFI()) {
1466     ++FIOperandNum;
1467     assert(FIOperandNum < MI.getNumOperands() &&
1468            "Instr doesn't have FrameIndex operand!");
1469   }
1470 
1471   MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
1472   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1473   Offset += MI.getOperand(OffsetOperandNo).getImm();
1474   MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1475 
1476   MachineBasicBlock &MBB = *MI.getParent();
1477   MachineFunction &MF = *MBB.getParent();
1478   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1479   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1480   const MCInstrDesc &MCID = MI.getDesc();
1481   MachineRegisterInfo &MRI = MF.getRegInfo();
1482   MRI.constrainRegClass(BaseReg,
1483                         TII.getRegClass(MCID, FIOperandNum, this, MF));
1484 }
1485 
1486 bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
1487                                          Register BaseReg,
1488                                          int64_t Offset) const {
1489   unsigned FIOperandNum = 0;
1490   while (!MI->getOperand(FIOperandNum).isFI()) {
1491     ++FIOperandNum;
1492     assert(FIOperandNum < MI->getNumOperands() &&
1493            "Instr doesn't have FrameIndex operand!");
1494   }
1495 
1496   unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
1497   Offset += MI->getOperand(OffsetOperandNo).getImm();
1498 
1499   return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
1500          MI->getOpcode() == TargetOpcode::STACKMAP ||
1501          MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1502          (isInt<16>(Offset) && (Offset % offsetMinAlign(*MI)) == 0);
1503 }
1504