Use a command-line option to turn register scavenging on/off for PPC.
[oota-llvm.git] / lib / Target / PowerPC / PPCRegisterInfo.cpp
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/Constants.h"
23 #include "llvm/Type.h"
24 #include "llvm/CodeGen/ValueTypes.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineLocation.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/RegisterScavenging.h"
32 #include "llvm/CodeGen/SelectionDAGNodes.h"
33 #include "llvm/Target/TargetFrameInfo.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/MathExtras.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/STLExtras.h"
42 #include <cstdlib>
43 using namespace llvm;
44
45 // FIXME (64-bit): Eventually enable by default.
46 cl::opt<bool> EnablePPCRS("enable-ppc-regscavenger",
47                           cl::init(false),
48                           cl::desc("enable PPC register scavenger"),
49                           cl::Hidden);
50
51 // FIXME (64-bit): Should be inlined.
52 bool
53 PPCRegisterInfo::requiresRegisterScavenging(const MachineFunction &) const {
54   return EnablePPCRS;
55 }
56
57 /// getRegisterNumbering - Given the enum value for some register, e.g.
58 /// PPC::F14, return the number that it corresponds to (e.g. 14).
59 unsigned PPCRegisterInfo::getRegisterNumbering(unsigned RegEnum) {
60   using namespace PPC;
61   switch (RegEnum) {
62   case 0: return 0;
63   case R0 :  case X0 :  case F0 :  case V0 : case CR0:  return  0;
64   case R1 :  case X1 :  case F1 :  case V1 : case CR1:  return  1;
65   case R2 :  case X2 :  case F2 :  case V2 : case CR2:  return  2;
66   case R3 :  case X3 :  case F3 :  case V3 : case CR3:  return  3;
67   case R4 :  case X4 :  case F4 :  case V4 : case CR4:  return  4;
68   case R5 :  case X5 :  case F5 :  case V5 : case CR5:  return  5;
69   case R6 :  case X6 :  case F6 :  case V6 : case CR6:  return  6;
70   case R7 :  case X7 :  case F7 :  case V7 : case CR7:  return  7;
71   case R8 :  case X8 :  case F8 :  case V8 : return  8;
72   case R9 :  case X9 :  case F9 :  case V9 : return  9;
73   case R10:  case X10:  case F10:  case V10: return 10;
74   case R11:  case X11:  case F11:  case V11: return 11;
75   case R12:  case X12:  case F12:  case V12: return 12;
76   case R13:  case X13:  case F13:  case V13: return 13;
77   case R14:  case X14:  case F14:  case V14: return 14;
78   case R15:  case X15:  case F15:  case V15: return 15;
79   case R16:  case X16:  case F16:  case V16: return 16;
80   case R17:  case X17:  case F17:  case V17: return 17;
81   case R18:  case X18:  case F18:  case V18: return 18;
82   case R19:  case X19:  case F19:  case V19: return 19;
83   case R20:  case X20:  case F20:  case V20: return 20;
84   case R21:  case X21:  case F21:  case V21: return 21;
85   case R22:  case X22:  case F22:  case V22: return 22;
86   case R23:  case X23:  case F23:  case V23: return 23;
87   case R24:  case X24:  case F24:  case V24: return 24;
88   case R25:  case X25:  case F25:  case V25: return 25;
89   case R26:  case X26:  case F26:  case V26: return 26;
90   case R27:  case X27:  case F27:  case V27: return 27;
91   case R28:  case X28:  case F28:  case V28: return 28;
92   case R29:  case X29:  case F29:  case V29: return 29;
93   case R30:  case X30:  case F30:  case V30: return 30;
94   case R31:  case X31:  case F31:  case V31: return 31;
95   default:
96     cerr << "Unhandled reg in PPCRegisterInfo::getRegisterNumbering!\n";
97     abort();
98   }
99 }
100
101 PPCRegisterInfo::PPCRegisterInfo(const PPCSubtarget &ST,
102                                  const TargetInstrInfo &tii)
103   : PPCGenRegisterInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP),
104     Subtarget(ST), TII(tii) {
105   ImmToIdxMap[PPC::LD]   = PPC::LDX;    ImmToIdxMap[PPC::STD]  = PPC::STDX;
106   ImmToIdxMap[PPC::LBZ]  = PPC::LBZX;   ImmToIdxMap[PPC::STB]  = PPC::STBX;
107   ImmToIdxMap[PPC::LHZ]  = PPC::LHZX;   ImmToIdxMap[PPC::LHA]  = PPC::LHAX;
108   ImmToIdxMap[PPC::LWZ]  = PPC::LWZX;   ImmToIdxMap[PPC::LWA]  = PPC::LWAX;
109   ImmToIdxMap[PPC::LFS]  = PPC::LFSX;   ImmToIdxMap[PPC::LFD]  = PPC::LFDX;
110   ImmToIdxMap[PPC::STH]  = PPC::STHX;   ImmToIdxMap[PPC::STW]  = PPC::STWX;
111   ImmToIdxMap[PPC::STFS] = PPC::STFSX;  ImmToIdxMap[PPC::STFD] = PPC::STFDX;
112   ImmToIdxMap[PPC::ADDI] = PPC::ADD4;
113
114   // 64-bit
115   ImmToIdxMap[PPC::LHA8] = PPC::LHAX8; ImmToIdxMap[PPC::LBZ8] = PPC::LBZX8;
116   ImmToIdxMap[PPC::LHZ8] = PPC::LHZX8; ImmToIdxMap[PPC::LWZ8] = PPC::LWZX8;
117   ImmToIdxMap[PPC::STB8] = PPC::STBX8; ImmToIdxMap[PPC::STH8] = PPC::STHX8;
118   ImmToIdxMap[PPC::STW8] = PPC::STWX8; ImmToIdxMap[PPC::STDU] = PPC::STDUX;
119   ImmToIdxMap[PPC::ADDI8] = PPC::ADD8; ImmToIdxMap[PPC::STD_32] = PPC::STDX_32;
120 }
121
122 void PPCRegisterInfo::reMaterialize(MachineBasicBlock &MBB,
123                                     MachineBasicBlock::iterator I,
124                                     unsigned DestReg,
125                                     const MachineInstr *Orig) const {
126   MachineInstr *MI = Orig->clone();
127   MI->getOperand(0).setReg(DestReg);
128   MBB.insert(I, MI);
129 }
130
131 const unsigned*
132 PPCRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
133   // 32-bit Darwin calling convention. 
134   static const unsigned Macho32_CalleeSavedRegs[] = {
135               PPC::R13, PPC::R14, PPC::R15,
136     PPC::R16, PPC::R17, PPC::R18, PPC::R19,
137     PPC::R20, PPC::R21, PPC::R22, PPC::R23,
138     PPC::R24, PPC::R25, PPC::R26, PPC::R27,
139     PPC::R28, PPC::R29, PPC::R30, PPC::R31,
140
141     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
142     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
143     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
144     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
145     PPC::F30, PPC::F31,
146     
147     PPC::CR2, PPC::CR3, PPC::CR4,
148     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
149     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
150     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
151     
152     PPC::LR,  0
153   };
154   
155   static const unsigned ELF32_CalleeSavedRegs[] = {
156               PPC::R13, PPC::R14, PPC::R15,
157     PPC::R16, PPC::R17, PPC::R18, PPC::R19,
158     PPC::R20, PPC::R21, PPC::R22, PPC::R23,
159     PPC::R24, PPC::R25, PPC::R26, PPC::R27,
160     PPC::R28, PPC::R29, PPC::R30, PPC::R31,
161
162                                   PPC::F9,
163     PPC::F10, PPC::F11, PPC::F12, PPC::F13,
164     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
165     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
166     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
167     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
168     PPC::F30, PPC::F31,
169     
170     PPC::CR2, PPC::CR3, PPC::CR4,
171     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
172     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
173     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
174     
175     PPC::LR,  0
176   };
177   // 64-bit Darwin calling convention. 
178   static const unsigned Macho64_CalleeSavedRegs[] = {
179     PPC::X14, PPC::X15,
180     PPC::X16, PPC::X17, PPC::X18, PPC::X19,
181     PPC::X20, PPC::X21, PPC::X22, PPC::X23,
182     PPC::X24, PPC::X25, PPC::X26, PPC::X27,
183     PPC::X28, PPC::X29, PPC::X30, PPC::X31,
184     
185     PPC::F14, PPC::F15, PPC::F16, PPC::F17,
186     PPC::F18, PPC::F19, PPC::F20, PPC::F21,
187     PPC::F22, PPC::F23, PPC::F24, PPC::F25,
188     PPC::F26, PPC::F27, PPC::F28, PPC::F29,
189     PPC::F30, PPC::F31,
190     
191     PPC::CR2, PPC::CR3, PPC::CR4,
192     PPC::V20, PPC::V21, PPC::V22, PPC::V23,
193     PPC::V24, PPC::V25, PPC::V26, PPC::V27,
194     PPC::V28, PPC::V29, PPC::V30, PPC::V31,
195     
196     PPC::LR8,  0
197   };
198   
199   if (Subtarget.isMachoABI())
200     return Subtarget.isPPC64() ? Macho64_CalleeSavedRegs :
201                                  Macho32_CalleeSavedRegs;
202   
203   // ELF 32.
204   return ELF32_CalleeSavedRegs;
205 }
206
207 const TargetRegisterClass* const*
208 PPCRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
209   // 32-bit Macho calling convention. 
210   static const TargetRegisterClass * const Macho32_CalleeSavedRegClasses[] = {
211                        &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
212     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
213     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
214     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
215     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
216
217     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
218     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
219     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
220     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
221     &PPC::F8RCRegClass,&PPC::F8RCRegClass,
222     
223     &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
224     
225     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
226     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
227     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
228     
229     &PPC::GPRCRegClass, 0
230   };
231   
232   static const TargetRegisterClass * const ELF32_CalleeSavedRegClasses[] = {
233                        &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
234     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
235     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
236     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
237     &PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,&PPC::GPRCRegClass,
238
239                                                              &PPC::F8RCRegClass,
240     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
241     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
242     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
243     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
244     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
245     &PPC::F8RCRegClass,&PPC::F8RCRegClass,
246     
247     &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
248     
249     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
250     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
251     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
252     
253     &PPC::GPRCRegClass, 0
254   };
255   
256   // 64-bit Macho calling convention. 
257   static const TargetRegisterClass * const Macho64_CalleeSavedRegClasses[] = {
258     &PPC::G8RCRegClass,&PPC::G8RCRegClass,
259     &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
260     &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
261     &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
262     &PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,&PPC::G8RCRegClass,
263     
264     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
265     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
266     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
267     &PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,&PPC::F8RCRegClass,
268     &PPC::F8RCRegClass,&PPC::F8RCRegClass,
269     
270     &PPC::CRRCRegClass,&PPC::CRRCRegClass,&PPC::CRRCRegClass,
271     
272     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
273     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
274     &PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,&PPC::VRRCRegClass,
275     
276     &PPC::G8RCRegClass, 0
277   };
278   
279   if (Subtarget.isMachoABI())
280     return Subtarget.isPPC64() ? Macho64_CalleeSavedRegClasses :
281                                  Macho32_CalleeSavedRegClasses;
282   
283   // ELF 32.
284   return ELF32_CalleeSavedRegClasses;
285 }
286
287 // needsFP - Return true if the specified function should have a dedicated frame
288 // pointer register.  This is true if the function has variable sized allocas or
289 // if frame pointer elimination is disabled.
290 //
291 static bool needsFP(const MachineFunction &MF) {
292   const MachineFrameInfo *MFI = MF.getFrameInfo();
293   return NoFramePointerElim || MFI->hasVarSizedObjects();
294 }
295
296 static bool spillsCR(const MachineFunction &MF) {
297   const PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
298   return FuncInfo->isCRSpilled();
299 }
300
301 BitVector PPCRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
302   BitVector Reserved(getNumRegs());
303   Reserved.set(PPC::R0);
304   Reserved.set(PPC::R1);
305   Reserved.set(PPC::LR);
306   Reserved.set(PPC::LR8);
307
308   // In Linux, r2 is reserved for the OS.
309   if (!Subtarget.isDarwin())
310     Reserved.set(PPC::R2);
311
312   // On PPC64, r13 is the thread pointer. Never allocate this register. Note
313   // that this is over conservative, as it also prevents allocation of R31 when
314   // the FP is not needed.
315   if (Subtarget.isPPC64()) {
316     Reserved.set(PPC::R13);
317     Reserved.set(PPC::R31);
318
319     if (!EnablePPCRS)
320       Reserved.set(PPC::R0);    // FIXME (64-bit): Remove
321
322     Reserved.set(PPC::X0);
323     Reserved.set(PPC::X1);
324     Reserved.set(PPC::X13);
325     Reserved.set(PPC::X31);
326   }
327
328   if (needsFP(MF))
329     Reserved.set(PPC::R31);
330
331   return Reserved;
332 }
333
334 //===----------------------------------------------------------------------===//
335 // Stack Frame Processing methods
336 //===----------------------------------------------------------------------===//
337
338 // hasFP - Return true if the specified function actually has a dedicated frame
339 // pointer register.  This is true if the function needs a frame pointer and has
340 // a non-zero stack size.
341 bool PPCRegisterInfo::hasFP(const MachineFunction &MF) const {
342   const MachineFrameInfo *MFI = MF.getFrameInfo();
343   return MFI->getStackSize() && needsFP(MF);
344 }
345
346 /// MustSaveLR - Return true if this function requires that we save the LR
347 /// register onto the stack in the prolog and restore it in the epilog of the
348 /// function.
349 static bool MustSaveLR(const MachineFunction &MF) {
350   const PPCFunctionInfo *MFI = MF.getInfo<PPCFunctionInfo>();
351   
352   // We need an save/restore of LR if there is any use/def of LR explicitly, or
353   // if there is some use of the LR stack slot (e.g. for builtin_return_address.
354   return MFI->usesLR() || MFI->isLRStoreRequired() ||
355          // FIXME: Anything that has a call should clobber the LR register,
356          // isn't this redundant??
357          MF.getFrameInfo()->hasCalls();
358 }
359
360 void PPCRegisterInfo::
361 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
362                               MachineBasicBlock::iterator I) const {
363   // Simply discard ADJCALLSTACKDOWN, ADJCALLSTACKUP instructions.
364   MBB.erase(I);
365 }
366
367 /// findScratchRegister - Find a 'free' PPC register. Try for a call-clobbered
368 /// register first and then a spilled callee-saved register if that fails.
369 static
370 unsigned findScratchRegister(MachineBasicBlock::iterator II, RegScavenger *RS,
371                              const TargetRegisterClass *RC, int SPAdj) {
372   assert(RS && "Register scavenging must be on");
373   unsigned Reg = RS->FindUnusedReg(RC, true);
374   // FIXME: move ARM callee-saved reg scan to target independent code, then 
375   // search for already spilled CS register here.
376   if (Reg == 0)
377     Reg = RS->scavengeRegister(RC, II, SPAdj);
378   return Reg;
379 }
380
381 /// lowerDynamicAlloc - Generate the code for allocating an object in the
382 /// current frame.  The sequence of code with be in the general form
383 ///
384 ///   addi   R0, SP, #frameSize ; get the address of the previous frame
385 ///   stwxu  R0, SP, Rnegsize   ; add and update the SP with the negated size
386 ///   addi   Rnew, SP, #maxCalFrameSize ; get the top of the allocation
387 ///
388 void PPCRegisterInfo::lowerDynamicAlloc(MachineBasicBlock::iterator II,
389                                         int SPAdj, RegScavenger *RS) const {
390   // Get the instruction.
391   MachineInstr &MI = *II;
392   // Get the instruction's basic block.
393   MachineBasicBlock &MBB = *MI.getParent();
394   // Get the basic block's function.
395   MachineFunction &MF = *MBB.getParent();
396   // Get the frame info.
397   MachineFrameInfo *MFI = MF.getFrameInfo();
398   // Determine whether 64-bit pointers are used.
399   bool LP64 = Subtarget.isPPC64();
400
401   // Get the maximum call stack size.
402   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
403   // Get the total frame size.
404   unsigned FrameSize = MFI->getStackSize();
405   
406   // Get stack alignments.
407   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
408   unsigned MaxAlign = MFI->getMaxAlignment();
409   assert(MaxAlign <= TargetAlign &&
410          "Dynamic alloca with large aligns not supported");
411
412   // Determine the previous frame's address.  If FrameSize can't be
413   // represented as 16 bits or we need special alignment, then we load the
414   // previous frame's address from 0(SP).  Why not do an addis of the hi? 
415   // Because R0 is our only safe tmp register and addi/addis treat R0 as zero. 
416   // Constructing the constant and adding would take 3 instructions. 
417   // Fortunately, a frame greater than 32K is rare.
418   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
419   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
420   const TargetRegisterClass *RC = LP64 ? G8RC : GPRC;
421
422   // FIXME (64-bit): Use "findScratchRegister"
423   unsigned Reg;
424   if (EnablePPCRS)
425     Reg = findScratchRegister(II, RS, RC, SPAdj);
426   else
427     Reg = PPC::R0;
428   
429   if (MaxAlign < TargetAlign && isInt16(FrameSize)) {
430     BuildMI(MBB, II, TII.get(PPC::ADDI), Reg)
431       .addReg(PPC::R31)
432       .addImm(FrameSize);
433   } else if (LP64) {
434     if (!EnablePPCRS)
435     if (EnablePPCRS) // FIXME (64-bit): Use "true" version.
436       BuildMI(MBB, II, TII.get(PPC::LD), Reg)
437         .addImm(0)
438         .addReg(PPC::X1);
439     else
440       BuildMI(MBB, II, TII.get(PPC::LD), PPC::X0)
441         .addImm(0)
442         .addReg(PPC::X1);
443   } else {
444     BuildMI(MBB, II, TII.get(PPC::LWZ), Reg)
445       .addImm(0)
446       .addReg(PPC::R1);
447   }
448   
449   // Grow the stack and update the stack pointer link, then determine the
450   // address of new allocated space.
451   if (LP64) {
452     if (EnablePPCRS) // FIXME (64-bit): Use "true" version.
453       BuildMI(MBB, II, TII.get(PPC::STDUX))
454         .addReg(Reg, false, false, true)
455         .addReg(PPC::X1)
456         .addReg(MI.getOperand(1).getReg());
457     else
458       BuildMI(MBB, II, TII.get(PPC::STDUX))
459         .addReg(PPC::X0, false, false, true)
460         .addReg(PPC::X1)
461         .addReg(MI.getOperand(1).getReg());
462
463     if (!MI.getOperand(1).isKill())
464       BuildMI(MBB, II, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
465         .addReg(PPC::X1)
466         .addImm(maxCallFrameSize);
467     else
468       // Implicitly kill the register.
469       BuildMI(MBB, II, TII.get(PPC::ADDI8), MI.getOperand(0).getReg())
470         .addReg(PPC::X1)
471         .addImm(maxCallFrameSize)
472         .addReg(MI.getOperand(1).getReg(), false, true, true);
473   } else {
474     BuildMI(MBB, II, TII.get(PPC::STWUX))
475       .addReg(Reg, false, false, true)
476       .addReg(PPC::R1)
477       .addReg(MI.getOperand(1).getReg());
478
479     if (!MI.getOperand(1).isKill())
480       BuildMI(MBB, II, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
481         .addReg(PPC::R1)
482         .addImm(maxCallFrameSize);
483     else
484       // Implicitly kill the register.
485       BuildMI(MBB, II, TII.get(PPC::ADDI), MI.getOperand(0).getReg())
486         .addReg(PPC::R1)
487         .addImm(maxCallFrameSize)
488         .addReg(MI.getOperand(1).getReg(), false, true, true);
489   }
490   
491   // Discard the DYNALLOC instruction.
492   MBB.erase(II);
493 }
494
495 /// lowerCRSpilling - Generate the code for spilling a CR register. Instead of
496 /// reserving a whole register (R0), we scrounge for one here. This generates
497 /// code like this:
498 ///
499 ///   mfcr rA                  ; Move the conditional register into GPR rA.
500 ///   rlwinm rA, rA, SB, 0, 31 ; Shift the bits left so they are in CR0's slot.
501 ///   stw rA, FI               ; Store rA to the frame.
502 ///
503 void PPCRegisterInfo::lowerCRSpilling(MachineBasicBlock::iterator II,
504                                       unsigned FrameIndex, int SPAdj,
505                                       RegScavenger *RS) const {
506   // Get the instruction.
507   MachineInstr &MI = *II;       // ; SPILL_CR <SrcReg>, <offset>, <FI>
508   // Get the instruction's basic block.
509   MachineBasicBlock &MBB = *MI.getParent();
510
511   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
512   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
513   const TargetRegisterClass *RC = Subtarget.isPPC64() ? G8RC : GPRC;
514   unsigned Reg = findScratchRegister(II, RS, RC, SPAdj);
515
516   // We need to store the CR in the low 4-bits of the saved value.  First, issue
517   // an MFCR to save all of the CRBits.
518   if (!MI.getOperand(0).isKill())
519     BuildMI(MBB, II, TII.get(PPC::MFCR), Reg);
520   else
521     // Implicitly kill the CR register.
522     BuildMI(MBB, II, TII.get(PPC::MFCR), Reg)
523       .addReg(MI.getOperand(0).getReg(), false, true, true);
524
525   // If the saved register wasn't CR0, shift the bits left so that they are in
526   // CR0's slot.
527   unsigned SrcReg = MI.getOperand(0).getReg();
528   if (SrcReg != PPC::CR0)
529     // rlwinm rA, rA, ShiftBits, 0, 31.
530     BuildMI(MBB, II, TII.get(PPC::RLWINM), Reg)
531       .addReg(Reg, false, false, true)
532       .addImm(PPCRegisterInfo::getRegisterNumbering(SrcReg) * 4)
533       .addImm(0)
534       .addImm(31);
535
536   addFrameReference(BuildMI(MBB, II, TII.get(PPC::STW))
537                     .addReg(Reg, false, false, MI.getOperand(1).getImm()),
538                     FrameIndex);
539
540   // Discard the pseudo instruction.
541   MBB.erase(II);
542 }
543
544 void PPCRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
545                                           int SPAdj, RegScavenger *RS) const {
546   assert(SPAdj == 0 && "Unexpected");
547
548   // Get the instruction.
549   MachineInstr &MI = *II;
550   // Get the instruction's basic block.
551   MachineBasicBlock &MBB = *MI.getParent();
552   // Get the basic block's function.
553   MachineFunction &MF = *MBB.getParent();
554   // Get the frame info.
555   MachineFrameInfo *MFI = MF.getFrameInfo();
556
557   // Find out which operand is the frame index.
558   unsigned FIOperandNo = 0;
559   while (!MI.getOperand(FIOperandNo).isFrameIndex()) {
560     ++FIOperandNo;
561     assert(FIOperandNo != MI.getNumOperands() &&
562            "Instr doesn't have FrameIndex operand!");
563   }
564   // Take into account whether it's an add or mem instruction
565   unsigned OffsetOperandNo = (FIOperandNo == 2) ? 1 : 2;
566   if (MI.getOpcode() == TargetInstrInfo::INLINEASM)
567     OffsetOperandNo = FIOperandNo-1;
568
569   // Get the frame index.
570   int FrameIndex = MI.getOperand(FIOperandNo).getIndex();
571
572   // Get the frame pointer save index.  Users of this index are primarily
573   // DYNALLOC instructions.
574   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
575   int FPSI = FI->getFramePointerSaveIndex();
576   // Get the instruction opcode.
577   unsigned OpC = MI.getOpcode();
578   
579   // Special case for dynamic alloca.
580   if (FPSI && FrameIndex == FPSI &&
581       (OpC == PPC::DYNALLOC || OpC == PPC::DYNALLOC8)) {
582     lowerDynamicAlloc(II, SPAdj, RS);
583     return;
584   }
585
586   // Special case for pseudo-op SPILL_CR.
587   if (EnablePPCRS)  // FIXME (64-bit): Enable by default
588     if (OpC == PPC::SPILL_CR) {
589       lowerCRSpilling(II, FrameIndex, SPAdj, RS);
590       return;
591     }
592
593   // Replace the FrameIndex with base register with GPR1 (SP) or GPR31 (FP).
594   MI.getOperand(FIOperandNo).ChangeToRegister(hasFP(MF) ? PPC::R31 : PPC::R1,
595                                               false);
596
597   // Figure out if the offset in the instruction is shifted right two bits. This
598   // is true for instructions like "STD", which the machine implicitly adds two
599   // low zeros to.
600   bool isIXAddr = false;
601   switch (OpC) {
602   case PPC::LWA:
603   case PPC::LD:
604   case PPC::STD:
605   case PPC::STD_32:
606     isIXAddr = true;
607     break;
608   }
609   
610   // Now add the frame object offset to the offset from r1.
611   int Offset = MFI->getObjectOffset(FrameIndex);
612   if (!isIXAddr)
613     Offset += MI.getOperand(OffsetOperandNo).getImm();
614   else
615     Offset += MI.getOperand(OffsetOperandNo).getImm() << 2;
616
617   // If we're not using a Frame Pointer that has been set to the value of the
618   // SP before having the stack size subtracted from it, then add the stack size
619   // to Offset to get the correct offset.
620   Offset += MFI->getStackSize();
621
622   // If we can, encode the offset directly into the instruction.  If this is a
623   // normal PPC "ri" instruction, any 16-bit value can be safely encoded.  If
624   // this is a PPC64 "ix" instruction, only a 16-bit value with the low two bits
625   // clear can be encoded.  This is extremely uncommon, because normally you
626   // only "std" to a stack slot that is at least 4-byte aligned, but it can
627   // happen in invalid code.
628   if (isInt16(Offset) && (!isIXAddr || (Offset & 3) == 0)) {
629     if (isIXAddr)
630       Offset >>= 2;    // The actual encoded value has the low two bits zero.
631     MI.getOperand(OffsetOperandNo).ChangeToImmediate(Offset);
632     return;
633   }
634
635   // The offset doesn't fit into a single register, scavenge one to build the
636   // offset in.
637   // FIXME: figure out what SPAdj is doing here.
638
639   // FIXME (64-bit): Use "findScratchRegister".
640   unsigned SReg;
641   if (EnablePPCRS)
642     SReg = findScratchRegister(II, RS, &PPC::GPRCRegClass, SPAdj);
643   else
644     SReg = PPC::R0;
645
646   // Insert a set of rA with the full offset value before the ld, st, or add
647   BuildMI(MBB, II, TII.get(PPC::LIS), SReg)
648     .addImm(Offset >> 16);
649   BuildMI(MBB, II, TII.get(PPC::ORI), SReg)
650     .addReg(SReg, false, false, true)
651     .addImm(Offset);
652
653   // Convert into indexed form of the instruction:
654   // 
655   //   sth 0:rA, 1:imm 2:(rB) ==> sthx 0:rA, 2:rB, 1:r0
656   //   addi 0:rA 1:rB, 2, imm ==> add 0:rA, 1:rB, 2:r0
657   unsigned OperandBase;
658
659   if (OpC != TargetInstrInfo::INLINEASM) {
660     assert(ImmToIdxMap.count(OpC) &&
661            "No indexed form of load or store available!");
662     unsigned NewOpcode = ImmToIdxMap.find(OpC)->second;
663     MI.setDesc(TII.get(NewOpcode));
664     OperandBase = 1;
665   } else {
666     OperandBase = OffsetOperandNo;
667   }
668     
669   unsigned StackReg = MI.getOperand(FIOperandNo).getReg();
670   MI.getOperand(OperandBase).ChangeToRegister(StackReg, false);
671   MI.getOperand(OperandBase + 1).ChangeToRegister(SReg, false);
672 }
673
674 /// VRRegNo - Map from a numbered VR register to its enum value.
675 ///
676 static const unsigned short VRRegNo[] = {
677  PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 , PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
678  PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, PPC::V12, PPC::V13, PPC::V14, PPC::V15,
679  PPC::V16, PPC::V17, PPC::V18, PPC::V19, PPC::V20, PPC::V21, PPC::V22, PPC::V23,
680  PPC::V24, PPC::V25, PPC::V26, PPC::V27, PPC::V28, PPC::V29, PPC::V30, PPC::V31
681 };
682
683 /// RemoveVRSaveCode - We have found that this function does not need any code
684 /// to manipulate the VRSAVE register, even though it uses vector registers.
685 /// This can happen when the only registers used are known to be live in or out
686 /// of the function.  Remove all of the VRSAVE related code from the function.
687 static void RemoveVRSaveCode(MachineInstr *MI) {
688   MachineBasicBlock *Entry = MI->getParent();
689   MachineFunction *MF = Entry->getParent();
690
691   // We know that the MTVRSAVE instruction immediately follows MI.  Remove it.
692   MachineBasicBlock::iterator MBBI = MI;
693   ++MBBI;
694   assert(MBBI != Entry->end() && MBBI->getOpcode() == PPC::MTVRSAVE);
695   MBBI->eraseFromParent();
696   
697   bool RemovedAllMTVRSAVEs = true;
698   // See if we can find and remove the MTVRSAVE instruction from all of the
699   // epilog blocks.
700   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E; ++I) {
701     // If last instruction is a return instruction, add an epilogue
702     if (!I->empty() && I->back().getDesc().isReturn()) {
703       bool FoundIt = false;
704       for (MBBI = I->end(); MBBI != I->begin(); ) {
705         --MBBI;
706         if (MBBI->getOpcode() == PPC::MTVRSAVE) {
707           MBBI->eraseFromParent();  // remove it.
708           FoundIt = true;
709           break;
710         }
711       }
712       RemovedAllMTVRSAVEs &= FoundIt;
713     }
714   }
715
716   // If we found and removed all MTVRSAVE instructions, remove the read of
717   // VRSAVE as well.
718   if (RemovedAllMTVRSAVEs) {
719     MBBI = MI;
720     assert(MBBI != Entry->begin() && "UPDATE_VRSAVE is first instr in block?");
721     --MBBI;
722     assert(MBBI->getOpcode() == PPC::MFVRSAVE && "VRSAVE instrs wandered?");
723     MBBI->eraseFromParent();
724   }
725   
726   // Finally, nuke the UPDATE_VRSAVE.
727   MI->eraseFromParent();
728 }
729
730 // HandleVRSaveUpdate - MI is the UPDATE_VRSAVE instruction introduced by the
731 // instruction selector.  Based on the vector registers that have been used,
732 // transform this into the appropriate ORI instruction.
733 static void HandleVRSaveUpdate(MachineInstr *MI, const TargetInstrInfo &TII) {
734   MachineFunction *MF = MI->getParent()->getParent();
735
736   unsigned UsedRegMask = 0;
737   for (unsigned i = 0; i != 32; ++i)
738     if (MF->getRegInfo().isPhysRegUsed(VRRegNo[i]))
739       UsedRegMask |= 1 << (31-i);
740   
741   // Live in and live out values already must be in the mask, so don't bother
742   // marking them.
743   for (MachineRegisterInfo::livein_iterator
744        I = MF->getRegInfo().livein_begin(),
745        E = MF->getRegInfo().livein_end(); I != E; ++I) {
746     unsigned RegNo = PPCRegisterInfo::getRegisterNumbering(I->first);
747     if (VRRegNo[RegNo] == I->first)        // If this really is a vector reg.
748       UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
749   }
750   for (MachineRegisterInfo::liveout_iterator
751        I = MF->getRegInfo().liveout_begin(),
752        E = MF->getRegInfo().liveout_end(); I != E; ++I) {
753     unsigned RegNo = PPCRegisterInfo::getRegisterNumbering(*I);
754     if (VRRegNo[RegNo] == *I)              // If this really is a vector reg.
755       UsedRegMask &= ~(1 << (31-RegNo));   // Doesn't need to be marked.
756   }
757   
758   // If no registers are used, turn this into a copy.
759   if (UsedRegMask == 0) {
760     // Remove all VRSAVE code.
761     RemoveVRSaveCode(MI);
762     return;
763   }
764
765   unsigned SrcReg = MI->getOperand(1).getReg();
766   unsigned DstReg = MI->getOperand(0).getReg();
767
768   if ((UsedRegMask & 0xFFFF) == UsedRegMask) {
769     if (DstReg != SrcReg)
770       BuildMI(*MI->getParent(), MI, TII.get(PPC::ORI), DstReg)
771         .addReg(SrcReg)
772         .addImm(UsedRegMask);
773     else
774       BuildMI(*MI->getParent(), MI, TII.get(PPC::ORI), DstReg)
775         .addReg(SrcReg, false, false, true)
776         .addImm(UsedRegMask);
777   } else if ((UsedRegMask & 0xFFFF0000) == UsedRegMask) {
778     if (DstReg != SrcReg)
779       BuildMI(*MI->getParent(), MI, TII.get(PPC::ORIS), DstReg)
780         .addReg(SrcReg)
781         .addImm(UsedRegMask >> 16);
782     else
783       BuildMI(*MI->getParent(), MI, TII.get(PPC::ORIS), DstReg)
784         .addReg(SrcReg, false, false, true)
785         .addImm(UsedRegMask >> 16);
786   } else {
787     if (DstReg != SrcReg)
788       BuildMI(*MI->getParent(), MI, TII.get(PPC::ORIS), DstReg)
789         .addReg(SrcReg)
790         .addImm(UsedRegMask >> 16);
791     else
792       BuildMI(*MI->getParent(), MI, TII.get(PPC::ORIS), DstReg)
793         .addReg(SrcReg, false, false, true)
794         .addImm(UsedRegMask >> 16);
795
796     BuildMI(*MI->getParent(), MI, TII.get(PPC::ORI), DstReg)
797       .addReg(DstReg, false, false, true)
798       .addImm(UsedRegMask & 0xFFFF);
799   }
800   
801   // Remove the old UPDATE_VRSAVE instruction.
802   MI->eraseFromParent();
803 }
804
805 /// determineFrameLayout - Determine the size of the frame and maximum call
806 /// frame size.
807 void PPCRegisterInfo::determineFrameLayout(MachineFunction &MF) const {
808   MachineFrameInfo *MFI = MF.getFrameInfo();
809
810   // Get the number of bytes to allocate from the FrameInfo
811   unsigned FrameSize = MFI->getStackSize();
812   
813   // Get the alignments provided by the target, and the maximum alignment
814   // (if any) of the fixed frame objects.
815   unsigned MaxAlign = MFI->getMaxAlignment();
816   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
817   unsigned AlignMask = TargetAlign - 1;  //
818
819   // If we are a leaf function, and use up to 224 bytes of stack space,
820   // don't have a frame pointer, calls, or dynamic alloca then we do not need
821   // to adjust the stack pointer (we fit in the Red Zone).
822   if (FrameSize <= 224 &&             // Fits in red zone.
823       !MFI->hasVarSizedObjects() &&   // No dynamic alloca.
824       !MFI->hasCalls() &&             // No calls.
825       MaxAlign <= TargetAlign) {      // No special alignment.
826     // No need for frame
827     MFI->setStackSize(0);
828     return;
829   }
830   
831   // Get the maximum call frame size of all the calls.
832   unsigned maxCallFrameSize = MFI->getMaxCallFrameSize();
833   
834   // Maximum call frame needs to be at least big enough for linkage and 8 args.
835   unsigned minCallFrameSize =
836     PPCFrameInfo::getMinCallFrameSize(Subtarget.isPPC64(), 
837                                       Subtarget.isMachoABI());
838   maxCallFrameSize = std::max(maxCallFrameSize, minCallFrameSize);
839
840   // If we have dynamic alloca then maxCallFrameSize needs to be aligned so
841   // that allocations will be aligned.
842   if (MFI->hasVarSizedObjects())
843     maxCallFrameSize = (maxCallFrameSize + AlignMask) & ~AlignMask;
844   
845   // Update maximum call frame size.
846   MFI->setMaxCallFrameSize(maxCallFrameSize);
847   
848   // Include call frame size in total.
849   FrameSize += maxCallFrameSize;
850   
851   // Make sure the frame is aligned.
852   FrameSize = (FrameSize + AlignMask) & ~AlignMask;
853
854   // Update frame info.
855   MFI->setStackSize(FrameSize);
856 }
857
858 void
859 PPCRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
860                                                       RegScavenger *RS) const {
861   //  Save and clear the LR state.
862   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
863   unsigned LR = getRARegister();
864   FI->setUsesLR(MF.getRegInfo().isPhysRegUsed(LR));
865   MF.getRegInfo().setPhysRegUnused(LR);
866
867   //  Save R31 if necessary
868   int FPSI = FI->getFramePointerSaveIndex();
869   bool IsPPC64 = Subtarget.isPPC64();
870   bool IsELF32_ABI = Subtarget.isELF32_ABI();
871   bool IsMachoABI  = Subtarget.isMachoABI();
872   MachineFrameInfo *MFI = MF.getFrameInfo();
873  
874   // If the frame pointer save index hasn't been defined yet.
875   if (!FPSI && (NoFramePointerElim || MFI->hasVarSizedObjects()) &&
876       IsELF32_ABI) {
877     // Find out what the fix offset of the frame pointer save area.
878     int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64,
879                                                            IsMachoABI);
880     // Allocate the frame index for frame pointer save area.
881     FPSI = MF.getFrameInfo()->CreateFixedObject(IsPPC64? 8 : 4, FPOffset);
882     // Save the result.
883     FI->setFramePointerSaveIndex(FPSI);                      
884   }
885
886   // Reserve a slot closest to SP or frame pointer if we have a dynalloc or
887   // a large stack, which will require scavenging a register to materialize a
888   // large offset.
889   // FIXME: this doesn't actually check stack size, so is a bit pessimistic
890   // FIXME: doesn't detect whether or not we need to spill vXX, which requires
891   //        r0 for now.
892
893   if (EnablePPCRS)  // FIXME (64-bit): Enable.
894     if (needsFP(MF) || spillsCR(MF)) {
895       const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
896       const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
897       const TargetRegisterClass *RC = IsPPC64 ? G8RC : GPRC;
898       RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
899                                                          RC->getAlignment()));
900     }
901 }
902
903 void
904 PPCRegisterInfo::emitPrologue(MachineFunction &MF) const {
905   MachineBasicBlock &MBB = MF.front();   // Prolog goes in entry BB
906   MachineBasicBlock::iterator MBBI = MBB.begin();
907   MachineFrameInfo *MFI = MF.getFrameInfo();
908   MachineModuleInfo *MMI = MFI->getMachineModuleInfo();
909   
910   // Prepare for frame info.
911   unsigned FrameLabelId = 0;
912
913   // Scan the prolog, looking for an UPDATE_VRSAVE instruction.  If we find it,
914   // process it.
915   for (unsigned i = 0; MBBI != MBB.end(); ++i, ++MBBI) {
916     if (MBBI->getOpcode() == PPC::UPDATE_VRSAVE) {
917       HandleVRSaveUpdate(MBBI, TII);
918       break;
919     }
920   }
921   
922   // Move MBBI back to the beginning of the function.
923   MBBI = MBB.begin();
924
925   // Work out frame sizes.
926   determineFrameLayout(MF);
927   unsigned FrameSize = MFI->getStackSize();
928   
929   int NegFrameSize = -FrameSize;
930   
931   // Get processor type.
932   bool IsPPC64 = Subtarget.isPPC64();
933   // Get operating system
934   bool IsMachoABI = Subtarget.isMachoABI();
935   // Check if the link register (LR) has been used.
936   bool UsesLR = MustSaveLR(MF);
937   // Do we have a frame pointer for this function?
938   bool HasFP = hasFP(MF) && FrameSize;
939   
940   int LROffset = PPCFrameInfo::getReturnSaveOffset(IsPPC64, IsMachoABI);
941   int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, IsMachoABI);
942
943   if (IsPPC64) {
944     if (UsesLR)
945       BuildMI(MBB, MBBI, TII.get(PPC::MFLR8), PPC::X0);
946       
947     if (HasFP)
948       BuildMI(MBB, MBBI, TII.get(PPC::STD))
949         .addReg(PPC::X31)
950         .addImm(FPOffset/4)
951         .addReg(PPC::X1);
952     
953     if (UsesLR)
954       BuildMI(MBB, MBBI, TII.get(PPC::STD))
955         .addReg(PPC::X0)
956         .addImm(LROffset / 4)
957         .addReg(PPC::X1);
958   } else {
959     if (UsesLR)
960       BuildMI(MBB, MBBI, TII.get(PPC::MFLR), PPC::R0);
961       
962     if (HasFP)
963       BuildMI(MBB, MBBI, TII.get(PPC::STW))
964         .addReg(PPC::R31)
965         .addImm(FPOffset)
966         .addReg(PPC::R1);
967
968     if (UsesLR)
969       BuildMI(MBB, MBBI, TII.get(PPC::STW))
970         .addReg(PPC::R0)
971         .addImm(LROffset)
972         .addReg(PPC::R1);
973   }
974   
975   // Skip if a leaf routine.
976   if (!FrameSize) return;
977   
978   // Get stack alignments.
979   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
980   unsigned MaxAlign = MFI->getMaxAlignment();
981
982   if (MMI && MMI->needsFrameInfo()) {
983     // Mark effective beginning of when frame pointer becomes valid.
984     FrameLabelId = MMI->NextLabelID();
985     BuildMI(MBB, MBBI, TII.get(PPC::LABEL)).addImm(FrameLabelId).addImm(0);
986   }
987   
988   // Adjust stack pointer: r1 += NegFrameSize.
989   // If there is a preferred stack alignment, align R1 now
990   if (!IsPPC64) {
991     // PPC32.
992     if (MaxAlign > TargetAlign) {
993       assert(isPowerOf2_32(MaxAlign)&&isInt16(MaxAlign)&&"Invalid alignment!");
994       assert(isInt16(NegFrameSize) && "Unhandled stack size and alignment!");
995
996       BuildMI(MBB, MBBI, TII.get(PPC::RLWINM), PPC::R0)
997         .addReg(PPC::R1)
998         .addImm(0)
999         .addImm(32 - Log2_32(MaxAlign))
1000         .addImm(31);
1001       BuildMI(MBB, MBBI, TII.get(PPC::SUBFIC) ,PPC::R0)
1002         .addReg(PPC::R0, false, false, true)
1003         .addImm(NegFrameSize);
1004       BuildMI(MBB, MBBI, TII.get(PPC::STWUX))
1005         .addReg(PPC::R1)
1006         .addReg(PPC::R1)
1007         .addReg(PPC::R0);
1008     } else if (isInt16(NegFrameSize)) {
1009       BuildMI(MBB, MBBI, TII.get(PPC::STWU), PPC::R1)
1010         .addReg(PPC::R1)
1011         .addImm(NegFrameSize)
1012         .addReg(PPC::R1);
1013     } else {
1014       BuildMI(MBB, MBBI, TII.get(PPC::LIS), PPC::R0)
1015         .addImm(NegFrameSize >> 16);
1016       BuildMI(MBB, MBBI, TII.get(PPC::ORI), PPC::R0)
1017         .addReg(PPC::R0, false, false, true)
1018         .addImm(NegFrameSize & 0xFFFF);
1019       BuildMI(MBB, MBBI, TII.get(PPC::STWUX))
1020         .addReg(PPC::R1)
1021         .addReg(PPC::R1)
1022         .addReg(PPC::R0);
1023     }
1024   } else {    // PPC64.
1025     if (MaxAlign > TargetAlign) {
1026       assert(isPowerOf2_32(MaxAlign)&&isInt16(MaxAlign)&&"Invalid alignment!");
1027       assert(isInt16(NegFrameSize) && "Unhandled stack size and alignment!");
1028
1029       BuildMI(MBB, MBBI, TII.get(PPC::RLDICL), PPC::X0)
1030         .addReg(PPC::X1)
1031         .addImm(0)
1032         .addImm(64 - Log2_32(MaxAlign));
1033       BuildMI(MBB, MBBI, TII.get(PPC::SUBFIC8), PPC::X0)
1034         .addReg(PPC::X0)
1035         .addImm(NegFrameSize);
1036       BuildMI(MBB, MBBI, TII.get(PPC::STDUX))
1037         .addReg(PPC::X1)
1038         .addReg(PPC::X1)
1039         .addReg(PPC::X0);
1040     } else if (isInt16(NegFrameSize)) {
1041       BuildMI(MBB, MBBI, TII.get(PPC::STDU), PPC::X1)
1042         .addReg(PPC::X1)
1043         .addImm(NegFrameSize / 4)
1044         .addReg(PPC::X1);
1045     } else {
1046       BuildMI(MBB, MBBI, TII.get(PPC::LIS8), PPC::X0)
1047         .addImm(NegFrameSize >> 16);
1048       BuildMI(MBB, MBBI, TII.get(PPC::ORI8), PPC::X0)
1049         .addReg(PPC::X0, false, false, true)
1050         .addImm(NegFrameSize & 0xFFFF);
1051       BuildMI(MBB, MBBI, TII.get(PPC::STDUX))
1052         .addReg(PPC::X1)
1053         .addReg(PPC::X1)
1054         .addReg(PPC::X0);
1055     }
1056   }
1057   
1058   if (MMI && MMI->needsFrameInfo()) {
1059     std::vector<MachineMove> &Moves = MMI->getFrameMoves();
1060     
1061     if (NegFrameSize) {
1062       // Show update of SP.
1063       MachineLocation SPDst(MachineLocation::VirtualFP);
1064       MachineLocation SPSrc(MachineLocation::VirtualFP, NegFrameSize);
1065       Moves.push_back(MachineMove(FrameLabelId, SPDst, SPSrc));
1066     } else {
1067       MachineLocation SP(IsPPC64 ? PPC::X31 : PPC::R31);
1068       Moves.push_back(MachineMove(FrameLabelId, SP, SP));
1069     }
1070     
1071     if (HasFP) {
1072       MachineLocation FPDst(MachineLocation::VirtualFP, FPOffset);
1073       MachineLocation FPSrc(IsPPC64 ? PPC::X31 : PPC::R31);
1074       Moves.push_back(MachineMove(FrameLabelId, FPDst, FPSrc));
1075     }
1076
1077     // Add callee saved registers to move list.
1078     const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1079     for (unsigned I = 0, E = CSI.size(); I != E; ++I) {
1080       int Offset = MFI->getObjectOffset(CSI[I].getFrameIdx());
1081       unsigned Reg = CSI[I].getReg();
1082       if (Reg == PPC::LR || Reg == PPC::LR8) continue;
1083       MachineLocation CSDst(MachineLocation::VirtualFP, Offset);
1084       MachineLocation CSSrc(Reg);
1085       Moves.push_back(MachineMove(FrameLabelId, CSDst, CSSrc));
1086     }
1087     
1088     MachineLocation LRDst(MachineLocation::VirtualFP, LROffset);
1089     MachineLocation LRSrc(IsPPC64 ? PPC::LR8 : PPC::LR);
1090     Moves.push_back(MachineMove(FrameLabelId, LRDst, LRSrc));
1091     
1092     // Mark effective beginning of when frame pointer is ready.
1093     unsigned ReadyLabelId = MMI->NextLabelID();
1094     BuildMI(MBB, MBBI, TII.get(PPC::LABEL)).addImm(ReadyLabelId).addImm(0);
1095     
1096     MachineLocation FPDst(HasFP ? (IsPPC64 ? PPC::X31 : PPC::R31) :
1097                                   (IsPPC64 ? PPC::X1 : PPC::R1));
1098     MachineLocation FPSrc(MachineLocation::VirtualFP);
1099     Moves.push_back(MachineMove(ReadyLabelId, FPDst, FPSrc));
1100   }
1101
1102   // If there is a frame pointer, copy R1 into R31
1103   if (HasFP) {
1104     if (!IsPPC64) {
1105       BuildMI(MBB, MBBI, TII.get(PPC::OR), PPC::R31)
1106         .addReg(PPC::R1)
1107         .addReg(PPC::R1);
1108     } else {
1109       BuildMI(MBB, MBBI, TII.get(PPC::OR8), PPC::X31)
1110         .addReg(PPC::X1)
1111         .addReg(PPC::X1);
1112     }
1113   }
1114 }
1115
1116 void PPCRegisterInfo::emitEpilogue(MachineFunction &MF,
1117                                    MachineBasicBlock &MBB) const {
1118   MachineBasicBlock::iterator MBBI = prior(MBB.end());
1119   assert(MBBI->getOpcode() == PPC::BLR &&
1120          "Can only insert epilog into returning blocks");
1121
1122   // Get alignment info so we know how to restore r1
1123   const MachineFrameInfo *MFI = MF.getFrameInfo();
1124   unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1125   unsigned MaxAlign = MFI->getMaxAlignment();
1126
1127   // Get the number of bytes allocated from the FrameInfo.
1128   unsigned FrameSize = MFI->getStackSize();
1129
1130   // Get processor type.
1131   bool IsPPC64 = Subtarget.isPPC64();
1132   // Get operating system
1133   bool IsMachoABI = Subtarget.isMachoABI();
1134   // Check if the link register (LR) has been used.
1135   bool UsesLR = MustSaveLR(MF);
1136   // Do we have a frame pointer for this function?
1137   bool HasFP = hasFP(MF) && FrameSize;
1138   
1139   int LROffset = PPCFrameInfo::getReturnSaveOffset(IsPPC64, IsMachoABI);
1140   int FPOffset = PPCFrameInfo::getFramePointerSaveOffset(IsPPC64, IsMachoABI);
1141   
1142   if (FrameSize) {
1143     // The loaded (or persistent) stack pointer value is offset by the 'stwu'
1144     // on entry to the function.  Add this offset back now.
1145     if (!Subtarget.isPPC64()) {
1146       if (isInt16(FrameSize) && TargetAlign >= MaxAlign &&
1147             !MFI->hasVarSizedObjects()) {
1148           BuildMI(MBB, MBBI, TII.get(PPC::ADDI), PPC::R1)
1149               .addReg(PPC::R1).addImm(FrameSize);
1150       } else {
1151         BuildMI(MBB, MBBI, TII.get(PPC::LWZ),PPC::R1).addImm(0).addReg(PPC::R1);
1152       }
1153     } else {
1154       if (isInt16(FrameSize) && TargetAlign >= MaxAlign &&
1155             !MFI->hasVarSizedObjects()) {
1156         BuildMI(MBB, MBBI, TII.get(PPC::ADDI8), PPC::X1)
1157            .addReg(PPC::X1).addImm(FrameSize);
1158       } else {
1159         BuildMI(MBB, MBBI, TII.get(PPC::LD), PPC::X1).addImm(0).addReg(PPC::X1);
1160       }
1161     }
1162   }
1163
1164   if (IsPPC64) {
1165     if (UsesLR)
1166       BuildMI(MBB, MBBI, TII.get(PPC::LD), PPC::X0)
1167         .addImm(LROffset/4).addReg(PPC::X1);
1168         
1169     if (HasFP)
1170       BuildMI(MBB, MBBI, TII.get(PPC::LD), PPC::X31)
1171         .addImm(FPOffset/4).addReg(PPC::X1);
1172         
1173     if (UsesLR)
1174       BuildMI(MBB, MBBI, TII.get(PPC::MTLR8)).addReg(PPC::X0);
1175   } else {
1176     if (UsesLR)
1177       BuildMI(MBB, MBBI, TII.get(PPC::LWZ), PPC::R0)
1178           .addImm(LROffset).addReg(PPC::R1);
1179         
1180     if (HasFP)
1181       BuildMI(MBB, MBBI, TII.get(PPC::LWZ), PPC::R31)
1182           .addImm(FPOffset).addReg(PPC::R1);
1183           
1184     if (UsesLR)
1185       BuildMI(MBB, MBBI, TII.get(PPC::MTLR)).addReg(PPC::R0);
1186   }
1187 }
1188
1189 unsigned PPCRegisterInfo::getRARegister() const {
1190   return !Subtarget.isPPC64() ? PPC::LR : PPC::LR8;
1191 }
1192
1193 unsigned PPCRegisterInfo::getFrameRegister(MachineFunction &MF) const {
1194   if (!Subtarget.isPPC64())
1195     return hasFP(MF) ? PPC::R31 : PPC::R1;
1196   else
1197     return hasFP(MF) ? PPC::X31 : PPC::X1;
1198 }
1199
1200 void PPCRegisterInfo::getInitialFrameState(std::vector<MachineMove> &Moves)
1201                                                                          const {
1202   // Initial state of the frame pointer is R1.
1203   MachineLocation Dst(MachineLocation::VirtualFP);
1204   MachineLocation Src(PPC::R1, 0);
1205   Moves.push_back(MachineMove(0, Dst, Src));
1206 }
1207
1208 unsigned PPCRegisterInfo::getEHExceptionRegister() const {
1209   return !Subtarget.isPPC64() ? PPC::R3 : PPC::X3;
1210 }
1211
1212 unsigned PPCRegisterInfo::getEHHandlerRegister() const {
1213   return !Subtarget.isPPC64() ? PPC::R4 : PPC::X4;
1214 }
1215
1216 int PPCRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
1217   // FIXME: Most probably dwarf numbers differs for Linux and Darwin
1218   return PPCGenRegisterInfo::getDwarfRegNumFull(RegNum, 0);
1219 }
1220
1221 #include "PPCGenRegisterInfo.inc"
1222