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