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