1//===-- PPCRegisterInfo.cpp - PowerPC Register Information ----------------===//
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 "PPCRegisterInfo.h"
17#include "PPC.h"
18#include "PPCInstrBuilder.h"
19#include "PPCMachineFunctionInfo.h"
20#include "PPCFrameLowering.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/MachineRegisterInfo.h"
32#include "llvm/CodeGen/RegisterScavenging.h"
33#include "llvm/Target/TargetFrameLowering.h"
34#include "llvm/Target/TargetInstrInfo.h"
35#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetOptions.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/Debug.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/MathExtras.h"
41#include "llvm/Support/raw_ostream.h"
42#include "llvm/ADT/BitVector.h"
43#include "llvm/ADT/STLExtras.h"
44#include <cstdlib>
45
46#define GET_REGINFO_TARGET_DESC
47#include "PPCGenRegisterInfo.inc"
48
49namespace llvm {
50cl::opt<bool> DisablePPC32RS("disable-ppc32-regscavenger",
51                                   cl::init(false),
52                                   cl::desc("Disable PPC32 register scavenger"),
53                                   cl::Hidden);
54cl::opt<bool> DisablePPC64RS("disable-ppc64-regscavenger",
55                                   cl::init(false),
56                                   cl::desc("Disable PPC64 register scavenger"),
57                                   cl::Hidden);
58}
59
60using namespace llvm;
61
62// FIXME (64-bit): Should be inlined.
63bool
64PPCRegisterInfo::requiresRegisterScavenging(const MachineFunction &) const {
65  return ((!DisablePPC32RS && !Subtarget.isPPC64()) ||
66          (!DisablePPC64RS && Subtarget.isPPC64()));
67}
68
69PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST,
70                                 const TargetInstrInfo &tii)
71  : PPCGenRegisterInfo(ST.isPPC64() ? PPC::LR8 : PPC::LR,
72                       ST.isPPC64() ? 0 : 1,
73                       ST.isPPC64() ? 0 : 1),
74    Subtarget(ST), TII(tii), CRSpillFrameIdx(0) {
75  ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
76  ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
77  ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
78  ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
79  ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
80  ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
81  ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
82  ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
83
84  // 64-bit
85  ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
86  ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
87  ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
88  ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
89  ImmToIdxMap[PPC::ADDI8] = PPC::ADD8; ImmToIdxMap[PPC::STD_32] = PPC::STDX_32;
90}
91
92bool
93PPCRegisterInfo::trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
94  return requiresRegisterScavenging(MF);
95}
96
97
98/// getPointerRegClass - Return the register class to use to hold pointers.
99/// This is used for addressing modes.
100const TargetRegisterClass *
101PPCRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
102                                                                       const {
103  if (Subtarget.isPPC64())
104    return &PPC::G8RCRegClass;
105  return &PPC::GPRCRegClass;
106}
107
108const uint16_t*
109PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
110  if (Subtarget.isDarwinABI())
111    return Subtarget.isPPC64() ? CSR_Darwin64_SaveList :
112                                 CSR_Darwin32_SaveList;
113
114  // For 32-bit SVR4, also initialize the frame index associated with
115  // the CR spill slot.
116  if (!Subtarget.isPPC64())
117    CRSpillFrameIdx = 0;
118
119  return Subtarget.isPPC64() ? CSR_SVR464_SaveList : CSR_SVR432_SaveList;
120}
121
122const uint32_t*
123PPCRegisterInfo::getCallPreservedMask(CallingConv::ID CC) const {
124  if (Subtarget.isDarwinABI())
125    return Subtarget.isPPC64() ? CSR_Darwin64_RegMask :
126                                 CSR_Darwin32_RegMask;
127
128  return Subtarget.isPPC64() ? CSR_SVR464_RegMask : CSR_SVR432_RegMask;
129}
130
131BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
132  BitVector Reserved(getNumRegs());
133  const PPCFrameLowering *PPCFI =
134    static_cast<const PPCFrameLowering*>(MF.getTarget().getFrameLowering());
135
136  Reserved.set(PPC::R0);
137  Reserved.set(PPC::R1);
138  Reserved.set(PPC::LR);
139  Reserved.set(PPC::LR8);
140  Reserved.set(PPC::RM);
141
142  // The SVR4 ABI reserves r2 and r13
143  if (Subtarget.isSVR4ABI()) {
144    Reserved.set(PPC::R2);  // System-reserved register
145    Reserved.set(PPC::R13); // Small Data Area pointer register
146  }
147  // Reserve R2 on Darwin to hack around the problem of save/restore of CR
148  // when the stack frame is too big to address directly; we need two regs.
149  // This is a hack.
150  if (Subtarget.isDarwinABI()) {
151    Reserved.set(PPC::R2);
152  }
153
154  // On PPC64, r13 is the thread pointer. Never allocate this register.
155  // Note that this is over conservative, as it also prevents allocation of R31
156  // when the FP is not needed.
157  if (Subtarget.isPPC64()) {
158    Reserved.set(PPC::R13);
159    Reserved.set(PPC::R31);
160
161    Reserved.set(PPC::X0);
162    Reserved.set(PPC::X1);
163    Reserved.set(PPC::X13);
164    Reserved.set(PPC::X31);
165
166    // The 64-bit SVR4 ABI reserves r2 for the TOC pointer.
167    if (Subtarget.isSVR4ABI()) {
168      Reserved.set(PPC::X2);
169    }
170    // Reserve X2 on Darwin to hack around the problem of save/restore of CR
171    // when the stack frame is too big to address directly; we need two regs.
172    // This is a hack.
173    if (Subtarget.isDarwinABI()) {
174      Reserved.set(PPC::X2);
175    }
176  }
177
178  if (PPCFI->needsFP(MF))
179    Reserved.set(PPC::R31);
180
181  return Reserved;
182}
183
184unsigned
185PPCRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
186                                         MachineFunction &MF) const {
187  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
188  const unsigned DefaultSafety = 1;
189
190  switch (RC->getID()) {
191  default:
192    return 0;
193  case PPC::G8RCRegClassID:
194  case PPC::GPRCRegClassID: {
195    unsigned FP = TFI->hasFP(MF) ? 1 : 0;
196    return 32 - FP - DefaultSafety;
197  }
198  case PPC::F8RCRegClassID:
199  case PPC::F4RCRegClassID:
200  case PPC::VRRCRegClassID:
201    return 32 - DefaultSafety;
202  case PPC::CRRCRegClassID:
203    return 8 - DefaultSafety;
204  }
205}
206
207bool
208PPCRegisterInfo::avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
209  switch (RC->getID()) {
210  case PPC::G8RCRegClassID:
211  case PPC::GPRCRegClassID:
212  case PPC::F8RCRegClassID:
213  case PPC::F4RCRegClassID:
214  case PPC::VRRCRegClassID:
215    return true;
216  default:
217    return false;
218  }
219}
220
221//===----------------------------------------------------------------------===//
222// Stack Frame Processing methods
223//===----------------------------------------------------------------------===//
224
225void PPCRegisterInfo::
226eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
227                              MachineBasicBlock::iterator I) const {
228  if (MF.getTarget().Options.GuaranteedTailCallOpt &&
229      I->getOpcode() == PPC::ADJCALLSTACKUP) {
230    // Add (actually subtract) back the amount the callee popped on return.
231    if (int CalleeAmt =  I->getOperand(1).getImm()) {
232      bool is64Bit = Subtarget.isPPC64();
233      CalleeAmt *= -1;
234      unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
235      unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
236      unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
237      unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
238      unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
239      unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
240      MachineInstr *MI = I;
241      DebugLoc dl = MI->getDebugLoc();
242
243      if (isInt<16>(CalleeAmt)) {
244        BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg)
245          .addReg(StackReg, RegState::Kill)
246          .addImm(CalleeAmt);
247      } else {
248        MachineBasicBlock::iterator MBBI = I;
249        BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
250          .addImm(CalleeAmt >> 16);
251        BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
252          .addReg(TmpReg, RegState::Kill)
253          .addImm(CalleeAmt & 0xFFFF);
254        BuildMI(MBB, MBBI, dl, TII.get(ADDInstr), StackReg)
255          .addReg(StackReg, RegState::Kill)
256          .addReg(TmpReg);
257      }
258    }
259  }
260  // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
261  MBB.erase(I);
262}
263
264/// findScratchRegister - Find a 'free' PPC register. Try for a call-clobbered
265/// register first and then a spilled callee-saved register if that fails.
266static
267unsigned findScratchRegister(MachineBasicBlock::iterator II, RegScavenger *RS,
268                             const TargetRegisterClass *RC, int SPAdj) {
269  assert(RS && "Register scavenging must be on");
270  unsigned Reg = RS->FindUnusedReg(RC);
271  // FIXME: move ARM callee-saved reg scan to target independent code, then
272  // search for already spilled CS register here.
273  if (Reg == 0)
274    Reg = RS->scavengeRegister(RC, II, SPAdj);
275  return Reg;
276}
277
278/// lowerDynamicAlloc - Generate the code for allocating an object in the
279/// current frame.  The sequence of code with be in the general form
280///
281///   addi   R0, SP, \#frameSize ; get the address of the previous frame
282///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
283///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
284///
285void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II,
286                                        int SPAdj, RegScavenger *RS) const {
287  // Get the instruction.
288  MachineInstr &MI = *II;
289  // Get the instruction's basic block.
290  MachineBasicBlock &MBB = *MI.getParent();
291  // Get the basic block's function.
292  MachineFunction &MF = *MBB.getParent();
293  // Get the frame info.
294  MachineFrameInfo *MFI = MF.getFrameInfo();
295  // Determine whether 64-bit pointers are used.
296  bool LP64 = Subtarget.isPPC64();
297  DebugLoc dl = MI.getDebugLoc();
298
299  // Get the maximum call stack size.
300  unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
301  // Get the total frame size.
302  unsigned FrameSize = MFI->getStackSize();
303
304  // Get stack alignments.
305  unsigned TargetAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
306  unsigned MaxAlign = MFI->getMaxAlignment();
307  if (MaxAlign > TargetAlign)
308    report_fatal_error("Dynamic alloca with large aligns not supported");
309
310  // Determine the previous frame's address.  If FrameSize can't be
311  // represented as 16 bits or we need special alignment, then we load the
312  // previous frame's address from 0(SP).  Why not do an addis of the hi?
313  // Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
314  // Constructing the constant and adding would take 3 instructions.
315  // Fortunately, a frame greater than 32K is rare.
316  const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
317  const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
318  const TargetRegisterClass *RC = LP64 ? G8RC : GPRC;
319
320  // FIXME (64-bit): Use "findScratchRegister"
321  unsigned Reg;
322  if (requiresRegisterScavenging(MF))
323    Reg = findScratchRegister(II, RS, RC, SPAdj);
324  else
325    Reg = PPC::R0;
326
327  if (MaxAlign < TargetAlign && isInt<16>(FrameSize)) {
328    BuildMI(MBB, II, dl, TII.get(PPC::ADDI), Reg)
329      .addReg(PPC::R31)
330      .addImm(FrameSize);
331  } else if (LP64) {
332    if (requiresRegisterScavenging(MF)) // FIXME (64-bit): Use "true" part.
333      BuildMI(MBB, II, dl, TII.get(PPC::LD), Reg)
334        .addImm(0)
335        .addReg(PPC::X1);
336    else
337      BuildMI(MBB, II, dl, TII.get(PPC::LD), PPC::X0)
338        .addImm(0)
339        .addReg(PPC::X1);
340  } else {
341    BuildMI(MBB, II, dl, TII.get(PPC::LWZ), Reg)
342      .addImm(0)
343      .addReg(PPC::R1);
344  }
345
346  // Grow the stack and update the stack pointer link, then determine the
347  // address of new allocated space.
348  if (LP64) {
349    if (requiresRegisterScavenging(MF)) // FIXME (64-bit): Use "true" part.
350      BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
351        .addReg(Reg, RegState::Kill)
352        .addReg(PPC::X1)
353        .addReg(MI.getOperand(1).getReg());
354    else
355      BuildMI(MBB, II, dl, TII.get(PPC::STDUX), PPC::X1)
356        .addReg(PPC::X0, RegState::Kill)
357        .addReg(PPC::X1)
358        .addReg(MI.getOperand(1).getReg());
359
360    if (!MI.getOperand(1).isKill())
361      BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
362        .addReg(PPC::X1)
363        .addImm(maxCallFrameSize);
364    else
365      // Implicitly kill the register.
366      BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
367        .addReg(PPC::X1)
368        .addImm(maxCallFrameSize)
369        .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
370  } else {
371    BuildMI(MBB, II, dl, TII.get(PPC::STWUX), PPC::R1)
372      .addReg(Reg, RegState::Kill)
373      .addReg(PPC::R1)
374      .addReg(MI.getOperand(1).getReg());
375
376    if (!MI.getOperand(1).isKill())
377      BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
378        .addReg(PPC::R1)
379        .addImm(maxCallFrameSize);
380    else
381      // Implicitly kill the register.
382      BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
383        .addReg(PPC::R1)
384        .addImm(maxCallFrameSize)
385        .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
386  }
387
388  // Discard the DYNALLOC instruction.
389  MBB.erase(II);
390}
391
392/// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
393/// reserving a whole register (R0), we scrounge for one here. This generates
394/// code like this:
395///
396///   mfcr rA                  ; Move the conditional register into GPR rA.
397///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
398///   stw rA, FI               ; Store rA to the frame.
399///
400void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
401                                      unsigned FrameIndex, int SPAdj,
402                                      RegScavenger *RS) const {
403  // Get the instruction.
404  MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>
405  // Get the instruction's basic block.
406  MachineBasicBlock &MBB = *MI.getParent();
407  DebugLoc dl = MI.getDebugLoc();
408
409  // FIXME: Once LLVM supports creating virtual registers here, or the register
410  // scavenger can return multiple registers, stop using reserved registers
411  // here.
412  (void) SPAdj;
413  (void) RS;
414
415  bool LP64 = Subtarget.isPPC64();
416  unsigned Reg = Subtarget.isDarwinABI() ?  (LP64 ? PPC::X2 : PPC::R2) :
417                                            (LP64 ? PPC::X0 : PPC::R0);
418  unsigned SrcReg = MI.getOperand(0).getReg();
419
420  // We need to store the CR in the low 4-bits of the saved value. First, issue
421  // an MFCRpsued to save all of the CRBits and, if needed, kill the SrcReg.
422  BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MFCR8pseud : PPC::MFCRpseud), Reg)
423          .addReg(SrcReg, getKillRegState(MI.getOperand(0).isKill()));
424
425  // If the saved register wasn't CR0, shift the bits left so that they are in
426  // CR0's slot.
427  if (SrcReg != PPC::CR0)
428    // rlwinm rA, rA, ShiftBits, 0, 31.
429    BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
430      .addReg(Reg, RegState::Kill)
431      .addImm(getPPCRegisterNumbering(SrcReg) * 4)
432      .addImm(0)
433      .addImm(31);
434
435  addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::STW8 : PPC::STW))
436                    .addReg(Reg, getKillRegState(MI.getOperand(1).getImm())),
437                    FrameIndex);
438
439  // Discard the pseudo instruction.
440  MBB.erase(II);
441}
442
443void PPCRegisterInfo::lowerCRRestore(MachineBasicBlock::iterator II,
444                                      unsigned FrameIndex, int SPAdj,
445                                      RegScavenger *RS) const {
446  // Get the instruction.
447  MachineInstr &MI = *II;       // ; <DestReg> = RESTORE_CR <offset>
448  // Get the instruction's basic block.
449  MachineBasicBlock &MBB = *MI.getParent();
450  DebugLoc dl = MI.getDebugLoc();
451
452  // FIXME: Once LLVM supports creating virtual registers here, or the register
453  // scavenger can return multiple registers, stop using reserved registers
454  // here.
455  (void) SPAdj;
456  (void) RS;
457
458  bool LP64 = Subtarget.isPPC64();
459  unsigned Reg = Subtarget.isDarwinABI() ?  (LP64 ? PPC::X2 : PPC::R2) :
460                                            (LP64 ? PPC::X0 : PPC::R0);
461  unsigned DestReg = MI.getOperand(0).getReg();
462  assert(MI.definesRegister(DestReg) &&
463    "RESTORE_CR does not define its destination");
464
465  addFrameReference(BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::LWZ8 : PPC::LWZ),
466                              Reg), FrameIndex);
467
468  // If the reloaded register isn't CR0, shift the bits right so that they are
469  // in the right CR's slot.
470  if (DestReg != PPC::CR0) {
471    unsigned ShiftBits = getPPCRegisterNumbering(DestReg)*4;
472    // rlwinm r11, r11, 32-ShiftBits, 0, 31.
473    BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::RLWINM8 : PPC::RLWINM), Reg)
474             .addReg(Reg).addImm(32-ShiftBits).addImm(0)
475             .addImm(31);
476  }
477
478  BuildMI(MBB, II, dl, TII.get(LP64 ? PPC::MTCRF8 : PPC::MTCRF), DestReg)
479             .addReg(Reg);
480
481  // Discard the pseudo instruction.
482  MBB.erase(II);
483}
484
485bool
486PPCRegisterInfo::hasReservedSpillSlot(const MachineFunction &MF,
487				      unsigned Reg, int &FrameIdx) const {
488
489  // For the nonvolatile condition registers (CR2, CR3, CR4) in an SVR4
490  // ABI, return true to prevent allocating an additional frame slot.
491  // For 64-bit, the CR save area is at SP+8; the value of FrameIdx = 0
492  // is arbitrary and will be subsequently ignored.  For 32-bit, we must
493  // create exactly one stack slot and return its FrameIdx for all
494  // nonvolatiles.
495  if (Subtarget.isSVR4ABI() && PPC::CR2 <= Reg && Reg <= PPC::CR4) {
496    if (Subtarget.isPPC64()) {
497      FrameIdx = 0;
498    } else if (CRSpillFrameIdx) {
499      FrameIdx = CRSpillFrameIdx;
500    } else {
501      MachineFrameInfo *MFI = ((MachineFunction &)MF).getFrameInfo();
502      FrameIdx = MFI->CreateFixedObject((uint64_t)4, (int64_t)-4, true);
503      CRSpillFrameIdx = FrameIdx;
504    }
505    return true;
506  }
507  return false;
508}
509
510void
511PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
512                                     int SPAdj, RegScavenger *RS) const {
513  assert(SPAdj == 0 && "Unexpected");
514
515  // Get the instruction.
516  MachineInstr &MI = *II;
517  // Get the instruction's basic block.
518  MachineBasicBlock &MBB = *MI.getParent();
519  // Get the basic block's function.
520  MachineFunction &MF = *MBB.getParent();
521  // Get the frame info.
522  MachineFrameInfo *MFI = MF.getFrameInfo();
523  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
524  DebugLoc dl = MI.getDebugLoc();
525
526  // Find out which operand is the frame index.
527  unsigned FIOperandNo = 0;
528  while (!MI.getOperand(FIOperandNo).isFI()) {
529    ++FIOperandNo;
530    assert(FIOperandNo != MI.getNumOperands() &&
531           "Instr doesn't have FrameIndex operand!");
532  }
533  // Take into account whether it's an add or mem instruction
534  unsigned OffsetOperandNo = (FIOperandNo == 2) ? 1 : 2;
535  if (MI.isInlineAsm())
536    OffsetOperandNo = FIOperandNo-1;
537
538  // Get the frame index.
539  int FrameIndex = MI.getOperand(FIOperandNo).getIndex();
540
541  // Get the frame pointer save index.  Users of this index are primarily
542  // DYNALLOC instructions.
543  PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
544  int FPSI = FI->getFramePointerSaveIndex();
545  // Get the instruction opcode.
546  unsigned OpC = MI.getOpcode();
547
548  // Special case for dynamic alloca.
549  if (FPSI && FrameIndex == FPSI &&
550      (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
551    lowerDynamicAlloc(II, SPAdj, RS);
552    return;
553  }
554
555  // Special case for pseudo-ops SPILL_CR and RESTORE_CR.
556  if (requiresRegisterScavenging(MF)) {
557    if (OpC == PPC::SPILL_CR) {
558      lowerCRSpilling(II, FrameIndex, SPAdj, RS);
559      return;
560    } else if (OpC == PPC::RESTORE_CR) {
561      lowerCRRestore(II, FrameIndex, SPAdj, RS);
562      return;
563    }
564  }
565
566  // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
567
568  bool is64Bit = Subtarget.isPPC64();
569  MI.getOperand(FIOperandNo).ChangeToRegister(TFI->hasFP(MF) ?
570                                              (is64Bit ? PPC::X31 : PPC::R31) :
571                                                (is64Bit ? PPC::X1 : PPC::R1),
572                                              false);
573
574  // Figure out if the offset in the instruction is shifted right two bits. This
575  // is true for instructions like "STD", which the machine implicitly adds two
576  // low zeros to.
577  bool isIXAddr = false;
578  switch (OpC) {
579  case PPC::LWA:
580  case PPC::LD:
581  case PPC::STD:
582  case PPC::STD_32:
583    isIXAddr = true;
584    break;
585  }
586
587  // Now add the frame object offset to the offset from r1.
588  int Offset = MFI->getObjectOffset(FrameIndex);
589  if (!isIXAddr)
590    Offset += MI.getOperand(OffsetOperandNo).getImm();
591  else
592    Offset += MI.getOperand(OffsetOperandNo).getImm() << 2;
593
594  // If we're not using a Frame Pointer that has been set to the value of the
595  // SP before having the stack size subtracted from it, then add the stack size
596  // to Offset to get the correct offset.
597  // Naked functions have stack size 0, although getStackSize may not reflect that
598  // because we didn't call all the pieces that compute it for naked functions.
599  if (!MF.getFunction()->getFnAttributes().hasNakedAttr())
600    Offset += MFI->getStackSize();
601
602  // If we can, encode the offset directly into the instruction.  If this is a
603  // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
604  // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
605  // clear can be encoded.  This is extremely uncommon, because normally you
606  // only "std" to a stack slot that is at least 4-byte aligned, but it can
607  // happen in invalid code.
608  if (OpC == PPC::DBG_VALUE || // DBG_VALUE is always Reg+Imm
609      (isInt<16>(Offset) && (!isIXAddr || (Offset & 3) == 0))) {
610    if (isIXAddr)
611      Offset >>= 2;    // The actual encoded value has the low two bits zero.
612    MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
613    return;
614  }
615
616  // The offset doesn't fit into a single register, scavenge one to build the
617  // offset in.
618
619  unsigned SReg;
620  if (requiresRegisterScavenging(MF)) {
621    const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
622    const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
623    SReg = findScratchRegister(II, RS, is64Bit ? G8RC : GPRC, SPAdj);
624  } else
625    SReg = is64Bit ? PPC::X0 : PPC::R0;
626
627  // Insert a set of rA with the full offset value before the ld, st, or add
628  BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::LIS8 : PPC::LIS), SReg)
629    .addImm(Offset >> 16);
630  BuildMI(MBB, II, dl, TII.get(is64Bit ? PPC::ORI8 : PPC::ORI), SReg)
631    .addReg(SReg, RegState::Kill)
632    .addImm(Offset);
633
634  // Convert into indexed form of the instruction:
635  //
636  //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
637  //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
638  unsigned OperandBase;
639
640  if (OpC != TargetOpcode::INLINEASM) {
641    assert(ImmToIdxMap.count(OpC) &&
642           "No indexed form of load or store available!");
643    unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
644    MI.setDesc(TII.get(NewOpcode));
645    OperandBase = 1;
646  } else {
647    OperandBase = OffsetOperandNo;
648  }
649
650  unsigned StackReg = MI.getOperand(FIOperandNo).getReg();
651  MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
652  MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false, false, true);
653}
654
655unsigned PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
656  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
657
658  if (!Subtarget.isPPC64())
659    return TFI->hasFP(MF) ? PPC::R31 : PPC::R1;
660  else
661    return TFI->hasFP(MF) ? PPC::X31 : PPC::X1;
662}
663
664unsigned PPCRegisterInfo::getEHExceptionRegister() const {
665  return !Subtarget.isPPC64() ? PPC::R3 : PPC::X3;
666}
667
668unsigned PPCRegisterInfo::getEHHandlerRegister() const {
669  return !Subtarget.isPPC64() ? PPC::R4 : PPC::X4;
670}
671