6ecd817c78b3e8566b86813dc1503990b627499c
[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
42 using namespace llvm;
43
44 static cl::opt<bool>
45 ForceAllBaseRegAlloc("arm-force-base-reg-alloc", cl::Hidden, cl::init(false),
46           cl::desc("Force use of virtual base registers for stack load/store"));
47 static cl::opt<bool>
48 EnableLocalStackAlloc("enable-local-stack-alloc", cl::init(true), cl::Hidden,
49           cl::desc("Enable pre-regalloc stack frame index allocation"));
50 static cl::opt<bool>
51 EnableBasePointer("arm-use-base-pointer", cl::Hidden, cl::init(true),
52           cl::desc("Enable use of a base pointer for complex stack frames"));
53
54 ARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMBaseInstrInfo &tii,
55                                          const ARMSubtarget &sti)
56   : ARMGenRegisterInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
57     TII(tii), STI(sti),
58     FramePtr((STI.isTargetDarwin() || STI.isThumb()) ? ARM::R7 : ARM::R11),
59     BasePtr(ARM::R6) {
60 }
61
62 const unsigned*
63 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
64   static const unsigned CalleeSavedRegs[] = {
65     ARM::LR, ARM::R11, ARM::R10, ARM::R9, ARM::R8,
66     ARM::R7, ARM::R6,  ARM::R5,  ARM::R4,
67
68     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
69     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
70     0
71   };
72
73   static const unsigned DarwinCalleeSavedRegs[] = {
74     // Darwin ABI deviates from ARM standard ABI. R9 is not a callee-saved
75     // register.
76     ARM::LR,  ARM::R7,  ARM::R6, ARM::R5, ARM::R4,
77     ARM::R11, ARM::R10, ARM::R8,
78
79     ARM::D15, ARM::D14, ARM::D13, ARM::D12,
80     ARM::D11, ARM::D10, ARM::D9,  ARM::D8,
81     0
82   };
83   return STI.isTargetDarwin() ? DarwinCalleeSavedRegs : CalleeSavedRegs;
84 }
85
86 BitVector ARMBaseRegisterInfo::
87 getReservedRegs(const MachineFunction &MF) const {
88   // FIXME: avoid re-calculating this everytime.
89   BitVector Reserved(getNumRegs());
90   Reserved.set(ARM::SP);
91   Reserved.set(ARM::PC);
92   Reserved.set(ARM::FPSCR);
93   if (hasFP(MF))
94     Reserved.set(FramePtr);
95   if (hasBasePointer(MF))
96     Reserved.set(BasePtr);
97   // Some targets reserve R9.
98   if (STI.isR9Reserved())
99     Reserved.set(ARM::R9);
100   return Reserved;
101 }
102
103 bool ARMBaseRegisterInfo::isReservedReg(const MachineFunction &MF,
104                                         unsigned Reg) const {
105   switch (Reg) {
106   default: break;
107   case ARM::SP:
108   case ARM::PC:
109     return true;
110   case ARM::R6:
111     if (hasBasePointer(MF))
112       return true;
113     break;
114   case ARM::R7:
115   case ARM::R11:
116     if (FramePtr == Reg && hasFP(MF))
117       return true;
118     break;
119   case ARM::R9:
120     return STI.isR9Reserved();
121   }
122
123   return false;
124 }
125
126 const TargetRegisterClass *
127 ARMBaseRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
128                                               const TargetRegisterClass *B,
129                                               unsigned SubIdx) const {
130   switch (SubIdx) {
131   default: return 0;
132   case ARM::ssub_0:
133   case ARM::ssub_1:
134   case ARM::ssub_2:
135   case ARM::ssub_3: {
136     // S sub-registers.
137     if (A->getSize() == 8) {
138       if (B == &ARM::SPR_8RegClass)
139         return &ARM::DPR_8RegClass;
140       assert(B == &ARM::SPRRegClass && "Expecting SPR register class!");
141       if (A == &ARM::DPR_8RegClass)
142         return A;
143       return &ARM::DPR_VFP2RegClass;
144     }
145
146     if (A->getSize() == 16) {
147       if (B == &ARM::SPR_8RegClass)
148         return &ARM::QPR_8RegClass;
149       return &ARM::QPR_VFP2RegClass;
150     }
151
152     if (A->getSize() == 32) {
153       if (B == &ARM::SPR_8RegClass)
154         return 0;  // Do not allow coalescing!
155       return &ARM::QQPR_VFP2RegClass;
156     }
157
158     assert(A->getSize() == 64 && "Expecting a QQQQ register class!");
159     return 0;  // Do not allow coalescing!
160   }
161   case ARM::dsub_0:
162   case ARM::dsub_1:
163   case ARM::dsub_2:
164   case ARM::dsub_3: {
165     // D sub-registers.
166     if (A->getSize() == 16) {
167       if (B == &ARM::DPR_VFP2RegClass)
168         return &ARM::QPR_VFP2RegClass;
169       if (B == &ARM::DPR_8RegClass)
170         return 0;  // Do not allow coalescing!
171       return A;
172     }
173
174     if (A->getSize() == 32) {
175       if (B == &ARM::DPR_VFP2RegClass)
176         return &ARM::QQPR_VFP2RegClass;
177       if (B == &ARM::DPR_8RegClass)
178         return 0;  // Do not allow coalescing!
179       return A;
180     }
181
182     assert(A->getSize() == 64 && "Expecting a QQQQ register class!");
183     if (B != &ARM::DPRRegClass)
184       return 0;  // Do not allow coalescing!
185     return A;
186   }
187   case ARM::dsub_4:
188   case ARM::dsub_5:
189   case ARM::dsub_6:
190   case ARM::dsub_7: {
191     // D sub-registers of QQQQ registers.
192     if (A->getSize() == 64 && B == &ARM::DPRRegClass)
193       return A;
194     return 0;  // Do not allow coalescing!
195   }
196
197   case ARM::qsub_0:
198   case ARM::qsub_1: {
199     // Q sub-registers.
200     if (A->getSize() == 32) {
201       if (B == &ARM::QPR_VFP2RegClass)
202         return &ARM::QQPR_VFP2RegClass;
203       if (B == &ARM::QPR_8RegClass)
204         return 0;  // Do not allow coalescing!
205       return A;
206     }
207
208     assert(A->getSize() == 64 && "Expecting a QQQQ register class!");
209     if (B == &ARM::QPRRegClass)
210       return A;
211     return 0;  // Do not allow coalescing!
212   }
213   case ARM::qsub_2:
214   case ARM::qsub_3: {
215     // Q sub-registers of QQQQ registers.
216     if (A->getSize() == 64 && B == &ARM::QPRRegClass)
217       return A;
218     return 0;  // Do not allow coalescing!
219   }
220   }
221   return 0;
222 }
223
224 bool
225 ARMBaseRegisterInfo::canCombineSubRegIndices(const TargetRegisterClass *RC,
226                                           SmallVectorImpl<unsigned> &SubIndices,
227                                           unsigned &NewSubIdx) const {
228
229   unsigned Size = RC->getSize() * 8;
230   if (Size < 6)
231     return 0;
232
233   NewSubIdx = 0;  // Whole register.
234   unsigned NumRegs = SubIndices.size();
235   if (NumRegs == 8) {
236     // 8 D registers -> 1 QQQQ register.
237     return (Size == 512 &&
238             SubIndices[0] == ARM::dsub_0 &&
239             SubIndices[1] == ARM::dsub_1 &&
240             SubIndices[2] == ARM::dsub_2 &&
241             SubIndices[3] == ARM::dsub_3 &&
242             SubIndices[4] == ARM::dsub_4 &&
243             SubIndices[5] == ARM::dsub_5 &&
244             SubIndices[6] == ARM::dsub_6 &&
245             SubIndices[7] == ARM::dsub_7);
246   } else if (NumRegs == 4) {
247     if (SubIndices[0] == ARM::qsub_0) {
248       // 4 Q registers -> 1 QQQQ register.
249       return (Size == 512 &&
250               SubIndices[1] == ARM::qsub_1 &&
251               SubIndices[2] == ARM::qsub_2 &&
252               SubIndices[3] == ARM::qsub_3);
253     } else if (SubIndices[0] == ARM::dsub_0) {
254       // 4 D registers -> 1 QQ register.
255       if (Size >= 256 &&
256           SubIndices[1] == ARM::dsub_1 &&
257           SubIndices[2] == ARM::dsub_2 &&
258           SubIndices[3] == ARM::dsub_3) {
259         if (Size == 512)
260           NewSubIdx = ARM::qqsub_0;
261         return true;
262       }
263     } else if (SubIndices[0] == ARM::dsub_4) {
264       // 4 D registers -> 1 QQ register (2nd).
265       if (Size == 512 &&
266           SubIndices[1] == ARM::dsub_5 &&
267           SubIndices[2] == ARM::dsub_6 &&
268           SubIndices[3] == ARM::dsub_7) {
269         NewSubIdx = ARM::qqsub_1;
270         return true;
271       }
272     } else if (SubIndices[0] == ARM::ssub_0) {
273       // 4 S registers -> 1 Q register.
274       if (Size >= 128 &&
275           SubIndices[1] == ARM::ssub_1 &&
276           SubIndices[2] == ARM::ssub_2 &&
277           SubIndices[3] == ARM::ssub_3) {
278         if (Size >= 256)
279           NewSubIdx = ARM::qsub_0;
280         return true;
281       }
282     }
283   } else if (NumRegs == 2) {
284     if (SubIndices[0] == ARM::qsub_0) {
285       // 2 Q registers -> 1 QQ register.
286       if (Size >= 256 && SubIndices[1] == ARM::qsub_1) {
287         if (Size == 512)
288           NewSubIdx = ARM::qqsub_0;
289         return true;
290       }
291     } else if (SubIndices[0] == ARM::qsub_2) {
292       // 2 Q registers -> 1 QQ register (2nd).
293       if (Size == 512 && SubIndices[1] == ARM::qsub_3) {
294         NewSubIdx = ARM::qqsub_1;
295         return true;
296       }
297     } else if (SubIndices[0] == ARM::dsub_0) {
298       // 2 D registers -> 1 Q register.
299       if (Size >= 128 && SubIndices[1] == ARM::dsub_1) {
300         if (Size >= 256)
301           NewSubIdx = ARM::qsub_0;
302         return true;
303       }
304     } else if (SubIndices[0] == ARM::dsub_2) {
305       // 2 D registers -> 1 Q register (2nd).
306       if (Size >= 256 && SubIndices[1] == ARM::dsub_3) {
307         NewSubIdx = ARM::qsub_1;
308         return true;
309       }
310     } else if (SubIndices[0] == ARM::dsub_4) {
311       // 2 D registers -> 1 Q register (3rd).
312       if (Size == 512 && SubIndices[1] == ARM::dsub_5) {
313         NewSubIdx = ARM::qsub_2;
314         return true;
315       }
316     } else if (SubIndices[0] == ARM::dsub_6) {
317       // 2 D registers -> 1 Q register (3rd).
318       if (Size == 512 && SubIndices[1] == ARM::dsub_7) {
319         NewSubIdx = ARM::qsub_3;
320         return true;
321       }
322     } else if (SubIndices[0] == ARM::ssub_0) {
323       // 2 S registers -> 1 D register.
324       if (SubIndices[1] == ARM::ssub_1) {
325         if (Size >= 128)
326           NewSubIdx = ARM::dsub_0;
327         return true;
328       }
329     } else if (SubIndices[0] == ARM::ssub_2) {
330       // 2 S registers -> 1 D register (2nd).
331       if (Size >= 128 && SubIndices[1] == ARM::ssub_3) {
332         NewSubIdx = ARM::dsub_1;
333         return true;
334       }
335     }
336   }
337   return false;
338 }
339
340
341 const TargetRegisterClass *
342 ARMBaseRegisterInfo::getPointerRegClass(unsigned Kind) const {
343   return ARM::GPRRegisterClass;
344 }
345
346 /// getAllocationOrder - Returns the register allocation order for a specified
347 /// register class in the form of a pair of TargetRegisterClass iterators.
348 std::pair<TargetRegisterClass::iterator,TargetRegisterClass::iterator>
349 ARMBaseRegisterInfo::getAllocationOrder(const TargetRegisterClass *RC,
350                                         unsigned HintType, unsigned HintReg,
351                                         const MachineFunction &MF) const {
352   // Alternative register allocation orders when favoring even / odd registers
353   // of register pairs.
354
355   // No FP, R9 is available.
356   static const unsigned GPREven1[] = {
357     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8, ARM::R10,
358     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7,
359     ARM::R9, ARM::R11
360   };
361   static const unsigned GPROdd1[] = {
362     ARM::R1, ARM::R3, ARM::R5, ARM::R7, ARM::R9, ARM::R11,
363     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
364     ARM::R8, ARM::R10
365   };
366
367   // FP is R7, R9 is available.
368   static const unsigned GPREven2[] = {
369     ARM::R0, ARM::R2, ARM::R4,          ARM::R8, ARM::R10,
370     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6,
371     ARM::R9, ARM::R11
372   };
373   static const unsigned GPROdd2[] = {
374     ARM::R1, ARM::R3, ARM::R5,          ARM::R9, ARM::R11,
375     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
376     ARM::R8, ARM::R10
377   };
378
379   // FP is R11, R9 is available.
380   static const unsigned GPREven3[] = {
381     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8,
382     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7,
383     ARM::R9
384   };
385   static const unsigned GPROdd3[] = {
386     ARM::R1, ARM::R3, ARM::R5, ARM::R6, ARM::R9,
387     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R7,
388     ARM::R8
389   };
390
391   // No FP, R9 is not available.
392   static const unsigned GPREven4[] = {
393     ARM::R0, ARM::R2, ARM::R4, ARM::R6,          ARM::R10,
394     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8,
395     ARM::R11
396   };
397   static const unsigned GPROdd4[] = {
398     ARM::R1, ARM::R3, ARM::R5, ARM::R7,          ARM::R11,
399     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
400     ARM::R10
401   };
402
403   // FP is R7, R9 is not available.
404   static const unsigned GPREven5[] = {
405     ARM::R0, ARM::R2, ARM::R4,                   ARM::R10,
406     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6, ARM::R8,
407     ARM::R11
408   };
409   static const unsigned GPROdd5[] = {
410     ARM::R1, ARM::R3, ARM::R5,                   ARM::R11,
411     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
412     ARM::R10
413   };
414
415   // FP is R11, R9 is not available.
416   static const unsigned GPREven6[] = {
417     ARM::R0, ARM::R2, ARM::R4, ARM::R6,
418     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8
419   };
420   static const unsigned GPROdd6[] = {
421     ARM::R1, ARM::R3, ARM::R5, ARM::R7,
422     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8
423   };
424
425
426   if (HintType == ARMRI::RegPairEven) {
427     if (isPhysicalRegister(HintReg) && getRegisterPairEven(HintReg, MF) == 0)
428       // It's no longer possible to fulfill this hint. Return the default
429       // allocation order.
430       return std::make_pair(RC->allocation_order_begin(MF),
431                             RC->allocation_order_end(MF));
432
433     if (!hasFP(MF)) {
434       if (!STI.isR9Reserved())
435         return std::make_pair(GPREven1,
436                               GPREven1 + (sizeof(GPREven1)/sizeof(unsigned)));
437       else
438         return std::make_pair(GPREven4,
439                               GPREven4 + (sizeof(GPREven4)/sizeof(unsigned)));
440     } else if (FramePtr == ARM::R7) {
441       if (!STI.isR9Reserved())
442         return std::make_pair(GPREven2,
443                               GPREven2 + (sizeof(GPREven2)/sizeof(unsigned)));
444       else
445         return std::make_pair(GPREven5,
446                               GPREven5 + (sizeof(GPREven5)/sizeof(unsigned)));
447     } else { // FramePtr == ARM::R11
448       if (!STI.isR9Reserved())
449         return std::make_pair(GPREven3,
450                               GPREven3 + (sizeof(GPREven3)/sizeof(unsigned)));
451       else
452         return std::make_pair(GPREven6,
453                               GPREven6 + (sizeof(GPREven6)/sizeof(unsigned)));
454     }
455   } else if (HintType == ARMRI::RegPairOdd) {
456     if (isPhysicalRegister(HintReg) && getRegisterPairOdd(HintReg, MF) == 0)
457       // It's no longer possible to fulfill this hint. Return the default
458       // allocation order.
459       return std::make_pair(RC->allocation_order_begin(MF),
460                             RC->allocation_order_end(MF));
461
462     if (!hasFP(MF)) {
463       if (!STI.isR9Reserved())
464         return std::make_pair(GPROdd1,
465                               GPROdd1 + (sizeof(GPROdd1)/sizeof(unsigned)));
466       else
467         return std::make_pair(GPROdd4,
468                               GPROdd4 + (sizeof(GPROdd4)/sizeof(unsigned)));
469     } else if (FramePtr == ARM::R7) {
470       if (!STI.isR9Reserved())
471         return std::make_pair(GPROdd2,
472                               GPROdd2 + (sizeof(GPROdd2)/sizeof(unsigned)));
473       else
474         return std::make_pair(GPROdd5,
475                               GPROdd5 + (sizeof(GPROdd5)/sizeof(unsigned)));
476     } else { // FramePtr == ARM::R11
477       if (!STI.isR9Reserved())
478         return std::make_pair(GPROdd3,
479                               GPROdd3 + (sizeof(GPROdd3)/sizeof(unsigned)));
480       else
481         return std::make_pair(GPROdd6,
482                               GPROdd6 + (sizeof(GPROdd6)/sizeof(unsigned)));
483     }
484   }
485   return std::make_pair(RC->allocation_order_begin(MF),
486                         RC->allocation_order_end(MF));
487 }
488
489 /// ResolveRegAllocHint - Resolves the specified register allocation hint
490 /// to a physical register. Returns the physical register if it is successful.
491 unsigned
492 ARMBaseRegisterInfo::ResolveRegAllocHint(unsigned Type, unsigned Reg,
493                                          const MachineFunction &MF) const {
494   if (Reg == 0 || !isPhysicalRegister(Reg))
495     return 0;
496   if (Type == 0)
497     return Reg;
498   else if (Type == (unsigned)ARMRI::RegPairOdd)
499     // Odd register.
500     return getRegisterPairOdd(Reg, MF);
501   else if (Type == (unsigned)ARMRI::RegPairEven)
502     // Even register.
503     return getRegisterPairEven(Reg, MF);
504   return 0;
505 }
506
507 void
508 ARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
509                                         MachineFunction &MF) const {
510   MachineRegisterInfo *MRI = &MF.getRegInfo();
511   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
512   if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
513        Hint.first == (unsigned)ARMRI::RegPairEven) &&
514       Hint.second && TargetRegisterInfo::isVirtualRegister(Hint.second)) {
515     // If 'Reg' is one of the even / odd register pair and it's now changed
516     // (e.g. coalesced) into a different register. The other register of the
517     // pair allocation hint must be updated to reflect the relationship
518     // change.
519     unsigned OtherReg = Hint.second;
520     Hint = MRI->getRegAllocationHint(OtherReg);
521     if (Hint.second == Reg)
522       // Make sure the pair has not already divorced.
523       MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
524   }
525 }
526
527 /// hasFP - Return true if the specified function should have a dedicated frame
528 /// pointer register.  This is true if the function has variable sized allocas
529 /// or if frame pointer elimination is disabled.
530 ///
531 bool ARMBaseRegisterInfo::hasFP(const MachineFunction &MF) const {
532   // Mac OS X requires FP not to be clobbered for backtracing purpose.
533   if (STI.isTargetDarwin())
534     return true;
535
536   const MachineFrameInfo *MFI = MF.getFrameInfo();
537   // Always eliminate non-leaf frame pointers.
538   return ((DisableFramePointerElim(MF) && MFI->hasCalls()) ||
539           needsStackRealignment(MF) ||
540           MFI->hasVarSizedObjects() ||
541           MFI->isFrameAddressTaken());
542 }
543
544 bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
545   const MachineFrameInfo *MFI = MF.getFrameInfo();
546   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
547
548   if (!EnableBasePointer)
549     return false;
550
551   if (needsStackRealignment(MF) && MFI->hasVarSizedObjects())
552     return true;
553
554   // Thumb has trouble with negative offsets from the FP. Thumb2 has a limited
555   // negative range for ldr/str (255), and thumb1 is positive offsets only.
556   // It's going to be better to use the SP or Base Pointer instead. When there
557   // are variable sized objects, we can't reference off of the SP, so we
558   // reserve a Base Pointer.
559   if (AFI->isThumbFunction() && MFI->hasVarSizedObjects()) {
560     // Conservatively estimate whether the negative offset from the frame
561     // pointer will be sufficient to reach. If a function has a smallish
562     // frame, it's less likely to have lots of spills and callee saved
563     // space, so it's all more likely to be within range of the frame pointer.
564     // If it's wrong, the scavenger will still enable access to work, it just
565     // won't be optimal.
566     if (AFI->isThumb2Function() && MFI->getLocalFrameSize() < 128)
567       return false;
568     return true;
569   }
570
571   return false;
572 }
573
574 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
575   const MachineFrameInfo *MFI = MF.getFrameInfo();
576   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
577   // We can't realign the stack if:
578   // 1. Dynamic stack realignment is explicitly disabled,
579   // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
580   // 3. There are VLAs in the function and the base pointer is disabled.
581   return (RealignStack && !AFI->isThumb1OnlyFunction() &&
582           (!MFI->hasVarSizedObjects() || EnableBasePointer));
583 }
584
585 bool ARMBaseRegisterInfo::
586 needsStackRealignment(const MachineFunction &MF) const {
587   const MachineFrameInfo *MFI = MF.getFrameInfo();
588   const Function *F = MF.getFunction();
589   unsigned StackAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
590   bool requiresRealignment = ((MFI->getLocalFrameMaxAlign() > StackAlign) ||
591                                F->hasFnAttr(Attribute::StackAlignment));
592
593   return requiresRealignment && canRealignStack(MF);
594 }
595
596 bool ARMBaseRegisterInfo::
597 cannotEliminateFrame(const MachineFunction &MF) const {
598   const MachineFrameInfo *MFI = MF.getFrameInfo();
599   if (DisableFramePointerElim(MF) && MFI->adjustsStack())
600     return true;
601   return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
602     || needsStackRealignment(MF);
603 }
604
605 /// estimateStackSize - Estimate and return the size of the frame.
606 static unsigned estimateStackSize(MachineFunction &MF) {
607   const MachineFrameInfo *FFI = MF.getFrameInfo();
608   int Offset = 0;
609   for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
610     int FixedOff = -FFI->getObjectOffset(i);
611     if (FixedOff > Offset) Offset = FixedOff;
612   }
613   for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
614     if (FFI->isDeadObjectIndex(i))
615       continue;
616     Offset += FFI->getObjectSize(i);
617     unsigned Align = FFI->getObjectAlignment(i);
618     // Adjust to alignment boundary
619     Offset = (Offset+Align-1)/Align*Align;
620   }
621   return (unsigned)Offset;
622 }
623
624 /// estimateRSStackSizeLimit - Look at each instruction that references stack
625 /// frames and return the stack size limit beyond which some of these
626 /// instructions will require a scratch register during their expansion later.
627 unsigned
628 ARMBaseRegisterInfo::estimateRSStackSizeLimit(MachineFunction &MF) const {
629   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
630   unsigned Limit = (1 << 12) - 1;
631   for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
632     for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
633          I != E; ++I) {
634       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
635         if (!I->getOperand(i).isFI()) continue;
636
637         // When using ADDri to get the address of a stack object, 255 is the
638         // largest offset guaranteed to fit in the immediate offset.
639         if (I->getOpcode() == ARM::ADDri) {
640           Limit = std::min(Limit, (1U << 8) - 1);
641           break;
642         }
643
644         // Otherwise check the addressing mode.
645         switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
646         case ARMII::AddrMode3:
647         case ARMII::AddrModeT2_i8:
648           Limit = std::min(Limit, (1U << 8) - 1);
649           break;
650         case ARMII::AddrMode5:
651         case ARMII::AddrModeT2_i8s4:
652           Limit = std::min(Limit, ((1U << 8) - 1) * 4);
653           break;
654         case ARMII::AddrModeT2_i12:
655           // i12 supports only positive offset so these will be converted to
656           // i8 opcodes. See llvm::rewriteT2FrameIndex.
657           if (hasFP(MF) && AFI->hasStackFrame())
658             Limit = std::min(Limit, (1U << 8) - 1);
659           break;
660         case ARMII::AddrMode4:
661         case ARMII::AddrMode6:
662           // Addressing modes 4 & 6 (load/store) instructions can't encode an
663           // immediate offset for stack references.
664           return 0;
665         default:
666           break;
667         }
668         break; // At most one FI per instruction
669       }
670     }
671   }
672
673   return Limit;
674 }
675
676 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
677                                        const ARMBaseInstrInfo &TII) {
678   unsigned FnSize = 0;
679   for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
680        MBBI != E; ++MBBI) {
681     const MachineBasicBlock &MBB = *MBBI;
682     for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
683          I != E; ++I)
684       FnSize += TII.GetInstSizeInBytes(I);
685   }
686   return FnSize;
687 }
688
689 void
690 ARMBaseRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
691                                                        RegScavenger *RS) const {
692   // This tells PEI to spill the FP as if it is any other callee-save register
693   // to take advantage the eliminateFrameIndex machinery. This also ensures it
694   // is spilled in the order specified by getCalleeSavedRegs() to make it easier
695   // to combine multiple loads / stores.
696   bool CanEliminateFrame = true;
697   bool CS1Spilled = false;
698   bool LRSpilled = false;
699   unsigned NumGPRSpills = 0;
700   SmallVector<unsigned, 4> UnspilledCS1GPRs;
701   SmallVector<unsigned, 4> UnspilledCS2GPRs;
702   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
703   MachineFrameInfo *MFI = MF.getFrameInfo();
704
705   // Spill R4 if Thumb2 function requires stack realignment - it will be used as
706   // scratch register.
707   // FIXME: It will be better just to find spare register here.
708   if (needsStackRealignment(MF) &&
709       AFI->isThumb2Function())
710     MF.getRegInfo().setPhysRegUsed(ARM::R4);
711
712   // Spill LR if Thumb1 function uses variable length argument lists.
713   if (AFI->isThumb1OnlyFunction() && AFI->getVarArgsRegSaveSize() > 0)
714     MF.getRegInfo().setPhysRegUsed(ARM::LR);
715
716   // Spill the BasePtr if it's used.
717   if (hasBasePointer(MF))
718     MF.getRegInfo().setPhysRegUsed(BasePtr);
719
720   // Don't spill FP if the frame can be eliminated. This is determined
721   // by scanning the callee-save registers to see if any is used.
722   const unsigned *CSRegs = getCalleeSavedRegs();
723   for (unsigned i = 0; CSRegs[i]; ++i) {
724     unsigned Reg = CSRegs[i];
725     bool Spilled = false;
726     if (MF.getRegInfo().isPhysRegUsed(Reg)) {
727       AFI->setCSRegisterIsSpilled(Reg);
728       Spilled = true;
729       CanEliminateFrame = false;
730     } else {
731       // Check alias registers too.
732       for (const unsigned *Aliases = getAliasSet(Reg); *Aliases; ++Aliases) {
733         if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
734           Spilled = true;
735           CanEliminateFrame = false;
736         }
737       }
738     }
739
740     if (!ARM::GPRRegisterClass->contains(Reg))
741       continue;
742
743     if (Spilled) {
744       NumGPRSpills++;
745
746       if (!STI.isTargetDarwin()) {
747         if (Reg == ARM::LR)
748           LRSpilled = true;
749         CS1Spilled = true;
750         continue;
751       }
752
753       // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
754       switch (Reg) {
755       case ARM::LR:
756         LRSpilled = true;
757         // Fallthrough
758       case ARM::R4:
759       case ARM::R5:
760       case ARM::R6:
761       case ARM::R7:
762         CS1Spilled = true;
763         break;
764       default:
765         break;
766       }
767     } else {
768       if (!STI.isTargetDarwin()) {
769         UnspilledCS1GPRs.push_back(Reg);
770         continue;
771       }
772
773       switch (Reg) {
774       case ARM::R4:
775       case ARM::R5:
776       case ARM::R6:
777       case ARM::R7:
778       case ARM::LR:
779         UnspilledCS1GPRs.push_back(Reg);
780         break;
781       default:
782         UnspilledCS2GPRs.push_back(Reg);
783         break;
784       }
785     }
786   }
787
788   bool ForceLRSpill = false;
789   if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
790     unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
791     // Force LR to be spilled if the Thumb function size is > 2048. This enables
792     // use of BL to implement far jump. If it turns out that it's not needed
793     // then the branch fix up path will undo it.
794     if (FnSize >= (1 << 11)) {
795       CanEliminateFrame = false;
796       ForceLRSpill = true;
797     }
798   }
799
800   // If any of the stack slot references may be out of range of an immediate
801   // offset, make sure a register (or a spill slot) is available for the
802   // register scavenger. Note that if we're indexing off the frame pointer, the
803   // effective stack size is 4 bytes larger since the FP points to the stack
804   // slot of the previous FP. Also, if we have variable sized objects in the
805   // function, stack slot references will often be negative, and some of
806   // our instructions are positive-offset only, so conservatively consider
807   // that case to want a spill slot (or register) as well. Similarly, if
808   // the function adjusts the stack pointer during execution and the
809   // adjustments aren't already part of our stack size estimate, our offset
810   // calculations may be off, so be conservative.
811   // FIXME: We could add logic to be more precise about negative offsets
812   //        and which instructions will need a scratch register for them. Is it
813   //        worth the effort and added fragility?
814   bool BigStack =
815     (RS &&
816      (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
817       estimateRSStackSizeLimit(MF)))
818     || MFI->hasVarSizedObjects()
819     || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
820
821   bool ExtraCSSpill = false;
822   if (BigStack || !CanEliminateFrame || cannotEliminateFrame(MF)) {
823     AFI->setHasStackFrame(true);
824
825     // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
826     // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
827     if (!LRSpilled && CS1Spilled) {
828       MF.getRegInfo().setPhysRegUsed(ARM::LR);
829       AFI->setCSRegisterIsSpilled(ARM::LR);
830       NumGPRSpills++;
831       UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
832                                     UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
833       ForceLRSpill = false;
834       ExtraCSSpill = true;
835     }
836
837     if (hasFP(MF)) {
838       MF.getRegInfo().setPhysRegUsed(FramePtr);
839       NumGPRSpills++;
840     }
841
842     // If stack and double are 8-byte aligned and we are spilling an odd number
843     // of GPRs, spill one extra callee save GPR so we won't have to pad between
844     // the integer and double callee save areas.
845     unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
846     if (TargetAlign == 8 && (NumGPRSpills & 1)) {
847       if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
848         for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
849           unsigned Reg = UnspilledCS1GPRs[i];
850           // Don't spill high register if the function is thumb1
851           if (!AFI->isThumb1OnlyFunction() ||
852               isARMLowRegister(Reg) || Reg == ARM::LR) {
853             MF.getRegInfo().setPhysRegUsed(Reg);
854             AFI->setCSRegisterIsSpilled(Reg);
855             if (!isReservedReg(MF, Reg))
856               ExtraCSSpill = true;
857             break;
858           }
859         }
860       } else if (!UnspilledCS2GPRs.empty() &&
861                  !AFI->isThumb1OnlyFunction()) {
862         unsigned Reg = UnspilledCS2GPRs.front();
863         MF.getRegInfo().setPhysRegUsed(Reg);
864         AFI->setCSRegisterIsSpilled(Reg);
865         if (!isReservedReg(MF, Reg))
866           ExtraCSSpill = true;
867       }
868     }
869
870     // Estimate if we might need to scavenge a register at some point in order
871     // to materialize a stack offset. If so, either spill one additional
872     // callee-saved register or reserve a special spill slot to facilitate
873     // register scavenging. Thumb1 needs a spill slot for stack pointer
874     // adjustments also, even when the frame itself is small.
875     if (BigStack && !ExtraCSSpill) {
876       // If any non-reserved CS register isn't spilled, just spill one or two
877       // extra. That should take care of it!
878       unsigned NumExtras = TargetAlign / 4;
879       SmallVector<unsigned, 2> Extras;
880       while (NumExtras && !UnspilledCS1GPRs.empty()) {
881         unsigned Reg = UnspilledCS1GPRs.back();
882         UnspilledCS1GPRs.pop_back();
883         if (!isReservedReg(MF, Reg) &&
884             (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
885              Reg == ARM::LR)) {
886           Extras.push_back(Reg);
887           NumExtras--;
888         }
889       }
890       // For non-Thumb1 functions, also check for hi-reg CS registers
891       if (!AFI->isThumb1OnlyFunction()) {
892         while (NumExtras && !UnspilledCS2GPRs.empty()) {
893           unsigned Reg = UnspilledCS2GPRs.back();
894           UnspilledCS2GPRs.pop_back();
895           if (!isReservedReg(MF, Reg)) {
896             Extras.push_back(Reg);
897             NumExtras--;
898           }
899         }
900       }
901       if (Extras.size() && NumExtras == 0) {
902         for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
903           MF.getRegInfo().setPhysRegUsed(Extras[i]);
904           AFI->setCSRegisterIsSpilled(Extras[i]);
905         }
906       } else if (!AFI->isThumb1OnlyFunction()) {
907         // note: Thumb1 functions spill to R12, not the stack.  Reserve a slot
908         // closest to SP or frame pointer.
909         const TargetRegisterClass *RC = ARM::GPRRegisterClass;
910         RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
911                                                            RC->getAlignment(),
912                                                            false));
913       }
914     }
915   }
916
917   if (ForceLRSpill) {
918     MF.getRegInfo().setPhysRegUsed(ARM::LR);
919     AFI->setCSRegisterIsSpilled(ARM::LR);
920     AFI->setLRIsSpilledForFarJump(true);
921   }
922 }
923
924 unsigned ARMBaseRegisterInfo::getRARegister() const {
925   return ARM::LR;
926 }
927
928 unsigned
929 ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
930   if (hasFP(MF))
931     return FramePtr;
932   return ARM::SP;
933 }
934
935 // Provide a base+offset reference to an FI slot for debug info. It's the
936 // same as what we use for resolving the code-gen references for now.
937 // FIXME: This can go wrong when references are SP-relative and simple call
938 //        frames aren't used.
939 int
940 ARMBaseRegisterInfo::getFrameIndexReference(const MachineFunction &MF, int FI,
941                                             unsigned &FrameReg) const {
942   return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
943 }
944
945 int
946 ARMBaseRegisterInfo::ResolveFrameIndexReference(const MachineFunction &MF,
947                                                 int FI,
948                                                 unsigned &FrameReg,
949                                                 int SPAdj) const {
950   const MachineFrameInfo *MFI = MF.getFrameInfo();
951   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
952   int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
953   int FPOffset = Offset - AFI->getFramePtrSpillOffset();
954   bool isFixed = MFI->isFixedObjectIndex(FI);
955
956   FrameReg = ARM::SP;
957   Offset += SPAdj;
958   if (AFI->isGPRCalleeSavedArea1Frame(FI))
959     return Offset - AFI->getGPRCalleeSavedArea1Offset();
960   else if (AFI->isGPRCalleeSavedArea2Frame(FI))
961     return Offset - AFI->getGPRCalleeSavedArea2Offset();
962   else if (AFI->isDPRCalleeSavedAreaFrame(FI))
963     return Offset - AFI->getDPRCalleeSavedAreaOffset();
964
965   // When dynamically realigning the stack, use the frame pointer for
966   // parameters, and the stack/base pointer for locals.
967   if (needsStackRealignment(MF)) {
968     assert (hasFP(MF) && "dynamic stack realignment without a FP!");
969     if (isFixed) {
970       FrameReg = getFrameRegister(MF);
971       Offset = FPOffset;
972     } else if (MFI->hasVarSizedObjects()) {
973       assert(hasBasePointer(MF) &&
974              "VLAs and dynamic stack alignment, but missing base pointer!");
975       FrameReg = BasePtr;
976     }
977     return Offset;
978   }
979
980   // If there is a frame pointer, use it when we can.
981   if (hasFP(MF) && AFI->hasStackFrame()) {
982     // Use frame pointer to reference fixed objects. Use it for locals if
983     // there are VLAs (and thus the SP isn't reliable as a base).
984     if (isFixed || (MFI->hasVarSizedObjects() && !hasBasePointer(MF))) {
985       FrameReg = getFrameRegister(MF);
986       return FPOffset;
987     } else if (MFI->hasVarSizedObjects()) {
988       assert(hasBasePointer(MF) && "missing base pointer!");
989       // Try to use the frame pointer if we can, else use the base pointer
990       // since it's available. This is handy for the emergency spill slot, in
991       // particular.
992       if (AFI->isThumb2Function()) {
993         if (FPOffset >= -255 && FPOffset < 0) {
994           FrameReg = getFrameRegister(MF);
995           return FPOffset;
996         }
997       } else
998         FrameReg = BasePtr;
999     } else if (AFI->isThumb2Function()) {
1000       // In Thumb2 mode, the negative offset is very limited. Try to avoid
1001       // out of range references.
1002       if (FPOffset >= -255 && FPOffset < 0) {
1003         FrameReg = getFrameRegister(MF);
1004         return FPOffset;
1005       }
1006     } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
1007       // Otherwise, use SP or FP, whichever is closer to the stack slot.
1008       FrameReg = getFrameRegister(MF);
1009       return FPOffset;
1010     }
1011   }
1012   // Use the base pointer if we have one.
1013   if (hasBasePointer(MF))
1014     FrameReg = BasePtr;
1015   return Offset;
1016 }
1017
1018 int
1019 ARMBaseRegisterInfo::getFrameIndexOffset(const MachineFunction &MF,
1020                                          int FI) const {
1021   unsigned FrameReg;
1022   return getFrameIndexReference(MF, FI, FrameReg);
1023 }
1024
1025 unsigned ARMBaseRegisterInfo::getEHExceptionRegister() const {
1026   llvm_unreachable("What is the exception register");
1027   return 0;
1028 }
1029
1030 unsigned ARMBaseRegisterInfo::getEHHandlerRegister() const {
1031   llvm_unreachable("What is the exception handler register");
1032   return 0;
1033 }
1034
1035 int ARMBaseRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
1036   return ARMGenRegisterInfo::getDwarfRegNumFull(RegNum, 0);
1037 }
1038
1039 unsigned ARMBaseRegisterInfo::getRegisterPairEven(unsigned Reg,
1040                                               const MachineFunction &MF) const {
1041   switch (Reg) {
1042   default: break;
1043   // Return 0 if either register of the pair is a special register.
1044   // So no R12, etc.
1045   case ARM::R1:
1046     return ARM::R0;
1047   case ARM::R3:
1048     return ARM::R2;
1049   case ARM::R5:
1050     return ARM::R4;
1051   case ARM::R7:
1052     return (isReservedReg(MF, ARM::R7) || isReservedReg(MF, ARM::R6))
1053       ? 0 : ARM::R6;
1054   case ARM::R9:
1055     return isReservedReg(MF, ARM::R9)  ? 0 :ARM::R8;
1056   case ARM::R11:
1057     return isReservedReg(MF, ARM::R11) ? 0 : ARM::R10;
1058
1059   case ARM::S1:
1060     return ARM::S0;
1061   case ARM::S3:
1062     return ARM::S2;
1063   case ARM::S5:
1064     return ARM::S4;
1065   case ARM::S7:
1066     return ARM::S6;
1067   case ARM::S9:
1068     return ARM::S8;
1069   case ARM::S11:
1070     return ARM::S10;
1071   case ARM::S13:
1072     return ARM::S12;
1073   case ARM::S15:
1074     return ARM::S14;
1075   case ARM::S17:
1076     return ARM::S16;
1077   case ARM::S19:
1078     return ARM::S18;
1079   case ARM::S21:
1080     return ARM::S20;
1081   case ARM::S23:
1082     return ARM::S22;
1083   case ARM::S25:
1084     return ARM::S24;
1085   case ARM::S27:
1086     return ARM::S26;
1087   case ARM::S29:
1088     return ARM::S28;
1089   case ARM::S31:
1090     return ARM::S30;
1091
1092   case ARM::D1:
1093     return ARM::D0;
1094   case ARM::D3:
1095     return ARM::D2;
1096   case ARM::D5:
1097     return ARM::D4;
1098   case ARM::D7:
1099     return ARM::D6;
1100   case ARM::D9:
1101     return ARM::D8;
1102   case ARM::D11:
1103     return ARM::D10;
1104   case ARM::D13:
1105     return ARM::D12;
1106   case ARM::D15:
1107     return ARM::D14;
1108   case ARM::D17:
1109     return ARM::D16;
1110   case ARM::D19:
1111     return ARM::D18;
1112   case ARM::D21:
1113     return ARM::D20;
1114   case ARM::D23:
1115     return ARM::D22;
1116   case ARM::D25:
1117     return ARM::D24;
1118   case ARM::D27:
1119     return ARM::D26;
1120   case ARM::D29:
1121     return ARM::D28;
1122   case ARM::D31:
1123     return ARM::D30;
1124   }
1125
1126   return 0;
1127 }
1128
1129 unsigned ARMBaseRegisterInfo::getRegisterPairOdd(unsigned Reg,
1130                                              const MachineFunction &MF) const {
1131   switch (Reg) {
1132   default: break;
1133   // Return 0 if either register of the pair is a special register.
1134   // So no R12, etc.
1135   case ARM::R0:
1136     return ARM::R1;
1137   case ARM::R2:
1138     return ARM::R3;
1139   case ARM::R4:
1140     return ARM::R5;
1141   case ARM::R6:
1142     return (isReservedReg(MF, ARM::R7) || isReservedReg(MF, ARM::R6))
1143       ? 0 : ARM::R7;
1144   case ARM::R8:
1145     return isReservedReg(MF, ARM::R9)  ? 0 :ARM::R9;
1146   case ARM::R10:
1147     return isReservedReg(MF, ARM::R11) ? 0 : ARM::R11;
1148
1149   case ARM::S0:
1150     return ARM::S1;
1151   case ARM::S2:
1152     return ARM::S3;
1153   case ARM::S4:
1154     return ARM::S5;
1155   case ARM::S6:
1156     return ARM::S7;
1157   case ARM::S8:
1158     return ARM::S9;
1159   case ARM::S10:
1160     return ARM::S11;
1161   case ARM::S12:
1162     return ARM::S13;
1163   case ARM::S14:
1164     return ARM::S15;
1165   case ARM::S16:
1166     return ARM::S17;
1167   case ARM::S18:
1168     return ARM::S19;
1169   case ARM::S20:
1170     return ARM::S21;
1171   case ARM::S22:
1172     return ARM::S23;
1173   case ARM::S24:
1174     return ARM::S25;
1175   case ARM::S26:
1176     return ARM::S27;
1177   case ARM::S28:
1178     return ARM::S29;
1179   case ARM::S30:
1180     return ARM::S31;
1181
1182   case ARM::D0:
1183     return ARM::D1;
1184   case ARM::D2:
1185     return ARM::D3;
1186   case ARM::D4:
1187     return ARM::D5;
1188   case ARM::D6:
1189     return ARM::D7;
1190   case ARM::D8:
1191     return ARM::D9;
1192   case ARM::D10:
1193     return ARM::D11;
1194   case ARM::D12:
1195     return ARM::D13;
1196   case ARM::D14:
1197     return ARM::D15;
1198   case ARM::D16:
1199     return ARM::D17;
1200   case ARM::D18:
1201     return ARM::D19;
1202   case ARM::D20:
1203     return ARM::D21;
1204   case ARM::D22:
1205     return ARM::D23;
1206   case ARM::D24:
1207     return ARM::D25;
1208   case ARM::D26:
1209     return ARM::D27;
1210   case ARM::D28:
1211     return ARM::D29;
1212   case ARM::D30:
1213     return ARM::D31;
1214   }
1215
1216   return 0;
1217 }
1218
1219 /// emitLoadConstPool - Emits a load from constpool to materialize the
1220 /// specified immediate.
1221 void ARMBaseRegisterInfo::
1222 emitLoadConstPool(MachineBasicBlock &MBB,
1223                   MachineBasicBlock::iterator &MBBI,
1224                   DebugLoc dl,
1225                   unsigned DestReg, unsigned SubIdx, int Val,
1226                   ARMCC::CondCodes Pred,
1227                   unsigned PredReg) const {
1228   MachineFunction &MF = *MBB.getParent();
1229   MachineConstantPool *ConstantPool = MF.getConstantPool();
1230   const Constant *C =
1231         ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
1232   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
1233
1234   BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
1235     .addReg(DestReg, getDefRegState(true), SubIdx)
1236     .addConstantPoolIndex(Idx)
1237     .addImm(0).addImm(Pred).addReg(PredReg);
1238 }
1239
1240 bool ARMBaseRegisterInfo::
1241 requiresRegisterScavenging(const MachineFunction &MF) const {
1242   return true;
1243 }
1244
1245 bool ARMBaseRegisterInfo::
1246 requiresFrameIndexScavenging(const MachineFunction &MF) const {
1247   return true;
1248 }
1249
1250 bool ARMBaseRegisterInfo::
1251 requiresVirtualBaseRegisters(const MachineFunction &MF) const {
1252   return EnableLocalStackAlloc;
1253 }
1254
1255 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
1256 // not required, we reserve argument space for call sites in the function
1257 // immediately on entry to the current function. This eliminates the need for
1258 // add/sub sp brackets around call sites. Returns true if the call frame is
1259 // included as part of the stack frame.
1260 bool ARMBaseRegisterInfo::
1261 hasReservedCallFrame(const MachineFunction &MF) const {
1262   const MachineFrameInfo *FFI = MF.getFrameInfo();
1263   unsigned CFSize = FFI->getMaxCallFrameSize();
1264   // It's not always a good idea to include the call frame as part of the
1265   // stack frame. ARM (especially Thumb) has small immediate offset to
1266   // address the stack frame. So a large call frame can cause poor codegen
1267   // and may even makes it impossible to scavenge a register.
1268   if (CFSize >= ((1 << 12) - 1) / 2)  // Half of imm12
1269     return false;
1270
1271   return !MF.getFrameInfo()->hasVarSizedObjects();
1272 }
1273
1274 // canSimplifyCallFramePseudos - If there is a reserved call frame, the
1275 // call frame pseudos can be simplified. Unlike most targets, having a FP
1276 // is not sufficient here since we still may reference some objects via SP
1277 // even when FP is available in Thumb2 mode.
1278 bool ARMBaseRegisterInfo::
1279 canSimplifyCallFramePseudos(const MachineFunction &MF) const {
1280   return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
1281 }
1282
1283 static void
1284 emitSPUpdate(bool isARM,
1285              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
1286              DebugLoc dl, const ARMBaseInstrInfo &TII,
1287              int NumBytes,
1288              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
1289   if (isARM)
1290     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1291                             Pred, PredReg, TII);
1292   else
1293     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1294                            Pred, PredReg, TII);
1295 }
1296
1297
1298 void ARMBaseRegisterInfo::
1299 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1300                               MachineBasicBlock::iterator I) const {
1301   if (!hasReservedCallFrame(MF)) {
1302     // If we have alloca, convert as follows:
1303     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1304     // ADJCALLSTACKUP   -> add, sp, sp, amount
1305     MachineInstr *Old = I;
1306     DebugLoc dl = Old->getDebugLoc();
1307     unsigned Amount = Old->getOperand(0).getImm();
1308     if (Amount != 0) {
1309       // We need to keep the stack aligned properly.  To do this, we round the
1310       // amount of space needed for the outgoing arguments up to the next
1311       // alignment boundary.
1312       unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1313       Amount = (Amount+Align-1)/Align*Align;
1314
1315       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1316       assert(!AFI->isThumb1OnlyFunction() &&
1317              "This eliminateCallFramePseudoInstr does not support Thumb1!");
1318       bool isARM = !AFI->isThumbFunction();
1319
1320       // Replace the pseudo instruction with a new instruction...
1321       unsigned Opc = Old->getOpcode();
1322       int PIdx = Old->findFirstPredOperandIdx();
1323       ARMCC::CondCodes Pred = (PIdx == -1)
1324         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1325       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1326         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1327         unsigned PredReg = Old->getOperand(2).getReg();
1328         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, Pred, PredReg);
1329       } else {
1330         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1331         unsigned PredReg = Old->getOperand(3).getReg();
1332         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1333         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, Pred, PredReg);
1334       }
1335     }
1336   }
1337   MBB.erase(I);
1338 }
1339
1340 int64_t ARMBaseRegisterInfo::
1341 getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
1342   const TargetInstrDesc &Desc = MI->getDesc();
1343   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1344   int64_t InstrOffs = 0;;
1345   int Scale = 1;
1346   unsigned ImmIdx = 0;
1347   switch (AddrMode) {
1348   case ARMII::AddrModeT2_i8:
1349   case ARMII::AddrModeT2_i12:
1350   case ARMII::AddrMode_i12:
1351     InstrOffs = MI->getOperand(Idx+1).getImm();
1352     Scale = 1;
1353     break;
1354   case ARMII::AddrMode5: {
1355     // VFP address mode.
1356     const MachineOperand &OffOp = MI->getOperand(Idx+1);
1357     InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
1358     if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
1359       InstrOffs = -InstrOffs;
1360     Scale = 4;
1361     break;
1362   }
1363   case ARMII::AddrMode2: {
1364     ImmIdx = Idx+2;
1365     InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
1366     if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1367       InstrOffs = -InstrOffs;
1368     break;
1369   }
1370   case ARMII::AddrMode3: {
1371     ImmIdx = Idx+2;
1372     InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
1373     if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1374       InstrOffs = -InstrOffs;
1375     break;
1376   }
1377   case ARMII::AddrModeT1_s: {
1378     ImmIdx = Idx+1;
1379     InstrOffs = MI->getOperand(ImmIdx).getImm();
1380     Scale = 4;
1381     break;
1382   }
1383   default:
1384     llvm_unreachable("Unsupported addressing mode!");
1385     break;
1386   }
1387
1388   return InstrOffs * Scale;
1389 }
1390
1391 /// needsFrameBaseReg - Returns true if the instruction's frame index
1392 /// reference would be better served by a base register other than FP
1393 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
1394 /// references it should create new base registers for.
1395 bool ARMBaseRegisterInfo::
1396 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
1397   for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
1398     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
1399   }
1400
1401   // It's the load/store FI references that cause issues, as it can be difficult
1402   // to materialize the offset if it won't fit in the literal field. Estimate
1403   // based on the size of the local frame and some conservative assumptions
1404   // about the rest of the stack frame (note, this is pre-regalloc, so
1405   // we don't know everything for certain yet) whether this offset is likely
1406   // to be out of range of the immediate. Return true if so.
1407
1408   // We only generate virtual base registers for loads and stores, so
1409   // return false for everything else.
1410   unsigned Opc = MI->getOpcode();
1411   switch (Opc) {
1412   case ARM::LDRi12: case ARM::LDRH: case ARM::LDRBi12:
1413   case ARM::STRi12: case ARM::STRH: case ARM::STRBi12:
1414   case ARM::t2LDRi12: case ARM::t2LDRi8:
1415   case ARM::t2STRi12: case ARM::t2STRi8:
1416   case ARM::VLDRS: case ARM::VLDRD:
1417   case ARM::VSTRS: case ARM::VSTRD:
1418   case ARM::tSTRspi: case ARM::tLDRspi:
1419     if (ForceAllBaseRegAlloc)
1420       return true;
1421     break;
1422   default:
1423     return false;
1424   }
1425
1426   // Without a virtual base register, if the function has variable sized
1427   // objects, all fixed-size local references will be via the frame pointer,
1428   // Approximate the offset and see if it's legal for the instruction.
1429   // Note that the incoming offset is based on the SP value at function entry,
1430   // so it'll be negative.
1431   MachineFunction &MF = *MI->getParent()->getParent();
1432   MachineFrameInfo *MFI = MF.getFrameInfo();
1433   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1434
1435   // Estimate an offset from the frame pointer.
1436   // Conservatively assume all callee-saved registers get pushed. R4-R6
1437   // will be earlier than the FP, so we ignore those.
1438   // R7, LR
1439   int64_t FPOffset = Offset - 8;
1440   // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
1441   if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
1442     FPOffset -= 80;
1443   // Estimate an offset from the stack pointer.
1444   // The incoming offset is relating to the SP at the start of the function,
1445   // but when we access the local it'll be relative to the SP after local
1446   // allocation, so adjust our SP-relative offset by that allocation size.
1447   Offset = -Offset;
1448   Offset += MFI->getLocalFrameSize();
1449   // Assume that we'll have at least some spill slots allocated.
1450   // FIXME: This is a total SWAG number. We should run some statistics
1451   //        and pick a real one.
1452   Offset += 128; // 128 bytes of spill slots
1453
1454   // If there is a frame pointer, try using it.
1455   // The FP is only available if there is no dynamic realignment. We
1456   // don't know for sure yet whether we'll need that, so we guess based
1457   // on whether there are any local variables that would trigger it.
1458   unsigned StackAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1459   if (hasFP(MF) &&
1460       !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
1461     if (isFrameOffsetLegal(MI, FPOffset))
1462       return false;
1463   }
1464   // If we can reference via the stack pointer, try that.
1465   // FIXME: This (and the code that resolves the references) can be improved
1466   //        to only disallow SP relative references in the live range of
1467   //        the VLA(s). In practice, it's unclear how much difference that
1468   //        would make, but it may be worth doing.
1469   if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
1470     return false;
1471
1472   // The offset likely isn't legal, we want to allocate a virtual base register.
1473   return true;
1474 }
1475
1476 /// materializeFrameBaseRegister - Insert defining instruction(s) for
1477 /// BaseReg to be a pointer to FrameIdx before insertion point I.
1478 void ARMBaseRegisterInfo::
1479 materializeFrameBaseRegister(MachineBasicBlock::iterator I, unsigned BaseReg,
1480                              int FrameIdx, int64_t Offset) const {
1481   ARMFunctionInfo *AFI =
1482     I->getParent()->getParent()->getInfo<ARMFunctionInfo>();
1483   unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
1484     (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
1485
1486   MachineInstrBuilder MIB =
1487     BuildMI(*I->getParent(), I, I->getDebugLoc(), TII.get(ADDriOpc), BaseReg)
1488     .addFrameIndex(FrameIdx).addImm(Offset);
1489   if (!AFI->isThumb1OnlyFunction())
1490     AddDefaultCC(AddDefaultPred(MIB));
1491 }
1492
1493 void
1494 ARMBaseRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
1495                                        unsigned BaseReg, int64_t Offset) const {
1496   MachineInstr &MI = *I;
1497   MachineBasicBlock &MBB = *MI.getParent();
1498   MachineFunction &MF = *MBB.getParent();
1499   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1500   int Off = Offset; // ARM doesn't need the general 64-bit offsets
1501   unsigned i = 0;
1502
1503   assert(!AFI->isThumb1OnlyFunction() &&
1504          "This resolveFrameIndex does not support Thumb1!");
1505
1506   while (!MI.getOperand(i).isFI()) {
1507     ++i;
1508     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
1509   }
1510   bool Done = false;
1511   if (!AFI->isThumbFunction())
1512     Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
1513   else {
1514     assert(AFI->isThumb2Function());
1515     Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
1516   }
1517   assert (Done && "Unable to resolve frame index!");
1518 }
1519
1520 bool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
1521                                              int64_t Offset) const {
1522   const TargetInstrDesc &Desc = MI->getDesc();
1523   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1524   unsigned i = 0;
1525
1526   while (!MI->getOperand(i).isFI()) {
1527     ++i;
1528     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
1529   }
1530
1531   // AddrMode4 and AddrMode6 cannot handle any offset.
1532   if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
1533     return Offset == 0;
1534
1535   unsigned NumBits = 0;
1536   unsigned Scale = 1;
1537   bool isSigned = true;
1538   switch (AddrMode) {
1539   case ARMII::AddrModeT2_i8:
1540   case ARMII::AddrModeT2_i12:
1541     // i8 supports only negative, and i12 supports only positive, so
1542     // based on Offset sign, consider the appropriate instruction
1543     Scale = 1;
1544     if (Offset < 0) {
1545       NumBits = 8;
1546       Offset = -Offset;
1547     } else {
1548       NumBits = 12;
1549     }
1550     break;
1551   case ARMII::AddrMode5:
1552     // VFP address mode.
1553     NumBits = 8;
1554     Scale = 4;
1555     break;
1556   case ARMII::AddrMode_i12:
1557   case ARMII::AddrMode2:
1558     NumBits = 12;
1559     break;
1560   case ARMII::AddrMode3:
1561     NumBits = 8;
1562     break;
1563   case ARMII::AddrModeT1_s:
1564     NumBits = 5;
1565     Scale = 4;
1566     isSigned = false;
1567     break;
1568   default:
1569     llvm_unreachable("Unsupported addressing mode!");
1570     break;
1571   }
1572
1573   Offset += getFrameIndexInstrOffset(MI, i);
1574   // Make sure the offset is encodable for instructions that scale the
1575   // immediate.
1576   if ((Offset & (Scale-1)) != 0)
1577     return false;
1578
1579   if (isSigned && Offset < 0)
1580     Offset = -Offset;
1581
1582   unsigned Mask = (1 << NumBits) - 1;
1583   if ((unsigned)Offset <= Mask * Scale)
1584     return true;
1585
1586   return false;
1587 }
1588
1589 void
1590 ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
1591                                          int SPAdj, RegScavenger *RS) const {
1592   unsigned i = 0;
1593   MachineInstr &MI = *II;
1594   MachineBasicBlock &MBB = *MI.getParent();
1595   MachineFunction &MF = *MBB.getParent();
1596   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1597   assert(!AFI->isThumb1OnlyFunction() &&
1598          "This eliminateFrameIndex does not support Thumb1!");
1599
1600   while (!MI.getOperand(i).isFI()) {
1601     ++i;
1602     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
1603   }
1604
1605   int FrameIndex = MI.getOperand(i).getIndex();
1606   unsigned FrameReg;
1607
1608   int Offset = ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
1609
1610   // Special handling of dbg_value instructions.
1611   if (MI.isDebugValue()) {
1612     MI.getOperand(i).  ChangeToRegister(FrameReg, false /*isDef*/);
1613     MI.getOperand(i+1).ChangeToImmediate(Offset);
1614     return;
1615   }
1616
1617   // Modify MI as necessary to handle as much of 'Offset' as possible
1618   bool Done = false;
1619   if (!AFI->isThumbFunction())
1620     Done = rewriteARMFrameIndex(MI, i, FrameReg, Offset, TII);
1621   else {
1622     assert(AFI->isThumb2Function());
1623     Done = rewriteT2FrameIndex(MI, i, FrameReg, Offset, TII);
1624   }
1625   if (Done)
1626     return;
1627
1628   // If we get here, the immediate doesn't fit into the instruction.  We folded
1629   // as much as possible above, handle the rest, providing a register that is
1630   // SP+LargeImm.
1631   assert((Offset ||
1632           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
1633           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
1634          "This code isn't needed if offset already handled!");
1635
1636   unsigned ScratchReg = 0;
1637   int PIdx = MI.findFirstPredOperandIdx();
1638   ARMCC::CondCodes Pred = (PIdx == -1)
1639     ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
1640   unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
1641   if (Offset == 0)
1642     // Must be addrmode4/6.
1643     MI.getOperand(i).ChangeToRegister(FrameReg, false, false, false);
1644   else {
1645     ScratchReg = MF.getRegInfo().createVirtualRegister(ARM::GPRRegisterClass);
1646     if (!AFI->isThumbFunction())
1647       emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1648                               Offset, Pred, PredReg, TII);
1649     else {
1650       assert(AFI->isThumb2Function());
1651       emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1652                              Offset, Pred, PredReg, TII);
1653     }
1654     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
1655   }
1656 }
1657
1658 #include "ARMGenRegisterInfo.inc"