use DebugLoc default ctor instead of DebugLoc::getUnknownLoc()
[oota-llvm.git] / lib / Target / ARM / ARMBaseRegisterInfo.cpp
1 //===- ARMBaseRegisterInfo.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 base ARM implementation of TargetRegisterInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARM.h"
15 #include "ARMAddressingModes.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMInstrInfo.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMSubtarget.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/LLVMContext.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineLocation.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/RegisterScavenging.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetFrameInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/BitVector.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/Support/CommandLine.h"
41 using namespace llvm;
42
43 cl::opt<bool>
44 ReuseFrameIndexVals("arm-reuse-frame-index-vals", cl::Hidden, cl::init(true),
45           cl::desc("Reuse repeated frame index values"));
46
47 unsigned ARMBaseRegisterInfo::getRegisterNumbering(unsigned RegEnum,
48                                                    bool *isSPVFP) {
49   if (isSPVFP)
50     *isSPVFP = false;
51
52   using namespace ARM;
53   switch (RegEnum) {
54   default:
55     llvm_unreachable("Unknown ARM register!");
56   case R0:  case D0:  case Q0:  return 0;
57   case R1:  case D1:  case Q1:  return 1;
58   case R2:  case D2:  case Q2:  return 2;
59   case R3:  case D3:  case Q3:  return 3;
60   case R4:  case D4:  case Q4:  return 4;
61   case R5:  case D5:  case Q5:  return 5;
62   case R6:  case D6:  case Q6:  return 6;
63   case R7:  case D7:  case Q7:  return 7;
64   case R8:  case D8:  case Q8:  return 8;
65   case R9:  case D9:  case Q9:  return 9;
66   case R10: case D10: case Q10: return 10;
67   case R11: case D11: case Q11: return 11;
68   case R12: case D12: case Q12: return 12;
69   case SP:  case D13: case Q13: return 13;
70   case LR:  case D14: case Q14: return 14;
71   case PC:  case D15: case Q15: return 15;
72
73   case D16: return 16;
74   case D17: return 17;
75   case D18: return 18;
76   case D19: return 19;
77   case D20: return 20;
78   case D21: return 21;
79   case D22: return 22;
80   case D23: return 23;
81   case D24: return 24;
82   case D25: return 25;
83   case D26: return 26;
84   case D27: return 27;
85   case D28: return 28;
86   case D29: return 29;
87   case D30: return 30;
88   case D31: return 31;
89
90   case S0: case S1: case S2: case S3:
91   case S4: case S5: case S6: case S7:
92   case S8: case S9: case S10: case S11:
93   case S12: case S13: case S14: case S15:
94   case S16: case S17: case S18: case S19:
95   case S20: case S21: case S22: case S23:
96   case S24: case S25: case S26: case S27:
97   case S28: case S29: case S30: case S31: {
98     if (isSPVFP)
99       *isSPVFP = true;
100     switch (RegEnum) {
101     default: return 0; // Avoid compile time warning.
102     case S0: return 0;
103     case S1: return 1;
104     case S2: return 2;
105     case S3: return 3;
106     case S4: return 4;
107     case S5: return 5;
108     case S6: return 6;
109     case S7: return 7;
110     case S8: return 8;
111     case S9: return 9;
112     case S10: return 10;
113     case S11: return 11;
114     case S12: return 12;
115     case S13: return 13;
116     case S14: return 14;
117     case S15: return 15;
118     case S16: return 16;
119     case S17: return 17;
120     case S18: return 18;
121     case S19: return 19;
122     case S20: return 20;
123     case S21: return 21;
124     case S22: return 22;
125     case S23: return 23;
126     case S24: return 24;
127     case S25: return 25;
128     case S26: return 26;
129     case S27: return 27;
130     case S28: return 28;
131     case S29: return 29;
132     case S30: return 30;
133     case S31: return 31;
134     }
135   }
136   }
137 }
138
139 ARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMBaseInstrInfo &tii,
140                                          const ARMSubtarget &sti)
141   : ARMGenRegisterInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
142     TII(tii), STI(sti),
143     FramePtr((STI.isTargetDarwin() || STI.isThumb()) ? ARM::R7 : ARM::R11) {
144 }
145
146 const unsigned*
147 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
148   static const unsigned CalleeSavedRegs[] = {
149     ARM::LR, ARM::R11, ARM::R10, ARM::R9, ARM::R8,
150     ARM::R7, ARM::R6,  ARM::R5,  ARM::R4,
151
152     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
153     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
154     0
155   };
156
157   static const unsigned DarwinCalleeSavedRegs[] = {
158     // Darwin ABI deviates from ARM standard ABI. R9 is not a callee-saved
159     // register.
160     ARM::LR,  ARM::R7,  ARM::R6, ARM::R5, ARM::R4,
161     ARM::R11, ARM::R10, ARM::R8,
162
163     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
164     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
165     0
166   };
167   return STI.isTargetDarwin() ? DarwinCalleeSavedRegs : CalleeSavedRegs;
168 }
169
170 const TargetRegisterClass* const *
171 ARMBaseRegisterInfo::getCalleeSavedRegClasses(const MachineFunction *MF) const {
172   static const TargetRegisterClass * const CalleeSavedRegClasses[] = {
173     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
174     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
175     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
176
177     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
178     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
179     0
180   };
181
182   static const TargetRegisterClass * const ThumbCalleeSavedRegClasses[] = {
183     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
184     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::tGPRRegClass,
185     &ARM::tGPRRegClass,&ARM::tGPRRegClass,&ARM::tGPRRegClass,
186
187     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
188     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
189     0
190   };
191
192   static const TargetRegisterClass * const DarwinCalleeSavedRegClasses[] = {
193     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
194     &ARM::GPRRegClass, &ARM::GPRRegClass, &ARM::GPRRegClass,
195     &ARM::GPRRegClass, &ARM::GPRRegClass,
196
197     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
198     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
199     0
200   };
201
202   static const TargetRegisterClass * const DarwinThumbCalleeSavedRegClasses[] ={
203     &ARM::GPRRegClass,  &ARM::tGPRRegClass, &ARM::tGPRRegClass,
204     &ARM::tGPRRegClass, &ARM::tGPRRegClass, &ARM::GPRRegClass,
205     &ARM::GPRRegClass,  &ARM::GPRRegClass,
206
207     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
208     &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass, &ARM::DPRRegClass,
209     0
210   };
211
212   if (STI.isThumb1Only()) {
213     return STI.isTargetDarwin()
214       ? DarwinThumbCalleeSavedRegClasses : ThumbCalleeSavedRegClasses;
215   }
216   return STI.isTargetDarwin()
217     ? DarwinCalleeSavedRegClasses : CalleeSavedRegClasses;
218 }
219
220 BitVector ARMBaseRegisterInfo::
221 getReservedRegs(const MachineFunction &MF) const {
222   // FIXME: avoid re-calculating this everytime.
223   BitVector Reserved(getNumRegs());
224   Reserved.set(ARM::SP);
225   Reserved.set(ARM::PC);
226   if (STI.isTargetDarwin() || hasFP(MF))
227     Reserved.set(FramePtr);
228   // Some targets reserve R9.
229   if (STI.isR9Reserved())
230     Reserved.set(ARM::R9);
231   return Reserved;
232 }
233
234 bool ARMBaseRegisterInfo::isReservedReg(const MachineFunction &MF,
235                                         unsigned Reg) const {
236   switch (Reg) {
237   default: break;
238   case ARM::SP:
239   case ARM::PC:
240     return true;
241   case ARM::R7:
242   case ARM::R11:
243     if (FramePtr == Reg && (STI.isTargetDarwin() || hasFP(MF)))
244       return true;
245     break;
246   case ARM::R9:
247     return STI.isR9Reserved();
248   }
249
250   return false;
251 }
252
253 const TargetRegisterClass *
254 ARMBaseRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
255                                               const TargetRegisterClass *B,
256                                               unsigned SubIdx) const {
257   switch (SubIdx) {
258   default: return 0;
259   case 1:
260   case 2:
261   case 3:
262   case 4:
263     // S sub-registers.
264     if (A->getSize() == 8) {
265       if (B == &ARM::SPR_8RegClass)
266         return &ARM::DPR_8RegClass;
267       assert(B == &ARM::SPRRegClass && "Expecting SPR register class!");
268       if (A == &ARM::DPR_8RegClass)
269         return A;
270       return &ARM::DPR_VFP2RegClass;
271     }
272
273     assert(A->getSize() == 16 && "Expecting a Q register class!");
274     if (B == &ARM::SPR_8RegClass)
275       return &ARM::QPR_8RegClass;
276     return &ARM::QPR_VFP2RegClass;
277   case 5:
278   case 6:
279     // D sub-registers.
280     if (B == &ARM::DPR_VFP2RegClass)
281       return &ARM::QPR_VFP2RegClass;
282     if (B == &ARM::DPR_8RegClass)
283       return &ARM::QPR_8RegClass;
284     return A;
285   }
286   return 0;
287 }
288
289 const TargetRegisterClass *
290 ARMBaseRegisterInfo::getPointerRegClass(unsigned Kind) const {
291   return ARM::GPRRegisterClass;
292 }
293
294 /// getAllocationOrder - Returns the register allocation order for a specified
295 /// register class in the form of a pair of TargetRegisterClass iterators.
296 std::pair<TargetRegisterClass::iterator,TargetRegisterClass::iterator>
297 ARMBaseRegisterInfo::getAllocationOrder(const TargetRegisterClass *RC,
298                                         unsigned HintType, unsigned HintReg,
299                                         const MachineFunction &MF) const {
300   // Alternative register allocation orders when favoring even / odd registers
301   // of register pairs.
302
303   // No FP, R9 is available.
304   static const unsigned GPREven1[] = {
305     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8, ARM::R10,
306     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7,
307     ARM::R9, ARM::R11
308   };
309   static const unsigned GPROdd1[] = {
310     ARM::R1, ARM::R3, ARM::R5, ARM::R7, ARM::R9, ARM::R11,
311     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
312     ARM::R8, ARM::R10
313   };
314
315   // FP is R7, R9 is available.
316   static const unsigned GPREven2[] = {
317     ARM::R0, ARM::R2, ARM::R4,          ARM::R8, ARM::R10,
318     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6,
319     ARM::R9, ARM::R11
320   };
321   static const unsigned GPROdd2[] = {
322     ARM::R1, ARM::R3, ARM::R5,          ARM::R9, ARM::R11,
323     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
324     ARM::R8, ARM::R10
325   };
326
327   // FP is R11, R9 is available.
328   static const unsigned GPREven3[] = {
329     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8,
330     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7,
331     ARM::R9
332   };
333   static const unsigned GPROdd3[] = {
334     ARM::R1, ARM::R3, ARM::R5, ARM::R6, ARM::R9,
335     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R7,
336     ARM::R8
337   };
338
339   // No FP, R9 is not available.
340   static const unsigned GPREven4[] = {
341     ARM::R0, ARM::R2, ARM::R4, ARM::R6,          ARM::R10,
342     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8,
343     ARM::R11
344   };
345   static const unsigned GPROdd4[] = {
346     ARM::R1, ARM::R3, ARM::R5, ARM::R7,          ARM::R11,
347     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
348     ARM::R10
349   };
350
351   // FP is R7, R9 is not available.
352   static const unsigned GPREven5[] = {
353     ARM::R0, ARM::R2, ARM::R4,                   ARM::R10,
354     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6, ARM::R8,
355     ARM::R11
356   };
357   static const unsigned GPROdd5[] = {
358     ARM::R1, ARM::R3, ARM::R5,                   ARM::R11,
359     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
360     ARM::R10
361   };
362
363   // FP is R11, R9 is not available.
364   static const unsigned GPREven6[] = {
365     ARM::R0, ARM::R2, ARM::R4, ARM::R6,
366     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8
367   };
368   static const unsigned GPROdd6[] = {
369     ARM::R1, ARM::R3, ARM::R5, ARM::R7,
370     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8
371   };
372
373
374   if (HintType == ARMRI::RegPairEven) {
375     if (isPhysicalRegister(HintReg) && getRegisterPairEven(HintReg, MF) == 0)
376       // It's no longer possible to fulfill this hint. Return the default
377       // allocation order.
378       return std::make_pair(RC->allocation_order_begin(MF),
379                             RC->allocation_order_end(MF));
380
381     if (!STI.isTargetDarwin() && !hasFP(MF)) {
382       if (!STI.isR9Reserved())
383         return std::make_pair(GPREven1,
384                               GPREven1 + (sizeof(GPREven1)/sizeof(unsigned)));
385       else
386         return std::make_pair(GPREven4,
387                               GPREven4 + (sizeof(GPREven4)/sizeof(unsigned)));
388     } else if (FramePtr == ARM::R7) {
389       if (!STI.isR9Reserved())
390         return std::make_pair(GPREven2,
391                               GPREven2 + (sizeof(GPREven2)/sizeof(unsigned)));
392       else
393         return std::make_pair(GPREven5,
394                               GPREven5 + (sizeof(GPREven5)/sizeof(unsigned)));
395     } else { // FramePtr == ARM::R11
396       if (!STI.isR9Reserved())
397         return std::make_pair(GPREven3,
398                               GPREven3 + (sizeof(GPREven3)/sizeof(unsigned)));
399       else
400         return std::make_pair(GPREven6,
401                               GPREven6 + (sizeof(GPREven6)/sizeof(unsigned)));
402     }
403   } else if (HintType == ARMRI::RegPairOdd) {
404     if (isPhysicalRegister(HintReg) && getRegisterPairOdd(HintReg, MF) == 0)
405       // It's no longer possible to fulfill this hint. Return the default
406       // allocation order.
407       return std::make_pair(RC->allocation_order_begin(MF),
408                             RC->allocation_order_end(MF));
409
410     if (!STI.isTargetDarwin() && !hasFP(MF)) {
411       if (!STI.isR9Reserved())
412         return std::make_pair(GPROdd1,
413                               GPROdd1 + (sizeof(GPROdd1)/sizeof(unsigned)));
414       else
415         return std::make_pair(GPROdd4,
416                               GPROdd4 + (sizeof(GPROdd4)/sizeof(unsigned)));
417     } else if (FramePtr == ARM::R7) {
418       if (!STI.isR9Reserved())
419         return std::make_pair(GPROdd2,
420                               GPROdd2 + (sizeof(GPROdd2)/sizeof(unsigned)));
421       else
422         return std::make_pair(GPROdd5,
423                               GPROdd5 + (sizeof(GPROdd5)/sizeof(unsigned)));
424     } else { // FramePtr == ARM::R11
425       if (!STI.isR9Reserved())
426         return std::make_pair(GPROdd3,
427                               GPROdd3 + (sizeof(GPROdd3)/sizeof(unsigned)));
428       else
429         return std::make_pair(GPROdd6,
430                               GPROdd6 + (sizeof(GPROdd6)/sizeof(unsigned)));
431     }
432   }
433   return std::make_pair(RC->allocation_order_begin(MF),
434                         RC->allocation_order_end(MF));
435 }
436
437 /// ResolveRegAllocHint - Resolves the specified register allocation hint
438 /// to a physical register. Returns the physical register if it is successful.
439 unsigned
440 ARMBaseRegisterInfo::ResolveRegAllocHint(unsigned Type, unsigned Reg,
441                                          const MachineFunction &MF) const {
442   if (Reg == 0 || !isPhysicalRegister(Reg))
443     return 0;
444   if (Type == 0)
445     return Reg;
446   else if (Type == (unsigned)ARMRI::RegPairOdd)
447     // Odd register.
448     return getRegisterPairOdd(Reg, MF);
449   else if (Type == (unsigned)ARMRI::RegPairEven)
450     // Even register.
451     return getRegisterPairEven(Reg, MF);
452   return 0;
453 }
454
455 void
456 ARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
457                                         MachineFunction &MF) const {
458   MachineRegisterInfo *MRI = &MF.getRegInfo();
459   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
460   if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
461        Hint.first == (unsigned)ARMRI::RegPairEven) &&
462       Hint.second && TargetRegisterInfo::isVirtualRegister(Hint.second)) {
463     // If 'Reg' is one of the even / odd register pair and it's now changed
464     // (e.g. coalesced) into a different register. The other register of the
465     // pair allocation hint must be updated to reflect the relationship
466     // change.
467     unsigned OtherReg = Hint.second;
468     Hint = MRI->getRegAllocationHint(OtherReg);
469     if (Hint.second == Reg)
470       // Make sure the pair has not already divorced.
471       MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
472   }
473 }
474
475 /// hasFP - Return true if the specified function should have a dedicated frame
476 /// pointer register.  This is true if the function has variable sized allocas
477 /// or if frame pointer elimination is disabled.
478 ///
479 bool ARMBaseRegisterInfo::hasFP(const MachineFunction &MF) const {
480   const MachineFrameInfo *MFI = MF.getFrameInfo();
481   return ((NoFramePointerElim && MFI->hasCalls())||
482           needsStackRealignment(MF) ||
483           MFI->hasVarSizedObjects() ||
484           MFI->isFrameAddressTaken());
485 }
486
487 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
488   const MachineFrameInfo *MFI = MF.getFrameInfo();
489   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
490   return (RealignStack &&
491           !AFI->isThumb1OnlyFunction() &&
492           !MFI->hasVarSizedObjects());
493 }
494
495 bool ARMBaseRegisterInfo::
496 needsStackRealignment(const MachineFunction &MF) const {
497   const MachineFrameInfo *MFI = MF.getFrameInfo();
498   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
499   unsigned StackAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
500   return (RealignStack &&
501           !AFI->isThumb1OnlyFunction() &&
502           (MFI->getMaxAlignment() > StackAlign) &&
503           !MFI->hasVarSizedObjects());
504 }
505
506 bool ARMBaseRegisterInfo::
507 cannotEliminateFrame(const MachineFunction &MF) const {
508   const MachineFrameInfo *MFI = MF.getFrameInfo();
509   if (NoFramePointerElim && MFI->hasCalls())
510     return true;
511   return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
512     || needsStackRealignment(MF);
513 }
514
515 /// estimateStackSize - Estimate and return the size of the frame.
516 static unsigned estimateStackSize(MachineFunction &MF) {
517   const MachineFrameInfo *FFI = MF.getFrameInfo();
518   int Offset = 0;
519   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
520     int FixedOff = -FFI->getObjectOffset(i);
521     if (FixedOff > Offset) Offset = FixedOff;
522   }
523   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
524     if (FFI->isDeadObjectIndex(i))
525       continue;
526     Offset += FFI->getObjectSize(i);
527     unsigned Align = FFI->getObjectAlignment(i);
528     // Adjust to alignment boundary
529     Offset = (Offset+Align-1)/Align*Align;
530   }
531   return (unsigned)Offset;
532 }
533
534 /// estimateRSStackSizeLimit - Look at each instruction that references stack
535 /// frames and return the stack size limit beyond which some of these
536 /// instructions will require a scratch register during their expansion later.
537 unsigned
538 ARMBaseRegisterInfo::estimateRSStackSizeLimit(MachineFunction &MF) const {
539   unsigned Limit = (1 << 12) - 1;
540   for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
541     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
542          I != E; ++I) {
543       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
544         if (!I->getOperand(i).isFI()) continue;
545
546         const TargetInstrDesc &Desc = TII.get(I->getOpcode());
547         unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
548         if (AddrMode == ARMII::AddrMode3 ||
549             AddrMode == ARMII::AddrModeT2_i8)
550           return (1 << 8) - 1;
551
552         if (AddrMode == ARMII::AddrMode5 ||
553             AddrMode == ARMII::AddrModeT2_i8s4)
554           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
555
556         if (AddrMode == ARMII::AddrModeT2_i12 && hasFP(MF))
557           // When the stack offset is negative, we will end up using
558           // the i8 instructions instead.
559           return (1 << 8) - 1;
560
561         if (AddrMode == ARMII::AddrMode6)
562           return 0;
563         break; // At most one FI per instruction
564       }
565     }
566   }
567
568   return Limit;
569 }
570
571 void
572 ARMBaseRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
573                                                        RegScavenger *RS) const {
574   // This tells PEI to spill the FP as if it is any other callee-save register
575   // to take advantage the eliminateFrameIndex machinery. This also ensures it
576   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
577   // to combine multiple loads / stores.
578   bool CanEliminateFrame = true;
579   bool CS1Spilled = false;
580   bool LRSpilled = false;
581   unsigned NumGPRSpills = 0;
582   SmallVector<unsigned, 4> UnspilledCS1GPRs;
583   SmallVector<unsigned, 4> UnspilledCS2GPRs;
584   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
585
586   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
587   // scratch register.
588   // FIXME: It will be better just to find spare register here.
589   if (needsStackRealignment(MF) &&
590       AFI->isThumb2Function())
591     MF.getRegInfo().setPhysRegUsed(ARM::R4);
592
593   // Spill LR if Thumb1 function uses variable length argument lists.
594   if (AFI->isThumb1OnlyFunction() && AFI->getVarArgsRegSaveSize() > 0)
595     MF.getRegInfo().setPhysRegUsed(ARM::LR);
596
597   // Don't spill FP if the frame can be eliminated. This is determined
598   // by scanning the callee-save registers to see if any is used.
599   const unsigned *CSRegs = getCalleeSavedRegs();
600   const TargetRegisterClass* const *CSRegClasses = getCalleeSavedRegClasses();
601   for (unsigned i = 0; CSRegs[i]; ++i) {
602     unsigned Reg = CSRegs[i];
603     bool Spilled = false;
604     if (MF.getRegInfo().isPhysRegUsed(Reg)) {
605       AFI->setCSRegisterIsSpilled(Reg);
606       Spilled = true;
607       CanEliminateFrame = false;
608     } else {
609       // Check alias registers too.
610       for (const unsigned *Aliases = getAliasSet(Reg); *Aliases; ++Aliases) {
611         if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
612           Spilled = true;
613           CanEliminateFrame = false;
614         }
615       }
616     }
617
618     if (CSRegClasses[i] == ARM::GPRRegisterClass ||
619         CSRegClasses[i] == ARM::tGPRRegisterClass) {
620       if (Spilled) {
621         NumGPRSpills++;
622
623         if (!STI.isTargetDarwin()) {
624           if (Reg == ARM::LR)
625             LRSpilled = true;
626           CS1Spilled = true;
627           continue;
628         }
629
630         // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
631         switch (Reg) {
632         case ARM::LR:
633           LRSpilled = true;
634           // Fallthrough
635         case ARM::R4:
636         case ARM::R5:
637         case ARM::R6:
638         case ARM::R7:
639           CS1Spilled = true;
640           break;
641         default:
642           break;
643         }
644       } else {
645         if (!STI.isTargetDarwin()) {
646           UnspilledCS1GPRs.push_back(Reg);
647           continue;
648         }
649
650         switch (Reg) {
651         case ARM::R4:
652         case ARM::R5:
653         case ARM::R6:
654         case ARM::R7:
655         case ARM::LR:
656           UnspilledCS1GPRs.push_back(Reg);
657           break;
658         default:
659           UnspilledCS2GPRs.push_back(Reg);
660           break;
661         }
662       }
663     }
664   }
665
666   bool ForceLRSpill = false;
667   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
668     unsigned FnSize = TII.GetFunctionSizeInBytes(MF);
669     // Force LR to be spilled if the Thumb function size is > 2048. This enables
670     // use of BL to implement far jump. If it turns out that it's not needed
671     // then the branch fix up path will undo it.
672     if (FnSize >= (1 << 11)) {
673       CanEliminateFrame = false;
674       ForceLRSpill = true;
675     }
676   }
677
678   // If any of the stack slot references may be out of range of an immediate
679   // offset, make sure a register (or a spill slot) is available for the
680   // register scavenger. Note that if we're indexing off the frame pointer, the
681   // effective stack size is 4 bytes larger since the FP points to the stack
682   // slot of the previous FP.
683   bool BigStack = RS &&
684     estimateStackSize(MF) + (hasFP(MF) ? 4 : 0) >= estimateRSStackSizeLimit(MF);
685
686   bool ExtraCSSpill = false;
687   if (BigStack || !CanEliminateFrame || cannotEliminateFrame(MF)) {
688     AFI->setHasStackFrame(true);
689
690     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
691     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
692     if (!LRSpilled && CS1Spilled) {
693       MF.getRegInfo().setPhysRegUsed(ARM::LR);
694       AFI->setCSRegisterIsSpilled(ARM::LR);
695       NumGPRSpills++;
696       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
697                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
698       ForceLRSpill = false;
699       ExtraCSSpill = true;
700     }
701
702     // Darwin ABI requires FP to point to the stack slot that contains the
703     // previous FP.
704     if (STI.isTargetDarwin() || hasFP(MF)) {
705       MF.getRegInfo().setPhysRegUsed(FramePtr);
706       NumGPRSpills++;
707     }
708
709     // If stack and double are 8-byte aligned and we are spilling an odd number
710     // of GPRs. Spill one extra callee save GPR so we won't have to pad between
711     // the integer and double callee save areas.
712     unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
713     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
714       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
715         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
716           unsigned Reg = UnspilledCS1GPRs[i];
717           // Don't spill high register if the function is thumb1
718           if (!AFI->isThumb1OnlyFunction() ||
719               isARMLowRegister(Reg) || Reg == ARM::LR) {
720             MF.getRegInfo().setPhysRegUsed(Reg);
721             AFI->setCSRegisterIsSpilled(Reg);
722             if (!isReservedReg(MF, Reg))
723               ExtraCSSpill = true;
724             break;
725           }
726         }
727       } else if (!UnspilledCS2GPRs.empty() &&
728                  !AFI->isThumb1OnlyFunction()) {
729         unsigned Reg = UnspilledCS2GPRs.front();
730         MF.getRegInfo().setPhysRegUsed(Reg);
731         AFI->setCSRegisterIsSpilled(Reg);
732         if (!isReservedReg(MF, Reg))
733           ExtraCSSpill = true;
734       }
735     }
736
737     // Estimate if we might need to scavenge a register at some point in order
738     // to materialize a stack offset. If so, either spill one additional
739     // callee-saved register or reserve a special spill slot to facilitate
740     // register scavenging. Thumb1 needs a spill slot for stack pointer
741     // adjustments also, even when the frame itself is small.
742     if (BigStack && !ExtraCSSpill) {
743       // If any non-reserved CS register isn't spilled, just spill one or two
744       // extra. That should take care of it!
745       unsigned NumExtras = TargetAlign / 4;
746       SmallVector<unsigned, 2> Extras;
747       while (NumExtras && !UnspilledCS1GPRs.empty()) {
748         unsigned Reg = UnspilledCS1GPRs.back();
749         UnspilledCS1GPRs.pop_back();
750         if (!isReservedReg(MF, Reg)) {
751           Extras.push_back(Reg);
752           NumExtras--;
753         }
754       }
755       // For non-Thumb1 functions, also check for hi-reg CS registers
756       if (!AFI->isThumb1OnlyFunction()) {
757         while (NumExtras && !UnspilledCS2GPRs.empty()) {
758           unsigned Reg = UnspilledCS2GPRs.back();
759           UnspilledCS2GPRs.pop_back();
760           if (!isReservedReg(MF, Reg)) {
761             Extras.push_back(Reg);
762             NumExtras--;
763           }
764         }
765       }
766       if (Extras.size() && NumExtras == 0) {
767         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
768           MF.getRegInfo().setPhysRegUsed(Extras[i]);
769           AFI->setCSRegisterIsSpilled(Extras[i]);
770         }
771       } else if (!AFI->isThumb1OnlyFunction()) {
772         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
773         // closest to SP or frame pointer.
774         const TargetRegisterClass *RC = ARM::GPRRegisterClass;
775         MachineFrameInfo *MFI = MF.getFrameInfo();
776         RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
777                                                            RC->getAlignment(),
778                                                            false));
779       }
780     }
781   }
782
783   if (ForceLRSpill) {
784     MF.getRegInfo().setPhysRegUsed(ARM::LR);
785     AFI->setCSRegisterIsSpilled(ARM::LR);
786     AFI->setLRIsSpilledForFarJump(true);
787   }
788 }
789
790 unsigned ARMBaseRegisterInfo::getRARegister() const {
791   return ARM::LR;
792 }
793
794 unsigned 
795 ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
796   if (STI.isTargetDarwin() || hasFP(MF))
797     return FramePtr;
798   return ARM::SP;
799 }
800
801 int
802 ARMBaseRegisterInfo::getFrameIndexReference(const MachineFunction &MF, int FI,
803                                             unsigned &FrameReg) const {
804   const MachineFrameInfo *MFI = MF.getFrameInfo();
805   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
806   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
807   bool isFixed = MFI->isFixedObjectIndex(FI);
808
809   FrameReg = ARM::SP;
810   if (AFI->isGPRCalleeSavedArea1Frame(FI))
811     Offset -= AFI->getGPRCalleeSavedArea1Offset();
812   else if (AFI->isGPRCalleeSavedArea2Frame(FI))
813     Offset -= AFI->getGPRCalleeSavedArea2Offset();
814   else if (AFI->isDPRCalleeSavedAreaFrame(FI))
815     Offset -= AFI->getDPRCalleeSavedAreaOffset();
816   else if (needsStackRealignment(MF)) {
817     // When dynamically realigning the stack, use the frame pointer for
818     // parameters, and the stack pointer for locals.
819     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
820     if (isFixed) {
821       FrameReg = getFrameRegister(MF);
822       Offset -= AFI->getFramePtrSpillOffset();
823     }
824   } else if (hasFP(MF) && AFI->hasStackFrame()) {
825     if (isFixed || MFI->hasVarSizedObjects()) {
826       // Use frame pointer to reference fixed objects unless this is a
827       // frameless function.
828       FrameReg = getFrameRegister(MF);
829       Offset -= AFI->getFramePtrSpillOffset();
830     } else if (AFI->isThumb2Function()) {
831       // In Thumb2 mode, the negative offset is very limited.
832       int FPOffset = Offset - AFI->getFramePtrSpillOffset();
833       if (FPOffset >= -255 && FPOffset < 0) {
834         FrameReg = getFrameRegister(MF);
835         Offset = FPOffset;
836       }
837     }
838   }
839   return Offset;
840 }
841
842
843 int
844 ARMBaseRegisterInfo::getFrameIndexOffset(const MachineFunction &MF,
845                                          int FI) const {
846   unsigned FrameReg;
847   return getFrameIndexReference(MF, FI, FrameReg);
848 }
849
850 unsigned ARMBaseRegisterInfo::getEHExceptionRegister() const {
851   llvm_unreachable("What is the exception register");
852   return 0;
853 }
854
855 unsigned ARMBaseRegisterInfo::getEHHandlerRegister() const {
856   llvm_unreachable("What is the exception handler register");
857   return 0;
858 }
859
860 int ARMBaseRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
861   return ARMGenRegisterInfo::getDwarfRegNumFull(RegNum, 0);
862 }
863
864 unsigned ARMBaseRegisterInfo::getRegisterPairEven(unsigned Reg,
865                                               const MachineFunction &MF) const {
866   switch (Reg) {
867   default: break;
868   // Return 0 if either register of the pair is a special register.
869   // So no R12, etc.
870   case ARM::R1:
871     return ARM::R0;
872   case ARM::R3:
873     return ARM::R2;
874   case ARM::R5:
875     return ARM::R4;
876   case ARM::R7:
877     return isReservedReg(MF, ARM::R7)  ? 0 : ARM::R6;
878   case ARM::R9:
879     return isReservedReg(MF, ARM::R9)  ? 0 :ARM::R8;
880   case ARM::R11:
881     return isReservedReg(MF, ARM::R11) ? 0 : ARM::R10;
882
883   case ARM::S1:
884     return ARM::S0;
885   case ARM::S3:
886     return ARM::S2;
887   case ARM::S5:
888     return ARM::S4;
889   case ARM::S7:
890     return ARM::S6;
891   case ARM::S9:
892     return ARM::S8;
893   case ARM::S11:
894     return ARM::S10;
895   case ARM::S13:
896     return ARM::S12;
897   case ARM::S15:
898     return ARM::S14;
899   case ARM::S17:
900     return ARM::S16;
901   case ARM::S19:
902     return ARM::S18;
903   case ARM::S21:
904     return ARM::S20;
905   case ARM::S23:
906     return ARM::S22;
907   case ARM::S25:
908     return ARM::S24;
909   case ARM::S27:
910     return ARM::S26;
911   case ARM::S29:
912     return ARM::S28;
913   case ARM::S31:
914     return ARM::S30;
915
916   case ARM::D1:
917     return ARM::D0;
918   case ARM::D3:
919     return ARM::D2;
920   case ARM::D5:
921     return ARM::D4;
922   case ARM::D7:
923     return ARM::D6;
924   case ARM::D9:
925     return ARM::D8;
926   case ARM::D11:
927     return ARM::D10;
928   case ARM::D13:
929     return ARM::D12;
930   case ARM::D15:
931     return ARM::D14;
932   case ARM::D17:
933     return ARM::D16;
934   case ARM::D19:
935     return ARM::D18;
936   case ARM::D21:
937     return ARM::D20;
938   case ARM::D23:
939     return ARM::D22;
940   case ARM::D25:
941     return ARM::D24;
942   case ARM::D27:
943     return ARM::D26;
944   case ARM::D29:
945     return ARM::D28;
946   case ARM::D31:
947     return ARM::D30;
948   }
949
950   return 0;
951 }
952
953 unsigned ARMBaseRegisterInfo::getRegisterPairOdd(unsigned Reg,
954                                              const MachineFunction &MF) const {
955   switch (Reg) {
956   default: break;
957   // Return 0 if either register of the pair is a special register.
958   // So no R12, etc.
959   case ARM::R0:
960     return ARM::R1;
961   case ARM::R2:
962     return ARM::R3;
963   case ARM::R4:
964     return ARM::R5;
965   case ARM::R6:
966     return isReservedReg(MF, ARM::R7)  ? 0 : ARM::R7;
967   case ARM::R8:
968     return isReservedReg(MF, ARM::R9)  ? 0 :ARM::R9;
969   case ARM::R10:
970     return isReservedReg(MF, ARM::R11) ? 0 : ARM::R11;
971
972   case ARM::S0:
973     return ARM::S1;
974   case ARM::S2:
975     return ARM::S3;
976   case ARM::S4:
977     return ARM::S5;
978   case ARM::S6:
979     return ARM::S7;
980   case ARM::S8:
981     return ARM::S9;
982   case ARM::S10:
983     return ARM::S11;
984   case ARM::S12:
985     return ARM::S13;
986   case ARM::S14:
987     return ARM::S15;
988   case ARM::S16:
989     return ARM::S17;
990   case ARM::S18:
991     return ARM::S19;
992   case ARM::S20:
993     return ARM::S21;
994   case ARM::S22:
995     return ARM::S23;
996   case ARM::S24:
997     return ARM::S25;
998   case ARM::S26:
999     return ARM::S27;
1000   case ARM::S28:
1001     return ARM::S29;
1002   case ARM::S30:
1003     return ARM::S31;
1004
1005   case ARM::D0:
1006     return ARM::D1;
1007   case ARM::D2:
1008     return ARM::D3;
1009   case ARM::D4:
1010     return ARM::D5;
1011   case ARM::D6:
1012     return ARM::D7;
1013   case ARM::D8:
1014     return ARM::D9;
1015   case ARM::D10:
1016     return ARM::D11;
1017   case ARM::D12:
1018     return ARM::D13;
1019   case ARM::D14:
1020     return ARM::D15;
1021   case ARM::D16:
1022     return ARM::D17;
1023   case ARM::D18:
1024     return ARM::D19;
1025   case ARM::D20:
1026     return ARM::D21;
1027   case ARM::D22:
1028     return ARM::D23;
1029   case ARM::D24:
1030     return ARM::D25;
1031   case ARM::D26:
1032     return ARM::D27;
1033   case ARM::D28:
1034     return ARM::D29;
1035   case ARM::D30:
1036     return ARM::D31;
1037   }
1038
1039   return 0;
1040 }
1041
1042 /// emitLoadConstPool - Emits a load from constpool to materialize the
1043 /// specified immediate.
1044 void ARMBaseRegisterInfo::
1045 emitLoadConstPool(MachineBasicBlock &MBB,
1046                   MachineBasicBlock::iterator &MBBI,
1047                   DebugLoc dl,
1048                   unsigned DestReg, unsigned SubIdx, int Val,
1049                   ARMCC::CondCodes Pred,
1050                   unsigned PredReg) const {
1051   MachineFunction &MF = *MBB.getParent();
1052   MachineConstantPool *ConstantPool = MF.getConstantPool();
1053   Constant *C =
1054         ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
1055   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
1056
1057   BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
1058     .addReg(DestReg, getDefRegState(true), SubIdx)
1059     .addConstantPoolIndex(Idx)
1060     .addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
1061 }
1062
1063 bool ARMBaseRegisterInfo::
1064 requiresRegisterScavenging(const MachineFunction &MF) const {
1065   return true;
1066 }
1067
1068 bool ARMBaseRegisterInfo::
1069 requiresFrameIndexScavenging(const MachineFunction &MF) const {
1070   return true;
1071 }
1072
1073 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
1074 // not required, we reserve argument space for call sites in the function
1075 // immediately on entry to the current function. This eliminates the need for
1076 // add/sub sp brackets around call sites. Returns true if the call frame is
1077 // included as part of the stack frame.
1078 bool ARMBaseRegisterInfo::
1079 hasReservedCallFrame(MachineFunction &MF) const {
1080   const MachineFrameInfo *FFI = MF.getFrameInfo();
1081   unsigned CFSize = FFI->getMaxCallFrameSize();
1082   // It's not always a good idea to include the call frame as part of the
1083   // stack frame. ARM (especially Thumb) has small immediate offset to
1084   // address the stack frame. So a large call frame can cause poor codegen
1085   // and may even makes it impossible to scavenge a register.
1086   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
1087     return false;
1088
1089   return !MF.getFrameInfo()->hasVarSizedObjects();
1090 }
1091
1092 // canSimplifyCallFramePseudos - If there is a reserved call frame, the
1093 // call frame pseudos can be simplified. Unlike most targets, having a FP
1094 // is not sufficient here since we still may reference some objects via SP
1095 // even when FP is available in Thumb2 mode.
1096 bool ARMBaseRegisterInfo::
1097 canSimplifyCallFramePseudos(MachineFunction &MF) const {
1098   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
1099 }
1100
1101 static void
1102 emitSPUpdate(bool isARM,
1103              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
1104              DebugLoc dl, const ARMBaseInstrInfo &TII,
1105              int NumBytes,
1106              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
1107   if (isARM)
1108     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1109                             Pred, PredReg, TII);
1110   else
1111     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1112                            Pred, PredReg, TII);
1113 }
1114
1115
1116 void ARMBaseRegisterInfo::
1117 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1118                               MachineBasicBlock::iterator I) const {
1119   if (!hasReservedCallFrame(MF)) {
1120     // If we have alloca, convert as follows:
1121     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1122     // ADJCALLSTACKUP   -> add, sp, sp, amount
1123     MachineInstr *Old = I;
1124     DebugLoc dl = Old->getDebugLoc();
1125     unsigned Amount = Old->getOperand(0).getImm();
1126     if (Amount != 0) {
1127       // We need to keep the stack aligned properly.  To do this, we round the
1128       // amount of space needed for the outgoing arguments up to the next
1129       // alignment boundary.
1130       unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1131       Amount = (Amount+Align-1)/Align*Align;
1132
1133       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1134       assert(!AFI->isThumb1OnlyFunction() &&
1135              "This eliminateCallFramePseudoInstr does not support Thumb1!");
1136       bool isARM = !AFI->isThumbFunction();
1137
1138       // Replace the pseudo instruction with a new instruction...
1139       unsigned Opc = Old->getOpcode();
1140       int PIdx = Old->findFirstPredOperandIdx();
1141       ARMCC::CondCodes Pred = (PIdx == -1)
1142         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1143       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1144         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1145         unsigned PredReg = Old->getOperand(2).getReg();
1146         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, Pred, PredReg);
1147       } else {
1148         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1149         unsigned PredReg = Old->getOperand(3).getReg();
1150         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1151         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, Pred, PredReg);
1152       }
1153     }
1154   }
1155   MBB.erase(I);
1156 }
1157
1158 unsigned
1159 ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
1160                                          int SPAdj, FrameIndexValue *Value,
1161                                          RegScavenger *RS) const {
1162   unsigned i = 0;
1163   MachineInstr &MI = *II;
1164   MachineBasicBlock &MBB = *MI.getParent();
1165   MachineFunction &MF = *MBB.getParent();
1166   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1167   assert(!AFI->isThumb1OnlyFunction() &&
1168          "This eliminateFrameIndex does not support Thumb1!");
1169
1170   while (!MI.getOperand(i).isFI()) {
1171     ++i;
1172     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
1173   }
1174
1175   int FrameIndex = MI.getOperand(i).getIndex();
1176   unsigned FrameReg;
1177
1178   int Offset = getFrameIndexReference(MF, FrameIndex, FrameReg);
1179   if (FrameReg != ARM::SP)
1180     SPAdj = 0;
1181   Offset += SPAdj;
1182
1183   // Modify MI as necessary to handle as much of 'Offset' as possible
1184   bool Done = false;
1185   if (!AFI->isThumbFunction())
1186     Done = rewriteARMFrameIndex(MI, i, FrameReg, Offset, TII);
1187   else {
1188     assert(AFI->isThumb2Function());
1189     Done = rewriteT2FrameIndex(MI, i, FrameReg, Offset, TII);
1190   }
1191   if (Done)
1192     return 0;
1193
1194   // If we get here, the immediate doesn't fit into the instruction.  We folded
1195   // as much as possible above, handle the rest, providing a register that is
1196   // SP+LargeImm.
1197   assert((Offset ||
1198           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
1199           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
1200          "This code isn't needed if offset already handled!");
1201
1202   unsigned ScratchReg = 0;
1203   int PIdx = MI.findFirstPredOperandIdx();
1204   ARMCC::CondCodes Pred = (PIdx == -1)
1205     ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
1206   unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
1207   if (Offset == 0)
1208     // Must be addrmode4/6.
1209     MI.getOperand(i).ChangeToRegister(FrameReg, false, false, false);
1210   else {
1211     ScratchReg = MF.getRegInfo().createVirtualRegister(ARM::GPRRegisterClass);
1212     if (Value) {
1213       Value->first = FrameReg; // use the frame register as a kind indicator
1214       Value->second = Offset;
1215     }
1216     if (!AFI->isThumbFunction())
1217       emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1218                               Offset, Pred, PredReg, TII);
1219     else {
1220       assert(AFI->isThumb2Function());
1221       emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1222                              Offset, Pred, PredReg, TII);
1223     }
1224     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
1225     if (!ReuseFrameIndexVals)
1226       ScratchReg = 0;
1227   }
1228   return ScratchReg;
1229 }
1230
1231 /// Move iterator past the next bunch of callee save load / store ops for
1232 /// the particular spill area (1: integer area 1, 2: integer area 2,
1233 /// 3: fp area, 0: don't care).
1234 static void movePastCSLoadStoreOps(MachineBasicBlock &MBB,
1235                                    MachineBasicBlock::iterator &MBBI,
1236                                    int Opc1, int Opc2, unsigned Area,
1237                                    const ARMSubtarget &STI) {
1238   while (MBBI != MBB.end() &&
1239          ((MBBI->getOpcode() == Opc1) || (MBBI->getOpcode() == Opc2)) &&
1240          MBBI->getOperand(1).isFI()) {
1241     if (Area != 0) {
1242       bool Done = false;
1243       unsigned Category = 0;
1244       switch (MBBI->getOperand(0).getReg()) {
1245       case ARM::R4:  case ARM::R5:  case ARM::R6: case ARM::R7:
1246       case ARM::LR:
1247         Category = 1;
1248         break;
1249       case ARM::R8:  case ARM::R9:  case ARM::R10: case ARM::R11:
1250         Category = STI.isTargetDarwin() ? 2 : 1;
1251         break;
1252       case ARM::D8:  case ARM::D9:  case ARM::D10: case ARM::D11:
1253       case ARM::D12: case ARM::D13: case ARM::D14: case ARM::D15:
1254         Category = 3;
1255         break;
1256       default:
1257         Done = true;
1258         break;
1259       }
1260       if (Done || Category != Area)
1261         break;
1262     }
1263
1264     ++MBBI;
1265   }
1266 }
1267
1268 void ARMBaseRegisterInfo::
1269 emitPrologue(MachineFunction &MF) const {
1270   MachineBasicBlock &MBB = MF.front();
1271   MachineBasicBlock::iterator MBBI = MBB.begin();
1272   MachineFrameInfo  *MFI = MF.getFrameInfo();
1273   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1274   assert(!AFI->isThumb1OnlyFunction() &&
1275          "This emitPrologue does not support Thumb1!");
1276   bool isARM = !AFI->isThumbFunction();
1277   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1278   unsigned NumBytes = MFI->getStackSize();
1279   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1280   DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1281
1282   // Determine the sizes of each callee-save spill areas and record which frame
1283   // belongs to which callee-save spill areas.
1284   unsigned GPRCS1Size = 0, GPRCS2Size = 0, DPRCSSize = 0;
1285   int FramePtrSpillFI = 0;
1286
1287   // Allocate the vararg register save area. This is not counted in NumBytes.
1288   if (VARegSaveSize)
1289     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize);
1290
1291   if (!AFI->hasStackFrame()) {
1292     if (NumBytes != 0)
1293       emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
1294     return;
1295   }
1296
1297   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1298     unsigned Reg = CSI[i].getReg();
1299     int FI = CSI[i].getFrameIdx();
1300     switch (Reg) {
1301     case ARM::R4:
1302     case ARM::R5:
1303     case ARM::R6:
1304     case ARM::R7:
1305     case ARM::LR:
1306       if (Reg == FramePtr)
1307         FramePtrSpillFI = FI;
1308       AFI->addGPRCalleeSavedArea1Frame(FI);
1309       GPRCS1Size += 4;
1310       break;
1311     case ARM::R8:
1312     case ARM::R9:
1313     case ARM::R10:
1314     case ARM::R11:
1315       if (Reg == FramePtr)
1316         FramePtrSpillFI = FI;
1317       if (STI.isTargetDarwin()) {
1318         AFI->addGPRCalleeSavedArea2Frame(FI);
1319         GPRCS2Size += 4;
1320       } else {
1321         AFI->addGPRCalleeSavedArea1Frame(FI);
1322         GPRCS1Size += 4;
1323       }
1324       break;
1325     default:
1326       AFI->addDPRCalleeSavedAreaFrame(FI);
1327       DPRCSSize += 8;
1328     }
1329   }
1330
1331   // Build the new SUBri to adjust SP for integer callee-save spill area 1.
1332   emitSPUpdate(isARM, MBB, MBBI, dl, TII, -GPRCS1Size);
1333   movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, ARM::t2STRi12, 1, STI);
1334
1335   // Set FP to point to the stack slot that contains the previous FP.
1336   // For Darwin, FP is R7, which has now been stored in spill area 1.
1337   // Otherwise, if this is not Darwin, all the callee-saved registers go
1338   // into spill area 1, including the FP in R11.  In either case, it is
1339   // now safe to emit this assignment.
1340   if (STI.isTargetDarwin() || hasFP(MF)) {
1341     unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
1342     MachineInstrBuilder MIB =
1343       BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
1344       .addFrameIndex(FramePtrSpillFI).addImm(0);
1345     AddDefaultCC(AddDefaultPred(MIB));
1346   }
1347
1348   // Build the new SUBri to adjust SP for integer callee-save spill area 2.
1349   emitSPUpdate(isARM, MBB, MBBI, dl, TII, -GPRCS2Size);
1350
1351   // Build the new SUBri to adjust SP for FP callee-save spill area.
1352   movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, ARM::t2STRi12, 2, STI);
1353   emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRCSSize);
1354
1355   // Determine starting offsets of spill areas.
1356   unsigned DPRCSOffset  = NumBytes - (GPRCS1Size + GPRCS2Size + DPRCSSize);
1357   unsigned GPRCS2Offset = DPRCSOffset + DPRCSSize;
1358   unsigned GPRCS1Offset = GPRCS2Offset + GPRCS2Size;
1359   if (STI.isTargetDarwin() || hasFP(MF))
1360     AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
1361                                 NumBytes);
1362   AFI->setGPRCalleeSavedArea1Offset(GPRCS1Offset);
1363   AFI->setGPRCalleeSavedArea2Offset(GPRCS2Offset);
1364   AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
1365
1366   movePastCSLoadStoreOps(MBB, MBBI, ARM::VSTRD, 0, 3, STI);
1367   NumBytes = DPRCSOffset;
1368   if (NumBytes) {
1369     // Adjust SP after all the callee-save spills.
1370     emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
1371   }
1372
1373   if (STI.isTargetELF() && hasFP(MF)) {
1374     MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
1375                              AFI->getFramePtrSpillOffset());
1376   }
1377
1378   AFI->setGPRCalleeSavedArea1Size(GPRCS1Size);
1379   AFI->setGPRCalleeSavedArea2Size(GPRCS2Size);
1380   AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
1381
1382   // If we need dynamic stack realignment, do it here.
1383   if (needsStackRealignment(MF)) {
1384     unsigned MaxAlign = MFI->getMaxAlignment();
1385     assert (!AFI->isThumb1OnlyFunction());
1386     if (!AFI->isThumbFunction()) {
1387       // Emit bic sp, sp, MaxAlign
1388       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
1389                                           TII.get(ARM::BICri), ARM::SP)
1390                                   .addReg(ARM::SP, RegState::Kill)
1391                                   .addImm(MaxAlign-1)));
1392     } else {
1393       // We cannot use sp as source/dest register here, thus we're emitting the
1394       // following sequence:
1395       // mov r4, sp
1396       // bic r4, r4, MaxAlign
1397       // mov sp, r4
1398       // FIXME: It will be better just to find spare register here.
1399       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2tgpr), ARM::R4)
1400         .addReg(ARM::SP, RegState::Kill);
1401       AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
1402                                           TII.get(ARM::t2BICri), ARM::R4)
1403                                   .addReg(ARM::R4, RegState::Kill)
1404                                   .addImm(MaxAlign-1)));
1405       BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVtgpr2gpr), ARM::SP)
1406         .addReg(ARM::R4, RegState::Kill);
1407     }
1408   }
1409 }
1410
1411 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
1412   for (unsigned i = 0; CSRegs[i]; ++i)
1413     if (Reg == CSRegs[i])
1414       return true;
1415   return false;
1416 }
1417
1418 static bool isCSRestore(MachineInstr *MI,
1419                         const ARMBaseInstrInfo &TII,
1420                         const unsigned *CSRegs) {
1421   return ((MI->getOpcode() == (int)ARM::VLDRD ||
1422            MI->getOpcode() == (int)ARM::LDR ||
1423            MI->getOpcode() == (int)ARM::t2LDRi12) &&
1424           MI->getOperand(1).isFI() &&
1425           isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs));
1426 }
1427
1428 void ARMBaseRegisterInfo::
1429 emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const {
1430   MachineBasicBlock::iterator MBBI = prior(MBB.end());
1431   assert(MBBI->getDesc().isReturn() &&
1432          "Can only insert epilog into returning blocks");
1433   DebugLoc dl = MBBI->getDebugLoc();
1434   MachineFrameInfo *MFI = MF.getFrameInfo();
1435   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1436   assert(!AFI->isThumb1OnlyFunction() &&
1437          "This emitEpilogue does not support Thumb1!");
1438   bool isARM = !AFI->isThumbFunction();
1439
1440   unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1441   int NumBytes = (int)MFI->getStackSize();
1442
1443   if (!AFI->hasStackFrame()) {
1444     if (NumBytes != 0)
1445       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
1446   } else {
1447     // Unwind MBBI to point to first LDR / VLDRD.
1448     const unsigned *CSRegs = getCalleeSavedRegs();
1449     if (MBBI != MBB.begin()) {
1450       do
1451         --MBBI;
1452       while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
1453       if (!isCSRestore(MBBI, TII, CSRegs))
1454         ++MBBI;
1455     }
1456
1457     // Move SP to start of FP callee save spill area.
1458     NumBytes -= (AFI->getGPRCalleeSavedArea1Size() +
1459                  AFI->getGPRCalleeSavedArea2Size() +
1460                  AFI->getDPRCalleeSavedAreaSize());
1461
1462     // Darwin ABI requires FP to point to the stack slot that contains the
1463     // previous FP.
1464     bool HasFP = hasFP(MF);
1465     if ((STI.isTargetDarwin() && NumBytes) || HasFP) {
1466       NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1467       // Reset SP based on frame pointer only if the stack frame extends beyond
1468       // frame pointer stack slot or target is ELF and the function has FP.
1469       if (HasFP ||
1470           AFI->getGPRCalleeSavedArea2Size() ||
1471           AFI->getDPRCalleeSavedAreaSize()  ||
1472           AFI->getDPRCalleeSavedAreaOffset()) {
1473         if (NumBytes) {
1474           if (isARM)
1475             emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
1476                                     ARMCC::AL, 0, TII);
1477           else
1478             emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
1479                                     ARMCC::AL, 0, TII);
1480         } else {
1481           // Thumb2 or ARM.
1482           if (isARM)
1483             BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
1484               .addReg(FramePtr)
1485               .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
1486           else
1487             BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
1488               .addReg(FramePtr);
1489         }
1490       }
1491     } else if (NumBytes)
1492       emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
1493
1494     // Move SP to start of integer callee save spill area 2.
1495     movePastCSLoadStoreOps(MBB, MBBI, ARM::VLDRD, 0, 3, STI);
1496     emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedAreaSize());
1497
1498     // Move SP to start of integer callee save spill area 1.
1499     movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, ARM::t2LDRi12, 2, STI);
1500     emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getGPRCalleeSavedArea2Size());
1501
1502     // Move SP to SP upon entry to the function.
1503     movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, ARM::t2LDRi12, 1, STI);
1504     emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getGPRCalleeSavedArea1Size());
1505   }
1506
1507   if (VARegSaveSize)
1508     emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
1509 }
1510
1511 #include "ARMGenRegisterInfo.inc"