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