xref: /llvm-project/llvm/lib/Target/PowerPC/PPCRegisterInfo.cpp (revision f7183edb590b6d644856c29d1e90a2bb724aba08)
1 //===- PPCRegisterInfo.cpp - PowerPC Register Information -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains the PowerPC implementation of the TargetRegisterInfo
11 // class.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #define DEBUG_TYPE "reginfo"
16 #include "PPC.h"
17 #include "PPCInstrBuilder.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCRegisterInfo.h"
20 #include "PPCFrameInfo.h"
21 #include "PPCSubtarget.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/Function.h"
25 #include "llvm/Type.h"
26 #include "llvm/CodeGen/ValueTypes.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineLocation.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/RegisterScavenging.h"
34 #include "llvm/Target/TargetFrameInfo.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/ADT/BitVector.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include <cstdlib>
46 
47 // FIXME (64-bit): Eventually enable by default.
48 namespace llvm {
49 cl::opt<bool> EnablePPC32RS("enable-ppc32-regscavenger",
50                                    cl::init(false),
51                                    cl::desc("Enable PPC32 register scavenger"),
52                                    cl::Hidden);
53 cl::opt<bool> EnablePPC64RS("enable-ppc64-regscavenger",
54                                    cl::init(false),
55                                    cl::desc("Enable PPC64 register scavenger"),
56                                    cl::Hidden);
57 }
58 
59 using namespace llvm;
60 
61 #define EnableRegisterScavenging \
62   ((EnablePPC32RS && !Subtarget.isPPC64()) || \
63    (EnablePPC64RS && Subtarget.isPPC64()))
64 
65 // FIXME (64-bit): Should be inlined.
66 bool
67 PPCRegisterInfo::requiresRegisterScavenging(const MachineFunction &) const {
68   return EnableRegisterScavenging;
69 }
70 
71 /// getRegisterNumbering - Given the enum value for some register, e.g.
72 /// PPC::F14, return the number that it corresponds to (e.g. 14).
73 unsigned PPCRegisterInfo::getRegisterNumbering(unsigned RegEnum) {
74   using namespace PPC;
75   switch (RegEnum) {
76   case 0: return 0;
77   case R0 :  case X0 :  case F0 :  case V0 : case CR0:  case CR0LT: return  0;
78   case R1 :  case X1 :  case F1 :  case V1 : case CR1:  case CR0GT: return  1;
79   case R2 :  case X2 :  case F2 :  case V2 : case CR2:  case CR0EQ: return  2;
80   case R3 :  case X3 :  case F3 :  case V3 : case CR3:  case CR0UN: return  3;
81   case R4 :  case X4 :  case F4 :  case V4 : case CR4:  case CR1LT: return  4;
82   case R5 :  case X5 :  case F5 :  case V5 : case CR5:  case CR1GT: return  5;
83   case R6 :  case X6 :  case F6 :  case V6 : case CR6:  case CR1EQ: return  6;
84   case R7 :  case X7 :  case F7 :  case V7 : case CR7:  case CR1UN: return  7;
85   case R8 :  case X8 :  case F8 :  case V8 : case CR2LT: return  8;
86   case R9 :  case X9 :  case F9 :  case V9 : case CR2GT: return  9;
87   case R10:  case X10:  case F10:  case V10: case CR2EQ: return 10;
88   case R11:  case X11:  case F11:  case V11: case CR2UN: return 11;
89   case R12:  case X12:  case F12:  case V12: case CR3LT: return 12;
90   case R13:  case X13:  case F13:  case V13: case CR3GT: return 13;
91   case R14:  case X14:  case F14:  case V14: case CR3EQ: return 14;
92   case R15:  case X15:  case F15:  case V15: case CR3UN: return 15;
93   case R16:  case X16:  case F16:  case V16: case CR4LT: return 16;
94   case R17:  case X17:  case F17:  case V17: case CR4GT: return 17;
95   case R18:  case X18:  case F18:  case V18: case CR4EQ: return 18;
96   case R19:  case X19:  case F19:  case V19: case CR4UN: return 19;
97   case R20:  case X20:  case F20:  case V20: case CR5LT: return 20;
98   case R21:  case X21:  case F21:  case V21: case CR5GT: return 21;
99   case R22:  case X22:  case F22:  case V22: case CR5EQ: return 22;
100   case R23:  case X23:  case F23:  case V23: case CR5UN: return 23;
101   case R24:  case X24:  case F24:  case V24: case CR6LT: return 24;
102   case R25:  case X25:  case F25:  case V25: case CR6GT: return 25;
103   case R26:  case X26:  case F26:  case V26: case CR6EQ: return 26;
104   case R27:  case X27:  case F27:  case V27: case CR6UN: return 27;
105   case R28:  case X28:  case F28:  case V28: case CR7LT: return 28;
106   case R29:  case X29:  case F29:  case V29: case CR7GT: return 29;
107   case R30:  case X30:  case F30:  case V30: case CR7EQ: return 30;
108   case R31:  case X31:  case F31:  case V31: case CR7UN: return 31;
109   default:
110     llvm_unreachable("Unhandled reg in PPCRegisterInfo::getRegisterNumbering!");
111   }
112 }
113 
114 PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST,
115                                  const TargetInstrInfo &tii)
116   : PPCGenRegisterInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
117     Subtarget(ST), TII(tii) {
118   ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
119   ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
120   ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
121   ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
122   ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
123   ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
124   ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
125   ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
126 
127   // 64-bit
128   ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
129   ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
130   ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
131   ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
132   ImmToIdxMap[PPC::ADDI8] = PPC::ADD8; ImmToIdxMap[PPC::STD_32] = PPC::STDX_32;
133 }
134 
135 /// getPointerRegClass - Return the register class to use to hold pointers.
136 /// This is used for addressing modes.
137 const TargetRegisterClass *
138 PPCRegisterInfo::getPointerRegClass(unsigned Kind) const {
139   if (Subtarget.isPPC64())
140     return &PPC::G8RCRegClass;
141   return &PPC::GPRCRegClass;
142 }
143 
144 const unsigned*
145 PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
146   // 32-bit Darwin calling convention.
147   static const unsigned Darwin32_CalleeSavedRegs[] = {
148               PPC::R13, PPC::R14, PPC::R15,
149     PPC::R16, PPC::R17, PPC::R18, PPC::R19,
150     PPC::R20, PPC::R21, PPC::R22, PPC::R23,
151     PPC::R24, PPC::R25, PPC::R26, PPC::R27,
152     PPC::R28, PPC::R29, PPC::R30, PPC::R31,
153 
154     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
155     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
156     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
157     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
158     PPC::F30, PPC::F31,
159 
160     PPC::CR2, PPC::CR3, PPC::CR4,
161     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
162     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
163     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
164 
165     PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
166     PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
167     PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
168 
169     PPC::LR,  0
170   };
171 
172   // 32-bit SVR4 calling convention.
173   static const unsigned SVR4_CalleeSavedRegs[] = {
174                         PPC::R14, PPC::R15,
175     PPC::R16, PPC::R17, PPC::R18, PPC::R19,
176     PPC::R20, PPC::R21, PPC::R22, PPC::R23,
177     PPC::R24, PPC::R25, PPC::R26, PPC::R27,
178     PPC::R28, PPC::R29, PPC::R30, PPC::R31,
179 
180     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
181     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
182     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
183     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
184     PPC::F30, PPC::F31,
185 
186     PPC::CR2, PPC::CR3, PPC::CR4,
187 
188     PPC::VRSAVE,
189 
190     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
191     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
192     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
193 
194     PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
195     PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
196     PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
197 
198     0
199   };
200   // 64-bit Darwin calling convention.
201   static const unsigned Darwin64_CalleeSavedRegs[] = {
202     PPC::X14, PPC::X15,
203     PPC::X16, PPC::X17, PPC::X18, PPC::X19,
204     PPC::X20, PPC::X21, PPC::X22, PPC::X23,
205     PPC::X24, PPC::X25, PPC::X26, PPC::X27,
206     PPC::X28, PPC::X29, PPC::X30, PPC::X31,
207 
208     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
209     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
210     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
211     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
212     PPC::F30, PPC::F31,
213 
214     PPC::CR2, PPC::CR3, PPC::CR4,
215     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
216     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
217     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
218 
219     PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
220     PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
221     PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
222 
223     PPC::LR8,  0
224   };
225 
226   // 64-bit SVR4 calling convention.
227   static const unsigned SVR4_64_CalleeSavedRegs[] = {
228     PPC::X14, PPC::X15,
229     PPC::X16, PPC::X17, PPC::X18, PPC::X19,
230     PPC::X20, PPC::X21, PPC::X22, PPC::X23,
231     PPC::X24, PPC::X25, PPC::X26, PPC::X27,
232     PPC::X28, PPC::X29, PPC::X30, PPC::X31,
233 
234     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
235     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
236     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
237     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
238     PPC::F30, PPC::F31,
239 
240     PPC::CR2, PPC::CR3, PPC::CR4,
241 
242     PPC::VRSAVE,
243 
244     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
245     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
246     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
247 
248     PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
249     PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
250     PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
251 
252     0
253   };
254 
255   if (Subtarget.isDarwinABI())
256     return Subtarget.isPPC64() ? Darwin64_CalleeSavedRegs :
257                                  Darwin32_CalleeSavedRegs;
258 
259   return Subtarget.isPPC64() ? SVR4_64_CalleeSavedRegs : SVR4_CalleeSavedRegs;
260 }
261 
262 // needsFP - Return true if the specified function should have a dedicated frame
263 // pointer register.  This is true if the function has variable sized allocas or
264 // if frame pointer elimination is disabled.
265 //
266 static bool needsFP(const MachineFunction &MF) {
267   const MachineFrameInfo *MFI = MF.getFrameInfo();
268   // Naked functions have no stack frame pushed, so we don't have a frame pointer.
269   if (MF.getFunction()->hasFnAttr(Attribute::Naked))
270     return false;
271   return DisableFramePointerElim(MF) || MFI->hasVarSizedObjects() ||
272     (GuaranteedTailCallOpt && MF.getInfo<PPCFunctionInfo>()->hasFastCall());
273 }
274 
275 static bool spillsCR(const MachineFunction &MF) {
276   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
277   return FuncInfo->isCRSpilled();
278 }
279 
280 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
281   BitVector Reserved(getNumRegs());
282   Reserved.set(PPC::R0);
283   Reserved.set(PPC::R1);
284   Reserved.set(PPC::LR);
285   Reserved.set(PPC::LR8);
286   Reserved.set(PPC::RM);
287 
288   // The SVR4 ABI reserves r2 and r13
289   if (Subtarget.isSVR4ABI()) {
290     Reserved.set(PPC::R2);  // System-reserved register
291     Reserved.set(PPC::R13); // Small Data Area pointer register
292   }
293   // Reserve R2 on Darwin to hack around the problem of save/restore of CR
294   // when the stack frame is too big to address directly; we need two regs.
295   // This is a hack.
296   if (Subtarget.isDarwinABI()) {
297     Reserved.set(PPC::R2);
298   }
299 
300   // On PPC64, r13 is the thread pointer. Never allocate this register.
301   // Note that this is over conservative, as it also prevents allocation of R31
302   // when the FP is not needed.
303   if (Subtarget.isPPC64()) {
304     Reserved.set(PPC::R13);
305     Reserved.set(PPC::R31);
306 
307     if (!EnableRegisterScavenging)
308       Reserved.set(PPC::R0);    // FIXME (64-bit): Remove
309 
310     Reserved.set(PPC::X0);
311     Reserved.set(PPC::X1);
312     Reserved.set(PPC::X13);
313     Reserved.set(PPC::X31);
314 
315     // The 64-bit SVR4 ABI reserves r2 for the TOC pointer.
316     if (Subtarget.isSVR4ABI()) {
317       Reserved.set(PPC::X2);
318     }
319     // Reserve R2 on Darwin to hack around the problem of save/restore of CR
320     // when the stack frame is too big to address directly; we need two regs.
321     // This is a hack.
322     if (Subtarget.isDarwinABI()) {
323       Reserved.set(PPC::X2);
324     }
325   }
326 
327   if (needsFP(MF))
328     Reserved.set(PPC::R31);
329 
330   return Reserved;
331 }
332 
333 //===----------------------------------------------------------------------===//
334 // Stack Frame Processing methods
335 //===----------------------------------------------------------------------===//
336 
337 // hasFP - Return true if the specified function actually has a dedicated frame
338 // pointer register.  This is true if the function needs a frame pointer and has
339 // a non-zero stack size.
340 bool PPCRegisterInfo::hasFP(const MachineFunction &MF) const {
341   const MachineFrameInfo *MFI = MF.getFrameInfo();
342   return MFI->getStackSize() && needsFP(MF);
343 }
344 
345 /// MustSaveLR - Return true if this function requires that we save the LR
346 /// register onto the stack in the prolog and restore it in the epilog of the
347 /// function.
348 static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
349   const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
350 
351   // We need a save/restore of LR if there is any def of LR (which is
352   // defined by calls, including the PIC setup sequence), or if there is
353   // some use of the LR stack slot (e.g. for builtin_return_address).
354   // (LR comes in 32 and 64 bit versions.)
355   MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
356   return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
357 }
358 
359 
360 
361 void PPCRegisterInfo::
362 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
363                               MachineBasicBlock::iterator I) const {
364   if (GuaranteedTailCallOpt && I->getOpcode() == PPC::ADJCALLSTACKUP) {
365     // Add (actually subtract) back the amount the callee popped on return.
366     if (int CalleeAmt =  I->getOperand(1).getImm()) {
367       bool is64Bit = Subtarget.isPPC64();
368       CalleeAmt *= -1;
369       unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
370       unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
371       unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
372       unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
373       unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
374       unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
375       MachineInstr *MI = I;
376       DebugLoc dl = MI->getDebugLoc();
377 
378       if (isInt<16>(CalleeAmt)) {
379         BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg).addReg(StackReg).
380           addImm(CalleeAmt);
381       } else {
382         MachineBasicBlock::iterator MBBI = I;
383         BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
384           .addImm(CalleeAmt >> 16);
385         BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
386           .addReg(TmpReg, RegState::Kill)
387           .addImm(CalleeAmt & 0xFFFF);
388         BuildMI(MBB, MBBI, dl, TII.get(ADDInstr))
389           .addReg(StackReg)
390           .addReg(StackReg)
391           .addReg(TmpReg);
392       }
393     }
394   }
395   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
396   MBB.erase(I);
397 }
398 
399 /// findScratchRegister - Find a 'free' PPC register. Try for a call-clobbered
400 /// register first and then a spilled callee-saved register if that fails.
401 static
402 unsigned findScratchRegister(MachineBasicBlock::iterator II, RegScavenger *RS,
403                              const TargetRegisterClass *RC, int SPAdj) {
404   assert(RS && "Register scavenging must be on");
405   unsigned Reg = RS->FindUnusedReg(RC);
406   // FIXME: move ARM callee-saved reg scan to target independent code, then
407   // search for already spilled CS register here.
408   if (Reg == 0)
409     Reg = RS->scavengeRegister(RC, II, SPAdj);
410   return Reg;
411 }
412 
413 /// lowerDynamicAlloc - Generate the code for allocating an object in the
414 /// current frame.  The sequence of code with be in the general form
415 ///
416 ///   addi   R0, SP, \#frameSize ; get the address of the previous frame
417 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
418 ///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
419 ///
420 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II,
421                                         int SPAdj, RegScavenger *RS) const {
422   // Get the instruction.
423   MachineInstr &MI = *II;
424   // Get the instruction's basic block.
425   MachineBasicBlock &MBB = *MI.getParent();
426   // Get the basic block's function.
427   MachineFunction &MF = *MBB.getParent();
428   // Get the frame info.
429   MachineFrameInfo *MFI = MF.getFrameInfo();
430   // Determine whether 64-bit pointers are used.
431   bool LP64 = Subtarget.isPPC64();
432   DebugLoc dl = MI.getDebugLoc();
433 
434   // Get the maximum call stack size.
435   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
436   // Get the total frame size.
437   unsigned FrameSize = MFI->getStackSize();
438 
439   // Get stack alignments.
440   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
441   unsigned MaxAlign = MFI->getMaxAlignment();
442   if (MaxAlign > TargetAlign)
443     report_fatal_error("Dynamic alloca with large aligns not supported");
444 
445   // Determine the previous frame's address.  If FrameSize can't be
446   // represented as 16 bits or we need special alignment, then we load the
447   // previous frame's address from 0(SP).  Why not do an addis of the hi?
448   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
449   // Constructing the constant and adding would take 3 instructions.
450   // Fortunately, a frame greater than 32K is rare.
451   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
452   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
453   const TargetRegisterClass *RC = LP64 ? G8RC : GPRC;
454 
455   // FIXME (64-bit): Use "findScratchRegister"
456   unsigned Reg;
457   if (EnableRegisterScavenging)
458     Reg = findScratchRegister(II, RS, RC, SPAdj);
459   else
460     Reg = PPC::R0;
461 
462   if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
463     BuildMI(MBB, II, dl, TII.get(PPC::ADDI), Reg)
464       .addReg(PPC::R31)
465       .addImm(FrameSize);
466   } else if (LP64) {
467     if (EnableRegisterScavenging) // FIXME (64-bit): Use "true" part.
468       BuildMI(MBB, II, dl, TII.get(PPC::LD), Reg)
469         .addImm(0)
470         .addReg(PPC::X1);
471     else
472       BuildMI(MBB, II, dl, TII.get(PPC::LD), PPC::X0)
473         .addImm(0)
474         .addReg(PPC::X1);
475   } else {
476     BuildMI(MBB, II, dl, TII.get(PPC::LWZ), Reg)
477       .addImm(0)
478       .addReg(PPC::R1);
479   }
480 
481   // Grow the stack and update the stack pointer link, then determine the
482   // address of new allocated space.
483   if (LP64) {
484     if (EnableRegisterScavenging) // FIXME (64-bit): Use "true" part.
485       BuildMI(MBB, II, dl, TII.get(PPC::STDUX))
486         .addReg(Reg, RegState::Kill)
487         .addReg(PPC::X1)
488         .addReg(MI.getOperand(1).getReg());
489     else
490       BuildMI(MBB, II, dl, TII.get(PPC::STDUX))
491         .addReg(PPC::X0, RegState::Kill)
492         .addReg(PPC::X1)
493         .addReg(MI.getOperand(1).getReg());
494 
495     if (!MI.getOperand(1).isKill())
496       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
497         .addReg(PPC::X1)
498         .addImm(maxCallFrameSize);
499     else
500       // Implicitly kill the register.
501       BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
502         .addReg(PPC::X1)
503         .addImm(maxCallFrameSize)
504         .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
505   } else {
506     BuildMI(MBB, II, dl, TII.get(PPC::STWUX))
507       .addReg(Reg, RegState::Kill)
508       .addReg(PPC::R1)
509       .addReg(MI.getOperand(1).getReg());
510 
511     if (!MI.getOperand(1).isKill())
512       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
513         .addReg(PPC::R1)
514         .addImm(maxCallFrameSize);
515     else
516       // Implicitly kill the register.
517       BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
518         .addReg(PPC::R1)
519         .addImm(maxCallFrameSize)
520         .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
521   }
522 
523   // Discard the DYNALLOC instruction.
524   MBB.erase(II);
525 }
526 
527 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
528 /// reserving a whole register (R0), we scrounge for one here. This generates
529 /// code like this:
530 ///
531 ///   mfcr rA                  ; Move the conditional register into GPR rA.
532 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
533 ///   stw rA, FI               ; Store rA to the frame.
534 ///
535 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
536                                       unsigned FrameIndex, int SPAdj,
537                                       RegScavenger *RS) const {
538   // Get the instruction.
539   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>, <FI>
540   // Get the instruction's basic block.
541   MachineBasicBlock &MBB = *MI.getParent();
542   DebugLoc dl = MI.getDebugLoc();
543 
544   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
545   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
546   const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
547   unsigned Reg = findScratchRegister(II, RS, RC, SPAdj);
548   unsigned SrcReg = MI.getOperand(0).getReg();
549 
550   // We need to store the CR in the low 4-bits of the saved value. First, issue
551   // an MFCRpsued to save all of the CRBits and, if needed, kill the SrcReg.
552   BuildMI(MBB, II, dl, TII.get(PPC::MFCRpseud), Reg)
553           .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
554 
555   // If the saved register wasn't CR0, shift the bits left so that they are in
556   // CR0's slot.
557   if (SrcReg != PPC::CR0)
558     // rlwinm rA, rA, ShiftBits, 0, 31.
559     BuildMI(MBB, II, dl, TII.get(PPC::RLWINM), Reg)
560       .addReg(Reg, RegState::Kill)
561       .addImm(PPCRegisterInfo::getRegisterNumbering(SrcReg) * 4)
562       .addImm(0)
563       .addImm(31);
564 
565   addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::STW))
566                     .addReg(Reg, getKillRegState(MI.getOperand(1).getImm())),
567                     FrameIndex);
568 
569   // Discard the pseudo instruction.
570   MBB.erase(II);
571 }
572 
573 void
574 PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
575                                      int SPAdj, RegScavenger *RS) const {
576   assert(SPAdj == 0 && "Unexpected");
577 
578   // Get the instruction.
579   MachineInstr &MI = *II;
580   // Get the instruction's basic block.
581   MachineBasicBlock &MBB = *MI.getParent();
582   // Get the basic block's function.
583   MachineFunction &MF = *MBB.getParent();
584   // Get the frame info.
585   MachineFrameInfo *MFI = MF.getFrameInfo();
586   DebugLoc dl = MI.getDebugLoc();
587 
588   // Find out which operand is the frame index.
589   unsigned FIOperandNo = 0;
590   while (!MI.getOperand(FIOperandNo).isFI()) {
591     ++FIOperandNo;
592     assert(FIOperandNo != MI.getNumOperands() &&
593            "Instr doesn't have FrameIndex operand!");
594   }
595   // Take into account whether it's an add or mem instruction
596   unsigned OffsetOperandNo = (FIOperandNo == 2) ? 1 : 2;
597   if (MI.isInlineAsm())
598     OffsetOperandNo = FIOperandNo-1;
599 
600   // Get the frame index.
601   int FrameIndex = MI.getOperand(FIOperandNo).getIndex();
602 
603   // Get the frame pointer save index.  Users of this index are primarily
604   // DYNALLOC instructions.
605   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
606   int FPSI = FI->getFramePointerSaveIndex();
607   // Get the instruction opcode.
608   unsigned OpC = MI.getOpcode();
609 
610   // Special case for dynamic alloca.
611   if (FPSI && FrameIndex == FPSI &&
612       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
613     lowerDynamicAlloc(II, SPAdj, RS);
614     return;
615   }
616 
617   // Special case for pseudo-op SPILL_CR.
618   if (EnableRegisterScavenging) // FIXME (64-bit): Enable by default.
619     if (OpC == PPC::SPILL_CR) {
620       lowerCRSpilling(II, FrameIndex, SPAdj, RS);
621       return;
622     }
623 
624   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
625   MI.getOperand(FIOperandNo).ChangeToRegister(hasFP(MF) ? PPC::R31 : PPC::R1,
626                                               false);
627 
628   // Figure out if the offset in the instruction is shifted right two bits. This
629   // is true for instructions like "STD", which the machine implicitly adds two
630   // low zeros to.
631   bool isIXAddr = false;
632   switch (OpC) {
633   case PPC::LWA:
634   case PPC::LD:
635   case PPC::STD:
636   case PPC::STD_32:
637     isIXAddr = true;
638     break;
639   }
640 
641   // Now add the frame object offset to the offset from r1.
642   int Offset = MFI->getObjectOffset(FrameIndex);
643   if (!isIXAddr)
644     Offset += MI.getOperand(OffsetOperandNo).getImm();
645   else
646     Offset += MI.getOperand(OffsetOperandNo).getImm() << 2;
647 
648   // If we're not using a Frame Pointer that has been set to the value of the
649   // SP before having the stack size subtracted from it, then add the stack size
650   // to Offset to get the correct offset.
651   // Naked functions have stack size 0, although getStackSize may not reflect that
652   // because we didn't call all the pieces that compute it for naked functions.
653   if (!MF.getFunction()->hasFnAttr(Attribute::Naked))
654     Offset += MFI->getStackSize();
655 
656   // If we can, encode the offset directly into the instruction.  If this is a
657   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
658   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
659   // clear can be encoded.  This is extremely uncommon, because normally you
660   // only "std" to a stack slot that is at least 4-byte aligned, but it can
661   // happen in invalid code.
662   if (isInt<16>(Offset) && (!isIXAddr || (Offset & 3) == 0)) {
663     if (isIXAddr)
664       Offset >>= 2;    // The actual encoded value has the low two bits zero.
665     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
666     return;
667   }
668 
669   // The offset doesn't fit into a single register, scavenge one to build the
670   // offset in.
671   // FIXME: figure out what SPAdj is doing here.
672 
673   // FIXME (64-bit): Use "findScratchRegister".
674   unsigned SReg;
675   if (EnableRegisterScavenging)
676     SReg = findScratchRegister(II, RS, &PPC::GPRCRegClass, SPAdj);
677   else
678     SReg = PPC::R0;
679 
680   // Insert a set of rA with the full offset value before the ld, st, or add
681   BuildMI(MBB, II, dl, TII.get(PPC::LIS), SReg)
682     .addImm(Offset >> 16);
683   BuildMI(MBB, II, dl, TII.get(PPC::ORI), SReg)
684     .addReg(SReg, RegState::Kill)
685     .addImm(Offset);
686 
687   // Convert into indexed form of the instruction:
688   //
689   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
690   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
691   unsigned OperandBase;
692 
693   if (OpC != TargetOpcode::INLINEASM) {
694     assert(ImmToIdxMap.count(OpC) &&
695            "No indexed form of load or store available!");
696     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
697     MI.setDesc(TII.get(NewOpcode));
698     OperandBase = 1;
699   } else {
700     OperandBase = OffsetOperandNo;
701   }
702 
703   unsigned StackReg = MI.getOperand(FIOperandNo).getReg();
704   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
705   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false);
706 }
707 
708 void
709 PPCRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
710                                                       RegScavenger *RS) const {
711   //  Save and clear the LR state.
712   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
713   unsigned LR = getRARegister();
714   FI->setMustSaveLR(MustSaveLR(MF, LR));
715   MF.getRegInfo().setPhysRegUnused(LR);
716 
717   //  Save R31 if necessary
718   int FPSI = FI->getFramePointerSaveIndex();
719   bool isPPC64 = Subtarget.isPPC64();
720   bool isDarwinABI  = Subtarget.isDarwinABI();
721   MachineFrameInfo *MFI = MF.getFrameInfo();
722 
723   // If the frame pointer save index hasn't been defined yet.
724   if (!FPSI && needsFP(MF)) {
725     // Find out what the fix offset of the frame pointer save area.
726     int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(isPPC64,
727                                                            isDarwinABI);
728     // Allocate the frame index for frame pointer save area.
729     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
730     // Save the result.
731     FI->setFramePointerSaveIndex(FPSI);
732   }
733 
734   // Reserve stack space to move the linkage area to in case of a tail call.
735   int TCSPDelta = 0;
736   if (GuaranteedTailCallOpt && (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
737     MF.getFrameInfo()->CreateFixedObject(-1 * TCSPDelta, TCSPDelta, true);
738   }
739 
740   // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
741   // a large stack, which will require scavenging a register to materialize a
742   // large offset.
743   // FIXME: this doesn't actually check stack size, so is a bit pessimistic
744   // FIXME: doesn't detect whether or not we need to spill vXX, which requires
745   //        r0 for now.
746 
747   if (EnableRegisterScavenging) // FIXME (64-bit): Enable.
748     if (needsFP(MF) || spillsCR(MF)) {
749       const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
750       const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
751       const TargetRegisterClass *RC = isPPC64 ? G8RC : GPRC;
752       RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
753                                                          RC->getAlignment(),
754                                                          false));
755     }
756 }
757 
758 void
759 PPCRegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF)
760                                                      const {
761   // Early exit if not using the SVR4 ABI.
762   if (!Subtarget.isSVR4ABI()) {
763     return;
764   }
765 
766   // Get callee saved register information.
767   MachineFrameInfo *FFI = MF.getFrameInfo();
768   const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
769 
770   // Early exit if no callee saved registers are modified!
771   if (CSI.empty() && !needsFP(MF)) {
772     return;
773   }
774 
775   unsigned MinGPR = PPC::R31;
776   unsigned MinG8R = PPC::X31;
777   unsigned MinFPR = PPC::F31;
778   unsigned MinVR = PPC::V31;
779 
780   bool HasGPSaveArea = false;
781   bool HasG8SaveArea = false;
782   bool HasFPSaveArea = false;
783   bool HasCRSaveArea = false;
784   bool HasVRSAVESaveArea = false;
785   bool HasVRSaveArea = false;
786 
787   SmallVector<CalleeSavedInfo, 18> GPRegs;
788   SmallVector<CalleeSavedInfo, 18> G8Regs;
789   SmallVector<CalleeSavedInfo, 18> FPRegs;
790   SmallVector<CalleeSavedInfo, 18> VRegs;
791 
792   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
793     unsigned Reg = CSI[i].getReg();
794     if (PPC::GPRCRegisterClass->contains(Reg)) {
795       HasGPSaveArea = true;
796 
797       GPRegs.push_back(CSI[i]);
798 
799       if (Reg < MinGPR) {
800         MinGPR = Reg;
801       }
802     } else if (PPC::G8RCRegisterClass->contains(Reg)) {
803       HasG8SaveArea = true;
804 
805       G8Regs.push_back(CSI[i]);
806 
807       if (Reg < MinG8R) {
808         MinG8R = Reg;
809       }
810     } else if (PPC::F8RCRegisterClass->contains(Reg)) {
811       HasFPSaveArea = true;
812 
813       FPRegs.push_back(CSI[i]);
814 
815       if (Reg < MinFPR) {
816         MinFPR = Reg;
817       }
818 // FIXME SVR4: Disable CR save area for now.
819     } else if (PPC::CRBITRCRegisterClass->contains(Reg)
820                || PPC::CRRCRegisterClass->contains(Reg)) {
821 //      HasCRSaveArea = true;
822     } else if (PPC::VRSAVERCRegisterClass->contains(Reg)) {
823       HasVRSAVESaveArea = true;
824     } else if (PPC::VRRCRegisterClass->contains(Reg)) {
825       HasVRSaveArea = true;
826 
827       VRegs.push_back(CSI[i]);
828 
829       if (Reg < MinVR) {
830         MinVR = Reg;
831       }
832     } else {
833       llvm_unreachable("Unknown RegisterClass!");
834     }
835   }
836 
837   PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
838 
839   int64_t LowerBound = 0;
840 
841   // Take into account stack space reserved for tail calls.
842   int TCSPDelta = 0;
843   if (GuaranteedTailCallOpt && (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
844     LowerBound = TCSPDelta;
845   }
846 
847   // The Floating-point register save area is right below the back chain word
848   // of the previous stack frame.
849   if (HasFPSaveArea) {
850     for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
851       int FI = FPRegs[i].getFrameIdx();
852 
853       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
854     }
855 
856     LowerBound -= (31 - getRegisterNumbering(MinFPR) + 1) * 8;
857   }
858 
859   // Check whether the frame pointer register is allocated. If so, make sure it
860   // is spilled to the correct offset.
861   if (needsFP(MF)) {
862     HasGPSaveArea = true;
863 
864     int FI = PFI->getFramePointerSaveIndex();
865     assert(FI && "No Frame Pointer Save Slot!");
866 
867     FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
868   }
869 
870   // General register save area starts right below the Floating-point
871   // register save area.
872   if (HasGPSaveArea || HasG8SaveArea) {
873     // Move general register save area spill slots down, taking into account
874     // the size of the Floating-point register save area.
875     for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
876       int FI = GPRegs[i].getFrameIdx();
877 
878       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
879     }
880 
881     // Move general register save area spill slots down, taking into account
882     // the size of the Floating-point register save area.
883     for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
884       int FI = G8Regs[i].getFrameIdx();
885 
886       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
887     }
888 
889     unsigned MinReg = std::min<unsigned>(getRegisterNumbering(MinGPR),
890                                          getRegisterNumbering(MinG8R));
891 
892     if (Subtarget.isPPC64()) {
893       LowerBound -= (31 - MinReg + 1) * 8;
894     } else {
895       LowerBound -= (31 - MinReg + 1) * 4;
896     }
897   }
898 
899   // The CR save area is below the general register save area.
900   if (HasCRSaveArea) {
901     // FIXME SVR4: Is it actually possible to have multiple elements in CSI
902     //             which have the CR/CRBIT register class?
903     // Adjust the frame index of the CR spill slot.
904     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
905       unsigned Reg = CSI[i].getReg();
906 
907       if (PPC::CRBITRCRegisterClass->contains(Reg) ||
908           PPC::CRRCRegisterClass->contains(Reg)) {
909         int FI = CSI[i].getFrameIdx();
910 
911         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
912       }
913     }
914 
915     LowerBound -= 4; // The CR save area is always 4 bytes long.
916   }
917 
918   if (HasVRSAVESaveArea) {
919     // FIXME SVR4: Is it actually possible to have multiple elements in CSI
920     //             which have the VRSAVE register class?
921     // Adjust the frame index of the VRSAVE spill slot.
922     for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
923       unsigned Reg = CSI[i].getReg();
924 
925       if (PPC::VRSAVERCRegisterClass->contains(Reg)) {
926         int FI = CSI[i].getFrameIdx();
927 
928         FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
929       }
930     }
931 
932     LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
933   }
934 
935   if (HasVRSaveArea) {
936     // Insert alignment padding, we need 16-byte alignment.
937     LowerBound = (LowerBound - 15) & ~(15);
938 
939     for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
940       int FI = VRegs[i].getFrameIdx();
941 
942       FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
943     }
944   }
945 }
946 
947 unsigned PPCRegisterInfo::getRARegister() const {
948   return !Subtarget.isPPC64() ? PPC::LR : PPC::LR8;
949 }
950 
951 unsigned PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
952   if (!Subtarget.isPPC64())
953     return hasFP(MF) ? PPC::R31 : PPC::R1;
954   else
955     return hasFP(MF) ? PPC::X31 : PPC::X1;
956 }
957 
958 void PPCRegisterInfo::getInitialFrameState(std::vector<MachineMove> &Moves)
959                                                                          const {
960   // Initial state of the frame pointer is R1.
961   MachineLocation Dst(MachineLocation::VirtualFP);
962   MachineLocation Src(PPC::R1, 0);
963   Moves.push_back(MachineMove(0, Dst, Src));
964 }
965 
966 unsigned PPCRegisterInfo::getEHExceptionRegister() const {
967   return !Subtarget.isPPC64() ? PPC::R3 : PPC::X3;
968 }
969 
970 unsigned PPCRegisterInfo::getEHHandlerRegister() const {
971   return !Subtarget.isPPC64() ? PPC::R4 : PPC::X4;
972 }
973 
974 int PPCRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
975   // FIXME: Most probably dwarf numbers differs for Linux and Darwin
976   return PPCGenRegisterInfo::getDwarfRegNumFull(RegNum, 0);
977 }
978 
979 #include "PPCGenRegisterInfo.inc"
980