xref: /llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp (revision d8921a80052575bb2b9cb345e81e8e22d6c6f516)
1 //===-- PPCRegisterInfo.cpp - PowerPC Register Information ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the PowerPC implementation of the TargetRegisterInfo
10 // class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PPCRegisterInfo.h"
15 #include "PPCFrameLowering.h"
16 #include "PPCInstrBuilder.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCSubtarget.h"
19 #include "PPCTargetMachine.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/CodeGen/TargetFrameLowering.h"
30 #include "llvm/CodeGen/TargetInstrInfo.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include <cstdlib>
43 
44 using namespace llvm;
45 
46 #define DEBUG_TYPE "reginfo"
47 
48 #define GET_REGINFO_TARGET_DESC
49 #include "PPCGenRegisterInfo.inc"
50 
51 STATISTIC(InflateGPRC, "Number of gprc inputs for getLargestLegalClass");
52 STATISTIC(InflateGP8RC, "Number of g8rc inputs for getLargestLegalClass");
53 
54 static cl::opt<bool>
55 EnableBasePointer("ppc-use-base-pointer", cl::Hidden, cl::init(true),
56          cl::desc("Enable use of a base pointer for complex stack frames"));
57 
58 static cl::opt<bool>
59 AlwaysBasePointer("ppc-always-use-base-pointer", cl::Hidden, cl::init(false),
60          cl::desc("Force the use of a base pointer in every function"));
61 
62 static cl::opt<bool>
63 EnableGPRToVecSpills("ppc-enable-gpr-to-vsr-spills", cl::Hidden, cl::init(false),
64          cl::desc("Enable spills from gpr to vsr rather than stack"));
65 
66 static cl::opt<bool>
67 StackPtrConst("ppc-stack-ptr-caller-preserved",
68                 cl::desc("Consider R1 caller preserved so stack saves of "
69                          "caller preserved registers can be LICM candidates"),
70                 cl::init(true), cl::Hidden);
71 
72 static cl::opt<unsigned>
73 MaxCRBitSpillDist("ppc-max-crbit-spill-dist",
74                   cl::desc("Maximum search distance for definition of CR bit "
75                            "spill on ppc"),
76                   cl::Hidden, cl::init(100));
77 
78 static unsigned offsetMinAlignForOpcode(unsigned OpC);
79 
80 PPCRegisterInfo::PPCRegisterInfo(const PPCTargetMachine &TM)
81   : PPCGenRegisterInfo(TM.isPPC64() ? PPC::LR8 : PPC::LR,
82                        TM.isPPC64() ? 0 : 1,
83                        TM.isPPC64() ? 0 : 1),
84     TM(TM) {
85   ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
86   ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
87   ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
88   ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
89   ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
90   ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
91   ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
92   ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
93   ImmToIdxMap[PPC::LWA_32] = PPC::LWAX_32;
94 
95   // 64-bit
96   ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
97   ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
98   ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
99   ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
100   ImmToIdxMap[PPC::ADDI8] = PPC::ADD8;
101 
102   // VSX
103   ImmToIdxMap[PPC::DFLOADf32] = PPC::LXSSPX;
104   ImmToIdxMap[PPC::DFLOADf64] = PPC::LXSDX;
105   ImmToIdxMap[PPC::SPILLTOVSR_LD] = PPC::SPILLTOVSR_LDX;
106   ImmToIdxMap[PPC::SPILLTOVSR_ST] = PPC::SPILLTOVSR_STX;
107   ImmToIdxMap[PPC::DFSTOREf32] = PPC::STXSSPX;
108   ImmToIdxMap[PPC::DFSTOREf64] = PPC::STXSDX;
109   ImmToIdxMap[PPC::LXV] = PPC::LXVX;
110   ImmToIdxMap[PPC::LXSD] = PPC::LXSDX;
111   ImmToIdxMap[PPC::LXSSP] = PPC::LXSSPX;
112   ImmToIdxMap[PPC::STXV] = PPC::STXVX;
113   ImmToIdxMap[PPC::STXSD] = PPC::STXSDX;
114   ImmToIdxMap[PPC::STXSSP] = PPC::STXSSPX;
115 
116   // SPE
117   ImmToIdxMap[PPC::EVLDD] = PPC::EVLDDX;
118   ImmToIdxMap[PPC::EVSTDD] = PPC::EVSTDDX;
119   ImmToIdxMap[PPC::SPESTW] = PPC::SPESTWX;
120   ImmToIdxMap[PPC::SPELWZ] = PPC::SPELWZX;
121 }
122 
123 /// getPointerRegClass - Return the register class to use to hold pointers.
124 /// This is used for addressing modes.
125 const TargetRegisterClass *
126 PPCRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
127                                                                        const {
128   // Note that PPCInstrInfo::FoldImmediate also directly uses this Kind value
129   // when it checks for ZERO folding.
130   if (Kind == 1) {
131     if (TM.isPPC64())
132       return &PPC::G8RC_NOX0RegClass;
133     return &PPC::GPRC_NOR0RegClass;
134   }
135 
136   if (TM.isPPC64())
137     return &PPC::G8RCRegClass;
138   return &PPC::GPRCRegClass;
139 }
140 
141 const MCPhysReg*
142 PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
143   const PPCSubtarget &Subtarget = MF->getSubtarget<PPCSubtarget>();
144   if (MF->getFunction().getCallingConv() == CallingConv::AnyReg) {
145     if (!TM.isPPC64() && Subtarget.isAIXABI())
146       report_fatal_error("AnyReg unimplemented on 32-bit AIX.");
147     if (Subtarget.hasVSX())
148       return CSR_64_AllRegs_VSX_SaveList;
149     if (Subtarget.hasAltivec())
150       return CSR_64_AllRegs_Altivec_SaveList;
151     return CSR_64_AllRegs_SaveList;
152   }
153 
154   // On PPC64, we might need to save r2 (but only if it is not reserved).
155   // We do not need to treat R2 as callee-saved when using PC-Relative calls
156   // because any direct uses of R2 will cause it to be reserved. If the function
157   // is a leaf or the only uses of R2 are implicit uses for calls, the calls
158   // will use the @notoc relocation which will cause this function to set the
159   // st_other bit to 1, thereby communicating to its caller that it arbitrarily
160   // clobbers the TOC.
161   bool SaveR2 = MF->getRegInfo().isAllocatable(PPC::X2) &&
162                 !Subtarget.isUsingPCRelativeCalls();
163 
164   // Cold calling convention CSRs.
165   if (MF->getFunction().getCallingConv() == CallingConv::Cold) {
166     if (Subtarget.isAIXABI())
167       report_fatal_error("Cold calling unimplemented on AIX.");
168     if (TM.isPPC64()) {
169       if (Subtarget.hasAltivec())
170         return SaveR2 ? CSR_SVR64_ColdCC_R2_Altivec_SaveList
171                       : CSR_SVR64_ColdCC_Altivec_SaveList;
172       return SaveR2 ? CSR_SVR64_ColdCC_R2_SaveList
173                     : CSR_SVR64_ColdCC_SaveList;
174     }
175     // 32-bit targets.
176     if (Subtarget.hasAltivec())
177       return CSR_SVR32_ColdCC_Altivec_SaveList;
178     else if (Subtarget.hasSPE())
179       return CSR_SVR32_ColdCC_SPE_SaveList;
180     return CSR_SVR32_ColdCC_SaveList;
181   }
182   // Standard calling convention CSRs.
183   if (TM.isPPC64()) {
184     if (Subtarget.hasAltivec())
185       return SaveR2 ? CSR_PPC64_R2_Altivec_SaveList
186                     : CSR_PPC64_Altivec_SaveList;
187     return SaveR2 ? CSR_PPC64_R2_SaveList : CSR_PPC64_SaveList;
188   }
189   // 32-bit targets.
190   if (Subtarget.isAIXABI())
191     return CSR_AIX32_SaveList;
192   if (Subtarget.hasAltivec())
193     return CSR_SVR432_Altivec_SaveList;
194   else if (Subtarget.hasSPE())
195     return CSR_SVR432_SPE_SaveList;
196   return CSR_SVR432_SaveList;
197 }
198 
199 const uint32_t *
200 PPCRegisterInfo::getCallPreservedMask(const MachineFunction &MF,
201                                       CallingConv::ID CC) const {
202   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
203   if (CC == CallingConv::AnyReg) {
204     if (Subtarget.hasVSX())
205       return CSR_64_AllRegs_VSX_RegMask;
206     if (Subtarget.hasAltivec())
207       return CSR_64_AllRegs_Altivec_RegMask;
208     return CSR_64_AllRegs_RegMask;
209   }
210 
211   if (Subtarget.isAIXABI()) {
212     assert(!Subtarget.hasAltivec() && "Altivec is not implemented on AIX yet.");
213     return TM.isPPC64() ? CSR_PPC64_RegMask : CSR_AIX32_RegMask;
214   }
215 
216   if (CC == CallingConv::Cold) {
217     return TM.isPPC64() ? (Subtarget.hasAltivec() ? CSR_SVR64_ColdCC_Altivec_RegMask
218                                                   : CSR_SVR64_ColdCC_RegMask)
219                         : (Subtarget.hasAltivec() ? CSR_SVR32_ColdCC_Altivec_RegMask
220                                                   : (Subtarget.hasSPE()
221                                                   ? CSR_SVR32_ColdCC_SPE_RegMask
222                                                   : CSR_SVR32_ColdCC_RegMask));
223   }
224 
225   return TM.isPPC64() ? (Subtarget.hasAltivec() ? CSR_PPC64_Altivec_RegMask
226                                                 : CSR_PPC64_RegMask)
227                       : (Subtarget.hasAltivec()
228                              ? CSR_SVR432_Altivec_RegMask
229                              : (Subtarget.hasSPE() ? CSR_SVR432_SPE_RegMask
230                                                    : CSR_SVR432_RegMask));
231 }
232 
233 const uint32_t*
234 PPCRegisterInfo::getNoPreservedMask() const {
235   return CSR_NoRegs_RegMask;
236 }
237 
238 void PPCRegisterInfo::adjustStackMapLiveOutMask(uint32_t *Mask) const {
239   for (unsigned PseudoReg : {PPC::ZERO, PPC::ZERO8, PPC::RM})
240     Mask[PseudoReg / 32] &= ~(1u << (PseudoReg % 32));
241 }
242 
243 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
244   BitVector Reserved(getNumRegs());
245   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
246   const PPCFrameLowering *TFI = getFrameLowering(MF);
247 
248   // The ZERO register is not really a register, but the representation of r0
249   // when used in instructions that treat r0 as the constant 0.
250   markSuperRegs(Reserved, PPC::ZERO);
251 
252   // The FP register is also not really a register, but is the representation
253   // of the frame pointer register used by ISD::FRAMEADDR.
254   markSuperRegs(Reserved, PPC::FP);
255 
256   // The BP register is also not really a register, but is the representation
257   // of the base pointer register used by setjmp.
258   markSuperRegs(Reserved, PPC::BP);
259 
260   // The counter registers must be reserved so that counter-based loops can
261   // be correctly formed (and the mtctr instructions are not DCE'd).
262   markSuperRegs(Reserved, PPC::CTR);
263   markSuperRegs(Reserved, PPC::CTR8);
264 
265   markSuperRegs(Reserved, PPC::R1);
266   markSuperRegs(Reserved, PPC::LR);
267   markSuperRegs(Reserved, PPC::LR8);
268   markSuperRegs(Reserved, PPC::RM);
269 
270   markSuperRegs(Reserved, PPC::VRSAVE);
271 
272   // The SVR4 ABI reserves r2 and r13
273   if (Subtarget.isSVR4ABI()) {
274     // We only reserve r2 if we need to use the TOC pointer. If we have no
275     // explicit uses of the TOC pointer (meaning we're a leaf function with
276     // no constant-pool loads, etc.) and we have no potential uses inside an
277     // inline asm block, then we can treat r2 has an ordinary callee-saved
278     // register.
279     const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
280     if (!TM.isPPC64() || FuncInfo->usesTOCBasePtr() || MF.hasInlineAsm())
281       markSuperRegs(Reserved, PPC::R2);  // System-reserved register
282     markSuperRegs(Reserved, PPC::R13); // Small Data Area pointer register
283   }
284 
285   // Always reserve r2 on AIX for now.
286   // TODO: Make r2 allocatable on AIX/XCOFF for some leaf functions.
287   if (Subtarget.isAIXABI())
288     markSuperRegs(Reserved, PPC::R2);  // System-reserved register
289 
290   // On PPC64, r13 is the thread pointer. Never allocate this register.
291   if (TM.isPPC64())
292     markSuperRegs(Reserved, PPC::R13);
293 
294   if (TFI->needsFP(MF))
295     markSuperRegs(Reserved, PPC::R31);
296 
297   bool IsPositionIndependent = TM.isPositionIndependent();
298   if (hasBasePointer(MF)) {
299     if (Subtarget.is32BitELFABI() && IsPositionIndependent)
300       markSuperRegs(Reserved, PPC::R29);
301     else
302       markSuperRegs(Reserved, PPC::R30);
303   }
304 
305   if (Subtarget.is32BitELFABI() && IsPositionIndependent)
306     markSuperRegs(Reserved, PPC::R30);
307 
308   // Reserve Altivec registers when Altivec is unavailable.
309   if (!Subtarget.hasAltivec())
310     for (TargetRegisterClass::iterator I = PPC::VRRCRegClass.begin(),
311          IE = PPC::VRRCRegClass.end(); I != IE; ++I)
312       markSuperRegs(Reserved, *I);
313 
314   assert(checkAllSuperRegsMarked(Reserved));
315   return Reserved;
316 }
317 
318 bool PPCRegisterInfo::requiresFrameIndexScavenging(const MachineFunction &MF) const {
319   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
320   const PPCInstrInfo *InstrInfo =  Subtarget.getInstrInfo();
321   const MachineFrameInfo &MFI = MF.getFrameInfo();
322   const std::vector<CalleeSavedInfo> &Info = MFI.getCalleeSavedInfo();
323 
324   // If the callee saved info is invalid we have to default to true for safety.
325   if (!MFI.isCalleeSavedInfoValid())
326     return true;
327 
328   // We will require the use of X-Forms because the frame is larger than what
329   // can be represented in signed 16 bits that fit in the immediate of a D-Form.
330   // If we need an X-Form then we need a register to store the address offset.
331   unsigned FrameSize = MFI.getStackSize();
332   // Signed 16 bits means that the FrameSize cannot be more than 15 bits.
333   if (FrameSize & ~0x7FFF)
334     return true;
335 
336   // The callee saved info is valid so it can be traversed.
337   // Checking for registers that need saving that do not have load or store
338   // forms where the address offset is an immediate.
339   for (unsigned i = 0; i < Info.size(); i++) {
340     int FrIdx = Info[i].getFrameIdx();
341     unsigned Reg = Info[i].getReg();
342 
343     const TargetRegisterClass *RC = getMinimalPhysRegClass(Reg);
344     unsigned Opcode = InstrInfo->getStoreOpcodeForSpill(RC);
345     if (!MFI.isFixedObjectIndex(FrIdx)) {
346       // This is not a fixed object. If it requires alignment then we may still
347       // need to use the XForm.
348       if (offsetMinAlignForOpcode(Opcode) > 1)
349         return true;
350     }
351 
352     // This is eiher:
353     // 1) A fixed frame index object which we know are aligned so
354     // as long as we have a valid DForm/DSForm/DQForm (non XForm) we don't
355     // need to consider the alignment here.
356     // 2) A not fixed object but in that case we now know that the min required
357     // alignment is no more than 1 based on the previous check.
358     if (InstrInfo->isXFormMemOp(Opcode))
359       return true;
360   }
361   return false;
362 }
363 
364 bool PPCRegisterInfo::isCallerPreservedPhysReg(MCRegister PhysReg,
365                                                const MachineFunction &MF) const {
366   assert(Register::isPhysicalRegister(PhysReg));
367   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
368   const MachineFrameInfo &MFI = MF.getFrameInfo();
369   if (!TM.isPPC64())
370     return false;
371 
372   if (!Subtarget.isSVR4ABI())
373     return false;
374   if (PhysReg == PPC::X2)
375     // X2 is guaranteed to be preserved within a function if it is reserved.
376     // The reason it's reserved is that it's the TOC pointer (and the function
377     // uses the TOC). In functions where it isn't reserved (i.e. leaf functions
378     // with no TOC access), we can't claim that it is preserved.
379     return (getReservedRegs(MF).test(PPC::X2));
380   if (StackPtrConst && (PhysReg == PPC::X1) && !MFI.hasVarSizedObjects()
381       && !MFI.hasOpaqueSPAdjustment())
382     // The value of the stack pointer does not change within a function after
383     // the prologue and before the epilogue if there are no dynamic allocations
384     // and no inline asm which clobbers X1.
385     return true;
386   return false;
387 }
388 
389 unsigned PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
390                                               MachineFunction &MF) const {
391   const PPCFrameLowering *TFI = getFrameLowering(MF);
392   const unsigned DefaultSafety = 1;
393 
394   switch (RC->getID()) {
395   default:
396     return 0;
397   case PPC::G8RC_NOX0RegClassID:
398   case PPC::GPRC_NOR0RegClassID:
399   case PPC::SPERCRegClassID:
400   case PPC::G8RCRegClassID:
401   case PPC::GPRCRegClassID: {
402     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
403     return 32 - FP - DefaultSafety;
404   }
405   case PPC::F8RCRegClassID:
406   case PPC::F4RCRegClassID:
407   case PPC::QFRCRegClassID:
408   case PPC::QSRCRegClassID:
409   case PPC::QBRCRegClassID:
410   case PPC::VRRCRegClassID:
411   case PPC::VFRCRegClassID:
412   case PPC::VSLRCRegClassID:
413     return 32 - DefaultSafety;
414   case PPC::VSRCRegClassID:
415   case PPC::VSFRCRegClassID:
416   case PPC::VSSRCRegClassID:
417     return 64 - DefaultSafety;
418   case PPC::CRRCRegClassID:
419     return 8 - DefaultSafety;
420   }
421 }
422 
423 const TargetRegisterClass *
424 PPCRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC,
425                                            const MachineFunction &MF) const {
426   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
427   if (Subtarget.hasVSX()) {
428     // With VSX, we can inflate various sub-register classes to the full VSX
429     // register set.
430 
431     // For Power9 we allow the user to enable GPR to vector spills.
432     // FIXME: Currently limited to spilling GP8RC. A follow on patch will add
433     // support to spill GPRC.
434     if (TM.isELFv2ABI()) {
435       if (Subtarget.hasP9Vector() && EnableGPRToVecSpills &&
436           RC == &PPC::G8RCRegClass) {
437         InflateGP8RC++;
438         return &PPC::SPILLTOVSRRCRegClass;
439       }
440       if (RC == &PPC::GPRCRegClass && EnableGPRToVecSpills)
441         InflateGPRC++;
442     }
443     if (RC == &PPC::F8RCRegClass)
444       return &PPC::VSFRCRegClass;
445     else if (RC == &PPC::VRRCRegClass)
446       return &PPC::VSRCRegClass;
447     else if (RC == &PPC::F4RCRegClass && Subtarget.hasP8Vector())
448       return &PPC::VSSRCRegClass;
449   }
450 
451   return TargetRegisterInfo::getLargestLegalSuperClass(RC, MF);
452 }
453 
454 //===----------------------------------------------------------------------===//
455 // Stack Frame Processing methods
456 //===----------------------------------------------------------------------===//
457 
458 /// lowerDynamicAlloc - Generate the code for allocating an object in the
459 /// current frame.  The sequence of code will be in the general form
460 ///
461 ///   addi   R0, SP, \#frameSize ; get the address of the previous frame
462 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
463 ///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
464 ///
465 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II) const {
466   // Get the instruction.
467   MachineInstr &MI = *II;
468   // Get the instruction's basic block.
469   MachineBasicBlock &MBB = *MI.getParent();
470   // Get the basic block's function.
471   MachineFunction &MF = *MBB.getParent();
472   // Get the frame info.
473   MachineFrameInfo &MFI = MF.getFrameInfo();
474   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
475   // Get the instruction info.
476   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
477   // Determine whether 64-bit pointers are used.
478   bool LP64 = TM.isPPC64();
479   DebugLoc dl = MI.getDebugLoc();
480 
481   // Get the maximum call stack size.
482   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
483   Align MaxAlign = MFI.getMaxAlign();
484   assert(isAligned(MaxAlign, maxCallFrameSize) &&
485          "Maximum call-frame size not sufficiently aligned");
486   (void)MaxAlign;
487 
488   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
489   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
490   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
491   bool KillNegSizeReg = MI.getOperand(1).isKill();
492   Register NegSizeReg = MI.getOperand(1).getReg();
493 
494   prepareDynamicAlloca(II, NegSizeReg, KillNegSizeReg, Reg);
495   // Grow the stack and update the stack pointer link, then determine the
496   // address of new allocated space.
497   if (LP64) {
498     BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
499         .addReg(Reg, RegState::Kill)
500         .addReg(PPC::X1)
501         .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
502     BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
503         .addReg(PPC::X1)
504         .addImm(maxCallFrameSize);
505   } else {
506     BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
507         .addReg(Reg, RegState::Kill)
508         .addReg(PPC::R1)
509         .addReg(NegSizeReg, getKillRegState(KillNegSizeReg));
510     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
511         .addReg(PPC::R1)
512         .addImm(maxCallFrameSize);
513   }
514 
515   // Discard the DYNALLOC instruction.
516   MBB.erase(II);
517 }
518 
519 /// To accomplish dynamic stack allocation, we have to calculate exact size
520 /// subtracted from the stack pointer according alignment information and get
521 /// previous frame pointer.
522 void PPCRegisterInfo::prepareDynamicAlloca(MachineBasicBlock::iterator II,
523                                            Register &NegSizeReg,
524                                            bool &KillNegSizeReg,
525                                            Register &FramePointer) const {
526   // Get the instruction.
527   MachineInstr &MI = *II;
528   // Get the instruction's basic block.
529   MachineBasicBlock &MBB = *MI.getParent();
530   // Get the basic block's function.
531   MachineFunction &MF = *MBB.getParent();
532   // Get the frame info.
533   MachineFrameInfo &MFI = MF.getFrameInfo();
534   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
535   // Get the instruction info.
536   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
537   // Determine whether 64-bit pointers are used.
538   bool LP64 = TM.isPPC64();
539   DebugLoc dl = MI.getDebugLoc();
540   // Get the total frame size.
541   unsigned FrameSize = MFI.getStackSize();
542 
543   // Get stack alignments.
544   const PPCFrameLowering *TFI = getFrameLowering(MF);
545   Align TargetAlign = TFI->getStackAlign();
546   Align MaxAlign = MFI.getMaxAlign();
547 
548   // Determine the previous frame's address.  If FrameSize can't be
549   // represented as 16 bits or we need special alignment, then we load the
550   // previous frame's address from 0(SP).  Why not do an addis of the hi?
551   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
552   // Constructing the constant and adding would take 3 instructions.
553   // Fortunately, a frame greater than 32K is rare.
554   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
555   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
556 
557   if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
558     if (LP64)
559       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), FramePointer)
560           .addReg(PPC::X31)
561           .addImm(FrameSize);
562     else
563       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), FramePointer)
564           .addReg(PPC::R31)
565           .addImm(FrameSize);
566   } else if (LP64) {
567     BuildMI(MBB, II, dl, TII.get(PPC::LD), FramePointer)
568         .addImm(0)
569         .addReg(PPC::X1);
570   } else {
571     BuildMI(MBB, II, dl, TII.get(PPC::LWZ), FramePointer)
572         .addImm(0)
573         .addReg(PPC::R1);
574   }
575   // Determine the actual NegSizeReg according to alignment info.
576   if (LP64) {
577     if (MaxAlign > TargetAlign) {
578       unsigned UnalNegSizeReg = NegSizeReg;
579       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
580 
581       // Unfortunately, there is no andi, only andi., and we can't insert that
582       // here because we might clobber cr0 while it is live.
583       BuildMI(MBB, II, dl, TII.get(PPC::LI8), NegSizeReg)
584           .addImm(~(MaxAlign.value() - 1));
585 
586       unsigned NegSizeReg1 = NegSizeReg;
587       NegSizeReg = MF.getRegInfo().createVirtualRegister(G8RC);
588       BuildMI(MBB, II, dl, TII.get(PPC::AND8), NegSizeReg)
589           .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
590           .addReg(NegSizeReg1, RegState::Kill);
591       KillNegSizeReg = true;
592     }
593   } else {
594     if (MaxAlign > TargetAlign) {
595       unsigned UnalNegSizeReg = NegSizeReg;
596       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
597 
598       // Unfortunately, there is no andi, only andi., and we can't insert that
599       // here because we might clobber cr0 while it is live.
600       BuildMI(MBB, II, dl, TII.get(PPC::LI), NegSizeReg)
601           .addImm(~(MaxAlign.value() - 1));
602 
603       unsigned NegSizeReg1 = NegSizeReg;
604       NegSizeReg = MF.getRegInfo().createVirtualRegister(GPRC);
605       BuildMI(MBB, II, dl, TII.get(PPC::AND), NegSizeReg)
606           .addReg(UnalNegSizeReg, getKillRegState(KillNegSizeReg))
607           .addReg(NegSizeReg1, RegState::Kill);
608       KillNegSizeReg = true;
609     }
610   }
611 }
612 
613 void PPCRegisterInfo::lowerDynamicAreaOffset(
614     MachineBasicBlock::iterator II) const {
615   // Get the instruction.
616   MachineInstr &MI = *II;
617   // Get the instruction's basic block.
618   MachineBasicBlock &MBB = *MI.getParent();
619   // Get the basic block's function.
620   MachineFunction &MF = *MBB.getParent();
621   // Get the frame info.
622   MachineFrameInfo &MFI = MF.getFrameInfo();
623   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
624   // Get the instruction info.
625   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
626 
627   unsigned maxCallFrameSize = MFI.getMaxCallFrameSize();
628   bool is64Bit = TM.isPPC64();
629   DebugLoc dl = MI.getDebugLoc();
630   BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI),
631           MI.getOperand(0).getReg())
632       .addImm(maxCallFrameSize);
633   MBB.erase(II);
634 }
635 
636 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
637 /// reserving a whole register (R0), we scrounge for one here. This generates
638 /// code like this:
639 ///
640 ///   mfcr rA                  ; Move the conditional register into GPR rA.
641 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
642 ///   stw rA, FI               ; Store rA to the frame.
643 ///
644 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
645                                       unsigned FrameIndex) const {
646   // Get the instruction.
647   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>
648   // Get the instruction's basic block.
649   MachineBasicBlock &MBB = *MI.getParent();
650   MachineFunction &MF = *MBB.getParent();
651   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
652   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
653   DebugLoc dl = MI.getDebugLoc();
654 
655   bool LP64 = TM.isPPC64();
656   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
657   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
658 
659   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
660   Register SrcReg = MI.getOperand(0).getReg();
661 
662   // We need to store the CR in the low 4-bits of the saved value. First, issue
663   // an MFOCRF to save all of the CRBits and, if needed, kill the SrcReg.
664   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
665       .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
666 
667   // If the saved register wasn't CR0, shift the bits left so that they are in
668   // CR0's slot.
669   if (SrcReg != PPC::CR0) {
670     Register Reg1 = Reg;
671     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
672 
673     // rlwinm rA, rA, ShiftBits, 0, 31.
674     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
675       .addReg(Reg1, RegState::Kill)
676       .addImm(getEncodingValue(SrcReg) * 4)
677       .addImm(0)
678       .addImm(31);
679   }
680 
681   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
682                     .addReg(Reg, RegState::Kill),
683                     FrameIndex);
684 
685   // Discard the pseudo instruction.
686   MBB.erase(II);
687 }
688 
689 void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
690                                       unsigned FrameIndex) const {
691   // Get the instruction.
692   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CR <offset>
693   // Get the instruction's basic block.
694   MachineBasicBlock &MBB = *MI.getParent();
695   MachineFunction &MF = *MBB.getParent();
696   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
697   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
698   DebugLoc dl = MI.getDebugLoc();
699 
700   bool LP64 = TM.isPPC64();
701   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
702   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
703 
704   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
705   Register DestReg = MI.getOperand(0).getReg();
706   assert(MI.definesRegister(DestReg) &&
707     "RESTORE_CR does not define its destination");
708 
709   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
710                               Reg), FrameIndex);
711 
712   // If the reloaded register isn't CR0, shift the bits right so that they are
713   // in the right CR's slot.
714   if (DestReg != PPC::CR0) {
715     Register Reg1 = Reg;
716     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
717 
718     unsigned ShiftBits = getEncodingValue(DestReg)*4;
719     // rlwinm r11, r11, 32-ShiftBits, 0, 31.
720     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
721              .addReg(Reg1, RegState::Kill).addImm(32-ShiftBits).addImm(0)
722              .addImm(31);
723   }
724 
725   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF), DestReg)
726              .addReg(Reg, RegState::Kill);
727 
728   // Discard the pseudo instruction.
729   MBB.erase(II);
730 }
731 
732 void PPCRegisterInfo::lowerCRBitSpilling(MachineBasicBlock::iterator II,
733                                          unsigned FrameIndex) const {
734   // Get the instruction.
735   MachineInstr &MI = *II;       // ; SPILL_CRBIT <SrcReg>, <offset>
736   // Get the instruction's basic block.
737   MachineBasicBlock &MBB = *MI.getParent();
738   MachineFunction &MF = *MBB.getParent();
739   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
740   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
741   const TargetRegisterInfo* TRI = Subtarget.getRegisterInfo();
742   DebugLoc dl = MI.getDebugLoc();
743 
744   bool LP64 = TM.isPPC64();
745   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
746   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
747 
748   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
749   Register SrcReg = MI.getOperand(0).getReg();
750 
751   // Search up the BB to find the definition of the CR bit.
752   MachineBasicBlock::reverse_iterator Ins = MI;
753   MachineBasicBlock::reverse_iterator Rend = MBB.rend();
754   ++Ins;
755   unsigned CRBitSpillDistance = 0;
756   bool SeenUse = false;
757   for (; Ins != Rend; ++Ins) {
758     // Definition found.
759     if (Ins->modifiesRegister(SrcReg, TRI))
760       break;
761     // Use found.
762     if (Ins->readsRegister(SrcReg, TRI))
763       SeenUse = true;
764     // Unable to find CR bit definition within maximum search distance.
765     if (CRBitSpillDistance == MaxCRBitSpillDist) {
766       Ins = MI;
767       break;
768     }
769     // Skip debug instructions when counting CR bit spill distance.
770     if (!Ins->isDebugInstr())
771       CRBitSpillDistance++;
772   }
773 
774   // Unable to find the definition of the CR bit in the MBB.
775   if (Ins == MBB.rend())
776     Ins = MI;
777 
778   bool SpillsKnownBit = false;
779   // There is no need to extract the CR bit if its value is already known.
780   switch (Ins->getOpcode()) {
781   case PPC::CRUNSET:
782     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LI8 : PPC::LI), Reg)
783       .addImm(0);
784     SpillsKnownBit = true;
785     break;
786   case PPC::CRSET:
787     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LIS8 : PPC::LIS), Reg)
788       .addImm(-32768);
789     SpillsKnownBit = true;
790     break;
791   default:
792     // On Power9, we can use SETB to extract the LT bit. This only works for
793     // the LT bit since SETB produces -1/1/0 for LT/GT/<neither>. So the value
794     // of the bit we care about (32-bit sign bit) will be set to the value of
795     // the LT bit (regardless of the other bits in the CR field).
796     if (Subtarget.isISA3_0()) {
797       if (SrcReg == PPC::CR0LT || SrcReg == PPC::CR1LT ||
798           SrcReg == PPC::CR2LT || SrcReg == PPC::CR3LT ||
799           SrcReg == PPC::CR4LT || SrcReg == PPC::CR5LT ||
800           SrcReg == PPC::CR6LT || SrcReg == PPC::CR7LT) {
801         BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::SETB8 : PPC::SETB), Reg)
802           .addReg(getCRFromCRBit(SrcReg), RegState::Undef);
803         break;
804       }
805     }
806 
807     // We need to move the CR field that contains the CR bit we are spilling.
808     // The super register may not be explicitly defined (i.e. it can be defined
809     // by a CR-logical that only defines the subreg) so we state that the CR
810     // field is undef. Also, in order to preserve the kill flag on the CR bit,
811     // we add it as an implicit use.
812     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), Reg)
813       .addReg(getCRFromCRBit(SrcReg), RegState::Undef)
814       .addReg(SrcReg,
815               RegState::Implicit | getKillRegState(MI.getOperand(0).isKill()));
816 
817     // If the saved register wasn't CR0LT, shift the bits left so that the bit
818     // to store is the first one. Mask all but that bit.
819     Register Reg1 = Reg;
820     Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
821 
822     // rlwinm rA, rA, ShiftBits, 0, 0.
823     BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
824       .addReg(Reg1, RegState::Kill)
825       .addImm(getEncodingValue(SrcReg))
826       .addImm(0).addImm(0);
827   }
828   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
829                     .addReg(Reg, RegState::Kill),
830                     FrameIndex);
831 
832   bool KillsCRBit = MI.killsRegister(SrcReg, TRI);
833   // Discard the pseudo instruction.
834   MBB.erase(II);
835   if (SpillsKnownBit && KillsCRBit && !SeenUse) {
836     Ins->setDesc(TII.get(PPC::UNENCODED_NOP));
837     Ins->RemoveOperand(0);
838   }
839 }
840 
841 void PPCRegisterInfo::lowerCRBitRestore(MachineBasicBlock::iterator II,
842                                       unsigned FrameIndex) const {
843   // Get the instruction.
844   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CRBIT <offset>
845   // Get the instruction's basic block.
846   MachineBasicBlock &MBB = *MI.getParent();
847   MachineFunction &MF = *MBB.getParent();
848   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
849   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
850   DebugLoc dl = MI.getDebugLoc();
851 
852   bool LP64 = TM.isPPC64();
853   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
854   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
855 
856   Register Reg = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
857   Register DestReg = MI.getOperand(0).getReg();
858   assert(MI.definesRegister(DestReg) &&
859     "RESTORE_CRBIT does not define its destination");
860 
861   addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
862                               Reg), FrameIndex);
863 
864   BuildMI(MBB, II, dl, TII.get(TargetOpcode::IMPLICIT_DEF), DestReg);
865 
866   Register RegO = MF.getRegInfo().createVirtualRegister(LP64 ? G8RC : GPRC);
867   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFOCRF8 : PPC::MFOCRF), RegO)
868           .addReg(getCRFromCRBit(DestReg));
869 
870   unsigned ShiftBits = getEncodingValue(DestReg);
871   // rlwimi r11, r10, 32-ShiftBits, ..., ...
872   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWIMI8 : PPC::RLWIMI), RegO)
873       .addReg(RegO, RegState::Kill)
874       .addReg(Reg, RegState::Kill)
875       .addImm(ShiftBits ? 32 - ShiftBits : 0)
876       .addImm(ShiftBits)
877       .addImm(ShiftBits);
878 
879   BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTOCRF8 : PPC::MTOCRF),
880           getCRFromCRBit(DestReg))
881       .addReg(RegO, RegState::Kill)
882       // Make sure we have a use dependency all the way through this
883       // sequence of instructions. We can't have the other bits in the CR
884       // modified in between the mfocrf and the mtocrf.
885       .addReg(getCRFromCRBit(DestReg), RegState::Implicit);
886 
887   // Discard the pseudo instruction.
888   MBB.erase(II);
889 }
890 
891 void PPCRegisterInfo::lowerVRSAVESpilling(MachineBasicBlock::iterator II,
892                                           unsigned FrameIndex) const {
893   // Get the instruction.
894   MachineInstr &MI = *II;       // ; SPILL_VRSAVE <SrcReg>, <offset>
895   // Get the instruction's basic block.
896   MachineBasicBlock &MBB = *MI.getParent();
897   MachineFunction &MF = *MBB.getParent();
898   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
899   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
900   DebugLoc dl = MI.getDebugLoc();
901 
902   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
903   Register Reg = MF.getRegInfo().createVirtualRegister(GPRC);
904   Register SrcReg = MI.getOperand(0).getReg();
905 
906   BuildMI(MBB, II, dl, TII.get(PPC::MFVRSAVEv), Reg)
907       .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
908 
909   addFrameReference(
910       BuildMI(MBB, II, dl, TII.get(PPC::STW)).addReg(Reg, RegState::Kill),
911       FrameIndex);
912 
913   // Discard the pseudo instruction.
914   MBB.erase(II);
915 }
916 
917 void PPCRegisterInfo::lowerVRSAVERestore(MachineBasicBlock::iterator II,
918                                          unsigned FrameIndex) const {
919   // Get the instruction.
920   MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_VRSAVE <offset>
921   // Get the instruction's basic block.
922   MachineBasicBlock &MBB = *MI.getParent();
923   MachineFunction &MF = *MBB.getParent();
924   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
925   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
926   DebugLoc dl = MI.getDebugLoc();
927 
928   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
929   Register Reg = MF.getRegInfo().createVirtualRegister(GPRC);
930   Register DestReg = MI.getOperand(0).getReg();
931   assert(MI.definesRegister(DestReg) &&
932     "RESTORE_VRSAVE does not define its destination");
933 
934   addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::LWZ),
935                               Reg), FrameIndex);
936 
937   BuildMI(MBB, II, dl, TII.get(PPC::MTVRSAVEv), DestReg)
938              .addReg(Reg, RegState::Kill);
939 
940   // Discard the pseudo instruction.
941   MBB.erase(II);
942 }
943 
944 bool PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
945                                            Register Reg, int &FrameIdx) const {
946   // For the nonvolatile condition registers (CR2, CR3, CR4) return true to
947   // prevent allocating an additional frame slot.
948   // For 64-bit ELF and AIX, the CR save area is in the linkage area at SP+8,
949   // for 32-bit AIX the CR save area is in the linkage area at SP+4.
950   // We have created a FrameIndex to that spill slot to keep the CalleSaveInfos
951   // valid.
952   // For 32-bit ELF, we have previously created the stack slot if needed, so
953   // return its FrameIdx.
954   if (PPC::CR2 <= Reg && Reg <= PPC::CR4) {
955     FrameIdx = MF.getInfo<PPCFunctionInfo>()->getCRSpillFrameIndex();
956     return true;
957   }
958   return false;
959 }
960 
961 // If the offset must be a multiple of some value, return what that value is.
962 static unsigned offsetMinAlignForOpcode(unsigned OpC) {
963   switch (OpC) {
964   default:
965     return 1;
966   case PPC::LWA:
967   case PPC::LWA_32:
968   case PPC::LD:
969   case PPC::LDU:
970   case PPC::STD:
971   case PPC::STDU:
972   case PPC::DFLOADf32:
973   case PPC::DFLOADf64:
974   case PPC::DFSTOREf32:
975   case PPC::DFSTOREf64:
976   case PPC::LXSD:
977   case PPC::LXSSP:
978   case PPC::STXSD:
979   case PPC::STXSSP:
980     return 4;
981   case PPC::EVLDD:
982   case PPC::EVSTDD:
983     return 8;
984   case PPC::LXV:
985   case PPC::STXV:
986     return 16;
987   }
988 }
989 
990 // If the offset must be a multiple of some value, return what that value is.
991 static unsigned offsetMinAlign(const MachineInstr &MI) {
992   unsigned OpC = MI.getOpcode();
993   return offsetMinAlignForOpcode(OpC);
994 }
995 
996 // Return the OffsetOperandNo given the FIOperandNum (and the instruction).
997 static unsigned getOffsetONFromFION(const MachineInstr &MI,
998                                     unsigned FIOperandNum) {
999   // Take into account whether it's an add or mem instruction
1000   unsigned OffsetOperandNo = (FIOperandNum == 2) ? 1 : 2;
1001   if (MI.isInlineAsm())
1002     OffsetOperandNo = FIOperandNum - 1;
1003   else if (MI.getOpcode() == TargetOpcode::STACKMAP ||
1004            MI.getOpcode() == TargetOpcode::PATCHPOINT)
1005     OffsetOperandNo = FIOperandNum + 1;
1006 
1007   return OffsetOperandNo;
1008 }
1009 
1010 void
1011 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
1012                                      int SPAdj, unsigned FIOperandNum,
1013                                      RegScavenger *RS) const {
1014   assert(SPAdj == 0 && "Unexpected");
1015 
1016   // Get the instruction.
1017   MachineInstr &MI = *II;
1018   // Get the instruction's basic block.
1019   MachineBasicBlock &MBB = *MI.getParent();
1020   // Get the basic block's function.
1021   MachineFunction &MF = *MBB.getParent();
1022   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1023   // Get the instruction info.
1024   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1025   // Get the frame info.
1026   MachineFrameInfo &MFI = MF.getFrameInfo();
1027   DebugLoc dl = MI.getDebugLoc();
1028 
1029   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1030 
1031   // Get the frame index.
1032   int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
1033 
1034   // Get the frame pointer save index.  Users of this index are primarily
1035   // DYNALLOC instructions.
1036   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1037   int FPSI = FI->getFramePointerSaveIndex();
1038   // Get the instruction opcode.
1039   unsigned OpC = MI.getOpcode();
1040 
1041   if ((OpC == PPC::DYNAREAOFFSET || OpC == PPC::DYNAREAOFFSET8)) {
1042     lowerDynamicAreaOffset(II);
1043     return;
1044   }
1045 
1046   // Special case for dynamic alloca.
1047   if (FPSI && FrameIndex == FPSI &&
1048       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
1049     lowerDynamicAlloc(II);
1050     return;
1051   }
1052 
1053   // Special case for pseudo-ops SPILL_CR and RESTORE_CR, etc.
1054   if (OpC == PPC::SPILL_CR) {
1055     lowerCRSpilling(II, FrameIndex);
1056     return;
1057   } else if (OpC == PPC::RESTORE_CR) {
1058     lowerCRRestore(II, FrameIndex);
1059     return;
1060   } else if (OpC == PPC::SPILL_CRBIT) {
1061     lowerCRBitSpilling(II, FrameIndex);
1062     return;
1063   } else if (OpC == PPC::RESTORE_CRBIT) {
1064     lowerCRBitRestore(II, FrameIndex);
1065     return;
1066   } else if (OpC == PPC::SPILL_VRSAVE) {
1067     lowerVRSAVESpilling(II, FrameIndex);
1068     return;
1069   } else if (OpC == PPC::RESTORE_VRSAVE) {
1070     lowerVRSAVERestore(II, FrameIndex);
1071     return;
1072   }
1073 
1074   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
1075   MI.getOperand(FIOperandNum).ChangeToRegister(
1076     FrameIndex < 0 ? getBaseRegister(MF) : getFrameRegister(MF), false);
1077 
1078   // If the instruction is not present in ImmToIdxMap, then it has no immediate
1079   // form (and must be r+r).
1080   bool noImmForm = !MI.isInlineAsm() && OpC != TargetOpcode::STACKMAP &&
1081                    OpC != TargetOpcode::PATCHPOINT && !ImmToIdxMap.count(OpC);
1082 
1083   // Now add the frame object offset to the offset from r1.
1084   int Offset = MFI.getObjectOffset(FrameIndex);
1085   Offset += MI.getOperand(OffsetOperandNo).getImm();
1086 
1087   // If we're not using a Frame Pointer that has been set to the value of the
1088   // SP before having the stack size subtracted from it, then add the stack size
1089   // to Offset to get the correct offset.
1090   // Naked functions have stack size 0, although getStackSize may not reflect
1091   // that because we didn't call all the pieces that compute it for naked
1092   // functions.
1093   if (!MF.getFunction().hasFnAttribute(Attribute::Naked)) {
1094     if (!(hasBasePointer(MF) && FrameIndex < 0))
1095       Offset += MFI.getStackSize();
1096   }
1097 
1098   // If we can, encode the offset directly into the instruction.  If this is a
1099   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
1100   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
1101   // clear can be encoded.  This is extremely uncommon, because normally you
1102   // only "std" to a stack slot that is at least 4-byte aligned, but it can
1103   // happen in invalid code.
1104   assert(OpC != PPC::DBG_VALUE &&
1105          "This should be handled in a target-independent way");
1106   bool OffsetFitsMnemonic = (OpC == PPC::EVSTDD || OpC == PPC::EVLDD) ?
1107                             isUInt<8>(Offset) :
1108                             isInt<16>(Offset);
1109   if (!noImmForm && ((OffsetFitsMnemonic &&
1110                       ((Offset % offsetMinAlign(MI)) == 0)) ||
1111                      OpC == TargetOpcode::STACKMAP ||
1112                      OpC == TargetOpcode::PATCHPOINT)) {
1113     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1114     return;
1115   }
1116 
1117   // The offset doesn't fit into a single register, scavenge one to build the
1118   // offset in.
1119 
1120   bool is64Bit = TM.isPPC64();
1121   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1122   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1123   const TargetRegisterClass *RC = is64Bit ? G8RC : GPRC;
1124   Register SRegHi = MF.getRegInfo().createVirtualRegister(RC),
1125            SReg = MF.getRegInfo().createVirtualRegister(RC);
1126 
1127   // Insert a set of rA with the full offset value before the ld, st, or add
1128   if (isInt<16>(Offset))
1129     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LI8 : PPC::LI), SReg)
1130       .addImm(Offset);
1131   else {
1132     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SRegHi)
1133       .addImm(Offset >> 16);
1134     BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
1135       .addReg(SRegHi, RegState::Kill)
1136       .addImm(Offset);
1137   }
1138 
1139   // Convert into indexed form of the instruction:
1140   //
1141   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
1142   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
1143   unsigned OperandBase;
1144 
1145   if (noImmForm)
1146     OperandBase = 1;
1147   else if (OpC != TargetOpcode::INLINEASM &&
1148            OpC != TargetOpcode::INLINEASM_BR) {
1149     assert(ImmToIdxMap.count(OpC) &&
1150            "No indexed form of load or store available!");
1151     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
1152     MI.setDesc(TII.get(NewOpcode));
1153     OperandBase = 1;
1154   } else {
1155     OperandBase = OffsetOperandNo;
1156   }
1157 
1158   Register StackReg = MI.getOperand(FIOperandNum).getReg();
1159   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
1160   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
1161 }
1162 
1163 Register PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
1164   const PPCFrameLowering *TFI = getFrameLowering(MF);
1165 
1166   if (!TM.isPPC64())
1167     return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
1168   else
1169     return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
1170 }
1171 
1172 Register PPCRegisterInfo::getBaseRegister(const MachineFunction &MF) const {
1173   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1174   if (!hasBasePointer(MF))
1175     return getFrameRegister(MF);
1176 
1177   if (TM.isPPC64())
1178     return PPC::X30;
1179 
1180   if (Subtarget.isSVR4ABI() && TM.isPositionIndependent())
1181     return PPC::R29;
1182 
1183   return PPC::R30;
1184 }
1185 
1186 bool PPCRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
1187   if (!EnableBasePointer)
1188     return false;
1189   if (AlwaysBasePointer)
1190     return true;
1191 
1192   // If we need to realign the stack, then the stack pointer can no longer
1193   // serve as an offset into the caller's stack space. As a result, we need a
1194   // base pointer.
1195   return needsStackRealignment(MF);
1196 }
1197 
1198 /// Returns true if the instruction's frame index
1199 /// reference would be better served by a base register other than FP
1200 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
1201 /// references it should create new base registers for.
1202 bool PPCRegisterInfo::
1203 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
1204   assert(Offset < 0 && "Local offset must be negative");
1205 
1206   // It's the load/store FI references that cause issues, as it can be difficult
1207   // to materialize the offset if it won't fit in the literal field. Estimate
1208   // based on the size of the local frame and some conservative assumptions
1209   // about the rest of the stack frame (note, this is pre-regalloc, so
1210   // we don't know everything for certain yet) whether this offset is likely
1211   // to be out of range of the immediate. Return true if so.
1212 
1213   // We only generate virtual base registers for loads and stores that have
1214   // an r+i form. Return false for everything else.
1215   unsigned OpC = MI->getOpcode();
1216   if (!ImmToIdxMap.count(OpC))
1217     return false;
1218 
1219   // Don't generate a new virtual base register just to add zero to it.
1220   if ((OpC == PPC::ADDI || OpC == PPC::ADDI8) &&
1221       MI->getOperand(2).getImm() == 0)
1222     return false;
1223 
1224   MachineBasicBlock &MBB = *MI->getParent();
1225   MachineFunction &MF = *MBB.getParent();
1226   const PPCFrameLowering *TFI = getFrameLowering(MF);
1227   unsigned StackEst = TFI->determineFrameLayout(MF, true);
1228 
1229   // If we likely don't need a stack frame, then we probably don't need a
1230   // virtual base register either.
1231   if (!StackEst)
1232     return false;
1233 
1234   // Estimate an offset from the stack pointer.
1235   // The incoming offset is relating to the SP at the start of the function,
1236   // but when we access the local it'll be relative to the SP after local
1237   // allocation, so adjust our SP-relative offset by that allocation size.
1238   Offset += StackEst;
1239 
1240   // The frame pointer will point to the end of the stack, so estimate the
1241   // offset as the difference between the object offset and the FP location.
1242   return !isFrameOffsetLegal(MI, getBaseRegister(MF), Offset);
1243 }
1244 
1245 /// Insert defining instruction(s) for BaseReg to
1246 /// be a pointer to FrameIdx at the beginning of the basic block.
1247 void PPCRegisterInfo::materializeFrameBaseRegister(MachineBasicBlock *MBB,
1248                                                    Register BaseReg,
1249                                                    int FrameIdx,
1250                                                    int64_t Offset) const {
1251   unsigned ADDriOpc = TM.isPPC64() ? PPC::ADDI8 : PPC::ADDI;
1252 
1253   MachineBasicBlock::iterator Ins = MBB->begin();
1254   DebugLoc DL;                  // Defaults to "unknown"
1255   if (Ins != MBB->end())
1256     DL = Ins->getDebugLoc();
1257 
1258   const MachineFunction &MF = *MBB->getParent();
1259   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1260   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1261   const MCInstrDesc &MCID = TII.get(ADDriOpc);
1262   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
1263   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
1264 
1265   BuildMI(*MBB, Ins, DL, MCID, BaseReg)
1266     .addFrameIndex(FrameIdx).addImm(Offset);
1267 }
1268 
1269 void PPCRegisterInfo::resolveFrameIndex(MachineInstr &MI, Register BaseReg,
1270                                         int64_t Offset) const {
1271   unsigned FIOperandNum = 0;
1272   while (!MI.getOperand(FIOperandNum).isFI()) {
1273     ++FIOperandNum;
1274     assert(FIOperandNum < MI.getNumOperands() &&
1275            "Instr doesn't have FrameIndex operand!");
1276   }
1277 
1278   MI.getOperand(FIOperandNum).ChangeToRegister(BaseReg, false);
1279   unsigned OffsetOperandNo = getOffsetONFromFION(MI, FIOperandNum);
1280   Offset += MI.getOperand(OffsetOperandNo).getImm();
1281   MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
1282 
1283   MachineBasicBlock &MBB = *MI.getParent();
1284   MachineFunction &MF = *MBB.getParent();
1285   const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
1286   const TargetInstrInfo &TII = *Subtarget.getInstrInfo();
1287   const MCInstrDesc &MCID = MI.getDesc();
1288   MachineRegisterInfo &MRI = MF.getRegInfo();
1289   MRI.constrainRegClass(BaseReg,
1290                         TII.getRegClass(MCID, FIOperandNum, this, MF));
1291 }
1292 
1293 bool PPCRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
1294                                          Register BaseReg,
1295                                          int64_t Offset) const {
1296   unsigned FIOperandNum = 0;
1297   while (!MI->getOperand(FIOperandNum).isFI()) {
1298     ++FIOperandNum;
1299     assert(FIOperandNum < MI->getNumOperands() &&
1300            "Instr doesn't have FrameIndex operand!");
1301   }
1302 
1303   unsigned OffsetOperandNo = getOffsetONFromFION(*MI, FIOperandNum);
1304   Offset += MI->getOperand(OffsetOperandNo).getImm();
1305 
1306   return MI->getOpcode() == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
1307          MI->getOpcode() == TargetOpcode::STACKMAP ||
1308          MI->getOpcode() == TargetOpcode::PATCHPOINT ||
1309          (isInt<16>(Offset) && (Offset % offsetMinAlign(*MI)) == 0);
1310 }
1311