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