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