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