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