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