Rewrite some ARM InstrInfo functions to be most accepting of arbitrary register subcl...
[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;
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   else if (ARM::QQPRRegClass.contains(DestReg, SrcReg))
670     Opc = ARM::VMOVQQ;
671   else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg))
672     Opc = ARM::VMOVQQQQ;
673   else
674     llvm_unreachable("Impossible reg-to-reg copy");
675
676   MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
677   MIB.addReg(SrcReg, getKillRegState(KillSrc));
678   if (Opc == ARM::VORRq)
679     MIB.addReg(SrcReg, getKillRegState(KillSrc));
680   if (Opc != ARM::VMOVQQ && Opc != ARM::VMOVQQQQ)
681     AddDefaultPred(MIB);
682 }
683
684 static const
685 MachineInstrBuilder &AddDReg(MachineInstrBuilder &MIB,
686                              unsigned Reg, unsigned SubIdx, unsigned State,
687                              const TargetRegisterInfo *TRI) {
688   if (!SubIdx)
689     return MIB.addReg(Reg, State);
690
691   if (TargetRegisterInfo::isPhysicalRegister(Reg))
692     return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
693   return MIB.addReg(Reg, State, SubIdx);
694 }
695
696 void ARMBaseInstrInfo::
697 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
698                     unsigned SrcReg, bool isKill, int FI,
699                     const TargetRegisterClass *RC,
700                     const TargetRegisterInfo *TRI) const {
701   DebugLoc DL;
702   if (I != MBB.end()) DL = I->getDebugLoc();
703   MachineFunction &MF = *MBB.getParent();
704   MachineFrameInfo &MFI = *MF.getFrameInfo();
705   unsigned Align = MFI.getObjectAlignment(FI);
706
707   MachineMemOperand *MMO =
708     MF.getMachineMemOperand(MachinePointerInfo(
709                                          PseudoSourceValue::getFixedStack(FI)),
710                             MachineMemOperand::MOStore,
711                             MFI.getObjectSize(FI),
712                             Align);
713
714   switch (RC->getSize()) {
715     case 4:
716       if (ARM::GPRRegClass.hasSubClassEq(RC)) {
717         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STRi12))
718                    .addReg(SrcReg, getKillRegState(isKill))
719                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
720       } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
721         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRS))
722                    .addReg(SrcReg, getKillRegState(isKill))
723                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
724       } else
725         llvm_unreachable("Unknown reg class!");
726       break;
727     case 8:
728       if (ARM::DPRRegClass.hasSubClassEq(RC)) {
729         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRD))
730                    .addReg(SrcReg, getKillRegState(isKill))
731                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
732       } else
733         llvm_unreachable("Unknown reg class!");
734       break;
735     case 16:
736       if (ARM::QPRRegClass.hasSubClassEq(RC)) {
737         if (Align >= 16 && getRegisterInfo().needsStackRealignment(MF)) {
738           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q64Pseudo))
739                      .addFrameIndex(FI).addImm(16)
740                      .addReg(SrcReg, getKillRegState(isKill))
741                      .addMemOperand(MMO));
742         } else {
743           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMQIA))
744                      .addReg(SrcReg, getKillRegState(isKill))
745                      .addFrameIndex(FI)
746                      .addMemOperand(MMO));
747         }
748       } else
749         llvm_unreachable("Unknown reg class!");
750       break;
751     case 32:
752       if (ARM::QQPRRegClass.hasSubClassEq(RC)) {
753         if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
754           // FIXME: It's possible to only store part of the QQ register if the
755           // spilled def has a sub-register index.
756           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64QPseudo))
757                      .addFrameIndex(FI).addImm(16)
758                      .addReg(SrcReg, getKillRegState(isKill))
759                      .addMemOperand(MMO));
760         } else {
761           MachineInstrBuilder MIB =
762           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
763                        .addFrameIndex(FI))
764                        .addMemOperand(MMO);
765           MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
766           MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
767           MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
768                 AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
769         }
770       } else
771         llvm_unreachable("Unknown reg class!");
772       break;
773     case 64:
774       if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
775         MachineInstrBuilder MIB =
776           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
777                          .addFrameIndex(FI))
778                          .addMemOperand(MMO);
779         MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
780         MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
781         MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
782         MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
783         MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
784         MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
785         MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
786               AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
787       } else
788         llvm_unreachable("Unknown reg class!");
789       break;
790     default:
791       llvm_unreachable("Unknown reg class!");
792   }
793 }
794
795 unsigned
796 ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
797                                      int &FrameIndex) const {
798   switch (MI->getOpcode()) {
799   default: break;
800   case ARM::STRrs:
801   case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
802     if (MI->getOperand(1).isFI() &&
803         MI->getOperand(2).isReg() &&
804         MI->getOperand(3).isImm() &&
805         MI->getOperand(2).getReg() == 0 &&
806         MI->getOperand(3).getImm() == 0) {
807       FrameIndex = MI->getOperand(1).getIndex();
808       return MI->getOperand(0).getReg();
809     }
810     break;
811   case ARM::STRi12:
812   case ARM::t2STRi12:
813   case ARM::tSTRspi:
814   case ARM::VSTRD:
815   case ARM::VSTRS:
816     if (MI->getOperand(1).isFI() &&
817         MI->getOperand(2).isImm() &&
818         MI->getOperand(2).getImm() == 0) {
819       FrameIndex = MI->getOperand(1).getIndex();
820       return MI->getOperand(0).getReg();
821     }
822     break;
823   case ARM::VST1q64Pseudo:
824     if (MI->getOperand(0).isFI() &&
825         MI->getOperand(2).getSubReg() == 0) {
826       FrameIndex = MI->getOperand(0).getIndex();
827       return MI->getOperand(2).getReg();
828     }
829     break;
830   case ARM::VSTMQIA:
831     if (MI->getOperand(1).isFI() &&
832         MI->getOperand(0).getSubReg() == 0) {
833       FrameIndex = MI->getOperand(1).getIndex();
834       return MI->getOperand(0).getReg();
835     }
836     break;
837   }
838
839   return 0;
840 }
841
842 unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr *MI,
843                                                     int &FrameIndex) const {
844   const MachineMemOperand *Dummy;
845   return MI->getDesc().mayStore() && hasStoreToStackSlot(MI, Dummy, FrameIndex);
846 }
847
848 void ARMBaseInstrInfo::
849 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
850                      unsigned DestReg, int FI,
851                      const TargetRegisterClass *RC,
852                      const TargetRegisterInfo *TRI) const {
853   DebugLoc DL;
854   if (I != MBB.end()) DL = I->getDebugLoc();
855   MachineFunction &MF = *MBB.getParent();
856   MachineFrameInfo &MFI = *MF.getFrameInfo();
857   unsigned Align = MFI.getObjectAlignment(FI);
858   MachineMemOperand *MMO =
859     MF.getMachineMemOperand(
860                     MachinePointerInfo(PseudoSourceValue::getFixedStack(FI)),
861                             MachineMemOperand::MOLoad,
862                             MFI.getObjectSize(FI),
863                             Align);
864
865   switch (RC->getSize()) {
866   case 4:
867     if (ARM::GPRRegClass.hasSubClassEq(RC)) {
868       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
869                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
870
871     } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
872       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
873                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
874     } else
875       llvm_unreachable("Unknown reg class!");
876     break;
877   case 8:
878     if (ARM::DPRRegClass.hasSubClassEq(RC)) {
879       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
880                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
881     } else
882       llvm_unreachable("Unknown reg class!");
883     break;
884   case 16:
885     if (ARM::QPRRegClass.hasSubClassEq(RC)) {
886       if (Align >= 16 && getRegisterInfo().needsStackRealignment(MF)) {
887         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q64Pseudo), DestReg)
888                      .addFrameIndex(FI).addImm(16)
889                      .addMemOperand(MMO));
890       } else {
891         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
892                        .addFrameIndex(FI)
893                        .addMemOperand(MMO));
894       }
895     } else
896       llvm_unreachable("Unknown reg class!");
897     break;
898   case 32:
899     if (ARM::QQPRRegClass.hasSubClassEq(RC)) {
900       if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
901         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
902                      .addFrameIndex(FI).addImm(16)
903                      .addMemOperand(MMO));
904       } else {
905         MachineInstrBuilder MIB =
906         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
907                        .addFrameIndex(FI))
908                        .addMemOperand(MMO);
909         MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
910         MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
911         MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
912               AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
913       }
914     } else
915       llvm_unreachable("Unknown reg class!");
916     break;
917   case 64:
918     if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
919       MachineInstrBuilder MIB =
920       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
921                      .addFrameIndex(FI))
922                      .addMemOperand(MMO);
923       MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::Define, TRI);
924       MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::Define, TRI);
925       MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::Define, TRI);
926       MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::Define, TRI);
927       MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::Define, TRI);
928       MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::Define, TRI);
929       MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::Define, TRI);
930       AddDReg(MIB, DestReg, ARM::dsub_7, RegState::Define, TRI);
931     } else
932       llvm_unreachable("Unknown reg class!");
933     break;
934   default:
935     llvm_unreachable("Unknown regclass!");
936   }
937 }
938
939 unsigned
940 ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
941                                       int &FrameIndex) const {
942   switch (MI->getOpcode()) {
943   default: break;
944   case ARM::LDRrs:
945   case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
946     if (MI->getOperand(1).isFI() &&
947         MI->getOperand(2).isReg() &&
948         MI->getOperand(3).isImm() &&
949         MI->getOperand(2).getReg() == 0 &&
950         MI->getOperand(3).getImm() == 0) {
951       FrameIndex = MI->getOperand(1).getIndex();
952       return MI->getOperand(0).getReg();
953     }
954     break;
955   case ARM::LDRi12:
956   case ARM::t2LDRi12:
957   case ARM::tLDRspi:
958   case ARM::VLDRD:
959   case ARM::VLDRS:
960     if (MI->getOperand(1).isFI() &&
961         MI->getOperand(2).isImm() &&
962         MI->getOperand(2).getImm() == 0) {
963       FrameIndex = MI->getOperand(1).getIndex();
964       return MI->getOperand(0).getReg();
965     }
966     break;
967   case ARM::VLD1q64Pseudo:
968     if (MI->getOperand(1).isFI() &&
969         MI->getOperand(0).getSubReg() == 0) {
970       FrameIndex = MI->getOperand(1).getIndex();
971       return MI->getOperand(0).getReg();
972     }
973     break;
974   case ARM::VLDMQIA:
975     if (MI->getOperand(1).isFI() &&
976         MI->getOperand(0).getSubReg() == 0) {
977       FrameIndex = MI->getOperand(1).getIndex();
978       return MI->getOperand(0).getReg();
979     }
980     break;
981   }
982
983   return 0;
984 }
985
986 unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr *MI,
987                                              int &FrameIndex) const {
988   const MachineMemOperand *Dummy;
989   return MI->getDesc().mayLoad() && hasLoadFromStackSlot(MI, Dummy, FrameIndex);
990 }
991
992 MachineInstr*
993 ARMBaseInstrInfo::emitFrameIndexDebugValue(MachineFunction &MF,
994                                            int FrameIx, uint64_t Offset,
995                                            const MDNode *MDPtr,
996                                            DebugLoc DL) const {
997   MachineInstrBuilder MIB = BuildMI(MF, DL, get(ARM::DBG_VALUE))
998     .addFrameIndex(FrameIx).addImm(0).addImm(Offset).addMetadata(MDPtr);
999   return &*MIB;
1000 }
1001
1002 /// Create a copy of a const pool value. Update CPI to the new index and return
1003 /// the label UID.
1004 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
1005   MachineConstantPool *MCP = MF.getConstantPool();
1006   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1007
1008   const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
1009   assert(MCPE.isMachineConstantPoolEntry() &&
1010          "Expecting a machine constantpool entry!");
1011   ARMConstantPoolValue *ACPV =
1012     static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
1013
1014   unsigned PCLabelId = AFI->createPICLabelUId();
1015   ARMConstantPoolValue *NewCPV = 0;
1016   // FIXME: The below assumes PIC relocation model and that the function
1017   // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
1018   // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
1019   // instructions, so that's probably OK, but is PIC always correct when
1020   // we get here?
1021   if (ACPV->isGlobalValue())
1022     NewCPV = new ARMConstantPoolValue(ACPV->getGV(), PCLabelId,
1023                                       ARMCP::CPValue, 4);
1024   else if (ACPV->isExtSymbol())
1025     NewCPV = new ARMConstantPoolValue(MF.getFunction()->getContext(),
1026                                       ACPV->getSymbol(), PCLabelId, 4);
1027   else if (ACPV->isBlockAddress())
1028     NewCPV = new ARMConstantPoolValue(ACPV->getBlockAddress(), PCLabelId,
1029                                       ARMCP::CPBlockAddress, 4);
1030   else if (ACPV->isLSDA())
1031     NewCPV = new ARMConstantPoolValue(MF.getFunction(), PCLabelId,
1032                                       ARMCP::CPLSDA, 4);
1033   else
1034     llvm_unreachable("Unexpected ARM constantpool value type!!");
1035   CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
1036   return PCLabelId;
1037 }
1038
1039 void ARMBaseInstrInfo::
1040 reMaterialize(MachineBasicBlock &MBB,
1041               MachineBasicBlock::iterator I,
1042               unsigned DestReg, unsigned SubIdx,
1043               const MachineInstr *Orig,
1044               const TargetRegisterInfo &TRI) const {
1045   unsigned Opcode = Orig->getOpcode();
1046   switch (Opcode) {
1047   default: {
1048     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
1049     MI->substituteRegister(Orig->getOperand(0).getReg(), DestReg, SubIdx, TRI);
1050     MBB.insert(I, MI);
1051     break;
1052   }
1053   case ARM::tLDRpci_pic:
1054   case ARM::t2LDRpci_pic: {
1055     MachineFunction &MF = *MBB.getParent();
1056     unsigned CPI = Orig->getOperand(1).getIndex();
1057     unsigned PCLabelId = duplicateCPV(MF, CPI);
1058     MachineInstrBuilder MIB = BuildMI(MBB, I, Orig->getDebugLoc(), get(Opcode),
1059                                       DestReg)
1060       .addConstantPoolIndex(CPI).addImm(PCLabelId);
1061     MIB->setMemRefs(Orig->memoperands_begin(), Orig->memoperands_end());
1062     break;
1063   }
1064   }
1065 }
1066
1067 MachineInstr *
1068 ARMBaseInstrInfo::duplicate(MachineInstr *Orig, MachineFunction &MF) const {
1069   MachineInstr *MI = TargetInstrInfoImpl::duplicate(Orig, MF);
1070   switch(Orig->getOpcode()) {
1071   case ARM::tLDRpci_pic:
1072   case ARM::t2LDRpci_pic: {
1073     unsigned CPI = Orig->getOperand(1).getIndex();
1074     unsigned PCLabelId = duplicateCPV(MF, CPI);
1075     Orig->getOperand(1).setIndex(CPI);
1076     Orig->getOperand(2).setImm(PCLabelId);
1077     break;
1078   }
1079   }
1080   return MI;
1081 }
1082
1083 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr *MI0,
1084                                         const MachineInstr *MI1,
1085                                         const MachineRegisterInfo *MRI) const {
1086   int Opcode = MI0->getOpcode();
1087   if (Opcode == ARM::t2LDRpci ||
1088       Opcode == ARM::t2LDRpci_pic ||
1089       Opcode == ARM::tLDRpci ||
1090       Opcode == ARM::tLDRpci_pic ||
1091       Opcode == ARM::MOV_ga_dyn ||
1092       Opcode == ARM::MOV_ga_pcrel ||
1093       Opcode == ARM::MOV_ga_pcrel_ldr ||
1094       Opcode == ARM::t2MOV_ga_dyn ||
1095       Opcode == ARM::t2MOV_ga_pcrel) {
1096     if (MI1->getOpcode() != Opcode)
1097       return false;
1098     if (MI0->getNumOperands() != MI1->getNumOperands())
1099       return false;
1100
1101     const MachineOperand &MO0 = MI0->getOperand(1);
1102     const MachineOperand &MO1 = MI1->getOperand(1);
1103     if (MO0.getOffset() != MO1.getOffset())
1104       return false;
1105
1106     if (Opcode == ARM::MOV_ga_dyn ||
1107         Opcode == ARM::MOV_ga_pcrel ||
1108         Opcode == ARM::MOV_ga_pcrel_ldr ||
1109         Opcode == ARM::t2MOV_ga_dyn ||
1110         Opcode == ARM::t2MOV_ga_pcrel)
1111       // Ignore the PC labels.
1112       return MO0.getGlobal() == MO1.getGlobal();
1113
1114     const MachineFunction *MF = MI0->getParent()->getParent();
1115     const MachineConstantPool *MCP = MF->getConstantPool();
1116     int CPI0 = MO0.getIndex();
1117     int CPI1 = MO1.getIndex();
1118     const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1119     const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1120     bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
1121     bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
1122     if (isARMCP0 && isARMCP1) {
1123       ARMConstantPoolValue *ACPV0 =
1124         static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1125       ARMConstantPoolValue *ACPV1 =
1126         static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1127       return ACPV0->hasSameValue(ACPV1);
1128     } else if (!isARMCP0 && !isARMCP1) {
1129       return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
1130     }
1131     return false;
1132   } else if (Opcode == ARM::PICLDR) {
1133     if (MI1->getOpcode() != Opcode)
1134       return false;
1135     if (MI0->getNumOperands() != MI1->getNumOperands())
1136       return false;
1137
1138     unsigned Addr0 = MI0->getOperand(1).getReg();
1139     unsigned Addr1 = MI1->getOperand(1).getReg();
1140     if (Addr0 != Addr1) {
1141       if (!MRI ||
1142           !TargetRegisterInfo::isVirtualRegister(Addr0) ||
1143           !TargetRegisterInfo::isVirtualRegister(Addr1))
1144         return false;
1145
1146       // This assumes SSA form.
1147       MachineInstr *Def0 = MRI->getVRegDef(Addr0);
1148       MachineInstr *Def1 = MRI->getVRegDef(Addr1);
1149       // Check if the loaded value, e.g. a constantpool of a global address, are
1150       // the same.
1151       if (!produceSameValue(Def0, Def1, MRI))
1152         return false;
1153     }
1154
1155     for (unsigned i = 3, e = MI0->getNumOperands(); i != e; ++i) {
1156       // %vreg12<def> = PICLDR %vreg11, 0, pred:14, pred:%noreg
1157       const MachineOperand &MO0 = MI0->getOperand(i);
1158       const MachineOperand &MO1 = MI1->getOperand(i);
1159       if (!MO0.isIdenticalTo(MO1))
1160         return false;
1161     }
1162     return true;
1163   }
1164
1165   return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1166 }
1167
1168 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1169 /// determine if two loads are loading from the same base address. It should
1170 /// only return true if the base pointers are the same and the only differences
1171 /// between the two addresses is the offset. It also returns the offsets by
1172 /// reference.
1173 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1174                                                int64_t &Offset1,
1175                                                int64_t &Offset2) const {
1176   // Don't worry about Thumb: just ARM and Thumb2.
1177   if (Subtarget.isThumb1Only()) return false;
1178
1179   if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1180     return false;
1181
1182   switch (Load1->getMachineOpcode()) {
1183   default:
1184     return false;
1185   case ARM::LDRi12:
1186   case ARM::LDRBi12:
1187   case ARM::LDRD:
1188   case ARM::LDRH:
1189   case ARM::LDRSB:
1190   case ARM::LDRSH:
1191   case ARM::VLDRD:
1192   case ARM::VLDRS:
1193   case ARM::t2LDRi8:
1194   case ARM::t2LDRDi8:
1195   case ARM::t2LDRSHi8:
1196   case ARM::t2LDRi12:
1197   case ARM::t2LDRSHi12:
1198     break;
1199   }
1200
1201   switch (Load2->getMachineOpcode()) {
1202   default:
1203     return false;
1204   case ARM::LDRi12:
1205   case ARM::LDRBi12:
1206   case ARM::LDRD:
1207   case ARM::LDRH:
1208   case ARM::LDRSB:
1209   case ARM::LDRSH:
1210   case ARM::VLDRD:
1211   case ARM::VLDRS:
1212   case ARM::t2LDRi8:
1213   case ARM::t2LDRDi8:
1214   case ARM::t2LDRSHi8:
1215   case ARM::t2LDRi12:
1216   case ARM::t2LDRSHi12:
1217     break;
1218   }
1219
1220   // Check if base addresses and chain operands match.
1221   if (Load1->getOperand(0) != Load2->getOperand(0) ||
1222       Load1->getOperand(4) != Load2->getOperand(4))
1223     return false;
1224
1225   // Index should be Reg0.
1226   if (Load1->getOperand(3) != Load2->getOperand(3))
1227     return false;
1228
1229   // Determine the offsets.
1230   if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1231       isa<ConstantSDNode>(Load2->getOperand(1))) {
1232     Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1233     Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1234     return true;
1235   }
1236
1237   return false;
1238 }
1239
1240 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1241 /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
1242 /// be scheduled togther. On some targets if two loads are loading from
1243 /// addresses in the same cache line, it's better if they are scheduled
1244 /// together. This function takes two integers that represent the load offsets
1245 /// from the common base address. It returns true if it decides it's desirable
1246 /// to schedule the two loads together. "NumLoads" is the number of loads that
1247 /// have already been scheduled after Load1.
1248 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1249                                                int64_t Offset1, int64_t Offset2,
1250                                                unsigned NumLoads) const {
1251   // Don't worry about Thumb: just ARM and Thumb2.
1252   if (Subtarget.isThumb1Only()) return false;
1253
1254   assert(Offset2 > Offset1);
1255
1256   if ((Offset2 - Offset1) / 8 > 64)
1257     return false;
1258
1259   if (Load1->getMachineOpcode() != Load2->getMachineOpcode())
1260     return false;  // FIXME: overly conservative?
1261
1262   // Four loads in a row should be sufficient.
1263   if (NumLoads >= 3)
1264     return false;
1265
1266   return true;
1267 }
1268
1269 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1270                                             const MachineBasicBlock *MBB,
1271                                             const MachineFunction &MF) const {
1272   // Debug info is never a scheduling boundary. It's necessary to be explicit
1273   // due to the special treatment of IT instructions below, otherwise a
1274   // dbg_value followed by an IT will result in the IT instruction being
1275   // considered a scheduling hazard, which is wrong. It should be the actual
1276   // instruction preceding the dbg_value instruction(s), just like it is
1277   // when debug info is not present.
1278   if (MI->isDebugValue())
1279     return false;
1280
1281   // Terminators and labels can't be scheduled around.
1282   if (MI->getDesc().isTerminator() || MI->isLabel())
1283     return true;
1284
1285   // Treat the start of the IT block as a scheduling boundary, but schedule
1286   // t2IT along with all instructions following it.
1287   // FIXME: This is a big hammer. But the alternative is to add all potential
1288   // true and anti dependencies to IT block instructions as implicit operands
1289   // to the t2IT instruction. The added compile time and complexity does not
1290   // seem worth it.
1291   MachineBasicBlock::const_iterator I = MI;
1292   // Make sure to skip any dbg_value instructions
1293   while (++I != MBB->end() && I->isDebugValue())
1294     ;
1295   if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
1296     return true;
1297
1298   // Don't attempt to schedule around any instruction that defines
1299   // a stack-oriented pointer, as it's unlikely to be profitable. This
1300   // saves compile time, because it doesn't require every single
1301   // stack slot reference to depend on the instruction that does the
1302   // modification.
1303   if (MI->definesRegister(ARM::SP))
1304     return true;
1305
1306   return false;
1307 }
1308
1309 bool ARMBaseInstrInfo::
1310 isProfitableToIfCvt(MachineBasicBlock &MBB,
1311                     unsigned NumCycles, unsigned ExtraPredCycles,
1312                     const BranchProbability &Probability) const {
1313   if (!NumCycles)
1314     return false;
1315
1316   // Attempt to estimate the relative costs of predication versus branching.
1317   unsigned UnpredCost = Probability.getNumerator() * NumCycles;
1318   UnpredCost /= Probability.getDenominator();
1319   UnpredCost += 1; // The branch itself
1320   UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1321
1322   return (NumCycles + ExtraPredCycles) <= UnpredCost;
1323 }
1324
1325 bool ARMBaseInstrInfo::
1326 isProfitableToIfCvt(MachineBasicBlock &TMBB,
1327                     unsigned TCycles, unsigned TExtra,
1328                     MachineBasicBlock &FMBB,
1329                     unsigned FCycles, unsigned FExtra,
1330                     const BranchProbability &Probability) const {
1331   if (!TCycles || !FCycles)
1332     return false;
1333
1334   // Attempt to estimate the relative costs of predication versus branching.
1335   unsigned TUnpredCost = Probability.getNumerator() * TCycles;
1336   TUnpredCost /= Probability.getDenominator();
1337     
1338   uint32_t Comp = Probability.getDenominator() - Probability.getNumerator();
1339   unsigned FUnpredCost = Comp * FCycles;
1340   FUnpredCost /= Probability.getDenominator();
1341
1342   unsigned UnpredCost = TUnpredCost + FUnpredCost;
1343   UnpredCost += 1; // The branch itself
1344   UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1345
1346   return (TCycles + FCycles + TExtra + FExtra) <= UnpredCost;
1347 }
1348
1349 /// getInstrPredicate - If instruction is predicated, returns its predicate
1350 /// condition, otherwise returns AL. It also returns the condition code
1351 /// register by reference.
1352 ARMCC::CondCodes
1353 llvm::getInstrPredicate(const MachineInstr *MI, unsigned &PredReg) {
1354   int PIdx = MI->findFirstPredOperandIdx();
1355   if (PIdx == -1) {
1356     PredReg = 0;
1357     return ARMCC::AL;
1358   }
1359
1360   PredReg = MI->getOperand(PIdx+1).getReg();
1361   return (ARMCC::CondCodes)MI->getOperand(PIdx).getImm();
1362 }
1363
1364
1365 int llvm::getMatchingCondBranchOpcode(int Opc) {
1366   if (Opc == ARM::B)
1367     return ARM::Bcc;
1368   else if (Opc == ARM::tB)
1369     return ARM::tBcc;
1370   else if (Opc == ARM::t2B)
1371       return ARM::t2Bcc;
1372
1373   llvm_unreachable("Unknown unconditional branch opcode!");
1374   return 0;
1375 }
1376
1377
1378 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
1379                                MachineBasicBlock::iterator &MBBI, DebugLoc dl,
1380                                unsigned DestReg, unsigned BaseReg, int NumBytes,
1381                                ARMCC::CondCodes Pred, unsigned PredReg,
1382                                const ARMBaseInstrInfo &TII, unsigned MIFlags) {
1383   bool isSub = NumBytes < 0;
1384   if (isSub) NumBytes = -NumBytes;
1385
1386   while (NumBytes) {
1387     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
1388     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
1389     assert(ThisVal && "Didn't extract field correctly");
1390
1391     // We will handle these bits from offset, clear them.
1392     NumBytes &= ~ThisVal;
1393
1394     assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
1395
1396     // Build the new ADD / SUB.
1397     unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
1398     BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
1399       .addReg(BaseReg, RegState::Kill).addImm(ThisVal)
1400       .addImm((unsigned)Pred).addReg(PredReg).addReg(0)
1401       .setMIFlags(MIFlags);
1402     BaseReg = DestReg;
1403   }
1404 }
1405
1406 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
1407                                 unsigned FrameReg, int &Offset,
1408                                 const ARMBaseInstrInfo &TII) {
1409   unsigned Opcode = MI.getOpcode();
1410   const MCInstrDesc &Desc = MI.getDesc();
1411   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1412   bool isSub = false;
1413
1414   // Memory operands in inline assembly always use AddrMode2.
1415   if (Opcode == ARM::INLINEASM)
1416     AddrMode = ARMII::AddrMode2;
1417
1418   if (Opcode == ARM::ADDri) {
1419     Offset += MI.getOperand(FrameRegIdx+1).getImm();
1420     if (Offset == 0) {
1421       // Turn it into a move.
1422       MI.setDesc(TII.get(ARM::MOVr));
1423       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1424       MI.RemoveOperand(FrameRegIdx+1);
1425       Offset = 0;
1426       return true;
1427     } else if (Offset < 0) {
1428       Offset = -Offset;
1429       isSub = true;
1430       MI.setDesc(TII.get(ARM::SUBri));
1431     }
1432
1433     // Common case: small offset, fits into instruction.
1434     if (ARM_AM::getSOImmVal(Offset) != -1) {
1435       // Replace the FrameIndex with sp / fp
1436       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1437       MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
1438       Offset = 0;
1439       return true;
1440     }
1441
1442     // Otherwise, pull as much of the immedidate into this ADDri/SUBri
1443     // as possible.
1444     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
1445     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
1446
1447     // We will handle these bits from offset, clear them.
1448     Offset &= ~ThisImmVal;
1449
1450     // Get the properly encoded SOImmVal field.
1451     assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
1452            "Bit extraction didn't work?");
1453     MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
1454  } else {
1455     unsigned ImmIdx = 0;
1456     int InstrOffs = 0;
1457     unsigned NumBits = 0;
1458     unsigned Scale = 1;
1459     switch (AddrMode) {
1460     case ARMII::AddrMode_i12: {
1461       ImmIdx = FrameRegIdx + 1;
1462       InstrOffs = MI.getOperand(ImmIdx).getImm();
1463       NumBits = 12;
1464       break;
1465     }
1466     case ARMII::AddrMode2: {
1467       ImmIdx = FrameRegIdx+2;
1468       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
1469       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1470         InstrOffs *= -1;
1471       NumBits = 12;
1472       break;
1473     }
1474     case ARMII::AddrMode3: {
1475       ImmIdx = FrameRegIdx+2;
1476       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
1477       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1478         InstrOffs *= -1;
1479       NumBits = 8;
1480       break;
1481     }
1482     case ARMII::AddrMode4:
1483     case ARMII::AddrMode6:
1484       // Can't fold any offset even if it's zero.
1485       return false;
1486     case ARMII::AddrMode5: {
1487       ImmIdx = FrameRegIdx+1;
1488       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
1489       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
1490         InstrOffs *= -1;
1491       NumBits = 8;
1492       Scale = 4;
1493       break;
1494     }
1495     default:
1496       llvm_unreachable("Unsupported addressing mode!");
1497       break;
1498     }
1499
1500     Offset += InstrOffs * Scale;
1501     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
1502     if (Offset < 0) {
1503       Offset = -Offset;
1504       isSub = true;
1505     }
1506
1507     // Attempt to fold address comp. if opcode has offset bits
1508     if (NumBits > 0) {
1509       // Common case: small offset, fits into instruction.
1510       MachineOperand &ImmOp = MI.getOperand(ImmIdx);
1511       int ImmedOffset = Offset / Scale;
1512       unsigned Mask = (1 << NumBits) - 1;
1513       if ((unsigned)Offset <= Mask * Scale) {
1514         // Replace the FrameIndex with sp
1515         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1516         // FIXME: When addrmode2 goes away, this will simplify (like the
1517         // T2 version), as the LDR.i12 versions don't need the encoding
1518         // tricks for the offset value.
1519         if (isSub) {
1520           if (AddrMode == ARMII::AddrMode_i12)
1521             ImmedOffset = -ImmedOffset;
1522           else
1523             ImmedOffset |= 1 << NumBits;
1524         }
1525         ImmOp.ChangeToImmediate(ImmedOffset);
1526         Offset = 0;
1527         return true;
1528       }
1529
1530       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
1531       ImmedOffset = ImmedOffset & Mask;
1532       if (isSub) {
1533         if (AddrMode == ARMII::AddrMode_i12)
1534           ImmedOffset = -ImmedOffset;
1535         else
1536           ImmedOffset |= 1 << NumBits;
1537       }
1538       ImmOp.ChangeToImmediate(ImmedOffset);
1539       Offset &= ~(Mask*Scale);
1540     }
1541   }
1542
1543   Offset = (isSub) ? -Offset : Offset;
1544   return Offset == 0;
1545 }
1546
1547 bool ARMBaseInstrInfo::
1548 AnalyzeCompare(const MachineInstr *MI, unsigned &SrcReg, int &CmpMask,
1549                int &CmpValue) const {
1550   switch (MI->getOpcode()) {
1551   default: break;
1552   case ARM::CMPri:
1553   case ARM::t2CMPri:
1554     SrcReg = MI->getOperand(0).getReg();
1555     CmpMask = ~0;
1556     CmpValue = MI->getOperand(1).getImm();
1557     return true;
1558   case ARM::TSTri:
1559   case ARM::t2TSTri:
1560     SrcReg = MI->getOperand(0).getReg();
1561     CmpMask = MI->getOperand(1).getImm();
1562     CmpValue = 0;
1563     return true;
1564   }
1565
1566   return false;
1567 }
1568
1569 /// isSuitableForMask - Identify a suitable 'and' instruction that
1570 /// operates on the given source register and applies the same mask
1571 /// as a 'tst' instruction. Provide a limited look-through for copies.
1572 /// When successful, MI will hold the found instruction.
1573 static bool isSuitableForMask(MachineInstr *&MI, unsigned SrcReg,
1574                               int CmpMask, bool CommonUse) {
1575   switch (MI->getOpcode()) {
1576     case ARM::ANDri:
1577     case ARM::t2ANDri:
1578       if (CmpMask != MI->getOperand(2).getImm())
1579         return false;
1580       if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
1581         return true;
1582       break;
1583     case ARM::COPY: {
1584       // Walk down one instruction which is potentially an 'and'.
1585       const MachineInstr &Copy = *MI;
1586       MachineBasicBlock::iterator AND(
1587         llvm::next(MachineBasicBlock::iterator(MI)));
1588       if (AND == MI->getParent()->end()) return false;
1589       MI = AND;
1590       return isSuitableForMask(MI, Copy.getOperand(0).getReg(),
1591                                CmpMask, true);
1592     }
1593   }
1594
1595   return false;
1596 }
1597
1598 /// OptimizeCompareInstr - Convert the instruction supplying the argument to the
1599 /// comparison into one that sets the zero bit in the flags register.
1600 bool ARMBaseInstrInfo::
1601 OptimizeCompareInstr(MachineInstr *CmpInstr, unsigned SrcReg, int CmpMask,
1602                      int CmpValue, const MachineRegisterInfo *MRI) const {
1603   if (CmpValue != 0)
1604     return false;
1605
1606   MachineRegisterInfo::def_iterator DI = MRI->def_begin(SrcReg);
1607   if (llvm::next(DI) != MRI->def_end())
1608     // Only support one definition.
1609     return false;
1610
1611   MachineInstr *MI = &*DI;
1612
1613   // Masked compares sometimes use the same register as the corresponding 'and'.
1614   if (CmpMask != ~0) {
1615     if (!isSuitableForMask(MI, SrcReg, CmpMask, false)) {
1616       MI = 0;
1617       for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SrcReg),
1618            UE = MRI->use_end(); UI != UE; ++UI) {
1619         if (UI->getParent() != CmpInstr->getParent()) continue;
1620         MachineInstr *PotentialAND = &*UI;
1621         if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true))
1622           continue;
1623         MI = PotentialAND;
1624         break;
1625       }
1626       if (!MI) return false;
1627     }
1628   }
1629
1630   // Conservatively refuse to convert an instruction which isn't in the same BB
1631   // as the comparison.
1632   if (MI->getParent() != CmpInstr->getParent())
1633     return false;
1634
1635   // Check that CPSR isn't set between the comparison instruction and the one we
1636   // want to change.
1637   MachineBasicBlock::const_iterator I = CmpInstr, E = MI,
1638     B = MI->getParent()->begin();
1639
1640   // Early exit if CmpInstr is at the beginning of the BB.
1641   if (I == B) return false;
1642
1643   --I;
1644   for (; I != E; --I) {
1645     const MachineInstr &Instr = *I;
1646
1647     for (unsigned IO = 0, EO = Instr.getNumOperands(); IO != EO; ++IO) {
1648       const MachineOperand &MO = Instr.getOperand(IO);
1649       if (!MO.isReg()) continue;
1650
1651       // This instruction modifies or uses CPSR after the one we want to
1652       // change. We can't do this transformation.
1653       if (MO.getReg() == ARM::CPSR)
1654         return false;
1655     }
1656
1657     if (I == B)
1658       // The 'and' is below the comparison instruction.
1659       return false;
1660   }
1661
1662   // Set the "zero" bit in CPSR.
1663   switch (MI->getOpcode()) {
1664   default: break;
1665   case ARM::RSBrr:
1666   case ARM::RSBri:
1667   case ARM::RSCrr:
1668   case ARM::RSCri:
1669   case ARM::ADDrr:
1670   case ARM::ADDri:
1671   case ARM::ADCrr:
1672   case ARM::ADCri:
1673   case ARM::SUBrr:
1674   case ARM::SUBri:
1675   case ARM::SBCrr:
1676   case ARM::SBCri:
1677   case ARM::t2RSBri:
1678   case ARM::t2ADDrr:
1679   case ARM::t2ADDri:
1680   case ARM::t2ADCrr:
1681   case ARM::t2ADCri:
1682   case ARM::t2SUBrr:
1683   case ARM::t2SUBri:
1684   case ARM::t2SBCrr:
1685   case ARM::t2SBCri:
1686   case ARM::ANDrr:
1687   case ARM::ANDri:
1688   case ARM::t2ANDrr:
1689   case ARM::t2ANDri:
1690   case ARM::ORRrr:
1691   case ARM::ORRri:
1692   case ARM::t2ORRrr:
1693   case ARM::t2ORRri:
1694   case ARM::EORrr:
1695   case ARM::EORri:
1696   case ARM::t2EORrr:
1697   case ARM::t2EORri: {
1698     // Scan forward for the use of CPSR, if it's a conditional code requires
1699     // checking of V bit, then this is not safe to do. If we can't find the
1700     // CPSR use (i.e. used in another block), then it's not safe to perform
1701     // the optimization.
1702     bool isSafe = false;
1703     I = CmpInstr;
1704     E = MI->getParent()->end();
1705     while (!isSafe && ++I != E) {
1706       const MachineInstr &Instr = *I;
1707       for (unsigned IO = 0, EO = Instr.getNumOperands();
1708            !isSafe && IO != EO; ++IO) {
1709         const MachineOperand &MO = Instr.getOperand(IO);
1710         if (!MO.isReg() || MO.getReg() != ARM::CPSR)
1711           continue;
1712         if (MO.isDef()) {
1713           isSafe = true;
1714           break;
1715         }
1716         // Condition code is after the operand before CPSR.
1717         ARMCC::CondCodes CC = (ARMCC::CondCodes)Instr.getOperand(IO-1).getImm();
1718         switch (CC) {
1719         default:
1720           isSafe = true;
1721           break;
1722         case ARMCC::VS:
1723         case ARMCC::VC:
1724         case ARMCC::GE:
1725         case ARMCC::LT:
1726         case ARMCC::GT:
1727         case ARMCC::LE:
1728           return false;
1729         }
1730       }
1731     }
1732
1733     if (!isSafe)
1734       return false;
1735
1736     // Toggle the optional operand to CPSR.
1737     MI->getOperand(5).setReg(ARM::CPSR);
1738     MI->getOperand(5).setIsDef(true);
1739     CmpInstr->eraseFromParent();
1740     return true;
1741   }
1742   }
1743
1744   return false;
1745 }
1746
1747 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr *UseMI,
1748                                      MachineInstr *DefMI, unsigned Reg,
1749                                      MachineRegisterInfo *MRI) const {
1750   // Fold large immediates into add, sub, or, xor.
1751   unsigned DefOpc = DefMI->getOpcode();
1752   if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
1753     return false;
1754   if (!DefMI->getOperand(1).isImm())
1755     // Could be t2MOVi32imm <ga:xx>
1756     return false;
1757
1758   if (!MRI->hasOneNonDBGUse(Reg))
1759     return false;
1760
1761   unsigned UseOpc = UseMI->getOpcode();
1762   unsigned NewUseOpc = 0;
1763   uint32_t ImmVal = (uint32_t)DefMI->getOperand(1).getImm();
1764   uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
1765   bool Commute = false;
1766   switch (UseOpc) {
1767   default: return false;
1768   case ARM::SUBrr:
1769   case ARM::ADDrr:
1770   case ARM::ORRrr:
1771   case ARM::EORrr:
1772   case ARM::t2SUBrr:
1773   case ARM::t2ADDrr:
1774   case ARM::t2ORRrr:
1775   case ARM::t2EORrr: {
1776     Commute = UseMI->getOperand(2).getReg() != Reg;
1777     switch (UseOpc) {
1778     default: break;
1779     case ARM::SUBrr: {
1780       if (Commute)
1781         return false;
1782       ImmVal = -ImmVal;
1783       NewUseOpc = ARM::SUBri;
1784       // Fallthrough
1785     }
1786     case ARM::ADDrr:
1787     case ARM::ORRrr:
1788     case ARM::EORrr: {
1789       if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
1790         return false;
1791       SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
1792       SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
1793       switch (UseOpc) {
1794       default: break;
1795       case ARM::ADDrr: NewUseOpc = ARM::ADDri; break;
1796       case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
1797       case ARM::EORrr: NewUseOpc = ARM::EORri; break;
1798       }
1799       break;
1800     }
1801     case ARM::t2SUBrr: {
1802       if (Commute)
1803         return false;
1804       ImmVal = -ImmVal;
1805       NewUseOpc = ARM::t2SUBri;
1806       // Fallthrough
1807     }
1808     case ARM::t2ADDrr:
1809     case ARM::t2ORRrr:
1810     case ARM::t2EORrr: {
1811       if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
1812         return false;
1813       SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
1814       SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
1815       switch (UseOpc) {
1816       default: break;
1817       case ARM::t2ADDrr: NewUseOpc = ARM::t2ADDri; break;
1818       case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
1819       case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
1820       }
1821       break;
1822     }
1823     }
1824   }
1825   }
1826
1827   unsigned OpIdx = Commute ? 2 : 1;
1828   unsigned Reg1 = UseMI->getOperand(OpIdx).getReg();
1829   bool isKill = UseMI->getOperand(OpIdx).isKill();
1830   unsigned NewReg = MRI->createVirtualRegister(MRI->getRegClass(Reg));
1831   AddDefaultCC(AddDefaultPred(BuildMI(*UseMI->getParent(),
1832                                       *UseMI, UseMI->getDebugLoc(),
1833                                       get(NewUseOpc), NewReg)
1834                               .addReg(Reg1, getKillRegState(isKill))
1835                               .addImm(SOImmValV1)));
1836   UseMI->setDesc(get(NewUseOpc));
1837   UseMI->getOperand(1).setReg(NewReg);
1838   UseMI->getOperand(1).setIsKill();
1839   UseMI->getOperand(2).ChangeToImmediate(SOImmValV2);
1840   DefMI->eraseFromParent();
1841   return true;
1842 }
1843
1844 unsigned
1845 ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
1846                                  const MachineInstr *MI) const {
1847   if (!ItinData || ItinData->isEmpty())
1848     return 1;
1849
1850   const MCInstrDesc &Desc = MI->getDesc();
1851   unsigned Class = Desc.getSchedClass();
1852   unsigned UOps = ItinData->Itineraries[Class].NumMicroOps;
1853   if (UOps)
1854     return UOps;
1855
1856   unsigned Opc = MI->getOpcode();
1857   switch (Opc) {
1858   default:
1859     llvm_unreachable("Unexpected multi-uops instruction!");
1860     break;
1861   case ARM::VLDMQIA:
1862   case ARM::VSTMQIA:
1863     return 2;
1864
1865   // The number of uOps for load / store multiple are determined by the number
1866   // registers.
1867   //
1868   // On Cortex-A8, each pair of register loads / stores can be scheduled on the
1869   // same cycle. The scheduling for the first load / store must be done
1870   // separately by assuming the the address is not 64-bit aligned.
1871   //
1872   // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
1873   // is not 64-bit aligned, then AGU would take an extra cycle.  For VFP / NEON
1874   // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
1875   case ARM::VLDMDIA:
1876   case ARM::VLDMDIA_UPD:
1877   case ARM::VLDMDDB_UPD:
1878   case ARM::VLDMSIA:
1879   case ARM::VLDMSIA_UPD:
1880   case ARM::VLDMSDB_UPD:
1881   case ARM::VSTMDIA:
1882   case ARM::VSTMDIA_UPD:
1883   case ARM::VSTMDDB_UPD:
1884   case ARM::VSTMSIA:
1885   case ARM::VSTMSIA_UPD:
1886   case ARM::VSTMSDB_UPD: {
1887     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands();
1888     return (NumRegs / 2) + (NumRegs % 2) + 1;
1889   }
1890
1891   case ARM::LDMIA_RET:
1892   case ARM::LDMIA:
1893   case ARM::LDMDA:
1894   case ARM::LDMDB:
1895   case ARM::LDMIB:
1896   case ARM::LDMIA_UPD:
1897   case ARM::LDMDA_UPD:
1898   case ARM::LDMDB_UPD:
1899   case ARM::LDMIB_UPD:
1900   case ARM::STMIA:
1901   case ARM::STMDA:
1902   case ARM::STMDB:
1903   case ARM::STMIB:
1904   case ARM::STMIA_UPD:
1905   case ARM::STMDA_UPD:
1906   case ARM::STMDB_UPD:
1907   case ARM::STMIB_UPD:
1908   case ARM::tLDMIA:
1909   case ARM::tLDMIA_UPD:
1910   case ARM::tSTMIA:
1911   case ARM::tSTMIA_UPD:
1912   case ARM::tPOP_RET:
1913   case ARM::tPOP:
1914   case ARM::tPUSH:
1915   case ARM::t2LDMIA_RET:
1916   case ARM::t2LDMIA:
1917   case ARM::t2LDMDB:
1918   case ARM::t2LDMIA_UPD:
1919   case ARM::t2LDMDB_UPD:
1920   case ARM::t2STMIA:
1921   case ARM::t2STMDB:
1922   case ARM::t2STMIA_UPD:
1923   case ARM::t2STMDB_UPD: {
1924     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands() + 1;
1925     if (Subtarget.isCortexA8()) {
1926       if (NumRegs < 4)
1927         return 2;
1928       // 4 registers would be issued: 2, 2.
1929       // 5 registers would be issued: 2, 2, 1.
1930       UOps = (NumRegs / 2);
1931       if (NumRegs % 2)
1932         ++UOps;
1933       return UOps;
1934     } else if (Subtarget.isCortexA9()) {
1935       UOps = (NumRegs / 2);
1936       // If there are odd number of registers or if it's not 64-bit aligned,
1937       // then it takes an extra AGU (Address Generation Unit) cycle.
1938       if ((NumRegs % 2) ||
1939           !MI->hasOneMemOperand() ||
1940           (*MI->memoperands_begin())->getAlignment() < 8)
1941         ++UOps;
1942       return UOps;
1943     } else {
1944       // Assume the worst.
1945       return NumRegs;
1946     }
1947   }
1948   }
1949 }
1950
1951 int
1952 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
1953                                   const MCInstrDesc &DefMCID,
1954                                   unsigned DefClass,
1955                                   unsigned DefIdx, unsigned DefAlign) const {
1956   int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
1957   if (RegNo <= 0)
1958     // Def is the address writeback.
1959     return ItinData->getOperandCycle(DefClass, DefIdx);
1960
1961   int DefCycle;
1962   if (Subtarget.isCortexA8()) {
1963     // (regno / 2) + (regno % 2) + 1
1964     DefCycle = RegNo / 2 + 1;
1965     if (RegNo % 2)
1966       ++DefCycle;
1967   } else if (Subtarget.isCortexA9()) {
1968     DefCycle = RegNo;
1969     bool isSLoad = false;
1970
1971     switch (DefMCID.getOpcode()) {
1972     default: break;
1973     case ARM::VLDMSIA:
1974     case ARM::VLDMSIA_UPD:
1975     case ARM::VLDMSDB_UPD:
1976       isSLoad = true;
1977       break;
1978     }
1979
1980     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
1981     // then it takes an extra cycle.
1982     if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
1983       ++DefCycle;
1984   } else {
1985     // Assume the worst.
1986     DefCycle = RegNo + 2;
1987   }
1988
1989   return DefCycle;
1990 }
1991
1992 int
1993 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
1994                                  const MCInstrDesc &DefMCID,
1995                                  unsigned DefClass,
1996                                  unsigned DefIdx, unsigned DefAlign) const {
1997   int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
1998   if (RegNo <= 0)
1999     // Def is the address writeback.
2000     return ItinData->getOperandCycle(DefClass, DefIdx);
2001
2002   int DefCycle;
2003   if (Subtarget.isCortexA8()) {
2004     // 4 registers would be issued: 1, 2, 1.
2005     // 5 registers would be issued: 1, 2, 2.
2006     DefCycle = RegNo / 2;
2007     if (DefCycle < 1)
2008       DefCycle = 1;
2009     // Result latency is issue cycle + 2: E2.
2010     DefCycle += 2;
2011   } else if (Subtarget.isCortexA9()) {
2012     DefCycle = (RegNo / 2);
2013     // If there are odd number of registers or if it's not 64-bit aligned,
2014     // then it takes an extra AGU (Address Generation Unit) cycle.
2015     if ((RegNo % 2) || DefAlign < 8)
2016       ++DefCycle;
2017     // Result latency is AGU cycles + 2.
2018     DefCycle += 2;
2019   } else {
2020     // Assume the worst.
2021     DefCycle = RegNo + 2;
2022   }
2023
2024   return DefCycle;
2025 }
2026
2027 int
2028 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
2029                                   const MCInstrDesc &UseMCID,
2030                                   unsigned UseClass,
2031                                   unsigned UseIdx, unsigned UseAlign) const {
2032   int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
2033   if (RegNo <= 0)
2034     return ItinData->getOperandCycle(UseClass, UseIdx);
2035
2036   int UseCycle;
2037   if (Subtarget.isCortexA8()) {
2038     // (regno / 2) + (regno % 2) + 1
2039     UseCycle = RegNo / 2 + 1;
2040     if (RegNo % 2)
2041       ++UseCycle;
2042   } else if (Subtarget.isCortexA9()) {
2043     UseCycle = RegNo;
2044     bool isSStore = false;
2045
2046     switch (UseMCID.getOpcode()) {
2047     default: break;
2048     case ARM::VSTMSIA:
2049     case ARM::VSTMSIA_UPD:
2050     case ARM::VSTMSDB_UPD:
2051       isSStore = true;
2052       break;
2053     }
2054
2055     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
2056     // then it takes an extra cycle.
2057     if ((isSStore && (RegNo % 2)) || UseAlign < 8)
2058       ++UseCycle;
2059   } else {
2060     // Assume the worst.
2061     UseCycle = RegNo + 2;
2062   }
2063
2064   return UseCycle;
2065 }
2066
2067 int
2068 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
2069                                  const MCInstrDesc &UseMCID,
2070                                  unsigned UseClass,
2071                                  unsigned UseIdx, unsigned UseAlign) const {
2072   int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
2073   if (RegNo <= 0)
2074     return ItinData->getOperandCycle(UseClass, UseIdx);
2075
2076   int UseCycle;
2077   if (Subtarget.isCortexA8()) {
2078     UseCycle = RegNo / 2;
2079     if (UseCycle < 2)
2080       UseCycle = 2;
2081     // Read in E3.
2082     UseCycle += 2;
2083   } else if (Subtarget.isCortexA9()) {
2084     UseCycle = (RegNo / 2);
2085     // If there are odd number of registers or if it's not 64-bit aligned,
2086     // then it takes an extra AGU (Address Generation Unit) cycle.
2087     if ((RegNo % 2) || UseAlign < 8)
2088       ++UseCycle;
2089   } else {
2090     // Assume the worst.
2091     UseCycle = 1;
2092   }
2093   return UseCycle;
2094 }
2095
2096 int
2097 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2098                                     const MCInstrDesc &DefMCID,
2099                                     unsigned DefIdx, unsigned DefAlign,
2100                                     const MCInstrDesc &UseMCID,
2101                                     unsigned UseIdx, unsigned UseAlign) const {
2102   unsigned DefClass = DefMCID.getSchedClass();
2103   unsigned UseClass = UseMCID.getSchedClass();
2104
2105   if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
2106     return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
2107
2108   // This may be a def / use of a variable_ops instruction, the operand
2109   // latency might be determinable dynamically. Let the target try to
2110   // figure it out.
2111   int DefCycle = -1;
2112   bool LdmBypass = false;
2113   switch (DefMCID.getOpcode()) {
2114   default:
2115     DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
2116     break;
2117
2118   case ARM::VLDMDIA:
2119   case ARM::VLDMDIA_UPD:
2120   case ARM::VLDMDDB_UPD:
2121   case ARM::VLDMSIA:
2122   case ARM::VLDMSIA_UPD:
2123   case ARM::VLDMSDB_UPD:
2124     DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
2125     break;
2126
2127   case ARM::LDMIA_RET:
2128   case ARM::LDMIA:
2129   case ARM::LDMDA:
2130   case ARM::LDMDB:
2131   case ARM::LDMIB:
2132   case ARM::LDMIA_UPD:
2133   case ARM::LDMDA_UPD:
2134   case ARM::LDMDB_UPD:
2135   case ARM::LDMIB_UPD:
2136   case ARM::tLDMIA:
2137   case ARM::tLDMIA_UPD:
2138   case ARM::tPUSH:
2139   case ARM::t2LDMIA_RET:
2140   case ARM::t2LDMIA:
2141   case ARM::t2LDMDB:
2142   case ARM::t2LDMIA_UPD:
2143   case ARM::t2LDMDB_UPD:
2144     LdmBypass = 1;
2145     DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
2146     break;
2147   }
2148
2149   if (DefCycle == -1)
2150     // We can't seem to determine the result latency of the def, assume it's 2.
2151     DefCycle = 2;
2152
2153   int UseCycle = -1;
2154   switch (UseMCID.getOpcode()) {
2155   default:
2156     UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
2157     break;
2158
2159   case ARM::VSTMDIA:
2160   case ARM::VSTMDIA_UPD:
2161   case ARM::VSTMDDB_UPD:
2162   case ARM::VSTMSIA:
2163   case ARM::VSTMSIA_UPD:
2164   case ARM::VSTMSDB_UPD:
2165     UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
2166     break;
2167
2168   case ARM::STMIA:
2169   case ARM::STMDA:
2170   case ARM::STMDB:
2171   case ARM::STMIB:
2172   case ARM::STMIA_UPD:
2173   case ARM::STMDA_UPD:
2174   case ARM::STMDB_UPD:
2175   case ARM::STMIB_UPD:
2176   case ARM::tSTMIA:
2177   case ARM::tSTMIA_UPD:
2178   case ARM::tPOP_RET:
2179   case ARM::tPOP:
2180   case ARM::t2STMIA:
2181   case ARM::t2STMDB:
2182   case ARM::t2STMIA_UPD:
2183   case ARM::t2STMDB_UPD:
2184     UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
2185     break;
2186   }
2187
2188   if (UseCycle == -1)
2189     // Assume it's read in the first stage.
2190     UseCycle = 1;
2191
2192   UseCycle = DefCycle - UseCycle + 1;
2193   if (UseCycle > 0) {
2194     if (LdmBypass) {
2195       // It's a variable_ops instruction so we can't use DefIdx here. Just use
2196       // first def operand.
2197       if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
2198                                           UseClass, UseIdx))
2199         --UseCycle;
2200     } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
2201                                                UseClass, UseIdx)) {
2202       --UseCycle;
2203     }
2204   }
2205
2206   return UseCycle;
2207 }
2208
2209 int
2210 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2211                              const MachineInstr *DefMI, unsigned DefIdx,
2212                              const MachineInstr *UseMI, unsigned UseIdx) const {
2213   if (DefMI->isCopyLike() || DefMI->isInsertSubreg() ||
2214       DefMI->isRegSequence() || DefMI->isImplicitDef())
2215     return 1;
2216
2217   const MCInstrDesc &DefMCID = DefMI->getDesc();
2218   if (!ItinData || ItinData->isEmpty())
2219     return DefMCID.mayLoad() ? 3 : 1;
2220
2221   const MCInstrDesc &UseMCID = UseMI->getDesc();
2222   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
2223   if (DefMO.getReg() == ARM::CPSR) {
2224     if (DefMI->getOpcode() == ARM::FMSTAT) {
2225       // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
2226       return Subtarget.isCortexA9() ? 1 : 20;
2227     }
2228
2229     // CPSR set and branch can be paired in the same cycle.
2230     if (UseMCID.isBranch())
2231       return 0;
2232   }
2233
2234   unsigned DefAlign = DefMI->hasOneMemOperand()
2235     ? (*DefMI->memoperands_begin())->getAlignment() : 0;
2236   unsigned UseAlign = UseMI->hasOneMemOperand()
2237     ? (*UseMI->memoperands_begin())->getAlignment() : 0;
2238   int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
2239                                   UseMCID, UseIdx, UseAlign);
2240
2241   if (Latency > 1 &&
2242       (Subtarget.isCortexA8() || Subtarget.isCortexA9())) {
2243     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
2244     // variants are one cycle cheaper.
2245     switch (DefMCID.getOpcode()) {
2246     default: break;
2247     case ARM::LDRrs:
2248     case ARM::LDRBrs: {
2249       unsigned ShOpVal = DefMI->getOperand(3).getImm();
2250       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2251       if (ShImm == 0 ||
2252           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
2253         --Latency;
2254       break;
2255     }
2256     case ARM::t2LDRs:
2257     case ARM::t2LDRBs:
2258     case ARM::t2LDRHs:
2259     case ARM::t2LDRSHs: {
2260       // Thumb2 mode: lsl only.
2261       unsigned ShAmt = DefMI->getOperand(3).getImm();
2262       if (ShAmt == 0 || ShAmt == 2)
2263         --Latency;
2264       break;
2265     }
2266     }
2267   }
2268
2269   if (DefAlign < 8 && Subtarget.isCortexA9())
2270     switch (DefMCID.getOpcode()) {
2271     default: break;
2272     case ARM::VLD1q8:
2273     case ARM::VLD1q16:
2274     case ARM::VLD1q32:
2275     case ARM::VLD1q64:
2276     case ARM::VLD1q8_UPD:
2277     case ARM::VLD1q16_UPD:
2278     case ARM::VLD1q32_UPD:
2279     case ARM::VLD1q64_UPD:
2280     case ARM::VLD2d8:
2281     case ARM::VLD2d16:
2282     case ARM::VLD2d32:
2283     case ARM::VLD2q8:
2284     case ARM::VLD2q16:
2285     case ARM::VLD2q32:
2286     case ARM::VLD2d8_UPD:
2287     case ARM::VLD2d16_UPD:
2288     case ARM::VLD2d32_UPD:
2289     case ARM::VLD2q8_UPD:
2290     case ARM::VLD2q16_UPD:
2291     case ARM::VLD2q32_UPD:
2292     case ARM::VLD3d8:
2293     case ARM::VLD3d16:
2294     case ARM::VLD3d32:
2295     case ARM::VLD1d64T:
2296     case ARM::VLD3d8_UPD:
2297     case ARM::VLD3d16_UPD:
2298     case ARM::VLD3d32_UPD:
2299     case ARM::VLD1d64T_UPD:
2300     case ARM::VLD3q8_UPD:
2301     case ARM::VLD3q16_UPD:
2302     case ARM::VLD3q32_UPD:
2303     case ARM::VLD4d8:
2304     case ARM::VLD4d16:
2305     case ARM::VLD4d32:
2306     case ARM::VLD1d64Q:
2307     case ARM::VLD4d8_UPD:
2308     case ARM::VLD4d16_UPD:
2309     case ARM::VLD4d32_UPD:
2310     case ARM::VLD1d64Q_UPD:
2311     case ARM::VLD4q8_UPD:
2312     case ARM::VLD4q16_UPD:
2313     case ARM::VLD4q32_UPD:
2314     case ARM::VLD1DUPq8:
2315     case ARM::VLD1DUPq16:
2316     case ARM::VLD1DUPq32:
2317     case ARM::VLD1DUPq8_UPD:
2318     case ARM::VLD1DUPq16_UPD:
2319     case ARM::VLD1DUPq32_UPD:
2320     case ARM::VLD2DUPd8:
2321     case ARM::VLD2DUPd16:
2322     case ARM::VLD2DUPd32:
2323     case ARM::VLD2DUPd8_UPD:
2324     case ARM::VLD2DUPd16_UPD:
2325     case ARM::VLD2DUPd32_UPD:
2326     case ARM::VLD4DUPd8:
2327     case ARM::VLD4DUPd16:
2328     case ARM::VLD4DUPd32:
2329     case ARM::VLD4DUPd8_UPD:
2330     case ARM::VLD4DUPd16_UPD:
2331     case ARM::VLD4DUPd32_UPD:
2332     case ARM::VLD1LNd8:
2333     case ARM::VLD1LNd16:
2334     case ARM::VLD1LNd32:
2335     case ARM::VLD1LNd8_UPD:
2336     case ARM::VLD1LNd16_UPD:
2337     case ARM::VLD1LNd32_UPD:
2338     case ARM::VLD2LNd8:
2339     case ARM::VLD2LNd16:
2340     case ARM::VLD2LNd32:
2341     case ARM::VLD2LNq16:
2342     case ARM::VLD2LNq32:
2343     case ARM::VLD2LNd8_UPD:
2344     case ARM::VLD2LNd16_UPD:
2345     case ARM::VLD2LNd32_UPD:
2346     case ARM::VLD2LNq16_UPD:
2347     case ARM::VLD2LNq32_UPD:
2348     case ARM::VLD4LNd8:
2349     case ARM::VLD4LNd16:
2350     case ARM::VLD4LNd32:
2351     case ARM::VLD4LNq16:
2352     case ARM::VLD4LNq32:
2353     case ARM::VLD4LNd8_UPD:
2354     case ARM::VLD4LNd16_UPD:
2355     case ARM::VLD4LNd32_UPD:
2356     case ARM::VLD4LNq16_UPD:
2357     case ARM::VLD4LNq32_UPD:
2358       // If the address is not 64-bit aligned, the latencies of these
2359       // instructions increases by one.
2360       ++Latency;
2361       break;
2362     }
2363
2364   return Latency;
2365 }
2366
2367 int
2368 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
2369                                     SDNode *DefNode, unsigned DefIdx,
2370                                     SDNode *UseNode, unsigned UseIdx) const {
2371   if (!DefNode->isMachineOpcode())
2372     return 1;
2373
2374   const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
2375
2376   if (isZeroCost(DefMCID.Opcode))
2377     return 0;
2378
2379   if (!ItinData || ItinData->isEmpty())
2380     return DefMCID.mayLoad() ? 3 : 1;
2381
2382   if (!UseNode->isMachineOpcode()) {
2383     int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
2384     if (Subtarget.isCortexA9())
2385       return Latency <= 2 ? 1 : Latency - 1;
2386     else
2387       return Latency <= 3 ? 1 : Latency - 2;
2388   }
2389
2390   const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
2391   const MachineSDNode *DefMN = dyn_cast<MachineSDNode>(DefNode);
2392   unsigned DefAlign = !DefMN->memoperands_empty()
2393     ? (*DefMN->memoperands_begin())->getAlignment() : 0;
2394   const MachineSDNode *UseMN = dyn_cast<MachineSDNode>(UseNode);
2395   unsigned UseAlign = !UseMN->memoperands_empty()
2396     ? (*UseMN->memoperands_begin())->getAlignment() : 0;
2397   int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
2398                                   UseMCID, UseIdx, UseAlign);
2399
2400   if (Latency > 1 &&
2401       (Subtarget.isCortexA8() || Subtarget.isCortexA9())) {
2402     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
2403     // variants are one cycle cheaper.
2404     switch (DefMCID.getOpcode()) {
2405     default: break;
2406     case ARM::LDRrs:
2407     case ARM::LDRBrs: {
2408       unsigned ShOpVal =
2409         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
2410       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2411       if (ShImm == 0 ||
2412           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
2413         --Latency;
2414       break;
2415     }
2416     case ARM::t2LDRs:
2417     case ARM::t2LDRBs:
2418     case ARM::t2LDRHs:
2419     case ARM::t2LDRSHs: {
2420       // Thumb2 mode: lsl only.
2421       unsigned ShAmt =
2422         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
2423       if (ShAmt == 0 || ShAmt == 2)
2424         --Latency;
2425       break;
2426     }
2427     }
2428   }
2429
2430   if (DefAlign < 8 && Subtarget.isCortexA9())
2431     switch (DefMCID.getOpcode()) {
2432     default: break;
2433     case ARM::VLD1q8Pseudo:
2434     case ARM::VLD1q16Pseudo:
2435     case ARM::VLD1q32Pseudo:
2436     case ARM::VLD1q64Pseudo:
2437     case ARM::VLD1q8Pseudo_UPD:
2438     case ARM::VLD1q16Pseudo_UPD:
2439     case ARM::VLD1q32Pseudo_UPD:
2440     case ARM::VLD1q64Pseudo_UPD:
2441     case ARM::VLD2d8Pseudo:
2442     case ARM::VLD2d16Pseudo:
2443     case ARM::VLD2d32Pseudo:
2444     case ARM::VLD2q8Pseudo:
2445     case ARM::VLD2q16Pseudo:
2446     case ARM::VLD2q32Pseudo:
2447     case ARM::VLD2d8Pseudo_UPD:
2448     case ARM::VLD2d16Pseudo_UPD:
2449     case ARM::VLD2d32Pseudo_UPD:
2450     case ARM::VLD2q8Pseudo_UPD:
2451     case ARM::VLD2q16Pseudo_UPD:
2452     case ARM::VLD2q32Pseudo_UPD:
2453     case ARM::VLD3d8Pseudo:
2454     case ARM::VLD3d16Pseudo:
2455     case ARM::VLD3d32Pseudo:
2456     case ARM::VLD1d64TPseudo:
2457     case ARM::VLD3d8Pseudo_UPD:
2458     case ARM::VLD3d16Pseudo_UPD:
2459     case ARM::VLD3d32Pseudo_UPD:
2460     case ARM::VLD1d64TPseudo_UPD:
2461     case ARM::VLD3q8Pseudo_UPD:
2462     case ARM::VLD3q16Pseudo_UPD:
2463     case ARM::VLD3q32Pseudo_UPD:
2464     case ARM::VLD3q8oddPseudo:
2465     case ARM::VLD3q16oddPseudo:
2466     case ARM::VLD3q32oddPseudo:
2467     case ARM::VLD3q8oddPseudo_UPD:
2468     case ARM::VLD3q16oddPseudo_UPD:
2469     case ARM::VLD3q32oddPseudo_UPD:
2470     case ARM::VLD4d8Pseudo:
2471     case ARM::VLD4d16Pseudo:
2472     case ARM::VLD4d32Pseudo:
2473     case ARM::VLD1d64QPseudo:
2474     case ARM::VLD4d8Pseudo_UPD:
2475     case ARM::VLD4d16Pseudo_UPD:
2476     case ARM::VLD4d32Pseudo_UPD:
2477     case ARM::VLD1d64QPseudo_UPD:
2478     case ARM::VLD4q8Pseudo_UPD:
2479     case ARM::VLD4q16Pseudo_UPD:
2480     case ARM::VLD4q32Pseudo_UPD:
2481     case ARM::VLD4q8oddPseudo:
2482     case ARM::VLD4q16oddPseudo:
2483     case ARM::VLD4q32oddPseudo:
2484     case ARM::VLD4q8oddPseudo_UPD:
2485     case ARM::VLD4q16oddPseudo_UPD:
2486     case ARM::VLD4q32oddPseudo_UPD:
2487     case ARM::VLD1DUPq8Pseudo:
2488     case ARM::VLD1DUPq16Pseudo:
2489     case ARM::VLD1DUPq32Pseudo:
2490     case ARM::VLD1DUPq8Pseudo_UPD:
2491     case ARM::VLD1DUPq16Pseudo_UPD:
2492     case ARM::VLD1DUPq32Pseudo_UPD:
2493     case ARM::VLD2DUPd8Pseudo:
2494     case ARM::VLD2DUPd16Pseudo:
2495     case ARM::VLD2DUPd32Pseudo:
2496     case ARM::VLD2DUPd8Pseudo_UPD:
2497     case ARM::VLD2DUPd16Pseudo_UPD:
2498     case ARM::VLD2DUPd32Pseudo_UPD:
2499     case ARM::VLD4DUPd8Pseudo:
2500     case ARM::VLD4DUPd16Pseudo:
2501     case ARM::VLD4DUPd32Pseudo:
2502     case ARM::VLD4DUPd8Pseudo_UPD:
2503     case ARM::VLD4DUPd16Pseudo_UPD:
2504     case ARM::VLD4DUPd32Pseudo_UPD:
2505     case ARM::VLD1LNq8Pseudo:
2506     case ARM::VLD1LNq16Pseudo:
2507     case ARM::VLD1LNq32Pseudo:
2508     case ARM::VLD1LNq8Pseudo_UPD:
2509     case ARM::VLD1LNq16Pseudo_UPD:
2510     case ARM::VLD1LNq32Pseudo_UPD:
2511     case ARM::VLD2LNd8Pseudo:
2512     case ARM::VLD2LNd16Pseudo:
2513     case ARM::VLD2LNd32Pseudo:
2514     case ARM::VLD2LNq16Pseudo:
2515     case ARM::VLD2LNq32Pseudo:
2516     case ARM::VLD2LNd8Pseudo_UPD:
2517     case ARM::VLD2LNd16Pseudo_UPD:
2518     case ARM::VLD2LNd32Pseudo_UPD:
2519     case ARM::VLD2LNq16Pseudo_UPD:
2520     case ARM::VLD2LNq32Pseudo_UPD:
2521     case ARM::VLD4LNd8Pseudo:
2522     case ARM::VLD4LNd16Pseudo:
2523     case ARM::VLD4LNd32Pseudo:
2524     case ARM::VLD4LNq16Pseudo:
2525     case ARM::VLD4LNq32Pseudo:
2526     case ARM::VLD4LNd8Pseudo_UPD:
2527     case ARM::VLD4LNd16Pseudo_UPD:
2528     case ARM::VLD4LNd32Pseudo_UPD:
2529     case ARM::VLD4LNq16Pseudo_UPD:
2530     case ARM::VLD4LNq32Pseudo_UPD:
2531       // If the address is not 64-bit aligned, the latencies of these
2532       // instructions increases by one.
2533       ++Latency;
2534       break;
2535     }
2536
2537   return Latency;
2538 }
2539
2540 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
2541                                       const MachineInstr *MI,
2542                                       unsigned *PredCost) const {
2543   if (MI->isCopyLike() || MI->isInsertSubreg() ||
2544       MI->isRegSequence() || MI->isImplicitDef())
2545     return 1;
2546
2547   if (!ItinData || ItinData->isEmpty())
2548     return 1;
2549
2550   const MCInstrDesc &MCID = MI->getDesc();
2551   unsigned Class = MCID.getSchedClass();
2552   unsigned UOps = ItinData->Itineraries[Class].NumMicroOps;
2553   if (PredCost && MCID.hasImplicitDefOfPhysReg(ARM::CPSR))
2554     // When predicated, CPSR is an additional source operand for CPSR updating
2555     // instructions, this apparently increases their latencies.
2556     *PredCost = 1;
2557   if (UOps)
2558     return ItinData->getStageLatency(Class);
2559   return getNumMicroOps(ItinData, MI);
2560 }
2561
2562 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
2563                                       SDNode *Node) const {
2564   if (!Node->isMachineOpcode())
2565     return 1;
2566
2567   if (!ItinData || ItinData->isEmpty())
2568     return 1;
2569
2570   unsigned Opcode = Node->getMachineOpcode();
2571   switch (Opcode) {
2572   default:
2573     return ItinData->getStageLatency(get(Opcode).getSchedClass());
2574   case ARM::VLDMQIA:
2575   case ARM::VSTMQIA:
2576     return 2;
2577   }
2578 }
2579
2580 bool ARMBaseInstrInfo::
2581 hasHighOperandLatency(const InstrItineraryData *ItinData,
2582                       const MachineRegisterInfo *MRI,
2583                       const MachineInstr *DefMI, unsigned DefIdx,
2584                       const MachineInstr *UseMI, unsigned UseIdx) const {
2585   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
2586   unsigned UDomain = UseMI->getDesc().TSFlags & ARMII::DomainMask;
2587   if (Subtarget.isCortexA8() &&
2588       (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
2589     // CortexA8 VFP instructions are not pipelined.
2590     return true;
2591
2592   // Hoist VFP / NEON instructions with 4 or higher latency.
2593   int Latency = getOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
2594   if (Latency <= 3)
2595     return false;
2596   return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
2597          UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
2598 }
2599
2600 bool ARMBaseInstrInfo::
2601 hasLowDefLatency(const InstrItineraryData *ItinData,
2602                  const MachineInstr *DefMI, unsigned DefIdx) const {
2603   if (!ItinData || ItinData->isEmpty())
2604     return false;
2605
2606   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
2607   if (DDomain == ARMII::DomainGeneral) {
2608     unsigned DefClass = DefMI->getDesc().getSchedClass();
2609     int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
2610     return (DefCycle != -1 && DefCycle <= 2);
2611   }
2612   return false;
2613 }
2614
2615 bool
2616 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
2617                                      unsigned &AddSubOpc,
2618                                      bool &NegAcc, bool &HasLane) const {
2619   DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
2620   if (I == MLxEntryMap.end())
2621     return false;
2622
2623   const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
2624   MulOpc = Entry.MulOpc;
2625   AddSubOpc = Entry.AddSubOpc;
2626   NegAcc = Entry.NegAcc;
2627   HasLane = Entry.HasLane;
2628   return true;
2629 }