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