68e7ce53c63ba9f17f26f9d3698a78e66d6c5ee1
[oota-llvm.git] / lib / Target / ARM / ARMBaseRegisterInfo.cpp
1 //===-- ARMBaseRegisterInfo.cpp - ARM Register Information ----------------===//
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 "ARMBaseRegisterInfo.h"
15 #include "ARM.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMFrameLowering.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMSubtarget.h"
20 #include "MCTargetDesc/ARMAddressingModes.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/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/RegisterScavenging.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetFrameLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/ADT/BitVector.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/Support/CommandLine.h"
40
41 #define GET_REGINFO_TARGET_DESC
42 #include "ARMGenRegisterInfo.inc"
43
44 using namespace llvm;
45
46 static cl::opt<bool>
47 ForceAllBaseRegAlloc("arm-force-base-reg-alloc", cl::Hidden, cl::init(false),
48           cl::desc("Force use of virtual base registers for stack load/store"));
49 static cl::opt<bool>
50 EnableLocalStackAlloc("enable-local-stack-alloc", cl::init(true), cl::Hidden,
51           cl::desc("Enable pre-regalloc stack frame index allocation"));
52 static cl::opt<bool>
53 EnableBasePointer("arm-use-base-pointer", cl::Hidden, cl::init(true),
54           cl::desc("Enable use of a base pointer for complex stack frames"));
55
56 ARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMBaseInstrInfo &tii,
57                                          const ARMSubtarget &sti)
58   : ARMGenRegisterInfo(ARM::LR), TII(tii), STI(sti),
59     FramePtr((STI.isTargetDarwin() || STI.isThumb()) ? ARM::R7 : ARM::R11),
60     BasePtr(ARM::R6) {
61 }
62
63 const uint16_t*
64 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
65   bool ghcCall = false;
66  
67   if (MF) {
68     const Function *F = MF->getFunction();
69     ghcCall = (F ? F->getCallingConv() == CallingConv::GHC : false);
70   }
71  
72   if (ghcCall) {
73       return CSR_GHC_SaveList;
74   }
75   else {
76   return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
77     ? CSR_iOS_SaveList : CSR_AAPCS_SaveList;
78   }
79 }
80
81 const uint32_t*
82 ARMBaseRegisterInfo::getCallPreservedMask(CallingConv::ID) const {
83   return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
84     ? CSR_iOS_RegMask : CSR_AAPCS_RegMask;
85 }
86
87 BitVector ARMBaseRegisterInfo::
88 getReservedRegs(const MachineFunction &MF) const {
89   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
90
91   // FIXME: avoid re-calculating this every time.
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   // Reserve D16-D31 if the subtarget doesn't support them.
104   if (!STI.hasVFP3() || STI.hasD16()) {
105     assert(ARM::D31 == ARM::D16 + 15);
106     for (unsigned i = 0; i != 16; ++i)
107       Reserved.set(ARM::D16 + i);
108   }
109   return Reserved;
110 }
111
112 bool ARMBaseRegisterInfo::isReservedReg(const MachineFunction &MF,
113                                         unsigned Reg) const {
114   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
115
116   switch (Reg) {
117   default: break;
118   case ARM::SP:
119   case ARM::PC:
120     return true;
121   case ARM::R6:
122     if (hasBasePointer(MF))
123       return true;
124     break;
125   case ARM::R7:
126   case ARM::R11:
127     if (FramePtr == Reg && TFI->hasFP(MF))
128       return true;
129     break;
130   case ARM::R9:
131     return STI.isR9Reserved();
132   }
133
134   return false;
135 }
136
137 const TargetRegisterClass*
138 ARMBaseRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC)
139                                                                          const {
140   const TargetRegisterClass *Super = RC;
141   TargetRegisterClass::sc_iterator I = RC->getSuperClasses();
142   do {
143     switch (Super->getID()) {
144     case ARM::GPRRegClassID:
145     case ARM::SPRRegClassID:
146     case ARM::DPRRegClassID:
147     case ARM::QPRRegClassID:
148     case ARM::QQPRRegClassID:
149     case ARM::QQQQPRRegClassID:
150       return Super;
151     }
152     Super = *I++;
153   } while (Super);
154   return RC;
155 }
156
157 const TargetRegisterClass *
158 ARMBaseRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
159                                                                          const {
160   return &ARM::GPRRegClass;
161 }
162
163 const TargetRegisterClass *
164 ARMBaseRegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
165   if (RC == &ARM::CCRRegClass)
166     return 0;  // Can't copy CCR registers.
167   return RC;
168 }
169
170 unsigned
171 ARMBaseRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
172                                          MachineFunction &MF) const {
173   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
174
175   switch (RC->getID()) {
176   default:
177     return 0;
178   case ARM::tGPRRegClassID:
179     return TFI->hasFP(MF) ? 4 : 5;
180   case ARM::GPRRegClassID: {
181     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
182     return 10 - FP - (STI.isR9Reserved() ? 1 : 0);
183   }
184   case ARM::SPRRegClassID:  // Currently not used as 'rep' register class.
185   case ARM::DPRRegClassID:
186     return 32 - 10;
187   }
188 }
189
190 /// getRawAllocationOrder - Returns the register allocation order for a
191 /// specified register class with a target-dependent hint.
192 ArrayRef<uint16_t>
193 ARMBaseRegisterInfo::getRawAllocationOrder(const TargetRegisterClass *RC,
194                                            unsigned HintType, unsigned HintReg,
195                                            const MachineFunction &MF) const {
196   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
197   // Alternative register allocation orders when favoring even / odd registers
198   // of register pairs.
199
200   // No FP, R9 is available.
201   static const uint16_t GPREven1[] = {
202     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8, ARM::R10,
203     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7,
204     ARM::R9, ARM::R11
205   };
206   static const uint16_t GPROdd1[] = {
207     ARM::R1, ARM::R3, ARM::R5, ARM::R7, ARM::R9, ARM::R11,
208     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
209     ARM::R8, ARM::R10
210   };
211
212   // FP is R7, R9 is available.
213   static const uint16_t GPREven2[] = {
214     ARM::R0, ARM::R2, ARM::R4,          ARM::R8, ARM::R10,
215     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6,
216     ARM::R9, ARM::R11
217   };
218   static const uint16_t GPROdd2[] = {
219     ARM::R1, ARM::R3, ARM::R5,          ARM::R9, ARM::R11,
220     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
221     ARM::R8, ARM::R10
222   };
223
224   // FP is R11, R9 is available.
225   static const uint16_t GPREven3[] = {
226     ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8,
227     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7,
228     ARM::R9
229   };
230   static const uint16_t GPROdd3[] = {
231     ARM::R1, ARM::R3, ARM::R5, ARM::R6, ARM::R9,
232     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R7,
233     ARM::R8
234   };
235
236   // No FP, R9 is not available.
237   static const uint16_t GPREven4[] = {
238     ARM::R0, ARM::R2, ARM::R4, ARM::R6,          ARM::R10,
239     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8,
240     ARM::R11
241   };
242   static const uint16_t GPROdd4[] = {
243     ARM::R1, ARM::R3, ARM::R5, ARM::R7,          ARM::R11,
244     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
245     ARM::R10
246   };
247
248   // FP is R7, R9 is not available.
249   static const uint16_t GPREven5[] = {
250     ARM::R0, ARM::R2, ARM::R4,                   ARM::R10,
251     ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6, ARM::R8,
252     ARM::R11
253   };
254   static const uint16_t GPROdd5[] = {
255     ARM::R1, ARM::R3, ARM::R5,                   ARM::R11,
256     ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
257     ARM::R10
258   };
259
260   // FP is R11, R9 is not available.
261   static const uint16_t GPREven6[] = {
262     ARM::R0, ARM::R2, ARM::R4, ARM::R6,
263     ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8
264   };
265   static const uint16_t GPROdd6[] = {
266     ARM::R1, ARM::R3, ARM::R5, ARM::R7,
267     ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8
268   };
269
270   // We only support even/odd hints for GPR and rGPR.
271   if (RC != &ARM::GPRRegClass && RC != &ARM::rGPRRegClass)
272     return RC->getRawAllocationOrder(MF);
273
274   if (HintType == ARMRI::RegPairEven) {
275     if (isPhysicalRegister(HintReg) && getRegisterPairEven(HintReg, MF) == 0)
276       // It's no longer possible to fulfill this hint. Return the default
277       // allocation order.
278       return RC->getRawAllocationOrder(MF);
279
280     if (!TFI->hasFP(MF)) {
281       if (!STI.isR9Reserved())
282         return makeArrayRef(GPREven1);
283       else
284         return makeArrayRef(GPREven4);
285     } else if (FramePtr == ARM::R7) {
286       if (!STI.isR9Reserved())
287         return makeArrayRef(GPREven2);
288       else
289         return makeArrayRef(GPREven5);
290     } else { // FramePtr == ARM::R11
291       if (!STI.isR9Reserved())
292         return makeArrayRef(GPREven3);
293       else
294         return makeArrayRef(GPREven6);
295     }
296   } else if (HintType == ARMRI::RegPairOdd) {
297     if (isPhysicalRegister(HintReg) && getRegisterPairOdd(HintReg, MF) == 0)
298       // It's no longer possible to fulfill this hint. Return the default
299       // allocation order.
300       return RC->getRawAllocationOrder(MF);
301
302     if (!TFI->hasFP(MF)) {
303       if (!STI.isR9Reserved())
304         return makeArrayRef(GPROdd1);
305       else
306         return makeArrayRef(GPROdd4);
307     } else if (FramePtr == ARM::R7) {
308       if (!STI.isR9Reserved())
309         return makeArrayRef(GPROdd2);
310       else
311         return makeArrayRef(GPROdd5);
312     } else { // FramePtr == ARM::R11
313       if (!STI.isR9Reserved())
314         return makeArrayRef(GPROdd3);
315       else
316         return makeArrayRef(GPROdd6);
317     }
318   }
319   return RC->getRawAllocationOrder(MF);
320 }
321
322 /// ResolveRegAllocHint - Resolves the specified register allocation hint
323 /// to a physical register. Returns the physical register if it is successful.
324 unsigned
325 ARMBaseRegisterInfo::ResolveRegAllocHint(unsigned Type, unsigned Reg,
326                                          const MachineFunction &MF) const {
327   if (Reg == 0 || !isPhysicalRegister(Reg))
328     return 0;
329   if (Type == 0)
330     return Reg;
331   else if (Type == (unsigned)ARMRI::RegPairOdd)
332     // Odd register.
333     return getRegisterPairOdd(Reg, MF);
334   else if (Type == (unsigned)ARMRI::RegPairEven)
335     // Even register.
336     return getRegisterPairEven(Reg, MF);
337   return 0;
338 }
339
340 void
341 ARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
342                                         MachineFunction &MF) const {
343   MachineRegisterInfo *MRI = &MF.getRegInfo();
344   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
345   if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
346        Hint.first == (unsigned)ARMRI::RegPairEven) &&
347       TargetRegisterInfo::isVirtualRegister(Hint.second)) {
348     // If 'Reg' is one of the even / odd register pair and it's now changed
349     // (e.g. coalesced) into a different register. The other register of the
350     // pair allocation hint must be updated to reflect the relationship
351     // change.
352     unsigned OtherReg = Hint.second;
353     Hint = MRI->getRegAllocationHint(OtherReg);
354     if (Hint.second == Reg)
355       // Make sure the pair has not already divorced.
356       MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
357   }
358 }
359
360 bool
361 ARMBaseRegisterInfo::avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
362   // CortexA9 has a Write-after-write hazard for NEON registers.
363   if (!STI.isLikeA9())
364     return false;
365
366   switch (RC->getID()) {
367   case ARM::DPRRegClassID:
368   case ARM::DPR_8RegClassID:
369   case ARM::DPR_VFP2RegClassID:
370   case ARM::QPRRegClassID:
371   case ARM::QPR_8RegClassID:
372   case ARM::QPR_VFP2RegClassID:
373   case ARM::SPRRegClassID:
374   case ARM::SPR_8RegClassID:
375     // Avoid reusing S, D, and Q registers.
376     // Don't increase register pressure for QQ and QQQQ.
377     return true;
378   default:
379     return false;
380   }
381 }
382
383 bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
384   const MachineFrameInfo *MFI = MF.getFrameInfo();
385   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
386   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
387
388   if (!EnableBasePointer)
389     return false;
390
391   // When outgoing call frames are so large that we adjust the stack pointer
392   // around the call, we can no longer use the stack pointer to reach the
393   // emergency spill slot.
394   if (needsStackRealignment(MF) && !TFI->hasReservedCallFrame(MF))
395     return true;
396
397   // Thumb has trouble with negative offsets from the FP. Thumb2 has a limited
398   // negative range for ldr/str (255), and thumb1 is positive offsets only.
399   // It's going to be better to use the SP or Base Pointer instead. When there
400   // are variable sized objects, we can't reference off of the SP, so we
401   // reserve a Base Pointer.
402   if (AFI->isThumbFunction() && MFI->hasVarSizedObjects()) {
403     // Conservatively estimate whether the negative offset from the frame
404     // pointer will be sufficient to reach. If a function has a smallish
405     // frame, it's less likely to have lots of spills and callee saved
406     // space, so it's all more likely to be within range of the frame pointer.
407     // If it's wrong, the scavenger will still enable access to work, it just
408     // won't be optimal.
409     if (AFI->isThumb2Function() && MFI->getLocalFrameSize() < 128)
410       return false;
411     return true;
412   }
413
414   return false;
415 }
416
417 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
418   const MachineRegisterInfo *MRI = &MF.getRegInfo();
419   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
420   // We can't realign the stack if:
421   // 1. Dynamic stack realignment is explicitly disabled,
422   // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
423   // 3. There are VLAs in the function and the base pointer is disabled.
424   if (!MF.getTarget().Options.RealignStack)
425     return false;
426   if (AFI->isThumb1OnlyFunction())
427     return false;
428   // Stack realignment requires a frame pointer.  If we already started
429   // register allocation with frame pointer elimination, it is too late now.
430   if (!MRI->canReserveReg(FramePtr))
431     return false;
432   // We may also need a base pointer if there are dynamic allocas or stack
433   // pointer adjustments around calls.
434   if (MF.getTarget().getFrameLowering()->hasReservedCallFrame(MF))
435     return true;
436   if (!EnableBasePointer)
437     return false;
438   // A base pointer is required and allowed.  Check that it isn't too late to
439   // reserve it.
440   return MRI->canReserveReg(BasePtr);
441 }
442
443 bool ARMBaseRegisterInfo::
444 needsStackRealignment(const MachineFunction &MF) const {
445   const MachineFrameInfo *MFI = MF.getFrameInfo();
446   const Function *F = MF.getFunction();
447   unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
448   bool requiresRealignment =
449     ((MFI->getMaxAlignment() > StackAlign) ||
450      F->getFnAttributes().hasAttribute(Attributes::StackAlignment));
451
452   return requiresRealignment && canRealignStack(MF);
453 }
454
455 bool ARMBaseRegisterInfo::
456 cannotEliminateFrame(const MachineFunction &MF) const {
457   const MachineFrameInfo *MFI = MF.getFrameInfo();
458   if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI->adjustsStack())
459     return true;
460   return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
461     || needsStackRealignment(MF);
462 }
463
464 unsigned
465 ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
466   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
467
468   if (TFI->hasFP(MF))
469     return FramePtr;
470   return ARM::SP;
471 }
472
473 unsigned ARMBaseRegisterInfo::getEHExceptionRegister() const {
474   llvm_unreachable("What is the exception register");
475 }
476
477 unsigned ARMBaseRegisterInfo::getEHHandlerRegister() const {
478   llvm_unreachable("What is the exception handler register");
479 }
480
481 unsigned ARMBaseRegisterInfo::getRegisterPairEven(unsigned Reg,
482                                               const MachineFunction &MF) const {
483   switch (Reg) {
484   default: break;
485   // Return 0 if either register of the pair is a special register.
486   // So no R12, etc.
487   case ARM::R1: return ARM::R0;
488   case ARM::R3: return ARM::R2;
489   case ARM::R5: return ARM::R4;
490   case ARM::R7:
491     return (isReservedReg(MF, ARM::R7) || isReservedReg(MF, ARM::R6))
492       ? 0 : ARM::R6;
493   case ARM::R9: return isReservedReg(MF, ARM::R9)  ? 0 :ARM::R8;
494   case ARM::R11: return isReservedReg(MF, ARM::R11) ? 0 : ARM::R10;
495
496   case ARM::S1: return ARM::S0;
497   case ARM::S3: return ARM::S2;
498   case ARM::S5: return ARM::S4;
499   case ARM::S7: return ARM::S6;
500   case ARM::S9: return ARM::S8;
501   case ARM::S11: return ARM::S10;
502   case ARM::S13: return ARM::S12;
503   case ARM::S15: return ARM::S14;
504   case ARM::S17: return ARM::S16;
505   case ARM::S19: return ARM::S18;
506   case ARM::S21: return ARM::S20;
507   case ARM::S23: return ARM::S22;
508   case ARM::S25: return ARM::S24;
509   case ARM::S27: return ARM::S26;
510   case ARM::S29: return ARM::S28;
511   case ARM::S31: return ARM::S30;
512
513   case ARM::D1: return ARM::D0;
514   case ARM::D3: return ARM::D2;
515   case ARM::D5: return ARM::D4;
516   case ARM::D7: return ARM::D6;
517   case ARM::D9: return ARM::D8;
518   case ARM::D11: return ARM::D10;
519   case ARM::D13: return ARM::D12;
520   case ARM::D15: return ARM::D14;
521   case ARM::D17: return ARM::D16;
522   case ARM::D19: return ARM::D18;
523   case ARM::D21: return ARM::D20;
524   case ARM::D23: return ARM::D22;
525   case ARM::D25: return ARM::D24;
526   case ARM::D27: return ARM::D26;
527   case ARM::D29: return ARM::D28;
528   case ARM::D31: return ARM::D30;
529   }
530
531   return 0;
532 }
533
534 unsigned ARMBaseRegisterInfo::getRegisterPairOdd(unsigned Reg,
535                                              const MachineFunction &MF) const {
536   switch (Reg) {
537   default: break;
538   // Return 0 if either register of the pair is a special register.
539   // So no R12, etc.
540   case ARM::R0: return ARM::R1;
541   case ARM::R2: return ARM::R3;
542   case ARM::R4: return ARM::R5;
543   case ARM::R6:
544     return (isReservedReg(MF, ARM::R7) || isReservedReg(MF, ARM::R6))
545       ? 0 : ARM::R7;
546   case ARM::R8: return isReservedReg(MF, ARM::R9)  ? 0 :ARM::R9;
547   case ARM::R10: return isReservedReg(MF, ARM::R11) ? 0 : ARM::R11;
548
549   case ARM::S0: return ARM::S1;
550   case ARM::S2: return ARM::S3;
551   case ARM::S4: return ARM::S5;
552   case ARM::S6: return ARM::S7;
553   case ARM::S8: return ARM::S9;
554   case ARM::S10: return ARM::S11;
555   case ARM::S12: return ARM::S13;
556   case ARM::S14: return ARM::S15;
557   case ARM::S16: return ARM::S17;
558   case ARM::S18: return ARM::S19;
559   case ARM::S20: return ARM::S21;
560   case ARM::S22: return ARM::S23;
561   case ARM::S24: return ARM::S25;
562   case ARM::S26: return ARM::S27;
563   case ARM::S28: return ARM::S29;
564   case ARM::S30: return ARM::S31;
565
566   case ARM::D0: return ARM::D1;
567   case ARM::D2: return ARM::D3;
568   case ARM::D4: return ARM::D5;
569   case ARM::D6: return ARM::D7;
570   case ARM::D8: return ARM::D9;
571   case ARM::D10: return ARM::D11;
572   case ARM::D12: return ARM::D13;
573   case ARM::D14: return ARM::D15;
574   case ARM::D16: return ARM::D17;
575   case ARM::D18: return ARM::D19;
576   case ARM::D20: return ARM::D21;
577   case ARM::D22: return ARM::D23;
578   case ARM::D24: return ARM::D25;
579   case ARM::D26: return ARM::D27;
580   case ARM::D28: return ARM::D29;
581   case ARM::D30: return ARM::D31;
582   }
583
584   return 0;
585 }
586
587 /// emitLoadConstPool - Emits a load from constpool to materialize the
588 /// specified immediate.
589 void ARMBaseRegisterInfo::
590 emitLoadConstPool(MachineBasicBlock &MBB,
591                   MachineBasicBlock::iterator &MBBI,
592                   DebugLoc dl,
593                   unsigned DestReg, unsigned SubIdx, int Val,
594                   ARMCC::CondCodes Pred,
595                   unsigned PredReg, unsigned MIFlags) const {
596   MachineFunction &MF = *MBB.getParent();
597   MachineConstantPool *ConstantPool = MF.getConstantPool();
598   const Constant *C =
599         ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
600   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
601
602   BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
603     .addReg(DestReg, getDefRegState(true), SubIdx)
604     .addConstantPoolIndex(Idx)
605     .addImm(0).addImm(Pred).addReg(PredReg)
606     .setMIFlags(MIFlags);
607 }
608
609 bool ARMBaseRegisterInfo::
610 requiresRegisterScavenging(const MachineFunction &MF) const {
611   return true;
612 }
613
614 bool ARMBaseRegisterInfo::
615 trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
616   return true;
617 }
618
619 bool ARMBaseRegisterInfo::
620 requiresFrameIndexScavenging(const MachineFunction &MF) const {
621   return true;
622 }
623
624 bool ARMBaseRegisterInfo::
625 requiresVirtualBaseRegisters(const MachineFunction &MF) const {
626   return EnableLocalStackAlloc;
627 }
628
629 static void
630 emitSPUpdate(bool isARM,
631              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
632              DebugLoc dl, const ARMBaseInstrInfo &TII,
633              int NumBytes,
634              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
635   if (isARM)
636     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
637                             Pred, PredReg, TII);
638   else
639     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
640                            Pred, PredReg, TII);
641 }
642
643
644 void ARMBaseRegisterInfo::
645 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
646                               MachineBasicBlock::iterator I) const {
647   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
648   if (!TFI->hasReservedCallFrame(MF)) {
649     // If we have alloca, convert as follows:
650     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
651     // ADJCALLSTACKUP   -> add, sp, sp, amount
652     MachineInstr *Old = I;
653     DebugLoc dl = Old->getDebugLoc();
654     unsigned Amount = Old->getOperand(0).getImm();
655     if (Amount != 0) {
656       // We need to keep the stack aligned properly.  To do this, we round the
657       // amount of space needed for the outgoing arguments up to the next
658       // alignment boundary.
659       unsigned Align = TFI->getStackAlignment();
660       Amount = (Amount+Align-1)/Align*Align;
661
662       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
663       assert(!AFI->isThumb1OnlyFunction() &&
664              "This eliminateCallFramePseudoInstr does not support Thumb1!");
665       bool isARM = !AFI->isThumbFunction();
666
667       // Replace the pseudo instruction with a new instruction...
668       unsigned Opc = Old->getOpcode();
669       int PIdx = Old->findFirstPredOperandIdx();
670       ARMCC::CondCodes Pred = (PIdx == -1)
671         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
672       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
673         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
674         unsigned PredReg = Old->getOperand(2).getReg();
675         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, Pred, PredReg);
676       } else {
677         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
678         unsigned PredReg = Old->getOperand(3).getReg();
679         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
680         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, Pred, PredReg);
681       }
682     }
683   }
684   MBB.erase(I);
685 }
686
687 int64_t ARMBaseRegisterInfo::
688 getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
689   const MCInstrDesc &Desc = MI->getDesc();
690   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
691   int64_t InstrOffs = 0;
692   int Scale = 1;
693   unsigned ImmIdx = 0;
694   switch (AddrMode) {
695   case ARMII::AddrModeT2_i8:
696   case ARMII::AddrModeT2_i12:
697   case ARMII::AddrMode_i12:
698     InstrOffs = MI->getOperand(Idx+1).getImm();
699     Scale = 1;
700     break;
701   case ARMII::AddrMode5: {
702     // VFP address mode.
703     const MachineOperand &OffOp = MI->getOperand(Idx+1);
704     InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
705     if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
706       InstrOffs = -InstrOffs;
707     Scale = 4;
708     break;
709   }
710   case ARMII::AddrMode2: {
711     ImmIdx = Idx+2;
712     InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
713     if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
714       InstrOffs = -InstrOffs;
715     break;
716   }
717   case ARMII::AddrMode3: {
718     ImmIdx = Idx+2;
719     InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
720     if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
721       InstrOffs = -InstrOffs;
722     break;
723   }
724   case ARMII::AddrModeT1_s: {
725     ImmIdx = Idx+1;
726     InstrOffs = MI->getOperand(ImmIdx).getImm();
727     Scale = 4;
728     break;
729   }
730   default:
731     llvm_unreachable("Unsupported addressing mode!");
732   }
733
734   return InstrOffs * Scale;
735 }
736
737 /// needsFrameBaseReg - Returns true if the instruction's frame index
738 /// reference would be better served by a base register other than FP
739 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
740 /// references it should create new base registers for.
741 bool ARMBaseRegisterInfo::
742 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
743   for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
744     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
745   }
746
747   // It's the load/store FI references that cause issues, as it can be difficult
748   // to materialize the offset if it won't fit in the literal field. Estimate
749   // based on the size of the local frame and some conservative assumptions
750   // about the rest of the stack frame (note, this is pre-regalloc, so
751   // we don't know everything for certain yet) whether this offset is likely
752   // to be out of range of the immediate. Return true if so.
753
754   // We only generate virtual base registers for loads and stores, so
755   // return false for everything else.
756   unsigned Opc = MI->getOpcode();
757   switch (Opc) {
758   case ARM::LDRi12: case ARM::LDRH: case ARM::LDRBi12:
759   case ARM::STRi12: case ARM::STRH: case ARM::STRBi12:
760   case ARM::t2LDRi12: case ARM::t2LDRi8:
761   case ARM::t2STRi12: case ARM::t2STRi8:
762   case ARM::VLDRS: case ARM::VLDRD:
763   case ARM::VSTRS: case ARM::VSTRD:
764   case ARM::tSTRspi: case ARM::tLDRspi:
765     if (ForceAllBaseRegAlloc)
766       return true;
767     break;
768   default:
769     return false;
770   }
771
772   // Without a virtual base register, if the function has variable sized
773   // objects, all fixed-size local references will be via the frame pointer,
774   // Approximate the offset and see if it's legal for the instruction.
775   // Note that the incoming offset is based on the SP value at function entry,
776   // so it'll be negative.
777   MachineFunction &MF = *MI->getParent()->getParent();
778   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
779   MachineFrameInfo *MFI = MF.getFrameInfo();
780   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
781
782   // Estimate an offset from the frame pointer.
783   // Conservatively assume all callee-saved registers get pushed. R4-R6
784   // will be earlier than the FP, so we ignore those.
785   // R7, LR
786   int64_t FPOffset = Offset - 8;
787   // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
788   if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
789     FPOffset -= 80;
790   // Estimate an offset from the stack pointer.
791   // The incoming offset is relating to the SP at the start of the function,
792   // but when we access the local it'll be relative to the SP after local
793   // allocation, so adjust our SP-relative offset by that allocation size.
794   Offset = -Offset;
795   Offset += MFI->getLocalFrameSize();
796   // Assume that we'll have at least some spill slots allocated.
797   // FIXME: This is a total SWAG number. We should run some statistics
798   //        and pick a real one.
799   Offset += 128; // 128 bytes of spill slots
800
801   // If there is a frame pointer, try using it.
802   // The FP is only available if there is no dynamic realignment. We
803   // don't know for sure yet whether we'll need that, so we guess based
804   // on whether there are any local variables that would trigger it.
805   unsigned StackAlign = TFI->getStackAlignment();
806   if (TFI->hasFP(MF) &&
807       !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
808     if (isFrameOffsetLegal(MI, FPOffset))
809       return false;
810   }
811   // If we can reference via the stack pointer, try that.
812   // FIXME: This (and the code that resolves the references) can be improved
813   //        to only disallow SP relative references in the live range of
814   //        the VLA(s). In practice, it's unclear how much difference that
815   //        would make, but it may be worth doing.
816   if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
817     return false;
818
819   // The offset likely isn't legal, we want to allocate a virtual base register.
820   return true;
821 }
822
823 /// materializeFrameBaseRegister - Insert defining instruction(s) for BaseReg to
824 /// be a pointer to FrameIdx at the beginning of the basic block.
825 void ARMBaseRegisterInfo::
826 materializeFrameBaseRegister(MachineBasicBlock *MBB,
827                              unsigned BaseReg, int FrameIdx,
828                              int64_t Offset) const {
829   ARMFunctionInfo *AFI = MBB->getParent()->getInfo<ARMFunctionInfo>();
830   unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
831     (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
832
833   MachineBasicBlock::iterator Ins = MBB->begin();
834   DebugLoc DL;                  // Defaults to "unknown"
835   if (Ins != MBB->end())
836     DL = Ins->getDebugLoc();
837
838   const MCInstrDesc &MCID = TII.get(ADDriOpc);
839   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
840   const MachineFunction &MF = *MBB->getParent();
841   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
842
843   MachineInstrBuilder MIB = AddDefaultPred(BuildMI(*MBB, Ins, DL, MCID, BaseReg)
844     .addFrameIndex(FrameIdx).addImm(Offset));
845
846   if (!AFI->isThumb1OnlyFunction())
847     AddDefaultCC(MIB);
848 }
849
850 void
851 ARMBaseRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
852                                        unsigned BaseReg, int64_t Offset) const {
853   MachineInstr &MI = *I;
854   MachineBasicBlock &MBB = *MI.getParent();
855   MachineFunction &MF = *MBB.getParent();
856   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
857   int Off = Offset; // ARM doesn't need the general 64-bit offsets
858   unsigned i = 0;
859
860   assert(!AFI->isThumb1OnlyFunction() &&
861          "This resolveFrameIndex does not support Thumb1!");
862
863   while (!MI.getOperand(i).isFI()) {
864     ++i;
865     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
866   }
867   bool Done = false;
868   if (!AFI->isThumbFunction())
869     Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
870   else {
871     assert(AFI->isThumb2Function());
872     Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
873   }
874   assert (Done && "Unable to resolve frame index!");
875   (void)Done;
876 }
877
878 bool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
879                                              int64_t Offset) const {
880   const MCInstrDesc &Desc = MI->getDesc();
881   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
882   unsigned i = 0;
883
884   while (!MI->getOperand(i).isFI()) {
885     ++i;
886     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
887   }
888
889   // AddrMode4 and AddrMode6 cannot handle any offset.
890   if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
891     return Offset == 0;
892
893   unsigned NumBits = 0;
894   unsigned Scale = 1;
895   bool isSigned = true;
896   switch (AddrMode) {
897   case ARMII::AddrModeT2_i8:
898   case ARMII::AddrModeT2_i12:
899     // i8 supports only negative, and i12 supports only positive, so
900     // based on Offset sign, consider the appropriate instruction
901     Scale = 1;
902     if (Offset < 0) {
903       NumBits = 8;
904       Offset = -Offset;
905     } else {
906       NumBits = 12;
907     }
908     break;
909   case ARMII::AddrMode5:
910     // VFP address mode.
911     NumBits = 8;
912     Scale = 4;
913     break;
914   case ARMII::AddrMode_i12:
915   case ARMII::AddrMode2:
916     NumBits = 12;
917     break;
918   case ARMII::AddrMode3:
919     NumBits = 8;
920     break;
921   case ARMII::AddrModeT1_s:
922     NumBits = 5;
923     Scale = 4;
924     isSigned = false;
925     break;
926   default:
927     llvm_unreachable("Unsupported addressing mode!");
928   }
929
930   Offset += getFrameIndexInstrOffset(MI, i);
931   // Make sure the offset is encodable for instructions that scale the
932   // immediate.
933   if ((Offset & (Scale-1)) != 0)
934     return false;
935
936   if (isSigned && Offset < 0)
937     Offset = -Offset;
938
939   unsigned Mask = (1 << NumBits) - 1;
940   if ((unsigned)Offset <= Mask * Scale)
941     return true;
942
943   return false;
944 }
945
946 void
947 ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
948                                          int SPAdj, RegScavenger *RS) const {
949   unsigned i = 0;
950   MachineInstr &MI = *II;
951   MachineBasicBlock &MBB = *MI.getParent();
952   MachineFunction &MF = *MBB.getParent();
953   const ARMFrameLowering *TFI =
954     static_cast<const ARMFrameLowering*>(MF.getTarget().getFrameLowering());
955   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
956   assert(!AFI->isThumb1OnlyFunction() &&
957          "This eliminateFrameIndex does not support Thumb1!");
958
959   while (!MI.getOperand(i).isFI()) {
960     ++i;
961     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
962   }
963
964   int FrameIndex = MI.getOperand(i).getIndex();
965   unsigned FrameReg;
966
967   int Offset = TFI->ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
968
969   // PEI::scavengeFrameVirtualRegs() cannot accurately track SPAdj because the
970   // call frame setup/destroy instructions have already been eliminated.  That
971   // means the stack pointer cannot be used to access the emergency spill slot
972   // when !hasReservedCallFrame().
973 #ifndef NDEBUG
974   if (RS && FrameReg == ARM::SP && FrameIndex == RS->getScavengingFrameIndex()){
975     assert(TFI->hasReservedCallFrame(MF) &&
976            "Cannot use SP to access the emergency spill slot in "
977            "functions without a reserved call frame");
978     assert(!MF.getFrameInfo()->hasVarSizedObjects() &&
979            "Cannot use SP to access the emergency spill slot in "
980            "functions with variable sized frame objects");
981   }
982 #endif // NDEBUG
983
984   // Special handling of dbg_value instructions.
985   if (MI.isDebugValue()) {
986     MI.getOperand(i).  ChangeToRegister(FrameReg, false /*isDef*/);
987     MI.getOperand(i+1).ChangeToImmediate(Offset);
988     return;
989   }
990
991   // Modify MI as necessary to handle as much of 'Offset' as possible
992   bool Done = false;
993   if (!AFI->isThumbFunction())
994     Done = rewriteARMFrameIndex(MI, i, FrameReg, Offset, TII);
995   else {
996     assert(AFI->isThumb2Function());
997     Done = rewriteT2FrameIndex(MI, i, FrameReg, Offset, TII);
998   }
999   if (Done)
1000     return;
1001
1002   // If we get here, the immediate doesn't fit into the instruction.  We folded
1003   // as much as possible above, handle the rest, providing a register that is
1004   // SP+LargeImm.
1005   assert((Offset ||
1006           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
1007           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
1008          "This code isn't needed if offset already handled!");
1009
1010   unsigned ScratchReg = 0;
1011   int PIdx = MI.findFirstPredOperandIdx();
1012   ARMCC::CondCodes Pred = (PIdx == -1)
1013     ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
1014   unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
1015   if (Offset == 0)
1016     // Must be addrmode4/6.
1017     MI.getOperand(i).ChangeToRegister(FrameReg, false, false, false);
1018   else {
1019     ScratchReg = MF.getRegInfo().createVirtualRegister(&ARM::GPRRegClass);
1020     if (!AFI->isThumbFunction())
1021       emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1022                               Offset, Pred, PredReg, TII);
1023     else {
1024       assert(AFI->isThumb2Function());
1025       emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1026                              Offset, Pred, PredReg, TII);
1027     }
1028     // Update the original instruction to use the scratch register.
1029     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
1030   }
1031 }