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