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