Use a spilled free callee-saved register as scratch register.
[oota-llvm.git] / lib / Target / ARM / ARMRegisterInfo.cpp
1 //===- ARMRegisterInfo.cpp - ARM Register Information -----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the "Instituto Nokia de Tecnologia" and
6 // is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 //
11 // This file contains the ARM implementation of the MRegisterInfo class.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMInstrInfo.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMRegisterInfo.h"
20 #include "ARMSubtarget.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineLocation.h"
28 #include "llvm/CodeGen/RegisterScavenging.h"
29 #include "llvm/Target/TargetFrameInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include <algorithm>
37 using namespace llvm;
38
39 static cl::opt<bool> EnableScavenging("enable-arm-reg-scavenging", cl::Hidden,
40                                  cl::desc("Enable register scavenging on ARM"));
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() ? ARM::R7 : ARM::R11) {
88   RS = (EnableScavenging) ? new RegScavenger() : NULL;
89 }
90
91 ARMRegisterInfo::~ARMRegisterInfo() {
92   delete RS;
93 }
94
95 bool ARMRegisterInfo::spillCalleeSavedRegisters(MachineBasicBlock &MBB,
96                                                 MachineBasicBlock::iterator MI,
97                                 const std::vector<CalleeSavedInfo> &CSI) const {
98   MachineFunction &MF = *MBB.getParent();
99   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
100   if (!AFI->isThumbFunction() || CSI.empty())
101     return false;
102
103   MachineInstrBuilder MIB = BuildMI(MBB, MI, TII.get(ARM::tPUSH));
104   for (unsigned i = CSI.size(); i != 0; --i) {
105     unsigned Reg = CSI[i-1].getReg();
106     // Add the callee-saved register as live-in. It's killed at the spill.
107     MBB.addLiveIn(Reg);
108     MIB.addReg(Reg, false/*isDef*/,false/*isImp*/,true/*isKill*/);
109   }
110   return true;
111 }
112
113 bool ARMRegisterInfo::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
114                                                  MachineBasicBlock::iterator MI,
115                                 const std::vector<CalleeSavedInfo> &CSI) const {
116   MachineFunction &MF = *MBB.getParent();
117   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
118   if (!AFI->isThumbFunction() || CSI.empty())
119     return false;
120
121   bool isVarArg = AFI->getVarArgsRegSaveSize() > 0;
122   MachineInstr *PopMI = new MachineInstr(TII.get(ARM::tPOP));
123   MBB.insert(MI, PopMI);
124   for (unsigned i = CSI.size(); i != 0; --i) {
125     unsigned Reg = CSI[i-1].getReg();
126     if (Reg == ARM::LR) {
127       // Special epilogue for vararg functions. See emitEpilogue
128       if (isVarArg)
129         continue;
130       Reg = ARM::PC;
131       PopMI->setInstrDescriptor(TII.get(ARM::tPOP_RET));
132       MBB.erase(MI);
133     }
134     PopMI->addRegOperand(Reg, true);
135   }
136   return true;
137 }
138
139 void ARMRegisterInfo::
140 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
141                     unsigned SrcReg, int FI,
142                     const TargetRegisterClass *RC) const {
143   if (RC == ARM::GPRRegisterClass) {
144     MachineFunction &MF = *MBB.getParent();
145     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
146     if (AFI->isThumbFunction())
147       BuildMI(MBB, I, TII.get(ARM::tSpill)).addReg(SrcReg, false, false, true)
148         .addFrameIndex(FI).addImm(0);
149     else
150       BuildMI(MBB, I, TII.get(ARM::STR)).addReg(SrcReg, false, false, true)
151           .addFrameIndex(FI).addReg(0).addImm(0);
152   } else if (RC == ARM::DPRRegisterClass) {
153     BuildMI(MBB, I, TII.get(ARM::FSTD)).addReg(SrcReg, false, false, true)
154     .addFrameIndex(FI).addImm(0);
155   } else {
156     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
157     BuildMI(MBB, I, TII.get(ARM::FSTS)).addReg(SrcReg, false, false, true)
158       .addFrameIndex(FI).addImm(0);
159   }
160 }
161
162 void ARMRegisterInfo::
163 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
164                      unsigned DestReg, int FI,
165                      const TargetRegisterClass *RC) const {
166   if (RC == ARM::GPRRegisterClass) {
167     MachineFunction &MF = *MBB.getParent();
168     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
169     if (AFI->isThumbFunction())
170       BuildMI(MBB, I, TII.get(ARM::tRestore), DestReg)
171         .addFrameIndex(FI).addImm(0);
172     else
173       BuildMI(MBB, I, TII.get(ARM::LDR), DestReg)
174       .addFrameIndex(FI).addReg(0).addImm(0);
175   } else if (RC == ARM::DPRRegisterClass) {
176     BuildMI(MBB, I, TII.get(ARM::FLDD), DestReg)
177       .addFrameIndex(FI).addImm(0);
178   } else {
179     assert(RC == ARM::SPRRegisterClass && "Unknown regclass!");
180     BuildMI(MBB, I, TII.get(ARM::FLDS), DestReg)
181       .addFrameIndex(FI).addImm(0);
182   }
183 }
184
185 void ARMRegisterInfo::copyRegToReg(MachineBasicBlock &MBB,
186                                    MachineBasicBlock::iterator I,
187                                    unsigned DestReg, unsigned SrcReg,
188                                    const TargetRegisterClass *RC) const {
189   if (RC == ARM::GPRRegisterClass) {
190     MachineFunction &MF = *MBB.getParent();
191     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
192     BuildMI(MBB, I, TII.get(AFI->isThumbFunction() ? ARM::tMOVrr : ARM::MOVrr),
193             DestReg).addReg(SrcReg);
194   } else if (RC == ARM::SPRRegisterClass)
195     BuildMI(MBB, I, TII.get(ARM::FCPYS), DestReg).addReg(SrcReg);
196   else if (RC == ARM::DPRRegisterClass)
197     BuildMI(MBB, I, TII.get(ARM::FCPYD), DestReg).addReg(SrcReg);
198   else
199     abort();
200 }
201
202 /// isLowRegister - Returns true if the register is low register r0-r7.
203 ///
204 static bool isLowRegister(unsigned Reg) {
205   using namespace ARM;
206   switch (Reg) {
207   case R0:  case R1:  case R2:  case R3:
208   case R4:  case R5:  case R6:  case R7:
209     return true;
210   default:
211     return false;
212   }
213 }
214
215 MachineInstr *ARMRegisterInfo::foldMemoryOperand(MachineInstr *MI,
216                                                  unsigned OpNum, int FI) const {
217   unsigned Opc = MI->getOpcode();
218   MachineInstr *NewMI = NULL;
219   switch (Opc) {
220   default: break;
221   case ARM::MOVrr: {
222     if (OpNum == 0) { // move -> store
223       unsigned SrcReg = MI->getOperand(1).getReg();
224       NewMI = BuildMI(TII.get(ARM::STR)).addReg(SrcReg).addFrameIndex(FI)
225         .addReg(0).addImm(0);
226     } else {          // move -> load
227       unsigned DstReg = MI->getOperand(0).getReg();
228       NewMI = BuildMI(TII.get(ARM::LDR), DstReg).addFrameIndex(FI).addReg(0)
229         .addImm(0);
230     }
231     break;
232   }
233   case ARM::tMOVrr: {
234     if (OpNum == 0) { // move -> store
235       unsigned SrcReg = MI->getOperand(1).getReg();
236       if (isPhysicalRegister(SrcReg) && !isLowRegister(SrcReg))
237         // tSpill cannot take a high register operand.
238         break;
239       NewMI = BuildMI(TII.get(ARM::tSpill)).addReg(SrcReg).addFrameIndex(FI)
240         .addImm(0);
241     } else {          // move -> load
242       unsigned DstReg = MI->getOperand(0).getReg();
243       if (isPhysicalRegister(DstReg) && !isLowRegister(DstReg))
244         // tRestore cannot target a high register operand.
245         break;
246       NewMI = BuildMI(TII.get(ARM::tRestore), DstReg).addFrameIndex(FI)
247         .addImm(0);
248     }
249     break;
250   }
251   case ARM::FCPYS: {
252     if (OpNum == 0) { // move -> store
253       unsigned SrcReg = MI->getOperand(1).getReg();
254       NewMI = BuildMI(TII.get(ARM::FSTS)).addReg(SrcReg).addFrameIndex(FI)
255         .addImm(0);
256     } else {          // move -> load
257       unsigned DstReg = MI->getOperand(0).getReg();
258       NewMI = BuildMI(TII.get(ARM::FLDS), DstReg).addFrameIndex(FI).addImm(0);
259     }
260     break;
261   }
262   case ARM::FCPYD: {
263     if (OpNum == 0) { // move -> store
264       unsigned SrcReg = MI->getOperand(1).getReg();
265       NewMI = BuildMI(TII.get(ARM::FSTD)).addReg(SrcReg).addFrameIndex(FI)
266         .addImm(0);
267     } else {          // move -> load
268       unsigned DstReg = MI->getOperand(0).getReg();
269       NewMI = BuildMI(TII.get(ARM::FLDD), DstReg).addFrameIndex(FI).addImm(0);
270     }
271     break;
272   }
273   }
274
275   if (NewMI)
276     NewMI->copyKillDeadInfo(MI);
277   return NewMI;
278 }
279
280 const unsigned* ARMRegisterInfo::getCalleeSavedRegs() const {
281   static const unsigned CalleeSavedRegs[] = {
282     ARM::LR, ARM::R11, ARM::R10, ARM::R9, ARM::R8,
283     ARM::R7, ARM::R6,  ARM::R5,  ARM::R4,
284
285     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
286     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
287     0
288   };
289
290   static const unsigned DarwinCalleeSavedRegs[] = {
291     ARM::LR,  ARM::R7,  ARM::R6, ARM::R5, ARM::R4,
292     ARM::R11, ARM::R10, ARM::R9, ARM::R8,
293
294     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
295     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
296     0
297   };
298   return STI.isTargetDarwin() ? DarwinCalleeSavedRegs : CalleeSavedRegs;
299 }
300
301 const TargetRegisterClass* const *
302 ARMRegisterInfo::getCalleeSavedRegClasses() const {
303   static const TargetRegisterClass * const CalleeSavedRegClasses[] = {
304     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
305     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
306     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
307
308     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
309     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
310     0
311   };
312   return CalleeSavedRegClasses;
313 }
314
315 BitVector ARMRegisterInfo::getReservedRegs(const MachineFunction &MF) const {
316   // FIXME: avoid re-calculating this everytime.
317   BitVector Reserved(getNumRegs());
318   Reserved.set(ARM::SP);
319   Reserved.set(ARM::PC);
320   if (STI.isTargetDarwin() || hasFP(MF))
321     Reserved.set(FramePtr);
322   // Some targets reserve R9.
323   if (STI.isR9Reserved())
324     Reserved.set(ARM::R9);
325   // At PEI time, if LR is used, it will be spilled upon entry.
326   if (MF.getUsedPhysregs() && !MF.isPhysRegUsed((unsigned)ARM::LR))
327     Reserved.set(ARM::LR);
328   return Reserved;
329 }
330
331 bool
332 ARMRegisterInfo::requiresRegisterScavenging(const MachineFunction &MF) const {
333   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
334   return EnableScavenging && !AFI->isThumbFunction();
335 }
336
337 /// hasFP - Return true if the specified function should have a dedicated frame
338 /// pointer register.  This is true if the function has variable sized allocas
339 /// or if frame pointer elimination is disabled.
340 ///
341 bool ARMRegisterInfo::hasFP(const MachineFunction &MF) const {
342   return NoFramePointerElim || MF.getFrameInfo()->hasVarSizedObjects();
343 }
344
345 /// emitARMRegPlusImmediate - Emits a series of instructions to materialize
346 /// a destreg = basereg + immediate in ARM code.
347 static
348 void emitARMRegPlusImmediate(MachineBasicBlock &MBB,
349                              MachineBasicBlock::iterator &MBBI,
350                              unsigned DestReg, unsigned BaseReg,
351                              int NumBytes, const TargetInstrInfo &TII) {
352   bool isSub = NumBytes < 0;
353   if (isSub) NumBytes = -NumBytes;
354
355   while (NumBytes) {
356     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
357     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
358     assert(ThisVal && "Didn't extract field correctly");
359     
360     // We will handle these bits from offset, clear them.
361     NumBytes &= ~ThisVal;
362     
363     // Get the properly encoded SOImmVal field.
364     int SOImmVal = ARM_AM::getSOImmVal(ThisVal);
365     assert(SOImmVal != -1 && "Bit extraction didn't work?");
366     
367     // Build the new ADD / SUB.
368     BuildMI(MBB, MBBI, TII.get(isSub ? ARM::SUBri : ARM::ADDri), DestReg)
369       .addReg(BaseReg, false, false, true).addImm(SOImmVal);
370     BaseReg = DestReg;
371   }
372 }
373
374 /// calcNumMI - Returns the number of instructions required to materialize
375 /// the specific add / sub r, c instruction.
376 static unsigned calcNumMI(int Opc, int ExtraOpc, unsigned Bytes,
377                           unsigned NumBits, unsigned Scale) {
378   unsigned NumMIs = 0;
379   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
380
381   if (Opc == ARM::tADDrSPi) {
382     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
383     Bytes -= ThisVal;
384     NumMIs++;
385     NumBits = 8;
386     Scale = 1;
387     Chunk = ((1 << NumBits) - 1) * Scale;
388   }
389
390   NumMIs += Bytes / Chunk;
391   if ((Bytes % Chunk) != 0)
392     NumMIs++;
393   if (ExtraOpc)
394     NumMIs++;
395   return NumMIs;
396 }
397
398 /// emitLoadConstPool - Emits a load from constpool to materialize NumBytes
399 /// immediate.
400 static void emitLoadConstPool(MachineBasicBlock &MBB,
401                               MachineBasicBlock::iterator &MBBI,
402                               unsigned DestReg, int NumBytes, 
403                               const TargetInstrInfo &TII) {
404   MachineFunction &MF = *MBB.getParent();
405   MachineConstantPool *ConstantPool = MF.getConstantPool();
406   Constant *C = ConstantInt::get(Type::Int32Ty, NumBytes);
407   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 2);
408   BuildMI(MBB, MBBI, TII.get(ARM::tLDRpci), DestReg).addConstantPoolIndex(Idx);
409 }
410
411 /// emitThumbRegPlusImmInReg - Emits a series of instructions to materialize
412 /// a destreg = basereg + immediate in Thumb code. Materialize the immediate
413 /// in a register using mov / mvn sequences or load the immediate from a
414 /// constpool entry.
415 static
416 void emitThumbRegPlusImmInReg(MachineBasicBlock &MBB,
417                                MachineBasicBlock::iterator &MBBI,
418                                unsigned DestReg, unsigned BaseReg,
419                                int NumBytes, bool CanChangeCC,
420                                const TargetInstrInfo &TII) {
421     bool isHigh = !isLowRegister(DestReg) ||
422                   (BaseReg != 0 && !isLowRegister(BaseReg));
423     bool isSub = false;
424     // Subtract doesn't have high register version. Load the negative value
425     // if either base or dest register is a high register. Also, if do not
426     // issue sub as part of the sequence if condition register is to be
427     // preserved.
428     if (NumBytes < 0 && !isHigh && CanChangeCC) {
429       isSub = true;
430       NumBytes = -NumBytes;
431     }
432     unsigned LdReg = DestReg;
433     if (DestReg == ARM::SP) {
434       assert(BaseReg == ARM::SP && "Unexpected!");
435       LdReg = ARM::R3;
436       BuildMI(MBB, MBBI, TII.get(ARM::tMOVrr), ARM::R12)
437         .addReg(ARM::R3, false, false, true);
438     }
439
440     if (NumBytes <= 255 && NumBytes >= 0)
441       BuildMI(MBB, MBBI, TII.get(ARM::tMOVri8), LdReg).addImm(NumBytes);
442     else if (NumBytes < 0 && NumBytes >= -255) {
443       BuildMI(MBB, MBBI, TII.get(ARM::tMOVri8), LdReg).addImm(NumBytes);
444       BuildMI(MBB, MBBI, TII.get(ARM::tNEG), LdReg)
445         .addReg(LdReg, false, false, true);
446     } else
447       emitLoadConstPool(MBB, MBBI, LdReg, NumBytes, TII);
448
449     // Emit add / sub.
450     int Opc = (isSub) ? ARM::tSUBrr : (isHigh ? ARM::tADDhirr : ARM::tADDrr);
451     const MachineInstrBuilder MIB = BuildMI(MBB, MBBI, TII.get(Opc), DestReg);
452     if (DestReg == ARM::SP || isSub)
453       MIB.addReg(BaseReg).addReg(LdReg, false, false, true);
454     else
455       MIB.addReg(LdReg).addReg(BaseReg, false, false, true);
456     if (DestReg == ARM::SP)
457       BuildMI(MBB, MBBI, TII.get(ARM::tMOVrr), ARM::R3)
458         .addReg(ARM::R12, false, false, true);
459 }
460
461 /// emitThumbRegPlusImmediate - Emits a series of instructions to materialize
462 /// a destreg = basereg + immediate in Thumb code.
463 static
464 void emitThumbRegPlusImmediate(MachineBasicBlock &MBB,
465                                MachineBasicBlock::iterator &MBBI,
466                                unsigned DestReg, unsigned BaseReg,
467                                int NumBytes, const TargetInstrInfo &TII) {
468   bool isSub = NumBytes < 0;
469   unsigned Bytes = (unsigned)NumBytes;
470   if (isSub) Bytes = -NumBytes;
471   bool isMul4 = (Bytes & 3) == 0;
472   bool isTwoAddr = false;
473   bool DstNotEqBase = false;
474   unsigned NumBits = 1;
475   unsigned Scale = 1;
476   int Opc = 0;
477   int ExtraOpc = 0;
478
479   if (DestReg == BaseReg && BaseReg == ARM::SP) {
480     assert(isMul4 && "Thumb sp inc / dec size must be multiple of 4!");
481     NumBits = 7;
482     Scale = 4;
483     Opc = isSub ? ARM::tSUBspi : ARM::tADDspi;
484     isTwoAddr = true;
485   } else if (!isSub && BaseReg == ARM::SP) {
486     // r1 = add sp, 403
487     // =>
488     // r1 = add sp, 100 * 4
489     // r1 = add r1, 3
490     if (!isMul4) {
491       Bytes &= ~3;
492       ExtraOpc = ARM::tADDi3;
493     }
494     NumBits = 8;
495     Scale = 4;
496     Opc = ARM::tADDrSPi;
497   } else {
498     // sp = sub sp, c
499     // r1 = sub sp, c
500     // r8 = sub sp, c
501     if (DestReg != BaseReg)
502       DstNotEqBase = true;
503     NumBits = 8;
504     Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
505     isTwoAddr = true;
506   }
507
508   unsigned NumMIs = calcNumMI(Opc, ExtraOpc, Bytes, NumBits, Scale);
509   unsigned Threshold = (DestReg == ARM::SP) ? 3 : 2;
510   if (NumMIs > Threshold) {
511     // This will expand into too many instructions. Load the immediate from a
512     // constpool entry.
513     emitThumbRegPlusImmInReg(MBB, MBBI, DestReg, BaseReg, NumBytes, true, TII);
514     return;
515   }
516
517   if (DstNotEqBase) {
518     if (isLowRegister(DestReg) && isLowRegister(BaseReg)) {
519       // If both are low registers, emit DestReg = add BaseReg, max(Imm, 7)
520       unsigned Chunk = (1 << 3) - 1;
521       unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
522       Bytes -= ThisVal;
523       BuildMI(MBB, MBBI, TII.get(isSub ? ARM::tSUBi3 : ARM::tADDi3), DestReg)
524         .addReg(BaseReg, false, false, true).addImm(ThisVal);
525     } else {
526       BuildMI(MBB, MBBI, TII.get(ARM::tMOVrr), DestReg)
527         .addReg(BaseReg, false, false, true);
528     }
529     BaseReg = DestReg;
530   }
531
532   unsigned Chunk = ((1 << NumBits) - 1) * Scale;
533   while (Bytes) {
534     unsigned ThisVal = (Bytes > Chunk) ? Chunk : Bytes;
535     Bytes -= ThisVal;
536     ThisVal /= Scale;
537     // Build the new tADD / tSUB.
538     if (isTwoAddr)
539       BuildMI(MBB, MBBI, TII.get(Opc), DestReg).addReg(DestReg).addImm(ThisVal);
540     else {
541       bool isKill = BaseReg != ARM::SP;
542       BuildMI(MBB, MBBI, TII.get(Opc), DestReg)
543         .addReg(BaseReg, false, false, isKill).addImm(ThisVal);
544       BaseReg = DestReg;
545
546       if (Opc == ARM::tADDrSPi) {
547         // r4 = add sp, imm
548         // r4 = add r4, imm
549         // ...
550         NumBits = 8;
551         Scale = 1;
552         Chunk = ((1 << NumBits) - 1) * Scale;
553         Opc = isSub ? ARM::tSUBi8 : ARM::tADDi8;
554         isTwoAddr = true;
555       }
556     }
557   }
558
559   if (ExtraOpc)
560     BuildMI(MBB, MBBI, TII.get(ExtraOpc), DestReg)
561       .addReg(DestReg, false, false, true)
562       .addImm(((unsigned)NumBytes) & 3);
563 }
564
565 static
566 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
567                   int NumBytes, bool isThumb, const TargetInstrInfo &TII) {
568   if (isThumb)
569     emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes, TII);
570   else
571     emitARMRegPlusImmediate(MBB, MBBI, ARM::SP, ARM::SP, NumBytes, TII);
572 }
573
574 void ARMRegisterInfo::
575 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
576                               MachineBasicBlock::iterator I) const {
577   if (hasFP(MF)) {
578     // If we have alloca, convert as follows:
579     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
580     // ADJCALLSTACKUP   -> add, sp, sp, amount
581     MachineInstr *Old = I;
582     unsigned Amount = Old->getOperand(0).getImmedValue();
583     if (Amount != 0) {
584       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
585       // We need to keep the stack aligned properly.  To do this, we round the
586       // amount of space needed for the outgoing arguments up to the next
587       // alignment boundary.
588       unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
589       Amount = (Amount+Align-1)/Align*Align;
590
591       // Replace the pseudo instruction with a new instruction...
592       if (Old->getOpcode() == ARM::ADJCALLSTACKDOWN) {
593         emitSPUpdate(MBB, I, -Amount, AFI->isThumbFunction(), TII);
594       } else {
595         assert(Old->getOpcode() == ARM::ADJCALLSTACKUP);
596         emitSPUpdate(MBB, I, Amount, AFI->isThumbFunction(), TII);
597       }
598     }
599   }
600   MBB.erase(I);
601 }
602
603 /// emitThumbConstant - Emit a series of instructions to materialize a
604 /// constant.
605 static void emitThumbConstant(MachineBasicBlock &MBB,
606                               MachineBasicBlock::iterator &MBBI,
607                               unsigned DestReg, int Imm,
608                               const TargetInstrInfo &TII) {
609   bool isSub = Imm < 0;
610   if (isSub) Imm = -Imm;
611
612   int Chunk = (1 << 8) - 1;
613   int ThisVal = (Imm > Chunk) ? Chunk : Imm;
614   Imm -= ThisVal;
615   BuildMI(MBB, MBBI, TII.get(ARM::tMOVri8), DestReg).addImm(ThisVal);
616   if (Imm > 0) 
617     emitThumbRegPlusImmediate(MBB, MBBI, DestReg, DestReg, Imm, TII);
618   if (isSub)
619     BuildMI(MBB, MBBI, TII.get(ARM::tNEG), DestReg)
620       .addReg(DestReg, false, false, true);
621 }
622
623 /// findScratchRegister - Find a 'free' ARM register. If register scavenger
624 /// is not being used, R12 is available. Otherwise, try for a call-clobbered
625 /// register first and then a spilled callee-saved register if that fails.
626 static
627 unsigned findScratchRegister(RegScavenger *RS, const TargetRegisterClass *RC,
628                              ARMFunctionInfo *AFI) {
629   unsigned Reg = RS ? RS->FindUnusedReg(RC, true) : (unsigned) ARM::R12;
630   if (Reg == 0)
631     // Try a already spilled CS register.
632     Reg = RS->FindUnusedReg(RC, AFI->getSpilledCSRegisters());
633
634   return Reg;
635 }
636
637 void ARMRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
638                                           RegScavenger *RS) const{
639   unsigned i = 0;
640   MachineInstr &MI = *II;
641   MachineBasicBlock &MBB = *MI.getParent();
642   MachineFunction &MF = *MBB.getParent();
643   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
644   bool isThumb = AFI->isThumbFunction();
645
646   while (!MI.getOperand(i).isFrameIndex()) {
647     ++i;
648     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
649   }
650   
651   unsigned FrameReg = ARM::SP;
652   int FrameIndex = MI.getOperand(i).getFrameIndex();
653   int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex) + 
654                MF.getFrameInfo()->getStackSize();
655
656   if (AFI->isGPRCalleeSavedArea1Frame(FrameIndex))
657     Offset -= AFI->getGPRCalleeSavedArea1Offset();
658   else if (AFI->isGPRCalleeSavedArea2Frame(FrameIndex))
659     Offset -= AFI->getGPRCalleeSavedArea2Offset();
660   else if (AFI->isDPRCalleeSavedAreaFrame(FrameIndex))
661     Offset -= AFI->getDPRCalleeSavedAreaOffset();
662   else if (hasFP(MF)) {
663     // There is alloca()'s in this function, must reference off the frame
664     // pointer instead.
665     FrameReg = getFrameRegister(MF);
666     Offset -= AFI->getFramePtrSpillOffset();
667   }
668
669   unsigned Opcode = MI.getOpcode();
670   const TargetInstrDescriptor &Desc = TII.get(Opcode);
671   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
672   bool isSub = false;
673   
674   if (Opcode == ARM::ADDri) {
675     Offset += MI.getOperand(i+1).getImm();
676     if (Offset == 0) {
677       // Turn it into a move.
678       MI.setInstrDescriptor(TII.get(ARM::MOVrr));
679       MI.getOperand(i).ChangeToRegister(FrameReg, false);
680       MI.RemoveOperand(i+1);
681       return;
682     } else if (Offset < 0) {
683       Offset = -Offset;
684       isSub = true;
685       MI.setInstrDescriptor(TII.get(ARM::SUBri));
686     }
687
688     // Common case: small offset, fits into instruction.
689     int ImmedOffset = ARM_AM::getSOImmVal(Offset);
690     if (ImmedOffset != -1) {
691       // Replace the FrameIndex with sp / fp
692       MI.getOperand(i).ChangeToRegister(FrameReg, false);
693       MI.getOperand(i+1).ChangeToImmediate(ImmedOffset);
694       return;
695     }
696     
697     // Otherwise, we fallback to common code below to form the imm offset with
698     // a sequence of ADDri instructions.  First though, pull as much of the imm
699     // into this ADDri as possible.
700     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
701     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, (32-RotAmt) & 31);
702     
703     // We will handle these bits from offset, clear them.
704     Offset &= ~ThisImmVal;
705     
706     // Get the properly encoded SOImmVal field.
707     int ThisSOImmVal = ARM_AM::getSOImmVal(ThisImmVal);
708     assert(ThisSOImmVal != -1 && "Bit extraction didn't work?");    
709     MI.getOperand(i+1).ChangeToImmediate(ThisSOImmVal);
710   } else if (Opcode == ARM::tADDrSPi) {
711     Offset += MI.getOperand(i+1).getImm();
712     assert((Offset & 3) == 0 &&
713            "Thumb add/sub sp, #imm immediate must be multiple of 4!");
714     if (Offset == 0) {
715       // Turn it into a move.
716       MI.setInstrDescriptor(TII.get(ARM::tMOVrr));
717       MI.getOperand(i).ChangeToRegister(FrameReg, false);
718       MI.RemoveOperand(i+1);
719       return;
720     }
721
722     // Common case: small offset, fits into instruction.
723     if (((Offset >> 2) & ~255U) == 0) {
724       // Replace the FrameIndex with sp / fp
725       MI.getOperand(i).ChangeToRegister(FrameReg, false);
726       MI.getOperand(i+1).ChangeToImmediate(Offset >> 2);
727       return;
728     }
729
730     unsigned DestReg = MI.getOperand(0).getReg();
731     unsigned Bytes = (Offset > 0) ? Offset : -Offset;
732     unsigned NumMIs = calcNumMI(Opcode, 0, Bytes, 8, 1);
733     // MI would expand into a large number of instructions. Don't try to
734     // simplify the immediate.
735     if (NumMIs > 2) {
736       emitThumbRegPlusImmediate(MBB, II, DestReg, FrameReg, Offset, TII);
737       MBB.erase(II);
738       return;
739     }
740
741     if (Offset > 0) {
742       // Translate r0 = add sp, imm to
743       // r0 = add sp, 255*4
744       // r0 = add r0, (imm - 255*4)
745       MI.getOperand(i).ChangeToRegister(FrameReg, false);
746       MI.getOperand(i+1).ChangeToImmediate(255);
747       Offset = (Offset - 255 * 4);
748       MachineBasicBlock::iterator NII = next(II);
749       emitThumbRegPlusImmediate(MBB, NII, DestReg, DestReg, Offset, TII);
750     } else {
751       // Translate r0 = add sp, -imm to
752       // r0 = -imm (this is then translated into a series of instructons)
753       // r0 = add r0, sp
754       emitThumbConstant(MBB, II, DestReg, Offset, TII);
755       MI.setInstrDescriptor(TII.get(ARM::tADDhirr));
756       MI.getOperand(i).ChangeToRegister(DestReg, false, false, true);
757       MI.getOperand(i+1).ChangeToRegister(FrameReg, false);
758     }
759     return;
760   } else {
761     unsigned ImmIdx = 0;
762     int InstrOffs = 0;
763     unsigned NumBits = 0;
764     unsigned Scale = 1;
765     switch (AddrMode) {
766     case ARMII::AddrMode2: {
767       ImmIdx = i+2;
768       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
769       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
770         InstrOffs *= -1;
771       NumBits = 12;
772       break;
773     }
774     case ARMII::AddrMode3: {
775       ImmIdx = i+2;
776       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
777       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
778         InstrOffs *= -1;
779       NumBits = 8;
780       break;
781     }
782     case ARMII::AddrMode5: {
783       ImmIdx = i+1;
784       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
785       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
786         InstrOffs *= -1;
787       NumBits = 8;
788       Scale = 4;
789       break;
790     }
791     case ARMII::AddrModeTs: {
792       ImmIdx = i+1;
793       InstrOffs = MI.getOperand(ImmIdx).getImm();
794       NumBits = (FrameReg == ARM::SP) ? 8 : 5;
795       Scale = 4;
796       break;
797     }
798     default:
799       assert(0 && "Unsupported addressing mode!");
800       abort();
801       break;
802     }
803
804     Offset += InstrOffs * Scale;
805     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
806     if (Offset < 0 && !isThumb) {
807       Offset = -Offset;
808       isSub = true;
809     }
810
811     // Common case: small offset, fits into instruction.
812     MachineOperand &ImmOp = MI.getOperand(ImmIdx);
813     int ImmedOffset = Offset / Scale;
814     unsigned Mask = (1 << NumBits) - 1;
815     if ((unsigned)Offset <= Mask * Scale) {
816       // Replace the FrameIndex with sp
817       MI.getOperand(i).ChangeToRegister(FrameReg, false);
818       if (isSub)
819         ImmedOffset |= 1 << NumBits;
820       ImmOp.ChangeToImmediate(ImmedOffset);
821       return;
822     }
823
824     bool isThumSpillRestore = Opcode == ARM::tRestore || Opcode == ARM::tSpill;
825     if (AddrMode == ARMII::AddrModeTs) {
826       // Thumb tLDRspi, tSTRspi. These will change to instructions that use
827       // a different base register.
828       NumBits = 5;
829       Mask = (1 << NumBits) - 1;
830     }
831     // If this is a thumb spill / restore, we will be using a constpool load to
832     // materialize the offset.
833     if (AddrMode == ARMII::AddrModeTs && isThumSpillRestore)
834       ImmOp.ChangeToImmediate(0);
835     else {
836       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
837       ImmedOffset = ImmedOffset & Mask;
838       if (isSub)
839         ImmedOffset |= 1 << NumBits;
840       ImmOp.ChangeToImmediate(ImmedOffset);
841       Offset &= ~(Mask*Scale);
842     }
843   }
844   
845   // If we get here, the immediate doesn't fit into the instruction.  We folded
846   // as much as possible above, handle the rest, providing a register that is
847   // SP+LargeImm.
848   assert(Offset && "This code isn't needed if offset already handled!");
849
850   if (isThumb) {
851     if (TII.isLoad(Opcode)) {
852       // Use the destination register to materialize sp + offset.
853       unsigned TmpReg = MI.getOperand(0).getReg();
854       bool UseRR = false;
855       if (Opcode == ARM::tRestore) {
856         if (FrameReg == ARM::SP)
857           emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,Offset,false,TII);
858         else {
859           emitLoadConstPool(MBB, II, TmpReg, Offset, TII);
860           UseRR = true;
861         }
862       } else
863         emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII);
864       MI.setInstrDescriptor(TII.get(ARM::tLDR));
865       MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
866       if (UseRR)
867         MI.addRegOperand(FrameReg, false);  // Use [reg, reg] addrmode.
868       else
869         MI.addRegOperand(0, false); // tLDR has an extra register operand.
870     } else if (TII.isStore(Opcode)) {
871       // FIXME! This is horrific!!! We need register scavenging.
872       // Our temporary workaround has marked r3 unavailable. Of course, r3 is
873       // also a ABI register so it's possible that is is the register that is
874       // being storing here. If that's the case, we do the following:
875       // r12 = r2
876       // Use r2 to materialize sp + offset
877       // str r3, r2
878       // r2 = r12
879       unsigned ValReg = MI.getOperand(0).getReg();
880       unsigned TmpReg = ARM::R3;
881       bool UseRR = false;
882       if (ValReg == ARM::R3) {
883         BuildMI(MBB, II, TII.get(ARM::tMOVrr), ARM::R12)
884           .addReg(ARM::R2, false, false, true);
885         TmpReg = ARM::R2;
886       }
887       if (TmpReg == ARM::R3 && AFI->isR3LiveIn())
888         BuildMI(MBB, II, TII.get(ARM::tMOVrr), ARM::R12)
889           .addReg(ARM::R3, false, false, true);
890       if (Opcode == ARM::tSpill) {
891         if (FrameReg == ARM::SP)
892           emitThumbRegPlusImmInReg(MBB, II, TmpReg, FrameReg,Offset,false,TII);
893         else {
894           emitLoadConstPool(MBB, II, TmpReg, Offset, TII);
895           UseRR = true;
896         }
897       } else
898         emitThumbRegPlusImmediate(MBB, II, TmpReg, FrameReg, Offset, TII);
899       MI.setInstrDescriptor(TII.get(ARM::tSTR));
900       MI.getOperand(i).ChangeToRegister(TmpReg, false, false, true);
901       if (UseRR)
902         MI.addRegOperand(FrameReg, false);  // Use [reg, reg] addrmode.
903       else
904         MI.addRegOperand(0, false); // tSTR has an extra register operand.
905
906       MachineBasicBlock::iterator NII = next(II);
907       if (ValReg == ARM::R3)
908         BuildMI(MBB, NII, TII.get(ARM::tMOVrr), ARM::R2)
909           .addReg(ARM::R12, false, false, true);
910       if (TmpReg == ARM::R3 && AFI->isR3LiveIn())
911         BuildMI(MBB, NII, TII.get(ARM::tMOVrr), ARM::R3)
912           .addReg(ARM::R12, false, false, true);
913     } else
914       assert(false && "Unexpected opcode!");
915   } else {
916     // Insert a set of r12 with the full address: r12 = sp + offset
917     // If the offset we have is too large to fit into the instruction, we need
918     // to form it with a series of ADDri's.  Do this by taking 8-bit chunks
919     // out of 'Offset'.
920     unsigned ScratchReg = findScratchRegister(RS, &ARM::GPRRegClass, AFI);
921     assert(ScratchReg && "Unable to find a free register!");
922     emitARMRegPlusImmediate(MBB, II, ScratchReg, FrameReg,
923                             isSub ? -Offset : Offset, TII);
924     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
925   }
926 }
927
928 void ARMRegisterInfo::
929 processFunctionBeforeCalleeSavedScan(MachineFunction &MF) const {
930   // This tells PEI to spill the FP as if it is any other callee-save register
931   // to take advantage the eliminateFrameIndex machinery. This also ensures it
932   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
933   // to combine multiple loads / stores.
934   bool CanEliminateFrame = true;
935   bool CS1Spilled = false;
936   bool LRSpilled = false;
937   unsigned NumGPRSpills = 0;
938   SmallVector<unsigned, 4> UnspilledCS1GPRs;
939   SmallVector<unsigned, 4> UnspilledCS2GPRs;
940   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
941
942   // Don't spill FP if the frame can be eliminated. This is determined
943   // by scanning the callee-save registers to see if any is used.
944   const unsigned *CSRegs = getCalleeSavedRegs();
945   const TargetRegisterClass* const *CSRegClasses = getCalleeSavedRegClasses();
946   for (unsigned i = 0; CSRegs[i]; ++i) {
947     unsigned Reg = CSRegs[i];
948     bool Spilled = false;
949     if (MF.isPhysRegUsed(Reg)) {
950       AFI->setCSRegisterIsSpilled(Reg);
951       Spilled = true;
952       CanEliminateFrame = false;
953     } else {
954       // Check alias registers too.
955       for (const unsigned *Aliases = getAliasSet(Reg); *Aliases; ++Aliases) {
956         if (MF.isPhysRegUsed(*Aliases)) {
957           Spilled = true;
958           CanEliminateFrame = false;
959         }
960       }
961     }
962
963     if (CSRegClasses[i] == &ARM::GPRRegClass) {
964       if (Spilled) {
965         NumGPRSpills++;
966
967         if (!STI.isTargetDarwin()) {
968           if (Reg == ARM::LR)
969             LRSpilled = true;
970           else
971             CS1Spilled = true;
972           continue;
973         }
974
975         // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
976         switch (Reg) {
977         case ARM::LR:
978           LRSpilled = true;
979           // Fallthrough
980         case ARM::R4:
981         case ARM::R5:
982         case ARM::R6:
983         case ARM::R7:
984           CS1Spilled = true;
985           break;
986         default:
987           break;
988         }
989       } else { 
990         if (!STI.isTargetDarwin()) {
991           UnspilledCS1GPRs.push_back(Reg);
992           continue;
993         }
994
995         switch (Reg) {
996         case ARM::R4:
997         case ARM::R5:
998         case ARM::R6:
999         case ARM::R7:
1000         case ARM::LR:
1001           UnspilledCS1GPRs.push_back(Reg);
1002           break;
1003         default:
1004           UnspilledCS2GPRs.push_back(Reg);
1005           break;
1006         }
1007       }
1008     }
1009   }
1010
1011   bool ForceLRSpill = false;
1012   if (!LRSpilled && AFI->isThumbFunction()) {
1013     unsigned FnSize = ARM::GetFunctionSize(MF);
1014     // Force LR to be spilled if the Thumb function size is > 2048. This enables
1015     // use of BL to implement far jump. If it turns out that it's not needed
1016     // then the branch fix up path will undo it.
1017     if (FnSize >= (1 << 11)) {
1018       CanEliminateFrame = false;
1019       ForceLRSpill = true;
1020     }
1021   }
1022
1023   if (!CanEliminateFrame || hasFP(MF)) {
1024     AFI->setHasStackFrame(true);
1025
1026     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
1027     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
1028     if (!LRSpilled && CS1Spilled) {
1029       MF.changePhyRegUsed(ARM::LR, true);
1030       AFI->setCSRegisterIsSpilled(ARM::LR);
1031       NumGPRSpills++;
1032       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
1033                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
1034       ForceLRSpill = false;
1035     }
1036
1037     // Darwin ABI requires FP to point to the stack slot that contains the
1038     // previous FP.
1039     if (STI.isTargetDarwin() || hasFP(MF)) {
1040       MF.changePhyRegUsed(FramePtr, true);
1041       NumGPRSpills++;
1042     }
1043
1044     // If stack and double are 8-byte aligned and we are spilling an odd number
1045     // of GPRs. Spill one extra callee save GPR so we won't have to pad between
1046     // the integer and double callee save areas.
1047     unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1048     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
1049       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
1050         unsigned Reg = UnspilledCS1GPRs.front();
1051         MF.changePhyRegUsed(Reg, true);
1052         AFI->setCSRegisterIsSpilled(Reg);
1053       } else if (!UnspilledCS2GPRs.empty()) {
1054         unsigned Reg = UnspilledCS2GPRs.front();
1055         MF.changePhyRegUsed(Reg, true);
1056         AFI->setCSRegisterIsSpilled(Reg);
1057       }
1058     }
1059   }
1060
1061   if (ForceLRSpill) {
1062     MF.changePhyRegUsed(ARM::LR, true);
1063     AFI->setCSRegisterIsSpilled(ARM::LR);
1064     AFI->setLRIsSpilledForFarJump(true);
1065   }
1066 }
1067
1068 /// Move iterator pass the next bunch of callee save load / store ops for
1069 /// the particular spill area (1: integer area 1, 2: integer area 2,
1070 /// 3: fp area, 0: don't care).
1071 static void movePastCSLoadStoreOps(MachineBasicBlock &MBB,
1072                                    MachineBasicBlock::iterator &MBBI,
1073                                    int Opc, unsigned Area,
1074                                    const ARMSubtarget &STI) {
1075   while (MBBI != MBB.end() &&
1076          MBBI->getOpcode() == Opc && MBBI->getOperand(1).isFrameIndex()) {
1077     if (Area != 0) {
1078       bool Done = false;
1079       unsigned Category = 0;
1080       switch (MBBI->getOperand(0).getReg()) {
1081       case ARM::R4:  case ARM::R5:  case ARM::R6: case ARM::R7:
1082       case ARM::LR:
1083         Category = 1;
1084         break;
1085       case ARM::R8:  case ARM::R9:  case ARM::R10: case ARM::R11:
1086         Category = STI.isTargetDarwin() ? 2 : 1;
1087         break;
1088       case ARM::D8:  case ARM::D9:  case ARM::D10: case ARM::D11:
1089       case ARM::D12: case ARM::D13: case ARM::D14: case ARM::D15:
1090         Category = 3;
1091         break;
1092       default:
1093         Done = true;
1094         break;
1095       }
1096       if (Done || Category != Area)
1097         break;
1098     }
1099
1100     ++MBBI;
1101   }
1102 }
1103
1104 void ARMRegisterInfo::emitPrologue(MachineFunction &MF) const {
1105   MachineBasicBlock &MBB = MF.front();
1106   MachineBasicBlock::iterator MBBI = MBB.begin();
1107   MachineFrameInfo  *MFI = MF.getFrameInfo();
1108   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1109   bool isThumb = AFI->isThumbFunction();
1110   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1111   unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1112   unsigned NumBytes = MFI->getStackSize();
1113   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1114
1115   if (isThumb) {
1116     // Check if R3 is live in. It might have to be used as a scratch register.
1117     for (MachineFunction::livein_iterator I=MF.livein_begin(),E=MF.livein_end();
1118          I != E; ++I) {
1119       if ((*I).first == ARM::R3) {
1120         AFI->setR3IsLiveIn(true);
1121         break;
1122       }
1123     }
1124
1125     // Thumb add/sub sp, imm8 instructions implicitly multiply the offset by 4.
1126     NumBytes = (NumBytes + 3) & ~3;
1127     MFI->setStackSize(NumBytes);
1128   }
1129
1130   // Determine the sizes of each callee-save spill areas and record which frame
1131   // belongs to which callee-save spill areas.
1132   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
1133   int FramePtrSpillFI = 0;
1134
1135   if (VARegSaveSize)
1136     emitSPUpdate(MBB, MBBI, -VARegSaveSize, isThumb, TII);
1137
1138   if (!AFI->hasStackFrame()) {
1139     if (NumBytes != 0)
1140       emitSPUpdate(MBB, MBBI, -NumBytes, isThumb, TII);
1141     return;
1142   }
1143
1144   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1145     unsigned Reg = CSI[i].getReg();
1146     int FI = CSI[i].getFrameIdx();
1147     switch (Reg) {
1148     case ARM::R4:
1149     case ARM::R5:
1150     case ARM::R6:
1151     case ARM::R7:
1152     case ARM::LR:
1153       if (Reg == FramePtr)
1154         FramePtrSpillFI = FI;
1155       AFI->addGPRCalleeSavedArea1Frame(FI);
1156       GPRCS1Size += 4;
1157       break;
1158     case ARM::R8:
1159     case ARM::R9:
1160     case ARM::R10:
1161     case ARM::R11:
1162       if (Reg == FramePtr)
1163         FramePtrSpillFI = FI;
1164       if (STI.isTargetDarwin()) {
1165         AFI->addGPRCalleeSavedArea2Frame(FI);
1166         GPRCS2Size += 4;
1167       } else {
1168         AFI->addGPRCalleeSavedArea1Frame(FI);
1169         GPRCS1Size += 4;
1170       }
1171       break;
1172     default:
1173       AFI->addDPRCalleeSavedAreaFrame(FI);
1174       DPRCSSize += 8;
1175     }
1176   }
1177
1178   if (Align == 8 && (GPRCS1Size & 7) != 0)
1179     // Pad CS1 to ensure proper alignment.
1180     GPRCS1Size += 4;
1181
1182   if (!isThumb) {
1183     // Build the new SUBri to adjust SP for integer callee-save spill area 1.
1184     emitSPUpdate(MBB, MBBI, -GPRCS1Size, isThumb, TII);
1185     movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, 1, STI);
1186   } else if (MBBI != MBB.end() && MBBI->getOpcode() == ARM::tPUSH)
1187     ++MBBI;
1188
1189   // Darwin ABI requires FP to point to the stack slot that contains the
1190   // previous FP.
1191   if (STI.isTargetDarwin() || hasFP(MF))
1192     BuildMI(MBB, MBBI, TII.get(isThumb ? ARM::tADDrSPi : ARM::ADDri), FramePtr)
1193       .addFrameIndex(FramePtrSpillFI).addImm(0);
1194
1195   if (!isThumb) {
1196     // Build the new SUBri to adjust SP for integer callee-save spill area 2.
1197     emitSPUpdate(MBB, MBBI, -GPRCS2Size, false, TII);
1198
1199     // Build the new SUBri to adjust SP for FP callee-save spill area.
1200     movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, 2, STI);
1201     emitSPUpdate(MBB, MBBI, -DPRCSSize, false, TII);
1202   }
1203
1204   // Determine starting offsets of spill areas.
1205   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
1206   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
1207   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
1208   AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) + NumBytes);
1209   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
1210   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
1211   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
1212   
1213   NumBytes = DPRCSOffset;
1214   if (NumBytes) {
1215     // Insert it after all the callee-save spills.
1216     if (!isThumb)
1217       movePastCSLoadStoreOps(MBB, MBBI, ARM::FSTD, 3, STI);
1218     emitSPUpdate(MBB, MBBI, -NumBytes, isThumb, TII);
1219   }
1220
1221   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
1222   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
1223   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
1224 }
1225
1226 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
1227   for (unsigned i = 0; CSRegs[i]; ++i)
1228     if (Reg == CSRegs[i])
1229       return true;
1230   return false;
1231 }
1232
1233 static bool isCSRestore(MachineInstr *MI, const unsigned *CSRegs) {
1234   return ((MI->getOpcode() == ARM::FLDD ||
1235            MI->getOpcode() == ARM::LDR  ||
1236            MI->getOpcode() == ARM::tRestore) &&
1237           MI->getOperand(1).isFrameIndex() &&
1238           isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs));
1239 }
1240
1241 void ARMRegisterInfo::emitEpilogue(MachineFunction &MF,
1242                                    MachineBasicBlock &MBB) const {
1243   MachineBasicBlock::iterator MBBI = prior(MBB.end());
1244   assert((MBBI->getOpcode() == ARM::BX_RET ||
1245           MBBI->getOpcode() == ARM::tBX_RET ||
1246           MBBI->getOpcode() == ARM::tPOP_RET) &&
1247          "Can only insert epilog into returning blocks");
1248
1249   MachineFrameInfo *MFI = MF.getFrameInfo();
1250   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1251   bool isThumb = AFI->isThumbFunction();
1252   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1253   int NumBytes = (int)MFI->getStackSize();
1254   if (!AFI->hasStackFrame()) {
1255     if (NumBytes != 0)
1256       emitSPUpdate(MBB, MBBI, NumBytes, isThumb, TII);
1257   } else {
1258     // Unwind MBBI to point to first LDR / FLDD.
1259     const unsigned *CSRegs = getCalleeSavedRegs();
1260     if (MBBI != MBB.begin()) {
1261       do
1262         --MBBI;
1263       while (MBBI != MBB.begin() && isCSRestore(MBBI, CSRegs));
1264       if (!isCSRestore(MBBI, CSRegs))
1265         ++MBBI;
1266     }
1267
1268     // Move SP to start of FP callee save spill area.
1269     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
1270                  AFI->getGPRCalleeSavedArea2Size() +
1271                  AFI->getDPRCalleeSavedAreaSize());
1272     if (isThumb) {
1273       if (hasFP(MF)) {
1274         NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1275         // Reset SP based on frame pointer only if the stack frame extends beyond
1276         // frame pointer stack slot or target is ELF and the function has FP.
1277         if (NumBytes)
1278           emitThumbRegPlusImmediate(MBB, MBBI, ARM::SP, FramePtr, -NumBytes, TII);
1279         else
1280           BuildMI(MBB, MBBI, TII.get(ARM::tMOVrr), ARM::SP).addReg(FramePtr);
1281       } else {
1282         if (MBBI->getOpcode() == ARM::tBX_RET &&
1283             &MBB.front() != MBBI &&
1284             prior(MBBI)->getOpcode() == ARM::tPOP) {
1285           MachineBasicBlock::iterator PMBBI = prior(MBBI);
1286           emitSPUpdate(MBB, PMBBI, NumBytes, isThumb, TII);
1287         } else
1288           emitSPUpdate(MBB, MBBI, NumBytes, isThumb, TII);
1289       }
1290     } else {
1291       // Darwin ABI requires FP to point to the stack slot that contains the
1292       // previous FP.
1293       if (STI.isTargetDarwin() || hasFP(MF)) {
1294         NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1295         // Reset SP based on frame pointer only if the stack frame extends beyond
1296         // frame pointer stack slot or target is ELF and the function has FP.
1297         if (AFI->getGPRCalleeSavedArea2Size() ||
1298             AFI->getDPRCalleeSavedAreaSize()  ||
1299             AFI->getDPRCalleeSavedAreaOffset()||
1300             hasFP(MF))
1301           if (NumBytes)
1302             BuildMI(MBB, MBBI, TII.get(ARM::SUBri), ARM::SP).addReg(FramePtr)
1303               .addImm(NumBytes);
1304           else
1305             BuildMI(MBB, MBBI, TII.get(ARM::MOVrr), ARM::SP).addReg(FramePtr);
1306       } else if (NumBytes) {
1307         emitSPUpdate(MBB, MBBI, NumBytes, false, TII);
1308       }
1309
1310       // Move SP to start of integer callee save spill area 2.
1311       movePastCSLoadStoreOps(MBB, MBBI, ARM::FLDD, 3, STI);
1312       emitSPUpdate(MBB, MBBI, AFI->getDPRCalleeSavedAreaSize(), false, TII);
1313
1314       // Move SP to start of integer callee save spill area 1.
1315       movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, 2, STI);
1316       emitSPUpdate(MBB, MBBI, AFI->getGPRCalleeSavedArea2Size(), false, TII);
1317
1318       // Move SP to SP upon entry to the function.
1319       movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, 1, STI);
1320       emitSPUpdate(MBB, MBBI, AFI->getGPRCalleeSavedArea1Size(), false, TII);
1321     }
1322   }
1323
1324   if (VARegSaveSize) {
1325     if (isThumb)
1326       // Epilogue for vararg functions: pop LR to R3 and branch off it.
1327       // FIXME: Verify this is still ok when R3 is no longer being reserved.
1328       BuildMI(MBB, MBBI, TII.get(ARM::tPOP)).addReg(ARM::R3);
1329
1330     emitSPUpdate(MBB, MBBI, VARegSaveSize, isThumb, TII);
1331
1332     if (isThumb) {
1333       BuildMI(MBB, MBBI, TII.get(ARM::tBX_RET_vararg)).addReg(ARM::R3);
1334       MBB.erase(MBBI);
1335     }
1336   }
1337 }
1338
1339 unsigned ARMRegisterInfo::getRARegister() const {
1340   return ARM::LR;
1341 }
1342
1343 unsigned ARMRegisterInfo::getFrameRegister(MachineFunction &MF) const {
1344   return STI.useThumbBacktraces() ? ARM::R7 : ARM::R11;
1345 }
1346
1347 unsigned ARMRegisterInfo::getEHExceptionRegister() const {
1348   assert(0 && "What is the exception register");
1349   return 0;
1350 }
1351
1352 unsigned ARMRegisterInfo::getEHHandlerRegister() const {
1353   assert(0 && "What is the exception handler register");
1354   return 0;
1355 }
1356
1357 #include "ARMGenRegisterInfo.inc"
1358