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