42742bf3b6614bc3b46564552329ea25605e141d
[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/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetFrameLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Target/TargetOptions.h"
40
41 #define GET_REGINFO_TARGET_DESC
42 #include "ARMGenRegisterInfo.inc"
43
44 using namespace llvm;
45
46 ARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMBaseInstrInfo &tii,
47                                          const ARMSubtarget &sti)
48   : ARMGenRegisterInfo(ARM::LR, 0, 0, ARM::PC), TII(tii), STI(sti),
49     FramePtr((STI.isTargetDarwin() || STI.isThumb()) ? ARM::R7 : ARM::R11),
50     BasePtr(ARM::R6) {
51 }
52
53 const uint16_t*
54 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
55   bool ghcCall = false;
56  
57   if (MF) {
58     const Function *F = MF->getFunction();
59     ghcCall = (F ? F->getCallingConv() == CallingConv::GHC : false);
60   }
61  
62   if (ghcCall) {
63       return CSR_GHC_SaveList;
64   }
65   else {
66   return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
67     ? CSR_iOS_SaveList : CSR_AAPCS_SaveList;
68   }
69 }
70
71 const uint32_t*
72 ARMBaseRegisterInfo::getCallPreservedMask(CallingConv::ID) const {
73   return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
74     ? CSR_iOS_RegMask : CSR_AAPCS_RegMask;
75 }
76
77 const uint32_t*
78 ARMBaseRegisterInfo::getNoPreservedMask() const {
79   return CSR_NoRegs_RegMask;
80 }
81
82 BitVector ARMBaseRegisterInfo::
83 getReservedRegs(const MachineFunction &MF) const {
84   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
85
86   // FIXME: avoid re-calculating this every time.
87   BitVector Reserved(getNumRegs());
88   Reserved.set(ARM::SP);
89   Reserved.set(ARM::PC);
90   Reserved.set(ARM::FPSCR);
91   if (TFI->hasFP(MF))
92     Reserved.set(FramePtr);
93   if (hasBasePointer(MF))
94     Reserved.set(BasePtr);
95   // Some targets reserve R9.
96   if (STI.isR9Reserved())
97     Reserved.set(ARM::R9);
98   // Reserve D16-D31 if the subtarget doesn't support them.
99   if (!STI.hasVFP3() || STI.hasD16()) {
100     assert(ARM::D31 == ARM::D16 + 15);
101     for (unsigned i = 0; i != 16; ++i)
102       Reserved.set(ARM::D16 + i);
103   }
104   const TargetRegisterClass *RC  = &ARM::GPRPairRegClass;
105   for(TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I!=E; ++I)
106     for (MCSubRegIterator SI(*I, this); SI.isValid(); ++SI)
107       if (Reserved.test(*SI)) Reserved.set(*I);
108
109   return Reserved;
110 }
111
112 const TargetRegisterClass*
113 ARMBaseRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC)
114                                                                          const {
115   const TargetRegisterClass *Super = RC;
116   TargetRegisterClass::sc_iterator I = RC->getSuperClasses();
117   do {
118     switch (Super->getID()) {
119     case ARM::GPRRegClassID:
120     case ARM::SPRRegClassID:
121     case ARM::DPRRegClassID:
122     case ARM::QPRRegClassID:
123     case ARM::QQPRRegClassID:
124     case ARM::QQQQPRRegClassID:
125     case ARM::GPRPairRegClassID:
126       return Super;
127     }
128     Super = *I++;
129   } while (Super);
130   return RC;
131 }
132
133 const TargetRegisterClass *
134 ARMBaseRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
135                                                                          const {
136   return &ARM::GPRRegClass;
137 }
138
139 const TargetRegisterClass *
140 ARMBaseRegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
141   if (RC == &ARM::CCRRegClass)
142     return 0;  // Can't copy CCR registers.
143   return RC;
144 }
145
146 unsigned
147 ARMBaseRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
148                                          MachineFunction &MF) const {
149   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
150
151   switch (RC->getID()) {
152   default:
153     return 0;
154   case ARM::tGPRRegClassID:
155     return TFI->hasFP(MF) ? 4 : 5;
156   case ARM::GPRRegClassID: {
157     unsigned FP = TFI->hasFP(MF) ? 1 : 0;
158     return 10 - FP - (STI.isR9Reserved() ? 1 : 0);
159   }
160   case ARM::SPRRegClassID:  // Currently not used as 'rep' register class.
161   case ARM::DPRRegClassID:
162     return 32 - 10;
163   }
164 }
165
166 // Get the other register in a GPRPair.
167 static unsigned getPairedGPR(unsigned Reg, bool Odd, const MCRegisterInfo *RI) {
168   for (MCSuperRegIterator Supers(Reg, RI); Supers.isValid(); ++Supers)
169     if (ARM::GPRPairRegClass.contains(*Supers))
170       return RI->getSubReg(*Supers, Odd ? ARM::gsub_1 : ARM::gsub_0);
171   return 0;
172 }
173
174 // Resolve the RegPairEven / RegPairOdd register allocator hints.
175 void
176 ARMBaseRegisterInfo::getRegAllocationHints(unsigned VirtReg,
177                                            ArrayRef<MCPhysReg> Order,
178                                            SmallVectorImpl<MCPhysReg> &Hints,
179                                            const MachineFunction &MF,
180                                            const VirtRegMap *VRM) const {
181   const MachineRegisterInfo &MRI = MF.getRegInfo();
182   std::pair<unsigned, unsigned> Hint = MRI.getRegAllocationHint(VirtReg);
183
184   unsigned Odd;
185   switch (Hint.first) {
186   case ARMRI::RegPairEven:
187     Odd = 0;
188     break;
189   case ARMRI::RegPairOdd:
190     Odd = 1;
191     break;
192   default:
193     TargetRegisterInfo::getRegAllocationHints(VirtReg, Order, Hints, MF, VRM);
194     return;
195   }
196
197   // This register should preferably be even (Odd == 0) or odd (Odd == 1).
198   // Check if the other part of the pair has already been assigned, and provide
199   // the paired register as the first hint.
200   unsigned PairedPhys = 0;
201   if (VRM && VRM->hasPhys(Hint.second)) {
202     PairedPhys = getPairedGPR(VRM->getPhys(Hint.second), Odd, this);
203     if (PairedPhys && MRI.isReserved(PairedPhys))
204       PairedPhys = 0;
205   }
206
207   // First prefer the paired physreg.
208   if (PairedPhys)
209     Hints.push_back(PairedPhys);
210
211   // Then prefer even or odd registers.
212   for (unsigned I = 0, E = Order.size(); I != E; ++I) {
213     unsigned Reg = Order[I];
214     if (Reg == PairedPhys || (getEncodingValue(Reg) & 1) != Odd)
215       continue;
216     // Don't provide hints that are paired to a reserved register.
217     unsigned Paired = getPairedGPR(Reg, !Odd, this);
218     if (!Paired || MRI.isReserved(Paired))
219       continue;
220     Hints.push_back(Reg);
221   }
222 }
223
224 void
225 ARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
226                                         MachineFunction &MF) const {
227   MachineRegisterInfo *MRI = &MF.getRegInfo();
228   std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
229   if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
230        Hint.first == (unsigned)ARMRI::RegPairEven) &&
231       TargetRegisterInfo::isVirtualRegister(Hint.second)) {
232     // If 'Reg' is one of the even / odd register pair and it's now changed
233     // (e.g. coalesced) into a different register. The other register of the
234     // pair allocation hint must be updated to reflect the relationship
235     // change.
236     unsigned OtherReg = Hint.second;
237     Hint = MRI->getRegAllocationHint(OtherReg);
238     if (Hint.second == Reg)
239       // Make sure the pair has not already divorced.
240       MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
241   }
242 }
243
244 bool
245 ARMBaseRegisterInfo::avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
246   // CortexA9 has a Write-after-write hazard for NEON registers.
247   if (!STI.isLikeA9())
248     return false;
249
250   switch (RC->getID()) {
251   case ARM::DPRRegClassID:
252   case ARM::DPR_8RegClassID:
253   case ARM::DPR_VFP2RegClassID:
254   case ARM::QPRRegClassID:
255   case ARM::QPR_8RegClassID:
256   case ARM::QPR_VFP2RegClassID:
257   case ARM::SPRRegClassID:
258   case ARM::SPR_8RegClassID:
259     // Avoid reusing S, D, and Q registers.
260     // Don't increase register pressure for QQ and QQQQ.
261     return true;
262   default:
263     return false;
264   }
265 }
266
267 bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
268   const MachineFrameInfo *MFI = MF.getFrameInfo();
269   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
270   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
271
272   // When outgoing call frames are so large that we adjust the stack pointer
273   // around the call, we can no longer use the stack pointer to reach the
274   // emergency spill slot.
275   if (needsStackRealignment(MF) && !TFI->hasReservedCallFrame(MF))
276     return true;
277
278   // Thumb has trouble with negative offsets from the FP. Thumb2 has a limited
279   // negative range for ldr/str (255), and thumb1 is positive offsets only.
280   // It's going to be better to use the SP or Base Pointer instead. When there
281   // are variable sized objects, we can't reference off of the SP, so we
282   // reserve a Base Pointer.
283   if (AFI->isThumbFunction() && MFI->hasVarSizedObjects()) {
284     // Conservatively estimate whether the negative offset from the frame
285     // pointer will be sufficient to reach. If a function has a smallish
286     // frame, it's less likely to have lots of spills and callee saved
287     // space, so it's all more likely to be within range of the frame pointer.
288     // If it's wrong, the scavenger will still enable access to work, it just
289     // won't be optimal.
290     if (AFI->isThumb2Function() && MFI->getLocalFrameSize() < 128)
291       return false;
292     return true;
293   }
294
295   return false;
296 }
297
298 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
299   const MachineRegisterInfo *MRI = &MF.getRegInfo();
300   const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
301   // We can't realign the stack if:
302   // 1. Dynamic stack realignment is explicitly disabled,
303   // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
304   // 3. There are VLAs in the function and the base pointer is disabled.
305   if (!MF.getTarget().Options.RealignStack)
306     return false;
307   if (AFI->isThumb1OnlyFunction())
308     return false;
309   // Stack realignment requires a frame pointer.  If we already started
310   // register allocation with frame pointer elimination, it is too late now.
311   if (!MRI->canReserveReg(FramePtr))
312     return false;
313   // We may also need a base pointer if there are dynamic allocas or stack
314   // pointer adjustments around calls.
315   if (MF.getTarget().getFrameLowering()->hasReservedCallFrame(MF))
316     return true;
317   // A base pointer is required and allowed.  Check that it isn't too late to
318   // reserve it.
319   return MRI->canReserveReg(BasePtr);
320 }
321
322 bool ARMBaseRegisterInfo::
323 needsStackRealignment(const MachineFunction &MF) const {
324   const MachineFrameInfo *MFI = MF.getFrameInfo();
325   const Function *F = MF.getFunction();
326   unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
327   bool requiresRealignment =
328     ((MFI->getMaxAlignment() > StackAlign) ||
329      F->getFnAttributes().hasAttribute(Attribute::StackAlignment));
330
331   return requiresRealignment && canRealignStack(MF);
332 }
333
334 bool ARMBaseRegisterInfo::
335 cannotEliminateFrame(const MachineFunction &MF) const {
336   const MachineFrameInfo *MFI = MF.getFrameInfo();
337   if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI->adjustsStack())
338     return true;
339   return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
340     || needsStackRealignment(MF);
341 }
342
343 unsigned
344 ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
345   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
346
347   if (TFI->hasFP(MF))
348     return FramePtr;
349   return ARM::SP;
350 }
351
352 unsigned ARMBaseRegisterInfo::getEHExceptionRegister() const {
353   llvm_unreachable("What is the exception register");
354 }
355
356 unsigned ARMBaseRegisterInfo::getEHHandlerRegister() const {
357   llvm_unreachable("What is the exception handler register");
358 }
359
360 /// emitLoadConstPool - Emits a load from constpool to materialize the
361 /// specified immediate.
362 void ARMBaseRegisterInfo::
363 emitLoadConstPool(MachineBasicBlock &MBB,
364                   MachineBasicBlock::iterator &MBBI,
365                   DebugLoc dl,
366                   unsigned DestReg, unsigned SubIdx, int Val,
367                   ARMCC::CondCodes Pred,
368                   unsigned PredReg, unsigned MIFlags) const {
369   MachineFunction &MF = *MBB.getParent();
370   MachineConstantPool *ConstantPool = MF.getConstantPool();
371   const Constant *C =
372         ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
373   unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
374
375   BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
376     .addReg(DestReg, getDefRegState(true), SubIdx)
377     .addConstantPoolIndex(Idx)
378     .addImm(0).addImm(Pred).addReg(PredReg)
379     .setMIFlags(MIFlags);
380 }
381
382 bool ARMBaseRegisterInfo::
383 requiresRegisterScavenging(const MachineFunction &MF) const {
384   return true;
385 }
386
387 bool ARMBaseRegisterInfo::
388 trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
389   return true;
390 }
391
392 bool ARMBaseRegisterInfo::
393 requiresFrameIndexScavenging(const MachineFunction &MF) const {
394   return true;
395 }
396
397 bool ARMBaseRegisterInfo::
398 requiresVirtualBaseRegisters(const MachineFunction &MF) const {
399   return true;
400 }
401
402 static void
403 emitSPUpdate(bool isARM,
404              MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
405              DebugLoc dl, const ARMBaseInstrInfo &TII,
406              int NumBytes,
407              ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
408   if (isARM)
409     emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
410                             Pred, PredReg, TII);
411   else
412     emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
413                            Pred, PredReg, TII);
414 }
415
416
417 void ARMBaseRegisterInfo::
418 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
419                               MachineBasicBlock::iterator I) const {
420   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
421   if (!TFI->hasReservedCallFrame(MF)) {
422     // If we have alloca, convert as follows:
423     // ADJCALLSTACKDOWN -> sub, sp, sp, amount
424     // ADJCALLSTACKUP   -> add, sp, sp, amount
425     MachineInstr *Old = I;
426     DebugLoc dl = Old->getDebugLoc();
427     unsigned Amount = Old->getOperand(0).getImm();
428     if (Amount != 0) {
429       // We need to keep the stack aligned properly.  To do this, we round the
430       // amount of space needed for the outgoing arguments up to the next
431       // alignment boundary.
432       unsigned Align = TFI->getStackAlignment();
433       Amount = (Amount+Align-1)/Align*Align;
434
435       ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
436       assert(!AFI->isThumb1OnlyFunction() &&
437              "This eliminateCallFramePseudoInstr does not support Thumb1!");
438       bool isARM = !AFI->isThumbFunction();
439
440       // Replace the pseudo instruction with a new instruction...
441       unsigned Opc = Old->getOpcode();
442       int PIdx = Old->findFirstPredOperandIdx();
443       ARMCC::CondCodes Pred = (PIdx == -1)
444         ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
445       if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
446         // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
447         unsigned PredReg = Old->getOperand(2).getReg();
448         emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, Pred, PredReg);
449       } else {
450         // Note: PredReg is operand 3 for ADJCALLSTACKUP.
451         unsigned PredReg = Old->getOperand(3).getReg();
452         assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
453         emitSPUpdate(isARM, MBB, I, dl, TII, Amount, Pred, PredReg);
454       }
455     }
456   }
457   MBB.erase(I);
458 }
459
460 int64_t ARMBaseRegisterInfo::
461 getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
462   const MCInstrDesc &Desc = MI->getDesc();
463   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
464   int64_t InstrOffs = 0;
465   int Scale = 1;
466   unsigned ImmIdx = 0;
467   switch (AddrMode) {
468   case ARMII::AddrModeT2_i8:
469   case ARMII::AddrModeT2_i12:
470   case ARMII::AddrMode_i12:
471     InstrOffs = MI->getOperand(Idx+1).getImm();
472     Scale = 1;
473     break;
474   case ARMII::AddrMode5: {
475     // VFP address mode.
476     const MachineOperand &OffOp = MI->getOperand(Idx+1);
477     InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
478     if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
479       InstrOffs = -InstrOffs;
480     Scale = 4;
481     break;
482   }
483   case ARMII::AddrMode2: {
484     ImmIdx = Idx+2;
485     InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
486     if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
487       InstrOffs = -InstrOffs;
488     break;
489   }
490   case ARMII::AddrMode3: {
491     ImmIdx = Idx+2;
492     InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
493     if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
494       InstrOffs = -InstrOffs;
495     break;
496   }
497   case ARMII::AddrModeT1_s: {
498     ImmIdx = Idx+1;
499     InstrOffs = MI->getOperand(ImmIdx).getImm();
500     Scale = 4;
501     break;
502   }
503   default:
504     llvm_unreachable("Unsupported addressing mode!");
505   }
506
507   return InstrOffs * Scale;
508 }
509
510 /// needsFrameBaseReg - Returns true if the instruction's frame index
511 /// reference would be better served by a base register other than FP
512 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
513 /// references it should create new base registers for.
514 bool ARMBaseRegisterInfo::
515 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
516   for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
517     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
518   }
519
520   // It's the load/store FI references that cause issues, as it can be difficult
521   // to materialize the offset if it won't fit in the literal field. Estimate
522   // based on the size of the local frame and some conservative assumptions
523   // about the rest of the stack frame (note, this is pre-regalloc, so
524   // we don't know everything for certain yet) whether this offset is likely
525   // to be out of range of the immediate. Return true if so.
526
527   // We only generate virtual base registers for loads and stores, so
528   // return false for everything else.
529   unsigned Opc = MI->getOpcode();
530   switch (Opc) {
531   case ARM::LDRi12: case ARM::LDRH: case ARM::LDRBi12:
532   case ARM::STRi12: case ARM::STRH: case ARM::STRBi12:
533   case ARM::t2LDRi12: case ARM::t2LDRi8:
534   case ARM::t2STRi12: case ARM::t2STRi8:
535   case ARM::VLDRS: case ARM::VLDRD:
536   case ARM::VSTRS: case ARM::VSTRD:
537   case ARM::tSTRspi: case ARM::tLDRspi:
538     break;
539   default:
540     return false;
541   }
542
543   // Without a virtual base register, if the function has variable sized
544   // objects, all fixed-size local references will be via the frame pointer,
545   // Approximate the offset and see if it's legal for the instruction.
546   // Note that the incoming offset is based on the SP value at function entry,
547   // so it'll be negative.
548   MachineFunction &MF = *MI->getParent()->getParent();
549   const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
550   MachineFrameInfo *MFI = MF.getFrameInfo();
551   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
552
553   // Estimate an offset from the frame pointer.
554   // Conservatively assume all callee-saved registers get pushed. R4-R6
555   // will be earlier than the FP, so we ignore those.
556   // R7, LR
557   int64_t FPOffset = Offset - 8;
558   // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
559   if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
560     FPOffset -= 80;
561   // Estimate an offset from the stack pointer.
562   // The incoming offset is relating to the SP at the start of the function,
563   // but when we access the local it'll be relative to the SP after local
564   // allocation, so adjust our SP-relative offset by that allocation size.
565   Offset = -Offset;
566   Offset += MFI->getLocalFrameSize();
567   // Assume that we'll have at least some spill slots allocated.
568   // FIXME: This is a total SWAG number. We should run some statistics
569   //        and pick a real one.
570   Offset += 128; // 128 bytes of spill slots
571
572   // If there is a frame pointer, try using it.
573   // The FP is only available if there is no dynamic realignment. We
574   // don't know for sure yet whether we'll need that, so we guess based
575   // on whether there are any local variables that would trigger it.
576   unsigned StackAlign = TFI->getStackAlignment();
577   if (TFI->hasFP(MF) &&
578       !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
579     if (isFrameOffsetLegal(MI, FPOffset))
580       return false;
581   }
582   // If we can reference via the stack pointer, try that.
583   // FIXME: This (and the code that resolves the references) can be improved
584   //        to only disallow SP relative references in the live range of
585   //        the VLA(s). In practice, it's unclear how much difference that
586   //        would make, but it may be worth doing.
587   if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
588     return false;
589
590   // The offset likely isn't legal, we want to allocate a virtual base register.
591   return true;
592 }
593
594 /// materializeFrameBaseRegister - Insert defining instruction(s) for BaseReg to
595 /// be a pointer to FrameIdx at the beginning of the basic block.
596 void ARMBaseRegisterInfo::
597 materializeFrameBaseRegister(MachineBasicBlock *MBB,
598                              unsigned BaseReg, int FrameIdx,
599                              int64_t Offset) const {
600   ARMFunctionInfo *AFI = MBB->getParent()->getInfo<ARMFunctionInfo>();
601   unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
602     (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
603
604   MachineBasicBlock::iterator Ins = MBB->begin();
605   DebugLoc DL;                  // Defaults to "unknown"
606   if (Ins != MBB->end())
607     DL = Ins->getDebugLoc();
608
609   const MCInstrDesc &MCID = TII.get(ADDriOpc);
610   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
611   const MachineFunction &MF = *MBB->getParent();
612   MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
613
614   MachineInstrBuilder MIB = AddDefaultPred(BuildMI(*MBB, Ins, DL, MCID, BaseReg)
615     .addFrameIndex(FrameIdx).addImm(Offset));
616
617   if (!AFI->isThumb1OnlyFunction())
618     AddDefaultCC(MIB);
619 }
620
621 void
622 ARMBaseRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
623                                        unsigned BaseReg, int64_t Offset) const {
624   MachineInstr &MI = *I;
625   MachineBasicBlock &MBB = *MI.getParent();
626   MachineFunction &MF = *MBB.getParent();
627   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
628   int Off = Offset; // ARM doesn't need the general 64-bit offsets
629   unsigned i = 0;
630
631   assert(!AFI->isThumb1OnlyFunction() &&
632          "This resolveFrameIndex does not support Thumb1!");
633
634   while (!MI.getOperand(i).isFI()) {
635     ++i;
636     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
637   }
638   bool Done = false;
639   if (!AFI->isThumbFunction())
640     Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
641   else {
642     assert(AFI->isThumb2Function());
643     Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
644   }
645   assert (Done && "Unable to resolve frame index!");
646   (void)Done;
647 }
648
649 bool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
650                                              int64_t Offset) const {
651   const MCInstrDesc &Desc = MI->getDesc();
652   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
653   unsigned i = 0;
654
655   while (!MI->getOperand(i).isFI()) {
656     ++i;
657     assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
658   }
659
660   // AddrMode4 and AddrMode6 cannot handle any offset.
661   if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
662     return Offset == 0;
663
664   unsigned NumBits = 0;
665   unsigned Scale = 1;
666   bool isSigned = true;
667   switch (AddrMode) {
668   case ARMII::AddrModeT2_i8:
669   case ARMII::AddrModeT2_i12:
670     // i8 supports only negative, and i12 supports only positive, so
671     // based on Offset sign, consider the appropriate instruction
672     Scale = 1;
673     if (Offset < 0) {
674       NumBits = 8;
675       Offset = -Offset;
676     } else {
677       NumBits = 12;
678     }
679     break;
680   case ARMII::AddrMode5:
681     // VFP address mode.
682     NumBits = 8;
683     Scale = 4;
684     break;
685   case ARMII::AddrMode_i12:
686   case ARMII::AddrMode2:
687     NumBits = 12;
688     break;
689   case ARMII::AddrMode3:
690     NumBits = 8;
691     break;
692   case ARMII::AddrModeT1_s:
693     NumBits = 5;
694     Scale = 4;
695     isSigned = false;
696     break;
697   default:
698     llvm_unreachable("Unsupported addressing mode!");
699   }
700
701   Offset += getFrameIndexInstrOffset(MI, i);
702   // Make sure the offset is encodable for instructions that scale the
703   // immediate.
704   if ((Offset & (Scale-1)) != 0)
705     return false;
706
707   if (isSigned && Offset < 0)
708     Offset = -Offset;
709
710   unsigned Mask = (1 << NumBits) - 1;
711   if ((unsigned)Offset <= Mask * Scale)
712     return true;
713
714   return false;
715 }
716
717 void
718 ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
719                                          int SPAdj, RegScavenger *RS) const {
720   unsigned i = 0;
721   MachineInstr &MI = *II;
722   MachineBasicBlock &MBB = *MI.getParent();
723   MachineFunction &MF = *MBB.getParent();
724   const ARMFrameLowering *TFI =
725     static_cast<const ARMFrameLowering*>(MF.getTarget().getFrameLowering());
726   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
727   assert(!AFI->isThumb1OnlyFunction() &&
728          "This eliminateFrameIndex does not support Thumb1!");
729
730   while (!MI.getOperand(i).isFI()) {
731     ++i;
732     assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
733   }
734
735   int FrameIndex = MI.getOperand(i).getIndex();
736   unsigned FrameReg;
737
738   int Offset = TFI->ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
739
740   // PEI::scavengeFrameVirtualRegs() cannot accurately track SPAdj because the
741   // call frame setup/destroy instructions have already been eliminated.  That
742   // means the stack pointer cannot be used to access the emergency spill slot
743   // when !hasReservedCallFrame().
744 #ifndef NDEBUG
745   if (RS && FrameReg == ARM::SP && FrameIndex == RS->getScavengingFrameIndex()){
746     assert(TFI->hasReservedCallFrame(MF) &&
747            "Cannot use SP to access the emergency spill slot in "
748            "functions without a reserved call frame");
749     assert(!MF.getFrameInfo()->hasVarSizedObjects() &&
750            "Cannot use SP to access the emergency spill slot in "
751            "functions with variable sized frame objects");
752   }
753 #endif // NDEBUG
754
755   // Special handling of dbg_value instructions.
756   if (MI.isDebugValue()) {
757     MI.getOperand(i).  ChangeToRegister(FrameReg, false /*isDef*/);
758     MI.getOperand(i+1).ChangeToImmediate(Offset);
759     return;
760   }
761
762   // Modify MI as necessary to handle as much of 'Offset' as possible
763   bool Done = false;
764   if (!AFI->isThumbFunction())
765     Done = rewriteARMFrameIndex(MI, i, FrameReg, Offset, TII);
766   else {
767     assert(AFI->isThumb2Function());
768     Done = rewriteT2FrameIndex(MI, i, FrameReg, Offset, TII);
769   }
770   if (Done)
771     return;
772
773   // If we get here, the immediate doesn't fit into the instruction.  We folded
774   // as much as possible above, handle the rest, providing a register that is
775   // SP+LargeImm.
776   assert((Offset ||
777           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
778           (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
779          "This code isn't needed if offset already handled!");
780
781   unsigned ScratchReg = 0;
782   int PIdx = MI.findFirstPredOperandIdx();
783   ARMCC::CondCodes Pred = (PIdx == -1)
784     ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
785   unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
786   if (Offset == 0)
787     // Must be addrmode4/6.
788     MI.getOperand(i).ChangeToRegister(FrameReg, false, false, false);
789   else {
790     ScratchReg = MF.getRegInfo().createVirtualRegister(&ARM::GPRRegClass);
791     if (!AFI->isThumbFunction())
792       emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
793                               Offset, Pred, PredReg, TII);
794     else {
795       assert(AFI->isThumb2Function());
796       emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
797                              Offset, Pred, PredReg, TII);
798     }
799     // Update the original instruction to use the scratch register.
800     MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
801   }
802 }