ARMBaseRegisterInfo.cpp revision 276479
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
46using namespace llvm;
47
48ARMBaseRegisterInfo::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
61const MCPhysReg*
62ARMBaseRegisterInfo::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
93const uint32_t*
94ARMBaseRegisterInfo::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
102const uint32_t*
103ARMBaseRegisterInfo::getNoPreservedMask() const {
104  return CSR_NoRegs_RegMask;
105}
106
107const uint32_t*
108ARMBaseRegisterInfo::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
124BitVector ARMBaseRegisterInfo::
125getReservedRegs(const MachineFunction &MF) const {
126  const TargetFrameLowering *TFI = MF.getTarget().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
155const TargetRegisterClass*
156ARMBaseRegisterInfo::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
176const TargetRegisterClass *
177ARMBaseRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
178                                                                         const {
179  return &ARM::GPRRegClass;
180}
181
182const TargetRegisterClass *
183ARMBaseRegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
184  if (RC == &ARM::CCRRegClass)
185    return nullptr;  // Can't copy CCR registers.
186  return RC;
187}
188
189unsigned
190ARMBaseRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
191                                         MachineFunction &MF) const {
192  const TargetFrameLowering *TFI = MF.getTarget().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.
210static 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.
218void
219ARMBaseRegisterInfo::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
268void
269ARMBaseRegisterInfo::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
288bool
289ARMBaseRegisterInfo::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
311bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
312  const MachineFrameInfo *MFI = MF.getFrameInfo();
313  const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
314  const TargetFrameLowering *TFI = MF.getTarget().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
342bool 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().getFrameLowering()->hasReservedCallFrame(MF))
360    return true;
361  // A base pointer is required and allowed.  Check that it isn't too late to
362  // reserve it.
363  return MRI->canReserveReg(BasePtr);
364}
365
366bool ARMBaseRegisterInfo::
367needsStackRealignment(const MachineFunction &MF) const {
368  const MachineFrameInfo *MFI = MF.getFrameInfo();
369  const Function *F = MF.getFunction();
370  unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
371  bool requiresRealignment =
372    ((MFI->getMaxAlignment() > StackAlign) ||
373     F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
374                                     Attribute::StackAlignment));
375
376  return requiresRealignment && canRealignStack(MF);
377}
378
379bool ARMBaseRegisterInfo::
380cannotEliminateFrame(const MachineFunction &MF) const {
381  const MachineFrameInfo *MFI = MF.getFrameInfo();
382  if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI->adjustsStack())
383    return true;
384  return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
385    || needsStackRealignment(MF);
386}
387
388unsigned
389ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
390  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
391
392  if (TFI->hasFP(MF))
393    return FramePtr;
394  return ARM::SP;
395}
396
397/// emitLoadConstPool - Emits a load from constpool to materialize the
398/// specified immediate.
399void ARMBaseRegisterInfo::
400emitLoadConstPool(MachineBasicBlock &MBB,
401                  MachineBasicBlock::iterator &MBBI,
402                  DebugLoc dl,
403                  unsigned DestReg, unsigned SubIdx, int Val,
404                  ARMCC::CondCodes Pred,
405                  unsigned PredReg, unsigned MIFlags) const {
406  MachineFunction &MF = *MBB.getParent();
407  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
408  MachineConstantPool *ConstantPool = MF.getConstantPool();
409  const Constant *C =
410        ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
411  unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
412
413  BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
414    .addReg(DestReg, getDefRegState(true), SubIdx)
415    .addConstantPoolIndex(Idx)
416    .addImm(0).addImm(Pred).addReg(PredReg)
417    .setMIFlags(MIFlags);
418}
419
420bool ARMBaseRegisterInfo::mayOverrideLocalAssignment() const {
421  // The native linux build hits a downstream codegen bug when this is enabled.
422  return STI.isTargetDarwin();
423}
424
425bool ARMBaseRegisterInfo::
426requiresRegisterScavenging(const MachineFunction &MF) const {
427  return true;
428}
429
430bool ARMBaseRegisterInfo::
431trackLivenessAfterRegAlloc(const MachineFunction &MF) const {
432  return true;
433}
434
435bool ARMBaseRegisterInfo::
436requiresFrameIndexScavenging(const MachineFunction &MF) const {
437  return true;
438}
439
440bool ARMBaseRegisterInfo::
441requiresVirtualBaseRegisters(const MachineFunction &MF) const {
442  return true;
443}
444
445int64_t ARMBaseRegisterInfo::
446getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
447  const MCInstrDesc &Desc = MI->getDesc();
448  unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
449  int64_t InstrOffs = 0;
450  int Scale = 1;
451  unsigned ImmIdx = 0;
452  switch (AddrMode) {
453  case ARMII::AddrModeT2_i8:
454  case ARMII::AddrModeT2_i12:
455  case ARMII::AddrMode_i12:
456    InstrOffs = MI->getOperand(Idx+1).getImm();
457    Scale = 1;
458    break;
459  case ARMII::AddrMode5: {
460    // VFP address mode.
461    const MachineOperand &OffOp = MI->getOperand(Idx+1);
462    InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
463    if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
464      InstrOffs = -InstrOffs;
465    Scale = 4;
466    break;
467  }
468  case ARMII::AddrMode2: {
469    ImmIdx = Idx+2;
470    InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
471    if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
472      InstrOffs = -InstrOffs;
473    break;
474  }
475  case ARMII::AddrMode3: {
476    ImmIdx = Idx+2;
477    InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
478    if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
479      InstrOffs = -InstrOffs;
480    break;
481  }
482  case ARMII::AddrModeT1_s: {
483    ImmIdx = Idx+1;
484    InstrOffs = MI->getOperand(ImmIdx).getImm();
485    Scale = 4;
486    break;
487  }
488  default:
489    llvm_unreachable("Unsupported addressing mode!");
490  }
491
492  return InstrOffs * Scale;
493}
494
495/// needsFrameBaseReg - Returns true if the instruction's frame index
496/// reference would be better served by a base register other than FP
497/// or SP. Used by LocalStackFrameAllocation to determine which frame index
498/// references it should create new base registers for.
499bool ARMBaseRegisterInfo::
500needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
501  for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
502    assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
503  }
504
505  // It's the load/store FI references that cause issues, as it can be difficult
506  // to materialize the offset if it won't fit in the literal field. Estimate
507  // based on the size of the local frame and some conservative assumptions
508  // about the rest of the stack frame (note, this is pre-regalloc, so
509  // we don't know everything for certain yet) whether this offset is likely
510  // to be out of range of the immediate. Return true if so.
511
512  // We only generate virtual base registers for loads and stores, so
513  // return false for everything else.
514  unsigned Opc = MI->getOpcode();
515  switch (Opc) {
516  case ARM::LDRi12: case ARM::LDRH: case ARM::LDRBi12:
517  case ARM::STRi12: case ARM::STRH: case ARM::STRBi12:
518  case ARM::t2LDRi12: case ARM::t2LDRi8:
519  case ARM::t2STRi12: case ARM::t2STRi8:
520  case ARM::VLDRS: case ARM::VLDRD:
521  case ARM::VSTRS: case ARM::VSTRD:
522  case ARM::tSTRspi: case ARM::tLDRspi:
523    break;
524  default:
525    return false;
526  }
527
528  // Without a virtual base register, if the function has variable sized
529  // objects, all fixed-size local references will be via the frame pointer,
530  // Approximate the offset and see if it's legal for the instruction.
531  // Note that the incoming offset is based on the SP value at function entry,
532  // so it'll be negative.
533  MachineFunction &MF = *MI->getParent()->getParent();
534  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
535  MachineFrameInfo *MFI = MF.getFrameInfo();
536  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
537
538  // Estimate an offset from the frame pointer.
539  // Conservatively assume all callee-saved registers get pushed. R4-R6
540  // will be earlier than the FP, so we ignore those.
541  // R7, LR
542  int64_t FPOffset = Offset - 8;
543  // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
544  if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
545    FPOffset -= 80;
546  // Estimate an offset from the stack pointer.
547  // The incoming offset is relating to the SP at the start of the function,
548  // but when we access the local it'll be relative to the SP after local
549  // allocation, so adjust our SP-relative offset by that allocation size.
550  Offset = -Offset;
551  Offset += MFI->getLocalFrameSize();
552  // Assume that we'll have at least some spill slots allocated.
553  // FIXME: This is a total SWAG number. We should run some statistics
554  //        and pick a real one.
555  Offset += 128; // 128 bytes of spill slots
556
557  // If there is a frame pointer, try using it.
558  // The FP is only available if there is no dynamic realignment. We
559  // don't know for sure yet whether we'll need that, so we guess based
560  // on whether there are any local variables that would trigger it.
561  unsigned StackAlign = TFI->getStackAlignment();
562  if (TFI->hasFP(MF) &&
563      !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
564    if (isFrameOffsetLegal(MI, FPOffset))
565      return false;
566  }
567  // If we can reference via the stack pointer, try that.
568  // FIXME: This (and the code that resolves the references) can be improved
569  //        to only disallow SP relative references in the live range of
570  //        the VLA(s). In practice, it's unclear how much difference that
571  //        would make, but it may be worth doing.
572  if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
573    return false;
574
575  // The offset likely isn't legal, we want to allocate a virtual base register.
576  return true;
577}
578
579/// materializeFrameBaseRegister - Insert defining instruction(s) for BaseReg to
580/// be a pointer to FrameIdx at the beginning of the basic block.
581void ARMBaseRegisterInfo::
582materializeFrameBaseRegister(MachineBasicBlock *MBB,
583                             unsigned BaseReg, int FrameIdx,
584                             int64_t Offset) const {
585  ARMFunctionInfo *AFI = MBB->getParent()->getInfo<ARMFunctionInfo>();
586  unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
587    (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
588
589  MachineBasicBlock::iterator Ins = MBB->begin();
590  DebugLoc DL;                  // Defaults to "unknown"
591  if (Ins != MBB->end())
592    DL = Ins->getDebugLoc();
593
594  const MachineFunction &MF = *MBB->getParent();
595  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
596  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
597  const MCInstrDesc &MCID = TII.get(ADDriOpc);
598  MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
599
600  MachineInstrBuilder MIB = AddDefaultPred(BuildMI(*MBB, Ins, DL, MCID, BaseReg)
601    .addFrameIndex(FrameIdx).addImm(Offset));
602
603  if (!AFI->isThumb1OnlyFunction())
604    AddDefaultCC(MIB);
605}
606
607void ARMBaseRegisterInfo::resolveFrameIndex(MachineInstr &MI, unsigned BaseReg,
608                                            int64_t Offset) const {
609  MachineBasicBlock &MBB = *MI.getParent();
610  MachineFunction &MF = *MBB.getParent();
611  const ARMBaseInstrInfo &TII =
612    *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
613  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
614  int Off = Offset; // ARM doesn't need the general 64-bit offsets
615  unsigned i = 0;
616
617  assert(!AFI->isThumb1OnlyFunction() &&
618         "This resolveFrameIndex does not support Thumb1!");
619
620  while (!MI.getOperand(i).isFI()) {
621    ++i;
622    assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
623  }
624  bool Done = false;
625  if (!AFI->isThumbFunction())
626    Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
627  else {
628    assert(AFI->isThumb2Function());
629    Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
630  }
631  assert (Done && "Unable to resolve frame index!");
632  (void)Done;
633}
634
635bool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
636                                             int64_t Offset) const {
637  const MCInstrDesc &Desc = MI->getDesc();
638  unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
639  unsigned i = 0;
640
641  while (!MI->getOperand(i).isFI()) {
642    ++i;
643    assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
644  }
645
646  // AddrMode4 and AddrMode6 cannot handle any offset.
647  if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
648    return Offset == 0;
649
650  unsigned NumBits = 0;
651  unsigned Scale = 1;
652  bool isSigned = true;
653  switch (AddrMode) {
654  case ARMII::AddrModeT2_i8:
655  case ARMII::AddrModeT2_i12:
656    // i8 supports only negative, and i12 supports only positive, so
657    // based on Offset sign, consider the appropriate instruction
658    Scale = 1;
659    if (Offset < 0) {
660      NumBits = 8;
661      Offset = -Offset;
662    } else {
663      NumBits = 12;
664    }
665    break;
666  case ARMII::AddrMode5:
667    // VFP address mode.
668    NumBits = 8;
669    Scale = 4;
670    break;
671  case ARMII::AddrMode_i12:
672  case ARMII::AddrMode2:
673    NumBits = 12;
674    break;
675  case ARMII::AddrMode3:
676    NumBits = 8;
677    break;
678  case ARMII::AddrModeT1_s:
679    NumBits = 5;
680    Scale = 4;
681    isSigned = false;
682    break;
683  default:
684    llvm_unreachable("Unsupported addressing mode!");
685  }
686
687  Offset += getFrameIndexInstrOffset(MI, i);
688  // Make sure the offset is encodable for instructions that scale the
689  // immediate.
690  if ((Offset & (Scale-1)) != 0)
691    return false;
692
693  if (isSigned && Offset < 0)
694    Offset = -Offset;
695
696  unsigned Mask = (1 << NumBits) - 1;
697  if ((unsigned)Offset <= Mask * Scale)
698    return true;
699
700  return false;
701}
702
703void
704ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
705                                         int SPAdj, unsigned FIOperandNum,
706                                         RegScavenger *RS) const {
707  MachineInstr &MI = *II;
708  MachineBasicBlock &MBB = *MI.getParent();
709  MachineFunction &MF = *MBB.getParent();
710  const ARMBaseInstrInfo &TII =
711    *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
712  const ARMFrameLowering *TFI =
713    static_cast<const ARMFrameLowering*>(MF.getTarget().getFrameLowering());
714  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
715  assert(!AFI->isThumb1OnlyFunction() &&
716         "This eliminateFrameIndex does not support Thumb1!");
717  int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
718  unsigned FrameReg;
719
720  int Offset = TFI->ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
721
722  // PEI::scavengeFrameVirtualRegs() cannot accurately track SPAdj because the
723  // call frame setup/destroy instructions have already been eliminated.  That
724  // means the stack pointer cannot be used to access the emergency spill slot
725  // when !hasReservedCallFrame().
726#ifndef NDEBUG
727  if (RS && FrameReg == ARM::SP && RS->isScavengingFrameIndex(FrameIndex)){
728    assert(TFI->hasReservedCallFrame(MF) &&
729           "Cannot use SP to access the emergency spill slot in "
730           "functions without a reserved call frame");
731    assert(!MF.getFrameInfo()->hasVarSizedObjects() &&
732           "Cannot use SP to access the emergency spill slot in "
733           "functions with variable sized frame objects");
734  }
735#endif // NDEBUG
736
737  assert(!MI.isDebugValue() && "DBG_VALUEs should be handled in target-independent code");
738
739  // Modify MI as necessary to handle as much of 'Offset' as possible
740  bool Done = false;
741  if (!AFI->isThumbFunction())
742    Done = rewriteARMFrameIndex(MI, FIOperandNum, FrameReg, Offset, TII);
743  else {
744    assert(AFI->isThumb2Function());
745    Done = rewriteT2FrameIndex(MI, FIOperandNum, FrameReg, Offset, TII);
746  }
747  if (Done)
748    return;
749
750  // If we get here, the immediate doesn't fit into the instruction.  We folded
751  // as much as possible above, handle the rest, providing a register that is
752  // SP+LargeImm.
753  assert((Offset ||
754          (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
755          (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
756         "This code isn't needed if offset already handled!");
757
758  unsigned ScratchReg = 0;
759  int PIdx = MI.findFirstPredOperandIdx();
760  ARMCC::CondCodes Pred = (PIdx == -1)
761    ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
762  unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
763  if (Offset == 0)
764    // Must be addrmode4/6.
765    MI.getOperand(FIOperandNum).ChangeToRegister(FrameReg, false, false, false);
766  else {
767    ScratchReg = MF.getRegInfo().createVirtualRegister(&ARM::GPRRegClass);
768    if (!AFI->isThumbFunction())
769      emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
770                              Offset, Pred, PredReg, TII);
771    else {
772      assert(AFI->isThumb2Function());
773      emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
774                             Offset, Pred, PredReg, TII);
775    }
776    // Update the original instruction to use the scratch register.
777    MI.getOperand(FIOperandNum).ChangeToRegister(ScratchReg, false, false,true);
778  }
779}
780
781bool ARMBaseRegisterInfo::shouldCoalesce(MachineInstr *MI,
782                                  const TargetRegisterClass *SrcRC,
783                                  unsigned SubReg,
784                                  const TargetRegisterClass *DstRC,
785                                  unsigned DstSubReg,
786                                  const TargetRegisterClass *NewRC) const {
787  auto MBB = MI->getParent();
788  auto MF = MBB->getParent();
789  const MachineRegisterInfo &MRI = MF->getRegInfo();
790  // If not copying into a sub-register this should be ok because we shouldn't
791  // need to split the reg.
792  if (!DstSubReg)
793    return true;
794  // Small registers don't frequently cause a problem, so we can coalesce them.
795  if (NewRC->getSize() < 32 && DstRC->getSize() < 32 && SrcRC->getSize() < 32)
796    return true;
797
798  auto NewRCWeight =
799              MRI.getTargetRegisterInfo()->getRegClassWeight(NewRC);
800  auto SrcRCWeight =
801              MRI.getTargetRegisterInfo()->getRegClassWeight(SrcRC);
802  auto DstRCWeight =
803              MRI.getTargetRegisterInfo()->getRegClassWeight(DstRC);
804  // If the source register class is more expensive than the destination, the
805  // coalescing is probably profitable.
806  if (SrcRCWeight.RegWeight > NewRCWeight.RegWeight)
807    return true;
808  if (DstRCWeight.RegWeight > NewRCWeight.RegWeight)
809    return true;
810
811  // If the register allocator isn't constrained, we can always allow coalescing
812  // unfortunately we don't know yet if we will be constrained.
813  // The goal of this heuristic is to restrict how many expensive registers
814  // we allow to coalesce in a given basic block.
815  auto AFI = MF->getInfo<ARMFunctionInfo>();
816  auto It = AFI->getCoalescedWeight(MBB);
817
818  DEBUG(dbgs() << "\tARM::shouldCoalesce - Coalesced Weight: "
819    << It->second << "\n");
820  DEBUG(dbgs() << "\tARM::shouldCoalesce - Reg Weight: "
821    << NewRCWeight.RegWeight << "\n");
822
823  // This number is the largest round number that which meets the criteria:
824  //  (1) addresses PR18825
825  //  (2) generates better code in some test cases (like vldm-shed-a9.ll)
826  //  (3) Doesn't regress any test cases (in-tree, test-suite, and SPEC)
827  // In practice the SizeMultiplier will only factor in for straight line code
828  // that uses a lot of NEON vectors, which isn't terribly common.
829  unsigned SizeMultiplier = MBB->size()/100;
830  SizeMultiplier = SizeMultiplier ? SizeMultiplier : 1;
831  if (It->second < NewRCWeight.WeightLimit * SizeMultiplier) {
832    It->second += NewRCWeight.RegWeight;
833    return true;
834  }
835  return false;
836}
837