1235633Sdim//===-- ARMBaseRegisterInfo.cpp - ARM Register Information ----------------===//
2198090Srdivacky//
3198090Srdivacky//                     The LLVM Compiler Infrastructure
4198090Srdivacky//
5198090Srdivacky// This file is distributed under the University of Illinois Open Source
6198090Srdivacky// License. See LICENSE.TXT for details.
7198090Srdivacky//
8198090Srdivacky//===----------------------------------------------------------------------===//
9198090Srdivacky//
10198090Srdivacky// This file contains the base ARM implementation of TargetRegisterInfo class.
11198090Srdivacky//
12198090Srdivacky//===----------------------------------------------------------------------===//
13198090Srdivacky
14235633Sdim#include "ARMBaseRegisterInfo.h"
15198090Srdivacky#include "ARM.h"
16198090Srdivacky#include "ARMBaseInstrInfo.h"
17218893Sdim#include "ARMFrameLowering.h"
18198090Srdivacky#include "ARMMachineFunctionInfo.h"
19198090Srdivacky#include "ARMSubtarget.h"
20226890Sdim#include "MCTargetDesc/ARMAddressingModes.h"
21252723Sdim#include "llvm/ADT/BitVector.h"
22252723Sdim#include "llvm/ADT/SmallVector.h"
23198090Srdivacky#include "llvm/CodeGen/MachineConstantPool.h"
24198090Srdivacky#include "llvm/CodeGen/MachineFrameInfo.h"
25198090Srdivacky#include "llvm/CodeGen/MachineFunction.h"
26198090Srdivacky#include "llvm/CodeGen/MachineInstrBuilder.h"
27198090Srdivacky#include "llvm/CodeGen/MachineRegisterInfo.h"
28198090Srdivacky#include "llvm/CodeGen/RegisterScavenging.h"
29252723Sdim#include "llvm/CodeGen/VirtRegMap.h"
30252723Sdim#include "llvm/IR/Constants.h"
31252723Sdim#include "llvm/IR/DerivedTypes.h"
32252723Sdim#include "llvm/IR/Function.h"
33252723Sdim#include "llvm/IR/LLVMContext.h"
34198892Srdivacky#include "llvm/Support/Debug.h"
35198090Srdivacky#include "llvm/Support/ErrorHandling.h"
36198090Srdivacky#include "llvm/Support/raw_ostream.h"
37218893Sdim#include "llvm/Target/TargetFrameLowering.h"
38198090Srdivacky#include "llvm/Target/TargetMachine.h"
39198090Srdivacky#include "llvm/Target/TargetOptions.h"
40198090Srdivacky
41224145Sdim#define GET_REGINFO_TARGET_DESC
42224145Sdim#include "ARMGenRegisterInfo.inc"
43224145Sdim
44218893Sdimusing namespace llvm;
45218893Sdim
46263509SdimARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMSubtarget &sti)
47263509Sdim  : ARMGenRegisterInfo(ARM::LR, 0, 0, ARM::PC), STI(sti),
48212904Sdim    FramePtr((STI.isTargetDarwin() || STI.isThumb()) ? ARM::R7 : ARM::R11),
49212904Sdim    BasePtr(ARM::R6) {
50198090Srdivacky}
51198090Srdivacky
52235633Sdimconst uint16_t*
53198090SrdivackyARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
54263509Sdim  const uint16_t *RegList = (STI.isTargetIOS() && !STI.isAAPCS_ABI())
55263509Sdim                                ? CSR_iOS_SaveList
56263509Sdim                                : CSR_AAPCS_SaveList;
57263509Sdim
58263509Sdim  if (!MF) return RegList;
59263509Sdim
60263509Sdim  const Function *F = MF->getFunction();
61263509Sdim  if (F->getCallingConv() == CallingConv::GHC) {
62263509Sdim    // GHC set of callee saved regs is empty as all those regs are
63263509Sdim    // used for passing STG regs around
64263509Sdim    return CSR_NoRegs_SaveList;
65263509Sdim  } else if (F->hasFnAttribute("interrupt")) {
66263509Sdim    if (STI.isMClass()) {
67263509Sdim      // M-class CPUs have hardware which saves the registers needed to allow a
68263509Sdim      // function conforming to the AAPCS to function as a handler.
69263509Sdim      return CSR_AAPCS_SaveList;
70263509Sdim    } else if (F->getFnAttribute("interrupt").getValueAsString() == "FIQ") {
71263509Sdim      // Fast interrupt mode gives the handler a private copy of R8-R14, so less
72263509Sdim      // need to be saved to restore user-mode state.
73263509Sdim      return CSR_FIQ_SaveList;
74263509Sdim    } else {
75263509Sdim      // Generally only R13-R14 (i.e. SP, LR) are automatically preserved by
76263509Sdim      // exception handling.
77263509Sdim      return CSR_GenericInt_SaveList;
78263509Sdim    }
79245431Sdim  }
80263509Sdim
81263509Sdim  return RegList;
82235633Sdim}
83229042Sdim
84235633Sdimconst uint32_t*
85263509SdimARMBaseRegisterInfo::getCallPreservedMask(CallingConv::ID CC) const {
86263509Sdim  if (CC == CallingConv::GHC)
87263509Sdim    // This is academic becase all GHC calls are (supposed to be) tail calls
88263509Sdim    return CSR_NoRegs_RegMask;
89245431Sdim  return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
90245431Sdim    ? CSR_iOS_RegMask : CSR_AAPCS_RegMask;
91198090Srdivacky}
92198090Srdivacky
93245431Sdimconst uint32_t*
94263509SdimARMBaseRegisterInfo::getNoPreservedMask() const {
95263509Sdim  return CSR_NoRegs_RegMask;
96252723Sdim}
97252723Sdim
98252723Sdimconst uint32_t*
99263509SdimARMBaseRegisterInfo::getThisReturnPreservedMask(CallingConv::ID CC) const {
100263509Sdim  // This should return a register mask that is the same as that returned by
101263509Sdim  // getCallPreservedMask but that additionally preserves the register used for
102263509Sdim  // the first i32 argument (which must also be the register used to return a
103263509Sdim  // single i32 return value)
104263509Sdim  //
105263509Sdim  // In case that the calling convention does not use the same register for
106263509Sdim  // both or otherwise does not want to enable this optimization, the function
107263509Sdim  // should return NULL
108263509Sdim  if (CC == CallingConv::GHC)
109263509Sdim    // This is academic becase all GHC calls are (supposed to be) tail calls
110263509Sdim    return NULL;
111263509Sdim  return (STI.isTargetIOS() && !STI.isAAPCS_ABI())
112263509Sdim    ? CSR_iOS_ThisReturn_RegMask : CSR_AAPCS_ThisReturn_RegMask;
113245431Sdim}
114245431Sdim
115202375SrdivackyBitVector ARMBaseRegisterInfo::
116202375SrdivackygetReservedRegs(const MachineFunction &MF) const {
117218893Sdim  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
118218893Sdim
119221345Sdim  // FIXME: avoid re-calculating this every time.
120198090Srdivacky  BitVector Reserved(getNumRegs());
121198090Srdivacky  Reserved.set(ARM::SP);
122198090Srdivacky  Reserved.set(ARM::PC);
123212904Sdim  Reserved.set(ARM::FPSCR);
124263509Sdim  Reserved.set(ARM::APSR_NZCV);
125218893Sdim  if (TFI->hasFP(MF))
126198090Srdivacky    Reserved.set(FramePtr);
127212904Sdim  if (hasBasePointer(MF))
128212904Sdim    Reserved.set(BasePtr);
129198090Srdivacky  // Some targets reserve R9.
130198090Srdivacky  if (STI.isR9Reserved())
131198090Srdivacky    Reserved.set(ARM::R9);
132224145Sdim  // Reserve D16-D31 if the subtarget doesn't support them.
133224145Sdim  if (!STI.hasVFP3() || STI.hasD16()) {
134224145Sdim    assert(ARM::D31 == ARM::D16 + 15);
135224145Sdim    for (unsigned i = 0; i != 16; ++i)
136224145Sdim      Reserved.set(ARM::D16 + i);
137224145Sdim  }
138245431Sdim  const TargetRegisterClass *RC  = &ARM::GPRPairRegClass;
139245431Sdim  for(TargetRegisterClass::iterator I = RC->begin(), E = RC->end(); I!=E; ++I)
140245431Sdim    for (MCSubRegIterator SI(*I, this); SI.isValid(); ++SI)
141245431Sdim      if (Reserved.test(*SI)) Reserved.set(*I);
142245431Sdim
143198090Srdivacky  return Reserved;
144198090Srdivacky}
145198090Srdivacky
146221345Sdimconst TargetRegisterClass*
147221345SdimARMBaseRegisterInfo::getLargestLegalSuperClass(const TargetRegisterClass *RC)
148221345Sdim                                                                         const {
149221345Sdim  const TargetRegisterClass *Super = RC;
150226890Sdim  TargetRegisterClass::sc_iterator I = RC->getSuperClasses();
151221345Sdim  do {
152221345Sdim    switch (Super->getID()) {
153221345Sdim    case ARM::GPRRegClassID:
154221345Sdim    case ARM::SPRRegClassID:
155221345Sdim    case ARM::DPRRegClassID:
156221345Sdim    case ARM::QPRRegClassID:
157221345Sdim    case ARM::QQPRRegClassID:
158221345Sdim    case ARM::QQQQPRRegClassID:
159245431Sdim    case ARM::GPRPairRegClassID:
160221345Sdim      return Super;
161221345Sdim    }
162221345Sdim    Super = *I++;
163221345Sdim  } while (Super);
164221345Sdim  return RC;
165221345Sdim}
166208599Srdivacky
167198892Srdivackyconst TargetRegisterClass *
168245431SdimARMBaseRegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind)
169245431Sdim                                                                         const {
170245431Sdim  return &ARM::GPRRegClass;
171198090Srdivacky}
172198090Srdivacky
173226890Sdimconst TargetRegisterClass *
174226890SdimARMBaseRegisterInfo::getCrossCopyRegClass(const TargetRegisterClass *RC) const {
175226890Sdim  if (RC == &ARM::CCRRegClass)
176226890Sdim    return 0;  // Can't copy CCR registers.
177226890Sdim  return RC;
178226890Sdim}
179226890Sdim
180221345Sdimunsigned
181221345SdimARMBaseRegisterInfo::getRegPressureLimit(const TargetRegisterClass *RC,
182221345Sdim                                         MachineFunction &MF) const {
183221345Sdim  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
184221345Sdim
185221345Sdim  switch (RC->getID()) {
186221345Sdim  default:
187221345Sdim    return 0;
188221345Sdim  case ARM::tGPRRegClassID:
189221345Sdim    return TFI->hasFP(MF) ? 4 : 5;
190221345Sdim  case ARM::GPRRegClassID: {
191221345Sdim    unsigned FP = TFI->hasFP(MF) ? 1 : 0;
192221345Sdim    return 10 - FP - (STI.isR9Reserved() ? 1 : 0);
193221345Sdim  }
194221345Sdim  case ARM::SPRRegClassID:  // Currently not used as 'rep' register class.
195221345Sdim  case ARM::DPRRegClassID:
196221345Sdim    return 32 - 10;
197221345Sdim  }
198221345Sdim}
199221345Sdim
200252723Sdim// Get the other register in a GPRPair.
201252723Sdimstatic unsigned getPairedGPR(unsigned Reg, bool Odd, const MCRegisterInfo *RI) {
202252723Sdim  for (MCSuperRegIterator Supers(Reg, RI); Supers.isValid(); ++Supers)
203252723Sdim    if (ARM::GPRPairRegClass.contains(*Supers))
204252723Sdim      return RI->getSubReg(*Supers, Odd ? ARM::gsub_1 : ARM::gsub_0);
205252723Sdim  return 0;
206252723Sdim}
207198090Srdivacky
208252723Sdim// Resolve the RegPairEven / RegPairOdd register allocator hints.
209252723Sdimvoid
210252723SdimARMBaseRegisterInfo::getRegAllocationHints(unsigned VirtReg,
211252723Sdim                                           ArrayRef<MCPhysReg> Order,
212252723Sdim                                           SmallVectorImpl<MCPhysReg> &Hints,
213252723Sdim                                           const MachineFunction &MF,
214252723Sdim                                           const VirtRegMap *VRM) const {
215252723Sdim  const MachineRegisterInfo &MRI = MF.getRegInfo();
216252723Sdim  std::pair<unsigned, unsigned> Hint = MRI.getRegAllocationHint(VirtReg);
217198090Srdivacky
218252723Sdim  unsigned Odd;
219252723Sdim  switch (Hint.first) {
220252723Sdim  case ARMRI::RegPairEven:
221252723Sdim    Odd = 0;
222252723Sdim    break;
223252723Sdim  case ARMRI::RegPairOdd:
224252723Sdim    Odd = 1;
225252723Sdim    break;
226252723Sdim  default:
227252723Sdim    TargetRegisterInfo::getRegAllocationHints(VirtReg, Order, Hints, MF, VRM);
228252723Sdim    return;
229252723Sdim  }
230198090Srdivacky
231252723Sdim  // This register should preferably be even (Odd == 0) or odd (Odd == 1).
232252723Sdim  // Check if the other part of the pair has already been assigned, and provide
233252723Sdim  // the paired register as the first hint.
234252723Sdim  unsigned PairedPhys = 0;
235252723Sdim  if (VRM && VRM->hasPhys(Hint.second)) {
236252723Sdim    PairedPhys = getPairedGPR(VRM->getPhys(Hint.second), Odd, this);
237252723Sdim    if (PairedPhys && MRI.isReserved(PairedPhys))
238252723Sdim      PairedPhys = 0;
239252723Sdim  }
240198090Srdivacky
241252723Sdim  // First prefer the paired physreg.
242252723Sdim  if (PairedPhys &&
243252723Sdim      std::find(Order.begin(), Order.end(), PairedPhys) != Order.end())
244252723Sdim    Hints.push_back(PairedPhys);
245198090Srdivacky
246252723Sdim  // Then prefer even or odd registers.
247252723Sdim  for (unsigned I = 0, E = Order.size(); I != E; ++I) {
248252723Sdim    unsigned Reg = Order[I];
249252723Sdim    if (Reg == PairedPhys || (getEncodingValue(Reg) & 1) != Odd)
250252723Sdim      continue;
251252723Sdim    // Don't provide hints that are paired to a reserved register.
252252723Sdim    unsigned Paired = getPairedGPR(Reg, !Odd, this);
253252723Sdim    if (!Paired || MRI.isReserved(Paired))
254252723Sdim      continue;
255252723Sdim    Hints.push_back(Reg);
256198090Srdivacky  }
257198090Srdivacky}
258198090Srdivacky
259198090Srdivackyvoid
260198090SrdivackyARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
261198090Srdivacky                                        MachineFunction &MF) const {
262198090Srdivacky  MachineRegisterInfo *MRI = &MF.getRegInfo();
263198090Srdivacky  std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
264198090Srdivacky  if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
265198090Srdivacky       Hint.first == (unsigned)ARMRI::RegPairEven) &&
266218893Sdim      TargetRegisterInfo::isVirtualRegister(Hint.second)) {
267198090Srdivacky    // If 'Reg' is one of the even / odd register pair and it's now changed
268198090Srdivacky    // (e.g. coalesced) into a different register. The other register of the
269198090Srdivacky    // pair allocation hint must be updated to reflect the relationship
270198090Srdivacky    // change.
271198090Srdivacky    unsigned OtherReg = Hint.second;
272198090Srdivacky    Hint = MRI->getRegAllocationHint(OtherReg);
273198090Srdivacky    if (Hint.second == Reg)
274198090Srdivacky      // Make sure the pair has not already divorced.
275198090Srdivacky      MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
276198090Srdivacky  }
277198090Srdivacky}
278198090Srdivacky
279221345Sdimbool
280221345SdimARMBaseRegisterInfo::avoidWriteAfterWrite(const TargetRegisterClass *RC) const {
281221345Sdim  // CortexA9 has a Write-after-write hazard for NEON registers.
282245431Sdim  if (!STI.isLikeA9())
283221345Sdim    return false;
284221345Sdim
285221345Sdim  switch (RC->getID()) {
286221345Sdim  case ARM::DPRRegClassID:
287221345Sdim  case ARM::DPR_8RegClassID:
288221345Sdim  case ARM::DPR_VFP2RegClassID:
289221345Sdim  case ARM::QPRRegClassID:
290221345Sdim  case ARM::QPR_8RegClassID:
291221345Sdim  case ARM::QPR_VFP2RegClassID:
292221345Sdim  case ARM::SPRRegClassID:
293221345Sdim  case ARM::SPR_8RegClassID:
294221345Sdim    // Avoid reusing S, D, and Q registers.
295221345Sdim    // Don't increase register pressure for QQ and QQQQ.
296221345Sdim    return true;
297221345Sdim  default:
298221345Sdim    return false;
299221345Sdim  }
300221345Sdim}
301221345Sdim
302212904Sdimbool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
303212904Sdim  const MachineFrameInfo *MFI = MF.getFrameInfo();
304212904Sdim  const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
305235633Sdim  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
306212904Sdim
307235633Sdim  // When outgoing call frames are so large that we adjust the stack pointer
308235633Sdim  // around the call, we can no longer use the stack pointer to reach the
309235633Sdim  // emergency spill slot.
310235633Sdim  if (needsStackRealignment(MF) && !TFI->hasReservedCallFrame(MF))
311212904Sdim    return true;
312212904Sdim
313212904Sdim  // Thumb has trouble with negative offsets from the FP. Thumb2 has a limited
314212904Sdim  // negative range for ldr/str (255), and thumb1 is positive offsets only.
315212904Sdim  // It's going to be better to use the SP or Base Pointer instead. When there
316212904Sdim  // are variable sized objects, we can't reference off of the SP, so we
317212904Sdim  // reserve a Base Pointer.
318212904Sdim  if (AFI->isThumbFunction() && MFI->hasVarSizedObjects()) {
319212904Sdim    // Conservatively estimate whether the negative offset from the frame
320212904Sdim    // pointer will be sufficient to reach. If a function has a smallish
321212904Sdim    // frame, it's less likely to have lots of spills and callee saved
322212904Sdim    // space, so it's all more likely to be within range of the frame pointer.
323212904Sdim    // If it's wrong, the scavenger will still enable access to work, it just
324212904Sdim    // won't be optimal.
325212904Sdim    if (AFI->isThumb2Function() && MFI->getLocalFrameSize() < 128)
326212904Sdim      return false;
327212904Sdim    return true;
328212904Sdim  }
329212904Sdim
330212904Sdim  return false;
331212904Sdim}
332212904Sdim
333202878Srdivackybool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
334235633Sdim  const MachineRegisterInfo *MRI = &MF.getRegInfo();
335202878Srdivacky  const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
336212904Sdim  // We can't realign the stack if:
337212904Sdim  // 1. Dynamic stack realignment is explicitly disabled,
338212904Sdim  // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
339212904Sdim  // 3. There are VLAs in the function and the base pointer is disabled.
340263509Sdim  if (MF.getFunction()->hasFnAttribute("no-realign-stack"))
341235633Sdim    return false;
342235633Sdim  if (AFI->isThumb1OnlyFunction())
343235633Sdim    return false;
344235633Sdim  // Stack realignment requires a frame pointer.  If we already started
345235633Sdim  // register allocation with frame pointer elimination, it is too late now.
346235633Sdim  if (!MRI->canReserveReg(FramePtr))
347235633Sdim    return false;
348235633Sdim  // We may also need a base pointer if there are dynamic allocas or stack
349235633Sdim  // pointer adjustments around calls.
350235633Sdim  if (MF.getTarget().getFrameLowering()->hasReservedCallFrame(MF))
351235633Sdim    return true;
352235633Sdim  // A base pointer is required and allowed.  Check that it isn't too late to
353235633Sdim  // reserve it.
354235633Sdim  return MRI->canReserveReg(BasePtr);
355202878Srdivacky}
356202878Srdivacky
357198892Srdivackybool ARMBaseRegisterInfo::
358198892SrdivackyneedsStackRealignment(const MachineFunction &MF) const {
359198892Srdivacky  const MachineFrameInfo *MFI = MF.getFrameInfo();
360212904Sdim  const Function *F = MF.getFunction();
361218893Sdim  unsigned StackAlign = MF.getTarget().getFrameLowering()->getStackAlignment();
362245431Sdim  bool requiresRealignment =
363245431Sdim    ((MFI->getMaxAlignment() > StackAlign) ||
364252723Sdim     F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
365252723Sdim                                     Attribute::StackAlignment));
366212904Sdim
367212904Sdim  return requiresRealignment && canRealignStack(MF);
368198892Srdivacky}
369198892Srdivacky
370202375Srdivackybool ARMBaseRegisterInfo::
371202375SrdivackycannotEliminateFrame(const MachineFunction &MF) const {
372198090Srdivacky  const MachineFrameInfo *MFI = MF.getFrameInfo();
373235633Sdim  if (MF.getTarget().Options.DisableFramePointerElim(MF) && MFI->adjustsStack())
374198090Srdivacky    return true;
375199481Srdivacky  return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
376199481Srdivacky    || needsStackRealignment(MF);
377198090Srdivacky}
378198090Srdivacky
379212904Sdimunsigned
380199481SrdivackyARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
381218893Sdim  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
382218893Sdim
383218893Sdim  if (TFI->hasFP(MF))
384198090Srdivacky    return FramePtr;
385198090Srdivacky  return ARM::SP;
386198090Srdivacky}
387198090Srdivacky
388198090Srdivacky/// emitLoadConstPool - Emits a load from constpool to materialize the
389198090Srdivacky/// specified immediate.
390198090Srdivackyvoid ARMBaseRegisterInfo::
391198090SrdivackyemitLoadConstPool(MachineBasicBlock &MBB,
392198090Srdivacky                  MachineBasicBlock::iterator &MBBI,
393198090Srdivacky                  DebugLoc dl,
394198090Srdivacky                  unsigned DestReg, unsigned SubIdx, int Val,
395198090Srdivacky                  ARMCC::CondCodes Pred,
396221345Sdim                  unsigned PredReg, unsigned MIFlags) const {
397198090Srdivacky  MachineFunction &MF = *MBB.getParent();
398263509Sdim  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
399198090Srdivacky  MachineConstantPool *ConstantPool = MF.getConstantPool();
400207618Srdivacky  const Constant *C =
401198090Srdivacky        ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
402198090Srdivacky  unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
403198090Srdivacky
404198090Srdivacky  BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
405198090Srdivacky    .addReg(DestReg, getDefRegState(true), SubIdx)
406198090Srdivacky    .addConstantPoolIndex(Idx)
407221345Sdim    .addImm(0).addImm(Pred).addReg(PredReg)
408221345Sdim    .setMIFlags(MIFlags);
409198090Srdivacky}
410198090Srdivacky
411198090Srdivackybool ARMBaseRegisterInfo::
412198090SrdivackyrequiresRegisterScavenging(const MachineFunction &MF) const {
413198090Srdivacky  return true;
414198090Srdivacky}
415198090Srdivacky
416198396Srdivackybool ARMBaseRegisterInfo::
417245431SdimtrackLivenessAfterRegAlloc(const MachineFunction &MF) const {
418245431Sdim  return true;
419245431Sdim}
420245431Sdim
421245431Sdimbool ARMBaseRegisterInfo::
422198396SrdivackyrequiresFrameIndexScavenging(const MachineFunction &MF) const {
423198892Srdivacky  return true;
424198396Srdivacky}
425198396Srdivacky
426212904Sdimbool ARMBaseRegisterInfo::
427212904SdimrequiresVirtualBaseRegisters(const MachineFunction &MF) const {
428252723Sdim  return true;
429212904Sdim}
430212904Sdim
431212904Sdimint64_t ARMBaseRegisterInfo::
432212904SdimgetFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
433224145Sdim  const MCInstrDesc &Desc = MI->getDesc();
434212904Sdim  unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
435235633Sdim  int64_t InstrOffs = 0;
436212904Sdim  int Scale = 1;
437212904Sdim  unsigned ImmIdx = 0;
438212904Sdim  switch (AddrMode) {
439212904Sdim  case ARMII::AddrModeT2_i8:
440212904Sdim  case ARMII::AddrModeT2_i12:
441218893Sdim  case ARMII::AddrMode_i12:
442212904Sdim    InstrOffs = MI->getOperand(Idx+1).getImm();
443212904Sdim    Scale = 1;
444212904Sdim    break;
445212904Sdim  case ARMII::AddrMode5: {
446212904Sdim    // VFP address mode.
447212904Sdim    const MachineOperand &OffOp = MI->getOperand(Idx+1);
448212904Sdim    InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
449212904Sdim    if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
450212904Sdim      InstrOffs = -InstrOffs;
451212904Sdim    Scale = 4;
452212904Sdim    break;
453212904Sdim  }
454212904Sdim  case ARMII::AddrMode2: {
455212904Sdim    ImmIdx = Idx+2;
456212904Sdim    InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
457212904Sdim    if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
458212904Sdim      InstrOffs = -InstrOffs;
459212904Sdim    break;
460212904Sdim  }
461212904Sdim  case ARMII::AddrMode3: {
462212904Sdim    ImmIdx = Idx+2;
463212904Sdim    InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
464212904Sdim    if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
465212904Sdim      InstrOffs = -InstrOffs;
466212904Sdim    break;
467212904Sdim  }
468212904Sdim  case ARMII::AddrModeT1_s: {
469212904Sdim    ImmIdx = Idx+1;
470212904Sdim    InstrOffs = MI->getOperand(ImmIdx).getImm();
471212904Sdim    Scale = 4;
472212904Sdim    break;
473212904Sdim  }
474212904Sdim  default:
475212904Sdim    llvm_unreachable("Unsupported addressing mode!");
476212904Sdim  }
477212904Sdim
478212904Sdim  return InstrOffs * Scale;
479212904Sdim}
480212904Sdim
481212904Sdim/// needsFrameBaseReg - Returns true if the instruction's frame index
482212904Sdim/// reference would be better served by a base register other than FP
483212904Sdim/// or SP. Used by LocalStackFrameAllocation to determine which frame index
484212904Sdim/// references it should create new base registers for.
485212904Sdimbool ARMBaseRegisterInfo::
486212904SdimneedsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
487212904Sdim  for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
488212904Sdim    assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
489212904Sdim  }
490212904Sdim
491212904Sdim  // It's the load/store FI references that cause issues, as it can be difficult
492212904Sdim  // to materialize the offset if it won't fit in the literal field. Estimate
493212904Sdim  // based on the size of the local frame and some conservative assumptions
494212904Sdim  // about the rest of the stack frame (note, this is pre-regalloc, so
495212904Sdim  // we don't know everything for certain yet) whether this offset is likely
496212904Sdim  // to be out of range of the immediate. Return true if so.
497212904Sdim
498212904Sdim  // We only generate virtual base registers for loads and stores, so
499212904Sdim  // return false for everything else.
500212904Sdim  unsigned Opc = MI->getOpcode();
501212904Sdim  switch (Opc) {
502218893Sdim  case ARM::LDRi12: case ARM::LDRH: case ARM::LDRBi12:
503218893Sdim  case ARM::STRi12: case ARM::STRH: case ARM::STRBi12:
504212904Sdim  case ARM::t2LDRi12: case ARM::t2LDRi8:
505212904Sdim  case ARM::t2STRi12: case ARM::t2STRi8:
506212904Sdim  case ARM::VLDRS: case ARM::VLDRD:
507212904Sdim  case ARM::VSTRS: case ARM::VSTRD:
508212904Sdim  case ARM::tSTRspi: case ARM::tLDRspi:
509212904Sdim    break;
510212904Sdim  default:
511212904Sdim    return false;
512212904Sdim  }
513212904Sdim
514212904Sdim  // Without a virtual base register, if the function has variable sized
515212904Sdim  // objects, all fixed-size local references will be via the frame pointer,
516212904Sdim  // Approximate the offset and see if it's legal for the instruction.
517212904Sdim  // Note that the incoming offset is based on the SP value at function entry,
518212904Sdim  // so it'll be negative.
519212904Sdim  MachineFunction &MF = *MI->getParent()->getParent();
520218893Sdim  const TargetFrameLowering *TFI = MF.getTarget().getFrameLowering();
521212904Sdim  MachineFrameInfo *MFI = MF.getFrameInfo();
522212904Sdim  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
523212904Sdim
524212904Sdim  // Estimate an offset from the frame pointer.
525212904Sdim  // Conservatively assume all callee-saved registers get pushed. R4-R6
526212904Sdim  // will be earlier than the FP, so we ignore those.
527212904Sdim  // R7, LR
528212904Sdim  int64_t FPOffset = Offset - 8;
529212904Sdim  // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
530212904Sdim  if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
531212904Sdim    FPOffset -= 80;
532212904Sdim  // Estimate an offset from the stack pointer.
533212904Sdim  // The incoming offset is relating to the SP at the start of the function,
534212904Sdim  // but when we access the local it'll be relative to the SP after local
535212904Sdim  // allocation, so adjust our SP-relative offset by that allocation size.
536212904Sdim  Offset = -Offset;
537212904Sdim  Offset += MFI->getLocalFrameSize();
538212904Sdim  // Assume that we'll have at least some spill slots allocated.
539212904Sdim  // FIXME: This is a total SWAG number. We should run some statistics
540212904Sdim  //        and pick a real one.
541212904Sdim  Offset += 128; // 128 bytes of spill slots
542212904Sdim
543212904Sdim  // If there is a frame pointer, try using it.
544212904Sdim  // The FP is only available if there is no dynamic realignment. We
545212904Sdim  // don't know for sure yet whether we'll need that, so we guess based
546212904Sdim  // on whether there are any local variables that would trigger it.
547218893Sdim  unsigned StackAlign = TFI->getStackAlignment();
548218893Sdim  if (TFI->hasFP(MF) &&
549212904Sdim      !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
550212904Sdim    if (isFrameOffsetLegal(MI, FPOffset))
551212904Sdim      return false;
552212904Sdim  }
553212904Sdim  // If we can reference via the stack pointer, try that.
554212904Sdim  // FIXME: This (and the code that resolves the references) can be improved
555212904Sdim  //        to only disallow SP relative references in the live range of
556212904Sdim  //        the VLA(s). In practice, it's unclear how much difference that
557212904Sdim  //        would make, but it may be worth doing.
558212904Sdim  if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
559212904Sdim    return false;
560212904Sdim
561212904Sdim  // The offset likely isn't legal, we want to allocate a virtual base register.
562212904Sdim  return true;
563212904Sdim}
564212904Sdim
565218893Sdim/// materializeFrameBaseRegister - Insert defining instruction(s) for BaseReg to
566218893Sdim/// be a pointer to FrameIdx at the beginning of the basic block.
567212904Sdimvoid ARMBaseRegisterInfo::
568218893SdimmaterializeFrameBaseRegister(MachineBasicBlock *MBB,
569218893Sdim                             unsigned BaseReg, int FrameIdx,
570218893Sdim                             int64_t Offset) const {
571218893Sdim  ARMFunctionInfo *AFI = MBB->getParent()->getInfo<ARMFunctionInfo>();
572212904Sdim  unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
573212904Sdim    (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
574212904Sdim
575218893Sdim  MachineBasicBlock::iterator Ins = MBB->begin();
576218893Sdim  DebugLoc DL;                  // Defaults to "unknown"
577218893Sdim  if (Ins != MBB->end())
578218893Sdim    DL = Ins->getDebugLoc();
579218893Sdim
580263509Sdim  const MachineFunction &MF = *MBB->getParent();
581263509Sdim  MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
582263509Sdim  const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
583224145Sdim  const MCInstrDesc &MCID = TII.get(ADDriOpc);
584245431Sdim  MRI.constrainRegClass(BaseReg, TII.getRegClass(MCID, 0, this, MF));
585223017Sdim
586226890Sdim  MachineInstrBuilder MIB = AddDefaultPred(BuildMI(*MBB, Ins, DL, MCID, BaseReg)
587226890Sdim    .addFrameIndex(FrameIdx).addImm(Offset));
588218893Sdim
589212904Sdim  if (!AFI->isThumb1OnlyFunction())
590226890Sdim    AddDefaultCC(MIB);
591212904Sdim}
592212904Sdim
593212904Sdimvoid
594212904SdimARMBaseRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
595212904Sdim                                       unsigned BaseReg, int64_t Offset) const {
596212904Sdim  MachineInstr &MI = *I;
597212904Sdim  MachineBasicBlock &MBB = *MI.getParent();
598212904Sdim  MachineFunction &MF = *MBB.getParent();
599263509Sdim  const ARMBaseInstrInfo &TII =
600263509Sdim    *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
601212904Sdim  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
602212904Sdim  int Off = Offset; // ARM doesn't need the general 64-bit offsets
603212904Sdim  unsigned i = 0;
604212904Sdim
605212904Sdim  assert(!AFI->isThumb1OnlyFunction() &&
606212904Sdim         "This resolveFrameIndex does not support Thumb1!");
607212904Sdim
608212904Sdim  while (!MI.getOperand(i).isFI()) {
609212904Sdim    ++i;
610212904Sdim    assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
611212904Sdim  }
612212904Sdim  bool Done = false;
613212904Sdim  if (!AFI->isThumbFunction())
614212904Sdim    Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
615212904Sdim  else {
616212904Sdim    assert(AFI->isThumb2Function());
617212904Sdim    Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
618212904Sdim  }
619212904Sdim  assert (Done && "Unable to resolve frame index!");
620226890Sdim  (void)Done;
621212904Sdim}
622212904Sdim
623212904Sdimbool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
624212904Sdim                                             int64_t Offset) const {
625224145Sdim  const MCInstrDesc &Desc = MI->getDesc();
626212904Sdim  unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
627212904Sdim  unsigned i = 0;
628212904Sdim
629212904Sdim  while (!MI->getOperand(i).isFI()) {
630212904Sdim    ++i;
631212904Sdim    assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
632212904Sdim  }
633212904Sdim
634212904Sdim  // AddrMode4 and AddrMode6 cannot handle any offset.
635212904Sdim  if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
636212904Sdim    return Offset == 0;
637212904Sdim
638212904Sdim  unsigned NumBits = 0;
639212904Sdim  unsigned Scale = 1;
640212904Sdim  bool isSigned = true;
641212904Sdim  switch (AddrMode) {
642212904Sdim  case ARMII::AddrModeT2_i8:
643212904Sdim  case ARMII::AddrModeT2_i12:
644212904Sdim    // i8 supports only negative, and i12 supports only positive, so
645212904Sdim    // based on Offset sign, consider the appropriate instruction
646212904Sdim    Scale = 1;
647212904Sdim    if (Offset < 0) {
648212904Sdim      NumBits = 8;
649212904Sdim      Offset = -Offset;
650212904Sdim    } else {
651212904Sdim      NumBits = 12;
652212904Sdim    }
653212904Sdim    break;
654212904Sdim  case ARMII::AddrMode5:
655212904Sdim    // VFP address mode.
656212904Sdim    NumBits = 8;
657212904Sdim    Scale = 4;
658212904Sdim    break;
659218893Sdim  case ARMII::AddrMode_i12:
660212904Sdim  case ARMII::AddrMode2:
661212904Sdim    NumBits = 12;
662212904Sdim    break;
663212904Sdim  case ARMII::AddrMode3:
664212904Sdim    NumBits = 8;
665212904Sdim    break;
666212904Sdim  case ARMII::AddrModeT1_s:
667212904Sdim    NumBits = 5;
668212904Sdim    Scale = 4;
669212904Sdim    isSigned = false;
670212904Sdim    break;
671212904Sdim  default:
672212904Sdim    llvm_unreachable("Unsupported addressing mode!");
673212904Sdim  }
674212904Sdim
675212904Sdim  Offset += getFrameIndexInstrOffset(MI, i);
676212904Sdim  // Make sure the offset is encodable for instructions that scale the
677212904Sdim  // immediate.
678212904Sdim  if ((Offset & (Scale-1)) != 0)
679212904Sdim    return false;
680212904Sdim
681212904Sdim  if (isSigned && Offset < 0)
682212904Sdim    Offset = -Offset;
683212904Sdim
684212904Sdim  unsigned Mask = (1 << NumBits) - 1;
685212904Sdim  if ((unsigned)Offset <= Mask * Scale)
686212904Sdim    return true;
687212904Sdim
688212904Sdim  return false;
689212904Sdim}
690212904Sdim
691212904Sdimvoid
692198090SrdivackyARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
693252723Sdim                                         int SPAdj, unsigned FIOperandNum,
694252723Sdim                                         RegScavenger *RS) const {
695198090Srdivacky  MachineInstr &MI = *II;
696198090Srdivacky  MachineBasicBlock &MBB = *MI.getParent();
697198090Srdivacky  MachineFunction &MF = *MBB.getParent();
698263509Sdim  const ARMBaseInstrInfo &TII =
699263509Sdim    *static_cast<const ARMBaseInstrInfo*>(MF.getTarget().getInstrInfo());
700218893Sdim  const ARMFrameLowering *TFI =
701218893Sdim    static_cast<const ARMFrameLowering*>(MF.getTarget().getFrameLowering());
702198090Srdivacky  ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
703198090Srdivacky  assert(!AFI->isThumb1OnlyFunction() &&
704198090Srdivacky         "This eliminateFrameIndex does not support Thumb1!");
705252723Sdim  int FrameIndex = MI.getOperand(FIOperandNum).getIndex();
706199989Srdivacky  unsigned FrameReg;
707198090Srdivacky
708218893Sdim  int Offset = TFI->ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
709198090Srdivacky
710235633Sdim  // PEI::scavengeFrameVirtualRegs() cannot accurately track SPAdj because the
711235633Sdim  // call frame setup/destroy instructions have already been eliminated.  That
712235633Sdim  // means the stack pointer cannot be used to access the emergency spill slot
713235633Sdim  // when !hasReservedCallFrame().
714235633Sdim#ifndef NDEBUG
715252723Sdim  if (RS && FrameReg == ARM::SP && RS->isScavengingFrameIndex(FrameIndex)){
716235633Sdim    assert(TFI->hasReservedCallFrame(MF) &&
717235633Sdim           "Cannot use SP to access the emergency spill slot in "
718235633Sdim           "functions without a reserved call frame");
719235633Sdim    assert(!MF.getFrameInfo()->hasVarSizedObjects() &&
720235633Sdim           "Cannot use SP to access the emergency spill slot in "
721235633Sdim           "functions with variable sized frame objects");
722235633Sdim  }
723235633Sdim#endif // NDEBUG
724235633Sdim
725263509Sdim  assert(!MI.isDebugValue() && "DBG_VALUEs should be handled in target-independent code");
726207618Srdivacky
727198892Srdivacky  // Modify MI as necessary to handle as much of 'Offset' as possible
728198090Srdivacky  bool Done = false;
729198090Srdivacky  if (!AFI->isThumbFunction())
730252723Sdim    Done = rewriteARMFrameIndex(MI, FIOperandNum, FrameReg, Offset, TII);
731198090Srdivacky  else {
732198090Srdivacky    assert(AFI->isThumb2Function());
733252723Sdim    Done = rewriteT2FrameIndex(MI, FIOperandNum, FrameReg, Offset, TII);
734198090Srdivacky  }
735198090Srdivacky  if (Done)
736212904Sdim    return;
737198090Srdivacky
738198090Srdivacky  // If we get here, the immediate doesn't fit into the instruction.  We folded
739198090Srdivacky  // as much as possible above, handle the rest, providing a register that is
740198090Srdivacky  // SP+LargeImm.
741198090Srdivacky  assert((Offset ||
742199481Srdivacky          (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
743199481Srdivacky          (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
744198090Srdivacky         "This code isn't needed if offset already handled!");
745198090Srdivacky
746198396Srdivacky  unsigned ScratchReg = 0;
747198090Srdivacky  int PIdx = MI.findFirstPredOperandIdx();
748198090Srdivacky  ARMCC::CondCodes Pred = (PIdx == -1)
749198090Srdivacky    ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
750198090Srdivacky  unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
751198090Srdivacky  if (Offset == 0)
752199481Srdivacky    // Must be addrmode4/6.
753252723Sdim    MI.getOperand(FIOperandNum).ChangeToRegister(FrameReg, false, false, false);
754198090Srdivacky  else {
755245431Sdim    ScratchReg = MF.getRegInfo().createVirtualRegister(&ARM::GPRRegClass);
756198090Srdivacky    if (!AFI->isThumbFunction())
757198090Srdivacky      emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
758198090Srdivacky                              Offset, Pred, PredReg, TII);
759198090Srdivacky    else {
760198090Srdivacky      assert(AFI->isThumb2Function());
761198090Srdivacky      emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
762198090Srdivacky                             Offset, Pred, PredReg, TII);
763198090Srdivacky    }
764218893Sdim    // Update the original instruction to use the scratch register.
765252723Sdim    MI.getOperand(FIOperandNum).ChangeToRegister(ScratchReg, false, false,true);
766198090Srdivacky  }
767198090Srdivacky}
768