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