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