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