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