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