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