Materialize GA addresses with movw + movt pairs for Darwin in PIC mode. e.g.
[oota-llvm.git] / lib / Target / ARM / ARMBaseInstrInfo.cpp
1 //===- ARMBaseInstrInfo.cpp - ARM Instruction Information -------*- C++ -*-===//
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 the TargetInstrInfo class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMBaseInstrInfo.h"
15 #include "ARM.h"
16 #include "ARMAddressingModes.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMHazardRecognizer.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMRegisterInfo.h"
21 #include "ARMGenInstrInfo.inc"
22 #include "llvm/Constants.h"
23 #include "llvm/Function.h"
24 #include "llvm/GlobalValue.h"
25 #include "llvm/CodeGen/LiveVariables.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/PseudoSourceValue.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/ADT/STLExtras.h"
38 using namespace llvm;
39
40 static cl::opt<bool>
41 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
42                cl::desc("Enable ARM 2-addr to 3-addr conv"));
43
44 // Other targets already have a hazard recognizer enabled by default, so this
45 // flag currently only affects ARM. It will be generalized when it becomes a
46 // disabled flag.
47 static cl::opt<bool> EnableHazardRecognizer(
48   "enable-sched-hazard", cl::Hidden,
49   cl::desc("Enable hazard detection during preRA scheduling"),
50   cl::init(false));
51
52 /// ARM_MLxEntry - Record information about MLA / MLS instructions.
53 struct ARM_MLxEntry {
54   unsigned MLxOpc;     // MLA / MLS opcode
55   unsigned MulOpc;     // Expanded multiplication opcode
56   unsigned AddSubOpc;  // Expanded add / sub opcode
57   bool NegAcc;         // True if the acc is negated before the add / sub.
58   bool HasLane;        // True if instruction has an extra "lane" operand.
59 };
60
61 static const ARM_MLxEntry ARM_MLxTable[] = {
62   // MLxOpc,          MulOpc,           AddSubOpc,       NegAcc, HasLane
63   // fp scalar ops
64   { ARM::VMLAS,       ARM::VMULS,       ARM::VADDS,      false,  false },
65   { ARM::VMLSS,       ARM::VMULS,       ARM::VSUBS,      false,  false },
66   { ARM::VMLAD,       ARM::VMULD,       ARM::VADDD,      false,  false },
67   { ARM::VMLSD,       ARM::VMULD,       ARM::VSUBD,      false,  false },
68   { ARM::VNMLAS,      ARM::VNMULS,      ARM::VSUBS,      true,   false },
69   { ARM::VNMLSS,      ARM::VMULS,       ARM::VSUBS,      true,   false },
70   { ARM::VNMLAD,      ARM::VNMULD,      ARM::VSUBD,      true,   false },
71   { ARM::VNMLSD,      ARM::VMULD,       ARM::VSUBD,      true,   false },
72
73   // fp SIMD ops
74   { ARM::VMLAfd,      ARM::VMULfd,      ARM::VADDfd,     false,  false },
75   { ARM::VMLSfd,      ARM::VMULfd,      ARM::VSUBfd,     false,  false },
76   { ARM::VMLAfq,      ARM::VMULfq,      ARM::VADDfq,     false,  false },
77   { ARM::VMLSfq,      ARM::VMULfq,      ARM::VSUBfq,     false,  false },
78   { ARM::VMLAslfd,    ARM::VMULslfd,    ARM::VADDfd,     false,  true  },
79   { ARM::VMLSslfd,    ARM::VMULslfd,    ARM::VSUBfd,     false,  true  },
80   { ARM::VMLAslfq,    ARM::VMULslfq,    ARM::VADDfq,     false,  true  },
81   { ARM::VMLSslfq,    ARM::VMULslfq,    ARM::VSUBfq,     false,  true  },
82 };
83
84 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
85   : TargetInstrInfoImpl(ARMInsts, array_lengthof(ARMInsts)),
86     Subtarget(STI) {
87   for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) {
88     if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
89       assert(false && "Duplicated entries?");
90     MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
91     MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
92   }
93 }
94
95 // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl
96 // currently defaults to no prepass hazard recognizer.
97 ScheduleHazardRecognizer *ARMBaseInstrInfo::
98 CreateTargetHazardRecognizer(const TargetMachine *TM,
99                              const ScheduleDAG *DAG) const {
100   if (EnableHazardRecognizer) {
101     const InstrItineraryData *II = TM->getInstrItineraryData();
102     return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched");
103   }
104   return TargetInstrInfoImpl::CreateTargetHazardRecognizer(TM, DAG);
105 }
106
107 ScheduleHazardRecognizer *ARMBaseInstrInfo::
108 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
109                                    const ScheduleDAG *DAG) const {
110   if (Subtarget.isThumb2() || Subtarget.hasVFP2())
111     return (ScheduleHazardRecognizer *)
112       new ARMHazardRecognizer(II, *this, getRegisterInfo(), Subtarget, DAG);
113   return TargetInstrInfoImpl::CreateTargetPostRAHazardRecognizer(II, DAG);
114 }
115
116 MachineInstr *
117 ARMBaseInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
118                                         MachineBasicBlock::iterator &MBBI,
119                                         LiveVariables *LV) const {
120   // FIXME: Thumb2 support.
121
122   if (!EnableARM3Addr)
123     return NULL;
124
125   MachineInstr *MI = MBBI;
126   MachineFunction &MF = *MI->getParent()->getParent();
127   uint64_t TSFlags = MI->getDesc().TSFlags;
128   bool isPre = false;
129   switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
130   default: return NULL;
131   case ARMII::IndexModePre:
132     isPre = true;
133     break;
134   case ARMII::IndexModePost:
135     break;
136   }
137
138   // Try splitting an indexed load/store to an un-indexed one plus an add/sub
139   // operation.
140   unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
141   if (MemOpc == 0)
142     return NULL;
143
144   MachineInstr *UpdateMI = NULL;
145   MachineInstr *MemMI = NULL;
146   unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
147   const TargetInstrDesc &TID = MI->getDesc();
148   unsigned NumOps = TID.getNumOperands();
149   bool isLoad = !TID.mayStore();
150   const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
151   const MachineOperand &Base = MI->getOperand(2);
152   const MachineOperand &Offset = MI->getOperand(NumOps-3);
153   unsigned WBReg = WB.getReg();
154   unsigned BaseReg = Base.getReg();
155   unsigned OffReg = Offset.getReg();
156   unsigned OffImm = MI->getOperand(NumOps-2).getImm();
157   ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
158   switch (AddrMode) {
159   default:
160     assert(false && "Unknown indexed op!");
161     return NULL;
162   case ARMII::AddrMode2: {
163     bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
164     unsigned Amt = ARM_AM::getAM2Offset(OffImm);
165     if (OffReg == 0) {
166       if (ARM_AM::getSOImmVal(Amt) == -1)
167         // Can't encode it in a so_imm operand. This transformation will
168         // add more than 1 instruction. Abandon!
169         return NULL;
170       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
171                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
172         .addReg(BaseReg).addImm(Amt)
173         .addImm(Pred).addReg(0).addReg(0);
174     } else if (Amt != 0) {
175       ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
176       unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
177       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
178                          get(isSub ? ARM::SUBrs : ARM::ADDrs), WBReg)
179         .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc)
180         .addImm(Pred).addReg(0).addReg(0);
181     } else
182       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
183                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
184         .addReg(BaseReg).addReg(OffReg)
185         .addImm(Pred).addReg(0).addReg(0);
186     break;
187   }
188   case ARMII::AddrMode3 : {
189     bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
190     unsigned Amt = ARM_AM::getAM3Offset(OffImm);
191     if (OffReg == 0)
192       // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
193       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
194                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
195         .addReg(BaseReg).addImm(Amt)
196         .addImm(Pred).addReg(0).addReg(0);
197     else
198       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
199                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
200         .addReg(BaseReg).addReg(OffReg)
201         .addImm(Pred).addReg(0).addReg(0);
202     break;
203   }
204   }
205
206   std::vector<MachineInstr*> NewMIs;
207   if (isPre) {
208     if (isLoad)
209       MemMI = BuildMI(MF, MI->getDebugLoc(),
210                       get(MemOpc), MI->getOperand(0).getReg())
211         .addReg(WBReg).addImm(0).addImm(Pred);
212     else
213       MemMI = BuildMI(MF, MI->getDebugLoc(),
214                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
215         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
216     NewMIs.push_back(MemMI);
217     NewMIs.push_back(UpdateMI);
218   } else {
219     if (isLoad)
220       MemMI = BuildMI(MF, MI->getDebugLoc(),
221                       get(MemOpc), MI->getOperand(0).getReg())
222         .addReg(BaseReg).addImm(0).addImm(Pred);
223     else
224       MemMI = BuildMI(MF, MI->getDebugLoc(),
225                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
226         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
227     if (WB.isDead())
228       UpdateMI->getOperand(0).setIsDead();
229     NewMIs.push_back(UpdateMI);
230     NewMIs.push_back(MemMI);
231   }
232
233   // Transfer LiveVariables states, kill / dead info.
234   if (LV) {
235     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
236       MachineOperand &MO = MI->getOperand(i);
237       if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
238         unsigned Reg = MO.getReg();
239
240         LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
241         if (MO.isDef()) {
242           MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
243           if (MO.isDead())
244             LV->addVirtualRegisterDead(Reg, NewMI);
245         }
246         if (MO.isUse() && MO.isKill()) {
247           for (unsigned j = 0; j < 2; ++j) {
248             // Look at the two new MI's in reverse order.
249             MachineInstr *NewMI = NewMIs[j];
250             if (!NewMI->readsRegister(Reg))
251               continue;
252             LV->addVirtualRegisterKilled(Reg, NewMI);
253             if (VI.removeKill(MI))
254               VI.Kills.push_back(NewMI);
255             break;
256           }
257         }
258       }
259     }
260   }
261
262   MFI->insert(MBBI, NewMIs[1]);
263   MFI->insert(MBBI, NewMIs[0]);
264   return NewMIs[0];
265 }
266
267 // Branch analysis.
268 bool
269 ARMBaseInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
270                                 MachineBasicBlock *&FBB,
271                                 SmallVectorImpl<MachineOperand> &Cond,
272                                 bool AllowModify) const {
273   // If the block has no terminators, it just falls into the block after it.
274   MachineBasicBlock::iterator I = MBB.end();
275   if (I == MBB.begin())
276     return false;
277   --I;
278   while (I->isDebugValue()) {
279     if (I == MBB.begin())
280       return false;
281     --I;
282   }
283   if (!isUnpredicatedTerminator(I))
284     return false;
285
286   // Get the last instruction in the block.
287   MachineInstr *LastInst = I;
288
289   // If there is only one terminator instruction, process it.
290   unsigned LastOpc = LastInst->getOpcode();
291   if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
292     if (isUncondBranchOpcode(LastOpc)) {
293       TBB = LastInst->getOperand(0).getMBB();
294       return false;
295     }
296     if (isCondBranchOpcode(LastOpc)) {
297       // Block ends with fall-through condbranch.
298       TBB = LastInst->getOperand(0).getMBB();
299       Cond.push_back(LastInst->getOperand(1));
300       Cond.push_back(LastInst->getOperand(2));
301       return false;
302     }
303     return true;  // Can't handle indirect branch.
304   }
305
306   // Get the instruction before it if it is a terminator.
307   MachineInstr *SecondLastInst = I;
308   unsigned SecondLastOpc = SecondLastInst->getOpcode();
309
310   // If AllowModify is true and the block ends with two or more unconditional
311   // branches, delete all but the first unconditional branch.
312   if (AllowModify && isUncondBranchOpcode(LastOpc)) {
313     while (isUncondBranchOpcode(SecondLastOpc)) {
314       LastInst->eraseFromParent();
315       LastInst = SecondLastInst;
316       LastOpc = LastInst->getOpcode();
317       if (I == MBB.begin() || !isUnpredicatedTerminator(--I)) {
318         // Return now the only terminator is an unconditional branch.
319         TBB = LastInst->getOperand(0).getMBB();
320         return false;
321       } else {
322         SecondLastInst = I;
323         SecondLastOpc = SecondLastInst->getOpcode();
324       }
325     }
326   }
327
328   // If there are three terminators, we don't know what sort of block this is.
329   if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(--I))
330     return true;
331
332   // If the block ends with a B and a Bcc, handle it.
333   if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
334     TBB =  SecondLastInst->getOperand(0).getMBB();
335     Cond.push_back(SecondLastInst->getOperand(1));
336     Cond.push_back(SecondLastInst->getOperand(2));
337     FBB = LastInst->getOperand(0).getMBB();
338     return false;
339   }
340
341   // If the block ends with two unconditional branches, handle it.  The second
342   // one is not executed, so remove it.
343   if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
344     TBB = SecondLastInst->getOperand(0).getMBB();
345     I = LastInst;
346     if (AllowModify)
347       I->eraseFromParent();
348     return false;
349   }
350
351   // ...likewise if it ends with a branch table followed by an unconditional
352   // branch. The branch folder can create these, and we must get rid of them for
353   // correctness of Thumb constant islands.
354   if ((isJumpTableBranchOpcode(SecondLastOpc) ||
355        isIndirectBranchOpcode(SecondLastOpc)) &&
356       isUncondBranchOpcode(LastOpc)) {
357     I = LastInst;
358     if (AllowModify)
359       I->eraseFromParent();
360     return true;
361   }
362
363   // Otherwise, can't handle this.
364   return true;
365 }
366
367
368 unsigned ARMBaseInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
369   MachineBasicBlock::iterator I = MBB.end();
370   if (I == MBB.begin()) return 0;
371   --I;
372   while (I->isDebugValue()) {
373     if (I == MBB.begin())
374       return 0;
375     --I;
376   }
377   if (!isUncondBranchOpcode(I->getOpcode()) &&
378       !isCondBranchOpcode(I->getOpcode()))
379     return 0;
380
381   // Remove the branch.
382   I->eraseFromParent();
383
384   I = MBB.end();
385
386   if (I == MBB.begin()) return 1;
387   --I;
388   if (!isCondBranchOpcode(I->getOpcode()))
389     return 1;
390
391   // Remove the branch.
392   I->eraseFromParent();
393   return 2;
394 }
395
396 unsigned
397 ARMBaseInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
398                                MachineBasicBlock *FBB,
399                                const SmallVectorImpl<MachineOperand> &Cond,
400                                DebugLoc DL) const {
401   ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
402   int BOpc   = !AFI->isThumbFunction()
403     ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
404   int BccOpc = !AFI->isThumbFunction()
405     ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
406
407   // Shouldn't be a fall through.
408   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
409   assert((Cond.size() == 2 || Cond.size() == 0) &&
410          "ARM branch conditions have two components!");
411
412   if (FBB == 0) {
413     if (Cond.empty()) // Unconditional branch?
414       BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
415     else
416       BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
417         .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
418     return 1;
419   }
420
421   // Two-way conditional branch.
422   BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
423     .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
424   BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
425   return 2;
426 }
427
428 bool ARMBaseInstrInfo::
429 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
430   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
431   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
432   return false;
433 }
434
435 bool ARMBaseInstrInfo::
436 PredicateInstruction(MachineInstr *MI,
437                      const SmallVectorImpl<MachineOperand> &Pred) const {
438   unsigned Opc = MI->getOpcode();
439   if (isUncondBranchOpcode(Opc)) {
440     MI->setDesc(get(getMatchingCondBranchOpcode(Opc)));
441     MI->addOperand(MachineOperand::CreateImm(Pred[0].getImm()));
442     MI->addOperand(MachineOperand::CreateReg(Pred[1].getReg(), false));
443     return true;
444   }
445
446   int PIdx = MI->findFirstPredOperandIdx();
447   if (PIdx != -1) {
448     MachineOperand &PMO = MI->getOperand(PIdx);
449     PMO.setImm(Pred[0].getImm());
450     MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
451     return true;
452   }
453   return false;
454 }
455
456 bool ARMBaseInstrInfo::
457 SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
458                   const SmallVectorImpl<MachineOperand> &Pred2) const {
459   if (Pred1.size() > 2 || Pred2.size() > 2)
460     return false;
461
462   ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
463   ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
464   if (CC1 == CC2)
465     return true;
466
467   switch (CC1) {
468   default:
469     return false;
470   case ARMCC::AL:
471     return true;
472   case ARMCC::HS:
473     return CC2 == ARMCC::HI;
474   case ARMCC::LS:
475     return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
476   case ARMCC::GE:
477     return CC2 == ARMCC::GT;
478   case ARMCC::LE:
479     return CC2 == ARMCC::LT;
480   }
481 }
482
483 bool ARMBaseInstrInfo::DefinesPredicate(MachineInstr *MI,
484                                     std::vector<MachineOperand> &Pred) const {
485   // FIXME: This confuses implicit_def with optional CPSR def.
486   const TargetInstrDesc &TID = MI->getDesc();
487   if (!TID.getImplicitDefs() && !TID.hasOptionalDef())
488     return false;
489
490   bool Found = false;
491   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
492     const MachineOperand &MO = MI->getOperand(i);
493     if (MO.isReg() && MO.getReg() == ARM::CPSR) {
494       Pred.push_back(MO);
495       Found = true;
496     }
497   }
498
499   return Found;
500 }
501
502 /// isPredicable - Return true if the specified instruction can be predicated.
503 /// By default, this returns true for every instruction with a
504 /// PredicateOperand.
505 bool ARMBaseInstrInfo::isPredicable(MachineInstr *MI) const {
506   const TargetInstrDesc &TID = MI->getDesc();
507   if (!TID.isPredicable())
508     return false;
509
510   if ((TID.TSFlags & ARMII::DomainMask) == ARMII::DomainNEON) {
511     ARMFunctionInfo *AFI =
512       MI->getParent()->getParent()->getInfo<ARMFunctionInfo>();
513     return AFI->isThumb2Function();
514   }
515   return true;
516 }
517
518 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing.
519 LLVM_ATTRIBUTE_NOINLINE
520 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
521                                 unsigned JTI);
522 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
523                                 unsigned JTI) {
524   assert(JTI < JT.size());
525   return JT[JTI].MBBs.size();
526 }
527
528 /// GetInstSize - Return the size of the specified MachineInstr.
529 ///
530 unsigned ARMBaseInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
531   const MachineBasicBlock &MBB = *MI->getParent();
532   const MachineFunction *MF = MBB.getParent();
533   const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
534
535   // Basic size info comes from the TSFlags field.
536   const TargetInstrDesc &TID = MI->getDesc();
537   uint64_t TSFlags = TID.TSFlags;
538
539   unsigned Opc = MI->getOpcode();
540   switch ((TSFlags & ARMII::SizeMask) >> ARMII::SizeShift) {
541   default: {
542     // If this machine instr is an inline asm, measure it.
543     if (MI->getOpcode() == ARM::INLINEASM)
544       return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
545     if (MI->isLabel())
546       return 0;
547     switch (Opc) {
548     default:
549       llvm_unreachable("Unknown or unset size field for instr!");
550     case TargetOpcode::IMPLICIT_DEF:
551     case TargetOpcode::KILL:
552     case TargetOpcode::PROLOG_LABEL:
553     case TargetOpcode::EH_LABEL:
554     case TargetOpcode::DBG_VALUE:
555       return 0;
556     }
557     break;
558   }
559   case ARMII::Size8Bytes: return 8;          // ARM instruction x 2.
560   case ARMII::Size4Bytes: return 4;          // ARM / Thumb2 instruction.
561   case ARMII::Size2Bytes: return 2;          // Thumb1 instruction.
562   case ARMII::SizeSpecial: {
563     switch (Opc) {
564     case ARM::MOVi16_pic_ga:
565     case ARM::MOVTi16_pic_ga:
566     case ARM::t2MOVi16_pic_ga:
567     case ARM::t2MOVTi16_pic_ga:
568       return 4;
569     case ARM::MOVi32imm:
570     case ARM::t2MOVi32imm:
571     case ARM::MOV_pic_ga:
572       return 8;
573     case ARM::CONSTPOOL_ENTRY:
574       // If this machine instr is a constant pool entry, its size is recorded as
575       // operand #2.
576       return MI->getOperand(2).getImm();
577     case ARM::Int_eh_sjlj_longjmp:
578       return 16;
579     case ARM::tInt_eh_sjlj_longjmp:
580       return 10;
581     case ARM::Int_eh_sjlj_setjmp:
582     case ARM::Int_eh_sjlj_setjmp_nofp:
583       return 20;
584     case ARM::tInt_eh_sjlj_setjmp:
585     case ARM::t2Int_eh_sjlj_setjmp:
586     case ARM::t2Int_eh_sjlj_setjmp_nofp:
587       return 12;
588     case ARM::BR_JTr:
589     case ARM::BR_JTm:
590     case ARM::BR_JTadd:
591     case ARM::tBR_JTr:
592     case ARM::t2BR_JT:
593     case ARM::t2TBB_JT:
594     case ARM::t2TBH_JT: {
595       // These are jumptable branches, i.e. a branch followed by an inlined
596       // jumptable. The size is 4 + 4 * number of entries. For TBB, each
597       // entry is one byte; TBH two byte each.
598       unsigned EntrySize = (Opc == ARM::t2TBB_JT)
599         ? 1 : ((Opc == ARM::t2TBH_JT) ? 2 : 4);
600       unsigned NumOps = TID.getNumOperands();
601       MachineOperand JTOP =
602         MI->getOperand(NumOps - (TID.isPredicable() ? 3 : 2));
603       unsigned JTI = JTOP.getIndex();
604       const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
605       assert(MJTI != 0);
606       const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
607       assert(JTI < JT.size());
608       // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
609       // 4 aligned. The assembler / linker may add 2 byte padding just before
610       // the JT entries.  The size does not include this padding; the
611       // constant islands pass does separate bookkeeping for it.
612       // FIXME: If we know the size of the function is less than (1 << 16) *2
613       // bytes, we can use 16-bit entries instead. Then there won't be an
614       // alignment issue.
615       unsigned InstSize = (Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT) ? 2 : 4;
616       unsigned NumEntries = getNumJTEntries(JT, JTI);
617       if (Opc == ARM::t2TBB_JT && (NumEntries & 1))
618         // Make sure the instruction that follows TBB is 2-byte aligned.
619         // FIXME: Constant island pass should insert an "ALIGN" instruction
620         // instead.
621         ++NumEntries;
622       return NumEntries * EntrySize + InstSize;
623     }
624     default:
625       // Otherwise, pseudo-instruction sizes are zero.
626       return 0;
627     }
628   }
629   }
630   return 0; // Not reached
631 }
632
633 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
634                                    MachineBasicBlock::iterator I, DebugLoc DL,
635                                    unsigned DestReg, unsigned SrcReg,
636                                    bool KillSrc) const {
637   bool GPRDest = ARM::GPRRegClass.contains(DestReg);
638   bool GPRSrc  = ARM::GPRRegClass.contains(SrcReg);
639
640   if (GPRDest && GPRSrc) {
641     AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
642                                   .addReg(SrcReg, getKillRegState(KillSrc))));
643     return;
644   }
645
646   bool SPRDest = ARM::SPRRegClass.contains(DestReg);
647   bool SPRSrc  = ARM::SPRRegClass.contains(SrcReg);
648
649   unsigned Opc;
650   if (SPRDest && SPRSrc)
651     Opc = ARM::VMOVS;
652   else if (GPRDest && SPRSrc)
653     Opc = ARM::VMOVRS;
654   else if (SPRDest && GPRSrc)
655     Opc = ARM::VMOVSR;
656   else if (ARM::DPRRegClass.contains(DestReg, SrcReg))
657     Opc = ARM::VMOVD;
658   else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
659     Opc = ARM::VMOVQ;
660   else if (ARM::QQPRRegClass.contains(DestReg, SrcReg))
661     Opc = ARM::VMOVQQ;
662   else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg))
663     Opc = ARM::VMOVQQQQ;
664   else
665     llvm_unreachable("Impossible reg-to-reg copy");
666
667   MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
668   MIB.addReg(SrcReg, getKillRegState(KillSrc));
669   if (Opc != ARM::VMOVQQ && Opc != ARM::VMOVQQQQ)
670     AddDefaultPred(MIB);
671 }
672
673 static const
674 MachineInstrBuilder &AddDReg(MachineInstrBuilder &MIB,
675                              unsigned Reg, unsigned SubIdx, unsigned State,
676                              const TargetRegisterInfo *TRI) {
677   if (!SubIdx)
678     return MIB.addReg(Reg, State);
679
680   if (TargetRegisterInfo::isPhysicalRegister(Reg))
681     return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
682   return MIB.addReg(Reg, State, SubIdx);
683 }
684
685 void ARMBaseInstrInfo::
686 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
687                     unsigned SrcReg, bool isKill, int FI,
688                     const TargetRegisterClass *RC,
689                     const TargetRegisterInfo *TRI) const {
690   DebugLoc DL;
691   if (I != MBB.end()) DL = I->getDebugLoc();
692   MachineFunction &MF = *MBB.getParent();
693   MachineFrameInfo &MFI = *MF.getFrameInfo();
694   unsigned Align = MFI.getObjectAlignment(FI);
695
696   MachineMemOperand *MMO =
697     MF.getMachineMemOperand(MachinePointerInfo(
698                                          PseudoSourceValue::getFixedStack(FI)),
699                             MachineMemOperand::MOStore,
700                             MFI.getObjectSize(FI),
701                             Align);
702
703   // tGPR is used sometimes in ARM instructions that need to avoid using
704   // certain registers.  Just treat it as GPR here. Likewise, rGPR.
705   if (RC == ARM::tGPRRegisterClass || RC == ARM::tcGPRRegisterClass
706       || RC == ARM::rGPRRegisterClass)
707     RC = ARM::GPRRegisterClass;
708
709   switch (RC->getID()) {
710   case ARM::GPRRegClassID:
711     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STRi12))
712                    .addReg(SrcReg, getKillRegState(isKill))
713                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
714     break;
715   case ARM::SPRRegClassID:
716     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRS))
717                    .addReg(SrcReg, getKillRegState(isKill))
718                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
719     break;
720   case ARM::DPRRegClassID:
721   case ARM::DPR_VFP2RegClassID:
722   case ARM::DPR_8RegClassID:
723     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRD))
724                    .addReg(SrcReg, getKillRegState(isKill))
725                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
726     break;
727   case ARM::QPRRegClassID:
728   case ARM::QPR_VFP2RegClassID:
729   case ARM::QPR_8RegClassID:
730     if (Align >= 16 && getRegisterInfo().needsStackRealignment(MF)) {
731       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q64Pseudo))
732                      .addFrameIndex(FI).addImm(16)
733                      .addReg(SrcReg, getKillRegState(isKill))
734                      .addMemOperand(MMO));
735     } else {
736       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMQIA))
737                      .addReg(SrcReg, getKillRegState(isKill))
738                      .addFrameIndex(FI)
739                      .addMemOperand(MMO));
740     }
741     break;
742   case ARM::QQPRRegClassID:
743   case ARM::QQPR_VFP2RegClassID:
744     if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
745       // FIXME: It's possible to only store part of the QQ register if the
746       // spilled def has a sub-register index.
747       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64QPseudo))
748                      .addFrameIndex(FI).addImm(16)
749                      .addReg(SrcReg, getKillRegState(isKill))
750                      .addMemOperand(MMO));
751     } else {
752       MachineInstrBuilder MIB =
753         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
754                        .addFrameIndex(FI))
755         .addMemOperand(MMO);
756       MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
757       MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
758       MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
759             AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
760     }
761     break;
762   case ARM::QQQQPRRegClassID: {
763     MachineInstrBuilder MIB =
764       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
765                      .addFrameIndex(FI))
766       .addMemOperand(MMO);
767     MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
768     MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
769     MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
770     MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
771     MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
772     MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
773     MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
774           AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
775     break;
776   }
777   default:
778     llvm_unreachable("Unknown regclass!");
779   }
780 }
781
782 unsigned
783 ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
784                                      int &FrameIndex) const {
785   switch (MI->getOpcode()) {
786   default: break;
787   case ARM::STRrs:
788   case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
789     if (MI->getOperand(1).isFI() &&
790         MI->getOperand(2).isReg() &&
791         MI->getOperand(3).isImm() &&
792         MI->getOperand(2).getReg() == 0 &&
793         MI->getOperand(3).getImm() == 0) {
794       FrameIndex = MI->getOperand(1).getIndex();
795       return MI->getOperand(0).getReg();
796     }
797     break;
798   case ARM::STRi12:
799   case ARM::t2STRi12:
800   case ARM::tSpill:
801   case ARM::VSTRD:
802   case ARM::VSTRS:
803     if (MI->getOperand(1).isFI() &&
804         MI->getOperand(2).isImm() &&
805         MI->getOperand(2).getImm() == 0) {
806       FrameIndex = MI->getOperand(1).getIndex();
807       return MI->getOperand(0).getReg();
808     }
809     break;
810   case ARM::VST1q64Pseudo:
811     if (MI->getOperand(0).isFI() &&
812         MI->getOperand(2).getSubReg() == 0) {
813       FrameIndex = MI->getOperand(0).getIndex();
814       return MI->getOperand(2).getReg();
815     }
816     break;
817   case ARM::VSTMQIA:
818     if (MI->getOperand(1).isFI() &&
819         MI->getOperand(0).getSubReg() == 0) {
820       FrameIndex = MI->getOperand(1).getIndex();
821       return MI->getOperand(0).getReg();
822     }
823     break;
824   }
825
826   return 0;
827 }
828
829 void ARMBaseInstrInfo::
830 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
831                      unsigned DestReg, int FI,
832                      const TargetRegisterClass *RC,
833                      const TargetRegisterInfo *TRI) const {
834   DebugLoc DL;
835   if (I != MBB.end()) DL = I->getDebugLoc();
836   MachineFunction &MF = *MBB.getParent();
837   MachineFrameInfo &MFI = *MF.getFrameInfo();
838   unsigned Align = MFI.getObjectAlignment(FI);
839   MachineMemOperand *MMO =
840     MF.getMachineMemOperand(
841                     MachinePointerInfo(PseudoSourceValue::getFixedStack(FI)),
842                             MachineMemOperand::MOLoad,
843                             MFI.getObjectSize(FI),
844                             Align);
845
846   // tGPR is used sometimes in ARM instructions that need to avoid using
847   // certain registers.  Just treat it as GPR here.
848   if (RC == ARM::tGPRRegisterClass || RC == ARM::tcGPRRegisterClass
849       || RC == ARM::rGPRRegisterClass)
850     RC = ARM::GPRRegisterClass;
851
852   switch (RC->getID()) {
853   case ARM::GPRRegClassID:
854     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
855                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
856     break;
857   case ARM::SPRRegClassID:
858     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
859                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
860     break;
861   case ARM::DPRRegClassID:
862   case ARM::DPR_VFP2RegClassID:
863   case ARM::DPR_8RegClassID:
864     AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
865                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
866     break;
867   case ARM::QPRRegClassID:
868   case ARM::QPR_VFP2RegClassID:
869   case ARM::QPR_8RegClassID:
870     if (Align >= 16 && getRegisterInfo().needsStackRealignment(MF)) {
871       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q64Pseudo), DestReg)
872                      .addFrameIndex(FI).addImm(16)
873                      .addMemOperand(MMO));
874     } else {
875       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
876                      .addFrameIndex(FI)
877                      .addMemOperand(MMO));
878     }
879     break;
880   case ARM::QQPRRegClassID:
881   case ARM::QQPR_VFP2RegClassID:
882     if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
883       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
884                      .addFrameIndex(FI).addImm(16)
885                      .addMemOperand(MMO));
886     } else {
887       MachineInstrBuilder MIB =
888         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
889                        .addFrameIndex(FI))
890         .addMemOperand(MMO);
891       MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
892       MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
893       MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
894             AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
895     }
896     break;
897   case ARM::QQQQPRRegClassID: {
898     MachineInstrBuilder MIB =
899       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
900                      .addFrameIndex(FI))
901       .addMemOperand(MMO);
902     MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
903     MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
904     MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
905     MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
906     MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::Define, TRI);
907     MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::Define, TRI);
908     MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::Define, TRI);
909     AddDReg(MIB, DestReg, ARM::dsub_7, RegState::Define, TRI);
910     break;
911   }
912   default:
913     llvm_unreachable("Unknown regclass!");
914   }
915 }
916
917 unsigned
918 ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
919                                       int &FrameIndex) const {
920   switch (MI->getOpcode()) {
921   default: break;
922   case ARM::LDRrs:
923   case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
924     if (MI->getOperand(1).isFI() &&
925         MI->getOperand(2).isReg() &&
926         MI->getOperand(3).isImm() &&
927         MI->getOperand(2).getReg() == 0 &&
928         MI->getOperand(3).getImm() == 0) {
929       FrameIndex = MI->getOperand(1).getIndex();
930       return MI->getOperand(0).getReg();
931     }
932     break;
933   case ARM::LDRi12:
934   case ARM::t2LDRi12:
935   case ARM::tRestore:
936   case ARM::VLDRD:
937   case ARM::VLDRS:
938     if (MI->getOperand(1).isFI() &&
939         MI->getOperand(2).isImm() &&
940         MI->getOperand(2).getImm() == 0) {
941       FrameIndex = MI->getOperand(1).getIndex();
942       return MI->getOperand(0).getReg();
943     }
944     break;
945   case ARM::VLD1q64Pseudo:
946     if (MI->getOperand(1).isFI() &&
947         MI->getOperand(0).getSubReg() == 0) {
948       FrameIndex = MI->getOperand(1).getIndex();
949       return MI->getOperand(0).getReg();
950     }
951     break;
952   case ARM::VLDMQIA:
953     if (MI->getOperand(1).isFI() &&
954         MI->getOperand(0).getSubReg() == 0) {
955       FrameIndex = MI->getOperand(1).getIndex();
956       return MI->getOperand(0).getReg();
957     }
958     break;
959   }
960
961   return 0;
962 }
963
964 MachineInstr*
965 ARMBaseInstrInfo::emitFrameIndexDebugValue(MachineFunction &MF,
966                                            int FrameIx, uint64_t Offset,
967                                            const MDNode *MDPtr,
968                                            DebugLoc DL) const {
969   MachineInstrBuilder MIB = BuildMI(MF, DL, get(ARM::DBG_VALUE))
970     .addFrameIndex(FrameIx).addImm(0).addImm(Offset).addMetadata(MDPtr);
971   return &*MIB;
972 }
973
974 /// Create a copy of a const pool value. Update CPI to the new index and return
975 /// the label UID.
976 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
977   MachineConstantPool *MCP = MF.getConstantPool();
978   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
979
980   const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
981   assert(MCPE.isMachineConstantPoolEntry() &&
982          "Expecting a machine constantpool entry!");
983   ARMConstantPoolValue *ACPV =
984     static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
985
986   unsigned PCLabelId = AFI->createPICLabelUId();
987   ARMConstantPoolValue *NewCPV = 0;
988   // FIXME: The below assumes PIC relocation model and that the function
989   // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
990   // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
991   // instructions, so that's probably OK, but is PIC always correct when
992   // we get here?
993   if (ACPV->isGlobalValue())
994     NewCPV = new ARMConstantPoolValue(ACPV->getGV(), PCLabelId,
995                                       ARMCP::CPValue, 4);
996   else if (ACPV->isExtSymbol())
997     NewCPV = new ARMConstantPoolValue(MF.getFunction()->getContext(),
998                                       ACPV->getSymbol(), PCLabelId, 4);
999   else if (ACPV->isBlockAddress())
1000     NewCPV = new ARMConstantPoolValue(ACPV->getBlockAddress(), PCLabelId,
1001                                       ARMCP::CPBlockAddress, 4);
1002   else if (ACPV->isLSDA())
1003     NewCPV = new ARMConstantPoolValue(MF.getFunction(), PCLabelId,
1004                                       ARMCP::CPLSDA, 4);
1005   else
1006     llvm_unreachable("Unexpected ARM constantpool value type!!");
1007   CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
1008   return PCLabelId;
1009 }
1010
1011 void ARMBaseInstrInfo::
1012 reMaterialize(MachineBasicBlock &MBB,
1013               MachineBasicBlock::iterator I,
1014               unsigned DestReg, unsigned SubIdx,
1015               const MachineInstr *Orig,
1016               const TargetRegisterInfo &TRI) const {
1017   unsigned Opcode = Orig->getOpcode();
1018   switch (Opcode) {
1019   default: {
1020     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
1021     MI->substituteRegister(Orig->getOperand(0).getReg(), DestReg, SubIdx, TRI);
1022     MBB.insert(I, MI);
1023     break;
1024   }
1025   case ARM::tLDRpci_pic:
1026   case ARM::t2LDRpci_pic: {
1027     MachineFunction &MF = *MBB.getParent();
1028     unsigned CPI = Orig->getOperand(1).getIndex();
1029     unsigned PCLabelId = duplicateCPV(MF, CPI);
1030     MachineInstrBuilder MIB = BuildMI(MBB, I, Orig->getDebugLoc(), get(Opcode),
1031                                       DestReg)
1032       .addConstantPoolIndex(CPI).addImm(PCLabelId);
1033     (*MIB).setMemRefs(Orig->memoperands_begin(), Orig->memoperands_end());
1034     break;
1035   }
1036   }
1037 }
1038
1039 MachineInstr *
1040 ARMBaseInstrInfo::duplicate(MachineInstr *Orig, MachineFunction &MF) const {
1041   MachineInstr *MI = TargetInstrInfoImpl::duplicate(Orig, MF);
1042   switch(Orig->getOpcode()) {
1043   case ARM::tLDRpci_pic:
1044   case ARM::t2LDRpci_pic: {
1045     unsigned CPI = Orig->getOperand(1).getIndex();
1046     unsigned PCLabelId = duplicateCPV(MF, CPI);
1047     Orig->getOperand(1).setIndex(CPI);
1048     Orig->getOperand(2).setImm(PCLabelId);
1049     break;
1050   }
1051   }
1052   return MI;
1053 }
1054
1055 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr *MI0,
1056                                         const MachineInstr *MI1) const {
1057   int Opcode = MI0->getOpcode();
1058   if (Opcode == ARM::t2LDRpci ||
1059       Opcode == ARM::t2LDRpci_pic ||
1060       Opcode == ARM::tLDRpci ||
1061       Opcode == ARM::tLDRpci_pic) {
1062     if (MI1->getOpcode() != Opcode)
1063       return false;
1064     if (MI0->getNumOperands() != MI1->getNumOperands())
1065       return false;
1066
1067     const MachineOperand &MO0 = MI0->getOperand(1);
1068     const MachineOperand &MO1 = MI1->getOperand(1);
1069     if (MO0.getOffset() != MO1.getOffset())
1070       return false;
1071
1072     const MachineFunction *MF = MI0->getParent()->getParent();
1073     const MachineConstantPool *MCP = MF->getConstantPool();
1074     int CPI0 = MO0.getIndex();
1075     int CPI1 = MO1.getIndex();
1076     const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1077     const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1078     ARMConstantPoolValue *ACPV0 =
1079       static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1080     ARMConstantPoolValue *ACPV1 =
1081       static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1082     return ACPV0->hasSameValue(ACPV1);
1083   }
1084
1085   return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1086 }
1087
1088 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1089 /// determine if two loads are loading from the same base address. It should
1090 /// only return true if the base pointers are the same and the only differences
1091 /// between the two addresses is the offset. It also returns the offsets by
1092 /// reference.
1093 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1094                                                int64_t &Offset1,
1095                                                int64_t &Offset2) const {
1096   // Don't worry about Thumb: just ARM and Thumb2.
1097   if (Subtarget.isThumb1Only()) return false;
1098
1099   if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1100     return false;
1101
1102   switch (Load1->getMachineOpcode()) {
1103   default:
1104     return false;
1105   case ARM::LDRi12:
1106   case ARM::LDRBi12:
1107   case ARM::LDRD:
1108   case ARM::LDRH:
1109   case ARM::LDRSB:
1110   case ARM::LDRSH:
1111   case ARM::VLDRD:
1112   case ARM::VLDRS:
1113   case ARM::t2LDRi8:
1114   case ARM::t2LDRDi8:
1115   case ARM::t2LDRSHi8:
1116   case ARM::t2LDRi12:
1117   case ARM::t2LDRSHi12:
1118     break;
1119   }
1120
1121   switch (Load2->getMachineOpcode()) {
1122   default:
1123     return false;
1124   case ARM::LDRi12:
1125   case ARM::LDRBi12:
1126   case ARM::LDRD:
1127   case ARM::LDRH:
1128   case ARM::LDRSB:
1129   case ARM::LDRSH:
1130   case ARM::VLDRD:
1131   case ARM::VLDRS:
1132   case ARM::t2LDRi8:
1133   case ARM::t2LDRDi8:
1134   case ARM::t2LDRSHi8:
1135   case ARM::t2LDRi12:
1136   case ARM::t2LDRSHi12:
1137     break;
1138   }
1139
1140   // Check if base addresses and chain operands match.
1141   if (Load1->getOperand(0) != Load2->getOperand(0) ||
1142       Load1->getOperand(4) != Load2->getOperand(4))
1143     return false;
1144
1145   // Index should be Reg0.
1146   if (Load1->getOperand(3) != Load2->getOperand(3))
1147     return false;
1148
1149   // Determine the offsets.
1150   if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1151       isa<ConstantSDNode>(Load2->getOperand(1))) {
1152     Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1153     Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1154     return true;
1155   }
1156
1157   return false;
1158 }
1159
1160 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1161 /// determine (in conjuction with areLoadsFromSameBasePtr) if two loads should
1162 /// be scheduled togther. On some targets if two loads are loading from
1163 /// addresses in the same cache line, it's better if they are scheduled
1164 /// together. This function takes two integers that represent the load offsets
1165 /// from the common base address. It returns true if it decides it's desirable
1166 /// to schedule the two loads together. "NumLoads" is the number of loads that
1167 /// have already been scheduled after Load1.
1168 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1169                                                int64_t Offset1, int64_t Offset2,
1170                                                unsigned NumLoads) const {
1171   // Don't worry about Thumb: just ARM and Thumb2.
1172   if (Subtarget.isThumb1Only()) return false;
1173
1174   assert(Offset2 > Offset1);
1175
1176   if ((Offset2 - Offset1) / 8 > 64)
1177     return false;
1178
1179   if (Load1->getMachineOpcode() != Load2->getMachineOpcode())
1180     return false;  // FIXME: overly conservative?
1181
1182   // Four loads in a row should be sufficient.
1183   if (NumLoads >= 3)
1184     return false;
1185
1186   return true;
1187 }
1188
1189 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1190                                             const MachineBasicBlock *MBB,
1191                                             const MachineFunction &MF) const {
1192   // Debug info is never a scheduling boundary. It's necessary to be explicit
1193   // due to the special treatment of IT instructions below, otherwise a
1194   // dbg_value followed by an IT will result in the IT instruction being
1195   // considered a scheduling hazard, which is wrong. It should be the actual
1196   // instruction preceding the dbg_value instruction(s), just like it is
1197   // when debug info is not present.
1198   if (MI->isDebugValue())
1199     return false;
1200
1201   // Terminators and labels can't be scheduled around.
1202   if (MI->getDesc().isTerminator() || MI->isLabel())
1203     return true;
1204
1205   // Treat the start of the IT block as a scheduling boundary, but schedule
1206   // t2IT along with all instructions following it.
1207   // FIXME: This is a big hammer. But the alternative is to add all potential
1208   // true and anti dependencies to IT block instructions as implicit operands
1209   // to the t2IT instruction. The added compile time and complexity does not
1210   // seem worth it.
1211   MachineBasicBlock::const_iterator I = MI;
1212   // Make sure to skip any dbg_value instructions
1213   while (++I != MBB->end() && I->isDebugValue())
1214     ;
1215   if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
1216     return true;
1217
1218   // Don't attempt to schedule around any instruction that defines
1219   // a stack-oriented pointer, as it's unlikely to be profitable. This
1220   // saves compile time, because it doesn't require every single
1221   // stack slot reference to depend on the instruction that does the
1222   // modification.
1223   if (MI->definesRegister(ARM::SP))
1224     return true;
1225
1226   return false;
1227 }
1228
1229 bool ARMBaseInstrInfo::isProfitableToIfCvt(MachineBasicBlock &MBB,
1230                                            unsigned NumCyles,
1231                                            unsigned ExtraPredCycles,
1232                                            float Probability,
1233                                            float Confidence) const {
1234   if (!NumCyles)
1235     return false;
1236
1237   // Attempt to estimate the relative costs of predication versus branching.
1238   float UnpredCost = Probability * NumCyles;
1239   UnpredCost += 1.0; // The branch itself
1240   UnpredCost += (1.0 - Confidence) * Subtarget.getMispredictionPenalty();
1241
1242   return (float)(NumCyles + ExtraPredCycles) < UnpredCost;
1243 }
1244
1245 bool ARMBaseInstrInfo::
1246 isProfitableToIfCvt(MachineBasicBlock &TMBB,
1247                     unsigned TCycles, unsigned TExtra,
1248                     MachineBasicBlock &FMBB,
1249                     unsigned FCycles, unsigned FExtra,
1250                     float Probability, float Confidence) const {
1251   if (!TCycles || !FCycles)
1252     return false;
1253
1254   // Attempt to estimate the relative costs of predication versus branching.
1255   float UnpredCost = Probability * TCycles + (1.0 - Probability) * FCycles;
1256   UnpredCost += 1.0; // The branch itself
1257   UnpredCost += (1.0 - Confidence) * Subtarget.getMispredictionPenalty();
1258
1259   return (float)(TCycles + FCycles + TExtra + FExtra) < UnpredCost;
1260 }
1261
1262 /// getInstrPredicate - If instruction is predicated, returns its predicate
1263 /// condition, otherwise returns AL. It also returns the condition code
1264 /// register by reference.
1265 ARMCC::CondCodes
1266 llvm::getInstrPredicate(const MachineInstr *MI, unsigned &PredReg) {
1267   int PIdx = MI->findFirstPredOperandIdx();
1268   if (PIdx == -1) {
1269     PredReg = 0;
1270     return ARMCC::AL;
1271   }
1272
1273   PredReg = MI->getOperand(PIdx+1).getReg();
1274   return (ARMCC::CondCodes)MI->getOperand(PIdx).getImm();
1275 }
1276
1277
1278 int llvm::getMatchingCondBranchOpcode(int Opc) {
1279   if (Opc == ARM::B)
1280     return ARM::Bcc;
1281   else if (Opc == ARM::tB)
1282     return ARM::tBcc;
1283   else if (Opc == ARM::t2B)
1284       return ARM::t2Bcc;
1285
1286   llvm_unreachable("Unknown unconditional branch opcode!");
1287   return 0;
1288 }
1289
1290
1291 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
1292                                MachineBasicBlock::iterator &MBBI, DebugLoc dl,
1293                                unsigned DestReg, unsigned BaseReg, int NumBytes,
1294                                ARMCC::CondCodes Pred, unsigned PredReg,
1295                                const ARMBaseInstrInfo &TII) {
1296   bool isSub = NumBytes < 0;
1297   if (isSub) NumBytes = -NumBytes;
1298
1299   while (NumBytes) {
1300     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
1301     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
1302     assert(ThisVal && "Didn't extract field correctly");
1303
1304     // We will handle these bits from offset, clear them.
1305     NumBytes &= ~ThisVal;
1306
1307     assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
1308
1309     // Build the new ADD / SUB.
1310     unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
1311     BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
1312       .addReg(BaseReg, RegState::Kill).addImm(ThisVal)
1313       .addImm((unsigned)Pred).addReg(PredReg).addReg(0);
1314     BaseReg = DestReg;
1315   }
1316 }
1317
1318 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
1319                                 unsigned FrameReg, int &Offset,
1320                                 const ARMBaseInstrInfo &TII) {
1321   unsigned Opcode = MI.getOpcode();
1322   const TargetInstrDesc &Desc = MI.getDesc();
1323   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1324   bool isSub = false;
1325
1326   // Memory operands in inline assembly always use AddrMode2.
1327   if (Opcode == ARM::INLINEASM)
1328     AddrMode = ARMII::AddrMode2;
1329
1330   if (Opcode == ARM::ADDri) {
1331     Offset += MI.getOperand(FrameRegIdx+1).getImm();
1332     if (Offset == 0) {
1333       // Turn it into a move.
1334       MI.setDesc(TII.get(ARM::MOVr));
1335       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1336       MI.RemoveOperand(FrameRegIdx+1);
1337       Offset = 0;
1338       return true;
1339     } else if (Offset < 0) {
1340       Offset = -Offset;
1341       isSub = true;
1342       MI.setDesc(TII.get(ARM::SUBri));
1343     }
1344
1345     // Common case: small offset, fits into instruction.
1346     if (ARM_AM::getSOImmVal(Offset) != -1) {
1347       // Replace the FrameIndex with sp / fp
1348       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1349       MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
1350       Offset = 0;
1351       return true;
1352     }
1353
1354     // Otherwise, pull as much of the immedidate into this ADDri/SUBri
1355     // as possible.
1356     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
1357     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
1358
1359     // We will handle these bits from offset, clear them.
1360     Offset &= ~ThisImmVal;
1361
1362     // Get the properly encoded SOImmVal field.
1363     assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
1364            "Bit extraction didn't work?");
1365     MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
1366  } else {
1367     unsigned ImmIdx = 0;
1368     int InstrOffs = 0;
1369     unsigned NumBits = 0;
1370     unsigned Scale = 1;
1371     switch (AddrMode) {
1372     case ARMII::AddrMode_i12: {
1373       ImmIdx = FrameRegIdx + 1;
1374       InstrOffs = MI.getOperand(ImmIdx).getImm();
1375       NumBits = 12;
1376       break;
1377     }
1378     case ARMII::AddrMode2: {
1379       ImmIdx = FrameRegIdx+2;
1380       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
1381       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1382         InstrOffs *= -1;
1383       NumBits = 12;
1384       break;
1385     }
1386     case ARMII::AddrMode3: {
1387       ImmIdx = FrameRegIdx+2;
1388       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
1389       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1390         InstrOffs *= -1;
1391       NumBits = 8;
1392       break;
1393     }
1394     case ARMII::AddrMode4:
1395     case ARMII::AddrMode6:
1396       // Can't fold any offset even if it's zero.
1397       return false;
1398     case ARMII::AddrMode5: {
1399       ImmIdx = FrameRegIdx+1;
1400       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
1401       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1402         InstrOffs *= -1;
1403       NumBits = 8;
1404       Scale = 4;
1405       break;
1406     }
1407     default:
1408       llvm_unreachable("Unsupported addressing mode!");
1409       break;
1410     }
1411
1412     Offset += InstrOffs * Scale;
1413     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1414     if (Offset < 0) {
1415       Offset = -Offset;
1416       isSub = true;
1417     }
1418
1419     // Attempt to fold address comp. if opcode has offset bits
1420     if (NumBits > 0) {
1421       // Common case: small offset, fits into instruction.
1422       MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1423       int ImmedOffset = Offset / Scale;
1424       unsigned Mask = (1 << NumBits) - 1;
1425       if ((unsigned)Offset <= Mask * Scale) {
1426         // Replace the FrameIndex with sp
1427         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1428         // FIXME: When addrmode2 goes away, this will simplify (like the
1429         // T2 version), as the LDR.i12 versions don't need the encoding
1430         // tricks for the offset value.
1431         if (isSub) {
1432           if (AddrMode == ARMII::AddrMode_i12)
1433             ImmedOffset = -ImmedOffset;
1434           else
1435             ImmedOffset |= 1 << NumBits;
1436         }
1437         ImmOp.ChangeToImmediate(ImmedOffset);
1438         Offset = 0;
1439         return true;
1440       }
1441
1442       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1443       ImmedOffset = ImmedOffset & Mask;
1444       if (isSub) {
1445         if (AddrMode == ARMII::AddrMode_i12)
1446           ImmedOffset = -ImmedOffset;
1447         else
1448           ImmedOffset |= 1 << NumBits;
1449       }
1450       ImmOp.ChangeToImmediate(ImmedOffset);
1451       Offset &= ~(Mask*Scale);
1452     }
1453   }
1454
1455   Offset = (isSub) ? -Offset : Offset;
1456   return Offset == 0;
1457 }
1458
1459 bool ARMBaseInstrInfo::
1460 AnalyzeCompare(const MachineInstr *MI, unsigned &SrcReg, int &CmpMask,
1461                int &CmpValue) const {
1462   switch (MI->getOpcode()) {
1463   default: break;
1464   case ARM::CMPri:
1465   case ARM::t2CMPri:
1466     SrcReg = MI->getOperand(0).getReg();
1467     CmpMask = ~0;
1468     CmpValue = MI->getOperand(1).getImm();
1469     return true;
1470   case ARM::TSTri:
1471   case ARM::t2TSTri:
1472     SrcReg = MI->getOperand(0).getReg();
1473     CmpMask = MI->getOperand(1).getImm();
1474     CmpValue = 0;
1475     return true;
1476   }
1477
1478   return false;
1479 }
1480
1481 /// isSuitableForMask - Identify a suitable 'and' instruction that
1482 /// operates on the given source register and applies the same mask
1483 /// as a 'tst' instruction. Provide a limited look-through for copies.
1484 /// When successful, MI will hold the found instruction.
1485 static bool isSuitableForMask(MachineInstr *&MI, unsigned SrcReg,
1486                               int CmpMask, bool CommonUse) {
1487   switch (MI->getOpcode()) {
1488     case ARM::ANDri:
1489     case ARM::t2ANDri:
1490       if (CmpMask != MI->getOperand(2).getImm())
1491         return false;
1492       if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
1493         return true;
1494       break;
1495     case ARM::COPY: {
1496       // Walk down one instruction which is potentially an 'and'.
1497       const MachineInstr &Copy = *MI;
1498       MachineBasicBlock::iterator AND(
1499         llvm::next(MachineBasicBlock::iterator(MI)));
1500       if (AND == MI->getParent()->end()) return false;
1501       MI = AND;
1502       return isSuitableForMask(MI, Copy.getOperand(0).getReg(),
1503                                CmpMask, true);
1504     }
1505   }
1506
1507   return false;
1508 }
1509
1510 /// OptimizeCompareInstr - Convert the instruction supplying the argument to the
1511 /// comparison into one that sets the zero bit in the flags register.
1512 bool ARMBaseInstrInfo::
1513 OptimizeCompareInstr(MachineInstr *CmpInstr, unsigned SrcReg, int CmpMask,
1514                      int CmpValue, const MachineRegisterInfo *MRI) const {
1515   if (CmpValue != 0)
1516     return false;
1517
1518   MachineRegisterInfo::def_iterator DI = MRI->def_begin(SrcReg);
1519   if (llvm::next(DI) != MRI->def_end())
1520     // Only support one definition.
1521     return false;
1522
1523   MachineInstr *MI = &*DI;
1524
1525   // Masked compares sometimes use the same register as the corresponding 'and'.
1526   if (CmpMask != ~0) {
1527     if (!isSuitableForMask(MI, SrcReg, CmpMask, false)) {
1528       MI = 0;
1529       for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SrcReg),
1530            UE = MRI->use_end(); UI != UE; ++UI) {
1531         if (UI->getParent() != CmpInstr->getParent()) continue;
1532         MachineInstr *PotentialAND = &*UI;
1533         if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true))
1534           continue;
1535         MI = PotentialAND;
1536         break;
1537       }
1538       if (!MI) return false;
1539     }
1540   }
1541
1542   // Conservatively refuse to convert an instruction which isn't in the same BB
1543   // as the comparison.
1544   if (MI->getParent() != CmpInstr->getParent())
1545     return false;
1546
1547   // Check that CPSR isn't set between the comparison instruction and the one we
1548   // want to change.
1549   MachineBasicBlock::const_iterator I = CmpInstr, E = MI,
1550     B = MI->getParent()->begin();
1551
1552   // Early exit if CmpInstr is at the beginning of the BB.
1553   if (I == B) return false;
1554
1555   --I;
1556   for (; I != E; --I) {
1557     const MachineInstr &Instr = *I;
1558
1559     for (unsigned IO = 0, EO = Instr.getNumOperands(); IO != EO; ++IO) {
1560       const MachineOperand &MO = Instr.getOperand(IO);
1561       if (!MO.isReg()) continue;
1562
1563       // This instruction modifies or uses CPSR after the one we want to
1564       // change. We can't do this transformation.
1565       if (MO.getReg() == ARM::CPSR)
1566         return false;
1567     }
1568
1569     if (I == B)
1570       // The 'and' is below the comparison instruction.
1571       return false;
1572   }
1573
1574   // Set the "zero" bit in CPSR.
1575   switch (MI->getOpcode()) {
1576   default: break;
1577   case ARM::ADDri:
1578   case ARM::ANDri:
1579   case ARM::t2ANDri:
1580   case ARM::SUBri:
1581   case ARM::t2ADDri:
1582   case ARM::t2SUBri:
1583     // Toggle the optional operand to CPSR.
1584     MI->getOperand(5).setReg(ARM::CPSR);
1585     MI->getOperand(5).setIsDef(true);
1586     CmpInstr->eraseFromParent();
1587     return true;
1588   }
1589
1590   return false;
1591 }
1592
1593 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr *UseMI,
1594                                      MachineInstr *DefMI, unsigned Reg,
1595                                      MachineRegisterInfo *MRI) const {
1596   // Fold large immediates into add, sub, or, xor.
1597   unsigned DefOpc = DefMI->getOpcode();
1598   if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
1599     return false;
1600   if (!DefMI->getOperand(1).isImm())
1601     // Could be t2MOVi32imm <ga:xx>
1602     return false;
1603
1604   if (!MRI->hasOneNonDBGUse(Reg))
1605     return false;
1606
1607   unsigned UseOpc = UseMI->getOpcode();
1608   unsigned NewUseOpc = 0;
1609   uint32_t ImmVal = (uint32_t)DefMI->getOperand(1).getImm();
1610   uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
1611   bool Commute = false;
1612   switch (UseOpc) {
1613   default: return false;
1614   case ARM::SUBrr:
1615   case ARM::ADDrr:
1616   case ARM::ORRrr:
1617   case ARM::EORrr:
1618   case ARM::t2SUBrr:
1619   case ARM::t2ADDrr:
1620   case ARM::t2ORRrr:
1621   case ARM::t2EORrr: {
1622     Commute = UseMI->getOperand(2).getReg() != Reg;
1623     switch (UseOpc) {
1624     default: break;
1625     case ARM::SUBrr: {
1626       if (Commute)
1627         return false;
1628       ImmVal = -ImmVal;
1629       NewUseOpc = ARM::SUBri;
1630       // Fallthrough
1631     }
1632     case ARM::ADDrr:
1633     case ARM::ORRrr:
1634     case ARM::EORrr: {
1635       if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
1636         return false;
1637       SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
1638       SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
1639       switch (UseOpc) {
1640       default: break;
1641       case ARM::ADDrr: NewUseOpc = ARM::ADDri; break;
1642       case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
1643       case ARM::EORrr: NewUseOpc = ARM::EORri; break;
1644       }
1645       break;
1646     }
1647     case ARM::t2SUBrr: {
1648       if (Commute)
1649         return false;
1650       ImmVal = -ImmVal;
1651       NewUseOpc = ARM::t2SUBri;
1652       // Fallthrough
1653     }
1654     case ARM::t2ADDrr:
1655     case ARM::t2ORRrr:
1656     case ARM::t2EORrr: {
1657       if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
1658         return false;
1659       SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
1660       SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
1661       switch (UseOpc) {
1662       default: break;
1663       case ARM::t2ADDrr: NewUseOpc = ARM::t2ADDri; break;
1664       case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
1665       case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
1666       }
1667       break;
1668     }
1669     }
1670   }
1671   }
1672
1673   unsigned OpIdx = Commute ? 2 : 1;
1674   unsigned Reg1 = UseMI->getOperand(OpIdx).getReg();
1675   bool isKill = UseMI->getOperand(OpIdx).isKill();
1676   unsigned NewReg = MRI->createVirtualRegister(MRI->getRegClass(Reg));
1677   AddDefaultCC(AddDefaultPred(BuildMI(*UseMI->getParent(),
1678                                       *UseMI, UseMI->getDebugLoc(),
1679                                       get(NewUseOpc), NewReg)
1680                               .addReg(Reg1, getKillRegState(isKill))
1681                               .addImm(SOImmValV1)));
1682   UseMI->setDesc(get(NewUseOpc));
1683   UseMI->getOperand(1).setReg(NewReg);
1684   UseMI->getOperand(1).setIsKill();
1685   UseMI->getOperand(2).ChangeToImmediate(SOImmValV2);
1686   DefMI->eraseFromParent();
1687   return true;
1688 }
1689
1690 unsigned
1691 ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
1692                                  const MachineInstr *MI) const {
1693   if (!ItinData || ItinData->isEmpty())
1694     return 1;
1695
1696   const TargetInstrDesc &Desc = MI->getDesc();
1697   unsigned Class = Desc.getSchedClass();
1698   unsigned UOps = ItinData->Itineraries[Class].NumMicroOps;
1699   if (UOps)
1700     return UOps;
1701
1702   unsigned Opc = MI->getOpcode();
1703   switch (Opc) {
1704   default:
1705     llvm_unreachable("Unexpected multi-uops instruction!");
1706     break;
1707   case ARM::VLDMQIA:
1708   case ARM::VLDMQDB:
1709   case ARM::VSTMQIA:
1710   case ARM::VSTMQDB:
1711     return 2;
1712
1713   // The number of uOps for load / store multiple are determined by the number
1714   // registers.
1715   //
1716   // On Cortex-A8, each pair of register loads / stores can be scheduled on the
1717   // same cycle. The scheduling for the first load / store must be done
1718   // separately by assuming the the address is not 64-bit aligned.
1719   //
1720   // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
1721   // is not 64-bit aligned, then AGU would take an extra cycle.  For VFP / NEON
1722   // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
1723   case ARM::VLDMDIA:
1724   case ARM::VLDMDDB:
1725   case ARM::VLDMDIA_UPD:
1726   case ARM::VLDMDDB_UPD:
1727   case ARM::VLDMSIA:
1728   case ARM::VLDMSDB:
1729   case ARM::VLDMSIA_UPD:
1730   case ARM::VLDMSDB_UPD:
1731   case ARM::VSTMDIA:
1732   case ARM::VSTMDDB:
1733   case ARM::VSTMDIA_UPD:
1734   case ARM::VSTMDDB_UPD:
1735   case ARM::VSTMSIA:
1736   case ARM::VSTMSDB:
1737   case ARM::VSTMSIA_UPD:
1738   case ARM::VSTMSDB_UPD: {
1739     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands();
1740     return (NumRegs / 2) + (NumRegs % 2) + 1;
1741   }
1742
1743   case ARM::LDMIA_RET:
1744   case ARM::LDMIA:
1745   case ARM::LDMDA:
1746   case ARM::LDMDB:
1747   case ARM::LDMIB:
1748   case ARM::LDMIA_UPD:
1749   case ARM::LDMDA_UPD:
1750   case ARM::LDMDB_UPD:
1751   case ARM::LDMIB_UPD:
1752   case ARM::STMIA:
1753   case ARM::STMDA:
1754   case ARM::STMDB:
1755   case ARM::STMIB:
1756   case ARM::STMIA_UPD:
1757   case ARM::STMDA_UPD:
1758   case ARM::STMDB_UPD:
1759   case ARM::STMIB_UPD:
1760   case ARM::tLDMIA:
1761   case ARM::tLDMIA_UPD:
1762   case ARM::tSTMIA:
1763   case ARM::tSTMIA_UPD:
1764   case ARM::tPOP_RET:
1765   case ARM::tPOP:
1766   case ARM::tPUSH:
1767   case ARM::t2LDMIA_RET:
1768   case ARM::t2LDMIA:
1769   case ARM::t2LDMDB:
1770   case ARM::t2LDMIA_UPD:
1771   case ARM::t2LDMDB_UPD:
1772   case ARM::t2STMIA:
1773   case ARM::t2STMDB:
1774   case ARM::t2STMIA_UPD:
1775   case ARM::t2STMDB_UPD: {
1776     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands() + 1;
1777     if (Subtarget.isCortexA8()) {
1778       if (NumRegs < 4)
1779         return 2;
1780       // 4 registers would be issued: 2, 2.
1781       // 5 registers would be issued: 2, 2, 1.
1782       UOps = (NumRegs / 2);
1783       if (NumRegs % 2)
1784         ++UOps;
1785       return UOps;
1786     } else if (Subtarget.isCortexA9()) {
1787       UOps = (NumRegs / 2);
1788       // If there are odd number of registers or if it's not 64-bit aligned,
1789       // then it takes an extra AGU (Address Generation Unit) cycle.
1790       if ((NumRegs % 2) ||
1791           !MI->hasOneMemOperand() ||
1792           (*MI->memoperands_begin())->getAlignment() < 8)
1793         ++UOps;
1794       return UOps;
1795     } else {
1796       // Assume the worst.
1797       return NumRegs;
1798     }
1799   }
1800   }
1801 }
1802
1803 int
1804 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
1805                                   const TargetInstrDesc &DefTID,
1806                                   unsigned DefClass,
1807                                   unsigned DefIdx, unsigned DefAlign) const {
1808   int RegNo = (int)(DefIdx+1) - DefTID.getNumOperands() + 1;
1809   if (RegNo <= 0)
1810     // Def is the address writeback.
1811     return ItinData->getOperandCycle(DefClass, DefIdx);
1812
1813   int DefCycle;
1814   if (Subtarget.isCortexA8()) {
1815     // (regno / 2) + (regno % 2) + 1
1816     DefCycle = RegNo / 2 + 1;
1817     if (RegNo % 2)
1818       ++DefCycle;
1819   } else if (Subtarget.isCortexA9()) {
1820     DefCycle = RegNo;
1821     bool isSLoad = false;
1822
1823     switch (DefTID.getOpcode()) {
1824     default: break;
1825     case ARM::VLDMSIA:
1826     case ARM::VLDMSDB:
1827     case ARM::VLDMSIA_UPD:
1828     case ARM::VLDMSDB_UPD:
1829       isSLoad = true;
1830       break;
1831     }
1832
1833     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
1834     // then it takes an extra cycle.
1835     if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
1836       ++DefCycle;
1837   } else {
1838     // Assume the worst.
1839     DefCycle = RegNo + 2;
1840   }
1841
1842   return DefCycle;
1843 }
1844
1845 int
1846 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
1847                                  const TargetInstrDesc &DefTID,
1848                                  unsigned DefClass,
1849                                  unsigned DefIdx, unsigned DefAlign) const {
1850   int RegNo = (int)(DefIdx+1) - DefTID.getNumOperands() + 1;
1851   if (RegNo <= 0)
1852     // Def is the address writeback.
1853     return ItinData->getOperandCycle(DefClass, DefIdx);
1854
1855   int DefCycle;
1856   if (Subtarget.isCortexA8()) {
1857     // 4 registers would be issued: 1, 2, 1.
1858     // 5 registers would be issued: 1, 2, 2.
1859     DefCycle = RegNo / 2;
1860     if (DefCycle < 1)
1861       DefCycle = 1;
1862     // Result latency is issue cycle + 2: E2.
1863     DefCycle += 2;
1864   } else if (Subtarget.isCortexA9()) {
1865     DefCycle = (RegNo / 2);
1866     // If there are odd number of registers or if it's not 64-bit aligned,
1867     // then it takes an extra AGU (Address Generation Unit) cycle.
1868     if ((RegNo % 2) || DefAlign < 8)
1869       ++DefCycle;
1870     // Result latency is AGU cycles + 2.
1871     DefCycle += 2;
1872   } else {
1873     // Assume the worst.
1874     DefCycle = RegNo + 2;
1875   }
1876
1877   return DefCycle;
1878 }
1879
1880 int
1881 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
1882                                   const TargetInstrDesc &UseTID,
1883                                   unsigned UseClass,
1884                                   unsigned UseIdx, unsigned UseAlign) const {
1885   int RegNo = (int)(UseIdx+1) - UseTID.getNumOperands() + 1;
1886   if (RegNo <= 0)
1887     return ItinData->getOperandCycle(UseClass, UseIdx);
1888
1889   int UseCycle;
1890   if (Subtarget.isCortexA8()) {
1891     // (regno / 2) + (regno % 2) + 1
1892     UseCycle = RegNo / 2 + 1;
1893     if (RegNo % 2)
1894       ++UseCycle;
1895   } else if (Subtarget.isCortexA9()) {
1896     UseCycle = RegNo;
1897     bool isSStore = false;
1898
1899     switch (UseTID.getOpcode()) {
1900     default: break;
1901     case ARM::VSTMSIA:
1902     case ARM::VSTMSDB:
1903     case ARM::VSTMSIA_UPD:
1904     case ARM::VSTMSDB_UPD:
1905       isSStore = true;
1906       break;
1907     }
1908
1909     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
1910     // then it takes an extra cycle.
1911     if ((isSStore && (RegNo % 2)) || UseAlign < 8)
1912       ++UseCycle;
1913   } else {
1914     // Assume the worst.
1915     UseCycle = RegNo + 2;
1916   }
1917
1918   return UseCycle;
1919 }
1920
1921 int
1922 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
1923                                  const TargetInstrDesc &UseTID,
1924                                  unsigned UseClass,
1925                                  unsigned UseIdx, unsigned UseAlign) const {
1926   int RegNo = (int)(UseIdx+1) - UseTID.getNumOperands() + 1;
1927   if (RegNo <= 0)
1928     return ItinData->getOperandCycle(UseClass, UseIdx);
1929
1930   int UseCycle;
1931   if (Subtarget.isCortexA8()) {
1932     UseCycle = RegNo / 2;
1933     if (UseCycle < 2)
1934       UseCycle = 2;
1935     // Read in E3.
1936     UseCycle += 2;
1937   } else if (Subtarget.isCortexA9()) {
1938     UseCycle = (RegNo / 2);
1939     // If there are odd number of registers or if it's not 64-bit aligned,
1940     // then it takes an extra AGU (Address Generation Unit) cycle.
1941     if ((RegNo % 2) || UseAlign < 8)
1942       ++UseCycle;
1943   } else {
1944     // Assume the worst.
1945     UseCycle = 1;
1946   }
1947   return UseCycle;
1948 }
1949
1950 int
1951 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
1952                                     const TargetInstrDesc &DefTID,
1953                                     unsigned DefIdx, unsigned DefAlign,
1954                                     const TargetInstrDesc &UseTID,
1955                                     unsigned UseIdx, unsigned UseAlign) const {
1956   unsigned DefClass = DefTID.getSchedClass();
1957   unsigned UseClass = UseTID.getSchedClass();
1958
1959   if (DefIdx < DefTID.getNumDefs() && UseIdx < UseTID.getNumOperands())
1960     return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
1961
1962   // This may be a def / use of a variable_ops instruction, the operand
1963   // latency might be determinable dynamically. Let the target try to
1964   // figure it out.
1965   int DefCycle = -1;
1966   bool LdmBypass = false;
1967   switch (DefTID.getOpcode()) {
1968   default:
1969     DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
1970     break;
1971
1972   case ARM::VLDMDIA:
1973   case ARM::VLDMDDB:
1974   case ARM::VLDMDIA_UPD:
1975   case ARM::VLDMDDB_UPD:
1976   case ARM::VLDMSIA:
1977   case ARM::VLDMSDB:
1978   case ARM::VLDMSIA_UPD:
1979   case ARM::VLDMSDB_UPD:
1980     DefCycle = getVLDMDefCycle(ItinData, DefTID, DefClass, DefIdx, DefAlign);
1981     break;
1982
1983   case ARM::LDMIA_RET:
1984   case ARM::LDMIA:
1985   case ARM::LDMDA:
1986   case ARM::LDMDB:
1987   case ARM::LDMIB:
1988   case ARM::LDMIA_UPD:
1989   case ARM::LDMDA_UPD:
1990   case ARM::LDMDB_UPD:
1991   case ARM::LDMIB_UPD:
1992   case ARM::tLDMIA:
1993   case ARM::tLDMIA_UPD:
1994   case ARM::tPUSH:
1995   case ARM::t2LDMIA_RET:
1996   case ARM::t2LDMIA:
1997   case ARM::t2LDMDB:
1998   case ARM::t2LDMIA_UPD:
1999   case ARM::t2LDMDB_UPD:
2000     LdmBypass = 1;
2001     DefCycle = getLDMDefCycle(ItinData, DefTID, DefClass, DefIdx, DefAlign);
2002     break;
2003   }
2004
2005   if (DefCycle == -1)
2006     // We can't seem to determine the result latency of the def, assume it's 2.
2007     DefCycle = 2;
2008
2009   int UseCycle = -1;
2010   switch (UseTID.getOpcode()) {
2011   default:
2012     UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
2013     break;
2014
2015   case ARM::VSTMDIA:
2016   case ARM::VSTMDDB:
2017   case ARM::VSTMDIA_UPD:
2018   case ARM::VSTMDDB_UPD:
2019   case ARM::VSTMSIA:
2020   case ARM::VSTMSDB:
2021   case ARM::VSTMSIA_UPD:
2022   case ARM::VSTMSDB_UPD:
2023     UseCycle = getVSTMUseCycle(ItinData, UseTID, UseClass, UseIdx, UseAlign);
2024     break;
2025
2026   case ARM::STMIA:
2027   case ARM::STMDA:
2028   case ARM::STMDB:
2029   case ARM::STMIB:
2030   case ARM::STMIA_UPD:
2031   case ARM::STMDA_UPD:
2032   case ARM::STMDB_UPD:
2033   case ARM::STMIB_UPD:
2034   case ARM::tSTMIA:
2035   case ARM::tSTMIA_UPD:
2036   case ARM::tPOP_RET:
2037   case ARM::tPOP:
2038   case ARM::t2STMIA:
2039   case ARM::t2STMDB:
2040   case ARM::t2STMIA_UPD:
2041   case ARM::t2STMDB_UPD:
2042     UseCycle = getSTMUseCycle(ItinData, UseTID, UseClass, UseIdx, UseAlign);
2043     break;
2044   }
2045
2046   if (UseCycle == -1)
2047     // Assume it's read in the first stage.
2048     UseCycle = 1;
2049
2050   UseCycle = DefCycle - UseCycle + 1;
2051   if (UseCycle > 0) {
2052     if (LdmBypass) {
2053       // It's a variable_ops instruction so we can't use DefIdx here. Just use
2054       // first def operand.
2055       if (ItinData->hasPipelineForwarding(DefClass, DefTID.getNumOperands()-1,
2056                                           UseClass, UseIdx))
2057         --UseCycle;
2058     } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
2059                                                UseClass, UseIdx)) {
2060       --UseCycle;
2061     }
2062   }
2063
2064   return UseCycle;
2065 }
2066
2067 int
2068 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2069                              const MachineInstr *DefMI, unsigned DefIdx,
2070                              const MachineInstr *UseMI, unsigned UseIdx) const {
2071   if (DefMI->isCopyLike() || DefMI->isInsertSubreg() ||
2072       DefMI->isRegSequence() || DefMI->isImplicitDef())
2073     return 1;
2074
2075   const TargetInstrDesc &DefTID = DefMI->getDesc();
2076   if (!ItinData || ItinData->isEmpty())
2077     return DefTID.mayLoad() ? 3 : 1;
2078
2079   const TargetInstrDesc &UseTID = UseMI->getDesc();
2080   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
2081   if (DefMO.getReg() == ARM::CPSR) {
2082     if (DefMI->getOpcode() == ARM::FMSTAT) {
2083       // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
2084       return Subtarget.isCortexA9() ? 1 : 20;
2085     }
2086
2087     // CPSR set and branch can be paired in the same cycle.
2088     if (UseTID.isBranch())
2089       return 0;
2090   }
2091
2092   unsigned DefAlign = DefMI->hasOneMemOperand()
2093     ? (*DefMI->memoperands_begin())->getAlignment() : 0;
2094   unsigned UseAlign = UseMI->hasOneMemOperand()
2095     ? (*UseMI->memoperands_begin())->getAlignment() : 0;
2096   int Latency = getOperandLatency(ItinData, DefTID, DefIdx, DefAlign,
2097                                   UseTID, UseIdx, UseAlign);
2098
2099   if (Latency > 1 &&
2100       (Subtarget.isCortexA8() || Subtarget.isCortexA9())) {
2101     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
2102     // variants are one cycle cheaper.
2103     switch (DefTID.getOpcode()) {
2104     default: break;
2105     case ARM::LDRrs:
2106     case ARM::LDRBrs: {
2107       unsigned ShOpVal = DefMI->getOperand(3).getImm();
2108       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2109       if (ShImm == 0 ||
2110           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
2111         --Latency;
2112       break;
2113     }
2114     case ARM::t2LDRs:
2115     case ARM::t2LDRBs:
2116     case ARM::t2LDRHs:
2117     case ARM::t2LDRSHs: {
2118       // Thumb2 mode: lsl only.
2119       unsigned ShAmt = DefMI->getOperand(3).getImm();
2120       if (ShAmt == 0 || ShAmt == 2)
2121         --Latency;
2122       break;
2123     }
2124     }
2125   }
2126
2127   return Latency;
2128 }
2129
2130 int
2131 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2132                                     SDNode *DefNode, unsigned DefIdx,
2133                                     SDNode *UseNode, unsigned UseIdx) const {
2134   if (!DefNode->isMachineOpcode())
2135     return 1;
2136
2137   const TargetInstrDesc &DefTID = get(DefNode->getMachineOpcode());
2138   if (!ItinData || ItinData->isEmpty())
2139     return DefTID.mayLoad() ? 3 : 1;
2140
2141   if (!UseNode->isMachineOpcode()) {
2142     int Latency = ItinData->getOperandCycle(DefTID.getSchedClass(), DefIdx);
2143     if (Subtarget.isCortexA9())
2144       return Latency <= 2 ? 1 : Latency - 1;
2145     else
2146       return Latency <= 3 ? 1 : Latency - 2;
2147   }
2148
2149   const TargetInstrDesc &UseTID = get(UseNode->getMachineOpcode());
2150   const MachineSDNode *DefMN = dyn_cast<MachineSDNode>(DefNode);
2151   unsigned DefAlign = !DefMN->memoperands_empty()
2152     ? (*DefMN->memoperands_begin())->getAlignment() : 0;
2153   const MachineSDNode *UseMN = dyn_cast<MachineSDNode>(UseNode);
2154   unsigned UseAlign = !UseMN->memoperands_empty()
2155     ? (*UseMN->memoperands_begin())->getAlignment() : 0;
2156   int Latency = getOperandLatency(ItinData, DefTID, DefIdx, DefAlign,
2157                                   UseTID, UseIdx, UseAlign);
2158
2159   if (Latency > 1 &&
2160       (Subtarget.isCortexA8() || Subtarget.isCortexA9())) {
2161     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
2162     // variants are one cycle cheaper.
2163     switch (DefTID.getOpcode()) {
2164     default: break;
2165     case ARM::LDRrs:
2166     case ARM::LDRBrs: {
2167       unsigned ShOpVal =
2168         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
2169       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2170       if (ShImm == 0 ||
2171           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
2172         --Latency;
2173       break;
2174     }
2175     case ARM::t2LDRs:
2176     case ARM::t2LDRBs:
2177     case ARM::t2LDRHs:
2178     case ARM::t2LDRSHs: {
2179       // Thumb2 mode: lsl only.
2180       unsigned ShAmt =
2181         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
2182       if (ShAmt == 0 || ShAmt == 2)
2183         --Latency;
2184       break;
2185     }
2186     }
2187   }
2188
2189   return Latency;
2190 }
2191
2192 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
2193                                       const MachineInstr *MI,
2194                                       unsigned *PredCost) const {
2195   if (MI->isCopyLike() || MI->isInsertSubreg() ||
2196       MI->isRegSequence() || MI->isImplicitDef())
2197     return 1;
2198
2199   if (!ItinData || ItinData->isEmpty())
2200     return 1;
2201
2202   const TargetInstrDesc &TID = MI->getDesc();
2203   unsigned Class = TID.getSchedClass();
2204   unsigned UOps = ItinData->Itineraries[Class].NumMicroOps;
2205   if (PredCost && TID.hasImplicitDefOfPhysReg(ARM::CPSR))
2206     // When predicated, CPSR is an additional source operand for CPSR updating
2207     // instructions, this apparently increases their latencies.
2208     *PredCost = 1;
2209   if (UOps)
2210     return ItinData->getStageLatency(Class);
2211   return getNumMicroOps(ItinData, MI);
2212 }
2213
2214 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
2215                                       SDNode *Node) const {
2216   if (!Node->isMachineOpcode())
2217     return 1;
2218
2219   if (!ItinData || ItinData->isEmpty())
2220     return 1;
2221
2222   unsigned Opcode = Node->getMachineOpcode();
2223   switch (Opcode) {
2224   default:
2225     return ItinData->getStageLatency(get(Opcode).getSchedClass());
2226   case ARM::VLDMQIA:
2227   case ARM::VLDMQDB:
2228   case ARM::VSTMQIA:
2229   case ARM::VSTMQDB:
2230     return 2;
2231   }
2232 }
2233
2234 bool ARMBaseInstrInfo::
2235 hasHighOperandLatency(const InstrItineraryData *ItinData,
2236                       const MachineRegisterInfo *MRI,
2237                       const MachineInstr *DefMI, unsigned DefIdx,
2238                       const MachineInstr *UseMI, unsigned UseIdx) const {
2239   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
2240   unsigned UDomain = UseMI->getDesc().TSFlags & ARMII::DomainMask;
2241   if (Subtarget.isCortexA8() &&
2242       (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
2243     // CortexA8 VFP instructions are not pipelined.
2244     return true;
2245
2246   // Hoist VFP / NEON instructions with 4 or higher latency.
2247   int Latency = getOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
2248   if (Latency <= 3)
2249     return false;
2250   return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
2251          UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
2252 }
2253
2254 bool ARMBaseInstrInfo::
2255 hasLowDefLatency(const InstrItineraryData *ItinData,
2256                  const MachineInstr *DefMI, unsigned DefIdx) const {
2257   if (!ItinData || ItinData->isEmpty())
2258     return false;
2259
2260   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
2261   if (DDomain == ARMII::DomainGeneral) {
2262     unsigned DefClass = DefMI->getDesc().getSchedClass();
2263     int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
2264     return (DefCycle != -1 && DefCycle <= 2);
2265   }
2266   return false;
2267 }
2268
2269 bool
2270 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
2271                                      unsigned &AddSubOpc,
2272                                      bool &NegAcc, bool &HasLane) const {
2273   DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
2274   if (I == MLxEntryMap.end())
2275     return false;
2276
2277   const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
2278   MulOpc = Entry.MulOpc;
2279   AddSubOpc = Entry.AddSubOpc;
2280   NegAcc = Entry.NegAcc;
2281   HasLane = Entry.HasLane;
2282   return true;
2283 }