1 //===- ARMBaseRegisterInfo.cpp - ARM Register Information -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the base ARM implementation of TargetRegisterInfo class.
12 //===----------------------------------------------------------------------===//
15 #include "ARMAddressingModes.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMInstrInfo.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMSubtarget.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/LLVMContext.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineLocation.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/RegisterScavenging.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetFrameInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/BitVector.h"
39 #include "llvm/ADT/SmallVector.h"
40 #include "llvm/Support/CommandLine.h"
44 ForceAllBaseRegAlloc("arm-force-base-reg-alloc", cl::Hidden, cl::init(false),
45 cl::desc("Force use of virtual base registers for stack load/store"));
47 EnableLocalStackAlloc("enable-local-stack-alloc", cl::init(true), cl::Hidden,
48 cl::desc("Enable pre-regalloc stack frame index allocation"));
54 EnableBasePointer("arm-use-base-pointer", cl::Hidden, cl::init(true),
55 cl::desc("Enable use of a base pointer for complex stack frames"));
58 ARMBaseRegisterInfo::ARMBaseRegisterInfo(const ARMBaseInstrInfo &tii,
59 const ARMSubtarget &sti)
60 : ARMGenRegisterInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
62 FramePtr((STI.isTargetDarwin() || STI.isThumb()) ? ARM::R7 : ARM::R11),
67 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
68 static const unsigned CalleeSavedRegs[] = {
69 ARM::LR, ARM::R11, ARM::R10, ARM::R9, ARM::R8,
70 ARM::R7, ARM::R6, ARM::R5, ARM::R4,
72 ARM::D15, ARM::D14, ARM::D13, ARM::D12,
73 ARM::D11, ARM::D10, ARM::D9, ARM::D8,
77 static const unsigned DarwinCalleeSavedRegs[] = {
78 // Darwin ABI deviates from ARM standard ABI. R9 is not a callee-saved
80 ARM::LR, ARM::R11, ARM::R10, ARM::R8,
81 ARM::R7, ARM::R6, ARM::R5, ARM::R4,
83 ARM::D15, ARM::D14, ARM::D13, ARM::D12,
84 ARM::D11, ARM::D10, ARM::D9, ARM::D8,
87 return STI.isTargetDarwin() ? DarwinCalleeSavedRegs : CalleeSavedRegs;
90 BitVector ARMBaseRegisterInfo::
91 getReservedRegs(const MachineFunction &MF) const {
92 // FIXME: avoid re-calculating this everytime.
93 BitVector Reserved(getNumRegs());
94 Reserved.set(ARM::SP);
95 Reserved.set(ARM::PC);
96 Reserved.set(ARM::FPSCR);
98 Reserved.set(FramePtr);
99 if (hasBasePointer(MF))
100 Reserved.set(BasePtr);
101 // Some targets reserve R9.
102 if (STI.isR9Reserved())
103 Reserved.set(ARM::R9);
107 bool ARMBaseRegisterInfo::isReservedReg(const MachineFunction &MF,
108 unsigned Reg) const {
115 if (hasBasePointer(MF))
120 if (FramePtr == Reg && hasFP(MF))
124 return STI.isR9Reserved();
130 const TargetRegisterClass *
131 ARMBaseRegisterInfo::getMatchingSuperRegClass(const TargetRegisterClass *A,
132 const TargetRegisterClass *B,
133 unsigned SubIdx) const {
141 if (A->getSize() == 8) {
142 if (B == &ARM::SPR_8RegClass)
143 return &ARM::DPR_8RegClass;
144 assert(B == &ARM::SPRRegClass && "Expecting SPR register class!");
145 if (A == &ARM::DPR_8RegClass)
147 return &ARM::DPR_VFP2RegClass;
150 if (A->getSize() == 16) {
151 if (B == &ARM::SPR_8RegClass)
152 return &ARM::QPR_8RegClass;
153 return &ARM::QPR_VFP2RegClass;
156 if (A->getSize() == 32) {
157 if (B == &ARM::SPR_8RegClass)
158 return 0; // Do not allow coalescing!
159 return &ARM::QQPR_VFP2RegClass;
162 assert(A->getSize() == 64 && "Expecting a QQQQ register class!");
163 return 0; // Do not allow coalescing!
170 if (A->getSize() == 16) {
171 if (B == &ARM::DPR_VFP2RegClass)
172 return &ARM::QPR_VFP2RegClass;
173 if (B == &ARM::DPR_8RegClass)
174 return 0; // Do not allow coalescing!
178 if (A->getSize() == 32) {
179 if (B == &ARM::DPR_VFP2RegClass)
180 return &ARM::QQPR_VFP2RegClass;
181 if (B == &ARM::DPR_8RegClass)
182 return 0; // Do not allow coalescing!
186 assert(A->getSize() == 64 && "Expecting a QQQQ register class!");
187 if (B != &ARM::DPRRegClass)
188 return 0; // Do not allow coalescing!
195 // D sub-registers of QQQQ registers.
196 if (A->getSize() == 64 && B == &ARM::DPRRegClass)
198 return 0; // Do not allow coalescing!
204 if (A->getSize() == 32) {
205 if (B == &ARM::QPR_VFP2RegClass)
206 return &ARM::QQPR_VFP2RegClass;
207 if (B == &ARM::QPR_8RegClass)
208 return 0; // Do not allow coalescing!
212 assert(A->getSize() == 64 && "Expecting a QQQQ register class!");
213 if (B == &ARM::QPRRegClass)
215 return 0; // Do not allow coalescing!
219 // Q sub-registers of QQQQ registers.
220 if (A->getSize() == 64 && B == &ARM::QPRRegClass)
222 return 0; // Do not allow coalescing!
229 ARMBaseRegisterInfo::canCombineSubRegIndices(const TargetRegisterClass *RC,
230 SmallVectorImpl<unsigned> &SubIndices,
231 unsigned &NewSubIdx) const {
233 unsigned Size = RC->getSize() * 8;
237 NewSubIdx = 0; // Whole register.
238 unsigned NumRegs = SubIndices.size();
240 // 8 D registers -> 1 QQQQ register.
241 return (Size == 512 &&
242 SubIndices[0] == ARM::dsub_0 &&
243 SubIndices[1] == ARM::dsub_1 &&
244 SubIndices[2] == ARM::dsub_2 &&
245 SubIndices[3] == ARM::dsub_3 &&
246 SubIndices[4] == ARM::dsub_4 &&
247 SubIndices[5] == ARM::dsub_5 &&
248 SubIndices[6] == ARM::dsub_6 &&
249 SubIndices[7] == ARM::dsub_7);
250 } else if (NumRegs == 4) {
251 if (SubIndices[0] == ARM::qsub_0) {
252 // 4 Q registers -> 1 QQQQ register.
253 return (Size == 512 &&
254 SubIndices[1] == ARM::qsub_1 &&
255 SubIndices[2] == ARM::qsub_2 &&
256 SubIndices[3] == ARM::qsub_3);
257 } else if (SubIndices[0] == ARM::dsub_0) {
258 // 4 D registers -> 1 QQ register.
260 SubIndices[1] == ARM::dsub_1 &&
261 SubIndices[2] == ARM::dsub_2 &&
262 SubIndices[3] == ARM::dsub_3) {
264 NewSubIdx = ARM::qqsub_0;
267 } else if (SubIndices[0] == ARM::dsub_4) {
268 // 4 D registers -> 1 QQ register (2nd).
270 SubIndices[1] == ARM::dsub_5 &&
271 SubIndices[2] == ARM::dsub_6 &&
272 SubIndices[3] == ARM::dsub_7) {
273 NewSubIdx = ARM::qqsub_1;
276 } else if (SubIndices[0] == ARM::ssub_0) {
277 // 4 S registers -> 1 Q register.
279 SubIndices[1] == ARM::ssub_1 &&
280 SubIndices[2] == ARM::ssub_2 &&
281 SubIndices[3] == ARM::ssub_3) {
283 NewSubIdx = ARM::qsub_0;
287 } else if (NumRegs == 2) {
288 if (SubIndices[0] == ARM::qsub_0) {
289 // 2 Q registers -> 1 QQ register.
290 if (Size >= 256 && SubIndices[1] == ARM::qsub_1) {
292 NewSubIdx = ARM::qqsub_0;
295 } else if (SubIndices[0] == ARM::qsub_2) {
296 // 2 Q registers -> 1 QQ register (2nd).
297 if (Size == 512 && SubIndices[1] == ARM::qsub_3) {
298 NewSubIdx = ARM::qqsub_1;
301 } else if (SubIndices[0] == ARM::dsub_0) {
302 // 2 D registers -> 1 Q register.
303 if (Size >= 128 && SubIndices[1] == ARM::dsub_1) {
305 NewSubIdx = ARM::qsub_0;
308 } else if (SubIndices[0] == ARM::dsub_2) {
309 // 2 D registers -> 1 Q register (2nd).
310 if (Size >= 256 && SubIndices[1] == ARM::dsub_3) {
311 NewSubIdx = ARM::qsub_1;
314 } else if (SubIndices[0] == ARM::dsub_4) {
315 // 2 D registers -> 1 Q register (3rd).
316 if (Size == 512 && SubIndices[1] == ARM::dsub_5) {
317 NewSubIdx = ARM::qsub_2;
320 } else if (SubIndices[0] == ARM::dsub_6) {
321 // 2 D registers -> 1 Q register (3rd).
322 if (Size == 512 && SubIndices[1] == ARM::dsub_7) {
323 NewSubIdx = ARM::qsub_3;
326 } else if (SubIndices[0] == ARM::ssub_0) {
327 // 2 S registers -> 1 D register.
328 if (SubIndices[1] == ARM::ssub_1) {
330 NewSubIdx = ARM::dsub_0;
333 } else if (SubIndices[0] == ARM::ssub_2) {
334 // 2 S registers -> 1 D register (2nd).
335 if (Size >= 128 && SubIndices[1] == ARM::ssub_3) {
336 NewSubIdx = ARM::dsub_1;
345 const TargetRegisterClass *
346 ARMBaseRegisterInfo::getPointerRegClass(unsigned Kind) const {
347 return ARM::GPRRegisterClass;
350 /// getAllocationOrder - Returns the register allocation order for a specified
351 /// register class in the form of a pair of TargetRegisterClass iterators.
352 std::pair<TargetRegisterClass::iterator,TargetRegisterClass::iterator>
353 ARMBaseRegisterInfo::getAllocationOrder(const TargetRegisterClass *RC,
354 unsigned HintType, unsigned HintReg,
355 const MachineFunction &MF) const {
356 // Alternative register allocation orders when favoring even / odd registers
357 // of register pairs.
359 // No FP, R9 is available.
360 static const unsigned GPREven1[] = {
361 ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8, ARM::R10,
362 ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7,
365 static const unsigned GPROdd1[] = {
366 ARM::R1, ARM::R3, ARM::R5, ARM::R7, ARM::R9, ARM::R11,
367 ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
371 // FP is R7, R9 is available.
372 static const unsigned GPREven2[] = {
373 ARM::R0, ARM::R2, ARM::R4, ARM::R8, ARM::R10,
374 ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6,
377 static const unsigned GPROdd2[] = {
378 ARM::R1, ARM::R3, ARM::R5, ARM::R9, ARM::R11,
379 ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6,
383 // FP is R11, R9 is available.
384 static const unsigned GPREven3[] = {
385 ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R8,
386 ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7,
389 static const unsigned GPROdd3[] = {
390 ARM::R1, ARM::R3, ARM::R5, ARM::R6, ARM::R9,
391 ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R7,
395 // No FP, R9 is not available.
396 static const unsigned GPREven4[] = {
397 ARM::R0, ARM::R2, ARM::R4, ARM::R6, ARM::R10,
398 ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8,
401 static const unsigned GPROdd4[] = {
402 ARM::R1, ARM::R3, ARM::R5, ARM::R7, ARM::R11,
403 ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
407 // FP is R7, R9 is not available.
408 static const unsigned GPREven5[] = {
409 ARM::R0, ARM::R2, ARM::R4, ARM::R10,
410 ARM::R1, ARM::R3, ARM::R12,ARM::LR, ARM::R5, ARM::R6, ARM::R8,
413 static const unsigned GPROdd5[] = {
414 ARM::R1, ARM::R3, ARM::R5, ARM::R11,
415 ARM::R0, ARM::R2, ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8,
419 // FP is R11, R9 is not available.
420 static const unsigned GPREven6[] = {
421 ARM::R0, ARM::R2, ARM::R4, ARM::R6,
422 ARM::R1, ARM::R3, ARM::R10,ARM::R12,ARM::LR, ARM::R5, ARM::R7, ARM::R8
424 static const unsigned GPROdd6[] = {
425 ARM::R1, ARM::R3, ARM::R5, ARM::R7,
426 ARM::R0, ARM::R2, ARM::R10,ARM::R12,ARM::LR, ARM::R4, ARM::R6, ARM::R8
430 if (HintType == ARMRI::RegPairEven) {
431 if (isPhysicalRegister(HintReg) && getRegisterPairEven(HintReg, MF) == 0)
432 // It's no longer possible to fulfill this hint. Return the default
434 return std::make_pair(RC->allocation_order_begin(MF),
435 RC->allocation_order_end(MF));
438 if (!STI.isR9Reserved())
439 return std::make_pair(GPREven1,
440 GPREven1 + (sizeof(GPREven1)/sizeof(unsigned)));
442 return std::make_pair(GPREven4,
443 GPREven4 + (sizeof(GPREven4)/sizeof(unsigned)));
444 } else if (FramePtr == ARM::R7) {
445 if (!STI.isR9Reserved())
446 return std::make_pair(GPREven2,
447 GPREven2 + (sizeof(GPREven2)/sizeof(unsigned)));
449 return std::make_pair(GPREven5,
450 GPREven5 + (sizeof(GPREven5)/sizeof(unsigned)));
451 } else { // FramePtr == ARM::R11
452 if (!STI.isR9Reserved())
453 return std::make_pair(GPREven3,
454 GPREven3 + (sizeof(GPREven3)/sizeof(unsigned)));
456 return std::make_pair(GPREven6,
457 GPREven6 + (sizeof(GPREven6)/sizeof(unsigned)));
459 } else if (HintType == ARMRI::RegPairOdd) {
460 if (isPhysicalRegister(HintReg) && getRegisterPairOdd(HintReg, MF) == 0)
461 // It's no longer possible to fulfill this hint. Return the default
463 return std::make_pair(RC->allocation_order_begin(MF),
464 RC->allocation_order_end(MF));
467 if (!STI.isR9Reserved())
468 return std::make_pair(GPROdd1,
469 GPROdd1 + (sizeof(GPROdd1)/sizeof(unsigned)));
471 return std::make_pair(GPROdd4,
472 GPROdd4 + (sizeof(GPROdd4)/sizeof(unsigned)));
473 } else if (FramePtr == ARM::R7) {
474 if (!STI.isR9Reserved())
475 return std::make_pair(GPROdd2,
476 GPROdd2 + (sizeof(GPROdd2)/sizeof(unsigned)));
478 return std::make_pair(GPROdd5,
479 GPROdd5 + (sizeof(GPROdd5)/sizeof(unsigned)));
480 } else { // FramePtr == ARM::R11
481 if (!STI.isR9Reserved())
482 return std::make_pair(GPROdd3,
483 GPROdd3 + (sizeof(GPROdd3)/sizeof(unsigned)));
485 return std::make_pair(GPROdd6,
486 GPROdd6 + (sizeof(GPROdd6)/sizeof(unsigned)));
489 return std::make_pair(RC->allocation_order_begin(MF),
490 RC->allocation_order_end(MF));
493 /// ResolveRegAllocHint - Resolves the specified register allocation hint
494 /// to a physical register. Returns the physical register if it is successful.
496 ARMBaseRegisterInfo::ResolveRegAllocHint(unsigned Type, unsigned Reg,
497 const MachineFunction &MF) const {
498 if (Reg == 0 || !isPhysicalRegister(Reg))
502 else if (Type == (unsigned)ARMRI::RegPairOdd)
504 return getRegisterPairOdd(Reg, MF);
505 else if (Type == (unsigned)ARMRI::RegPairEven)
507 return getRegisterPairEven(Reg, MF);
512 ARMBaseRegisterInfo::UpdateRegAllocHint(unsigned Reg, unsigned NewReg,
513 MachineFunction &MF) const {
514 MachineRegisterInfo *MRI = &MF.getRegInfo();
515 std::pair<unsigned, unsigned> Hint = MRI->getRegAllocationHint(Reg);
516 if ((Hint.first == (unsigned)ARMRI::RegPairOdd ||
517 Hint.first == (unsigned)ARMRI::RegPairEven) &&
518 Hint.second && TargetRegisterInfo::isVirtualRegister(Hint.second)) {
519 // If 'Reg' is one of the even / odd register pair and it's now changed
520 // (e.g. coalesced) into a different register. The other register of the
521 // pair allocation hint must be updated to reflect the relationship
523 unsigned OtherReg = Hint.second;
524 Hint = MRI->getRegAllocationHint(OtherReg);
525 if (Hint.second == Reg)
526 // Make sure the pair has not already divorced.
527 MRI->setRegAllocationHint(OtherReg, Hint.first, NewReg);
531 /// hasFP - Return true if the specified function should have a dedicated frame
532 /// pointer register. This is true if the function has variable sized allocas
533 /// or if frame pointer elimination is disabled.
535 bool ARMBaseRegisterInfo::hasFP(const MachineFunction &MF) const {
536 // Mac OS X requires FP not to be clobbered for backtracing purpose.
537 if (STI.isTargetDarwin())
540 const MachineFrameInfo *MFI = MF.getFrameInfo();
541 // Always eliminate non-leaf frame pointers.
542 return ((DisableFramePointerElim(MF) && MFI->hasCalls()) ||
543 needsStackRealignment(MF) ||
544 MFI->hasVarSizedObjects() ||
545 MFI->isFrameAddressTaken());
548 bool ARMBaseRegisterInfo::hasBasePointer(const MachineFunction &MF) const {
549 const MachineFrameInfo *MFI = MF.getFrameInfo();
550 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
552 if (!EnableBasePointer)
555 if (needsStackRealignment(MF) && MFI->hasVarSizedObjects())
558 // Thumb has trouble with negative offsets from the FP. Thumb2 has a limited
559 // negative range for ldr/str (255), and thumb1 is positive offsets only.
560 // It's going to be better to use the SP or Base Pointer instead. When there
561 // are variable sized objects, we can't reference off of the SP, so we
562 // reserve a Base Pointer.
563 if (AFI->isThumbFunction() && MFI->hasVarSizedObjects()) {
564 // Conservatively estimate whether the negative offset from the frame
565 // pointer will be sufficient to reach. If a function has a smallish
566 // frame, it's less likely to have lots of spills and callee saved
567 // space, so it's all more likely to be within range of the frame pointer.
568 // If it's wrong, the scavenger will still enable access to work, it just
570 if (AFI->isThumb2Function() && MFI->getLocalFrameSize() < 128)
578 bool ARMBaseRegisterInfo::canRealignStack(const MachineFunction &MF) const {
579 const MachineFrameInfo *MFI = MF.getFrameInfo();
580 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
581 // We can't realign the stack if:
582 // 1. Dynamic stack realignment is explicitly disabled,
583 // 2. This is a Thumb1 function (it's not useful, so we don't bother), or
584 // 3. There are VLAs in the function and the base pointer is disabled.
585 return (RealignStack && !AFI->isThumb1OnlyFunction() &&
586 (!MFI->hasVarSizedObjects() || EnableBasePointer));
589 bool ARMBaseRegisterInfo::
590 needsStackRealignment(const MachineFunction &MF) const {
591 const MachineFrameInfo *MFI = MF.getFrameInfo();
592 const Function *F = MF.getFunction();
593 unsigned StackAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
594 bool requiresRealignment = ((MFI->getLocalFrameMaxAlign() > StackAlign) ||
595 F->hasFnAttr(Attribute::StackAlignment));
597 return requiresRealignment && canRealignStack(MF);
600 bool ARMBaseRegisterInfo::
601 cannotEliminateFrame(const MachineFunction &MF) const {
602 const MachineFrameInfo *MFI = MF.getFrameInfo();
603 if (DisableFramePointerElim(MF) && MFI->adjustsStack())
605 return MFI->hasVarSizedObjects() || MFI->isFrameAddressTaken()
606 || needsStackRealignment(MF);
609 /// estimateStackSize - Estimate and return the size of the frame.
610 static unsigned estimateStackSize(MachineFunction &MF) {
611 const MachineFrameInfo *FFI = MF.getFrameInfo();
613 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) {
614 int FixedOff = -FFI->getObjectOffset(i);
615 if (FixedOff > Offset) Offset = FixedOff;
617 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) {
618 if (FFI->isDeadObjectIndex(i))
620 Offset += FFI->getObjectSize(i);
621 unsigned Align = FFI->getObjectAlignment(i);
622 // Adjust to alignment boundary
623 Offset = (Offset+Align-1)/Align*Align;
625 return (unsigned)Offset;
628 /// estimateRSStackSizeLimit - Look at each instruction that references stack
629 /// frames and return the stack size limit beyond which some of these
630 /// instructions will require a scratch register during their expansion later.
632 ARMBaseRegisterInfo::estimateRSStackSizeLimit(MachineFunction &MF) const {
633 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
634 unsigned Limit = (1 << 12) - 1;
635 for (MachineFunction::iterator BB = MF.begin(),E = MF.end(); BB != E; ++BB) {
636 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
638 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
639 if (!I->getOperand(i).isFI()) continue;
641 // When using ADDri to get the address of a stack object, 255 is the
642 // largest offset guaranteed to fit in the immediate offset.
643 if (I->getOpcode() == ARM::ADDri) {
644 Limit = std::min(Limit, (1U << 8) - 1);
648 // Otherwise check the addressing mode.
649 switch (I->getDesc().TSFlags & ARMII::AddrModeMask) {
650 case ARMII::AddrMode3:
651 case ARMII::AddrModeT2_i8:
652 Limit = std::min(Limit, (1U << 8) - 1);
654 case ARMII::AddrMode5:
655 case ARMII::AddrModeT2_i8s4:
656 Limit = std::min(Limit, ((1U << 8) - 1) * 4);
658 case ARMII::AddrModeT2_i12:
659 // i12 supports only positive offset so these will be converted to
660 // i8 opcodes. See llvm::rewriteT2FrameIndex.
661 if (hasFP(MF) && AFI->hasStackFrame())
662 Limit = std::min(Limit, (1U << 8) - 1);
664 case ARMII::AddrMode4:
665 case ARMII::AddrMode6:
666 // Addressing modes 4 & 6 (load/store) instructions can't encode an
667 // immediate offset for stack references.
672 break; // At most one FI per instruction
680 static unsigned GetFunctionSizeInBytes(const MachineFunction &MF,
681 const ARMBaseInstrInfo &TII) {
683 for (MachineFunction::const_iterator MBBI = MF.begin(), E = MF.end();
685 const MachineBasicBlock &MBB = *MBBI;
686 for (MachineBasicBlock::const_iterator I = MBB.begin(),E = MBB.end();
688 FnSize += TII.GetInstSizeInBytes(I);
694 ARMBaseRegisterInfo::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
695 RegScavenger *RS) const {
696 // This tells PEI to spill the FP as if it is any other callee-save register
697 // to take advantage the eliminateFrameIndex machinery. This also ensures it
698 // is spilled in the order specified by getCalleeSavedRegs() to make it easier
699 // to combine multiple loads / stores.
700 bool CanEliminateFrame = true;
701 bool CS1Spilled = false;
702 bool LRSpilled = false;
703 unsigned NumGPRSpills = 0;
704 SmallVector<unsigned, 4> UnspilledCS1GPRs;
705 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
706 MachineFrameInfo *MFI = MF.getFrameInfo();
708 // Spill R4 if Thumb2 function requires stack realignment - it will be used as
710 // FIXME: It will be better just to find spare register here.
711 if (needsStackRealignment(MF) &&
712 AFI->isThumb2Function())
713 MF.getRegInfo().setPhysRegUsed(ARM::R4);
715 // Spill LR if Thumb1 function uses variable length argument lists.
716 if (AFI->isThumb1OnlyFunction() && AFI->getVarArgsRegSaveSize() > 0)
717 MF.getRegInfo().setPhysRegUsed(ARM::LR);
719 // Spill the BasePtr if it's used.
720 if (hasBasePointer(MF))
721 MF.getRegInfo().setPhysRegUsed(BasePtr);
723 // Don't spill FP if the frame can be eliminated. This is determined
724 // by scanning the callee-save registers to see if any is used.
725 const unsigned *CSRegs = getCalleeSavedRegs();
726 for (unsigned i = 0; CSRegs[i]; ++i) {
727 unsigned Reg = CSRegs[i];
728 bool Spilled = false;
729 if (MF.getRegInfo().isPhysRegUsed(Reg)) {
730 AFI->setCSRegisterIsSpilled(Reg);
732 CanEliminateFrame = false;
734 // Check alias registers too.
735 for (const unsigned *Aliases = getAliasSet(Reg); *Aliases; ++Aliases) {
736 if (MF.getRegInfo().isPhysRegUsed(*Aliases)) {
738 CanEliminateFrame = false;
743 if (!ARM::GPRRegisterClass->contains(Reg))
749 if (!STI.isTargetDarwin()) {
756 // Keep track if LR and any of R4, R5, R6, and R7 is spilled.
771 UnspilledCS1GPRs.push_back(Reg);
775 bool ForceLRSpill = false;
776 if (!LRSpilled && AFI->isThumb1OnlyFunction()) {
777 unsigned FnSize = GetFunctionSizeInBytes(MF, TII);
778 // Force LR to be spilled if the Thumb function size is > 2048. This enables
779 // use of BL to implement far jump. If it turns out that it's not needed
780 // then the branch fix up path will undo it.
781 if (FnSize >= (1 << 11)) {
782 CanEliminateFrame = false;
787 // If any of the stack slot references may be out of range of an immediate
788 // offset, make sure a register (or a spill slot) is available for the
789 // register scavenger. Note that if we're indexing off the frame pointer, the
790 // effective stack size is 4 bytes larger since the FP points to the stack
791 // slot of the previous FP. Also, if we have variable sized objects in the
792 // function, stack slot references will often be negative, and some of
793 // our instructions are positive-offset only, so conservatively consider
794 // that case to want a spill slot (or register) as well. Similarly, if
795 // the function adjusts the stack pointer during execution and the
796 // adjustments aren't already part of our stack size estimate, our offset
797 // calculations may be off, so be conservative.
798 // FIXME: We could add logic to be more precise about negative offsets
799 // and which instructions will need a scratch register for them. Is it
800 // worth the effort and added fragility?
803 (estimateStackSize(MF) + ((hasFP(MF) && AFI->hasStackFrame()) ? 4:0) >=
804 estimateRSStackSizeLimit(MF)))
805 || MFI->hasVarSizedObjects()
806 || (MFI->adjustsStack() && !canSimplifyCallFramePseudos(MF));
808 bool ExtraCSSpill = false;
809 if (BigStack || !CanEliminateFrame || cannotEliminateFrame(MF)) {
810 AFI->setHasStackFrame(true);
812 // If LR is not spilled, but at least one of R4, R5, R6, and R7 is spilled.
813 // Spill LR as well so we can fold BX_RET to the registers restore (LDM).
814 if (!LRSpilled && CS1Spilled) {
815 MF.getRegInfo().setPhysRegUsed(ARM::LR);
816 AFI->setCSRegisterIsSpilled(ARM::LR);
818 UnspilledCS1GPRs.erase(std::find(UnspilledCS1GPRs.begin(),
819 UnspilledCS1GPRs.end(), (unsigned)ARM::LR));
820 ForceLRSpill = false;
825 MF.getRegInfo().setPhysRegUsed(FramePtr);
829 // If stack and double are 8-byte aligned and we are spilling an odd number
830 // of GPRs, spill one extra callee save GPR so we won't have to pad between
831 // the integer and double callee save areas.
832 unsigned TargetAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
833 if (TargetAlign == 8 && (NumGPRSpills & 1)) {
834 if (CS1Spilled && !UnspilledCS1GPRs.empty()) {
835 for (unsigned i = 0, e = UnspilledCS1GPRs.size(); i != e; ++i) {
836 unsigned Reg = UnspilledCS1GPRs[i];
837 // Don't spill high register if the function is thumb1
838 if (!AFI->isThumb1OnlyFunction() ||
839 isARMLowRegister(Reg) || Reg == ARM::LR) {
840 MF.getRegInfo().setPhysRegUsed(Reg);
841 AFI->setCSRegisterIsSpilled(Reg);
842 if (!isReservedReg(MF, Reg))
850 // Estimate if we might need to scavenge a register at some point in order
851 // to materialize a stack offset. If so, either spill one additional
852 // callee-saved register or reserve a special spill slot to facilitate
853 // register scavenging. Thumb1 needs a spill slot for stack pointer
854 // adjustments also, even when the frame itself is small.
855 if (BigStack && !ExtraCSSpill) {
856 // If any non-reserved CS register isn't spilled, just spill one or two
857 // extra. That should take care of it!
858 unsigned NumExtras = TargetAlign / 4;
859 SmallVector<unsigned, 2> Extras;
860 while (NumExtras && !UnspilledCS1GPRs.empty()) {
861 unsigned Reg = UnspilledCS1GPRs.back();
862 UnspilledCS1GPRs.pop_back();
863 if (!isReservedReg(MF, Reg) &&
864 (!AFI->isThumb1OnlyFunction() || isARMLowRegister(Reg) ||
866 Extras.push_back(Reg);
870 if (Extras.size() && NumExtras == 0) {
871 for (unsigned i = 0, e = Extras.size(); i != e; ++i) {
872 MF.getRegInfo().setPhysRegUsed(Extras[i]);
873 AFI->setCSRegisterIsSpilled(Extras[i]);
875 } else if (!AFI->isThumb1OnlyFunction()) {
876 // note: Thumb1 functions spill to R12, not the stack. Reserve a slot
877 // closest to SP or frame pointer.
878 const TargetRegisterClass *RC = ARM::GPRRegisterClass;
879 RS->setScavengingFrameIndex(MFI->CreateStackObject(RC->getSize(),
887 MF.getRegInfo().setPhysRegUsed(ARM::LR);
888 AFI->setCSRegisterIsSpilled(ARM::LR);
889 AFI->setLRIsSpilledForFarJump(true);
893 unsigned ARMBaseRegisterInfo::getRARegister() const {
898 ARMBaseRegisterInfo::getFrameRegister(const MachineFunction &MF) const {
904 // Provide a base+offset reference to an FI slot for debug info. It's the
905 // same as what we use for resolving the code-gen references for now.
906 // FIXME: This can go wrong when references are SP-relative and simple call
907 // frames aren't used.
909 ARMBaseRegisterInfo::getFrameIndexReference(const MachineFunction &MF, int FI,
910 unsigned &FrameReg) const {
911 return ResolveFrameIndexReference(MF, FI, FrameReg, 0);
915 ARMBaseRegisterInfo::ResolveFrameIndexReference(const MachineFunction &MF,
919 const MachineFrameInfo *MFI = MF.getFrameInfo();
920 const ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
921 int Offset = MFI->getObjectOffset(FI) + MFI->getStackSize();
922 int FPOffset = Offset - AFI->getFramePtrSpillOffset();
923 bool isFixed = MFI->isFixedObjectIndex(FI);
927 if (AFI->isGPRCalleeSavedAreaFrame(FI))
928 return Offset - AFI->getGPRCalleeSavedAreaOffset();
929 else if (AFI->isDPRCalleeSavedAreaFrame(FI))
930 return Offset - AFI->getDPRCalleeSavedAreaOffset();
932 // When dynamically realigning the stack, use the frame pointer for
933 // parameters, and the stack/base pointer for locals.
934 if (needsStackRealignment(MF)) {
935 assert (hasFP(MF) && "dynamic stack realignment without a FP!");
937 FrameReg = getFrameRegister(MF);
939 } else if (MFI->hasVarSizedObjects()) {
940 assert(hasBasePointer(MF) &&
941 "VLAs and dynamic stack alignment, but missing base pointer!");
947 // If there is a frame pointer, use it when we can.
948 if (hasFP(MF) && AFI->hasStackFrame()) {
949 // Use frame pointer to reference fixed objects. Use it for locals if
950 // there are VLAs (and thus the SP isn't reliable as a base).
951 if (isFixed || (MFI->hasVarSizedObjects() && !hasBasePointer(MF))) {
952 FrameReg = getFrameRegister(MF);
954 } else if (MFI->hasVarSizedObjects()) {
955 assert(hasBasePointer(MF) && "missing base pointer!");
956 // Use the base register since we have it.
958 } else if (AFI->isThumb2Function()) {
959 // In Thumb2 mode, the negative offset is very limited. Try to avoid
960 // out of range references.
961 if (FPOffset >= -255 && FPOffset < 0) {
962 FrameReg = getFrameRegister(MF);
965 } else if (Offset > (FPOffset < 0 ? -FPOffset : FPOffset)) {
966 // Otherwise, use SP or FP, whichever is closer to the stack slot.
967 FrameReg = getFrameRegister(MF);
971 // Use the base pointer if we have one.
972 if (hasBasePointer(MF))
978 ARMBaseRegisterInfo::getFrameIndexOffset(const MachineFunction &MF,
981 return getFrameIndexReference(MF, FI, FrameReg);
984 unsigned ARMBaseRegisterInfo::getEHExceptionRegister() const {
985 llvm_unreachable("What is the exception register");
989 unsigned ARMBaseRegisterInfo::getEHHandlerRegister() const {
990 llvm_unreachable("What is the exception handler register");
994 int ARMBaseRegisterInfo::getDwarfRegNum(unsigned RegNum, bool isEH) const {
995 return ARMGenRegisterInfo::getDwarfRegNumFull(RegNum, 0);
998 unsigned ARMBaseRegisterInfo::getRegisterPairEven(unsigned Reg,
999 const MachineFunction &MF) const {
1002 // Return 0 if either register of the pair is a special register.
1011 return (isReservedReg(MF, ARM::R7) || isReservedReg(MF, ARM::R6))
1014 return isReservedReg(MF, ARM::R9) ? 0 :ARM::R8;
1016 return isReservedReg(MF, ARM::R11) ? 0 : ARM::R10;
1088 unsigned ARMBaseRegisterInfo::getRegisterPairOdd(unsigned Reg,
1089 const MachineFunction &MF) const {
1092 // Return 0 if either register of the pair is a special register.
1101 return (isReservedReg(MF, ARM::R7) || isReservedReg(MF, ARM::R6))
1104 return isReservedReg(MF, ARM::R9) ? 0 :ARM::R9;
1106 return isReservedReg(MF, ARM::R11) ? 0 : ARM::R11;
1178 /// emitLoadConstPool - Emits a load from constpool to materialize the
1179 /// specified immediate.
1180 void ARMBaseRegisterInfo::
1181 emitLoadConstPool(MachineBasicBlock &MBB,
1182 MachineBasicBlock::iterator &MBBI,
1184 unsigned DestReg, unsigned SubIdx, int Val,
1185 ARMCC::CondCodes Pred,
1186 unsigned PredReg) const {
1187 MachineFunction &MF = *MBB.getParent();
1188 MachineConstantPool *ConstantPool = MF.getConstantPool();
1190 ConstantInt::get(Type::getInt32Ty(MF.getFunction()->getContext()), Val);
1191 unsigned Idx = ConstantPool->getConstantPoolIndex(C, 4);
1193 BuildMI(MBB, MBBI, dl, TII.get(ARM::LDRcp))
1194 .addReg(DestReg, getDefRegState(true), SubIdx)
1195 .addConstantPoolIndex(Idx)
1196 .addReg(0).addImm(0).addImm(Pred).addReg(PredReg);
1199 bool ARMBaseRegisterInfo::
1200 requiresRegisterScavenging(const MachineFunction &MF) const {
1204 bool ARMBaseRegisterInfo::
1205 requiresFrameIndexScavenging(const MachineFunction &MF) const {
1209 bool ARMBaseRegisterInfo::
1210 requiresVirtualBaseRegisters(const MachineFunction &MF) const {
1211 return EnableLocalStackAlloc;
1214 // hasReservedCallFrame - Under normal circumstances, when a frame pointer is
1215 // not required, we reserve argument space for call sites in the function
1216 // immediately on entry to the current function. This eliminates the need for
1217 // add/sub sp brackets around call sites. Returns true if the call frame is
1218 // included as part of the stack frame.
1219 bool ARMBaseRegisterInfo::
1220 hasReservedCallFrame(const MachineFunction &MF) const {
1221 const MachineFrameInfo *FFI = MF.getFrameInfo();
1222 unsigned CFSize = FFI->getMaxCallFrameSize();
1223 // It's not always a good idea to include the call frame as part of the
1224 // stack frame. ARM (especially Thumb) has small immediate offset to
1225 // address the stack frame. So a large call frame can cause poor codegen
1226 // and may even makes it impossible to scavenge a register.
1227 if (CFSize >= ((1 << 12) - 1) / 2) // Half of imm12
1230 return !MF.getFrameInfo()->hasVarSizedObjects();
1233 // canSimplifyCallFramePseudos - If there is a reserved call frame, the
1234 // call frame pseudos can be simplified. Unlike most targets, having a FP
1235 // is not sufficient here since we still may reference some objects via SP
1236 // even when FP is available in Thumb2 mode.
1237 bool ARMBaseRegisterInfo::
1238 canSimplifyCallFramePseudos(const MachineFunction &MF) const {
1239 return hasReservedCallFrame(MF) || MF.getFrameInfo()->hasVarSizedObjects();
1243 emitSPUpdate(bool isARM,
1244 MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
1245 DebugLoc dl, const ARMBaseInstrInfo &TII,
1247 ARMCC::CondCodes Pred = ARMCC::AL, unsigned PredReg = 0) {
1249 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1250 Pred, PredReg, TII);
1252 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, ARM::SP, NumBytes,
1253 Pred, PredReg, TII);
1257 void ARMBaseRegisterInfo::
1258 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1259 MachineBasicBlock::iterator I) const {
1260 if (!hasReservedCallFrame(MF)) {
1261 // If we have alloca, convert as follows:
1262 // ADJCALLSTACKDOWN -> sub, sp, sp, amount
1263 // ADJCALLSTACKUP -> add, sp, sp, amount
1264 MachineInstr *Old = I;
1265 DebugLoc dl = Old->getDebugLoc();
1266 unsigned Amount = Old->getOperand(0).getImm();
1268 // We need to keep the stack aligned properly. To do this, we round the
1269 // amount of space needed for the outgoing arguments up to the next
1270 // alignment boundary.
1271 unsigned Align = MF.getTarget().getFrameInfo()->getStackAlignment();
1272 Amount = (Amount+Align-1)/Align*Align;
1274 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1275 assert(!AFI->isThumb1OnlyFunction() &&
1276 "This eliminateCallFramePseudoInstr does not support Thumb1!");
1277 bool isARM = !AFI->isThumbFunction();
1279 // Replace the pseudo instruction with a new instruction...
1280 unsigned Opc = Old->getOpcode();
1281 int PIdx = Old->findFirstPredOperandIdx();
1282 ARMCC::CondCodes Pred = (PIdx == -1)
1283 ? ARMCC::AL : (ARMCC::CondCodes)Old->getOperand(PIdx).getImm();
1284 if (Opc == ARM::ADJCALLSTACKDOWN || Opc == ARM::tADJCALLSTACKDOWN) {
1285 // Note: PredReg is operand 2 for ADJCALLSTACKDOWN.
1286 unsigned PredReg = Old->getOperand(2).getReg();
1287 emitSPUpdate(isARM, MBB, I, dl, TII, -Amount, Pred, PredReg);
1289 // Note: PredReg is operand 3 for ADJCALLSTACKUP.
1290 unsigned PredReg = Old->getOperand(3).getReg();
1291 assert(Opc == ARM::ADJCALLSTACKUP || Opc == ARM::tADJCALLSTACKUP);
1292 emitSPUpdate(isARM, MBB, I, dl, TII, Amount, Pred, PredReg);
1299 int64_t ARMBaseRegisterInfo::
1300 getFrameIndexInstrOffset(const MachineInstr *MI, int Idx) const {
1301 const TargetInstrDesc &Desc = MI->getDesc();
1302 unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1303 int64_t InstrOffs = 0;;
1305 unsigned ImmIdx = 0;
1307 case ARMII::AddrModeT2_i8:
1308 case ARMII::AddrModeT2_i12:
1309 // i8 supports only negative, and i12 supports only positive, so
1310 // based on Offset sign, consider the appropriate instruction
1311 InstrOffs = MI->getOperand(Idx+1).getImm();
1314 case ARMII::AddrMode5: {
1315 // VFP address mode.
1316 const MachineOperand &OffOp = MI->getOperand(Idx+1);
1317 InstrOffs = ARM_AM::getAM5Offset(OffOp.getImm());
1318 if (ARM_AM::getAM5Op(OffOp.getImm()) == ARM_AM::sub)
1319 InstrOffs = -InstrOffs;
1323 case ARMII::AddrMode2: {
1325 InstrOffs = ARM_AM::getAM2Offset(MI->getOperand(ImmIdx).getImm());
1326 if (ARM_AM::getAM2Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1327 InstrOffs = -InstrOffs;
1330 case ARMII::AddrMode3: {
1332 InstrOffs = ARM_AM::getAM3Offset(MI->getOperand(ImmIdx).getImm());
1333 if (ARM_AM::getAM3Op(MI->getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1334 InstrOffs = -InstrOffs;
1337 case ARMII::AddrModeT1_s: {
1339 InstrOffs = MI->getOperand(ImmIdx).getImm();
1344 llvm_unreachable("Unsupported addressing mode!");
1348 return InstrOffs * Scale;
1351 /// needsFrameBaseReg - Returns true if the instruction's frame index
1352 /// reference would be better served by a base register other than FP
1353 /// or SP. Used by LocalStackFrameAllocation to determine which frame index
1354 /// references it should create new base registers for.
1355 bool ARMBaseRegisterInfo::
1356 needsFrameBaseReg(MachineInstr *MI, int64_t Offset) const {
1357 for (unsigned i = 0; !MI->getOperand(i).isFI(); ++i) {
1358 assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
1361 // It's the load/store FI references that cause issues, as it can be difficult
1362 // to materialize the offset if it won't fit in the literal field. Estimate
1363 // based on the size of the local frame and some conservative assumptions
1364 // about the rest of the stack frame (note, this is pre-regalloc, so
1365 // we don't know everything for certain yet) whether this offset is likely
1366 // to be out of range of the immediate. Return true if so.
1368 // We only generate virtual base registers for loads and stores, so
1369 // return false for everything else.
1370 unsigned Opc = MI->getOpcode();
1372 case ARM::LDR: case ARM::LDRH: case ARM::LDRB:
1373 case ARM::STR: case ARM::STRH: case ARM::STRB:
1374 case ARM::t2LDRi12: case ARM::t2LDRi8:
1375 case ARM::t2STRi12: case ARM::t2STRi8:
1376 case ARM::VLDRS: case ARM::VLDRD:
1377 case ARM::VSTRS: case ARM::VSTRD:
1378 case ARM::tSTRspi: case ARM::tLDRspi:
1379 if (ForceAllBaseRegAlloc)
1386 // Without a virtual base register, if the function has variable sized
1387 // objects, all fixed-size local references will be via the frame pointer,
1388 // Approximate the offset and see if it's legal for the instruction.
1389 // Note that the incoming offset is based on the SP value at function entry,
1390 // so it'll be negative.
1391 MachineFunction &MF = *MI->getParent()->getParent();
1392 MachineFrameInfo *MFI = MF.getFrameInfo();
1393 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1395 // Estimate an offset from the frame pointer.
1396 // Conservatively assume all callee-saved registers get pushed. R4-R6
1397 // will be earlier than the FP, so we ignore those.
1399 int64_t FPOffset = Offset - 8;
1400 // ARM and Thumb2 functions also need to consider R8-R11 and D8-D15
1401 if (!AFI->isThumbFunction() || !AFI->isThumb1OnlyFunction())
1403 // Estimate an offset from the stack pointer.
1404 // The incoming offset is relating to the SP at the start of the function,
1405 // but when we access the local it'll be relative to the SP after local
1406 // allocation, so adjust our SP-relative offset by that allocation size.
1408 Offset += MFI->getLocalFrameSize();
1409 // Assume that we'll have at least some spill slots allocated.
1410 // FIXME: This is a total SWAG number. We should run some statistics
1411 // and pick a real one.
1412 Offset += 128; // 128 bytes of spill slots
1414 // If there is a frame pointer, try using it.
1415 // The FP is only available if there is no dynamic realignment. We
1416 // don't know for sure yet whether we'll need that, so we guess based
1417 // on whether there are any local variables that would trigger it.
1418 unsigned StackAlign = MF.getTarget().getFrameInfo()->getStackAlignment();
1420 !((MFI->getLocalFrameMaxAlign() > StackAlign) && canRealignStack(MF))) {
1421 if (isFrameOffsetLegal(MI, FPOffset))
1424 // If we can reference via the stack pointer, try that.
1425 // FIXME: This (and the code that resolves the references) can be improved
1426 // to only disallow SP relative references in the live range of
1427 // the VLA(s). In practice, it's unclear how much difference that
1428 // would make, but it may be worth doing.
1429 if (!MFI->hasVarSizedObjects() && isFrameOffsetLegal(MI, Offset))
1432 // The offset likely isn't legal, we want to allocate a virtual base register.
1436 /// materializeFrameBaseRegister - Insert defining instruction(s) for
1437 /// BaseReg to be a pointer to FrameIdx before insertion point I.
1438 void ARMBaseRegisterInfo::
1439 materializeFrameBaseRegister(MachineBasicBlock::iterator I, unsigned BaseReg,
1440 int FrameIdx, int64_t Offset) const {
1441 ARMFunctionInfo *AFI =
1442 I->getParent()->getParent()->getInfo<ARMFunctionInfo>();
1443 unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri :
1444 (AFI->isThumb1OnlyFunction() ? ARM::tADDrSPi : ARM::t2ADDri);
1446 MachineInstrBuilder MIB =
1447 BuildMI(*I->getParent(), I, I->getDebugLoc(), TII.get(ADDriOpc), BaseReg)
1448 .addFrameIndex(FrameIdx).addImm(Offset);
1449 if (!AFI->isThumb1OnlyFunction())
1450 AddDefaultCC(AddDefaultPred(MIB));
1454 ARMBaseRegisterInfo::resolveFrameIndex(MachineBasicBlock::iterator I,
1455 unsigned BaseReg, int64_t Offset) const {
1456 MachineInstr &MI = *I;
1457 MachineBasicBlock &MBB = *MI.getParent();
1458 MachineFunction &MF = *MBB.getParent();
1459 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1460 int Off = Offset; // ARM doesn't need the general 64-bit offsets
1463 assert(!AFI->isThumb1OnlyFunction() &&
1464 "This resolveFrameIndex does not support Thumb1!");
1466 while (!MI.getOperand(i).isFI()) {
1468 assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
1471 if (!AFI->isThumbFunction())
1472 Done = rewriteARMFrameIndex(MI, i, BaseReg, Off, TII);
1474 assert(AFI->isThumb2Function());
1475 Done = rewriteT2FrameIndex(MI, i, BaseReg, Off, TII);
1477 assert (Done && "Unable to resolve frame index!");
1480 bool ARMBaseRegisterInfo::isFrameOffsetLegal(const MachineInstr *MI,
1481 int64_t Offset) const {
1482 const TargetInstrDesc &Desc = MI->getDesc();
1483 unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1486 while (!MI->getOperand(i).isFI()) {
1488 assert(i < MI->getNumOperands() &&"Instr doesn't have FrameIndex operand!");
1491 // AddrMode4 and AddrMode6 cannot handle any offset.
1492 if (AddrMode == ARMII::AddrMode4 || AddrMode == ARMII::AddrMode6)
1495 unsigned NumBits = 0;
1497 bool isSigned = true;
1499 case ARMII::AddrModeT2_i8:
1500 case ARMII::AddrModeT2_i12:
1501 // i8 supports only negative, and i12 supports only positive, so
1502 // based on Offset sign, consider the appropriate instruction
1511 case ARMII::AddrMode5:
1512 // VFP address mode.
1516 case ARMII::AddrMode2:
1519 case ARMII::AddrMode3:
1522 case ARMII::AddrModeT1_s:
1528 llvm_unreachable("Unsupported addressing mode!");
1532 Offset += getFrameIndexInstrOffset(MI, i);
1533 // Make sure the offset is encodable for instructions that scale the
1535 if ((Offset & (Scale-1)) != 0)
1538 if (isSigned && Offset < 0)
1541 unsigned Mask = (1 << NumBits) - 1;
1542 if ((unsigned)Offset <= Mask * Scale)
1549 ARMBaseRegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II,
1550 int SPAdj, RegScavenger *RS) const {
1552 MachineInstr &MI = *II;
1553 MachineBasicBlock &MBB = *MI.getParent();
1554 MachineFunction &MF = *MBB.getParent();
1555 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1556 assert(!AFI->isThumb1OnlyFunction() &&
1557 "This eliminateFrameIndex does not support Thumb1!");
1559 while (!MI.getOperand(i).isFI()) {
1561 assert(i < MI.getNumOperands() && "Instr doesn't have FrameIndex operand!");
1564 int FrameIndex = MI.getOperand(i).getIndex();
1567 int Offset = ResolveFrameIndexReference(MF, FrameIndex, FrameReg, SPAdj);
1569 // Special handling of dbg_value instructions.
1570 if (MI.isDebugValue()) {
1571 MI.getOperand(i). ChangeToRegister(FrameReg, false /*isDef*/);
1572 MI.getOperand(i+1).ChangeToImmediate(Offset);
1576 // Modify MI as necessary to handle as much of 'Offset' as possible
1578 if (!AFI->isThumbFunction())
1579 Done = rewriteARMFrameIndex(MI, i, FrameReg, Offset, TII);
1581 assert(AFI->isThumb2Function());
1582 Done = rewriteT2FrameIndex(MI, i, FrameReg, Offset, TII);
1587 // If we get here, the immediate doesn't fit into the instruction. We folded
1588 // as much as possible above, handle the rest, providing a register that is
1591 (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode4 ||
1592 (MI.getDesc().TSFlags & ARMII::AddrModeMask) == ARMII::AddrMode6) &&
1593 "This code isn't needed if offset already handled!");
1595 unsigned ScratchReg = 0;
1596 int PIdx = MI.findFirstPredOperandIdx();
1597 ARMCC::CondCodes Pred = (PIdx == -1)
1598 ? ARMCC::AL : (ARMCC::CondCodes)MI.getOperand(PIdx).getImm();
1599 unsigned PredReg = (PIdx == -1) ? 0 : MI.getOperand(PIdx+1).getReg();
1601 // Must be addrmode4/6.
1602 MI.getOperand(i).ChangeToRegister(FrameReg, false, false, false);
1604 ScratchReg = MF.getRegInfo().createVirtualRegister(ARM::GPRRegisterClass);
1605 if (!AFI->isThumbFunction())
1606 emitARMRegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1607 Offset, Pred, PredReg, TII);
1609 assert(AFI->isThumb2Function());
1610 emitT2RegPlusImmediate(MBB, II, MI.getDebugLoc(), ScratchReg, FrameReg,
1611 Offset, Pred, PredReg, TII);
1613 MI.getOperand(i).ChangeToRegister(ScratchReg, false, false, true);
1617 /// Move iterator past the next bunch of callee save load / store ops for
1618 /// the particular spill area (1: integer area 1, 2: fp area, 0: don't care).
1619 static void movePastCSLoadStoreOps(MachineBasicBlock &MBB,
1620 MachineBasicBlock::iterator &MBBI,
1621 int Opc1, int Opc2, unsigned Area,
1622 const ARMSubtarget &STI) {
1623 while (MBBI != MBB.end() &&
1624 ((MBBI->getOpcode() == Opc1) || (MBBI->getOpcode() == Opc2)) &&
1625 MBBI->getOperand(1).isFI()) {
1628 unsigned Category = 0;
1629 switch (MBBI->getOperand(0).getReg()) {
1630 case ARM::R4: case ARM::R5: case ARM::R6: case ARM::R7:
1631 case ARM::R8: case ARM::R9: case ARM::R10: case ARM::R11:
1635 case ARM::D8: case ARM::D9: case ARM::D10: case ARM::D11:
1636 case ARM::D12: case ARM::D13: case ARM::D14: case ARM::D15:
1643 if (Done || Category != Area)
1651 void ARMBaseRegisterInfo::
1652 emitPrologue(MachineFunction &MF) const {
1653 MachineBasicBlock &MBB = MF.front();
1654 MachineBasicBlock::iterator MBBI = MBB.begin();
1655 MachineFrameInfo *MFI = MF.getFrameInfo();
1656 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1657 assert(!AFI->isThumb1OnlyFunction() &&
1658 "This emitPrologue does not support Thumb1!");
1659 bool isARM = !AFI->isThumbFunction();
1660 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1661 unsigned NumBytes = MFI->getStackSize();
1662 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
1663 DebugLoc dl = MBBI != MBB.end() ? MBBI->getDebugLoc() : DebugLoc();
1665 // Determine the sizes of each callee-save spill areas and record which frame
1666 // belongs to which callee-save spill areas.
1667 unsigned GPRCSSize = 0/*, GPRCS2Size = 0*/, DPRCSSize = 0;
1668 int FramePtrSpillFI = 0;
1670 // Allocate the vararg register save area. This is not counted in NumBytes.
1672 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -VARegSaveSize);
1674 if (!AFI->hasStackFrame()) {
1676 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
1680 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1681 unsigned Reg = CSI[i].getReg();
1682 int FI = CSI[i].getFrameIdx();
1693 if (Reg == FramePtr)
1694 FramePtrSpillFI = FI;
1695 AFI->addGPRCalleeSavedAreaFrame(FI);
1699 AFI->addDPRCalleeSavedAreaFrame(FI);
1704 // Build the new SUBri to adjust SP for integer callee-save spill area.
1705 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -GPRCSSize);
1706 movePastCSLoadStoreOps(MBB, MBBI, ARM::STR, ARM::t2STRi12, 1, STI);
1708 // Set FP to point to the stack slot that contains the previous FP.
1709 bool HasFP = hasFP(MF);
1711 unsigned ADDriOpc = !AFI->isThumbFunction() ? ARM::ADDri : ARM::t2ADDri;
1712 MachineInstrBuilder MIB =
1713 BuildMI(MBB, MBBI, dl, TII.get(ADDriOpc), FramePtr)
1714 .addFrameIndex(FramePtrSpillFI).addImm(0);
1715 AddDefaultCC(AddDefaultPred(MIB));
1718 // Build the new SUBri to adjust SP for FP callee-save spill area.
1719 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -DPRCSSize);
1721 // Determine starting offsets of spill areas.
1722 unsigned DPRCSOffset = NumBytes - (GPRCSSize + DPRCSSize);
1723 unsigned GPRCSOffset = DPRCSOffset + DPRCSSize;
1725 AFI->setFramePtrSpillOffset(MFI->getObjectOffset(FramePtrSpillFI) +
1727 AFI->setGPRCalleeSavedAreaOffset(GPRCSOffset);
1728 AFI->setDPRCalleeSavedAreaOffset(DPRCSOffset);
1730 movePastCSLoadStoreOps(MBB, MBBI, ARM::VSTRD, 0, 2, STI);
1731 NumBytes = DPRCSOffset;
1733 // Adjust SP after all the callee-save spills.
1734 emitSPUpdate(isARM, MBB, MBBI, dl, TII, -NumBytes);
1736 AFI->setShouldRestoreSPFromFP(true);
1739 if (STI.isTargetELF() && hasFP(MF)) {
1740 MFI->setOffsetAdjustment(MFI->getOffsetAdjustment() -
1741 AFI->getFramePtrSpillOffset());
1742 AFI->setShouldRestoreSPFromFP(true);
1745 AFI->setGPRCalleeSavedAreaSize(GPRCSSize);
1746 AFI->setDPRCalleeSavedAreaSize(DPRCSSize);
1748 // If we need dynamic stack realignment, do it here. Be paranoid and make
1749 // sure if we also have VLAs, we have a base pointer for frame access.
1750 if (needsStackRealignment(MF)) {
1751 unsigned MaxAlign = MFI->getMaxAlignment();
1752 assert (!AFI->isThumb1OnlyFunction());
1753 if (!AFI->isThumbFunction()) {
1754 // Emit bic sp, sp, MaxAlign
1755 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
1756 TII.get(ARM::BICri), ARM::SP)
1757 .addReg(ARM::SP, RegState::Kill)
1758 .addImm(MaxAlign-1)));
1760 // We cannot use sp as source/dest register here, thus we're emitting the
1761 // following sequence:
1763 // bic r4, r4, MaxAlign
1765 // FIXME: It will be better just to find spare register here.
1766 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2tgpr), ARM::R4)
1767 .addReg(ARM::SP, RegState::Kill);
1768 AddDefaultCC(AddDefaultPred(BuildMI(MBB, MBBI, dl,
1769 TII.get(ARM::t2BICri), ARM::R4)
1770 .addReg(ARM::R4, RegState::Kill)
1771 .addImm(MaxAlign-1)));
1772 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVtgpr2gpr), ARM::SP)
1773 .addReg(ARM::R4, RegState::Kill);
1776 AFI->setShouldRestoreSPFromFP(true);
1779 // If we need a base pointer, set it up here. It's whatever the value
1780 // of the stack pointer is at this point. Any variable size objects
1781 // will be allocated after this, so we can still use the base pointer
1782 // to reference locals.
1783 if (hasBasePointer(MF)) {
1785 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), BasePtr)
1787 .addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
1789 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), BasePtr)
1793 // If the frame has variable sized objects then the epilogue must restore
1795 if (!AFI->shouldRestoreSPFromFP() && MFI->hasVarSizedObjects())
1796 AFI->setShouldRestoreSPFromFP(true);
1799 static bool isCalleeSavedRegister(unsigned Reg, const unsigned *CSRegs) {
1800 for (unsigned i = 0; CSRegs[i]; ++i)
1801 if (Reg == CSRegs[i])
1806 static bool isCSRestore(MachineInstr *MI,
1807 const ARMBaseInstrInfo &TII,
1808 const unsigned *CSRegs) {
1809 return ((MI->getOpcode() == (int)ARM::VLDRD ||
1810 MI->getOpcode() == (int)ARM::LDR ||
1811 MI->getOpcode() == (int)ARM::t2LDRi12) &&
1812 MI->getOperand(1).isFI() &&
1813 isCalleeSavedRegister(MI->getOperand(0).getReg(), CSRegs));
1816 void ARMBaseRegisterInfo::
1817 emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const {
1818 MachineBasicBlock::iterator MBBI = prior(MBB.end());
1819 assert(MBBI->getDesc().isReturn() &&
1820 "Can only insert epilog into returning blocks");
1821 unsigned RetOpcode = MBBI->getOpcode();
1822 DebugLoc dl = MBBI->getDebugLoc();
1823 MachineFrameInfo *MFI = MF.getFrameInfo();
1824 ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1825 assert(!AFI->isThumb1OnlyFunction() &&
1826 "This emitEpilogue does not support Thumb1!");
1827 bool isARM = !AFI->isThumbFunction();
1829 unsigned VARegSaveSize = AFI->getVarArgsRegSaveSize();
1830 int NumBytes = (int)MFI->getStackSize();
1832 if (!AFI->hasStackFrame()) {
1834 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
1836 // Unwind MBBI to point to first LDR / VLDRD.
1837 const unsigned *CSRegs = getCalleeSavedRegs();
1838 if (MBBI != MBB.begin()) {
1841 while (MBBI != MBB.begin() && isCSRestore(MBBI, TII, CSRegs));
1842 if (!isCSRestore(MBBI, TII, CSRegs))
1846 // Move SP to start of FP callee save spill area.
1847 NumBytes -= (AFI->getGPRCalleeSavedAreaSize() +
1848 AFI->getDPRCalleeSavedAreaSize());
1850 // Reset SP based on frame pointer only if the stack frame extends beyond
1851 // frame pointer stack slot or target is ELF and the function has FP.
1852 if (AFI->shouldRestoreSPFromFP()) {
1853 NumBytes = AFI->getFramePtrSpillOffset() - NumBytes;
1856 emitARMRegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
1859 emitT2RegPlusImmediate(MBB, MBBI, dl, ARM::SP, FramePtr, -NumBytes,
1864 BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), ARM::SP)
1865 .addReg(FramePtr).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
1867 BuildMI(MBB, MBBI, dl, TII.get(ARM::tMOVgpr2gpr), ARM::SP)
1870 } else if (NumBytes)
1871 emitSPUpdate(isARM, MBB, MBBI, dl, TII, NumBytes);
1873 // Move SP to start of integer callee save spill area.
1874 movePastCSLoadStoreOps(MBB, MBBI, ARM::VLDRD, 0, 2, STI);
1875 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getDPRCalleeSavedAreaSize());
1877 // Move SP to SP upon entry to the function.
1878 movePastCSLoadStoreOps(MBB, MBBI, ARM::LDR, ARM::t2LDRi12, 1, STI);
1879 emitSPUpdate(isARM, MBB, MBBI, dl, TII, AFI->getGPRCalleeSavedAreaSize());
1882 if (RetOpcode == ARM::TCRETURNdi || RetOpcode == ARM::TCRETURNdiND ||
1883 RetOpcode == ARM::TCRETURNri || RetOpcode == ARM::TCRETURNriND) {
1884 // Tail call return: adjust the stack pointer and jump to callee.
1885 MBBI = prior(MBB.end());
1886 MachineOperand &JumpTarget = MBBI->getOperand(0);
1888 // Jump to label or value in register.
1889 if (RetOpcode == ARM::TCRETURNdi) {
1890 BuildMI(MBB, MBBI, dl,
1891 TII.get(STI.isThumb() ? ARM::TAILJMPdt : ARM::TAILJMPd)).
1892 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1893 JumpTarget.getTargetFlags());
1894 } else if (RetOpcode == ARM::TCRETURNdiND) {
1895 BuildMI(MBB, MBBI, dl,
1896 TII.get(STI.isThumb() ? ARM::TAILJMPdNDt : ARM::TAILJMPdND)).
1897 addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1898 JumpTarget.getTargetFlags());
1899 } else if (RetOpcode == ARM::TCRETURNri) {
1900 BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPr)).
1901 addReg(JumpTarget.getReg(), RegState::Kill);
1902 } else if (RetOpcode == ARM::TCRETURNriND) {
1903 BuildMI(MBB, MBBI, dl, TII.get(ARM::TAILJMPrND)).
1904 addReg(JumpTarget.getReg(), RegState::Kill);
1907 MachineInstr *NewMI = prior(MBBI);
1908 for (unsigned i = 1, e = MBBI->getNumOperands(); i != e; ++i)
1909 NewMI->addOperand(MBBI->getOperand(i));
1911 // Delete the pseudo instruction TCRETURN.
1916 emitSPUpdate(isARM, MBB, MBBI, dl, TII, VARegSaveSize);
1919 #include "ARMGenRegisterInfo.inc"