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