PPCRegisterInfo.cpp revision 204961
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>
46using namespace llvm;
47
48// FIXME This disables some code that aligns the stack to a boundary
49// bigger than the default (16 bytes on Darwin) when there is a stack local
50// of greater alignment.  This does not currently work, because the delta
51// between old and new stack pointers is added to offsets that reference
52// incoming parameters after the prolog is generated, and the code that
53// does that doesn't handle a variable delta.  You don't want to do that
54// anyway; a better approach is to reserve another register that retains
55// to the incoming stack pointer, and reference parameters relative to that.
56#define ALIGN_STACK 0
57
58// FIXME (64-bit): Eventually enable by default.
59cl::opt<bool> EnablePPC32RS("enable-ppc32-regscavenger",
60                            cl::init(false),
61                            cl::desc("Enable PPC32 register scavenger"),
62                            cl::Hidden);
63cl::opt<bool> EnablePPC64RS("enable-ppc64-regscavenger",
64                            cl::init(false),
65                            cl::desc("Enable PPC64 register scavenger"),
66                            cl::Hidden);
67#define EnableRegisterScavenging \
68  ((EnablePPC32RS && !Subtarget.isPPC64()) || \
69   (EnablePPC64RS && Subtarget.isPPC64()))
70
71// FIXME (64-bit): Should be inlined.
72bool
73PPCRegisterInfo::requiresRegisterScavenging(const MachineFunction &) const {
74  return EnableRegisterScavenging;
75}
76
77/// getRegisterNumbering - Given the enum value for some register, e.g.
78/// PPC::F14, return the number that it corresponds to (e.g. 14).
79unsigned PPCRegisterInfo::getRegisterNumbering(unsigned RegEnum) {
80  using namespace PPC;
81  switch (RegEnum) {
82  case 0: return 0;
83  case R0 :  case X0 :  case F0 :  case V0 : case CR0:  case CR0LT: return  0;
84  case R1 :  case X1 :  case F1 :  case V1 : case CR1:  case CR0GT: return  1;
85  case R2 :  case X2 :  case F2 :  case V2 : case CR2:  case CR0EQ: return  2;
86  case R3 :  case X3 :  case F3 :  case V3 : case CR3:  case CR0UN: return  3;
87  case R4 :  case X4 :  case F4 :  case V4 : case CR4:  case CR1LT: return  4;
88  case R5 :  case X5 :  case F5 :  case V5 : case CR5:  case CR1GT: return  5;
89  case R6 :  case X6 :  case F6 :  case V6 : case CR6:  case CR1EQ: return  6;
90  case R7 :  case X7 :  case F7 :  case V7 : case CR7:  case CR1UN: return  7;
91  case R8 :  case X8 :  case F8 :  case V8 : case CR2LT: return  8;
92  case R9 :  case X9 :  case F9 :  case V9 : case CR2GT: return  9;
93  case R10:  case X10:  case F10:  case V10: case CR2EQ: return 10;
94  case R11:  case X11:  case F11:  case V11: case CR2UN: return 11;
95  case R12:  case X12:  case F12:  case V12: case CR3LT: return 12;
96  case R13:  case X13:  case F13:  case V13: case CR3GT: return 13;
97  case R14:  case X14:  case F14:  case V14: case CR3EQ: return 14;
98  case R15:  case X15:  case F15:  case V15: case CR3UN: return 15;
99  case R16:  case X16:  case F16:  case V16: case CR4LT: return 16;
100  case R17:  case X17:  case F17:  case V17: case CR4GT: return 17;
101  case R18:  case X18:  case F18:  case V18: case CR4EQ: return 18;
102  case R19:  case X19:  case F19:  case V19: case CR4UN: return 19;
103  case R20:  case X20:  case F20:  case V20: case CR5LT: return 20;
104  case R21:  case X21:  case F21:  case V21: case CR5GT: return 21;
105  case R22:  case X22:  case F22:  case V22: case CR5EQ: return 22;
106  case R23:  case X23:  case F23:  case V23: case CR5UN: return 23;
107  case R24:  case X24:  case F24:  case V24: case CR6LT: return 24;
108  case R25:  case X25:  case F25:  case V25: case CR6GT: return 25;
109  case R26:  case X26:  case F26:  case V26: case CR6EQ: return 26;
110  case R27:  case X27:  case F27:  case V27: case CR6UN: return 27;
111  case R28:  case X28:  case F28:  case V28: case CR7LT: return 28;
112  case R29:  case X29:  case F29:  case V29: case CR7GT: return 29;
113  case R30:  case X30:  case F30:  case V30: case CR7EQ: return 30;
114  case R31:  case X31:  case F31:  case V31: case CR7UN: return 31;
115  default:
116    llvm_unreachable("Unhandled reg in PPCRegisterInfo::getRegisterNumbering!");
117  }
118}
119
120PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST,
121                                 const TargetInstrInfo &tii)
122  : PPCGenRegisterInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
123    Subtarget(ST), TII(tii) {
124  ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
125  ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
126  ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
127  ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
128  ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
129  ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
130  ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
131  ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
132
133  // 64-bit
134  ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
135  ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
136  ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
137  ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
138  ImmToIdxMap[PPC::ADDI8] = PPC::ADD8; ImmToIdxMap[PPC::STD_32] = PPC::STDX_32;
139}
140
141/// getPointerRegClass - Return the register class to use to hold pointers.
142/// This is used for addressing modes.
143const TargetRegisterClass *
144PPCRegisterInfo::getPointerRegClass(unsigned Kind) const {
145  if (Subtarget.isPPC64())
146    return &PPC::G8RCRegClass;
147  return &PPC::GPRCRegClass;
148}
149
150const unsigned*
151PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
152  // 32-bit Darwin calling convention.
153  static const unsigned Darwin32_CalleeSavedRegs[] = {
154              PPC::R13, PPC::R14, PPC::R15,
155    PPC::R16, PPC::R17, PPC::R18, PPC::R19,
156    PPC::R20, PPC::R21, PPC::R22, PPC::R23,
157    PPC::R24, PPC::R25, PPC::R26, PPC::R27,
158    PPC::R28, PPC::R29, PPC::R30, PPC::R31,
159
160    PPC::F14, PPC::F15, PPC::F16, PPC::F17,
161    PPC::F18, PPC::F19, PPC::F20, PPC::F21,
162    PPC::F22, PPC::F23, PPC::F24, PPC::F25,
163    PPC::F26, PPC::F27, PPC::F28, PPC::F29,
164    PPC::F30, PPC::F31,
165
166    PPC::CR2, PPC::CR3, PPC::CR4,
167    PPC::V20, PPC::V21, PPC::V22, PPC::V23,
168    PPC::V24, PPC::V25, PPC::V26, PPC::V27,
169    PPC::V28, PPC::V29, PPC::V30, PPC::V31,
170
171    PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
172    PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
173    PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
174
175    PPC::LR,  0
176  };
177
178  // 32-bit SVR4 calling convention.
179  static const unsigned SVR4_CalleeSavedRegs[] = {
180                        PPC::R14, PPC::R15,
181    PPC::R16, PPC::R17, PPC::R18, PPC::R19,
182    PPC::R20, PPC::R21, PPC::R22, PPC::R23,
183    PPC::R24, PPC::R25, PPC::R26, PPC::R27,
184    PPC::R28, PPC::R29, PPC::R30, PPC::R31,
185
186    PPC::F14, PPC::F15, PPC::F16, PPC::F17,
187    PPC::F18, PPC::F19, PPC::F20, PPC::F21,
188    PPC::F22, PPC::F23, PPC::F24, PPC::F25,
189    PPC::F26, PPC::F27, PPC::F28, PPC::F29,
190    PPC::F30, PPC::F31,
191
192    PPC::CR2, PPC::CR3, PPC::CR4,
193
194    PPC::VRSAVE,
195
196    PPC::V20, PPC::V21, PPC::V22, PPC::V23,
197    PPC::V24, PPC::V25, PPC::V26, PPC::V27,
198    PPC::V28, PPC::V29, PPC::V30, PPC::V31,
199
200    PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
201    PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
202    PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
203
204    0
205  };
206  // 64-bit Darwin calling convention.
207  static const unsigned Darwin64_CalleeSavedRegs[] = {
208    PPC::X14, PPC::X15,
209    PPC::X16, PPC::X17, PPC::X18, PPC::X19,
210    PPC::X20, PPC::X21, PPC::X22, PPC::X23,
211    PPC::X24, PPC::X25, PPC::X26, PPC::X27,
212    PPC::X28, PPC::X29, PPC::X30, PPC::X31,
213
214    PPC::F14, PPC::F15, PPC::F16, PPC::F17,
215    PPC::F18, PPC::F19, PPC::F20, PPC::F21,
216    PPC::F22, PPC::F23, PPC::F24, PPC::F25,
217    PPC::F26, PPC::F27, PPC::F28, PPC::F29,
218    PPC::F30, PPC::F31,
219
220    PPC::CR2, PPC::CR3, PPC::CR4,
221    PPC::V20, PPC::V21, PPC::V22, PPC::V23,
222    PPC::V24, PPC::V25, PPC::V26, PPC::V27,
223    PPC::V28, PPC::V29, PPC::V30, PPC::V31,
224
225    PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
226    PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
227    PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
228
229    PPC::LR8,  0
230  };
231
232  // 64-bit SVR4 calling convention.
233  static const unsigned SVR4_64_CalleeSavedRegs[] = {
234    PPC::X14, PPC::X15,
235    PPC::X16, PPC::X17, PPC::X18, PPC::X19,
236    PPC::X20, PPC::X21, PPC::X22, PPC::X23,
237    PPC::X24, PPC::X25, PPC::X26, PPC::X27,
238    PPC::X28, PPC::X29, PPC::X30, PPC::X31,
239
240    PPC::F14, PPC::F15, PPC::F16, PPC::F17,
241    PPC::F18, PPC::F19, PPC::F20, PPC::F21,
242    PPC::F22, PPC::F23, PPC::F24, PPC::F25,
243    PPC::F26, PPC::F27, PPC::F28, PPC::F29,
244    PPC::F30, PPC::F31,
245
246    PPC::CR2, PPC::CR3, PPC::CR4,
247
248    PPC::VRSAVE,
249
250    PPC::V20, PPC::V21, PPC::V22, PPC::V23,
251    PPC::V24, PPC::V25, PPC::V26, PPC::V27,
252    PPC::V28, PPC::V29, PPC::V30, PPC::V31,
253
254    PPC::CR2LT, PPC::CR2GT, PPC::CR2EQ, PPC::CR2UN,
255    PPC::CR3LT, PPC::CR3GT, PPC::CR3EQ, PPC::CR3UN,
256    PPC::CR4LT, PPC::CR4GT, PPC::CR4EQ, PPC::CR4UN,
257
258    0
259  };
260
261  if (Subtarget.isDarwinABI())
262    return Subtarget.isPPC64() ? Darwin64_CalleeSavedRegs :
263                                 Darwin32_CalleeSavedRegs;
264
265  return Subtarget.isPPC64() ? SVR4_64_CalleeSavedRegs : SVR4_CalleeSavedRegs;
266}
267
268const TargetRegisterClass* const*
269PPCRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
270  // 32-bit Darwin calling convention.
271  static const TargetRegisterClass * const Darwin32_CalleeSavedRegClasses[] = {
272                       &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
273    &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
274    &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
275    &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
276    &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
277
278    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
279    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
280    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
281    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
282    &PPC::F8RCRegClass,&PPC::F8RCRegClass,
283
284    &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
285
286    &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
287    &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
288    &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
289
290    &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,
291    &PPC::CRBITRCRegClass,
292    &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,
293    &PPC::CRBITRCRegClass,
294    &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,
295    &PPC::CRBITRCRegClass,
296
297    &PPC::GPRCRegClass, 0
298  };
299
300  // 32-bit SVR4 calling convention.
301  static const TargetRegisterClass * const SVR4_CalleeSavedRegClasses[] = {
302                                          &PPC::GPRCRegClass,&PPC::GPRCRegClass,
303    &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
304    &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
305    &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
306    &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
307
308    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
309    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
310    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
311    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
312    &PPC::F8RCRegClass,&PPC::F8RCRegClass,
313
314    &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
315
316    &PPC::VRSAVERCRegClass,
317
318    &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
319    &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
320    &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
321
322    &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,
323    &PPC::CRBITRCRegClass,
324    &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,
325    &PPC::CRBITRCRegClass,
326    &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,
327    &PPC::CRBITRCRegClass,
328
329    0
330  };
331
332  // 64-bit Darwin calling convention.
333  static const TargetRegisterClass * const Darwin64_CalleeSavedRegClasses[] = {
334    &PPC::G8RCRegClass,&PPC::G8RCRegClass,
335    &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
336    &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
337    &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
338    &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
339
340    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
341    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
342    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
343    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
344    &PPC::F8RCRegClass,&PPC::F8RCRegClass,
345
346    &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
347
348    &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
349    &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
350    &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
351
352    &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,
353    &PPC::CRBITRCRegClass,
354    &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,
355    &PPC::CRBITRCRegClass,
356    &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,
357    &PPC::CRBITRCRegClass,
358
359    &PPC::G8RCRegClass, 0
360  };
361
362  // 64-bit SVR4 calling convention.
363  static const TargetRegisterClass * const SVR4_64_CalleeSavedRegClasses[] = {
364    &PPC::G8RCRegClass,&PPC::G8RCRegClass,
365    &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
366    &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
367    &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
368    &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
369
370    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
371    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
372    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
373    &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
374    &PPC::F8RCRegClass,&PPC::F8RCRegClass,
375
376    &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
377
378    &PPC::VRSAVERCRegClass,
379
380    &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
381    &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
382    &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
383
384    &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,
385    &PPC::CRBITRCRegClass,
386    &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,
387    &PPC::CRBITRCRegClass,
388    &PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,&PPC::CRBITRCRegClass,
389    &PPC::CRBITRCRegClass,
390
391    0
392  };
393
394  if (Subtarget.isDarwinABI())
395    return Subtarget.isPPC64() ? Darwin64_CalleeSavedRegClasses :
396                                 Darwin32_CalleeSavedRegClasses;
397
398  return Subtarget.isPPC64() ? SVR4_64_CalleeSavedRegClasses
399                             : SVR4_CalleeSavedRegClasses;
400}
401
402// needsFP - Return true if the specified function should have a dedicated frame
403// pointer register.  This is true if the function has variable sized allocas or
404// if frame pointer elimination is disabled.
405//
406static bool needsFP(const MachineFunction &MF) {
407  const MachineFrameInfo *MFI = MF.getFrameInfo();
408  return NoFramePointerElim || MFI->hasVarSizedObjects() ||
409    (GuaranteedTailCallOpt && MF.getInfo<PPCFunctionInfo>()->hasFastCall());
410}
411
412static bool spillsCR(const MachineFunction &MF) {
413  const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
414  return FuncInfo->isCRSpilled();
415}
416
417BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
418  BitVector Reserved(getNumRegs());
419  Reserved.set(PPC::R0);
420  Reserved.set(PPC::R1);
421  Reserved.set(PPC::LR);
422  Reserved.set(PPC::LR8);
423  Reserved.set(PPC::RM);
424
425  // The SVR4 ABI reserves r2 and r13
426  if (Subtarget.isSVR4ABI()) {
427    Reserved.set(PPC::R2);  // System-reserved register
428    Reserved.set(PPC::R13); // Small Data Area pointer register
429  }
430  // Reserve R2 on Darwin to hack around the problem of save/restore of CR
431  // when the stack frame is too big to address directly; we need two regs.
432  // This is a hack.
433  if (Subtarget.isDarwinABI()) {
434    Reserved.set(PPC::R2);
435  }
436
437  // On PPC64, r13 is the thread pointer. Never allocate this register.
438  // Note that this is over conservative, as it also prevents allocation of R31
439  // when the FP is not needed.
440  if (Subtarget.isPPC64()) {
441    Reserved.set(PPC::R13);
442    Reserved.set(PPC::R31);
443
444    if (!EnableRegisterScavenging)
445      Reserved.set(PPC::R0);    // FIXME (64-bit): Remove
446
447    Reserved.set(PPC::X0);
448    Reserved.set(PPC::X1);
449    Reserved.set(PPC::X13);
450    Reserved.set(PPC::X31);
451
452    // The 64-bit SVR4 ABI reserves r2 for the TOC pointer.
453    if (Subtarget.isSVR4ABI()) {
454      Reserved.set(PPC::X2);
455    }
456    // Reserve R2 on Darwin to hack around the problem of save/restore of CR
457    // when the stack frame is too big to address directly; we need two regs.
458    // This is a hack.
459    if (Subtarget.isDarwinABI()) {
460      Reserved.set(PPC::X2);
461    }
462  }
463
464  if (needsFP(MF))
465    Reserved.set(PPC::R31);
466
467  return Reserved;
468}
469
470//===----------------------------------------------------------------------===//
471// Stack Frame Processing methods
472//===----------------------------------------------------------------------===//
473
474// hasFP - Return true if the specified function actually has a dedicated frame
475// pointer register.  This is true if the function needs a frame pointer and has
476// a non-zero stack size.
477bool PPCRegisterInfo::hasFP(const MachineFunction &MF) const {
478  const MachineFrameInfo *MFI = MF.getFrameInfo();
479  return MFI->getStackSize() && needsFP(MF);
480}
481
482/// MustSaveLR - Return true if this function requires that we save the LR
483/// register onto the stack in the prolog and restore it in the epilog of the
484/// function.
485static bool MustSaveLR(const MachineFunction &MF, unsigned LR) {
486  const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
487
488  // We need a save/restore of LR if there is any def of LR (which is
489  // defined by calls, including the PIC setup sequence), or if there is
490  // some use of the LR stack slot (e.g. for builtin_return_address).
491  // (LR comes in 32 and 64 bit versions.)
492  MachineRegisterInfo::def_iterator RI = MF.getRegInfo().def_begin(LR);
493  return RI !=MF.getRegInfo().def_end() || MFI->isLRStoreRequired();
494}
495
496
497
498void PPCRegisterInfo::
499eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
500                              MachineBasicBlock::iterator I) const {
501  if (GuaranteedTailCallOpt && I->getOpcode() == PPC::ADJCALLSTACKUP) {
502    // Add (actually subtract) back the amount the callee popped on return.
503    if (int CalleeAmt =  I->getOperand(1).getImm()) {
504      bool is64Bit = Subtarget.isPPC64();
505      CalleeAmt *= -1;
506      unsigned StackReg = is64Bit ? PPC::X1 : PPC::R1;
507      unsigned TmpReg = is64Bit ? PPC::X0 : PPC::R0;
508      unsigned ADDIInstr = is64Bit ? PPC::ADDI8 : PPC::ADDI;
509      unsigned ADDInstr = is64Bit ? PPC::ADD8 : PPC::ADD4;
510      unsigned LISInstr = is64Bit ? PPC::LIS8 : PPC::LIS;
511      unsigned ORIInstr = is64Bit ? PPC::ORI8 : PPC::ORI;
512      MachineInstr *MI = I;
513      DebugLoc dl = MI->getDebugLoc();
514
515      if (isInt16(CalleeAmt)) {
516        BuildMI(MBB, I, dl, TII.get(ADDIInstr), StackReg).addReg(StackReg).
517          addImm(CalleeAmt);
518      } else {
519        MachineBasicBlock::iterator MBBI = I;
520        BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
521          .addImm(CalleeAmt >> 16);
522        BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
523          .addReg(TmpReg, RegState::Kill)
524          .addImm(CalleeAmt & 0xFFFF);
525        BuildMI(MBB, MBBI, dl, TII.get(ADDInstr))
526          .addReg(StackReg)
527          .addReg(StackReg)
528          .addReg(TmpReg);
529      }
530    }
531  }
532  // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
533  MBB.erase(I);
534}
535
536/// findScratchRegister - Find a 'free' PPC register. Try for a call-clobbered
537/// register first and then a spilled callee-saved register if that fails.
538static
539unsigned findScratchRegister(MachineBasicBlock::iterator II, RegScavenger *RS,
540                             const TargetRegisterClass *RC, int SPAdj) {
541  assert(RS && "Register scavenging must be on");
542  unsigned Reg = RS->FindUnusedReg(RC);
543  // FIXME: move ARM callee-saved reg scan to target independent code, then
544  // search for already spilled CS register here.
545  if (Reg == 0)
546    Reg = RS->scavengeRegister(RC, II, SPAdj);
547  return Reg;
548}
549
550/// lowerDynamicAlloc - Generate the code for allocating an object in the
551/// current frame.  The sequence of code with be in the general form
552///
553///   addi   R0, SP, \#frameSize ; get the address of the previous frame
554///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
555///   addi   Rnew, SP, \#maxCalFrameSize ; get the top of the allocation
556///
557void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II,
558                                        int SPAdj, RegScavenger *RS) const {
559  // Get the instruction.
560  MachineInstr &MI = *II;
561  // Get the instruction's basic block.
562  MachineBasicBlock &MBB = *MI.getParent();
563  // Get the basic block's function.
564  MachineFunction &MF = *MBB.getParent();
565  // Get the frame info.
566  MachineFrameInfo *MFI = MF.getFrameInfo();
567  // Determine whether 64-bit pointers are used.
568  bool LP64 = Subtarget.isPPC64();
569  DebugLoc dl = MI.getDebugLoc();
570
571  // Get the maximum call stack size.
572  unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
573  // Get the total frame size.
574  unsigned FrameSize = MFI->getStackSize();
575
576  // Get stack alignments.
577  unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
578  unsigned MaxAlign = MFI->getMaxAlignment();
579  assert(MaxAlign <= TargetAlign &&
580         "Dynamic alloca with large aligns not supported");
581
582  // Determine the previous frame's address.  If FrameSize can't be
583  // represented as 16 bits or we need special alignment, then we load the
584  // previous frame's address from 0(SP).  Why not do an addis of the hi?
585  // Because R0 is our only safe tmp register and addi/addis treat R0 as zero.
586  // Constructing the constant and adding would take 3 instructions.
587  // Fortunately, a frame greater than 32K is rare.
588  const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
589  const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
590  const TargetRegisterClass *RC = LP64 ? G8RC : GPRC;
591
592  // FIXME (64-bit): Use "findScratchRegister"
593  unsigned Reg;
594  if (EnableRegisterScavenging)
595    Reg = findScratchRegister(II, RS, RC, SPAdj);
596  else
597    Reg = PPC::R0;
598
599  if (MaxAlign < TargetAlign && isInt16(FrameSize)) {
600    BuildMI(MBB, II, dl, TII.get(PPC::ADDI), Reg)
601      .addReg(PPC::R31)
602      .addImm(FrameSize);
603  } else if (LP64) {
604    if (EnableRegisterScavenging) // FIXME (64-bit): Use "true" part.
605      BuildMI(MBB, II, dl, TII.get(PPC::LD), Reg)
606        .addImm(0)
607        .addReg(PPC::X1);
608    else
609      BuildMI(MBB, II, dl, TII.get(PPC::LD), PPC::X0)
610        .addImm(0)
611        .addReg(PPC::X1);
612  } else {
613    BuildMI(MBB, II, dl, TII.get(PPC::LWZ), Reg)
614      .addImm(0)
615      .addReg(PPC::R1);
616  }
617
618  // Grow the stack and update the stack pointer link, then determine the
619  // address of new allocated space.
620  if (LP64) {
621    if (EnableRegisterScavenging) // FIXME (64-bit): Use "true" part.
622      BuildMI(MBB, II, dl, TII.get(PPC::STDUX))
623        .addReg(Reg, RegState::Kill)
624        .addReg(PPC::X1)
625        .addReg(MI.getOperand(1).getReg());
626    else
627      BuildMI(MBB, II, dl, TII.get(PPC::STDUX))
628        .addReg(PPC::X0, RegState::Kill)
629        .addReg(PPC::X1)
630        .addReg(MI.getOperand(1).getReg());
631
632    if (!MI.getOperand(1).isKill())
633      BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
634        .addReg(PPC::X1)
635        .addImm(maxCallFrameSize);
636    else
637      // Implicitly kill the register.
638      BuildMI(MBB, II, dl, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
639        .addReg(PPC::X1)
640        .addImm(maxCallFrameSize)
641        .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
642  } else {
643    BuildMI(MBB, II, dl, TII.get(PPC::STWUX))
644      .addReg(Reg, RegState::Kill)
645      .addReg(PPC::R1)
646      .addReg(MI.getOperand(1).getReg());
647
648    if (!MI.getOperand(1).isKill())
649      BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
650        .addReg(PPC::R1)
651        .addImm(maxCallFrameSize);
652    else
653      // Implicitly kill the register.
654      BuildMI(MBB, II, dl, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
655        .addReg(PPC::R1)
656        .addImm(maxCallFrameSize)
657        .addReg(MI.getOperand(1).getReg(), RegState::ImplicitKill);
658  }
659
660  // Discard the DYNALLOC instruction.
661  MBB.erase(II);
662}
663
664/// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
665/// reserving a whole register (R0), we scrounge for one here. This generates
666/// code like this:
667///
668///   mfcr rA                  ; Move the conditional register into GPR rA.
669///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
670///   stw rA, FI               ; Store rA to the frame.
671///
672void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
673                                      unsigned FrameIndex, int SPAdj,
674                                      RegScavenger *RS) const {
675  // Get the instruction.
676  MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>, <FI>
677  // Get the instruction's basic block.
678  MachineBasicBlock &MBB = *MI.getParent();
679  DebugLoc dl = MI.getDebugLoc();
680
681  const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
682  const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
683  const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
684  unsigned Reg = findScratchRegister(II, RS, RC, SPAdj);
685
686  // We need to store the CR in the low 4-bits of the saved value. First, issue
687  // an MFCR to save all of the CRBits. Add an implicit kill of the CR.
688  if (!MI.getOperand(0).isKill())
689    BuildMI(MBB, II, dl, TII.get(PPC::MFCR), Reg);
690  else
691    // Implicitly kill the CR register.
692    BuildMI(MBB, II, dl, TII.get(PPC::MFCR), Reg)
693      .addReg(MI.getOperand(0).getReg(), RegState::ImplicitKill);
694
695  // If the saved register wasn't CR0, shift the bits left so that they are in
696  // CR0's slot.
697  unsigned SrcReg = MI.getOperand(0).getReg();
698  if (SrcReg != PPC::CR0)
699    // rlwinm rA, rA, ShiftBits, 0, 31.
700    BuildMI(MBB, II, dl, TII.get(PPC::RLWINM), Reg)
701      .addReg(Reg, RegState::Kill)
702      .addImm(PPCRegisterInfo::getRegisterNumbering(SrcReg) * 4)
703      .addImm(0)
704      .addImm(31);
705
706  addFrameReference(BuildMI(MBB, II, dl, TII.get(PPC::STW))
707                    .addReg(Reg, getKillRegState(MI.getOperand(1).getImm())),
708                    FrameIndex);
709
710  // Discard the pseudo instruction.
711  MBB.erase(II);
712}
713
714unsigned
715PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
716                                     int SPAdj, FrameIndexValue *Value,
717                                     RegScavenger *RS) const {
718  assert(SPAdj == 0 && "Unexpected");
719
720  // Get the instruction.
721  MachineInstr &MI = *II;
722  // Get the instruction's basic block.
723  MachineBasicBlock &MBB = *MI.getParent();
724  // Get the basic block's function.
725  MachineFunction &MF = *MBB.getParent();
726  // Get the frame info.
727  MachineFrameInfo *MFI = MF.getFrameInfo();
728  DebugLoc dl = MI.getDebugLoc();
729
730  // Find out which operand is the frame index.
731  unsigned FIOperandNo = 0;
732  while (!MI.getOperand(FIOperandNo).isFI()) {
733    ++FIOperandNo;
734    assert(FIOperandNo != MI.getNumOperands() &&
735           "Instr doesn't have FrameIndex operand!");
736  }
737  // Take into account whether it's an add or mem instruction
738  unsigned OffsetOperandNo = (FIOperandNo == 2) ? 1 : 2;
739  if (MI.isInlineAsm())
740    OffsetOperandNo = FIOperandNo-1;
741
742  // Get the frame index.
743  int FrameIndex = MI.getOperand(FIOperandNo).getIndex();
744
745  // Get the frame pointer save index.  Users of this index are primarily
746  // DYNALLOC instructions.
747  PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
748  int FPSI = FI->getFramePointerSaveIndex();
749  // Get the instruction opcode.
750  unsigned OpC = MI.getOpcode();
751
752  // Special case for dynamic alloca.
753  if (FPSI && FrameIndex == FPSI &&
754      (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
755    lowerDynamicAlloc(II, SPAdj, RS);
756    return 0;
757  }
758
759  // Special case for pseudo-op SPILL_CR.
760  if (EnableRegisterScavenging) // FIXME (64-bit): Enable by default.
761    if (OpC == PPC::SPILL_CR) {
762      lowerCRSpilling(II, FrameIndex, SPAdj, RS);
763      return 0;
764    }
765
766  // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
767  MI.getOperand(FIOperandNo).ChangeToRegister(hasFP(MF) ? PPC::R31 : PPC::R1,
768                                              false);
769
770  // Figure out if the offset in the instruction is shifted right two bits. This
771  // is true for instructions like "STD", which the machine implicitly adds two
772  // low zeros to.
773  bool isIXAddr = false;
774  switch (OpC) {
775  case PPC::LWA:
776  case PPC::LD:
777  case PPC::STD:
778  case PPC::STD_32:
779    isIXAddr = true;
780    break;
781  }
782
783  // Now add the frame object offset to the offset from r1.
784  int Offset = MFI->getObjectOffset(FrameIndex);
785  if (!isIXAddr)
786    Offset += MI.getOperand(OffsetOperandNo).getImm();
787  else
788    Offset += MI.getOperand(OffsetOperandNo).getImm() << 2;
789
790  // If we're not using a Frame Pointer that has been set to the value of the
791  // SP before having the stack size subtracted from it, then add the stack size
792  // to Offset to get the correct offset.
793  Offset += MFI->getStackSize();
794
795  // If we can, encode the offset directly into the instruction.  If this is a
796  // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
797  // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
798  // clear can be encoded.  This is extremely uncommon, because normally you
799  // only "std" to a stack slot that is at least 4-byte aligned, but it can
800  // happen in invalid code.
801  if (isInt16(Offset) && (!isIXAddr || (Offset & 3) == 0)) {
802    if (isIXAddr)
803      Offset >>= 2;    // The actual encoded value has the low two bits zero.
804    MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
805    return 0;
806  }
807
808  // The offset doesn't fit into a single register, scavenge one to build the
809  // offset in.
810  // FIXME: figure out what SPAdj is doing here.
811
812  // FIXME (64-bit): Use "findScratchRegister".
813  unsigned SReg;
814  if (EnableRegisterScavenging)
815    SReg = findScratchRegister(II, RS, &PPC::GPRCRegClass, SPAdj);
816  else
817    SReg = PPC::R0;
818
819  // Insert a set of rA with the full offset value before the ld, st, or add
820  BuildMI(MBB, II, dl, TII.get(PPC::LIS), SReg)
821    .addImm(Offset >> 16);
822  BuildMI(MBB, II, dl, TII.get(PPC::ORI), SReg)
823    .addReg(SReg, RegState::Kill)
824    .addImm(Offset);
825
826  // Convert into indexed form of the instruction:
827  //
828  //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
829  //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
830  unsigned OperandBase;
831
832  if (OpC != TargetOpcode::INLINEASM) {
833    assert(ImmToIdxMap.count(OpC) &&
834           "No indexed form of load or store available!");
835    unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
836    MI.setDesc(TII.get(NewOpcode));
837    OperandBase = 1;
838  } else {
839    OperandBase = OffsetOperandNo;
840  }
841
842  unsigned StackReg = MI.getOperand(FIOperandNo).getReg();
843  MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
844  MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false);
845  return 0;
846}
847
848/// VRRegNo - Map from a numbered VR register to its enum value.
849///
850static const unsigned short VRRegNo[] = {
851 PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
852 PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
853 PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
854 PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
855};
856
857/// RemoveVRSaveCode - We have found that this function does not need any code
858/// to manipulate the VRSAVE register, even though it uses vector registers.
859/// This can happen when the only registers used are known to be live in or out
860/// of the function.  Remove all of the VRSAVE related code from the function.
861static void RemoveVRSaveCode(MachineInstr *MI) {
862  MachineBasicBlock *Entry = MI->getParent();
863  MachineFunction *MF = Entry->getParent();
864
865  // We know that the MTVRSAVE instruction immediately follows MI.  Remove it.
866  MachineBasicBlock::iterator MBBI = MI;
867  ++MBBI;
868  assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
869  MBBI->eraseFromParent();
870
871  bool RemovedAllMTVRSAVEs = true;
872  // See if we can find and remove the MTVRSAVE instruction from all of the
873  // epilog blocks.
874  for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
875    // If last instruction is a return instruction, add an epilogue
876    if (!I->empty() && I->back().getDesc().isReturn()) {
877      bool FoundIt = false;
878      for (MBBI = I->end(); MBBI != I->begin(); ) {
879        --MBBI;
880        if (MBBI->getOpcode() == PPC::MTVRSAVE) {
881          MBBI->eraseFromParent();  // remove it.
882          FoundIt = true;
883          break;
884        }
885      }
886      RemovedAllMTVRSAVEs &= FoundIt;
887    }
888  }
889
890  // If we found and removed all MTVRSAVE instructions, remove the read of
891  // VRSAVE as well.
892  if (RemovedAllMTVRSAVEs) {
893    MBBI = MI;
894    assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
895    --MBBI;
896    assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
897    MBBI->eraseFromParent();
898  }
899
900  // Finally, nuke the UPDATE_VRSAVE.
901  MI->eraseFromParent();
902}
903
904// HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
905// instruction selector.  Based on the vector registers that have been used,
906// transform this into the appropriate ORI instruction.
907static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
908  MachineFunction *MF = MI->getParent()->getParent();
909  DebugLoc dl = MI->getDebugLoc();
910
911  unsigned UsedRegMask = 0;
912  for (unsigned i = 0; i != 32; ++i)
913    if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
914      UsedRegMask |= 1 << (31-i);
915
916  // Live in and live out values already must be in the mask, so don't bother
917  // marking them.
918  for (MachineRegisterInfo::livein_iterator
919       I = MF->getRegInfo().livein_begin(),
920       E = MF->getRegInfo().livein_end(); I != E; ++I) {
921    unsigned RegNo = PPCRegisterInfo::getRegisterNumbering(I->first);
922    if (VRRegNo[RegNo] == I->first)        // If this really is a vector reg.
923      UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
924  }
925  for (MachineRegisterInfo::liveout_iterator
926       I = MF->getRegInfo().liveout_begin(),
927       E = MF->getRegInfo().liveout_end(); I != E; ++I) {
928    unsigned RegNo = PPCRegisterInfo::getRegisterNumbering(*I);
929    if (VRRegNo[RegNo] == *I)              // If this really is a vector reg.
930      UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
931  }
932
933  // If no registers are used, turn this into a copy.
934  if (UsedRegMask == 0) {
935    // Remove all VRSAVE code.
936    RemoveVRSaveCode(MI);
937    return;
938  }
939
940  unsigned SrcReg = MI->getOperand(1).getReg();
941  unsigned DstReg = MI->getOperand(0).getReg();
942
943  if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
944    if (DstReg != SrcReg)
945      BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
946        .addReg(SrcReg)
947        .addImm(UsedRegMask);
948    else
949      BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
950        .addReg(SrcReg, RegState::Kill)
951        .addImm(UsedRegMask);
952  } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
953    if (DstReg != SrcReg)
954      BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
955        .addReg(SrcReg)
956        .addImm(UsedRegMask >> 16);
957    else
958      BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
959        .addReg(SrcReg, RegState::Kill)
960        .addImm(UsedRegMask >> 16);
961  } else {
962    if (DstReg != SrcReg)
963      BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
964        .addReg(SrcReg)
965        .addImm(UsedRegMask >> 16);
966    else
967      BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORIS), DstReg)
968        .addReg(SrcReg, RegState::Kill)
969        .addImm(UsedRegMask >> 16);
970
971    BuildMI(*MI->getParent(), MI, dl, TII.get(PPC::ORI), DstReg)
972      .addReg(DstReg, RegState::Kill)
973      .addImm(UsedRegMask & 0xFFFF);
974  }
975
976  // Remove the old UPDATE_VRSAVE instruction.
977  MI->eraseFromParent();
978}
979
980/// determineFrameLayout - Determine the size of the frame and maximum call
981/// frame size.
982void PPCRegisterInfo::determineFrameLayout(MachineFunction &MF) const {
983  MachineFrameInfo *MFI = MF.getFrameInfo();
984
985  // Get the number of bytes to allocate from the FrameInfo
986  unsigned FrameSize = MFI->getStackSize();
987
988  // Get the alignments provided by the target, and the maximum alignment
989  // (if any) of the fixed frame objects.
990  unsigned MaxAlign = MFI->getMaxAlignment();
991  unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
992  unsigned AlignMask = TargetAlign - 1;  //
993
994  // If we are a leaf function, and use up to 224 bytes of stack space,
995  // don't have a frame pointer, calls, or dynamic alloca then we do not need
996  // to adjust the stack pointer (we fit in the Red Zone).
997  bool DisableRedZone = MF.getFunction()->hasFnAttr(Attribute::NoRedZone);
998  // FIXME SVR4 The 32-bit SVR4 ABI has no red zone.
999  if (!DisableRedZone &&
1000      FrameSize <= 224 &&                          // Fits in red zone.
1001      !MFI->hasVarSizedObjects() &&                // No dynamic alloca.
1002      !MFI->hasCalls() &&                          // No calls.
1003      (!ALIGN_STACK || MaxAlign <= TargetAlign)) { // No special alignment.
1004    // No need for frame
1005    MFI->setStackSize(0);
1006    return;
1007  }
1008
1009  // Get the maximum call frame size of all the calls.
1010  unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
1011
1012  // Maximum call frame needs to be at least big enough for linkage and 8 args.
1013  unsigned minCallFrameSize =
1014    PPCFrameInfo::getMinCallFrameSize(Subtarget.isPPC64(),
1015                                      Subtarget.isDarwinABI());
1016  maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
1017
1018  // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
1019  // that allocations will be aligned.
1020  if (MFI->hasVarSizedObjects())
1021    maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
1022
1023  // Update maximum call frame size.
1024  MFI->setMaxCallFrameSize(maxCallFrameSize);
1025
1026  // Include call frame size in total.
1027  FrameSize += maxCallFrameSize;
1028
1029  // Make sure the frame is aligned.
1030  FrameSize = (FrameSize + AlignMask) & ~AlignMask;
1031
1032  // Update frame info.
1033  MFI->setStackSize(FrameSize);
1034}
1035
1036void
1037PPCRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1038                                                      RegScavenger *RS) const {
1039  //  Save and clear the LR state.
1040  PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1041  unsigned LR = getRARegister();
1042  FI->setMustSaveLR(MustSaveLR(MF, LR));
1043  MF.getRegInfo().setPhysRegUnused(LR);
1044
1045  //  Save R31 if necessary
1046  int FPSI = FI->getFramePointerSaveIndex();
1047  bool isPPC64 = Subtarget.isPPC64();
1048  bool isDarwinABI  = Subtarget.isDarwinABI();
1049  MachineFrameInfo *MFI = MF.getFrameInfo();
1050
1051  // If the frame pointer save index hasn't been defined yet.
1052  if (!FPSI && needsFP(MF)) {
1053    // Find out what the fix offset of the frame pointer save area.
1054    int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(isPPC64,
1055                                                           isDarwinABI);
1056    // Allocate the frame index for frame pointer save area.
1057    FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset,
1058                                                true, false);
1059    // Save the result.
1060    FI->setFramePointerSaveIndex(FPSI);
1061  }
1062
1063  // Reserve stack space to move the linkage area to in case of a tail call.
1064  int TCSPDelta = 0;
1065  if (GuaranteedTailCallOpt && (TCSPDelta = FI->getTailCallSPDelta()) < 0) {
1066    MF.getFrameInfo()->CreateFixedObject(-1 * TCSPDelta, TCSPDelta,
1067                                         true, false);
1068  }
1069
1070  // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
1071  // a large stack, which will require scavenging a register to materialize a
1072  // large offset.
1073  // FIXME: this doesn't actually check stack size, so is a bit pessimistic
1074  // FIXME: doesn't detect whether or not we need to spill vXX, which requires
1075  //        r0 for now.
1076
1077  if (EnableRegisterScavenging) // FIXME (64-bit): Enable.
1078    if (needsFP(MF) || spillsCR(MF)) {
1079      const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
1080      const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
1081      const TargetRegisterClass *RC = isPPC64 ? G8RC : GPRC;
1082      RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1083                                                         RC->getAlignment(),
1084                                                         false));
1085    }
1086}
1087
1088void
1089PPCRegisterInfo::processFunctionBeforeFrameFinalized(MachineFunction &MF)
1090                                                     const {
1091  // Early exit if not using the SVR4 ABI.
1092  if (!Subtarget.isSVR4ABI()) {
1093    return;
1094  }
1095
1096  // Get callee saved register information.
1097  MachineFrameInfo *FFI = MF.getFrameInfo();
1098  const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo();
1099
1100  // Early exit if no callee saved registers are modified!
1101  if (CSI.empty() && !needsFP(MF)) {
1102    return;
1103  }
1104
1105  unsigned MinGPR = PPC::R31;
1106  unsigned MinG8R = PPC::X31;
1107  unsigned MinFPR = PPC::F31;
1108  unsigned MinVR = PPC::V31;
1109
1110  bool HasGPSaveArea = false;
1111  bool HasG8SaveArea = false;
1112  bool HasFPSaveArea = false;
1113  bool HasCRSaveArea = false;
1114  bool HasVRSAVESaveArea = false;
1115  bool HasVRSaveArea = false;
1116
1117  SmallVector<CalleeSavedInfo, 18> GPRegs;
1118  SmallVector<CalleeSavedInfo, 18> G8Regs;
1119  SmallVector<CalleeSavedInfo, 18> FPRegs;
1120  SmallVector<CalleeSavedInfo, 18> VRegs;
1121
1122  for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1123    unsigned Reg = CSI[i].getReg();
1124    const TargetRegisterClass *RC = CSI[i].getRegClass();
1125
1126    if (RC == PPC::GPRCRegisterClass) {
1127      HasGPSaveArea = true;
1128
1129      GPRegs.push_back(CSI[i]);
1130
1131      if (Reg < MinGPR) {
1132        MinGPR = Reg;
1133      }
1134    } else if (RC == PPC::G8RCRegisterClass) {
1135      HasG8SaveArea = true;
1136
1137      G8Regs.push_back(CSI[i]);
1138
1139      if (Reg < MinG8R) {
1140        MinG8R = Reg;
1141      }
1142    } else if (RC == PPC::F8RCRegisterClass) {
1143      HasFPSaveArea = true;
1144
1145      FPRegs.push_back(CSI[i]);
1146
1147      if (Reg < MinFPR) {
1148        MinFPR = Reg;
1149      }
1150// FIXME SVR4: Disable CR save area for now.
1151    } else if (   RC == PPC::CRBITRCRegisterClass
1152               || RC == PPC::CRRCRegisterClass) {
1153//      HasCRSaveArea = true;
1154    } else if (RC == PPC::VRSAVERCRegisterClass) {
1155      HasVRSAVESaveArea = true;
1156    } else if (RC == PPC::VRRCRegisterClass) {
1157      HasVRSaveArea = true;
1158
1159      VRegs.push_back(CSI[i]);
1160
1161      if (Reg < MinVR) {
1162        MinVR = Reg;
1163      }
1164    } else {
1165      llvm_unreachable("Unknown RegisterClass!");
1166    }
1167  }
1168
1169  PPCFunctionInfo *PFI = MF.getInfo<PPCFunctionInfo>();
1170
1171  int64_t LowerBound = 0;
1172
1173  // Take into account stack space reserved for tail calls.
1174  int TCSPDelta = 0;
1175  if (GuaranteedTailCallOpt && (TCSPDelta = PFI->getTailCallSPDelta()) < 0) {
1176    LowerBound = TCSPDelta;
1177  }
1178
1179  // The Floating-point register save area is right below the back chain word
1180  // of the previous stack frame.
1181  if (HasFPSaveArea) {
1182    for (unsigned i = 0, e = FPRegs.size(); i != e; ++i) {
1183      int FI = FPRegs[i].getFrameIdx();
1184
1185      FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1186    }
1187
1188    LowerBound -= (31 - getRegisterNumbering(MinFPR) + 1) * 8;
1189  }
1190
1191  // Check whether the frame pointer register is allocated. If so, make sure it
1192  // is spilled to the correct offset.
1193  if (needsFP(MF)) {
1194    HasGPSaveArea = true;
1195
1196    int FI = PFI->getFramePointerSaveIndex();
1197    assert(FI && "No Frame Pointer Save Slot!");
1198
1199    FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1200  }
1201
1202  // General register save area starts right below the Floating-point
1203  // register save area.
1204  if (HasGPSaveArea || HasG8SaveArea) {
1205    // Move general register save area spill slots down, taking into account
1206    // the size of the Floating-point register save area.
1207    for (unsigned i = 0, e = GPRegs.size(); i != e; ++i) {
1208      int FI = GPRegs[i].getFrameIdx();
1209
1210      FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1211    }
1212
1213    // Move general register save area spill slots down, taking into account
1214    // the size of the Floating-point register save area.
1215    for (unsigned i = 0, e = G8Regs.size(); i != e; ++i) {
1216      int FI = G8Regs[i].getFrameIdx();
1217
1218      FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1219    }
1220
1221    unsigned MinReg = std::min<unsigned>(getRegisterNumbering(MinGPR),
1222                                         getRegisterNumbering(MinG8R));
1223
1224    if (Subtarget.isPPC64()) {
1225      LowerBound -= (31 - MinReg + 1) * 8;
1226    } else {
1227      LowerBound -= (31 - MinReg + 1) * 4;
1228    }
1229  }
1230
1231  // The CR save area is below the general register save area.
1232  if (HasCRSaveArea) {
1233    // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1234    //             which have the CR/CRBIT register class?
1235    // Adjust the frame index of the CR spill slot.
1236    for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1237      const TargetRegisterClass *RC = CSI[i].getRegClass();
1238
1239      if (RC == PPC::CRBITRCRegisterClass || RC == PPC::CRRCRegisterClass) {
1240        int FI = CSI[i].getFrameIdx();
1241
1242        FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1243      }
1244    }
1245
1246    LowerBound -= 4; // The CR save area is always 4 bytes long.
1247  }
1248
1249  if (HasVRSAVESaveArea) {
1250    // FIXME SVR4: Is it actually possible to have multiple elements in CSI
1251    //             which have the VRSAVE register class?
1252    // Adjust the frame index of the VRSAVE spill slot.
1253    for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1254      const TargetRegisterClass *RC = CSI[i].getRegClass();
1255
1256      if (RC == PPC::VRSAVERCRegisterClass) {
1257        int FI = CSI[i].getFrameIdx();
1258
1259        FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1260      }
1261    }
1262
1263    LowerBound -= 4; // The VRSAVE save area is always 4 bytes long.
1264  }
1265
1266  if (HasVRSaveArea) {
1267    // Insert alignment padding, we need 16-byte alignment.
1268    LowerBound = (LowerBound - 15) & ~(15);
1269
1270    for (unsigned i = 0, e = VRegs.size(); i != e; ++i) {
1271      int FI = VRegs[i].getFrameIdx();
1272
1273      FFI->setObjectOffset(FI, LowerBound + FFI->getObjectOffset(FI));
1274    }
1275  }
1276}
1277
1278void
1279PPCRegisterInfo::emitPrologue(MachineFunction &MF) const {
1280  MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
1281  MachineBasicBlock::iterator MBBI = MBB.begin();
1282  MachineFrameInfo *MFI = MF.getFrameInfo();
1283  MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
1284  DebugLoc dl = DebugLoc::getUnknownLoc();
1285  bool needsFrameMoves = (MMI && MMI->hasDebugInfo()) ||
1286       !MF.getFunction()->doesNotThrow() ||
1287       UnwindTablesMandatory;
1288
1289  // Prepare for frame info.
1290  unsigned FrameLabelId = 0;
1291
1292  // Scan the prolog, looking for an UPDATE_VRSAVE instruction.  If we find it,
1293  // process it.
1294  for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
1295    if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
1296      HandleVRSaveUpdate(MBBI, TII);
1297      break;
1298    }
1299  }
1300
1301  // Move MBBI back to the beginning of the function.
1302  MBBI = MBB.begin();
1303
1304  // Work out frame sizes.
1305  determineFrameLayout(MF);
1306  unsigned FrameSize = MFI->getStackSize();
1307
1308  int NegFrameSize = -FrameSize;
1309
1310  // Get processor type.
1311  bool isPPC64 = Subtarget.isPPC64();
1312  // Get operating system
1313  bool isDarwinABI = Subtarget.isDarwinABI();
1314  // Check if the link register (LR) must be saved.
1315  PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1316  bool MustSaveLR = FI->mustSaveLR();
1317  // Do we have a frame pointer for this function?
1318  bool HasFP = hasFP(MF) && FrameSize;
1319
1320  int LROffset = PPCFrameInfo::getReturnSaveOffset(isPPC64, isDarwinABI);
1321
1322  int FPOffset = 0;
1323  if (HasFP) {
1324    if (Subtarget.isSVR4ABI()) {
1325      MachineFrameInfo *FFI = MF.getFrameInfo();
1326      int FPIndex = FI->getFramePointerSaveIndex();
1327      assert(FPIndex && "No Frame Pointer Save Slot!");
1328      FPOffset = FFI->getObjectOffset(FPIndex);
1329    } else {
1330      FPOffset = PPCFrameInfo::getFramePointerSaveOffset(isPPC64, isDarwinABI);
1331    }
1332  }
1333
1334  if (isPPC64) {
1335    if (MustSaveLR)
1336      BuildMI(MBB, MBBI, dl, TII.get(PPC::MFLR8), PPC::X0);
1337
1338    if (HasFP)
1339      BuildMI(MBB, MBBI, dl, TII.get(PPC::STD))
1340        .addReg(PPC::X31)
1341        .addImm(FPOffset/4)
1342        .addReg(PPC::X1);
1343
1344    if (MustSaveLR)
1345      BuildMI(MBB, MBBI, dl, TII.get(PPC::STD))
1346        .addReg(PPC::X0)
1347        .addImm(LROffset / 4)
1348        .addReg(PPC::X1);
1349  } else {
1350    if (MustSaveLR)
1351      BuildMI(MBB, MBBI, dl, TII.get(PPC::MFLR), PPC::R0);
1352
1353    if (HasFP)
1354      BuildMI(MBB, MBBI, dl, TII.get(PPC::STW))
1355        .addReg(PPC::R31)
1356        .addImm(FPOffset)
1357        .addReg(PPC::R1);
1358
1359    if (MustSaveLR)
1360      BuildMI(MBB, MBBI, dl, TII.get(PPC::STW))
1361        .addReg(PPC::R0)
1362        .addImm(LROffset)
1363        .addReg(PPC::R1);
1364  }
1365
1366  // Skip if a leaf routine.
1367  if (!FrameSize) return;
1368
1369  // Get stack alignments.
1370  unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1371  unsigned MaxAlign = MFI->getMaxAlignment();
1372
1373  // Adjust stack pointer: r1 += NegFrameSize.
1374  // If there is a preferred stack alignment, align R1 now
1375  if (!isPPC64) {
1376    // PPC32.
1377    if (ALIGN_STACK && MaxAlign > TargetAlign) {
1378      assert(isPowerOf2_32(MaxAlign)&&isInt16(MaxAlign)&&"Invalid alignment!");
1379      assert(isInt16(NegFrameSize) && "Unhandled stack size and alignment!");
1380
1381      BuildMI(MBB, MBBI, dl, TII.get(PPC::RLWINM), PPC::R0)
1382        .addReg(PPC::R1)
1383        .addImm(0)
1384        .addImm(32 - Log2_32(MaxAlign))
1385        .addImm(31);
1386      BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBFIC) ,PPC::R0)
1387        .addReg(PPC::R0, RegState::Kill)
1388        .addImm(NegFrameSize);
1389      BuildMI(MBB, MBBI, dl, TII.get(PPC::STWUX))
1390        .addReg(PPC::R1)
1391        .addReg(PPC::R1)
1392        .addReg(PPC::R0);
1393    } else if (isInt16(NegFrameSize)) {
1394      BuildMI(MBB, MBBI, dl, TII.get(PPC::STWU), PPC::R1)
1395        .addReg(PPC::R1)
1396        .addImm(NegFrameSize)
1397        .addReg(PPC::R1);
1398    } else {
1399      BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS), PPC::R0)
1400        .addImm(NegFrameSize >> 16);
1401      BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI), PPC::R0)
1402        .addReg(PPC::R0, RegState::Kill)
1403        .addImm(NegFrameSize & 0xFFFF);
1404      BuildMI(MBB, MBBI, dl, TII.get(PPC::STWUX))
1405        .addReg(PPC::R1)
1406        .addReg(PPC::R1)
1407        .addReg(PPC::R0);
1408    }
1409  } else {    // PPC64.
1410    if (ALIGN_STACK && MaxAlign > TargetAlign) {
1411      assert(isPowerOf2_32(MaxAlign)&&isInt16(MaxAlign)&&"Invalid alignment!");
1412      assert(isInt16(NegFrameSize) && "Unhandled stack size and alignment!");
1413
1414      BuildMI(MBB, MBBI, dl, TII.get(PPC::RLDICL), PPC::X0)
1415        .addReg(PPC::X1)
1416        .addImm(0)
1417        .addImm(64 - Log2_32(MaxAlign));
1418      BuildMI(MBB, MBBI, dl, TII.get(PPC::SUBFIC8), PPC::X0)
1419        .addReg(PPC::X0)
1420        .addImm(NegFrameSize);
1421      BuildMI(MBB, MBBI, dl, TII.get(PPC::STDUX))
1422        .addReg(PPC::X1)
1423        .addReg(PPC::X1)
1424        .addReg(PPC::X0);
1425    } else if (isInt16(NegFrameSize)) {
1426      BuildMI(MBB, MBBI, dl, TII.get(PPC::STDU), PPC::X1)
1427        .addReg(PPC::X1)
1428        .addImm(NegFrameSize / 4)
1429        .addReg(PPC::X1);
1430    } else {
1431      BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS8), PPC::X0)
1432        .addImm(NegFrameSize >> 16);
1433      BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI8), PPC::X0)
1434        .addReg(PPC::X0, RegState::Kill)
1435        .addImm(NegFrameSize & 0xFFFF);
1436      BuildMI(MBB, MBBI, dl, TII.get(PPC::STDUX))
1437        .addReg(PPC::X1)
1438        .addReg(PPC::X1)
1439        .addReg(PPC::X0);
1440    }
1441  }
1442
1443  std::vector<MachineMove> &Moves = MMI->getFrameMoves();
1444
1445  // Add the "machine moves" for the instructions we generated above, but in
1446  // reverse order.
1447  if (needsFrameMoves) {
1448    // Mark effective beginning of when frame pointer becomes valid.
1449    FrameLabelId = MMI->NextLabelID();
1450    BuildMI(MBB, MBBI, dl, TII.get(PPC::DBG_LABEL)).addImm(FrameLabelId);
1451
1452    // Show update of SP.
1453    if (NegFrameSize) {
1454      MachineLocation SPDst(MachineLocation::VirtualFP);
1455      MachineLocation SPSrc(MachineLocation::VirtualFP, NegFrameSize);
1456      Moves.push_back(MachineMove(FrameLabelId, SPDst, SPSrc));
1457    } else {
1458      MachineLocation SP(isPPC64 ? PPC::X31 : PPC::R31);
1459      Moves.push_back(MachineMove(FrameLabelId, SP, SP));
1460    }
1461
1462    if (HasFP) {
1463      MachineLocation FPDst(MachineLocation::VirtualFP, FPOffset);
1464      MachineLocation FPSrc(isPPC64 ? PPC::X31 : PPC::R31);
1465      Moves.push_back(MachineMove(FrameLabelId, FPDst, FPSrc));
1466    }
1467
1468    if (MustSaveLR) {
1469      MachineLocation LRDst(MachineLocation::VirtualFP, LROffset);
1470      MachineLocation LRSrc(isPPC64 ? PPC::LR8 : PPC::LR);
1471      Moves.push_back(MachineMove(FrameLabelId, LRDst, LRSrc));
1472    }
1473  }
1474
1475  unsigned ReadyLabelId = 0;
1476
1477  // If there is a frame pointer, copy R1 into R31
1478  if (HasFP) {
1479    if (!isPPC64) {
1480      BuildMI(MBB, MBBI, dl, TII.get(PPC::OR), PPC::R31)
1481        .addReg(PPC::R1)
1482        .addReg(PPC::R1);
1483    } else {
1484      BuildMI(MBB, MBBI, dl, TII.get(PPC::OR8), PPC::X31)
1485        .addReg(PPC::X1)
1486        .addReg(PPC::X1);
1487    }
1488
1489    if (needsFrameMoves) {
1490      ReadyLabelId = MMI->NextLabelID();
1491
1492      // Mark effective beginning of when frame pointer is ready.
1493      BuildMI(MBB, MBBI, dl, TII.get(PPC::DBG_LABEL)).addImm(ReadyLabelId);
1494
1495      MachineLocation FPDst(HasFP ? (isPPC64 ? PPC::X31 : PPC::R31) :
1496                                    (isPPC64 ? PPC::X1 : PPC::R1));
1497      MachineLocation FPSrc(MachineLocation::VirtualFP);
1498      Moves.push_back(MachineMove(ReadyLabelId, FPDst, FPSrc));
1499    }
1500  }
1501
1502  if (needsFrameMoves) {
1503    unsigned LabelId = HasFP ? ReadyLabelId : FrameLabelId;
1504
1505    // Add callee saved registers to move list.
1506    const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1507    for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
1508      int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
1509      unsigned Reg = CSI[I].getReg();
1510      if (Reg == PPC::LR || Reg == PPC::LR8 || Reg == PPC::RM) continue;
1511      MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
1512      MachineLocation CSSrc(Reg);
1513      Moves.push_back(MachineMove(LabelId, CSDst, CSSrc));
1514    }
1515  }
1516}
1517
1518void PPCRegisterInfo::emitEpilogue(MachineFunction &MF,
1519                                   MachineBasicBlock &MBB) const {
1520  MachineBasicBlock::iterator MBBI = prior(MBB.end());
1521  unsigned RetOpcode = MBBI->getOpcode();
1522  DebugLoc dl = DebugLoc::getUnknownLoc();
1523
1524  assert( (RetOpcode == PPC::BLR ||
1525           RetOpcode == PPC::TCRETURNri ||
1526           RetOpcode == PPC::TCRETURNdi ||
1527           RetOpcode == PPC::TCRETURNai ||
1528           RetOpcode == PPC::TCRETURNri8 ||
1529           RetOpcode == PPC::TCRETURNdi8 ||
1530           RetOpcode == PPC::TCRETURNai8) &&
1531         "Can only insert epilog into returning blocks");
1532
1533  // Get alignment info so we know how to restore r1
1534  const MachineFrameInfo *MFI = MF.getFrameInfo();
1535  unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1536  unsigned MaxAlign = MFI->getMaxAlignment();
1537
1538  // Get the number of bytes allocated from the FrameInfo.
1539  int FrameSize = MFI->getStackSize();
1540
1541  // Get processor type.
1542  bool isPPC64 = Subtarget.isPPC64();
1543  // Get operating system
1544  bool isDarwinABI = Subtarget.isDarwinABI();
1545  // Check if the link register (LR) has been saved.
1546  PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1547  bool MustSaveLR = FI->mustSaveLR();
1548  // Do we have a frame pointer for this function?
1549  bool HasFP = hasFP(MF) && FrameSize;
1550
1551  int LROffset = PPCFrameInfo::getReturnSaveOffset(isPPC64, isDarwinABI);
1552
1553  int FPOffset = 0;
1554  if (HasFP) {
1555    if (Subtarget.isSVR4ABI()) {
1556      MachineFrameInfo *FFI = MF.getFrameInfo();
1557      int FPIndex = FI->getFramePointerSaveIndex();
1558      assert(FPIndex && "No Frame Pointer Save Slot!");
1559      FPOffset = FFI->getObjectOffset(FPIndex);
1560    } else {
1561      FPOffset = PPCFrameInfo::getFramePointerSaveOffset(isPPC64, isDarwinABI);
1562    }
1563  }
1564
1565  bool UsesTCRet =  RetOpcode == PPC::TCRETURNri ||
1566    RetOpcode == PPC::TCRETURNdi ||
1567    RetOpcode == PPC::TCRETURNai ||
1568    RetOpcode == PPC::TCRETURNri8 ||
1569    RetOpcode == PPC::TCRETURNdi8 ||
1570    RetOpcode == PPC::TCRETURNai8;
1571
1572  if (UsesTCRet) {
1573    int MaxTCRetDelta = FI->getTailCallSPDelta();
1574    MachineOperand &StackAdjust = MBBI->getOperand(1);
1575    assert(StackAdjust.isImm() && "Expecting immediate value.");
1576    // Adjust stack pointer.
1577    int StackAdj = StackAdjust.getImm();
1578    int Delta = StackAdj - MaxTCRetDelta;
1579    assert((Delta >= 0) && "Delta must be positive");
1580    if (MaxTCRetDelta>0)
1581      FrameSize += (StackAdj +Delta);
1582    else
1583      FrameSize += StackAdj;
1584  }
1585
1586  if (FrameSize) {
1587    // The loaded (or persistent) stack pointer value is offset by the 'stwu'
1588    // on entry to the function.  Add this offset back now.
1589    if (!isPPC64) {
1590      // If this function contained a fastcc call and GuaranteedTailCallOpt is
1591      // enabled (=> hasFastCall()==true) the fastcc call might contain a tail
1592      // call which invalidates the stack pointer value in SP(0). So we use the
1593      // value of R31 in this case.
1594      if (FI->hasFastCall() && isInt16(FrameSize)) {
1595        assert(hasFP(MF) && "Expecting a valid the frame pointer.");
1596        BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), PPC::R1)
1597          .addReg(PPC::R31).addImm(FrameSize);
1598      } else if(FI->hasFastCall()) {
1599        BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS), PPC::R0)
1600          .addImm(FrameSize >> 16);
1601        BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI), PPC::R0)
1602          .addReg(PPC::R0, RegState::Kill)
1603          .addImm(FrameSize & 0xFFFF);
1604        BuildMI(MBB, MBBI, dl, TII.get(PPC::ADD4))
1605          .addReg(PPC::R1)
1606          .addReg(PPC::R31)
1607          .addReg(PPC::R0);
1608      } else if (isInt16(FrameSize) &&
1609                 (!ALIGN_STACK || TargetAlign >= MaxAlign) &&
1610                 !MFI->hasVarSizedObjects()) {
1611        BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI), PPC::R1)
1612          .addReg(PPC::R1).addImm(FrameSize);
1613      } else {
1614        BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ),PPC::R1)
1615          .addImm(0).addReg(PPC::R1);
1616      }
1617    } else {
1618      if (FI->hasFastCall() && isInt16(FrameSize)) {
1619        assert(hasFP(MF) && "Expecting a valid the frame pointer.");
1620        BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI8), PPC::X1)
1621          .addReg(PPC::X31).addImm(FrameSize);
1622      } else if(FI->hasFastCall()) {
1623        BuildMI(MBB, MBBI, dl, TII.get(PPC::LIS8), PPC::X0)
1624          .addImm(FrameSize >> 16);
1625        BuildMI(MBB, MBBI, dl, TII.get(PPC::ORI8), PPC::X0)
1626          .addReg(PPC::X0, RegState::Kill)
1627          .addImm(FrameSize & 0xFFFF);
1628        BuildMI(MBB, MBBI, dl, TII.get(PPC::ADD8))
1629          .addReg(PPC::X1)
1630          .addReg(PPC::X31)
1631          .addReg(PPC::X0);
1632      } else if (isInt16(FrameSize) && TargetAlign >= MaxAlign &&
1633            !MFI->hasVarSizedObjects()) {
1634        BuildMI(MBB, MBBI, dl, TII.get(PPC::ADDI8), PPC::X1)
1635           .addReg(PPC::X1).addImm(FrameSize);
1636      } else {
1637        BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X1)
1638           .addImm(0).addReg(PPC::X1);
1639      }
1640    }
1641  }
1642
1643  if (isPPC64) {
1644    if (MustSaveLR)
1645      BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X0)
1646        .addImm(LROffset/4).addReg(PPC::X1);
1647
1648    if (HasFP)
1649      BuildMI(MBB, MBBI, dl, TII.get(PPC::LD), PPC::X31)
1650        .addImm(FPOffset/4).addReg(PPC::X1);
1651
1652    if (MustSaveLR)
1653      BuildMI(MBB, MBBI, dl, TII.get(PPC::MTLR8)).addReg(PPC::X0);
1654  } else {
1655    if (MustSaveLR)
1656      BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ), PPC::R0)
1657          .addImm(LROffset).addReg(PPC::R1);
1658
1659    if (HasFP)
1660      BuildMI(MBB, MBBI, dl, TII.get(PPC::LWZ), PPC::R31)
1661          .addImm(FPOffset).addReg(PPC::R1);
1662
1663    if (MustSaveLR)
1664      BuildMI(MBB, MBBI, dl, TII.get(PPC::MTLR)).addReg(PPC::R0);
1665  }
1666
1667  // Callee pop calling convention. Pop parameter/linkage area. Used for tail
1668  // call optimization
1669  if (GuaranteedTailCallOpt && RetOpcode == PPC::BLR &&
1670      MF.getFunction()->getCallingConv() == CallingConv::Fast) {
1671     PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1672     unsigned CallerAllocatedAmt = FI->getMinReservedArea();
1673     unsigned StackReg = isPPC64 ? PPC::X1 : PPC::R1;
1674     unsigned FPReg = isPPC64 ? PPC::X31 : PPC::R31;
1675     unsigned TmpReg = isPPC64 ? PPC::X0 : PPC::R0;
1676     unsigned ADDIInstr = isPPC64 ? PPC::ADDI8 : PPC::ADDI;
1677     unsigned ADDInstr = isPPC64 ? PPC::ADD8 : PPC::ADD4;
1678     unsigned LISInstr = isPPC64 ? PPC::LIS8 : PPC::LIS;
1679     unsigned ORIInstr = isPPC64 ? PPC::ORI8 : PPC::ORI;
1680
1681     if (CallerAllocatedAmt && isInt16(CallerAllocatedAmt)) {
1682       BuildMI(MBB, MBBI, dl, TII.get(ADDIInstr), StackReg)
1683         .addReg(StackReg).addImm(CallerAllocatedAmt);
1684     } else {
1685       BuildMI(MBB, MBBI, dl, TII.get(LISInstr), TmpReg)
1686          .addImm(CallerAllocatedAmt >> 16);
1687       BuildMI(MBB, MBBI, dl, TII.get(ORIInstr), TmpReg)
1688          .addReg(TmpReg, RegState::Kill)
1689          .addImm(CallerAllocatedAmt & 0xFFFF);
1690       BuildMI(MBB, MBBI, dl, TII.get(ADDInstr))
1691          .addReg(StackReg)
1692          .addReg(FPReg)
1693          .addReg(TmpReg);
1694     }
1695  } else if (RetOpcode == PPC::TCRETURNdi) {
1696    MBBI = prior(MBB.end());
1697    MachineOperand &JumpTarget = MBBI->getOperand(0);
1698    BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB)).
1699      addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1700  } else if (RetOpcode == PPC::TCRETURNri) {
1701    MBBI = prior(MBB.end());
1702    assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1703    BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR));
1704  } else if (RetOpcode == PPC::TCRETURNai) {
1705    MBBI = prior(MBB.end());
1706    MachineOperand &JumpTarget = MBBI->getOperand(0);
1707    BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA)).addImm(JumpTarget.getImm());
1708  } else if (RetOpcode == PPC::TCRETURNdi8) {
1709    MBBI = prior(MBB.end());
1710    MachineOperand &JumpTarget = MBBI->getOperand(0);
1711    BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILB8)).
1712      addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset());
1713  } else if (RetOpcode == PPC::TCRETURNri8) {
1714    MBBI = prior(MBB.end());
1715    assert(MBBI->getOperand(0).isReg() && "Expecting register operand.");
1716    BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBCTR8));
1717  } else if (RetOpcode == PPC::TCRETURNai8) {
1718    MBBI = prior(MBB.end());
1719    MachineOperand &JumpTarget = MBBI->getOperand(0);
1720    BuildMI(MBB, MBBI, dl, TII.get(PPC::TAILBA8)).addImm(JumpTarget.getImm());
1721  }
1722}
1723
1724unsigned PPCRegisterInfo::getRARegister() const {
1725  return !Subtarget.isPPC64() ? PPC::LR : PPC::LR8;
1726}
1727
1728unsigned PPCRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
1729  if (!Subtarget.isPPC64())
1730    return hasFP(MF) ? PPC::R31 : PPC::R1;
1731  else
1732    return hasFP(MF) ? PPC::X31 : PPC::X1;
1733}
1734
1735void PPCRegisterInfo::getInitialFrameState(std::vector<MachineMove> &Moves)
1736                                                                         const {
1737  // Initial state of the frame pointer is R1.
1738  MachineLocation Dst(MachineLocation::VirtualFP);
1739  MachineLocation Src(PPC::R1, 0);
1740  Moves.push_back(MachineMove(0, Dst, Src));
1741}
1742
1743unsigned PPCRegisterInfo::getEHExceptionRegister() const {
1744  return !Subtarget.isPPC64() ? PPC::R3 : PPC::X3;
1745}
1746
1747unsigned PPCRegisterInfo::getEHHandlerRegister() const {
1748  return !Subtarget.isPPC64() ? PPC::R4 : PPC::X4;
1749}
1750
1751int PPCRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
1752  // FIXME: Most probably dwarf numbers differs for Linux and Darwin
1753  return PPCGenRegisterInfo::getDwarfRegNumFull(RegNum, 0);
1754}
1755
1756#include "PPCGenRegisterInfo.inc"
1757
1758