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