827cb64d14c2b30a4008631ec2221a11f5d259f8
[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 void
236 ARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
237                                         MachineFunction &MF) const {
238   MachineRegisterInfo *MRI = &MF.getRegInfo();
239   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
240   if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
241        Hint.first == (unsigned)ARMRI::RegPairEven) &&
242       TargetRegisterInfo::isVirtualRegister(Hint.second)) {
243     // If 'Reg' is one of the even / odd register pair and it's now changed
244     // (e.g. coalesced) into a different register. The other register of the
245     // pair allocation hint must be updated to reflect the relationship
246     // change.
247     unsigned OtherReg = Hint.second;
248     Hint = MRI->getRegAllocationHint(OtherReg);
249     if (Hint.second == Reg)
250       // Make sure the pair has not already divorced.
251       MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
252   }
253 }
254
255 bool
256 ARMBaseRegisterInfo::avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
257   // CortexA9 has a Write-after-write hazard for NEON registers.
258   if (!STI.isLikeA9())
259     return false;
260
261   switch (RC->getID()) {
262   case ARM::DPRRegClassID:
263   case ARM::DPR_8RegClassID:
264   case ARM::DPR_VFP2RegClassID:
265   case ARM::QPRRegClassID:
266   case ARM::QPR_8RegClassID:
267   case ARM::QPR_VFP2RegClassID:
268   case ARM::SPRRegClassID:
269   case ARM::SPR_8RegClassID:
270     // Avoid reusing S, D, and Q registers.
271     // Don't increase register pressure for QQ and QQQQ.
272     return true;
273   default:
274     return false;
275   }
276 }
277
278 bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
279   const MachineFrameInfo *MFI = MF.getFrameInfo();
280   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
281   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
282
283   if (!EnableBasePointer)
284     return false;
285
286   // When outgoing call frames are so large that we adjust the stack pointer
287   // around the call, we can no longer use the stack pointer to reach the
288   // emergency spill slot.
289   if (needsStackRealignment(MF) && !TFI->hasReservedCallFrame(MF))
290     return true;
291
292   // Thumb has trouble with negative offsets from the FP. Thumb2 has a limited
293   // negative range for ldr/str (255), and thumb1 is positive offsets only.
294   // It's going to be better to use the SP or Base Pointer instead. When there
295   // are variable sized objects, we can't reference off of the SP, so we
296   // reserve a Base Pointer.
297   if (AFI->isThumbFunction() && MFI->hasVarSizedObjects()) {
298     // Conservatively estimate whether the negative offset from the frame
299     // pointer will be sufficient to reach. If a function has a smallish
300     // frame, it's less likely to have lots of spills and callee saved
301     // space, so it's all more likely to be within range of the frame pointer.
302     // If it's wrong, the scavenger will still enable access to work, it just
303     // won't be optimal.
304     if (AFI->isThumb2Function() && MFI->getLocalFrameSize() < 128)
305       return false;
306     return true;
307   }
308
309   return false;
310 }
311
312 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
313   const MachineRegisterInfo *MRI = &MF.getRegInfo();
314   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
315   // We can't realign the stack if:
316   // 1. Dynamic stack realignment is explicitly disabled,
317   // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
318   // 3. There are VLAs in the function and the base pointer is disabled.
319   if (!MF.getTarget().Options.RealignStack)
320     return false;
321   if (AFI->isThumb1OnlyFunction())
322     return false;
323   // Stack realignment requires a frame pointer.  If we already started
324   // register allocation with frame pointer elimination, it is too late now.
325   if (!MRI->canReserveReg(FramePtr))
326     return false;
327   // We may also need a base pointer if there are dynamic allocas or stack
328   // pointer adjustments around calls.
329   if (MF.getTarget().getFrameLowering()->hasReservedCallFrame(MF))
330     return true;
331   if (!EnableBasePointer)
332     return false;
333   // A base pointer is required and allowed.  Check that it isn't too late to
334   // reserve it.
335   return MRI->canReserveReg(BasePtr);
336 }
337
338 bool ARMBaseRegisterInfo::
339 needsStackRealignment(const MachineFunction &MF) const {
340   const MachineFrameInfo *MFI = MF.getFrameInfo();
341   const Function *F = MF.getFunction();
342   unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
343   bool requiresRealignment =
344     ((MFI->getMaxAlignment() > StackAlign) ||
345      F->getFnAttributes().hasAttribute(Attributes::StackAlignment));
346
347   return requiresRealignment && canRealignStack(MF);
348 }
349
350 bool ARMBaseRegisterInfo::
351 cannotEliminateFrame(const MachineFunction &MF) const {
352   const MachineFrameInfo *MFI = MF.getFrameInfo();
353   if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI->adjustsStack())
354     return true;
355   return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
356     || needsStackRealignment(MF);
357 }
358
359 unsigned
360 ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
361   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
362
363   if (TFI->hasFP(MF))
364     return FramePtr;
365   return ARM::SP;
366 }
367
368 unsigned ARMBaseRegisterInfo::getEHExceptionRegister() const {
369   llvm_unreachable("What is the exception register");
370 }
371
372 unsigned ARMBaseRegisterInfo::getEHHandlerRegister() const {
373   llvm_unreachable("What is the exception handler register");
374 }
375
376 /// emitLoadConstPool - Emits a load from constpool to materialize the
377 /// specified immediate.
378 void ARMBaseRegisterInfo::
379 emitLoadConstPool(MachineBasicBlock &MBB,
380                   MachineBasicBlock::iterator &MBBI,
381                   DebugLoc dl,
382                   unsigned DestReg, unsigned SubIdx, int Val,
383                   ARMCC::CondCodes Pred,
384                   unsigned PredReg, unsigned MIFlags) const {
385   MachineFunction &MF = *MBB.getParent();
386   MachineConstantPool *ConstantPool = MF.getConstantPool();
387   const Constant *C =
388         ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
389   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
390
391   BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
392     .addReg(DestReg, getDefRegState(true), SubIdx)
393     .addConstantPoolIndex(Idx)
394     .addImm(0).addImm(Pred).addReg(PredReg)
395     .setMIFlags(MIFlags);
396 }
397
398 bool ARMBaseRegisterInfo::
399 requiresRegisterScavenging(const MachineFunction &MF) const {
400   return true;
401 }
402
403 bool ARMBaseRegisterInfo::
404 trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
405   return true;
406 }
407
408 bool ARMBaseRegisterInfo::
409 requiresFrameIndexScavenging(const MachineFunction &MF) const {
410   return true;
411 }
412
413 bool ARMBaseRegisterInfo::
414 requiresVirtualBaseRegisters(const MachineFunction &MF) const {
415   return EnableLocalStackAlloc;
416 }
417
418 static void
419 emitSPUpdate(bool isARM,
420              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
421              DebugLoc dl, const ARMBaseInstrInfo &TII,
422              int NumBytes,
423              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
424   if (isARM)
425     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
426                             Pred, PredReg, TII);
427   else
428     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
429                            Pred, PredReg, TII);
430 }
431
432
433 void ARMBaseRegisterInfo::
434 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
435                               MachineBasicBlock::iterator I) const {
436   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
437   if (!TFI->hasReservedCallFrame(MF)) {
438     // If we have alloca, convert as follows:
439     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
440     // ADJCALLSTACKUP   -> add, sp, sp, amount
441     MachineInstr *Old = I;
442     DebugLoc dl = Old->getDebugLoc();
443     unsigned Amount = Old->getOperand(0).getImm();
444     if (Amount != 0) {
445       // We need to keep the stack aligned properly.  To do this, we round the
446       // amount of space needed for the outgoing arguments up to the next
447       // alignment boundary.
448       unsigned Align = TFI->getStackAlignment();
449       Amount = (Amount+Align-1)/Align*Align;
450
451       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
452       assert(!AFI->isThumb1OnlyFunction() &&
453              "This eliminateCallFramePseudoInstr does not support Thumb1!");
454       bool isARM = !AFI->isThumbFunction();
455
456       // Replace the pseudo instruction with a new instruction...
457       unsigned Opc = Old->getOpcode();
458       int PIdx = Old->findFirstPredOperandIdx();
459       ARMCC::CondCodes Pred = (PIdx == -1)
460         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
461       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
462         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
463         unsigned PredReg = Old->getOperand(2).getReg();
464         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, Pred, PredReg);
465       } else {
466         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
467         unsigned PredReg = Old->getOperand(3).getReg();
468         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
469         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, Pred, PredReg);
470       }
471     }
472   }
473   MBB.erase(I);
474 }
475
476 int64_t ARMBaseRegisterInfo::
477 getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
478   const MCInstrDesc &Desc = MI->getDesc();
479   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
480   int64_t InstrOffs = 0;
481   int Scale = 1;
482   unsigned ImmIdx = 0;
483   switch (AddrMode) {
484   case ARMII::AddrModeT2_i8:
485   case ARMII::AddrModeT2_i12:
486   case ARMII::AddrMode_i12:
487     InstrOffs = MI->getOperand(Idx+1).getImm();
488     Scale = 1;
489     break;
490   case ARMII::AddrMode5: {
491     // VFP address mode.
492     const MachineOperand &OffOp = MI->getOperand(Idx+1);
493     InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
494     if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
495       InstrOffs = -InstrOffs;
496     Scale = 4;
497     break;
498   }
499   case ARMII::AddrMode2: {
500     ImmIdx = Idx+2;
501     InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
502     if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
503       InstrOffs = -InstrOffs;
504     break;
505   }
506   case ARMII::AddrMode3: {
507     ImmIdx = Idx+2;
508     InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
509     if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
510       InstrOffs = -InstrOffs;
511     break;
512   }
513   case ARMII::AddrModeT1_s: {
514     ImmIdx = Idx+1;
515     InstrOffs = MI->getOperand(ImmIdx).getImm();
516     Scale = 4;
517     break;
518   }
519   default:
520     llvm_unreachable("Unsupported addressing mode!");
521   }
522
523   return InstrOffs * Scale;
524 }
525
526 /// needsFrameBaseReg - Returns true if the instruction's frame index
527 /// reference would be better served by a base register other than FP
528 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
529 /// references it should create new base registers for.
530 bool ARMBaseRegisterInfo::
531 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
532   for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
533     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
534   }
535
536   // It's the load/store FI references that cause issues, as it can be difficult
537   // to materialize the offset if it won't fit in the literal field. Estimate
538   // based on the size of the local frame and some conservative assumptions
539   // about the rest of the stack frame (note, this is pre-regalloc, so
540   // we don't know everything for certain yet) whether this offset is likely
541   // to be out of range of the immediate. Return true if so.
542
543   // We only generate virtual base registers for loads and stores, so
544   // return false for everything else.
545   unsigned Opc = MI->getOpcode();
546   switch (Opc) {
547   case ARM::LDRi12: case ARM::LDRH: case ARM::LDRBi12:
548   case ARM::STRi12: case ARM::STRH: case ARM::STRBi12:
549   case ARM::t2LDRi12: case ARM::t2LDRi8:
550   case ARM::t2STRi12: case ARM::t2STRi8:
551   case ARM::VLDRS: case ARM::VLDRD:
552   case ARM::VSTRS: case ARM::VSTRD:
553   case ARM::tSTRspi: case ARM::tLDRspi:
554     if (ForceAllBaseRegAlloc)
555       return true;
556     break;
557   default:
558     return false;
559   }
560
561   // Without a virtual base register, if the function has variable sized
562   // objects, all fixed-size local references will be via the frame pointer,
563   // Approximate the offset and see if it's legal for the instruction.
564   // Note that the incoming offset is based on the SP value at function entry,
565   // so it'll be negative.
566   MachineFunction &MF = *MI->getParent()->getParent();
567   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
568   MachineFrameInfo *MFI = MF.getFrameInfo();
569   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
570
571   // Estimate an offset from the frame pointer.
572   // Conservatively assume all callee-saved registers get pushed. R4-R6
573   // will be earlier than the FP, so we ignore those.
574   // R7, LR
575   int64_t FPOffset = Offset - 8;
576   // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
577   if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
578     FPOffset -= 80;
579   // Estimate an offset from the stack pointer.
580   // The incoming offset is relating to the SP at the start of the function,
581   // but when we access the local it'll be relative to the SP after local
582   // allocation, so adjust our SP-relative offset by that allocation size.
583   Offset = -Offset;
584   Offset += MFI->getLocalFrameSize();
585   // Assume that we'll have at least some spill slots allocated.
586   // FIXME: This is a total SWAG number. We should run some statistics
587   //        and pick a real one.
588   Offset += 128; // 128 bytes of spill slots
589
590   // If there is a frame pointer, try using it.
591   // The FP is only available if there is no dynamic realignment. We
592   // don't know for sure yet whether we'll need that, so we guess based
593   // on whether there are any local variables that would trigger it.
594   unsigned StackAlign = TFI->getStackAlignment();
595   if (TFI->hasFP(MF) &&
596       !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
597     if (isFrameOffsetLegal(MI, FPOffset))
598       return false;
599   }
600   // If we can reference via the stack pointer, try that.
601   // FIXME: This (and the code that resolves the references) can be improved
602   //        to only disallow SP relative references in the live range of
603   //        the VLA(s). In practice, it's unclear how much difference that
604   //        would make, but it may be worth doing.
605   if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
606     return false;
607
608   // The offset likely isn't legal, we want to allocate a virtual base register.
609   return true;
610 }
611
612 /// materializeFrameBaseRegister - Insert defining instruction(s) for BaseReg to
613 /// be a pointer to FrameIdx at the beginning of the basic block.
614 void ARMBaseRegisterInfo::
615 materializeFrameBaseRegister(MachineBasicBlock *MBB,
616                              unsigned BaseReg, int FrameIdx,
617                              int64_t Offset) const {
618   ARMFunctionInfo *AFI = MBB->getParent()->getInfo<ARMFunctionInfo>();
619   unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
620     (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
621
622   MachineBasicBlock::iterator Ins = MBB->begin();
623   DebugLoc DL;                  // Defaults to "unknown"
624   if (Ins != MBB->end())
625     DL = Ins->getDebugLoc();
626
627   const MCInstrDesc &MCID = TII.get(ADDriOpc);
628   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
629   const MachineFunction &MF = *MBB->getParent();
630   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
631
632   MachineInstrBuilder MIB = AddDefaultPred(BuildMI(*MBB, Ins, DL, MCID, BaseReg)
633     .addFrameIndex(FrameIdx).addImm(Offset));
634
635   if (!AFI->isThumb1OnlyFunction())
636     AddDefaultCC(MIB);
637 }
638
639 void
640 ARMBaseRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
641                                        unsigned BaseReg, int64_t Offset) const {
642   MachineInstr &MI = *I;
643   MachineBasicBlock &MBB = *MI.getParent();
644   MachineFunction &MF = *MBB.getParent();
645   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
646   int Off = Offset; // ARM doesn't need the general 64-bit offsets
647   unsigned i = 0;
648
649   assert(!AFI->isThumb1OnlyFunction() &&
650          "This resolveFrameIndex does not support Thumb1!");
651
652   while (!MI.getOperand(i).isFI()) {
653     ++i;
654     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
655   }
656   bool Done = false;
657   if (!AFI->isThumbFunction())
658     Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
659   else {
660     assert(AFI->isThumb2Function());
661     Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
662   }
663   assert (Done && "Unable to resolve frame index!");
664   (void)Done;
665 }
666
667 bool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
668                                              int64_t Offset) const {
669   const MCInstrDesc &Desc = MI->getDesc();
670   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
671   unsigned i = 0;
672
673   while (!MI->getOperand(i).isFI()) {
674     ++i;
675     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
676   }
677
678   // AddrMode4 and AddrMode6 cannot handle any offset.
679   if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
680     return Offset == 0;
681
682   unsigned NumBits = 0;
683   unsigned Scale = 1;
684   bool isSigned = true;
685   switch (AddrMode) {
686   case ARMII::AddrModeT2_i8:
687   case ARMII::AddrModeT2_i12:
688     // i8 supports only negative, and i12 supports only positive, so
689     // based on Offset sign, consider the appropriate instruction
690     Scale = 1;
691     if (Offset < 0) {
692       NumBits = 8;
693       Offset = -Offset;
694     } else {
695       NumBits = 12;
696     }
697     break;
698   case ARMII::AddrMode5:
699     // VFP address mode.
700     NumBits = 8;
701     Scale = 4;
702     break;
703   case ARMII::AddrMode_i12:
704   case ARMII::AddrMode2:
705     NumBits = 12;
706     break;
707   case ARMII::AddrMode3:
708     NumBits = 8;
709     break;
710   case ARMII::AddrModeT1_s:
711     NumBits = 5;
712     Scale = 4;
713     isSigned = false;
714     break;
715   default:
716     llvm_unreachable("Unsupported addressing mode!");
717   }
718
719   Offset += getFrameIndexInstrOffset(MI, i);
720   // Make sure the offset is encodable for instructions that scale the
721   // immediate.
722   if ((Offset & (Scale-1)) != 0)
723     return false;
724
725   if (isSigned && Offset < 0)
726     Offset = -Offset;
727
728   unsigned Mask = (1 << NumBits) - 1;
729   if ((unsigned)Offset <= Mask * Scale)
730     return true;
731
732   return false;
733 }
734
735 void
736 ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
737                                          int SPAdj, RegScavenger *RS) const {
738   unsigned i = 0;
739   MachineInstr &MI = *II;
740   MachineBasicBlock &MBB = *MI.getParent();
741   MachineFunction &MF = *MBB.getParent();
742   const ARMFrameLowering *TFI =
743     static_cast<const ARMFrameLowering*>(MF.getTarget().getFrameLowering());
744   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
745   assert(!AFI->isThumb1OnlyFunction() &&
746          "This eliminateFrameIndex does not support Thumb1!");
747
748   while (!MI.getOperand(i).isFI()) {
749     ++i;
750     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
751   }
752
753   int FrameIndex = MI.getOperand(i).getIndex();
754   unsigned FrameReg;
755
756   int Offset = TFI->ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
757
758   // PEI::scavengeFrameVirtualRegs() cannot accurately track SPAdj because the
759   // call frame setup/destroy instructions have already been eliminated.  That
760   // means the stack pointer cannot be used to access the emergency spill slot
761   // when !hasReservedCallFrame().
762 #ifndef NDEBUG
763   if (RS && FrameReg == ARM::SP && FrameIndex == RS->getScavengingFrameIndex()){
764     assert(TFI->hasReservedCallFrame(MF) &&
765            "Cannot use SP to access the emergency spill slot in "
766            "functions without a reserved call frame");
767     assert(!MF.getFrameInfo()->hasVarSizedObjects() &&
768            "Cannot use SP to access the emergency spill slot in "
769            "functions with variable sized frame objects");
770   }
771 #endif // NDEBUG
772
773   // Special handling of dbg_value instructions.
774   if (MI.isDebugValue()) {
775     MI.getOperand(i).  ChangeToRegister(FrameReg, false /*isDef*/);
776     MI.getOperand(i+1).ChangeToImmediate(Offset);
777     return;
778   }
779
780   // Modify MI as necessary to handle as much of 'Offset' as possible
781   bool Done = false;
782   if (!AFI->isThumbFunction())
783     Done = rewriteARMFrameIndex(MI, i, FrameReg, Offset, TII);
784   else {
785     assert(AFI->isThumb2Function());
786     Done = rewriteT2FrameIndex(MI, i, FrameReg, Offset, TII);
787   }
788   if (Done)
789     return;
790
791   // If we get here, the immediate doesn't fit into the instruction.  We folded
792   // as much as possible above, handle the rest, providing a register that is
793   // SP+LargeImm.
794   assert((Offset ||
795           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
796           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
797          "This code isn't needed if offset already handled!");
798
799   unsigned ScratchReg = 0;
800   int PIdx = MI.findFirstPredOperandIdx();
801   ARMCC::CondCodes Pred = (PIdx == -1)
802     ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
803   unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
804   if (Offset == 0)
805     // Must be addrmode4/6.
806     MI.getOperand(i).ChangeToRegister(FrameReg, false, false, false);
807   else {
808     ScratchReg = MF.getRegInfo().createVirtualRegister(&ARM::GPRRegClass);
809     if (!AFI->isThumbFunction())
810       emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
811                               Offset, Pred, PredReg, TII);
812     else {
813       assert(AFI->isThumb2Function());
814       emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
815                              Offset, Pred, PredReg, TII);
816     }
817     // Update the original instruction to use the scratch register.
818     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
819   }
820 }