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