Use TableGen to emit information for dwarf register numbers.
[oota-llvm.git] / lib / Target / ARM / ARMRegisterInfo.cpp
1 //===- ARMRegisterInfo.cpp - ARM Register Information -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the "Instituto Nokia de Tecnologia" and
6 // is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This file contains the ARM implementation of the MRegisterInfo class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMInstrInfo.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMRegisterInfo.h"
20 #include "ARMSubtarget.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineLocation.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/Target/TargetFrameInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include <algorithm>
37 using namespace llvm;
38
39 static cl::opt<bool> ThumbRegScavenging("enable-thumb-reg-scavenging",
40                                cl::Hidden,
41                                cl::desc("Enable register scavenging on Thumb"));
42
43 unsigned ARMRegisterInfo::getRegisterNumbering(unsigned RegEnum) {
44   using namespace ARM;
45   switch (RegEnum) {
46   case R0:  case S0:  case D0:  return 0;
47   case R1:  case S1:  case D1:  return 1;
48   case R2:  case S2:  case D2:  return 2;
49   case R3:  case S3:  case D3:  return 3;
50   case R4:  case S4:  case D4:  return 4;
51   case R5:  case S5:  case D5:  return 5;
52   case R6:  case S6:  case D6:  return 6;
53   case R7:  case S7:  case D7:  return 7;
54   case R8:  case S8:  case D8:  return 8;
55   case R9:  case S9:  case D9:  return 9;
56   case R10: case S10: case D10: return 10;
57   case R11: case S11: case D11: return 11;
58   case R12: case S12: case D12: return 12;
59   case SP:  case S13: case D13: return 13;
60   case LR:  case S14: case D14: return 14;
61   case PC:  case S15: case D15: return 15;
62   case S16: return 16;
63   case S17: return 17;
64   case S18: return 18;
65   case S19: return 19;
66   case S20: return 20;
67   case S21: return 21;
68   case S22: return 22;
69   case S23: return 23;
70   case S24: return 24;
71   case S25: return 25;
72   case S26: return 26;
73   case S27: return 27;
74   case S28: return 28;
75   case S29: return 29;
76   case S30: return 30;
77   case S31: return 31;
78   default:
79     assert(0 && "Unknown ARM register!");
80     abort();
81   }
82 }
83
84 ARMRegisterInfo::ARMRegisterInfo(const TargetInstrInfo &tii,
85                                  const ARMSubtarget &sti)
86   : ARMGenRegisterInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
87     TII(tii), STI(sti),
88     FramePtr((STI.useThumbBacktraces() || STI.isThumb()) ? ARM::R7 : ARM::R11) {
89 }
90
91 bool ARMRegisterInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
92                                                 MachineBasicBlock::iterator MI,
93                                 const std::vector<CalleeSavedInfo> &CSI) const {
94   MachineFunction &MF = *MBB.getParent();
95   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
96   if (!AFI->isThumbFunction() || CSI.empty())
97     return false;
98
99   MachineInstrBuilder MIB = BuildMI(MBB, MI, TII.get(ARM::tPUSH));
100   for (unsigned i = CSI.size(); i != 0; --i) {
101     unsigned Reg = CSI[i-1].getReg();
102     // Add the callee-saved register as live-in. It's killed at the spill.
103     MBB.addLiveIn(Reg);
104     MIB.addReg(Reg, false/*isDef*/,false/*isImp*/,true/*isKill*/);
105   }
106   return true;
107 }
108
109 bool ARMRegisterInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
110                                                  MachineBasicBlock::iterator MI,
111                                 const std::vector<CalleeSavedInfo> &CSI) const {
112   MachineFunction &MF = *MBB.getParent();
113   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
114   if (!AFI->isThumbFunction() || CSI.empty())
115     return false;
116
117   bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
118   MachineInstr *PopMI = new MachineInstr(TII.get(ARM::tPOP));
119   MBB.insert(MI, PopMI);
120   for (unsigned i = CSI.size(); i != 0; --i) {
121     unsigned Reg = CSI[i-1].getReg();
122     if (Reg == ARM::LR) {
123       // Special epilogue for vararg functions. See emitEpilogue
124       if (isVarArg)
125         continue;
126       Reg = ARM::PC;
127       PopMI->setInstrDescriptor(TII.get(ARM::tPOP_RET));
128       MBB.erase(MI);
129     }
130     PopMI->addRegOperand(Reg, true);
131   }
132   return true;
133 }
134
135 static inline
136 const MachineInstrBuilder &AddDefaultPred(const MachineInstrBuilder &MIB) {
137   return MIB.addImm((int64_t)ARMCC::AL).addReg(0);
138 }
139
140 static inline
141 const MachineInstrBuilder &AddDefaultCC(const MachineInstrBuilder &MIB) {
142   return MIB.addReg(0);
143 }
144
145 static const MachineInstrBuilder &ARMInstrAddOperand(MachineInstrBuilder &MIB,
146                                                      MachineOperand &MO) {
147   if (MO.isRegister())
148     MIB = MIB.addReg(MO.getReg(), MO.isDef(), MO.isImplicit());
149   else if (MO.isImmediate())
150     MIB = MIB.addImm(MO.getImm());
151   else if (MO.isFrameIndex())
152     MIB = MIB.addFrameIndex(MO.getFrameIndex());
153   else
154     assert(0 && "Unknown operand for ARMInstrAddOperand!");
155
156   return MIB;
157 }
158
159 void ARMRegisterInfo::
160 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
161                     unsigned SrcReg, int FI,
162                     const TargetRegisterClass *RC) const {
163   if (RC == ARM::GPRRegisterClass) {
164     MachineFunction &MF = *MBB.getParent();
165     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
166     if (AFI->isThumbFunction())
167       BuildMI(MBB, I, TII.get(ARM::tSpill)).addReg(SrcReg, false, false, true)
168         .addFrameIndex(FI).addImm(0);
169     else
170       AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::STR))
171                      .addReg(SrcReg, false, false, true)
172                      .addFrameIndex(FI).addReg(0).addImm(0));
173   } else if (RC == ARM::DPRRegisterClass) {
174     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FSTD))
175                    .addReg(SrcReg, false, false, true)
176                    .addFrameIndex(FI).addImm(0));
177   } else {
178     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
179     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FSTS))
180                    .addReg(SrcReg, false, false, true)
181                    .addFrameIndex(FI).addImm(0));
182   }
183 }
184
185 void ARMRegisterInfo::storeRegToAddr(MachineFunction &MF, unsigned SrcReg,
186                                      SmallVectorImpl<MachineOperand> &Addr,
187                                      const TargetRegisterClass *RC,
188                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
189   unsigned Opc = 0;
190   if (RC == ARM::GPRRegisterClass) {
191     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
192     if (AFI->isThumbFunction()) {
193       Opc = Addr[0].isFrameIndex() ? ARM::tSpill : ARM::tSTR;
194       MachineInstrBuilder MIB = 
195         BuildMI(TII.get(Opc)).addReg(SrcReg, false, false, true);
196       for (unsigned i = 0, e = Addr.size(); i != e; ++i)
197         MIB = ARMInstrAddOperand(MIB, Addr[i]);
198       NewMIs.push_back(MIB);
199       return;
200     }
201     Opc = ARM::STR;
202   } else if (RC == ARM::DPRRegisterClass) {
203     Opc = ARM::FSTD;
204   } else {
205     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
206     Opc = ARM::FSTS;
207   }
208
209   MachineInstrBuilder MIB = 
210     BuildMI(TII.get(Opc)).addReg(SrcReg, false, false, true);
211   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
212     MIB = ARMInstrAddOperand(MIB, Addr[i]);
213   AddDefaultPred(MIB);
214   NewMIs.push_back(MIB);
215   return;
216 }
217
218 void ARMRegisterInfo::
219 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
220                      unsigned DestReg, int FI,
221                      const TargetRegisterClass *RC) const {
222   if (RC == ARM::GPRRegisterClass) {
223     MachineFunction &MF = *MBB.getParent();
224     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
225     if (AFI->isThumbFunction())
226       BuildMI(MBB, I, TII.get(ARM::tRestore), DestReg)
227         .addFrameIndex(FI).addImm(0);
228     else
229       AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::LDR), DestReg)
230                      .addFrameIndex(FI).addReg(0).addImm(0));
231   } else if (RC == ARM::DPRRegisterClass) {
232     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FLDD), DestReg)
233                    .addFrameIndex(FI).addImm(0));
234   } else {
235     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
236     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FLDS), DestReg)
237                    .addFrameIndex(FI).addImm(0));
238   }
239 }
240
241 void ARMRegisterInfo::loadRegFromAddr(MachineFunction &MF, unsigned DestReg,
242                                       SmallVectorImpl<MachineOperand> &Addr,
243                                       const TargetRegisterClass *RC,
244                                  SmallVectorImpl<MachineInstr*> &NewMIs) const {
245   unsigned Opc = 0;
246   if (RC == ARM::GPRRegisterClass) {
247     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
248     if (AFI->isThumbFunction()) {
249       Opc = Addr[0].isFrameIndex() ? ARM::tRestore : ARM::tLDR;
250       MachineInstrBuilder MIB = BuildMI(TII.get(Opc), DestReg);
251       for (unsigned i = 0, e = Addr.size(); i != e; ++i)
252         MIB = ARMInstrAddOperand(MIB, Addr[i]);
253       NewMIs.push_back(MIB);
254       return;
255     }
256     Opc = ARM::LDR;
257   } else if (RC == ARM::DPRRegisterClass) {
258     Opc = ARM::FLDD;
259   } else {
260     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
261     Opc = ARM::FLDS;
262   }
263
264   MachineInstrBuilder MIB =  BuildMI(TII.get(Opc), DestReg);
265   for (unsigned i = 0, e = Addr.size(); i != e; ++i)
266     MIB = ARMInstrAddOperand(MIB, Addr[i]);
267   AddDefaultPred(MIB);
268   NewMIs.push_back(MIB);
269   return;
270 }
271
272 void ARMRegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
273                                    MachineBasicBlock::iterator I,
274                                    unsigned DestReg, unsigned SrcReg,
275                                    const TargetRegisterClass *DestRC,
276                                    const TargetRegisterClass *SrcRC) const {
277   if (DestRC != SrcRC) {
278     cerr << "Not yet supported!";
279     abort();
280   }
281
282   if (DestRC == ARM::GPRRegisterClass) {
283     MachineFunction &MF = *MBB.getParent();
284     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
285     if (AFI->isThumbFunction())
286       BuildMI(MBB, I, TII.get(ARM::tMOVr), DestReg).addReg(SrcReg);
287     else
288       AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::MOVr), DestReg)
289                                   .addReg(SrcReg)));
290   } else if (DestRC == ARM::SPRRegisterClass)
291     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FCPYS), DestReg)
292                    .addReg(SrcReg));
293   else if (DestRC == ARM::DPRRegisterClass)
294     AddDefaultPred(BuildMI(MBB, I, TII.get(ARM::FCPYD), DestReg)
295                    .addReg(SrcReg));
296   else
297     abort();
298 }
299
300 /// emitLoadConstPool - Emits a load from constpool to materialize the
301 /// specified immediate.
302 static void emitLoadConstPool(MachineBasicBlock &MBB,
303                               MachineBasicBlock::iterator &MBBI,
304                               unsigned DestReg, int Val,
305                               ARMCC::CondCodes Pred, unsigned PredReg,
306                               const TargetInstrInfo &TII, bool isThumb) {
307   MachineFunction &MF = *MBB.getParent();
308   MachineConstantPool *ConstantPool = MF.getConstantPool();
309   Constant *C = ConstantInt::get(Type::Int32Ty, Val);
310   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 2);
311   if (isThumb)
312     BuildMI(MBB, MBBI, TII.get(ARM::tLDRcp), DestReg).addConstantPoolIndex(Idx);
313   else
314     BuildMI(MBB, MBBI, TII.get(ARM::LDRcp), DestReg).addConstantPoolIndex(Idx)
315       .addReg(0).addImm(0).addImm((unsigned)Pred).addReg(PredReg);
316 }
317
318 void ARMRegisterInfo::reMaterialize(MachineBasicBlock &MBB,
319                                     MachineBasicBlock::iterator I,
320                                     unsigned DestReg,
321                                     const MachineInstr *Orig) const {
322   if (Orig->getOpcode() == ARM::MOVi2pieces) {
323     emitLoadConstPool(MBB, I, DestReg,
324                       Orig->getOperand(1).getImmedValue(),
325                       (ARMCC::CondCodes)Orig->getOperand(2).getImmedValue(),
326                       Orig->getOperand(3).getReg(),
327                       TII, false);
328     return;
329   }
330
331   MachineInstr *MI = Orig->clone();
332   MI->getOperand(0).setReg(DestReg);
333   MBB.insert(I, MI);
334 }
335
336 /// isLowRegister - Returns true if the register is low register r0-r7.
337 ///
338 static bool isLowRegister(unsigned Reg) {
339   using namespace ARM;
340   switch (Reg) {
341   case R0:  case R1:  case R2:  case R3:
342   case R4:  case R5:  case R6:  case R7:
343     return true;
344   default:
345     return false;
346   }
347 }
348
349 MachineInstr *ARMRegisterInfo::foldMemoryOperand(MachineInstr *MI,
350                                                  unsigned OpNum, int FI) const {
351   unsigned Opc = MI->getOpcode();
352   MachineInstr *NewMI = NULL;
353   switch (Opc) {
354   default: break;
355   case ARM::MOVr: {
356     if (MI->getOperand(4).getReg() == ARM::CPSR)
357       // If it is updating CPSR, then it cannot be foled.
358       break;
359     unsigned Pred = MI->getOperand(2).getImmedValue();
360     unsigned PredReg = MI->getOperand(3).getReg();
361     if (OpNum == 0) { // move -> store
362       unsigned SrcReg = MI->getOperand(1).getReg();
363       NewMI = BuildMI(TII.get(ARM::STR)).addReg(SrcReg).addFrameIndex(FI)
364         .addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
365     } else {          // move -> load
366       unsigned DstReg = MI->getOperand(0).getReg();
367       NewMI = BuildMI(TII.get(ARM::LDR), DstReg).addFrameIndex(FI).addReg(0)
368         .addImm(0).addImm(Pred).addReg(PredReg);
369     }
370     break;
371   }
372   case ARM::tMOVr: {
373     if (OpNum == 0) { // move -> store
374       unsigned SrcReg = MI->getOperand(1).getReg();
375       if (isPhysicalRegister(SrcReg) && !isLowRegister(SrcReg))
376         // tSpill cannot take a high register operand.
377         break;
378       NewMI = BuildMI(TII.get(ARM::tSpill)).addReg(SrcReg).addFrameIndex(FI)
379         .addImm(0);
380     } else {          // move -> load
381       unsigned DstReg = MI->getOperand(0).getReg();
382       if (isPhysicalRegister(DstReg) && !isLowRegister(DstReg))
383         // tRestore cannot target a high register operand.
384         break;
385       NewMI = BuildMI(TII.get(ARM::tRestore), DstReg).addFrameIndex(FI)
386         .addImm(0);
387     }
388     break;
389   }
390   case ARM::FCPYS: {
391     unsigned Pred = MI->getOperand(2).getImmedValue();
392     unsigned PredReg = MI->getOperand(3).getReg();
393     if (OpNum == 0) { // move -> store
394       unsigned SrcReg = MI->getOperand(1).getReg();
395       NewMI = BuildMI(TII.get(ARM::FSTS)).addReg(SrcReg).addFrameIndex(FI)
396         .addImm(0).addImm(Pred).addReg(PredReg);
397     } else {          // move -> load
398       unsigned DstReg = MI->getOperand(0).getReg();
399       NewMI = BuildMI(TII.get(ARM::FLDS), DstReg).addFrameIndex(FI)
400         .addImm(0).addImm(Pred).addReg(PredReg);
401     }
402     break;
403   }
404   case ARM::FCPYD: {
405     unsigned Pred = MI->getOperand(2).getImmedValue();
406     unsigned PredReg = MI->getOperand(3).getReg();
407     if (OpNum == 0) { // move -> store
408       unsigned SrcReg = MI->getOperand(1).getReg();
409       NewMI = BuildMI(TII.get(ARM::FSTD)).addReg(SrcReg).addFrameIndex(FI)
410         .addImm(0).addImm(Pred).addReg(PredReg);
411     } else {          // move -> load
412       unsigned DstReg = MI->getOperand(0).getReg();
413       NewMI = BuildMI(TII.get(ARM::FLDD), DstReg).addFrameIndex(FI)
414         .addImm(0).addImm(Pred).addReg(PredReg);
415     }
416     break;
417   }
418   }
419
420   if (NewMI)
421     NewMI->copyKillDeadInfo(MI);
422   return NewMI;
423 }
424
425 const unsigned*
426 ARMRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
427   static const unsigned CalleeSavedRegs[] = {
428     ARM::LR, ARM::R11, ARM::R10, ARM::R9, ARM::R8,
429     ARM::R7, ARM::R6,  ARM::R5,  ARM::R4,
430
431     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
432     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
433     0
434   };
435
436   static const unsigned DarwinCalleeSavedRegs[] = {
437     ARM::LR,  ARM::R7,  ARM::R6, ARM::R5, ARM::R4,
438     ARM::R11, ARM::R10, ARM::R9, ARM::R8,
439
440     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
441     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
442     0
443   };
444   return STI.isTargetDarwin() ? DarwinCalleeSavedRegs : CalleeSavedRegs;
445 }
446
447 const TargetRegisterClass* const *
448 ARMRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
449   static const TargetRegisterClass * const CalleeSavedRegClasses[] = {
450     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
451     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
452     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
453
454     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
455     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
456     0
457   };
458   return CalleeSavedRegClasses;
459 }
460
461 BitVector ARMRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
462   // FIXME: avoid re-calculating this everytime.
463   BitVector Reserved(getNumRegs());
464   Reserved.set(ARM::SP);
465   Reserved.set(ARM::PC);
466   if (STI.isTargetDarwin() || hasFP(MF))
467     Reserved.set(FramePtr);
468   // Some targets reserve R9.
469   if (STI.isR9Reserved())
470     Reserved.set(ARM::R9);
471   return Reserved;
472 }
473
474 bool
475 ARMRegisterInfo::isReservedReg(const MachineFunction &MF, unsigned Reg) const {
476   switch (Reg) {
477   default: break;
478   case ARM::SP:
479   case ARM::PC:
480     return true;
481   case ARM::R7:
482   case ARM::R11:
483     if (FramePtr == Reg && (STI.isTargetDarwin() || hasFP(MF)))
484       return true;
485     break;
486   case ARM::R9:
487     return STI.isR9Reserved();
488   }
489
490   return false;
491 }
492
493 bool
494 ARMRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
495   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
496   return ThumbRegScavenging || !AFI->isThumbFunction();
497 }
498
499 /// hasFP - Return true if the specified function should have a dedicated frame
500 /// pointer register.  This is true if the function has variable sized allocas
501 /// or if frame pointer elimination is disabled.
502 ///
503 bool ARMRegisterInfo::hasFP(const MachineFunction &MF) const {
504   return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
505 }
506
507 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
508 // not required, we reserve argument space for call sites in the function
509 // immediately on entry to the current function. This eliminates the need for
510 // add/sub sp brackets around call sites. Returns true if the call frame is
511 // included as part of the stack frame.
512 bool ARMRegisterInfo::hasReservedCallFrame(MachineFunction &MF) const {
513   const MachineFrameInfo *FFI = MF.getFrameInfo();
514   unsigned CFSize = FFI->getMaxCallFrameSize();
515   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
516   // It's not always a good idea to include the call frame as part of the
517   // stack frame. ARM (especially Thumb) has small immediate offset to
518   // address the stack frame. So a large call frame can cause poor codegen
519   // and may even makes it impossible to scavenge a register.
520   if (AFI->isThumbFunction()) {
521     if (CFSize >= ((1 << 8) - 1) * 4 / 2) // Half of imm8 * 4
522       return false;
523   } else {
524     if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
525       return false;
526   }
527   return !MF.getFrameInfo()->hasVarSizedObjects();
528 }
529
530 /// emitARMRegPlusImmediate - Emits a series of instructions to materialize
531 /// a destreg = basereg + immediate in ARM code.
532 static
533 void emitARMRegPlusImmediate(MachineBasicBlock &MBB,
534                              MachineBasicBlock::iterator &MBBI,
535                              unsigned DestReg, unsigned BaseReg, int NumBytes,
536                              ARMCC::CondCodes Pred, unsigned PredReg,
537                              const TargetInstrInfo &TII) {
538   bool isSub = NumBytes < 0;
539   if (isSub) NumBytes = -NumBytes;
540
541   while (NumBytes) {
542     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
543     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
544     assert(ThisVal && "Didn't extract field correctly");
545     
546     // We will handle these bits from offset, clear them.
547     NumBytes &= ~ThisVal;
548     
549     // Get the properly encoded SOImmVal field.
550     int SOImmVal = ARM_AM::getSOImmVal(ThisVal);
551     assert(SOImmVal != -1 && "Bit extraction didn't work?");
552     
553     // Build the new ADD / SUB.
554     BuildMI(MBB, MBBI, TII.get(isSub ? ARM::SUBri : ARM::ADDri), DestReg)
555       .addReg(BaseReg, false, false, true).addImm(SOImmVal)
556       .addImm((unsigned)Pred).addReg(PredReg).addReg(0);
557     BaseReg = DestReg;
558   }
559 }
560
561 /// calcNumMI - Returns the number of instructions required to materialize
562 /// the specific add / sub r, c instruction.
563 static unsigned calcNumMI(int Opc, int ExtraOpc, unsigned Bytes,
564                           unsigned NumBits, unsigned Scale) {
565   unsigned NumMIs = 0;
566   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
567
568   if (Opc == ARM::tADDrSPi) {
569     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
570     Bytes -= ThisVal;
571     NumMIs++;
572     NumBits = 8;
573     Scale = 1;  // Followed by a number of tADDi8.
574     Chunk = ((1 << NumBits) - 1) * Scale;
575   }
576
577   NumMIs += Bytes / Chunk;
578   if ((Bytes % Chunk) != 0)
579     NumMIs++;
580   if (ExtraOpc)
581     NumMIs++;
582   return NumMIs;
583 }
584
585 /// emitThumbRegPlusImmInReg - Emits a series of instructions to materialize
586 /// a destreg = basereg + immediate in Thumb code. Materialize the immediate
587 /// in a register using mov / mvn sequences or load the immediate from a
588 /// constpool entry.
589 static
590 void emitThumbRegPlusImmInReg(MachineBasicBlock &MBB,
591                                MachineBasicBlock::iterator &MBBI,
592                                unsigned DestReg, unsigned BaseReg,
593                                int NumBytes, bool CanChangeCC,
594                                const TargetInstrInfo &TII) {
595     bool isHigh = !isLowRegister(DestReg) ||
596                   (BaseReg != 0 && !isLowRegister(BaseReg));
597     bool isSub = false;
598     // Subtract doesn't have high register version. Load the negative value
599     // if either base or dest register is a high register. Also, if do not
600     // issue sub as part of the sequence if condition register is to be
601     // preserved.
602     if (NumBytes < 0 && !isHigh && CanChangeCC) {
603       isSub = true;
604       NumBytes = -NumBytes;
605     }
606     unsigned LdReg = DestReg;
607     if (DestReg == ARM::SP) {
608       assert(BaseReg == ARM::SP && "Unexpected!");
609       LdReg = ARM::R3;
610       BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::R12)
611         .addReg(ARM::R3, false, false, true);
612     }
613
614     if (NumBytes <= 255 && NumBytes >= 0)
615       BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), LdReg).addImm(NumBytes);
616     else if (NumBytes < 0 && NumBytes >= -255) {
617       BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), LdReg).addImm(NumBytes);
618       BuildMI(MBB, MBBI, TII.get(ARM::tNEG), LdReg)
619         .addReg(LdReg, false, false, true);
620     } else
621       emitLoadConstPool(MBB, MBBI, LdReg, NumBytes, ARMCC::AL, 0, TII, true);
622
623     // Emit add / sub.
624     int Opc = (isSub) ? ARM::tSUBrr : (isHigh ? ARM::tADDhirr : ARM::tADDrr);
625     const MachineInstrBuilder MIB = BuildMI(MBB, MBBI, TII.get(Opc), DestReg);
626     if (DestReg == ARM::SP || isSub)
627       MIB.addReg(BaseReg).addReg(LdReg, false, false, true);
628     else
629       MIB.addReg(LdReg).addReg(BaseReg, false, false, true);
630     if (DestReg == ARM::SP)
631       BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::R3)
632         .addReg(ARM::R12, false, false, true);
633 }
634
635 /// emitThumbRegPlusImmediate - Emits a series of instructions to materialize
636 /// a destreg = basereg + immediate in Thumb code.
637 static
638 void emitThumbRegPlusImmediate(MachineBasicBlock &MBB,
639                                MachineBasicBlock::iterator &MBBI,
640                                unsigned DestReg, unsigned BaseReg,
641                                int NumBytes, const TargetInstrInfo &TII) {
642   bool isSub = NumBytes < 0;
643   unsigned Bytes = (unsigned)NumBytes;
644   if (isSub) Bytes = -NumBytes;
645   bool isMul4 = (Bytes & 3) == 0;
646   bool isTwoAddr = false;
647   bool DstNotEqBase = false;
648   unsigned NumBits = 1;
649   unsigned Scale = 1;
650   int Opc = 0;
651   int ExtraOpc = 0;
652
653   if (DestReg == BaseReg && BaseReg == ARM::SP) {
654     assert(isMul4 && "Thumb sp inc / dec size must be multiple of 4!");
655     NumBits = 7;
656     Scale = 4;
657     Opc = isSub ? ARM::tSUBspi : ARM::tADDspi;
658     isTwoAddr = true;
659   } else if (!isSub && BaseReg == ARM::SP) {
660     // r1 = add sp, 403
661     // =>
662     // r1 = add sp, 100 * 4
663     // r1 = add r1, 3
664     if (!isMul4) {
665       Bytes &= ~3;
666       ExtraOpc = ARM::tADDi3;
667     }
668     NumBits = 8;
669     Scale = 4;
670     Opc = ARM::tADDrSPi;
671   } else {
672     // sp = sub sp, c
673     // r1 = sub sp, c
674     // r8 = sub sp, c
675     if (DestReg != BaseReg)
676       DstNotEqBase = true;
677     NumBits = 8;
678     Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
679     isTwoAddr = true;
680   }
681
682   unsigned NumMIs = calcNumMI(Opc, ExtraOpc, Bytes, NumBits, Scale);
683   unsigned Threshold = (DestReg == ARM::SP) ? 3 : 2;
684   if (NumMIs > Threshold) {
685     // This will expand into too many instructions. Load the immediate from a
686     // constpool entry.
687     emitThumbRegPlusImmInReg(MBB, MBBI, DestReg, BaseReg, NumBytes, true, TII);
688     return;
689   }
690
691   if (DstNotEqBase) {
692     if (isLowRegister(DestReg) && isLowRegister(BaseReg)) {
693       // If both are low registers, emit DestReg = add BaseReg, max(Imm, 7)
694       unsigned Chunk = (1 << 3) - 1;
695       unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
696       Bytes -= ThisVal;
697       BuildMI(MBB, MBBI, TII.get(isSub ? ARM::tSUBi3 : ARM::tADDi3), DestReg)
698         .addReg(BaseReg, false, false, true).addImm(ThisVal);
699     } else {
700       BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), DestReg)
701         .addReg(BaseReg, false, false, true);
702     }
703     BaseReg = DestReg;
704   }
705
706   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
707   while (Bytes) {
708     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
709     Bytes -= ThisVal;
710     ThisVal /= Scale;
711     // Build the new tADD / tSUB.
712     if (isTwoAddr)
713       BuildMI(MBB, MBBI, TII.get(Opc), DestReg).addReg(DestReg).addImm(ThisVal);
714     else {
715       bool isKill = BaseReg != ARM::SP;
716       BuildMI(MBB, MBBI, TII.get(Opc), DestReg)
717         .addReg(BaseReg, false, false, isKill).addImm(ThisVal);
718       BaseReg = DestReg;
719
720       if (Opc == ARM::tADDrSPi) {
721         // r4 = add sp, imm
722         // r4 = add r4, imm
723         // ...
724         NumBits = 8;
725         Scale = 1;
726         Chunk = ((1 << NumBits) - 1) * Scale;
727         Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
728         isTwoAddr = true;
729       }
730     }
731   }
732
733   if (ExtraOpc)
734     BuildMI(MBB, MBBI, TII.get(ExtraOpc), DestReg)
735       .addReg(DestReg, false, false, true)
736       .addImm(((unsigned)NumBytes) & 3);
737 }
738
739 static
740 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
741                   int NumBytes, ARMCC::CondCodes Pred, unsigned PredReg,
742                   bool isThumb, const TargetInstrInfo &TII) {
743   if (isThumb)
744     emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes, TII);
745   else
746     emitARMRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes,
747                             Pred, PredReg, TII);
748 }
749
750 void ARMRegisterInfo::
751 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
752                               MachineBasicBlock::iterator I) const {
753   if (!hasReservedCallFrame(MF)) {
754     // If we have alloca, convert as follows:
755     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
756     // ADJCALLSTACKUP   -> add, sp, sp, amount
757     MachineInstr *Old = I;
758     unsigned Amount = Old->getOperand(0).getImmedValue();
759     if (Amount != 0) {
760       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
761       // We need to keep the stack aligned properly.  To do this, we round the
762       // amount of space needed for the outgoing arguments up to the next
763       // alignment boundary.
764       unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
765       Amount = (Amount+Align-1)/Align*Align;
766
767       // Replace the pseudo instruction with a new instruction...
768       unsigned Opc = Old->getOpcode();
769       bool isThumb = AFI->isThumbFunction();
770       ARMCC::CondCodes Pred = isThumb
771         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(1).getImmedValue();
772       unsigned PredReg = isThumb ? 0 : Old->getOperand(2).getReg();
773       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
774         emitSPUpdate(MBB, I, -Amount, Pred, PredReg, isThumb, TII);
775       } else {
776         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
777         emitSPUpdate(MBB, I, Amount, Pred, PredReg, isThumb, TII);
778       }
779     }
780   }
781   MBB.erase(I);
782 }
783
784 /// emitThumbConstant - Emit a series of instructions to materialize a
785 /// constant.
786 static void emitThumbConstant(MachineBasicBlock &MBB,
787                               MachineBasicBlock::iterator &MBBI,
788                               unsigned DestReg, int Imm,
789                               const TargetInstrInfo &TII) {
790   bool isSub = Imm < 0;
791   if (isSub) Imm = -Imm;
792
793   int Chunk = (1 << 8) - 1;
794   int ThisVal = (Imm > Chunk) ? Chunk : Imm;
795   Imm -= ThisVal;
796   BuildMI(MBB, MBBI, TII.get(ARM::tMOVi8), DestReg).addImm(ThisVal);
797   if (Imm > 0) 
798     emitThumbRegPlusImmediate(MBB, MBBI, DestReg, DestReg, Imm, TII);
799   if (isSub)
800     BuildMI(MBB, MBBI, TII.get(ARM::tNEG), DestReg)
801       .addReg(DestReg, false, false, true);
802 }
803
804 /// findScratchRegister - Find a 'free' ARM register. If register scavenger
805 /// is not being used, R12 is available. Otherwise, try for a call-clobbered
806 /// register first and then a spilled callee-saved register if that fails.
807 static
808 unsigned findScratchRegister(RegScavenger *RS, const TargetRegisterClass *RC,
809                              ARMFunctionInfo *AFI) {
810   unsigned Reg = RS ? RS->FindUnusedReg(RC, true) : (unsigned) ARM::R12;
811   if (Reg == 0)
812     // Try a already spilled CS register.
813     Reg = RS->FindUnusedReg(RC, AFI->getSpilledCSRegisters());
814
815   return Reg;
816 }
817
818 void ARMRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
819                                           int SPAdj, RegScavenger *RS) const{
820   unsigned i = 0;
821   MachineInstr &MI = *II;
822   MachineBasicBlock &MBB = *MI.getParent();
823   MachineFunction &MF = *MBB.getParent();
824   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
825   bool isThumb = AFI->isThumbFunction();
826
827   while (!MI.getOperand(i).isFrameIndex()) {
828     ++i;
829     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
830   }
831   
832   unsigned FrameReg = ARM::SP;
833   int FrameIndex = MI.getOperand(i).getFrameIndex();
834   int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) + 
835                MF.getFrameInfo()->getStackSize() + SPAdj;
836
837   if (AFI->isGPRCalleeSavedArea1Frame(FrameIndex))
838     Offset -= AFI->getGPRCalleeSavedArea1Offset();
839   else if (AFI->isGPRCalleeSavedArea2Frame(FrameIndex))
840     Offset -= AFI->getGPRCalleeSavedArea2Offset();
841   else if (AFI->isDPRCalleeSavedAreaFrame(FrameIndex))
842     Offset -= AFI->getDPRCalleeSavedAreaOffset();
843   else if (hasFP(MF)) {
844     assert(SPAdj == 0 && "Unexpected");
845     // There is alloca()'s in this function, must reference off the frame
846     // pointer instead.
847     FrameReg = getFrameRegister(MF);
848     Offset -= AFI->getFramePtrSpillOffset();
849   }
850
851   unsigned Opcode = MI.getOpcode();
852   const TargetInstrDescriptor &Desc = TII.get(Opcode);
853   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
854   bool isSub = false;
855
856   if (Opcode == ARM::ADDri) {
857     Offset += MI.getOperand(i+1).getImm();
858     if (Offset == 0) {
859       // Turn it into a move.
860       MI.setInstrDescriptor(TII.get(ARM::MOVr));
861       MI.getOperand(i).ChangeToRegister(FrameReg, false);
862       MI.RemoveOperand(i+1);
863       return;
864     } else if (Offset < 0) {
865       Offset = -Offset;
866       isSub = true;
867       MI.setInstrDescriptor(TII.get(ARM::SUBri));
868     }
869
870     // Common case: small offset, fits into instruction.
871     int ImmedOffset = ARM_AM::getSOImmVal(Offset);
872     if (ImmedOffset != -1) {
873       // Replace the FrameIndex with sp / fp
874       MI.getOperand(i).ChangeToRegister(FrameReg, false);
875       MI.getOperand(i+1).ChangeToImmediate(ImmedOffset);
876       return;
877     }
878     
879     // Otherwise, we fallback to common code below to form the imm offset with
880     // a sequence of ADDri instructions.  First though, pull as much of the imm
881     // into this ADDri as possible.
882     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
883     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
884     
885     // We will handle these bits from offset, clear them.
886     Offset &= ~ThisImmVal;
887     
888     // Get the properly encoded SOImmVal field.
889     int ThisSOImmVal = ARM_AM::getSOImmVal(ThisImmVal);
890     assert(ThisSOImmVal != -1 && "Bit extraction didn't work?");    
891     MI.getOperand(i+1).ChangeToImmediate(ThisSOImmVal);
892   } else if (Opcode == ARM::tADDrSPi) {
893     Offset += MI.getOperand(i+1).getImm();
894
895     // Can't use tADDrSPi if it's based off the frame pointer.
896     unsigned NumBits = 0;
897     unsigned Scale = 1;
898     if (FrameReg != ARM::SP) {
899       Opcode = ARM::tADDi3;
900       MI.setInstrDescriptor(TII.get(ARM::tADDi3));
901       NumBits = 3;
902     } else {
903       NumBits = 8;
904       Scale = 4;
905       assert((Offset & 3) == 0 &&
906              "Thumb add/sub sp, #imm immediate must be multiple of 4!");
907     }
908
909     if (Offset == 0) {
910       // Turn it into a move.
911       MI.setInstrDescriptor(TII.get(ARM::tMOVr));
912       MI.getOperand(i).ChangeToRegister(FrameReg, false);
913       MI.RemoveOperand(i+1);
914       return;
915     }
916
917     // Common case: small offset, fits into instruction.
918     unsigned Mask = (1 << NumBits) - 1;
919     if (((Offset / Scale) & ~Mask) == 0) {
920       // Replace the FrameIndex with sp / fp
921       MI.getOperand(i).ChangeToRegister(FrameReg, false);
922       MI.getOperand(i+1).ChangeToImmediate(Offset / Scale);
923       return;
924     }
925
926     unsigned DestReg = MI.getOperand(0).getReg();
927     unsigned Bytes = (Offset > 0) ? Offset : -Offset;
928     unsigned NumMIs = calcNumMI(Opcode, 0, Bytes, NumBits, Scale);
929     // MI would expand into a large number of instructions. Don't try to
930     // simplify the immediate.
931     if (NumMIs > 2) {
932       emitThumbRegPlusImmediate(MBB, II, DestReg, FrameReg, Offset, TII);
933       MBB.erase(II);
934       return;
935     }
936
937     if (Offset > 0) {
938       // Translate r0 = add sp, imm to
939       // r0 = add sp, 255*4
940       // r0 = add r0, (imm - 255*4)
941       MI.getOperand(i).ChangeToRegister(FrameReg, false);
942       MI.getOperand(i+1).ChangeToImmediate(Mask);
943       Offset = (Offset - Mask * Scale);
944       MachineBasicBlock::iterator NII = next(II);
945       emitThumbRegPlusImmediate(MBB, NII, DestReg, DestReg, Offset, TII);
946     } else {
947       // Translate r0 = add sp, -imm to
948       // r0 = -imm (this is then translated into a series of instructons)
949       // r0 = add r0, sp
950       emitThumbConstant(MBB, II, DestReg, Offset, TII);
951       MI.setInstrDescriptor(TII.get(ARM::tADDhirr));
952       MI.getOperand(i).ChangeToRegister(DestReg, false, false, true);
953       MI.getOperand(i+1).ChangeToRegister(FrameReg, false);
954     }
955     return;
956   } else {
957     unsigned ImmIdx = 0;
958     int InstrOffs = 0;
959     unsigned NumBits = 0;
960     unsigned Scale = 1;
961     switch (AddrMode) {
962     case ARMII::AddrMode2: {
963       ImmIdx = i+2;
964       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
965       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
966         InstrOffs *= -1;
967       NumBits = 12;
968       break;
969     }
970     case ARMII::AddrMode3: {
971       ImmIdx = i+2;
972       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
973       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
974         InstrOffs *= -1;
975       NumBits = 8;
976       break;
977     }
978     case ARMII::AddrMode5: {
979       ImmIdx = i+1;
980       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
981       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
982         InstrOffs *= -1;
983       NumBits = 8;
984       Scale = 4;
985       break;
986     }
987     case ARMII::AddrModeTs: {
988       ImmIdx = i+1;
989       InstrOffs = MI.getOperand(ImmIdx).getImm();
990       NumBits = (FrameReg == ARM::SP) ? 8 : 5;
991       Scale = 4;
992       break;
993     }
994     default:
995       assert(0 && "Unsupported addressing mode!");
996       abort();
997       break;
998     }
999
1000     Offset += InstrOffs * Scale;
1001     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1002     if (Offset < 0 && !isThumb) {
1003       Offset = -Offset;
1004       isSub = true;
1005     }
1006
1007     // Common case: small offset, fits into instruction.
1008     MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1009     int ImmedOffset = Offset / Scale;
1010     unsigned Mask = (1 << NumBits) - 1;
1011     if ((unsigned)Offset <= Mask * Scale) {
1012       // Replace the FrameIndex with sp
1013       MI.getOperand(i).ChangeToRegister(FrameReg, false);
1014       if (isSub)
1015         ImmedOffset |= 1 << NumBits;
1016       ImmOp.ChangeToImmediate(ImmedOffset);
1017       return;
1018     }
1019
1020     bool isThumSpillRestore = Opcode == ARM::tRestore || Opcode == ARM::tSpill;
1021     if (AddrMode == ARMII::AddrModeTs) {
1022       // Thumb tLDRspi, tSTRspi. These will change to instructions that use
1023       // a different base register.
1024       NumBits = 5;
1025       Mask = (1 << NumBits) - 1;
1026     }
1027     // If this is a thumb spill / restore, we will be using a constpool load to
1028     // materialize the offset.
1029     if (AddrMode == ARMII::AddrModeTs && isThumSpillRestore)
1030       ImmOp.ChangeToImmediate(0);
1031     else {
1032       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1033       ImmedOffset = ImmedOffset & Mask;
1034       if (isSub)
1035         ImmedOffset |= 1 << NumBits;
1036       ImmOp.ChangeToImmediate(ImmedOffset);
1037       Offset &= ~(Mask*Scale);
1038     }
1039   }
1040   
1041   // If we get here, the immediate doesn't fit into the instruction.  We folded
1042   // as much as possible above, handle the rest, providing a register that is
1043   // SP+LargeImm.
1044   assert(Offset && "This code isn't needed if offset already handled!");
1045
1046   if (isThumb) {
1047     if (TII.isLoad(Opcode)) {
1048       // Use the destination register to materialize sp + offset.
1049       unsigned TmpReg = MI.getOperand(0).getReg();
1050       bool UseRR = false;
1051       if (Opcode == ARM::tRestore) {
1052         if (FrameReg == ARM::SP)
1053           emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,Offset,false,TII);
1054         else {
1055           emitLoadConstPool(MBB, II, TmpReg, Offset, ARMCC::AL, 0, TII, true);
1056           UseRR = true;
1057         }
1058       } else
1059         emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII);
1060       MI.setInstrDescriptor(TII.get(ARM::tLDR));
1061       MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
1062       if (UseRR)
1063         MI.addRegOperand(FrameReg, false);  // Use [reg, reg] addrmode.
1064       else
1065         MI.addRegOperand(0, false); // tLDR has an extra register operand.
1066     } else if (TII.isStore(Opcode)) {
1067       // FIXME! This is horrific!!! We need register scavenging.
1068       // Our temporary workaround has marked r3 unavailable. Of course, r3 is
1069       // also a ABI register so it's possible that is is the register that is
1070       // being storing here. If that's the case, we do the following:
1071       // r12 = r2
1072       // Use r2 to materialize sp + offset
1073       // str r3, r2
1074       // r2 = r12
1075       unsigned ValReg = MI.getOperand(0).getReg();
1076       unsigned TmpReg = ARM::R3;
1077       bool UseRR = false;
1078       if (ValReg == ARM::R3) {
1079         BuildMI(MBB, II, TII.get(ARM::tMOVr), ARM::R12)
1080           .addReg(ARM::R2, false, false, true);
1081         TmpReg = ARM::R2;
1082       }
1083       if (TmpReg == ARM::R3 && AFI->isR3LiveIn())
1084         BuildMI(MBB, II, TII.get(ARM::tMOVr), ARM::R12)
1085           .addReg(ARM::R3, false, false, true);
1086       if (Opcode == ARM::tSpill) {
1087         if (FrameReg == ARM::SP)
1088           emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,Offset,false,TII);
1089         else {
1090           emitLoadConstPool(MBB, II, TmpReg, Offset, ARMCC::AL, 0, TII, true);
1091           UseRR = true;
1092         }
1093       } else
1094         emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII);
1095       MI.setInstrDescriptor(TII.get(ARM::tSTR));
1096       MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
1097       if (UseRR)
1098         MI.addRegOperand(FrameReg, false);  // Use [reg, reg] addrmode.
1099       else
1100         MI.addRegOperand(0, false); // tSTR has an extra register operand.
1101
1102       MachineBasicBlock::iterator NII = next(II);
1103       if (ValReg == ARM::R3)
1104         BuildMI(MBB, NII, TII.get(ARM::tMOVr), ARM::R2)
1105           .addReg(ARM::R12, false, false, true);
1106       if (TmpReg == ARM::R3 && AFI->isR3LiveIn())
1107         BuildMI(MBB, NII, TII.get(ARM::tMOVr), ARM::R3)
1108           .addReg(ARM::R12, false, false, true);
1109     } else
1110       assert(false && "Unexpected opcode!");
1111   } else {
1112     // Insert a set of r12 with the full address: r12 = sp + offset
1113     // If the offset we have is too large to fit into the instruction, we need
1114     // to form it with a series of ADDri's.  Do this by taking 8-bit chunks
1115     // out of 'Offset'.
1116     unsigned ScratchReg = findScratchRegister(RS, &ARM::GPRRegClass, AFI);
1117     if (ScratchReg == 0)
1118       // No register is "free". Scavenge a register.
1119       ScratchReg = RS->scavengeRegister(&ARM::GPRRegClass, II, SPAdj);
1120     int PIdx = MI.findFirstPredOperandIdx();
1121     ARMCC::CondCodes Pred = (PIdx == -1)
1122       ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImmedValue();
1123     unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
1124     emitARMRegPlusImmediate(MBB, II, ScratchReg, FrameReg,
1125                             isSub ? -Offset : Offset, Pred, PredReg, TII);
1126     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
1127   }
1128 }
1129
1130 static unsigned estimateStackSize(MachineFunction &MF, MachineFrameInfo *MFI) {
1131   const MachineFrameInfo *FFI = MF.getFrameInfo();
1132   int Offset = 0;
1133   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
1134     int FixedOff = -FFI->getObjectOffset(i);
1135     if (FixedOff > Offset) Offset = FixedOff;
1136   }
1137   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
1138     Offset += FFI->getObjectSize(i);
1139     unsigned Align = FFI->getObjectAlignment(i);
1140     // Adjust to alignment boundary
1141     Offset = (Offset+Align-1)/Align*Align;
1142   }
1143   return (unsigned)Offset;
1144 }
1145
1146 void
1147 ARMRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1148                                                       RegScavenger *RS) const {
1149   // This tells PEI to spill the FP as if it is any other callee-save register
1150   // to take advantage the eliminateFrameIndex machinery. This also ensures it
1151   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
1152   // to combine multiple loads / stores.
1153   bool CanEliminateFrame = true;
1154   bool CS1Spilled = false;
1155   bool LRSpilled = false;
1156   unsigned NumGPRSpills = 0;
1157   SmallVector<unsigned, 4> UnspilledCS1GPRs;
1158   SmallVector<unsigned, 4> UnspilledCS2GPRs;
1159   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1160
1161   // Don't spill FP if the frame can be eliminated. This is determined
1162   // by scanning the callee-save registers to see if any is used.
1163   const unsigned *CSRegs = getCalleeSavedRegs();
1164   const TargetRegisterClass* const *CSRegClasses = getCalleeSavedRegClasses();
1165   for (unsigned i = 0; CSRegs[i]; ++i) {
1166     unsigned Reg = CSRegs[i];
1167     bool Spilled = false;
1168     if (MF.isPhysRegUsed(Reg)) {
1169       AFI->setCSRegisterIsSpilled(Reg);
1170       Spilled = true;
1171       CanEliminateFrame = false;
1172     } else {
1173       // Check alias registers too.
1174       for (const unsigned *Aliases = getAliasSet(Reg); *Aliases; ++Aliases) {
1175         if (MF.isPhysRegUsed(*Aliases)) {
1176           Spilled = true;
1177           CanEliminateFrame = false;
1178         }
1179       }
1180     }
1181
1182     if (CSRegClasses[i] == &ARM::GPRRegClass) {
1183       if (Spilled) {
1184         NumGPRSpills++;
1185
1186         if (!STI.isTargetDarwin()) {
1187           if (Reg == ARM::LR)
1188             LRSpilled = true;
1189           CS1Spilled = true;
1190           continue;
1191         }
1192
1193         // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
1194         switch (Reg) {
1195         case ARM::LR:
1196           LRSpilled = true;
1197           // Fallthrough
1198         case ARM::R4:
1199         case ARM::R5:
1200         case ARM::R6:
1201         case ARM::R7:
1202           CS1Spilled = true;
1203           break;
1204         default:
1205           break;
1206         }
1207       } else { 
1208         if (!STI.isTargetDarwin()) {
1209           UnspilledCS1GPRs.push_back(Reg);
1210           continue;
1211         }
1212
1213         switch (Reg) {
1214         case ARM::R4:
1215         case ARM::R5:
1216         case ARM::R6:
1217         case ARM::R7:
1218         case ARM::LR:
1219           UnspilledCS1GPRs.push_back(Reg);
1220           break;
1221         default:
1222           UnspilledCS2GPRs.push_back(Reg);
1223           break;
1224         }
1225       }
1226     }
1227   }
1228
1229   bool ForceLRSpill = false;
1230   if (!LRSpilled && AFI->isThumbFunction()) {
1231     unsigned FnSize = ARM::GetFunctionSize(MF);
1232     // Force LR to be spilled if the Thumb function size is > 2048. This enables
1233     // use of BL to implement far jump. If it turns out that it's not needed
1234     // then the branch fix up path will undo it.
1235     if (FnSize >= (1 << 11)) {
1236       CanEliminateFrame = false;
1237       ForceLRSpill = true;
1238     }
1239   }
1240
1241   bool ExtraCSSpill = false;
1242   if (!CanEliminateFrame || hasFP(MF)) {
1243     AFI->setHasStackFrame(true);
1244
1245     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1246     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1247     if (!LRSpilled && CS1Spilled) {
1248       MF.setPhysRegUsed(ARM::LR);
1249       AFI->setCSRegisterIsSpilled(ARM::LR);
1250       NumGPRSpills++;
1251       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
1252                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
1253       ForceLRSpill = false;
1254       ExtraCSSpill = true;
1255     }
1256
1257     // Darwin ABI requires FP to point to the stack slot that contains the
1258     // previous FP.
1259     if (STI.isTargetDarwin() || hasFP(MF)) {
1260       MF.setPhysRegUsed(FramePtr);
1261       NumGPRSpills++;
1262     }
1263
1264     // If stack and double are 8-byte aligned and we are spilling an odd number
1265     // of GPRs. Spill one extra callee save GPR so we won't have to pad between
1266     // the integer and double callee save areas.
1267     unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1268     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1269       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1270         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
1271           unsigned Reg = UnspilledCS1GPRs[i];
1272           // Don't spiil high register if the function is thumb
1273           if (!AFI->isThumbFunction() || isLowRegister(Reg) || Reg == ARM::LR) {
1274             MF.setPhysRegUsed(Reg);
1275             AFI->setCSRegisterIsSpilled(Reg);
1276             if (!isReservedReg(MF, Reg))
1277               ExtraCSSpill = true;
1278             break;
1279           }
1280         }
1281       } else if (!UnspilledCS2GPRs.empty() &&
1282                  !AFI->isThumbFunction()) {
1283         unsigned Reg = UnspilledCS2GPRs.front();
1284         MF.setPhysRegUsed(Reg);
1285         AFI->setCSRegisterIsSpilled(Reg);
1286         if (!isReservedReg(MF, Reg))
1287           ExtraCSSpill = true;
1288       }
1289     }
1290
1291     // Estimate if we might need to scavenge a register at some point in order
1292     // to materialize a stack offset. If so, either spill one additiona
1293     // callee-saved register or reserve a special spill slot to facilitate
1294     // register scavenging.
1295     if (RS && !ExtraCSSpill && !AFI->isThumbFunction()) {
1296       MachineFrameInfo  *MFI = MF.getFrameInfo();
1297       unsigned Size = estimateStackSize(MF, MFI);
1298       unsigned Limit = (1 << 12) - 1;
1299       for (MachineFunction::iterator BB = MF.begin(),E = MF.end();BB != E; ++BB)
1300         for (MachineBasicBlock::iterator I= BB->begin(); I != BB->end(); ++I) {
1301           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1302             if (I->getOperand(i).isFrameIndex()) {
1303               unsigned Opcode = I->getOpcode();
1304               const TargetInstrDescriptor &Desc = TII.get(Opcode);
1305               unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1306               if (AddrMode == ARMII::AddrMode3) {
1307                 Limit = (1 << 8) - 1;
1308                 goto DoneEstimating;
1309               } else if (AddrMode == ARMII::AddrMode5) {
1310                 unsigned ThisLimit = ((1 << 8) - 1) * 4;
1311                 if (ThisLimit < Limit)
1312                   Limit = ThisLimit;
1313               }
1314             }
1315         }
1316     DoneEstimating:
1317       if (Size >= Limit) {
1318         // If any non-reserved CS register isn't spilled, just spill one or two
1319         // extra. That should take care of it!
1320         unsigned NumExtras = TargetAlign / 4;
1321         SmallVector<unsigned, 2> Extras;
1322         while (NumExtras && !UnspilledCS1GPRs.empty()) {
1323           unsigned Reg = UnspilledCS1GPRs.back();
1324           UnspilledCS1GPRs.pop_back();
1325           if (!isReservedReg(MF, Reg)) {
1326             Extras.push_back(Reg);
1327             NumExtras--;
1328           }
1329         }
1330         while (NumExtras && !UnspilledCS2GPRs.empty()) {
1331           unsigned Reg = UnspilledCS2GPRs.back();
1332           UnspilledCS2GPRs.pop_back();
1333           if (!isReservedReg(MF, Reg)) {
1334             Extras.push_back(Reg);
1335             NumExtras--;
1336           }
1337         }
1338         if (Extras.size() && NumExtras == 0) {
1339           for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
1340             MF.setPhysRegUsed(Extras[i]);
1341             AFI->setCSRegisterIsSpilled(Extras[i]);
1342           }
1343         } else {
1344           // Reserve a slot closest to SP or frame pointer.
1345           const TargetRegisterClass *RC = &ARM::GPRRegClass;
1346           RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
1347                                                            RC->getAlignment()));
1348         }
1349       }
1350     }
1351   }
1352
1353   if (ForceLRSpill) {
1354     MF.setPhysRegUsed(ARM::LR);
1355     AFI->setCSRegisterIsSpilled(ARM::LR);
1356     AFI->setLRIsSpilledForFarJump(true);
1357   }
1358 }
1359
1360 /// Move iterator pass the next bunch of callee save load / store ops for
1361 /// the particular spill area (1: integer area 1, 2: integer area 2,
1362 /// 3: fp area, 0: don't care).
1363 static void movePastCSLoadStoreOps(MachineBasicBlock &MBB,
1364                                    MachineBasicBlock::iterator &MBBI,
1365                                    int Opc, unsigned Area,
1366                                    const ARMSubtarget &STI) {
1367   while (MBBI != MBB.end() &&
1368          MBBI->getOpcode() == Opc && MBBI->getOperand(1).isFrameIndex()) {
1369     if (Area != 0) {
1370       bool Done = false;
1371       unsigned Category = 0;
1372       switch (MBBI->getOperand(0).getReg()) {
1373       case ARM::R4:  case ARM::R5:  case ARM::R6: case ARM::R7:
1374       case ARM::LR:
1375         Category = 1;
1376         break;
1377       case ARM::R8:  case ARM::R9:  case ARM::R10: case ARM::R11:
1378         Category = STI.isTargetDarwin() ? 2 : 1;
1379         break;
1380       case ARM::D8:  case ARM::D9:  case ARM::D10: case ARM::D11:
1381       case ARM::D12: case ARM::D13: case ARM::D14: case ARM::D15:
1382         Category = 3;
1383         break;
1384       default:
1385         Done = true;
1386         break;
1387       }
1388       if (Done || Category != Area)
1389         break;
1390     }
1391
1392     ++MBBI;
1393   }
1394 }
1395
1396 void ARMRegisterInfo::emitPrologue(MachineFunction &MF) const {
1397   MachineBasicBlock &MBB = MF.front();
1398   MachineBasicBlock::iterator MBBI = MBB.begin();
1399   MachineFrameInfo  *MFI = MF.getFrameInfo();
1400   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1401   bool isThumb = AFI->isThumbFunction();
1402   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1403   unsigned NumBytes = MFI->getStackSize();
1404   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1405
1406   if (isThumb) {
1407     // Check if R3 is live in. It might have to be used as a scratch register.
1408     for (MachineFunction::livein_iterator I=MF.livein_begin(),E=MF.livein_end();
1409          I != E; ++I) {
1410       if ((*I).first == ARM::R3) {
1411         AFI->setR3IsLiveIn(true);
1412         break;
1413       }
1414     }
1415
1416     // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
1417     NumBytes = (NumBytes + 3) & ~3;
1418     MFI->setStackSize(NumBytes);
1419   }
1420
1421   // Determine the sizes of each callee-save spill areas and record which frame
1422   // belongs to which callee-save spill areas.
1423   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
1424   int FramePtrSpillFI = 0;
1425
1426   if (VARegSaveSize)
1427     emitSPUpdate(MBB, MBBI, -VARegSaveSize, ARMCC::AL, 0, isThumb, TII);
1428
1429   if (!AFI->hasStackFrame()) {
1430     if (NumBytes != 0)
1431       emitSPUpdate(MBB, MBBI, -NumBytes, ARMCC::AL, 0, isThumb, TII);
1432     return;
1433   }
1434
1435   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1436     unsigned Reg = CSI[i].getReg();
1437     int FI = CSI[i].getFrameIdx();
1438     switch (Reg) {
1439     case ARM::R4:
1440     case ARM::R5:
1441     case ARM::R6:
1442     case ARM::R7:
1443     case ARM::LR:
1444       if (Reg == FramePtr)
1445         FramePtrSpillFI = FI;
1446       AFI->addGPRCalleeSavedArea1Frame(FI);
1447       GPRCS1Size += 4;
1448       break;
1449     case ARM::R8:
1450     case ARM::R9:
1451     case ARM::R10:
1452     case ARM::R11:
1453       if (Reg == FramePtr)
1454         FramePtrSpillFI = FI;
1455       if (STI.isTargetDarwin()) {
1456         AFI->addGPRCalleeSavedArea2Frame(FI);
1457         GPRCS2Size += 4;
1458       } else {
1459         AFI->addGPRCalleeSavedArea1Frame(FI);
1460         GPRCS1Size += 4;
1461       }
1462       break;
1463     default:
1464       AFI->addDPRCalleeSavedAreaFrame(FI);
1465       DPRCSSize += 8;
1466     }
1467   }
1468
1469   if (!isThumb) {
1470     // Build the new SUBri to adjust SP for integer callee-save spill area 1.
1471     emitSPUpdate(MBB, MBBI, -GPRCS1Size, ARMCC::AL, 0, isThumb, TII);
1472     movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, 1, STI);
1473   } else if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH)
1474     ++MBBI;
1475
1476   // Darwin ABI requires FP to point to the stack slot that contains the
1477   // previous FP.
1478   if (STI.isTargetDarwin() || hasFP(MF)) {
1479     MachineInstrBuilder MIB =
1480       BuildMI(MBB, MBBI, TII.get(isThumb ? ARM::tADDrSPi : ARM::ADDri),FramePtr)
1481       .addFrameIndex(FramePtrSpillFI).addImm(0);
1482     if (!isThumb) AddDefaultCC(AddDefaultPred(MIB));
1483   }
1484
1485   if (!isThumb) {
1486     // Build the new SUBri to adjust SP for integer callee-save spill area 2.
1487     emitSPUpdate(MBB, MBBI, -GPRCS2Size, ARMCC::AL, 0, false, TII);
1488
1489     // Build the new SUBri to adjust SP for FP callee-save spill area.
1490     movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, 2, STI);
1491     emitSPUpdate(MBB, MBBI, -DPRCSSize, ARMCC::AL, 0, false, TII);
1492   }
1493
1494   // Determine starting offsets of spill areas.
1495   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
1496   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
1497   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
1498   AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) + NumBytes);
1499   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
1500   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
1501   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
1502   
1503   NumBytes = DPRCSOffset;
1504   if (NumBytes) {
1505     // Insert it after all the callee-save spills.
1506     if (!isThumb)
1507       movePastCSLoadStoreOps(MBB, MBBI, ARM::FSTD, 3, STI);
1508     emitSPUpdate(MBB, MBBI, -NumBytes, ARMCC::AL, 0, isThumb, TII);
1509   }
1510
1511   if(STI.isTargetELF() && hasFP(MF)) {
1512     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
1513                              AFI->getFramePtrSpillOffset());
1514   }
1515
1516   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
1517   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
1518   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
1519 }
1520
1521 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
1522   for (unsigned i = 0; CSRegs[i]; ++i)
1523     if (Reg == CSRegs[i])
1524       return true;
1525   return false;
1526 }
1527
1528 static bool isCSRestore(MachineInstr *MI, const unsigned *CSRegs) {
1529   return ((MI->getOpcode() == ARM::FLDD ||
1530            MI->getOpcode() == ARM::LDR  ||
1531            MI->getOpcode() == ARM::tRestore) &&
1532           MI->getOperand(1).isFrameIndex() &&
1533           isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs));
1534 }
1535
1536 void ARMRegisterInfo::emitEpilogue(MachineFunction &MF,
1537                                    MachineBasicBlock &MBB) const {
1538   MachineBasicBlock::iterator MBBI = prior(MBB.end());
1539   assert((MBBI->getOpcode() == ARM::BX_RET ||
1540           MBBI->getOpcode() == ARM::tBX_RET ||
1541           MBBI->getOpcode() == ARM::tPOP_RET) &&
1542          "Can only insert epilog into returning blocks");
1543
1544   MachineFrameInfo *MFI = MF.getFrameInfo();
1545   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1546   bool isThumb = AFI->isThumbFunction();
1547   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1548   int NumBytes = (int)MFI->getStackSize();
1549   if (!AFI->hasStackFrame()) {
1550     if (NumBytes != 0)
1551       emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, isThumb, TII);
1552   } else {
1553     // Unwind MBBI to point to first LDR / FLDD.
1554     const unsigned *CSRegs = getCalleeSavedRegs();
1555     if (MBBI != MBB.begin()) {
1556       do
1557         --MBBI;
1558       while (MBBI != MBB.begin() && isCSRestore(MBBI, CSRegs));
1559       if (!isCSRestore(MBBI, CSRegs))
1560         ++MBBI;
1561     }
1562
1563     // Move SP to start of FP callee save spill area.
1564     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
1565                  AFI->getGPRCalleeSavedArea2Size() +
1566                  AFI->getDPRCalleeSavedAreaSize());
1567     if (isThumb) {
1568       if (hasFP(MF)) {
1569         NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1570         // Reset SP based on frame pointer only if the stack frame extends beyond
1571         // frame pointer stack slot or target is ELF and the function has FP.
1572         if (NumBytes)
1573           emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, FramePtr, -NumBytes, TII);
1574         else
1575           BuildMI(MBB, MBBI, TII.get(ARM::tMOVr), ARM::SP).addReg(FramePtr);
1576       } else {
1577         if (MBBI->getOpcode() == ARM::tBX_RET &&
1578             &MBB.front() != MBBI &&
1579             prior(MBBI)->getOpcode() == ARM::tPOP) {
1580           MachineBasicBlock::iterator PMBBI = prior(MBBI);
1581           emitSPUpdate(MBB, PMBBI, NumBytes, ARMCC::AL, 0, isThumb, TII);
1582         } else
1583           emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, isThumb, TII);
1584       }
1585     } else {
1586       // Darwin ABI requires FP to point to the stack slot that contains the
1587       // previous FP.
1588       if ((STI.isTargetDarwin() && NumBytes) || hasFP(MF)) {
1589         NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1590         // Reset SP based on frame pointer only if the stack frame extends beyond
1591         // frame pointer stack slot or target is ELF and the function has FP.
1592         if (AFI->getGPRCalleeSavedArea2Size() ||
1593             AFI->getDPRCalleeSavedAreaSize()  ||
1594             AFI->getDPRCalleeSavedAreaOffset()||
1595             hasFP(MF))
1596           if (NumBytes)
1597             BuildMI(MBB, MBBI, TII.get(ARM::SUBri), ARM::SP).addReg(FramePtr)
1598               .addImm(NumBytes)
1599               .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
1600           else
1601             BuildMI(MBB, MBBI, TII.get(ARM::MOVr), ARM::SP).addReg(FramePtr)
1602               .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
1603       } else if (NumBytes) {
1604         emitSPUpdate(MBB, MBBI, NumBytes, ARMCC::AL, 0, false, TII);
1605       }
1606
1607       // Move SP to start of integer callee save spill area 2.
1608       movePastCSLoadStoreOps(MBB, MBBI, ARM::FLDD, 3, STI);
1609       emitSPUpdate(MBB, MBBI, AFI->getDPRCalleeSavedAreaSize(), ARMCC::AL, 0,
1610                    false, TII);
1611
1612       // Move SP to start of integer callee save spill area 1.
1613       movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, 2, STI);
1614       emitSPUpdate(MBB, MBBI, AFI->getGPRCalleeSavedArea2Size(), ARMCC::AL, 0,
1615                    false, TII);
1616
1617       // Move SP to SP upon entry to the function.
1618       movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, 1, STI);
1619       emitSPUpdate(MBB, MBBI, AFI->getGPRCalleeSavedArea1Size(), ARMCC::AL, 0,
1620                    false, TII);
1621     }
1622   }
1623
1624   if (VARegSaveSize) {
1625     if (isThumb)
1626       // Epilogue for vararg functions: pop LR to R3 and branch off it.
1627       // FIXME: Verify this is still ok when R3 is no longer being reserved.
1628       BuildMI(MBB, MBBI, TII.get(ARM::tPOP)).addReg(ARM::R3);
1629
1630     emitSPUpdate(MBB, MBBI, VARegSaveSize, ARMCC::AL, 0, isThumb, TII);
1631
1632     if (isThumb) {
1633       BuildMI(MBB, MBBI, TII.get(ARM::tBX_RET_vararg)).addReg(ARM::R3);
1634       MBB.erase(MBBI);
1635     }
1636   }
1637 }
1638
1639 unsigned ARMRegisterInfo::getRARegister() const {
1640   return ARM::LR;
1641 }
1642
1643 unsigned ARMRegisterInfo::getFrameRegister(MachineFunction &MF) const {
1644   if (STI.isTargetDarwin() || hasFP(MF))
1645     return (STI.useThumbBacktraces() || STI.isThumb()) ? ARM::R7 : ARM::R11;
1646   else
1647     return ARM::SP;
1648 }
1649
1650 unsigned ARMRegisterInfo::getEHExceptionRegister() const {
1651   assert(0 && "What is the exception register");
1652   return 0;
1653 }
1654
1655 unsigned ARMRegisterInfo::getEHHandlerRegister() const {
1656   assert(0 && "What is the exception handler register");
1657   return 0;
1658 }
1659
1660 int ARMRegisterInfo::getDwarfRegNum(unsigned RegNum) const {
1661   assert(0 && "What is the dwarf register number");
1662   return -1;
1663 }
1664
1665 #include "ARMGenRegisterInfo.inc"
1666