Add comment.
[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 "ARMConstantPoolValue.h"
17 #include "ARMHazardRecognizer.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMRegisterInfo.h"
20 #include "MCTargetDesc/ARMAddressingModes.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalValue.h"
24 #include "llvm/CodeGen/LiveVariables.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGNodes.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/Support/BranchProbability.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
39 #define GET_INSTRINFO_CTOR
40 #include "ARMGenInstrInfo.inc"
41
42 using namespace llvm;
43
44 static cl::opt<bool>
45 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
46                cl::desc("Enable ARM 2-addr to 3-addr conv"));
47
48 static cl::opt<bool>
49 WidenVMOVS("widen-vmovs", cl::Hidden, cl::init(true),
50            cl::desc("Widen ARM vmovs to vmovd when possible"));
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   : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
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 (usePreRAHazardRecognizer()) {
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 MCInstrDesc &MCID = MI->getDesc();
148   unsigned NumOps = MCID.getNumOperands();
149   bool isLoad = !MCID.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::SUBrsi : ARM::ADDrsi), 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   bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function();
407
408   // Shouldn't be a fall through.
409   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
410   assert((Cond.size() == 2 || Cond.size() == 0) &&
411          "ARM branch conditions have two components!");
412
413   if (FBB == 0) {
414     if (Cond.empty()) { // Unconditional branch?
415       if (isThumb)
416         BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).addImm(ARMCC::AL).addReg(0);
417       else
418         BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
419     } else
420       BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
421         .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
422     return 1;
423   }
424
425   // Two-way conditional branch.
426   BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
427     .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
428   if (isThumb)
429     BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).addImm(ARMCC::AL).addReg(0);
430   else
431     BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
432   return 2;
433 }
434
435 bool ARMBaseInstrInfo::
436 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
437   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
438   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
439   return false;
440 }
441
442 bool ARMBaseInstrInfo::
443 PredicateInstruction(MachineInstr *MI,
444                      const SmallVectorImpl<MachineOperand> &Pred) const {
445   unsigned Opc = MI->getOpcode();
446   if (isUncondBranchOpcode(Opc)) {
447     MI->setDesc(get(getMatchingCondBranchOpcode(Opc)));
448     MI->addOperand(MachineOperand::CreateImm(Pred[0].getImm()));
449     MI->addOperand(MachineOperand::CreateReg(Pred[1].getReg(), false));
450     return true;
451   }
452
453   int PIdx = MI->findFirstPredOperandIdx();
454   if (PIdx != -1) {
455     MachineOperand &PMO = MI->getOperand(PIdx);
456     PMO.setImm(Pred[0].getImm());
457     MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
458     return true;
459   }
460   return false;
461 }
462
463 bool ARMBaseInstrInfo::
464 SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
465                   const SmallVectorImpl<MachineOperand> &Pred2) const {
466   if (Pred1.size() > 2 || Pred2.size() > 2)
467     return false;
468
469   ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
470   ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
471   if (CC1 == CC2)
472     return true;
473
474   switch (CC1) {
475   default:
476     return false;
477   case ARMCC::AL:
478     return true;
479   case ARMCC::HS:
480     return CC2 == ARMCC::HI;
481   case ARMCC::LS:
482     return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
483   case ARMCC::GE:
484     return CC2 == ARMCC::GT;
485   case ARMCC::LE:
486     return CC2 == ARMCC::LT;
487   }
488 }
489
490 bool ARMBaseInstrInfo::DefinesPredicate(MachineInstr *MI,
491                                     std::vector<MachineOperand> &Pred) const {
492   // FIXME: This confuses implicit_def with optional CPSR def.
493   const MCInstrDesc &MCID = MI->getDesc();
494   if (!MCID.getImplicitDefs() && !MCID.hasOptionalDef())
495     return false;
496
497   bool Found = false;
498   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
499     const MachineOperand &MO = MI->getOperand(i);
500     if (MO.isReg() && MO.getReg() == ARM::CPSR) {
501       Pred.push_back(MO);
502       Found = true;
503     }
504   }
505
506   return Found;
507 }
508
509 /// isPredicable - Return true if the specified instruction can be predicated.
510 /// By default, this returns true for every instruction with a
511 /// PredicateOperand.
512 bool ARMBaseInstrInfo::isPredicable(MachineInstr *MI) const {
513   const MCInstrDesc &MCID = MI->getDesc();
514   if (!MCID.isPredicable())
515     return false;
516
517   if ((MCID.TSFlags & ARMII::DomainMask) == ARMII::DomainNEON) {
518     ARMFunctionInfo *AFI =
519       MI->getParent()->getParent()->getInfo<ARMFunctionInfo>();
520     return AFI->isThumb2Function();
521   }
522   return true;
523 }
524
525 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing.
526 LLVM_ATTRIBUTE_NOINLINE
527 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
528                                 unsigned JTI);
529 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
530                                 unsigned JTI) {
531   assert(JTI < JT.size());
532   return JT[JTI].MBBs.size();
533 }
534
535 /// GetInstSize - Return the size of the specified MachineInstr.
536 ///
537 unsigned ARMBaseInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
538   const MachineBasicBlock &MBB = *MI->getParent();
539   const MachineFunction *MF = MBB.getParent();
540   const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
541
542   const MCInstrDesc &MCID = MI->getDesc();
543   if (MCID.getSize())
544     return MCID.getSize();
545
546     // If this machine instr is an inline asm, measure it.
547     if (MI->getOpcode() == ARM::INLINEASM)
548       return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
549     if (MI->isLabel())
550       return 0;
551   unsigned Opc = MI->getOpcode();
552     switch (Opc) {
553     case TargetOpcode::IMPLICIT_DEF:
554     case TargetOpcode::KILL:
555     case TargetOpcode::PROLOG_LABEL:
556     case TargetOpcode::EH_LABEL:
557     case TargetOpcode::DBG_VALUE:
558       return 0;
559     case ARM::MOVi16_ga_pcrel:
560     case ARM::MOVTi16_ga_pcrel:
561     case ARM::t2MOVi16_ga_pcrel:
562     case ARM::t2MOVTi16_ga_pcrel:
563       return 4;
564     case ARM::MOVi32imm:
565     case ARM::t2MOVi32imm:
566       return 8;
567     case ARM::CONSTPOOL_ENTRY:
568       // If this machine instr is a constant pool entry, its size is recorded as
569       // operand #2.
570       return MI->getOperand(2).getImm();
571     case ARM::Int_eh_sjlj_longjmp:
572       return 16;
573     case ARM::tInt_eh_sjlj_longjmp:
574       return 10;
575     case ARM::Int_eh_sjlj_setjmp:
576     case ARM::Int_eh_sjlj_setjmp_nofp:
577       return 20;
578     case ARM::tInt_eh_sjlj_setjmp:
579     case ARM::t2Int_eh_sjlj_setjmp:
580     case ARM::t2Int_eh_sjlj_setjmp_nofp:
581       return 12;
582     case ARM::BR_JTr:
583     case ARM::BR_JTm:
584     case ARM::BR_JTadd:
585     case ARM::tBR_JTr:
586     case ARM::t2BR_JT:
587     case ARM::t2TBB_JT:
588     case ARM::t2TBH_JT: {
589       // These are jumptable branches, i.e. a branch followed by an inlined
590       // jumptable. The size is 4 + 4 * number of entries. For TBB, each
591       // entry is one byte; TBH two byte each.
592       unsigned EntrySize = (Opc == ARM::t2TBB_JT)
593         ? 1 : ((Opc == ARM::t2TBH_JT) ? 2 : 4);
594       unsigned NumOps = MCID.getNumOperands();
595       MachineOperand JTOP =
596         MI->getOperand(NumOps - (MCID.isPredicable() ? 3 : 2));
597       unsigned JTI = JTOP.getIndex();
598       const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
599       assert(MJTI != 0);
600       const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
601       assert(JTI < JT.size());
602       // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
603       // 4 aligned. The assembler / linker may add 2 byte padding just before
604       // the JT entries.  The size does not include this padding; the
605       // constant islands pass does separate bookkeeping for it.
606       // FIXME: If we know the size of the function is less than (1 << 16) *2
607       // bytes, we can use 16-bit entries instead. Then there won't be an
608       // alignment issue.
609       unsigned InstSize = (Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT) ? 2 : 4;
610       unsigned NumEntries = getNumJTEntries(JT, JTI);
611       if (Opc == ARM::t2TBB_JT && (NumEntries & 1))
612         // Make sure the instruction that follows TBB is 2-byte aligned.
613         // FIXME: Constant island pass should insert an "ALIGN" instruction
614         // instead.
615         ++NumEntries;
616       return NumEntries * EntrySize + InstSize;
617     }
618     default:
619       // Otherwise, pseudo-instruction sizes are zero.
620       return 0;
621     }
622   return 0; // Not reached
623 }
624
625 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
626                                    MachineBasicBlock::iterator I, DebugLoc DL,
627                                    unsigned DestReg, unsigned SrcReg,
628                                    bool KillSrc) const {
629   bool GPRDest = ARM::GPRRegClass.contains(DestReg);
630   bool GPRSrc  = ARM::GPRRegClass.contains(SrcReg);
631
632   if (GPRDest && GPRSrc) {
633     AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
634                                   .addReg(SrcReg, getKillRegState(KillSrc))));
635     return;
636   }
637
638   bool SPRDest = ARM::SPRRegClass.contains(DestReg);
639   bool SPRSrc  = ARM::SPRRegClass.contains(SrcReg);
640
641   unsigned Opc = 0;
642   if (SPRDest && SPRSrc)
643     Opc = ARM::VMOVS;
644   else if (GPRDest && SPRSrc)
645     Opc = ARM::VMOVRS;
646   else if (SPRDest && GPRSrc)
647     Opc = ARM::VMOVSR;
648   else if (ARM::DPRRegClass.contains(DestReg, SrcReg))
649     Opc = ARM::VMOVD;
650   else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
651     Opc = ARM::VORRq;
652
653   if (Opc) {
654     MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
655     MIB.addReg(SrcReg, getKillRegState(KillSrc));
656     if (Opc == ARM::VORRq)
657       MIB.addReg(SrcReg, getKillRegState(KillSrc));
658     AddDefaultPred(MIB);
659     return;
660   }
661
662   // Generate instructions for VMOVQQ and VMOVQQQQ pseudos in place.
663   if (ARM::QQPRRegClass.contains(DestReg, SrcReg) ||
664       ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) {
665     const TargetRegisterInfo *TRI = &getRegisterInfo();
666     assert(ARM::qsub_0 + 3 == ARM::qsub_3 && "Expected contiguous enum.");
667     unsigned EndSubReg = ARM::QQPRRegClass.contains(DestReg, SrcReg) ?
668       ARM::qsub_1 : ARM::qsub_3;
669     for (unsigned i = ARM::qsub_0, e = EndSubReg + 1; i != e; ++i) {
670       unsigned Dst = TRI->getSubReg(DestReg, i);
671       unsigned Src = TRI->getSubReg(SrcReg, i);
672       MachineInstrBuilder Mov =
673         AddDefaultPred(BuildMI(MBB, I, I->getDebugLoc(), get(ARM::VORRq))
674                        .addReg(Dst, RegState::Define)
675                        .addReg(Src, getKillRegState(KillSrc))
676                        .addReg(Src, getKillRegState(KillSrc)));
677       if (i == EndSubReg) {
678         Mov->addRegisterDefined(DestReg, TRI);
679         if (KillSrc)
680           Mov->addRegisterKilled(SrcReg, TRI);
681       }
682     }
683     return;
684   }
685   llvm_unreachable("Impossible reg-to-reg copy");
686 }
687
688 static const
689 MachineInstrBuilder &AddDReg(MachineInstrBuilder &MIB,
690                              unsigned Reg, unsigned SubIdx, unsigned State,
691                              const TargetRegisterInfo *TRI) {
692   if (!SubIdx)
693     return MIB.addReg(Reg, State);
694
695   if (TargetRegisterInfo::isPhysicalRegister(Reg))
696     return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
697   return MIB.addReg(Reg, State, SubIdx);
698 }
699
700 void ARMBaseInstrInfo::
701 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
702                     unsigned SrcReg, bool isKill, int FI,
703                     const TargetRegisterClass *RC,
704                     const TargetRegisterInfo *TRI) const {
705   DebugLoc DL;
706   if (I != MBB.end()) DL = I->getDebugLoc();
707   MachineFunction &MF = *MBB.getParent();
708   MachineFrameInfo &MFI = *MF.getFrameInfo();
709   unsigned Align = MFI.getObjectAlignment(FI);
710
711   MachineMemOperand *MMO =
712     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
713                             MachineMemOperand::MOStore,
714                             MFI.getObjectSize(FI),
715                             Align);
716
717   switch (RC->getSize()) {
718     case 4:
719       if (ARM::GPRRegClass.hasSubClassEq(RC)) {
720         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STRi12))
721                    .addReg(SrcReg, getKillRegState(isKill))
722                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
723       } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
724         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRS))
725                    .addReg(SrcReg, getKillRegState(isKill))
726                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
727       } else
728         llvm_unreachable("Unknown reg class!");
729       break;
730     case 8:
731       if (ARM::DPRRegClass.hasSubClassEq(RC)) {
732         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRD))
733                    .addReg(SrcReg, getKillRegState(isKill))
734                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
735       } else
736         llvm_unreachable("Unknown reg class!");
737       break;
738     case 16:
739       if (ARM::QPRRegClass.hasSubClassEq(RC)) {
740         if (Align >= 16 && getRegisterInfo().needsStackRealignment(MF)) {
741           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q64Pseudo))
742                      .addFrameIndex(FI).addImm(16)
743                      .addReg(SrcReg, getKillRegState(isKill))
744                      .addMemOperand(MMO));
745         } else {
746           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMQIA))
747                      .addReg(SrcReg, getKillRegState(isKill))
748                      .addFrameIndex(FI)
749                      .addMemOperand(MMO));
750         }
751       } else
752         llvm_unreachable("Unknown reg class!");
753       break;
754     case 32:
755       if (ARM::QQPRRegClass.hasSubClassEq(RC)) {
756         if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
757           // FIXME: It's possible to only store part of the QQ register if the
758           // spilled def has a sub-register index.
759           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64QPseudo))
760                      .addFrameIndex(FI).addImm(16)
761                      .addReg(SrcReg, getKillRegState(isKill))
762                      .addMemOperand(MMO));
763         } else {
764           MachineInstrBuilder MIB =
765           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
766                        .addFrameIndex(FI))
767                        .addMemOperand(MMO);
768           MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
769           MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
770           MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
771                 AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
772         }
773       } else
774         llvm_unreachable("Unknown reg class!");
775       break;
776     case 64:
777       if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
778         MachineInstrBuilder MIB =
779           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
780                          .addFrameIndex(FI))
781                          .addMemOperand(MMO);
782         MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
783         MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
784         MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
785         MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
786         MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
787         MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
788         MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
789               AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
790       } else
791         llvm_unreachable("Unknown reg class!");
792       break;
793     default:
794       llvm_unreachable("Unknown reg class!");
795   }
796 }
797
798 unsigned
799 ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
800                                      int &FrameIndex) const {
801   switch (MI->getOpcode()) {
802   default: break;
803   case ARM::STRrs:
804   case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
805     if (MI->getOperand(1).isFI() &&
806         MI->getOperand(2).isReg() &&
807         MI->getOperand(3).isImm() &&
808         MI->getOperand(2).getReg() == 0 &&
809         MI->getOperand(3).getImm() == 0) {
810       FrameIndex = MI->getOperand(1).getIndex();
811       return MI->getOperand(0).getReg();
812     }
813     break;
814   case ARM::STRi12:
815   case ARM::t2STRi12:
816   case ARM::tSTRspi:
817   case ARM::VSTRD:
818   case ARM::VSTRS:
819     if (MI->getOperand(1).isFI() &&
820         MI->getOperand(2).isImm() &&
821         MI->getOperand(2).getImm() == 0) {
822       FrameIndex = MI->getOperand(1).getIndex();
823       return MI->getOperand(0).getReg();
824     }
825     break;
826   case ARM::VST1q64Pseudo:
827     if (MI->getOperand(0).isFI() &&
828         MI->getOperand(2).getSubReg() == 0) {
829       FrameIndex = MI->getOperand(0).getIndex();
830       return MI->getOperand(2).getReg();
831     }
832     break;
833   case ARM::VSTMQIA:
834     if (MI->getOperand(1).isFI() &&
835         MI->getOperand(0).getSubReg() == 0) {
836       FrameIndex = MI->getOperand(1).getIndex();
837       return MI->getOperand(0).getReg();
838     }
839     break;
840   }
841
842   return 0;
843 }
844
845 unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr *MI,
846                                                     int &FrameIndex) const {
847   const MachineMemOperand *Dummy;
848   return MI->getDesc().mayStore() && hasStoreToStackSlot(MI, Dummy, FrameIndex);
849 }
850
851 void ARMBaseInstrInfo::
852 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
853                      unsigned DestReg, int FI,
854                      const TargetRegisterClass *RC,
855                      const TargetRegisterInfo *TRI) const {
856   DebugLoc DL;
857   if (I != MBB.end()) DL = I->getDebugLoc();
858   MachineFunction &MF = *MBB.getParent();
859   MachineFrameInfo &MFI = *MF.getFrameInfo();
860   unsigned Align = MFI.getObjectAlignment(FI);
861   MachineMemOperand *MMO =
862     MF.getMachineMemOperand(
863                     MachinePointerInfo::getFixedStack(FI),
864                             MachineMemOperand::MOLoad,
865                             MFI.getObjectSize(FI),
866                             Align);
867
868   switch (RC->getSize()) {
869   case 4:
870     if (ARM::GPRRegClass.hasSubClassEq(RC)) {
871       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
872                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
873
874     } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
875       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
876                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
877     } else
878       llvm_unreachable("Unknown reg class!");
879     break;
880   case 8:
881     if (ARM::DPRRegClass.hasSubClassEq(RC)) {
882       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
883                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
884     } else
885       llvm_unreachable("Unknown reg class!");
886     break;
887   case 16:
888     if (ARM::QPRRegClass.hasSubClassEq(RC)) {
889       if (Align >= 16 && getRegisterInfo().needsStackRealignment(MF)) {
890         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q64Pseudo), DestReg)
891                      .addFrameIndex(FI).addImm(16)
892                      .addMemOperand(MMO));
893       } else {
894         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
895                        .addFrameIndex(FI)
896                        .addMemOperand(MMO));
897       }
898     } else
899       llvm_unreachable("Unknown reg class!");
900     break;
901   case 32:
902     if (ARM::QQPRRegClass.hasSubClassEq(RC)) {
903       if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
904         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
905                      .addFrameIndex(FI).addImm(16)
906                      .addMemOperand(MMO));
907       } else {
908         MachineInstrBuilder MIB =
909         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
910                        .addFrameIndex(FI))
911                        .addMemOperand(MMO);
912         MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
913         MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
914         MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
915         MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
916         MIB.addReg(DestReg, RegState::Define | RegState::Implicit);
917       }
918     } else
919       llvm_unreachable("Unknown reg class!");
920     break;
921   case 64:
922     if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
923       MachineInstrBuilder MIB =
924       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
925                      .addFrameIndex(FI))
926                      .addMemOperand(MMO);
927       MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
928       MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
929       MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
930       MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
931       MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::Define, TRI);
932       MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::Define, TRI);
933       MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::Define, TRI);
934       MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::Define, TRI);
935       MIB.addReg(DestReg, RegState::Define | RegState::Implicit);
936     } else
937       llvm_unreachable("Unknown reg class!");
938     break;
939   default:
940     llvm_unreachable("Unknown regclass!");
941   }
942 }
943
944 unsigned
945 ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
946                                       int &FrameIndex) const {
947   switch (MI->getOpcode()) {
948   default: break;
949   case ARM::LDRrs:
950   case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
951     if (MI->getOperand(1).isFI() &&
952         MI->getOperand(2).isReg() &&
953         MI->getOperand(3).isImm() &&
954         MI->getOperand(2).getReg() == 0 &&
955         MI->getOperand(3).getImm() == 0) {
956       FrameIndex = MI->getOperand(1).getIndex();
957       return MI->getOperand(0).getReg();
958     }
959     break;
960   case ARM::LDRi12:
961   case ARM::t2LDRi12:
962   case ARM::tLDRspi:
963   case ARM::VLDRD:
964   case ARM::VLDRS:
965     if (MI->getOperand(1).isFI() &&
966         MI->getOperand(2).isImm() &&
967         MI->getOperand(2).getImm() == 0) {
968       FrameIndex = MI->getOperand(1).getIndex();
969       return MI->getOperand(0).getReg();
970     }
971     break;
972   case ARM::VLD1q64Pseudo:
973     if (MI->getOperand(1).isFI() &&
974         MI->getOperand(0).getSubReg() == 0) {
975       FrameIndex = MI->getOperand(1).getIndex();
976       return MI->getOperand(0).getReg();
977     }
978     break;
979   case ARM::VLDMQIA:
980     if (MI->getOperand(1).isFI() &&
981         MI->getOperand(0).getSubReg() == 0) {
982       FrameIndex = MI->getOperand(1).getIndex();
983       return MI->getOperand(0).getReg();
984     }
985     break;
986   }
987
988   return 0;
989 }
990
991 unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr *MI,
992                                              int &FrameIndex) const {
993   const MachineMemOperand *Dummy;
994   return MI->getDesc().mayLoad() && hasLoadFromStackSlot(MI, Dummy, FrameIndex);
995 }
996
997 bool ARMBaseInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const{
998   // This hook gets to expand COPY instructions before they become
999   // copyPhysReg() calls.  Look for VMOVS instructions that can legally be
1000   // widened to VMOVD.  We prefer the VMOVD when possible because it may be
1001   // changed into a VORR that can go down the NEON pipeline.
1002   if (!WidenVMOVS || !MI->isCopy())
1003     return false;
1004
1005   // Look for a copy between even S-registers.  That is where we keep floats
1006   // when using NEON v2f32 instructions for f32 arithmetic.
1007   unsigned DstRegS = MI->getOperand(0).getReg();
1008   unsigned SrcRegS = MI->getOperand(1).getReg();
1009   if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS))
1010     return false;
1011
1012   const TargetRegisterInfo *TRI = &getRegisterInfo();
1013   unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0,
1014                                               &ARM::DPRRegClass);
1015   unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0,
1016                                               &ARM::DPRRegClass);
1017   if (!DstRegD || !SrcRegD)
1018     return false;
1019
1020   // We want to widen this into a DstRegD = VMOVD SrcRegD copy.  This is only
1021   // legal if the COPY already defines the full DstRegD, and it isn't a
1022   // sub-register insertion.
1023   if (!MI->definesRegister(DstRegD, TRI) || MI->readsRegister(DstRegD, TRI))
1024     return false;
1025
1026   // A dead copy shouldn't show up here, but reject it just in case.
1027   if (MI->getOperand(0).isDead())
1028     return false;
1029
1030   // All clear, widen the COPY.
1031   DEBUG(dbgs() << "widening:    " << *MI);
1032
1033   // Get rid of the old <imp-def> of DstRegD.  Leave it if it defines a Q-reg
1034   // or some other super-register.
1035   int ImpDefIdx = MI->findRegisterDefOperandIdx(DstRegD);
1036   if (ImpDefIdx != -1)
1037     MI->RemoveOperand(ImpDefIdx);
1038
1039   // Change the opcode and operands.
1040   MI->setDesc(get(ARM::VMOVD));
1041   MI->getOperand(0).setReg(DstRegD);
1042   MI->getOperand(1).setReg(SrcRegD);
1043   AddDefaultPred(MachineInstrBuilder(MI));
1044
1045   // We are now reading SrcRegD instead of SrcRegS.  This may upset the
1046   // register scavenger and machine verifier, so we need to indicate that we
1047   // are reading an undefined value from SrcRegD, but a proper value from
1048   // SrcRegS.
1049   MI->getOperand(1).setIsUndef();
1050   MachineInstrBuilder(MI).addReg(SrcRegS, RegState::Implicit);
1051
1052   // SrcRegD may actually contain an unrelated value in the ssub_1
1053   // sub-register.  Don't kill it.  Only kill the ssub_0 sub-register.
1054   if (MI->getOperand(1).isKill()) {
1055     MI->getOperand(1).setIsKill(false);
1056     MI->addRegisterKilled(SrcRegS, TRI, true);
1057   }
1058
1059   DEBUG(dbgs() << "replaced by: " << *MI);
1060   return true;
1061 }
1062
1063 MachineInstr*
1064 ARMBaseInstrInfo::emitFrameIndexDebugValue(MachineFunction &MF,
1065                                            int FrameIx, uint64_t Offset,
1066                                            const MDNode *MDPtr,
1067                                            DebugLoc DL) const {
1068   MachineInstrBuilder MIB = BuildMI(MF, DL, get(ARM::DBG_VALUE))
1069     .addFrameIndex(FrameIx).addImm(0).addImm(Offset).addMetadata(MDPtr);
1070   return &*MIB;
1071 }
1072
1073 /// Create a copy of a const pool value. Update CPI to the new index and return
1074 /// the label UID.
1075 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
1076   MachineConstantPool *MCP = MF.getConstantPool();
1077   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1078
1079   const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
1080   assert(MCPE.isMachineConstantPoolEntry() &&
1081          "Expecting a machine constantpool entry!");
1082   ARMConstantPoolValue *ACPV =
1083     static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
1084
1085   unsigned PCLabelId = AFI->createPICLabelUId();
1086   ARMConstantPoolValue *NewCPV = 0;
1087   // FIXME: The below assumes PIC relocation model and that the function
1088   // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
1089   // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
1090   // instructions, so that's probably OK, but is PIC always correct when
1091   // we get here?
1092   if (ACPV->isGlobalValue())
1093     NewCPV = ARMConstantPoolConstant::
1094       Create(cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId,
1095              ARMCP::CPValue, 4);
1096   else if (ACPV->isExtSymbol())
1097     NewCPV = ARMConstantPoolSymbol::
1098       Create(MF.getFunction()->getContext(),
1099              cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4);
1100   else if (ACPV->isBlockAddress())
1101     NewCPV = ARMConstantPoolConstant::
1102       Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId,
1103              ARMCP::CPBlockAddress, 4);
1104   else if (ACPV->isLSDA())
1105     NewCPV = ARMConstantPoolConstant::Create(MF.getFunction(), PCLabelId,
1106                                              ARMCP::CPLSDA, 4);
1107   else if (ACPV->isMachineBasicBlock())
1108     NewCPV = ARMConstantPoolMBB::
1109       Create(MF.getFunction()->getContext(),
1110              cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4);
1111   else
1112     llvm_unreachable("Unexpected ARM constantpool value type!!");
1113   CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
1114   return PCLabelId;
1115 }
1116
1117 void ARMBaseInstrInfo::
1118 reMaterialize(MachineBasicBlock &MBB,
1119               MachineBasicBlock::iterator I,
1120               unsigned DestReg, unsigned SubIdx,
1121               const MachineInstr *Orig,
1122               const TargetRegisterInfo &TRI) const {
1123   unsigned Opcode = Orig->getOpcode();
1124   switch (Opcode) {
1125   default: {
1126     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
1127     MI->substituteRegister(Orig->getOperand(0).getReg(), DestReg, SubIdx, TRI);
1128     MBB.insert(I, MI);
1129     break;
1130   }
1131   case ARM::tLDRpci_pic:
1132   case ARM::t2LDRpci_pic: {
1133     MachineFunction &MF = *MBB.getParent();
1134     unsigned CPI = Orig->getOperand(1).getIndex();
1135     unsigned PCLabelId = duplicateCPV(MF, CPI);
1136     MachineInstrBuilder MIB = BuildMI(MBB, I, Orig->getDebugLoc(), get(Opcode),
1137                                       DestReg)
1138       .addConstantPoolIndex(CPI).addImm(PCLabelId);
1139     MIB->setMemRefs(Orig->memoperands_begin(), Orig->memoperands_end());
1140     break;
1141   }
1142   }
1143 }
1144
1145 MachineInstr *
1146 ARMBaseInstrInfo::duplicate(MachineInstr *Orig, MachineFunction &MF) const {
1147   MachineInstr *MI = TargetInstrInfoImpl::duplicate(Orig, MF);
1148   switch(Orig->getOpcode()) {
1149   case ARM::tLDRpci_pic:
1150   case ARM::t2LDRpci_pic: {
1151     unsigned CPI = Orig->getOperand(1).getIndex();
1152     unsigned PCLabelId = duplicateCPV(MF, CPI);
1153     Orig->getOperand(1).setIndex(CPI);
1154     Orig->getOperand(2).setImm(PCLabelId);
1155     break;
1156   }
1157   }
1158   return MI;
1159 }
1160
1161 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr *MI0,
1162                                         const MachineInstr *MI1,
1163                                         const MachineRegisterInfo *MRI) const {
1164   int Opcode = MI0->getOpcode();
1165   if (Opcode == ARM::t2LDRpci ||
1166       Opcode == ARM::t2LDRpci_pic ||
1167       Opcode == ARM::tLDRpci ||
1168       Opcode == ARM::tLDRpci_pic ||
1169       Opcode == ARM::MOV_ga_dyn ||
1170       Opcode == ARM::MOV_ga_pcrel ||
1171       Opcode == ARM::MOV_ga_pcrel_ldr ||
1172       Opcode == ARM::t2MOV_ga_dyn ||
1173       Opcode == ARM::t2MOV_ga_pcrel) {
1174     if (MI1->getOpcode() != Opcode)
1175       return false;
1176     if (MI0->getNumOperands() != MI1->getNumOperands())
1177       return false;
1178
1179     const MachineOperand &MO0 = MI0->getOperand(1);
1180     const MachineOperand &MO1 = MI1->getOperand(1);
1181     if (MO0.getOffset() != MO1.getOffset())
1182       return false;
1183
1184     if (Opcode == ARM::MOV_ga_dyn ||
1185         Opcode == ARM::MOV_ga_pcrel ||
1186         Opcode == ARM::MOV_ga_pcrel_ldr ||
1187         Opcode == ARM::t2MOV_ga_dyn ||
1188         Opcode == ARM::t2MOV_ga_pcrel)
1189       // Ignore the PC labels.
1190       return MO0.getGlobal() == MO1.getGlobal();
1191
1192     const MachineFunction *MF = MI0->getParent()->getParent();
1193     const MachineConstantPool *MCP = MF->getConstantPool();
1194     int CPI0 = MO0.getIndex();
1195     int CPI1 = MO1.getIndex();
1196     const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1197     const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1198     bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
1199     bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
1200     if (isARMCP0 && isARMCP1) {
1201       ARMConstantPoolValue *ACPV0 =
1202         static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1203       ARMConstantPoolValue *ACPV1 =
1204         static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1205       return ACPV0->hasSameValue(ACPV1);
1206     } else if (!isARMCP0 && !isARMCP1) {
1207       return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
1208     }
1209     return false;
1210   } else if (Opcode == ARM::PICLDR) {
1211     if (MI1->getOpcode() != Opcode)
1212       return false;
1213     if (MI0->getNumOperands() != MI1->getNumOperands())
1214       return false;
1215
1216     unsigned Addr0 = MI0->getOperand(1).getReg();
1217     unsigned Addr1 = MI1->getOperand(1).getReg();
1218     if (Addr0 != Addr1) {
1219       if (!MRI ||
1220           !TargetRegisterInfo::isVirtualRegister(Addr0) ||
1221           !TargetRegisterInfo::isVirtualRegister(Addr1))
1222         return false;
1223
1224       // This assumes SSA form.
1225       MachineInstr *Def0 = MRI->getVRegDef(Addr0);
1226       MachineInstr *Def1 = MRI->getVRegDef(Addr1);
1227       // Check if the loaded value, e.g. a constantpool of a global address, are
1228       // the same.
1229       if (!produceSameValue(Def0, Def1, MRI))
1230         return false;
1231     }
1232
1233     for (unsigned i = 3, e = MI0->getNumOperands(); i != e; ++i) {
1234       // %vreg12<def> = PICLDR %vreg11, 0, pred:14, pred:%noreg
1235       const MachineOperand &MO0 = MI0->getOperand(i);
1236       const MachineOperand &MO1 = MI1->getOperand(i);
1237       if (!MO0.isIdenticalTo(MO1))
1238         return false;
1239     }
1240     return true;
1241   }
1242
1243   return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1244 }
1245
1246 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1247 /// determine if two loads are loading from the same base address. It should
1248 /// only return true if the base pointers are the same and the only differences
1249 /// between the two addresses is the offset. It also returns the offsets by
1250 /// reference.
1251 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1252                                                int64_t &Offset1,
1253                                                int64_t &Offset2) const {
1254   // Don't worry about Thumb: just ARM and Thumb2.
1255   if (Subtarget.isThumb1Only()) return false;
1256
1257   if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1258     return false;
1259
1260   switch (Load1->getMachineOpcode()) {
1261   default:
1262     return false;
1263   case ARM::LDRi12:
1264   case ARM::LDRBi12:
1265   case ARM::LDRD:
1266   case ARM::LDRH:
1267   case ARM::LDRSB:
1268   case ARM::LDRSH:
1269   case ARM::VLDRD:
1270   case ARM::VLDRS:
1271   case ARM::t2LDRi8:
1272   case ARM::t2LDRDi8:
1273   case ARM::t2LDRSHi8:
1274   case ARM::t2LDRi12:
1275   case ARM::t2LDRSHi12:
1276     break;
1277   }
1278
1279   switch (Load2->getMachineOpcode()) {
1280   default:
1281     return false;
1282   case ARM::LDRi12:
1283   case ARM::LDRBi12:
1284   case ARM::LDRD:
1285   case ARM::LDRH:
1286   case ARM::LDRSB:
1287   case ARM::LDRSH:
1288   case ARM::VLDRD:
1289   case ARM::VLDRS:
1290   case ARM::t2LDRi8:
1291   case ARM::t2LDRDi8:
1292   case ARM::t2LDRSHi8:
1293   case ARM::t2LDRi12:
1294   case ARM::t2LDRSHi12:
1295     break;
1296   }
1297
1298   // Check if base addresses and chain operands match.
1299   if (Load1->getOperand(0) != Load2->getOperand(0) ||
1300       Load1->getOperand(4) != Load2->getOperand(4))
1301     return false;
1302
1303   // Index should be Reg0.
1304   if (Load1->getOperand(3) != Load2->getOperand(3))
1305     return false;
1306
1307   // Determine the offsets.
1308   if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1309       isa<ConstantSDNode>(Load2->getOperand(1))) {
1310     Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1311     Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1312     return true;
1313   }
1314
1315   return false;
1316 }
1317
1318 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1319 /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
1320 /// be scheduled togther. On some targets if two loads are loading from
1321 /// addresses in the same cache line, it's better if they are scheduled
1322 /// together. This function takes two integers that represent the load offsets
1323 /// from the common base address. It returns true if it decides it's desirable
1324 /// to schedule the two loads together. "NumLoads" is the number of loads that
1325 /// have already been scheduled after Load1.
1326 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1327                                                int64_t Offset1, int64_t Offset2,
1328                                                unsigned NumLoads) const {
1329   // Don't worry about Thumb: just ARM and Thumb2.
1330   if (Subtarget.isThumb1Only()) return false;
1331
1332   assert(Offset2 > Offset1);
1333
1334   if ((Offset2 - Offset1) / 8 > 64)
1335     return false;
1336
1337   if (Load1->getMachineOpcode() != Load2->getMachineOpcode())
1338     return false;  // FIXME: overly conservative?
1339
1340   // Four loads in a row should be sufficient.
1341   if (NumLoads >= 3)
1342     return false;
1343
1344   return true;
1345 }
1346
1347 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1348                                             const MachineBasicBlock *MBB,
1349                                             const MachineFunction &MF) const {
1350   // Debug info is never a scheduling boundary. It's necessary to be explicit
1351   // due to the special treatment of IT instructions below, otherwise a
1352   // dbg_value followed by an IT will result in the IT instruction being
1353   // considered a scheduling hazard, which is wrong. It should be the actual
1354   // instruction preceding the dbg_value instruction(s), just like it is
1355   // when debug info is not present.
1356   if (MI->isDebugValue())
1357     return false;
1358
1359   // Terminators and labels can't be scheduled around.
1360   if (MI->getDesc().isTerminator() || MI->isLabel())
1361     return true;
1362
1363   // Treat the start of the IT block as a scheduling boundary, but schedule
1364   // t2IT along with all instructions following it.
1365   // FIXME: This is a big hammer. But the alternative is to add all potential
1366   // true and anti dependencies to IT block instructions as implicit operands
1367   // to the t2IT instruction. The added compile time and complexity does not
1368   // seem worth it.
1369   MachineBasicBlock::const_iterator I = MI;
1370   // Make sure to skip any dbg_value instructions
1371   while (++I != MBB->end() && I->isDebugValue())
1372     ;
1373   if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
1374     return true;
1375
1376   // Don't attempt to schedule around any instruction that defines
1377   // a stack-oriented pointer, as it's unlikely to be profitable. This
1378   // saves compile time, because it doesn't require every single
1379   // stack slot reference to depend on the instruction that does the
1380   // modification.
1381   if (MI->definesRegister(ARM::SP))
1382     return true;
1383
1384   return false;
1385 }
1386
1387 bool ARMBaseInstrInfo::
1388 isProfitableToIfCvt(MachineBasicBlock &MBB,
1389                     unsigned NumCycles, unsigned ExtraPredCycles,
1390                     const BranchProbability &Probability) const {
1391   if (!NumCycles)
1392     return false;
1393
1394   // Attempt to estimate the relative costs of predication versus branching.
1395   unsigned UnpredCost = Probability.getNumerator() * NumCycles;
1396   UnpredCost /= Probability.getDenominator();
1397   UnpredCost += 1; // The branch itself
1398   UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1399
1400   return (NumCycles + ExtraPredCycles) <= UnpredCost;
1401 }
1402
1403 bool ARMBaseInstrInfo::
1404 isProfitableToIfCvt(MachineBasicBlock &TMBB,
1405                     unsigned TCycles, unsigned TExtra,
1406                     MachineBasicBlock &FMBB,
1407                     unsigned FCycles, unsigned FExtra,
1408                     const BranchProbability &Probability) const {
1409   if (!TCycles || !FCycles)
1410     return false;
1411
1412   // Attempt to estimate the relative costs of predication versus branching.
1413   unsigned TUnpredCost = Probability.getNumerator() * TCycles;
1414   TUnpredCost /= Probability.getDenominator();
1415
1416   uint32_t Comp = Probability.getDenominator() - Probability.getNumerator();
1417   unsigned FUnpredCost = Comp * FCycles;
1418   FUnpredCost /= Probability.getDenominator();
1419
1420   unsigned UnpredCost = TUnpredCost + FUnpredCost;
1421   UnpredCost += 1; // The branch itself
1422   UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1423
1424   return (TCycles + FCycles + TExtra + FExtra) <= UnpredCost;
1425 }
1426
1427 /// getInstrPredicate - If instruction is predicated, returns its predicate
1428 /// condition, otherwise returns AL. It also returns the condition code
1429 /// register by reference.
1430 ARMCC::CondCodes
1431 llvm::getInstrPredicate(const MachineInstr *MI, unsigned &PredReg) {
1432   int PIdx = MI->findFirstPredOperandIdx();
1433   if (PIdx == -1) {
1434     PredReg = 0;
1435     return ARMCC::AL;
1436   }
1437
1438   PredReg = MI->getOperand(PIdx+1).getReg();
1439   return (ARMCC::CondCodes)MI->getOperand(PIdx).getImm();
1440 }
1441
1442
1443 int llvm::getMatchingCondBranchOpcode(int Opc) {
1444   if (Opc == ARM::B)
1445     return ARM::Bcc;
1446   else if (Opc == ARM::tB)
1447     return ARM::tBcc;
1448   else if (Opc == ARM::t2B)
1449       return ARM::t2Bcc;
1450
1451   llvm_unreachable("Unknown unconditional branch opcode!");
1452   return 0;
1453 }
1454
1455
1456 /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the
1457 /// instruction is encoded with an 'S' bit is determined by the optional CPSR
1458 /// def operand.
1459 ///
1460 /// This will go away once we can teach tblgen how to set the optional CPSR def
1461 /// operand itself.
1462 struct AddSubFlagsOpcodePair {
1463   unsigned PseudoOpc;
1464   unsigned MachineOpc;
1465 };
1466
1467 static AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
1468   {ARM::ADDSri, ARM::ADDri},
1469   {ARM::ADDSrr, ARM::ADDrr},
1470   {ARM::ADDSrsi, ARM::ADDrsi},
1471   {ARM::ADDSrsr, ARM::ADDrsr},
1472
1473   {ARM::SUBSri, ARM::SUBri},
1474   {ARM::SUBSrr, ARM::SUBrr},
1475   {ARM::SUBSrsi, ARM::SUBrsi},
1476   {ARM::SUBSrsr, ARM::SUBrsr},
1477
1478   {ARM::RSBSri, ARM::RSBri},
1479   {ARM::RSBSrsi, ARM::RSBrsi},
1480   {ARM::RSBSrsr, ARM::RSBrsr},
1481
1482   {ARM::t2ADDSri, ARM::t2ADDri},
1483   {ARM::t2ADDSrr, ARM::t2ADDrr},
1484   {ARM::t2ADDSrs, ARM::t2ADDrs},
1485
1486   {ARM::t2SUBSri, ARM::t2SUBri},
1487   {ARM::t2SUBSrr, ARM::t2SUBrr},
1488   {ARM::t2SUBSrs, ARM::t2SUBrs},
1489
1490   {ARM::t2RSBSri, ARM::t2RSBri},
1491   {ARM::t2RSBSrs, ARM::t2RSBrs},
1492 };
1493
1494 unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) {
1495   static const int NPairs =
1496     sizeof(AddSubFlagsOpcodeMap) / sizeof(AddSubFlagsOpcodePair);
1497   for (AddSubFlagsOpcodePair *OpcPair = &AddSubFlagsOpcodeMap[0],
1498          *End = &AddSubFlagsOpcodeMap[NPairs]; OpcPair != End; ++OpcPair) {
1499     if (OldOpc == OpcPair->PseudoOpc) {
1500       return OpcPair->MachineOpc;
1501     }
1502   }
1503   return 0;
1504 }
1505
1506 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
1507                                MachineBasicBlock::iterator &MBBI, DebugLoc dl,
1508                                unsigned DestReg, unsigned BaseReg, int NumBytes,
1509                                ARMCC::CondCodes Pred, unsigned PredReg,
1510                                const ARMBaseInstrInfo &TII, unsigned MIFlags) {
1511   bool isSub = NumBytes < 0;
1512   if (isSub) NumBytes = -NumBytes;
1513
1514   while (NumBytes) {
1515     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
1516     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
1517     assert(ThisVal && "Didn't extract field correctly");
1518
1519     // We will handle these bits from offset, clear them.
1520     NumBytes &= ~ThisVal;
1521
1522     assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
1523
1524     // Build the new ADD / SUB.
1525     unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
1526     BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
1527       .addReg(BaseReg, RegState::Kill).addImm(ThisVal)
1528       .addImm((unsigned)Pred).addReg(PredReg).addReg(0)
1529       .setMIFlags(MIFlags);
1530     BaseReg = DestReg;
1531   }
1532 }
1533
1534 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
1535                                 unsigned FrameReg, int &Offset,
1536                                 const ARMBaseInstrInfo &TII) {
1537   unsigned Opcode = MI.getOpcode();
1538   const MCInstrDesc &Desc = MI.getDesc();
1539   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1540   bool isSub = false;
1541
1542   // Memory operands in inline assembly always use AddrMode2.
1543   if (Opcode == ARM::INLINEASM)
1544     AddrMode = ARMII::AddrMode2;
1545
1546   if (Opcode == ARM::ADDri) {
1547     Offset += MI.getOperand(FrameRegIdx+1).getImm();
1548     if (Offset == 0) {
1549       // Turn it into a move.
1550       MI.setDesc(TII.get(ARM::MOVr));
1551       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1552       MI.RemoveOperand(FrameRegIdx+1);
1553       Offset = 0;
1554       return true;
1555     } else if (Offset < 0) {
1556       Offset = -Offset;
1557       isSub = true;
1558       MI.setDesc(TII.get(ARM::SUBri));
1559     }
1560
1561     // Common case: small offset, fits into instruction.
1562     if (ARM_AM::getSOImmVal(Offset) != -1) {
1563       // Replace the FrameIndex with sp / fp
1564       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1565       MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
1566       Offset = 0;
1567       return true;
1568     }
1569
1570     // Otherwise, pull as much of the immedidate into this ADDri/SUBri
1571     // as possible.
1572     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
1573     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
1574
1575     // We will handle these bits from offset, clear them.
1576     Offset &= ~ThisImmVal;
1577
1578     // Get the properly encoded SOImmVal field.
1579     assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
1580            "Bit extraction didn't work?");
1581     MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
1582  } else {
1583     unsigned ImmIdx = 0;
1584     int InstrOffs = 0;
1585     unsigned NumBits = 0;
1586     unsigned Scale = 1;
1587     switch (AddrMode) {
1588     case ARMII::AddrMode_i12: {
1589       ImmIdx = FrameRegIdx + 1;
1590       InstrOffs = MI.getOperand(ImmIdx).getImm();
1591       NumBits = 12;
1592       break;
1593     }
1594     case ARMII::AddrMode2: {
1595       ImmIdx = FrameRegIdx+2;
1596       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
1597       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1598         InstrOffs *= -1;
1599       NumBits = 12;
1600       break;
1601     }
1602     case ARMII::AddrMode3: {
1603       ImmIdx = FrameRegIdx+2;
1604       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
1605       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1606         InstrOffs *= -1;
1607       NumBits = 8;
1608       break;
1609     }
1610     case ARMII::AddrMode4:
1611     case ARMII::AddrMode6:
1612       // Can't fold any offset even if it's zero.
1613       return false;
1614     case ARMII::AddrMode5: {
1615       ImmIdx = FrameRegIdx+1;
1616       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
1617       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1618         InstrOffs *= -1;
1619       NumBits = 8;
1620       Scale = 4;
1621       break;
1622     }
1623     default:
1624       llvm_unreachable("Unsupported addressing mode!");
1625       break;
1626     }
1627
1628     Offset += InstrOffs * Scale;
1629     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1630     if (Offset < 0) {
1631       Offset = -Offset;
1632       isSub = true;
1633     }
1634
1635     // Attempt to fold address comp. if opcode has offset bits
1636     if (NumBits > 0) {
1637       // Common case: small offset, fits into instruction.
1638       MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1639       int ImmedOffset = Offset / Scale;
1640       unsigned Mask = (1 << NumBits) - 1;
1641       if ((unsigned)Offset <= Mask * Scale) {
1642         // Replace the FrameIndex with sp
1643         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1644         // FIXME: When addrmode2 goes away, this will simplify (like the
1645         // T2 version), as the LDR.i12 versions don't need the encoding
1646         // tricks for the offset value.
1647         if (isSub) {
1648           if (AddrMode == ARMII::AddrMode_i12)
1649             ImmedOffset = -ImmedOffset;
1650           else
1651             ImmedOffset |= 1 << NumBits;
1652         }
1653         ImmOp.ChangeToImmediate(ImmedOffset);
1654         Offset = 0;
1655         return true;
1656       }
1657
1658       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1659       ImmedOffset = ImmedOffset & Mask;
1660       if (isSub) {
1661         if (AddrMode == ARMII::AddrMode_i12)
1662           ImmedOffset = -ImmedOffset;
1663         else
1664           ImmedOffset |= 1 << NumBits;
1665       }
1666       ImmOp.ChangeToImmediate(ImmedOffset);
1667       Offset &= ~(Mask*Scale);
1668     }
1669   }
1670
1671   Offset = (isSub) ? -Offset : Offset;
1672   return Offset == 0;
1673 }
1674
1675 bool ARMBaseInstrInfo::
1676 AnalyzeCompare(const MachineInstr *MI, unsigned &SrcReg, int &CmpMask,
1677                int &CmpValue) const {
1678   switch (MI->getOpcode()) {
1679   default: break;
1680   case ARM::CMPri:
1681   case ARM::t2CMPri:
1682     SrcReg = MI->getOperand(0).getReg();
1683     CmpMask = ~0;
1684     CmpValue = MI->getOperand(1).getImm();
1685     return true;
1686   case ARM::TSTri:
1687   case ARM::t2TSTri:
1688     SrcReg = MI->getOperand(0).getReg();
1689     CmpMask = MI->getOperand(1).getImm();
1690     CmpValue = 0;
1691     return true;
1692   }
1693
1694   return false;
1695 }
1696
1697 /// isSuitableForMask - Identify a suitable 'and' instruction that
1698 /// operates on the given source register and applies the same mask
1699 /// as a 'tst' instruction. Provide a limited look-through for copies.
1700 /// When successful, MI will hold the found instruction.
1701 static bool isSuitableForMask(MachineInstr *&MI, unsigned SrcReg,
1702                               int CmpMask, bool CommonUse) {
1703   switch (MI->getOpcode()) {
1704     case ARM::ANDri:
1705     case ARM::t2ANDri:
1706       if (CmpMask != MI->getOperand(2).getImm())
1707         return false;
1708       if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
1709         return true;
1710       break;
1711     case ARM::COPY: {
1712       // Walk down one instruction which is potentially an 'and'.
1713       const MachineInstr &Copy = *MI;
1714       MachineBasicBlock::iterator AND(
1715         llvm::next(MachineBasicBlock::iterator(MI)));
1716       if (AND == MI->getParent()->end()) return false;
1717       MI = AND;
1718       return isSuitableForMask(MI, Copy.getOperand(0).getReg(),
1719                                CmpMask, true);
1720     }
1721   }
1722
1723   return false;
1724 }
1725
1726 /// OptimizeCompareInstr - Convert the instruction supplying the argument to the
1727 /// comparison into one that sets the zero bit in the flags register.
1728 bool ARMBaseInstrInfo::
1729 OptimizeCompareInstr(MachineInstr *CmpInstr, unsigned SrcReg, int CmpMask,
1730                      int CmpValue, const MachineRegisterInfo *MRI) const {
1731   if (CmpValue != 0)
1732     return false;
1733
1734   MachineRegisterInfo::def_iterator DI = MRI->def_begin(SrcReg);
1735   if (llvm::next(DI) != MRI->def_end())
1736     // Only support one definition.
1737     return false;
1738
1739   MachineInstr *MI = &*DI;
1740
1741   // Masked compares sometimes use the same register as the corresponding 'and'.
1742   if (CmpMask != ~0) {
1743     if (!isSuitableForMask(MI, SrcReg, CmpMask, false)) {
1744       MI = 0;
1745       for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SrcReg),
1746            UE = MRI->use_end(); UI != UE; ++UI) {
1747         if (UI->getParent() != CmpInstr->getParent()) continue;
1748         MachineInstr *PotentialAND = &*UI;
1749         if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true))
1750           continue;
1751         MI = PotentialAND;
1752         break;
1753       }
1754       if (!MI) return false;
1755     }
1756   }
1757
1758   // Conservatively refuse to convert an instruction which isn't in the same BB
1759   // as the comparison.
1760   if (MI->getParent() != CmpInstr->getParent())
1761     return false;
1762
1763   // Check that CPSR isn't set between the comparison instruction and the one we
1764   // want to change.
1765   MachineBasicBlock::const_iterator I = CmpInstr, E = MI,
1766     B = MI->getParent()->begin();
1767
1768   // Early exit if CmpInstr is at the beginning of the BB.
1769   if (I == B) return false;
1770
1771   --I;
1772   for (; I != E; --I) {
1773     const MachineInstr &Instr = *I;
1774
1775     for (unsigned IO = 0, EO = Instr.getNumOperands(); IO != EO; ++IO) {
1776       const MachineOperand &MO = Instr.getOperand(IO);
1777       if (!MO.isReg()) continue;
1778
1779       // This instruction modifies or uses CPSR after the one we want to
1780       // change. We can't do this transformation.
1781       if (MO.getReg() == ARM::CPSR)
1782         return false;
1783     }
1784
1785     if (I == B)
1786       // The 'and' is below the comparison instruction.
1787       return false;
1788   }
1789
1790   // Set the "zero" bit in CPSR.
1791   switch (MI->getOpcode()) {
1792   default: break;
1793   case ARM::RSBrr:
1794   case ARM::RSBri:
1795   case ARM::RSCrr:
1796   case ARM::RSCri:
1797   case ARM::ADDrr:
1798   case ARM::ADDri:
1799   case ARM::ADCrr:
1800   case ARM::ADCri:
1801   case ARM::SUBrr:
1802   case ARM::SUBri:
1803   case ARM::SBCrr:
1804   case ARM::SBCri:
1805   case ARM::t2RSBri:
1806   case ARM::t2ADDrr:
1807   case ARM::t2ADDri:
1808   case ARM::t2ADCrr:
1809   case ARM::t2ADCri:
1810   case ARM::t2SUBrr:
1811   case ARM::t2SUBri:
1812   case ARM::t2SBCrr:
1813   case ARM::t2SBCri:
1814   case ARM::ANDrr:
1815   case ARM::ANDri:
1816   case ARM::t2ANDrr:
1817   case ARM::t2ANDri:
1818   case ARM::ORRrr:
1819   case ARM::ORRri:
1820   case ARM::t2ORRrr:
1821   case ARM::t2ORRri:
1822   case ARM::EORrr:
1823   case ARM::EORri:
1824   case ARM::t2EORrr:
1825   case ARM::t2EORri: {
1826     // Scan forward for the use of CPSR, if it's a conditional code requires
1827     // checking of V bit, then this is not safe to do. If we can't find the
1828     // CPSR use (i.e. used in another block), then it's not safe to perform
1829     // the optimization.
1830     bool isSafe = false;
1831     I = CmpInstr;
1832     E = MI->getParent()->end();
1833     while (!isSafe && ++I != E) {
1834       const MachineInstr &Instr = *I;
1835       for (unsigned IO = 0, EO = Instr.getNumOperands();
1836            !isSafe && IO != EO; ++IO) {
1837         const MachineOperand &MO = Instr.getOperand(IO);
1838         if (!MO.isReg() || MO.getReg() != ARM::CPSR)
1839           continue;
1840         if (MO.isDef()) {
1841           isSafe = true;
1842           break;
1843         }
1844         // Condition code is after the operand before CPSR.
1845         ARMCC::CondCodes CC = (ARMCC::CondCodes)Instr.getOperand(IO-1).getImm();
1846         switch (CC) {
1847         default:
1848           isSafe = true;
1849           break;
1850         case ARMCC::VS:
1851         case ARMCC::VC:
1852         case ARMCC::GE:
1853         case ARMCC::LT:
1854         case ARMCC::GT:
1855         case ARMCC::LE:
1856           return false;
1857         }
1858       }
1859     }
1860
1861     if (!isSafe)
1862       return false;
1863
1864     // Toggle the optional operand to CPSR.
1865     MI->getOperand(5).setReg(ARM::CPSR);
1866     MI->getOperand(5).setIsDef(true);
1867     CmpInstr->eraseFromParent();
1868     return true;
1869   }
1870   }
1871
1872   return false;
1873 }
1874
1875 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr *UseMI,
1876                                      MachineInstr *DefMI, unsigned Reg,
1877                                      MachineRegisterInfo *MRI) const {
1878   // Fold large immediates into add, sub, or, xor.
1879   unsigned DefOpc = DefMI->getOpcode();
1880   if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
1881     return false;
1882   if (!DefMI->getOperand(1).isImm())
1883     // Could be t2MOVi32imm <ga:xx>
1884     return false;
1885
1886   if (!MRI->hasOneNonDBGUse(Reg))
1887     return false;
1888
1889   unsigned UseOpc = UseMI->getOpcode();
1890   unsigned NewUseOpc = 0;
1891   uint32_t ImmVal = (uint32_t)DefMI->getOperand(1).getImm();
1892   uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
1893   bool Commute = false;
1894   switch (UseOpc) {
1895   default: return false;
1896   case ARM::SUBrr:
1897   case ARM::ADDrr:
1898   case ARM::ORRrr:
1899   case ARM::EORrr:
1900   case ARM::t2SUBrr:
1901   case ARM::t2ADDrr:
1902   case ARM::t2ORRrr:
1903   case ARM::t2EORrr: {
1904     Commute = UseMI->getOperand(2).getReg() != Reg;
1905     switch (UseOpc) {
1906     default: break;
1907     case ARM::SUBrr: {
1908       if (Commute)
1909         return false;
1910       ImmVal = -ImmVal;
1911       NewUseOpc = ARM::SUBri;
1912       // Fallthrough
1913     }
1914     case ARM::ADDrr:
1915     case ARM::ORRrr:
1916     case ARM::EORrr: {
1917       if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
1918         return false;
1919       SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
1920       SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
1921       switch (UseOpc) {
1922       default: break;
1923       case ARM::ADDrr: NewUseOpc = ARM::ADDri; break;
1924       case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
1925       case ARM::EORrr: NewUseOpc = ARM::EORri; break;
1926       }
1927       break;
1928     }
1929     case ARM::t2SUBrr: {
1930       if (Commute)
1931         return false;
1932       ImmVal = -ImmVal;
1933       NewUseOpc = ARM::t2SUBri;
1934       // Fallthrough
1935     }
1936     case ARM::t2ADDrr:
1937     case ARM::t2ORRrr:
1938     case ARM::t2EORrr: {
1939       if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
1940         return false;
1941       SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
1942       SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
1943       switch (UseOpc) {
1944       default: break;
1945       case ARM::t2ADDrr: NewUseOpc = ARM::t2ADDri; break;
1946       case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
1947       case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
1948       }
1949       break;
1950     }
1951     }
1952   }
1953   }
1954
1955   unsigned OpIdx = Commute ? 2 : 1;
1956   unsigned Reg1 = UseMI->getOperand(OpIdx).getReg();
1957   bool isKill = UseMI->getOperand(OpIdx).isKill();
1958   unsigned NewReg = MRI->createVirtualRegister(MRI->getRegClass(Reg));
1959   AddDefaultCC(AddDefaultPred(BuildMI(*UseMI->getParent(),
1960                                       *UseMI, UseMI->getDebugLoc(),
1961                                       get(NewUseOpc), NewReg)
1962                               .addReg(Reg1, getKillRegState(isKill))
1963                               .addImm(SOImmValV1)));
1964   UseMI->setDesc(get(NewUseOpc));
1965   UseMI->getOperand(1).setReg(NewReg);
1966   UseMI->getOperand(1).setIsKill();
1967   UseMI->getOperand(2).ChangeToImmediate(SOImmValV2);
1968   DefMI->eraseFromParent();
1969   return true;
1970 }
1971
1972 unsigned
1973 ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
1974                                  const MachineInstr *MI) const {
1975   if (!ItinData || ItinData->isEmpty())
1976     return 1;
1977
1978   const MCInstrDesc &Desc = MI->getDesc();
1979   unsigned Class = Desc.getSchedClass();
1980   unsigned UOps = ItinData->Itineraries[Class].NumMicroOps;
1981   if (UOps)
1982     return UOps;
1983
1984   unsigned Opc = MI->getOpcode();
1985   switch (Opc) {
1986   default:
1987     llvm_unreachable("Unexpected multi-uops instruction!");
1988     break;
1989   case ARM::VLDMQIA:
1990   case ARM::VSTMQIA:
1991     return 2;
1992
1993   // The number of uOps for load / store multiple are determined by the number
1994   // registers.
1995   //
1996   // On Cortex-A8, each pair of register loads / stores can be scheduled on the
1997   // same cycle. The scheduling for the first load / store must be done
1998   // separately by assuming the the address is not 64-bit aligned.
1999   //
2000   // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
2001   // is not 64-bit aligned, then AGU would take an extra cycle.  For VFP / NEON
2002   // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
2003   case ARM::VLDMDIA:
2004   case ARM::VLDMDIA_UPD:
2005   case ARM::VLDMDDB_UPD:
2006   case ARM::VLDMSIA:
2007   case ARM::VLDMSIA_UPD:
2008   case ARM::VLDMSDB_UPD:
2009   case ARM::VSTMDIA:
2010   case ARM::VSTMDIA_UPD:
2011   case ARM::VSTMDDB_UPD:
2012   case ARM::VSTMSIA:
2013   case ARM::VSTMSIA_UPD:
2014   case ARM::VSTMSDB_UPD: {
2015     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands();
2016     return (NumRegs / 2) + (NumRegs % 2) + 1;
2017   }
2018
2019   case ARM::LDMIA_RET:
2020   case ARM::LDMIA:
2021   case ARM::LDMDA:
2022   case ARM::LDMDB:
2023   case ARM::LDMIB:
2024   case ARM::LDMIA_UPD:
2025   case ARM::LDMDA_UPD:
2026   case ARM::LDMDB_UPD:
2027   case ARM::LDMIB_UPD:
2028   case ARM::STMIA:
2029   case ARM::STMDA:
2030   case ARM::STMDB:
2031   case ARM::STMIB:
2032   case ARM::STMIA_UPD:
2033   case ARM::STMDA_UPD:
2034   case ARM::STMDB_UPD:
2035   case ARM::STMIB_UPD:
2036   case ARM::tLDMIA:
2037   case ARM::tLDMIA_UPD:
2038   case ARM::tSTMIA_UPD:
2039   case ARM::tPOP_RET:
2040   case ARM::tPOP:
2041   case ARM::tPUSH:
2042   case ARM::t2LDMIA_RET:
2043   case ARM::t2LDMIA:
2044   case ARM::t2LDMDB:
2045   case ARM::t2LDMIA_UPD:
2046   case ARM::t2LDMDB_UPD:
2047   case ARM::t2STMIA:
2048   case ARM::t2STMDB:
2049   case ARM::t2STMIA_UPD:
2050   case ARM::t2STMDB_UPD: {
2051     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands() + 1;
2052     if (Subtarget.isCortexA8()) {
2053       if (NumRegs < 4)
2054         return 2;
2055       // 4 registers would be issued: 2, 2.
2056       // 5 registers would be issued: 2, 2, 1.
2057       UOps = (NumRegs / 2);
2058       if (NumRegs % 2)
2059         ++UOps;
2060       return UOps;
2061     } else if (Subtarget.isCortexA9()) {
2062       UOps = (NumRegs / 2);
2063       // If there are odd number of registers or if it's not 64-bit aligned,
2064       // then it takes an extra AGU (Address Generation Unit) cycle.
2065       if ((NumRegs % 2) ||
2066           !MI->hasOneMemOperand() ||
2067           (*MI->memoperands_begin())->getAlignment() < 8)
2068         ++UOps;
2069       return UOps;
2070     } else {
2071       // Assume the worst.
2072       return NumRegs;
2073     }
2074   }
2075   }
2076 }
2077
2078 int
2079 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
2080                                   const MCInstrDesc &DefMCID,
2081                                   unsigned DefClass,
2082                                   unsigned DefIdx, unsigned DefAlign) const {
2083   int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
2084   if (RegNo <= 0)
2085     // Def is the address writeback.
2086     return ItinData->getOperandCycle(DefClass, DefIdx);
2087
2088   int DefCycle;
2089   if (Subtarget.isCortexA8()) {
2090     // (regno / 2) + (regno % 2) + 1
2091     DefCycle = RegNo / 2 + 1;
2092     if (RegNo % 2)
2093       ++DefCycle;
2094   } else if (Subtarget.isCortexA9()) {
2095     DefCycle = RegNo;
2096     bool isSLoad = false;
2097
2098     switch (DefMCID.getOpcode()) {
2099     default: break;
2100     case ARM::VLDMSIA:
2101     case ARM::VLDMSIA_UPD:
2102     case ARM::VLDMSDB_UPD:
2103       isSLoad = true;
2104       break;
2105     }
2106
2107     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
2108     // then it takes an extra cycle.
2109     if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
2110       ++DefCycle;
2111   } else {
2112     // Assume the worst.
2113     DefCycle = RegNo + 2;
2114   }
2115
2116   return DefCycle;
2117 }
2118
2119 int
2120 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
2121                                  const MCInstrDesc &DefMCID,
2122                                  unsigned DefClass,
2123                                  unsigned DefIdx, unsigned DefAlign) const {
2124   int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
2125   if (RegNo <= 0)
2126     // Def is the address writeback.
2127     return ItinData->getOperandCycle(DefClass, DefIdx);
2128
2129   int DefCycle;
2130   if (Subtarget.isCortexA8()) {
2131     // 4 registers would be issued: 1, 2, 1.
2132     // 5 registers would be issued: 1, 2, 2.
2133     DefCycle = RegNo / 2;
2134     if (DefCycle < 1)
2135       DefCycle = 1;
2136     // Result latency is issue cycle + 2: E2.
2137     DefCycle += 2;
2138   } else if (Subtarget.isCortexA9()) {
2139     DefCycle = (RegNo / 2);
2140     // If there are odd number of registers or if it's not 64-bit aligned,
2141     // then it takes an extra AGU (Address Generation Unit) cycle.
2142     if ((RegNo % 2) || DefAlign < 8)
2143       ++DefCycle;
2144     // Result latency is AGU cycles + 2.
2145     DefCycle += 2;
2146   } else {
2147     // Assume the worst.
2148     DefCycle = RegNo + 2;
2149   }
2150
2151   return DefCycle;
2152 }
2153
2154 int
2155 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
2156                                   const MCInstrDesc &UseMCID,
2157                                   unsigned UseClass,
2158                                   unsigned UseIdx, unsigned UseAlign) const {
2159   int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
2160   if (RegNo <= 0)
2161     return ItinData->getOperandCycle(UseClass, UseIdx);
2162
2163   int UseCycle;
2164   if (Subtarget.isCortexA8()) {
2165     // (regno / 2) + (regno % 2) + 1
2166     UseCycle = RegNo / 2 + 1;
2167     if (RegNo % 2)
2168       ++UseCycle;
2169   } else if (Subtarget.isCortexA9()) {
2170     UseCycle = RegNo;
2171     bool isSStore = false;
2172
2173     switch (UseMCID.getOpcode()) {
2174     default: break;
2175     case ARM::VSTMSIA:
2176     case ARM::VSTMSIA_UPD:
2177     case ARM::VSTMSDB_UPD:
2178       isSStore = true;
2179       break;
2180     }
2181
2182     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
2183     // then it takes an extra cycle.
2184     if ((isSStore && (RegNo % 2)) || UseAlign < 8)
2185       ++UseCycle;
2186   } else {
2187     // Assume the worst.
2188     UseCycle = RegNo + 2;
2189   }
2190
2191   return UseCycle;
2192 }
2193
2194 int
2195 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
2196                                  const MCInstrDesc &UseMCID,
2197                                  unsigned UseClass,
2198                                  unsigned UseIdx, unsigned UseAlign) const {
2199   int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
2200   if (RegNo <= 0)
2201     return ItinData->getOperandCycle(UseClass, UseIdx);
2202
2203   int UseCycle;
2204   if (Subtarget.isCortexA8()) {
2205     UseCycle = RegNo / 2;
2206     if (UseCycle < 2)
2207       UseCycle = 2;
2208     // Read in E3.
2209     UseCycle += 2;
2210   } else if (Subtarget.isCortexA9()) {
2211     UseCycle = (RegNo / 2);
2212     // If there are odd number of registers or if it's not 64-bit aligned,
2213     // then it takes an extra AGU (Address Generation Unit) cycle.
2214     if ((RegNo % 2) || UseAlign < 8)
2215       ++UseCycle;
2216   } else {
2217     // Assume the worst.
2218     UseCycle = 1;
2219   }
2220   return UseCycle;
2221 }
2222
2223 int
2224 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2225                                     const MCInstrDesc &DefMCID,
2226                                     unsigned DefIdx, unsigned DefAlign,
2227                                     const MCInstrDesc &UseMCID,
2228                                     unsigned UseIdx, unsigned UseAlign) const {
2229   unsigned DefClass = DefMCID.getSchedClass();
2230   unsigned UseClass = UseMCID.getSchedClass();
2231
2232   if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
2233     return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
2234
2235   // This may be a def / use of a variable_ops instruction, the operand
2236   // latency might be determinable dynamically. Let the target try to
2237   // figure it out.
2238   int DefCycle = -1;
2239   bool LdmBypass = false;
2240   switch (DefMCID.getOpcode()) {
2241   default:
2242     DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
2243     break;
2244
2245   case ARM::VLDMDIA:
2246   case ARM::VLDMDIA_UPD:
2247   case ARM::VLDMDDB_UPD:
2248   case ARM::VLDMSIA:
2249   case ARM::VLDMSIA_UPD:
2250   case ARM::VLDMSDB_UPD:
2251     DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
2252     break;
2253
2254   case ARM::LDMIA_RET:
2255   case ARM::LDMIA:
2256   case ARM::LDMDA:
2257   case ARM::LDMDB:
2258   case ARM::LDMIB:
2259   case ARM::LDMIA_UPD:
2260   case ARM::LDMDA_UPD:
2261   case ARM::LDMDB_UPD:
2262   case ARM::LDMIB_UPD:
2263   case ARM::tLDMIA:
2264   case ARM::tLDMIA_UPD:
2265   case ARM::tPUSH:
2266   case ARM::t2LDMIA_RET:
2267   case ARM::t2LDMIA:
2268   case ARM::t2LDMDB:
2269   case ARM::t2LDMIA_UPD:
2270   case ARM::t2LDMDB_UPD:
2271     LdmBypass = 1;
2272     DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
2273     break;
2274   }
2275
2276   if (DefCycle == -1)
2277     // We can't seem to determine the result latency of the def, assume it's 2.
2278     DefCycle = 2;
2279
2280   int UseCycle = -1;
2281   switch (UseMCID.getOpcode()) {
2282   default:
2283     UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
2284     break;
2285
2286   case ARM::VSTMDIA:
2287   case ARM::VSTMDIA_UPD:
2288   case ARM::VSTMDDB_UPD:
2289   case ARM::VSTMSIA:
2290   case ARM::VSTMSIA_UPD:
2291   case ARM::VSTMSDB_UPD:
2292     UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
2293     break;
2294
2295   case ARM::STMIA:
2296   case ARM::STMDA:
2297   case ARM::STMDB:
2298   case ARM::STMIB:
2299   case ARM::STMIA_UPD:
2300   case ARM::STMDA_UPD:
2301   case ARM::STMDB_UPD:
2302   case ARM::STMIB_UPD:
2303   case ARM::tSTMIA_UPD:
2304   case ARM::tPOP_RET:
2305   case ARM::tPOP:
2306   case ARM::t2STMIA:
2307   case ARM::t2STMDB:
2308   case ARM::t2STMIA_UPD:
2309   case ARM::t2STMDB_UPD:
2310     UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
2311     break;
2312   }
2313
2314   if (UseCycle == -1)
2315     // Assume it's read in the first stage.
2316     UseCycle = 1;
2317
2318   UseCycle = DefCycle - UseCycle + 1;
2319   if (UseCycle > 0) {
2320     if (LdmBypass) {
2321       // It's a variable_ops instruction so we can't use DefIdx here. Just use
2322       // first def operand.
2323       if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
2324                                           UseClass, UseIdx))
2325         --UseCycle;
2326     } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
2327                                                UseClass, UseIdx)) {
2328       --UseCycle;
2329     }
2330   }
2331
2332   return UseCycle;
2333 }
2334
2335 int
2336 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2337                              const MachineInstr *DefMI, unsigned DefIdx,
2338                              const MachineInstr *UseMI, unsigned UseIdx) const {
2339   if (DefMI->isCopyLike() || DefMI->isInsertSubreg() ||
2340       DefMI->isRegSequence() || DefMI->isImplicitDef())
2341     return 1;
2342
2343   const MCInstrDesc &DefMCID = DefMI->getDesc();
2344   if (!ItinData || ItinData->isEmpty())
2345     return DefMCID.mayLoad() ? 3 : 1;
2346
2347   const MCInstrDesc &UseMCID = UseMI->getDesc();
2348   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
2349   if (DefMO.getReg() == ARM::CPSR) {
2350     if (DefMI->getOpcode() == ARM::FMSTAT) {
2351       // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
2352       return Subtarget.isCortexA9() ? 1 : 20;
2353     }
2354
2355     // CPSR set and branch can be paired in the same cycle.
2356     if (UseMCID.isBranch())
2357       return 0;
2358   }
2359
2360   unsigned DefAlign = DefMI->hasOneMemOperand()
2361     ? (*DefMI->memoperands_begin())->getAlignment() : 0;
2362   unsigned UseAlign = UseMI->hasOneMemOperand()
2363     ? (*UseMI->memoperands_begin())->getAlignment() : 0;
2364   int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
2365                                   UseMCID, UseIdx, UseAlign);
2366
2367   if (Latency > 1 &&
2368       (Subtarget.isCortexA8() || Subtarget.isCortexA9())) {
2369     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
2370     // variants are one cycle cheaper.
2371     switch (DefMCID.getOpcode()) {
2372     default: break;
2373     case ARM::LDRrs:
2374     case ARM::LDRBrs: {
2375       unsigned ShOpVal = DefMI->getOperand(3).getImm();
2376       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2377       if (ShImm == 0 ||
2378           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
2379         --Latency;
2380       break;
2381     }
2382     case ARM::t2LDRs:
2383     case ARM::t2LDRBs:
2384     case ARM::t2LDRHs:
2385     case ARM::t2LDRSHs: {
2386       // Thumb2 mode: lsl only.
2387       unsigned ShAmt = DefMI->getOperand(3).getImm();
2388       if (ShAmt == 0 || ShAmt == 2)
2389         --Latency;
2390       break;
2391     }
2392     }
2393   }
2394
2395   if (DefAlign < 8 && Subtarget.isCortexA9())
2396     switch (DefMCID.getOpcode()) {
2397     default: break;
2398     case ARM::VLD1q8:
2399     case ARM::VLD1q16:
2400     case ARM::VLD1q32:
2401     case ARM::VLD1q64:
2402     case ARM::VLD1q8wb_fixed:
2403     case ARM::VLD1q16wb_fixed:
2404     case ARM::VLD1q32wb_fixed:
2405     case ARM::VLD1q64wb_fixed:
2406     case ARM::VLD1q8wb_register:
2407     case ARM::VLD1q16wb_register:
2408     case ARM::VLD1q32wb_register:
2409     case ARM::VLD1q64wb_register:
2410     case ARM::VLD2d8:
2411     case ARM::VLD2d16:
2412     case ARM::VLD2d32:
2413     case ARM::VLD2q8:
2414     case ARM::VLD2q16:
2415     case ARM::VLD2q32:
2416     case ARM::VLD2d8_UPD:
2417     case ARM::VLD2d16_UPD:
2418     case ARM::VLD2d32_UPD:
2419     case ARM::VLD2q8_UPD:
2420     case ARM::VLD2q16_UPD:
2421     case ARM::VLD2q32_UPD:
2422     case ARM::VLD3d8:
2423     case ARM::VLD3d16:
2424     case ARM::VLD3d32:
2425     case ARM::VLD1d64T:
2426     case ARM::VLD3d8_UPD:
2427     case ARM::VLD3d16_UPD:
2428     case ARM::VLD3d32_UPD:
2429     case ARM::VLD1d64Twb_fixed:
2430     case ARM::VLD1d64Twb_register:
2431     case ARM::VLD3q8_UPD:
2432     case ARM::VLD3q16_UPD:
2433     case ARM::VLD3q32_UPD:
2434     case ARM::VLD4d8:
2435     case ARM::VLD4d16:
2436     case ARM::VLD4d32:
2437     case ARM::VLD1d64Q:
2438     case ARM::VLD4d8_UPD:
2439     case ARM::VLD4d16_UPD:
2440     case ARM::VLD4d32_UPD:
2441     case ARM::VLD1d64Qwb_fixed:
2442     case ARM::VLD1d64Qwb_register:
2443     case ARM::VLD4q8_UPD:
2444     case ARM::VLD4q16_UPD:
2445     case ARM::VLD4q32_UPD:
2446     case ARM::VLD1DUPq8:
2447     case ARM::VLD1DUPq16:
2448     case ARM::VLD1DUPq32:
2449     case ARM::VLD1DUPq8_UPD:
2450     case ARM::VLD1DUPq16_UPD:
2451     case ARM::VLD1DUPq32_UPD:
2452     case ARM::VLD2DUPd8:
2453     case ARM::VLD2DUPd16:
2454     case ARM::VLD2DUPd32:
2455     case ARM::VLD2DUPd8_UPD:
2456     case ARM::VLD2DUPd16_UPD:
2457     case ARM::VLD2DUPd32_UPD:
2458     case ARM::VLD4DUPd8:
2459     case ARM::VLD4DUPd16:
2460     case ARM::VLD4DUPd32:
2461     case ARM::VLD4DUPd8_UPD:
2462     case ARM::VLD4DUPd16_UPD:
2463     case ARM::VLD4DUPd32_UPD:
2464     case ARM::VLD1LNd8:
2465     case ARM::VLD1LNd16:
2466     case ARM::VLD1LNd32:
2467     case ARM::VLD1LNd8_UPD:
2468     case ARM::VLD1LNd16_UPD:
2469     case ARM::VLD1LNd32_UPD:
2470     case ARM::VLD2LNd8:
2471     case ARM::VLD2LNd16:
2472     case ARM::VLD2LNd32:
2473     case ARM::VLD2LNq16:
2474     case ARM::VLD2LNq32:
2475     case ARM::VLD2LNd8_UPD:
2476     case ARM::VLD2LNd16_UPD:
2477     case ARM::VLD2LNd32_UPD:
2478     case ARM::VLD2LNq16_UPD:
2479     case ARM::VLD2LNq32_UPD:
2480     case ARM::VLD4LNd8:
2481     case ARM::VLD4LNd16:
2482     case ARM::VLD4LNd32:
2483     case ARM::VLD4LNq16:
2484     case ARM::VLD4LNq32:
2485     case ARM::VLD4LNd8_UPD:
2486     case ARM::VLD4LNd16_UPD:
2487     case ARM::VLD4LNd32_UPD:
2488     case ARM::VLD4LNq16_UPD:
2489     case ARM::VLD4LNq32_UPD:
2490       // If the address is not 64-bit aligned, the latencies of these
2491       // instructions increases by one.
2492       ++Latency;
2493       break;
2494     }
2495
2496   return Latency;
2497 }
2498
2499 int
2500 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2501                                     SDNode *DefNode, unsigned DefIdx,
2502                                     SDNode *UseNode, unsigned UseIdx) const {
2503   if (!DefNode->isMachineOpcode())
2504     return 1;
2505
2506   const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
2507
2508   if (isZeroCost(DefMCID.Opcode))
2509     return 0;
2510
2511   if (!ItinData || ItinData->isEmpty())
2512     return DefMCID.mayLoad() ? 3 : 1;
2513
2514   if (!UseNode->isMachineOpcode()) {
2515     int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
2516     if (Subtarget.isCortexA9())
2517       return Latency <= 2 ? 1 : Latency - 1;
2518     else
2519       return Latency <= 3 ? 1 : Latency - 2;
2520   }
2521
2522   const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
2523   const MachineSDNode *DefMN = dyn_cast<MachineSDNode>(DefNode);
2524   unsigned DefAlign = !DefMN->memoperands_empty()
2525     ? (*DefMN->memoperands_begin())->getAlignment() : 0;
2526   const MachineSDNode *UseMN = dyn_cast<MachineSDNode>(UseNode);
2527   unsigned UseAlign = !UseMN->memoperands_empty()
2528     ? (*UseMN->memoperands_begin())->getAlignment() : 0;
2529   int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
2530                                   UseMCID, UseIdx, UseAlign);
2531
2532   if (Latency > 1 &&
2533       (Subtarget.isCortexA8() || Subtarget.isCortexA9())) {
2534     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
2535     // variants are one cycle cheaper.
2536     switch (DefMCID.getOpcode()) {
2537     default: break;
2538     case ARM::LDRrs:
2539     case ARM::LDRBrs: {
2540       unsigned ShOpVal =
2541         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
2542       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2543       if (ShImm == 0 ||
2544           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
2545         --Latency;
2546       break;
2547     }
2548     case ARM::t2LDRs:
2549     case ARM::t2LDRBs:
2550     case ARM::t2LDRHs:
2551     case ARM::t2LDRSHs: {
2552       // Thumb2 mode: lsl only.
2553       unsigned ShAmt =
2554         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
2555       if (ShAmt == 0 || ShAmt == 2)
2556         --Latency;
2557       break;
2558     }
2559     }
2560   }
2561
2562   if (DefAlign < 8 && Subtarget.isCortexA9())
2563     switch (DefMCID.getOpcode()) {
2564     default: break;
2565     case ARM::VLD1q8Pseudo:
2566     case ARM::VLD1q16Pseudo:
2567     case ARM::VLD1q32Pseudo:
2568     case ARM::VLD1q64Pseudo:
2569     case ARM::VLD1q8PseudoWB_register:
2570     case ARM::VLD1q16PseudoWB_register:
2571     case ARM::VLD1q32PseudoWB_register:
2572     case ARM::VLD1q64PseudoWB_register:
2573     case ARM::VLD1q8PseudoWB_fixed:
2574     case ARM::VLD1q16PseudoWB_fixed:
2575     case ARM::VLD1q32PseudoWB_fixed:
2576     case ARM::VLD1q64PseudoWB_fixed:
2577     case ARM::VLD2d8Pseudo:
2578     case ARM::VLD2d16Pseudo:
2579     case ARM::VLD2d32Pseudo:
2580     case ARM::VLD2q8Pseudo:
2581     case ARM::VLD2q16Pseudo:
2582     case ARM::VLD2q32Pseudo:
2583     case ARM::VLD2d8Pseudo_UPD:
2584     case ARM::VLD2d16Pseudo_UPD:
2585     case ARM::VLD2d32Pseudo_UPD:
2586     case ARM::VLD2q8Pseudo_UPD:
2587     case ARM::VLD2q16Pseudo_UPD:
2588     case ARM::VLD2q32Pseudo_UPD:
2589     case ARM::VLD3d8Pseudo:
2590     case ARM::VLD3d16Pseudo:
2591     case ARM::VLD3d32Pseudo:
2592     case ARM::VLD1d64TPseudo:
2593     case ARM::VLD3d8Pseudo_UPD:
2594     case ARM::VLD3d16Pseudo_UPD:
2595     case ARM::VLD3d32Pseudo_UPD:
2596     case ARM::VLD3q8Pseudo_UPD:
2597     case ARM::VLD3q16Pseudo_UPD:
2598     case ARM::VLD3q32Pseudo_UPD:
2599     case ARM::VLD3q8oddPseudo:
2600     case ARM::VLD3q16oddPseudo:
2601     case ARM::VLD3q32oddPseudo:
2602     case ARM::VLD3q8oddPseudo_UPD:
2603     case ARM::VLD3q16oddPseudo_UPD:
2604     case ARM::VLD3q32oddPseudo_UPD:
2605     case ARM::VLD4d8Pseudo:
2606     case ARM::VLD4d16Pseudo:
2607     case ARM::VLD4d32Pseudo:
2608     case ARM::VLD1d64QPseudo:
2609     case ARM::VLD4d8Pseudo_UPD:
2610     case ARM::VLD4d16Pseudo_UPD:
2611     case ARM::VLD4d32Pseudo_UPD:
2612     case ARM::VLD4q8Pseudo_UPD:
2613     case ARM::VLD4q16Pseudo_UPD:
2614     case ARM::VLD4q32Pseudo_UPD:
2615     case ARM::VLD4q8oddPseudo:
2616     case ARM::VLD4q16oddPseudo:
2617     case ARM::VLD4q32oddPseudo:
2618     case ARM::VLD4q8oddPseudo_UPD:
2619     case ARM::VLD4q16oddPseudo_UPD:
2620     case ARM::VLD4q32oddPseudo_UPD:
2621     case ARM::VLD1DUPq8Pseudo:
2622     case ARM::VLD1DUPq16Pseudo:
2623     case ARM::VLD1DUPq32Pseudo:
2624     case ARM::VLD1DUPq8Pseudo_UPD:
2625     case ARM::VLD1DUPq16Pseudo_UPD:
2626     case ARM::VLD1DUPq32Pseudo_UPD:
2627     case ARM::VLD2DUPd8Pseudo:
2628     case ARM::VLD2DUPd16Pseudo:
2629     case ARM::VLD2DUPd32Pseudo:
2630     case ARM::VLD2DUPd8Pseudo_UPD:
2631     case ARM::VLD2DUPd16Pseudo_UPD:
2632     case ARM::VLD2DUPd32Pseudo_UPD:
2633     case ARM::VLD4DUPd8Pseudo:
2634     case ARM::VLD4DUPd16Pseudo:
2635     case ARM::VLD4DUPd32Pseudo:
2636     case ARM::VLD4DUPd8Pseudo_UPD:
2637     case ARM::VLD4DUPd16Pseudo_UPD:
2638     case ARM::VLD4DUPd32Pseudo_UPD:
2639     case ARM::VLD1LNq8Pseudo:
2640     case ARM::VLD1LNq16Pseudo:
2641     case ARM::VLD1LNq32Pseudo:
2642     case ARM::VLD1LNq8Pseudo_UPD:
2643     case ARM::VLD1LNq16Pseudo_UPD:
2644     case ARM::VLD1LNq32Pseudo_UPD:
2645     case ARM::VLD2LNd8Pseudo:
2646     case ARM::VLD2LNd16Pseudo:
2647     case ARM::VLD2LNd32Pseudo:
2648     case ARM::VLD2LNq16Pseudo:
2649     case ARM::VLD2LNq32Pseudo:
2650     case ARM::VLD2LNd8Pseudo_UPD:
2651     case ARM::VLD2LNd16Pseudo_UPD:
2652     case ARM::VLD2LNd32Pseudo_UPD:
2653     case ARM::VLD2LNq16Pseudo_UPD:
2654     case ARM::VLD2LNq32Pseudo_UPD:
2655     case ARM::VLD4LNd8Pseudo:
2656     case ARM::VLD4LNd16Pseudo:
2657     case ARM::VLD4LNd32Pseudo:
2658     case ARM::VLD4LNq16Pseudo:
2659     case ARM::VLD4LNq32Pseudo:
2660     case ARM::VLD4LNd8Pseudo_UPD:
2661     case ARM::VLD4LNd16Pseudo_UPD:
2662     case ARM::VLD4LNd32Pseudo_UPD:
2663     case ARM::VLD4LNq16Pseudo_UPD:
2664     case ARM::VLD4LNq32Pseudo_UPD:
2665       // If the address is not 64-bit aligned, the latencies of these
2666       // instructions increases by one.
2667       ++Latency;
2668       break;
2669     }
2670
2671   return Latency;
2672 }
2673
2674 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
2675                                       const MachineInstr *MI,
2676                                       unsigned *PredCost) const {
2677   if (MI->isCopyLike() || MI->isInsertSubreg() ||
2678       MI->isRegSequence() || MI->isImplicitDef())
2679     return 1;
2680
2681   if (!ItinData || ItinData->isEmpty())
2682     return 1;
2683
2684   const MCInstrDesc &MCID = MI->getDesc();
2685   unsigned Class = MCID.getSchedClass();
2686   unsigned UOps = ItinData->Itineraries[Class].NumMicroOps;
2687   if (PredCost && MCID.hasImplicitDefOfPhysReg(ARM::CPSR))
2688     // When predicated, CPSR is an additional source operand for CPSR updating
2689     // instructions, this apparently increases their latencies.
2690     *PredCost = 1;
2691   if (UOps)
2692     return ItinData->getStageLatency(Class);
2693   return getNumMicroOps(ItinData, MI);
2694 }
2695
2696 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
2697                                       SDNode *Node) const {
2698   if (!Node->isMachineOpcode())
2699     return 1;
2700
2701   if (!ItinData || ItinData->isEmpty())
2702     return 1;
2703
2704   unsigned Opcode = Node->getMachineOpcode();
2705   switch (Opcode) {
2706   default:
2707     return ItinData->getStageLatency(get(Opcode).getSchedClass());
2708   case ARM::VLDMQIA:
2709   case ARM::VSTMQIA:
2710     return 2;
2711   }
2712 }
2713
2714 bool ARMBaseInstrInfo::
2715 hasHighOperandLatency(const InstrItineraryData *ItinData,
2716                       const MachineRegisterInfo *MRI,
2717                       const MachineInstr *DefMI, unsigned DefIdx,
2718                       const MachineInstr *UseMI, unsigned UseIdx) const {
2719   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
2720   unsigned UDomain = UseMI->getDesc().TSFlags & ARMII::DomainMask;
2721   if (Subtarget.isCortexA8() &&
2722       (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
2723     // CortexA8 VFP instructions are not pipelined.
2724     return true;
2725
2726   // Hoist VFP / NEON instructions with 4 or higher latency.
2727   int Latency = getOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
2728   if (Latency <= 3)
2729     return false;
2730   return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
2731          UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
2732 }
2733
2734 bool ARMBaseInstrInfo::
2735 hasLowDefLatency(const InstrItineraryData *ItinData,
2736                  const MachineInstr *DefMI, unsigned DefIdx) const {
2737   if (!ItinData || ItinData->isEmpty())
2738     return false;
2739
2740   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
2741   if (DDomain == ARMII::DomainGeneral) {
2742     unsigned DefClass = DefMI->getDesc().getSchedClass();
2743     int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
2744     return (DefCycle != -1 && DefCycle <= 2);
2745   }
2746   return false;
2747 }
2748
2749 bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr *MI,
2750                                          StringRef &ErrInfo) const {
2751   if (convertAddSubFlagsOpcode(MI->getOpcode())) {
2752     ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG";
2753     return false;
2754   }
2755   return true;
2756 }
2757
2758 bool
2759 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
2760                                      unsigned &AddSubOpc,
2761                                      bool &NegAcc, bool &HasLane) const {
2762   DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
2763   if (I == MLxEntryMap.end())
2764     return false;
2765
2766   const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
2767   MulOpc = Entry.MulOpc;
2768   AddSubOpc = Entry.AddSubOpc;
2769   NegAcc = Entry.NegAcc;
2770   HasLane = Entry.HasLane;
2771   return true;
2772 }
2773
2774 //===----------------------------------------------------------------------===//
2775 // Execution domains.
2776 //===----------------------------------------------------------------------===//
2777 //
2778 // Some instructions go down the NEON pipeline, some go down the VFP pipeline,
2779 // and some can go down both.  The vmov instructions go down the VFP pipeline,
2780 // but they can be changed to vorr equivalents that are executed by the NEON
2781 // pipeline.
2782 //
2783 // We use the following execution domain numbering:
2784 //
2785 enum ARMExeDomain {
2786   ExeGeneric = 0,
2787   ExeVFP = 1,
2788   ExeNEON = 2
2789 };
2790 //
2791 // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h
2792 //
2793 std::pair<uint16_t, uint16_t>
2794 ARMBaseInstrInfo::getExecutionDomain(const MachineInstr *MI) const {
2795   // VMOVD is a VFP instruction, but can be changed to NEON if it isn't
2796   // predicated.
2797   if (MI->getOpcode() == ARM::VMOVD && !isPredicated(MI))
2798     return std::make_pair(ExeVFP, (1<<ExeVFP) | (1<<ExeNEON));
2799
2800   // No other instructions can be swizzled, so just determine their domain.
2801   unsigned Domain = MI->getDesc().TSFlags & ARMII::DomainMask;
2802
2803   if (Domain & ARMII::DomainNEON)
2804     return std::make_pair(ExeNEON, 0);
2805
2806   // Certain instructions can go either way on Cortex-A8.
2807   // Treat them as NEON instructions.
2808   if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8())
2809     return std::make_pair(ExeNEON, 0);
2810
2811   if (Domain & ARMII::DomainVFP)
2812     return std::make_pair(ExeVFP, 0);
2813
2814   return std::make_pair(ExeGeneric, 0);
2815 }
2816
2817 void
2818 ARMBaseInstrInfo::setExecutionDomain(MachineInstr *MI, unsigned Domain) const {
2819   // We only know how to change VMOVD into VORR.
2820   assert(MI->getOpcode() == ARM::VMOVD && "Can only swizzle VMOVD");
2821   if (Domain != ExeNEON)
2822     return;
2823
2824   // Zap the predicate operands.
2825   assert(!isPredicated(MI) && "Cannot predicate a VORRd");
2826   MI->RemoveOperand(3);
2827   MI->RemoveOperand(2);
2828
2829   // Change to a VORRd which requires two identical use operands.
2830   MI->setDesc(get(ARM::VORRd));
2831
2832   // Add the extra source operand and new predicates.
2833   // This will go before any implicit ops.
2834   AddDefaultPred(MachineInstrBuilder(MI).addOperand(MI->getOperand(1)));
2835 }