Replace PROLOG_LABEL with a new CFI_INSTRUCTION.
[oota-llvm.git] / lib / Target / ARM / ARMBaseInstrInfo.cpp
1 //===-- ARMBaseInstrInfo.cpp - ARM Instruction Information ----------------===//
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 "ARM.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMFeatures.h"
19 #include "ARMHazardRecognizer.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "MCTargetDesc/ARMAddressingModes.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/CodeGen/LiveVariables.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAGNodes.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/Function.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/Support/BranchProbability.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39
40 #define GET_INSTRINFO_CTOR_DTOR
41 #include "ARMGenInstrInfo.inc"
42
43 using namespace llvm;
44
45 static cl::opt<bool>
46 EnableARM3Addr("enable-arm-3-addr-conv", cl::Hidden,
47                cl::desc("Enable ARM 2-addr to 3-addr conv"));
48
49 static cl::opt<bool>
50 WidenVMOVS("widen-vmovs", cl::Hidden, cl::init(true),
51            cl::desc("Widen ARM vmovs to vmovd when possible"));
52
53 static cl::opt<unsigned>
54 SwiftPartialUpdateClearance("swift-partial-update-clearance",
55      cl::Hidden, cl::init(12),
56      cl::desc("Clearance before partial register updates"));
57
58 /// ARM_MLxEntry - Record information about MLA / MLS instructions.
59 struct ARM_MLxEntry {
60   uint16_t MLxOpc;     // MLA / MLS opcode
61   uint16_t MulOpc;     // Expanded multiplication opcode
62   uint16_t AddSubOpc;  // Expanded add / sub opcode
63   bool NegAcc;         // True if the acc is negated before the add / sub.
64   bool HasLane;        // True if instruction has an extra "lane" operand.
65 };
66
67 static const ARM_MLxEntry ARM_MLxTable[] = {
68   // MLxOpc,          MulOpc,           AddSubOpc,       NegAcc, HasLane
69   // fp scalar ops
70   { ARM::VMLAS,       ARM::VMULS,       ARM::VADDS,      false,  false },
71   { ARM::VMLSS,       ARM::VMULS,       ARM::VSUBS,      false,  false },
72   { ARM::VMLAD,       ARM::VMULD,       ARM::VADDD,      false,  false },
73   { ARM::VMLSD,       ARM::VMULD,       ARM::VSUBD,      false,  false },
74   { ARM::VNMLAS,      ARM::VNMULS,      ARM::VSUBS,      true,   false },
75   { ARM::VNMLSS,      ARM::VMULS,       ARM::VSUBS,      true,   false },
76   { ARM::VNMLAD,      ARM::VNMULD,      ARM::VSUBD,      true,   false },
77   { ARM::VNMLSD,      ARM::VMULD,       ARM::VSUBD,      true,   false },
78
79   // fp SIMD ops
80   { ARM::VMLAfd,      ARM::VMULfd,      ARM::VADDfd,     false,  false },
81   { ARM::VMLSfd,      ARM::VMULfd,      ARM::VSUBfd,     false,  false },
82   { ARM::VMLAfq,      ARM::VMULfq,      ARM::VADDfq,     false,  false },
83   { ARM::VMLSfq,      ARM::VMULfq,      ARM::VSUBfq,     false,  false },
84   { ARM::VMLAslfd,    ARM::VMULslfd,    ARM::VADDfd,     false,  true  },
85   { ARM::VMLSslfd,    ARM::VMULslfd,    ARM::VSUBfd,     false,  true  },
86   { ARM::VMLAslfq,    ARM::VMULslfq,    ARM::VADDfq,     false,  true  },
87   { ARM::VMLSslfq,    ARM::VMULslfq,    ARM::VSUBfq,     false,  true  },
88 };
89
90 ARMBaseInstrInfo::ARMBaseInstrInfo(const ARMSubtarget& STI)
91   : ARMGenInstrInfo(ARM::ADJCALLSTACKDOWN, ARM::ADJCALLSTACKUP),
92     Subtarget(STI) {
93   for (unsigned i = 0, e = array_lengthof(ARM_MLxTable); i != e; ++i) {
94     if (!MLxEntryMap.insert(std::make_pair(ARM_MLxTable[i].MLxOpc, i)).second)
95       assert(false && "Duplicated entries?");
96     MLxHazardOpcodes.insert(ARM_MLxTable[i].AddSubOpc);
97     MLxHazardOpcodes.insert(ARM_MLxTable[i].MulOpc);
98   }
99 }
100
101 // Use a ScoreboardHazardRecognizer for prepass ARM scheduling. TargetInstrImpl
102 // currently defaults to no prepass hazard recognizer.
103 ScheduleHazardRecognizer *ARMBaseInstrInfo::
104 CreateTargetHazardRecognizer(const TargetMachine *TM,
105                              const ScheduleDAG *DAG) const {
106   if (usePreRAHazardRecognizer()) {
107     const InstrItineraryData *II = TM->getInstrItineraryData();
108     return new ScoreboardHazardRecognizer(II, DAG, "pre-RA-sched");
109   }
110   return TargetInstrInfo::CreateTargetHazardRecognizer(TM, DAG);
111 }
112
113 ScheduleHazardRecognizer *ARMBaseInstrInfo::
114 CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II,
115                                    const ScheduleDAG *DAG) const {
116   if (Subtarget.isThumb2() || Subtarget.hasVFP2())
117     return (ScheduleHazardRecognizer *)new ARMHazardRecognizer(II, DAG);
118   return TargetInstrInfo::CreateTargetPostRAHazardRecognizer(II, DAG);
119 }
120
121 MachineInstr *
122 ARMBaseInstrInfo::convertToThreeAddress(MachineFunction::iterator &MFI,
123                                         MachineBasicBlock::iterator &MBBI,
124                                         LiveVariables *LV) const {
125   // FIXME: Thumb2 support.
126
127   if (!EnableARM3Addr)
128     return NULL;
129
130   MachineInstr *MI = MBBI;
131   MachineFunction &MF = *MI->getParent()->getParent();
132   uint64_t TSFlags = MI->getDesc().TSFlags;
133   bool isPre = false;
134   switch ((TSFlags & ARMII::IndexModeMask) >> ARMII::IndexModeShift) {
135   default: return NULL;
136   case ARMII::IndexModePre:
137     isPre = true;
138     break;
139   case ARMII::IndexModePost:
140     break;
141   }
142
143   // Try splitting an indexed load/store to an un-indexed one plus an add/sub
144   // operation.
145   unsigned MemOpc = getUnindexedOpcode(MI->getOpcode());
146   if (MemOpc == 0)
147     return NULL;
148
149   MachineInstr *UpdateMI = NULL;
150   MachineInstr *MemMI = NULL;
151   unsigned AddrMode = (TSFlags & ARMII::AddrModeMask);
152   const MCInstrDesc &MCID = MI->getDesc();
153   unsigned NumOps = MCID.getNumOperands();
154   bool isLoad = !MI->mayStore();
155   const MachineOperand &WB = isLoad ? MI->getOperand(1) : MI->getOperand(0);
156   const MachineOperand &Base = MI->getOperand(2);
157   const MachineOperand &Offset = MI->getOperand(NumOps-3);
158   unsigned WBReg = WB.getReg();
159   unsigned BaseReg = Base.getReg();
160   unsigned OffReg = Offset.getReg();
161   unsigned OffImm = MI->getOperand(NumOps-2).getImm();
162   ARMCC::CondCodes Pred = (ARMCC::CondCodes)MI->getOperand(NumOps-1).getImm();
163   switch (AddrMode) {
164   default: llvm_unreachable("Unknown indexed op!");
165   case ARMII::AddrMode2: {
166     bool isSub = ARM_AM::getAM2Op(OffImm) == ARM_AM::sub;
167     unsigned Amt = ARM_AM::getAM2Offset(OffImm);
168     if (OffReg == 0) {
169       if (ARM_AM::getSOImmVal(Amt) == -1)
170         // Can't encode it in a so_imm operand. This transformation will
171         // add more than 1 instruction. Abandon!
172         return NULL;
173       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
174                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
175         .addReg(BaseReg).addImm(Amt)
176         .addImm(Pred).addReg(0).addReg(0);
177     } else if (Amt != 0) {
178       ARM_AM::ShiftOpc ShOpc = ARM_AM::getAM2ShiftOpc(OffImm);
179       unsigned SOOpc = ARM_AM::getSORegOpc(ShOpc, Amt);
180       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
181                          get(isSub ? ARM::SUBrsi : ARM::ADDrsi), WBReg)
182         .addReg(BaseReg).addReg(OffReg).addReg(0).addImm(SOOpc)
183         .addImm(Pred).addReg(0).addReg(0);
184     } else
185       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
186                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
187         .addReg(BaseReg).addReg(OffReg)
188         .addImm(Pred).addReg(0).addReg(0);
189     break;
190   }
191   case ARMII::AddrMode3 : {
192     bool isSub = ARM_AM::getAM3Op(OffImm) == ARM_AM::sub;
193     unsigned Amt = ARM_AM::getAM3Offset(OffImm);
194     if (OffReg == 0)
195       // Immediate is 8-bits. It's guaranteed to fit in a so_imm operand.
196       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
197                          get(isSub ? ARM::SUBri : ARM::ADDri), WBReg)
198         .addReg(BaseReg).addImm(Amt)
199         .addImm(Pred).addReg(0).addReg(0);
200     else
201       UpdateMI = BuildMI(MF, MI->getDebugLoc(),
202                          get(isSub ? ARM::SUBrr : ARM::ADDrr), WBReg)
203         .addReg(BaseReg).addReg(OffReg)
204         .addImm(Pred).addReg(0).addReg(0);
205     break;
206   }
207   }
208
209   std::vector<MachineInstr*> NewMIs;
210   if (isPre) {
211     if (isLoad)
212       MemMI = BuildMI(MF, MI->getDebugLoc(),
213                       get(MemOpc), MI->getOperand(0).getReg())
214         .addReg(WBReg).addImm(0).addImm(Pred);
215     else
216       MemMI = BuildMI(MF, MI->getDebugLoc(),
217                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
218         .addReg(WBReg).addReg(0).addImm(0).addImm(Pred);
219     NewMIs.push_back(MemMI);
220     NewMIs.push_back(UpdateMI);
221   } else {
222     if (isLoad)
223       MemMI = BuildMI(MF, MI->getDebugLoc(),
224                       get(MemOpc), MI->getOperand(0).getReg())
225         .addReg(BaseReg).addImm(0).addImm(Pred);
226     else
227       MemMI = BuildMI(MF, MI->getDebugLoc(),
228                       get(MemOpc)).addReg(MI->getOperand(1).getReg())
229         .addReg(BaseReg).addReg(0).addImm(0).addImm(Pred);
230     if (WB.isDead())
231       UpdateMI->getOperand(0).setIsDead();
232     NewMIs.push_back(UpdateMI);
233     NewMIs.push_back(MemMI);
234   }
235
236   // Transfer LiveVariables states, kill / dead info.
237   if (LV) {
238     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
239       MachineOperand &MO = MI->getOperand(i);
240       if (MO.isReg() && TargetRegisterInfo::isVirtualRegister(MO.getReg())) {
241         unsigned Reg = MO.getReg();
242
243         LiveVariables::VarInfo &VI = LV->getVarInfo(Reg);
244         if (MO.isDef()) {
245           MachineInstr *NewMI = (Reg == WBReg) ? UpdateMI : MemMI;
246           if (MO.isDead())
247             LV->addVirtualRegisterDead(Reg, NewMI);
248         }
249         if (MO.isUse() && MO.isKill()) {
250           for (unsigned j = 0; j < 2; ++j) {
251             // Look at the two new MI's in reverse order.
252             MachineInstr *NewMI = NewMIs[j];
253             if (!NewMI->readsRegister(Reg))
254               continue;
255             LV->addVirtualRegisterKilled(Reg, NewMI);
256             if (VI.removeKill(MI))
257               VI.Kills.push_back(NewMI);
258             break;
259           }
260         }
261       }
262     }
263   }
264
265   MFI->insert(MBBI, NewMIs[1]);
266   MFI->insert(MBBI, NewMIs[0]);
267   return NewMIs[0];
268 }
269
270 // Branch analysis.
271 bool
272 ARMBaseInstrInfo::AnalyzeBranch(MachineBasicBlock &MBB,MachineBasicBlock *&TBB,
273                                 MachineBasicBlock *&FBB,
274                                 SmallVectorImpl<MachineOperand> &Cond,
275                                 bool AllowModify) const {
276   TBB = 0;
277   FBB = 0;
278
279   MachineBasicBlock::iterator I = MBB.end();
280   if (I == MBB.begin())
281     return false; // Empty blocks are easy.
282   --I;
283
284   // Walk backwards from the end of the basic block until the branch is
285   // analyzed or we give up.
286   while (isPredicated(I) || I->isTerminator() || I->isDebugValue()) {
287
288     // Flag to be raised on unanalyzeable instructions. This is useful in cases
289     // where we want to clean up on the end of the basic block before we bail
290     // out.
291     bool CantAnalyze = false;
292
293     // Skip over DEBUG values and predicated nonterminators.
294     while (I->isDebugValue() || !I->isTerminator()) {
295       if (I == MBB.begin())
296         return false;
297       --I;
298     }
299
300     if (isIndirectBranchOpcode(I->getOpcode()) ||
301         isJumpTableBranchOpcode(I->getOpcode())) {
302       // Indirect branches and jump tables can't be analyzed, but we still want
303       // to clean up any instructions at the tail of the basic block.
304       CantAnalyze = true;
305     } else if (isUncondBranchOpcode(I->getOpcode())) {
306       TBB = I->getOperand(0).getMBB();
307     } else if (isCondBranchOpcode(I->getOpcode())) {
308       // Bail out if we encounter multiple conditional branches.
309       if (!Cond.empty())
310         return true;
311
312       assert(!FBB && "FBB should have been null.");
313       FBB = TBB;
314       TBB = I->getOperand(0).getMBB();
315       Cond.push_back(I->getOperand(1));
316       Cond.push_back(I->getOperand(2));
317     } else if (I->isReturn()) {
318       // Returns can't be analyzed, but we should run cleanup.
319       CantAnalyze = !isPredicated(I);
320     } else {
321       // We encountered other unrecognized terminator. Bail out immediately.
322       return true;
323     }
324
325     // Cleanup code - to be run for unpredicated unconditional branches and
326     //                returns.
327     if (!isPredicated(I) &&
328           (isUncondBranchOpcode(I->getOpcode()) ||
329            isIndirectBranchOpcode(I->getOpcode()) ||
330            isJumpTableBranchOpcode(I->getOpcode()) ||
331            I->isReturn())) {
332       // Forget any previous condition branch information - it no longer applies.
333       Cond.clear();
334       FBB = 0;
335
336       // If we can modify the function, delete everything below this
337       // unconditional branch.
338       if (AllowModify) {
339         MachineBasicBlock::iterator DI = std::next(I);
340         while (DI != MBB.end()) {
341           MachineInstr *InstToDelete = DI;
342           ++DI;
343           InstToDelete->eraseFromParent();
344         }
345       }
346     }
347
348     if (CantAnalyze)
349       return true;
350
351     if (I == MBB.begin())
352       return false;
353
354     --I;
355   }
356
357   // We made it past the terminators without bailing out - we must have
358   // analyzed this branch successfully.
359   return false;
360 }
361
362
363 unsigned ARMBaseInstrInfo::RemoveBranch(MachineBasicBlock &MBB) const {
364   MachineBasicBlock::iterator I = MBB.end();
365   if (I == MBB.begin()) return 0;
366   --I;
367   while (I->isDebugValue()) {
368     if (I == MBB.begin())
369       return 0;
370     --I;
371   }
372   if (!isUncondBranchOpcode(I->getOpcode()) &&
373       !isCondBranchOpcode(I->getOpcode()))
374     return 0;
375
376   // Remove the branch.
377   I->eraseFromParent();
378
379   I = MBB.end();
380
381   if (I == MBB.begin()) return 1;
382   --I;
383   if (!isCondBranchOpcode(I->getOpcode()))
384     return 1;
385
386   // Remove the branch.
387   I->eraseFromParent();
388   return 2;
389 }
390
391 unsigned
392 ARMBaseInstrInfo::InsertBranch(MachineBasicBlock &MBB, MachineBasicBlock *TBB,
393                                MachineBasicBlock *FBB,
394                                const SmallVectorImpl<MachineOperand> &Cond,
395                                DebugLoc DL) const {
396   ARMFunctionInfo *AFI = MBB.getParent()->getInfo<ARMFunctionInfo>();
397   int BOpc   = !AFI->isThumbFunction()
398     ? ARM::B : (AFI->isThumb2Function() ? ARM::t2B : ARM::tB);
399   int BccOpc = !AFI->isThumbFunction()
400     ? ARM::Bcc : (AFI->isThumb2Function() ? ARM::t2Bcc : ARM::tBcc);
401   bool isThumb = AFI->isThumbFunction() || AFI->isThumb2Function();
402
403   // Shouldn't be a fall through.
404   assert(TBB && "InsertBranch must not be told to insert a fallthrough");
405   assert((Cond.size() == 2 || Cond.size() == 0) &&
406          "ARM branch conditions have two components!");
407
408   if (FBB == 0) {
409     if (Cond.empty()) { // Unconditional branch?
410       if (isThumb)
411         BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB).addImm(ARMCC::AL).addReg(0);
412       else
413         BuildMI(&MBB, DL, get(BOpc)).addMBB(TBB);
414     } else
415       BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
416         .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
417     return 1;
418   }
419
420   // Two-way conditional branch.
421   BuildMI(&MBB, DL, get(BccOpc)).addMBB(TBB)
422     .addImm(Cond[0].getImm()).addReg(Cond[1].getReg());
423   if (isThumb)
424     BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB).addImm(ARMCC::AL).addReg(0);
425   else
426     BuildMI(&MBB, DL, get(BOpc)).addMBB(FBB);
427   return 2;
428 }
429
430 bool ARMBaseInstrInfo::
431 ReverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const {
432   ARMCC::CondCodes CC = (ARMCC::CondCodes)(int)Cond[0].getImm();
433   Cond[0].setImm(ARMCC::getOppositeCondition(CC));
434   return false;
435 }
436
437 bool ARMBaseInstrInfo::isPredicated(const MachineInstr *MI) const {
438   if (MI->isBundle()) {
439     MachineBasicBlock::const_instr_iterator I = MI;
440     MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
441     while (++I != E && I->isInsideBundle()) {
442       int PIdx = I->findFirstPredOperandIdx();
443       if (PIdx != -1 && I->getOperand(PIdx).getImm() != ARMCC::AL)
444         return true;
445     }
446     return false;
447   }
448
449   int PIdx = MI->findFirstPredOperandIdx();
450   return PIdx != -1 && MI->getOperand(PIdx).getImm() != ARMCC::AL;
451 }
452
453 bool ARMBaseInstrInfo::
454 PredicateInstruction(MachineInstr *MI,
455                      const SmallVectorImpl<MachineOperand> &Pred) const {
456   unsigned Opc = MI->getOpcode();
457   if (isUncondBranchOpcode(Opc)) {
458     MI->setDesc(get(getMatchingCondBranchOpcode(Opc)));
459     MachineInstrBuilder(*MI->getParent()->getParent(), MI)
460       .addImm(Pred[0].getImm())
461       .addReg(Pred[1].getReg());
462     return true;
463   }
464
465   int PIdx = MI->findFirstPredOperandIdx();
466   if (PIdx != -1) {
467     MachineOperand &PMO = MI->getOperand(PIdx);
468     PMO.setImm(Pred[0].getImm());
469     MI->getOperand(PIdx+1).setReg(Pred[1].getReg());
470     return true;
471   }
472   return false;
473 }
474
475 bool ARMBaseInstrInfo::
476 SubsumesPredicate(const SmallVectorImpl<MachineOperand> &Pred1,
477                   const SmallVectorImpl<MachineOperand> &Pred2) const {
478   if (Pred1.size() > 2 || Pred2.size() > 2)
479     return false;
480
481   ARMCC::CondCodes CC1 = (ARMCC::CondCodes)Pred1[0].getImm();
482   ARMCC::CondCodes CC2 = (ARMCC::CondCodes)Pred2[0].getImm();
483   if (CC1 == CC2)
484     return true;
485
486   switch (CC1) {
487   default:
488     return false;
489   case ARMCC::AL:
490     return true;
491   case ARMCC::HS:
492     return CC2 == ARMCC::HI;
493   case ARMCC::LS:
494     return CC2 == ARMCC::LO || CC2 == ARMCC::EQ;
495   case ARMCC::GE:
496     return CC2 == ARMCC::GT;
497   case ARMCC::LE:
498     return CC2 == ARMCC::LT;
499   }
500 }
501
502 bool ARMBaseInstrInfo::DefinesPredicate(MachineInstr *MI,
503                                     std::vector<MachineOperand> &Pred) const {
504   bool Found = false;
505   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
506     const MachineOperand &MO = MI->getOperand(i);
507     if ((MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) ||
508         (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)) {
509       Pred.push_back(MO);
510       Found = true;
511     }
512   }
513
514   return Found;
515 }
516
517 /// isPredicable - Return true if the specified instruction can be predicated.
518 /// By default, this returns true for every instruction with a
519 /// PredicateOperand.
520 bool ARMBaseInstrInfo::isPredicable(MachineInstr *MI) const {
521   if (!MI->isPredicable())
522     return false;
523
524   ARMFunctionInfo *AFI =
525     MI->getParent()->getParent()->getInfo<ARMFunctionInfo>();
526
527   if (AFI->isThumb2Function()) {
528     if (getSubtarget().restrictIT())
529       return isV8EligibleForIT(MI);
530   } else { // non-Thumb
531     if ((MI->getDesc().TSFlags & ARMII::DomainMask) == ARMII::DomainNEON)
532       return false;
533   }
534
535   return true;
536 }
537
538 template<> bool IsCPSRDead<MachineInstr>(MachineInstr* MI) {
539   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
540     const MachineOperand &MO = MI->getOperand(i);
541     if (!MO.isReg() || MO.isUndef() || MO.isUse())
542       continue;
543     if (MO.getReg() != ARM::CPSR)
544       continue;
545     if (!MO.isDead())
546       return false;
547   }
548   // all definitions of CPSR are dead
549   return true;
550 }
551
552 /// FIXME: Works around a gcc miscompilation with -fstrict-aliasing.
553 LLVM_ATTRIBUTE_NOINLINE
554 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
555                                 unsigned JTI);
556 static unsigned getNumJTEntries(const std::vector<MachineJumpTableEntry> &JT,
557                                 unsigned JTI) {
558   assert(JTI < JT.size());
559   return JT[JTI].MBBs.size();
560 }
561
562 /// GetInstSize - Return the size of the specified MachineInstr.
563 ///
564 unsigned ARMBaseInstrInfo::GetInstSizeInBytes(const MachineInstr *MI) const {
565   const MachineBasicBlock &MBB = *MI->getParent();
566   const MachineFunction *MF = MBB.getParent();
567   const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
568
569   const MCInstrDesc &MCID = MI->getDesc();
570   if (MCID.getSize())
571     return MCID.getSize();
572
573   // If this machine instr is an inline asm, measure it.
574   if (MI->getOpcode() == ARM::INLINEASM)
575     return getInlineAsmLength(MI->getOperand(0).getSymbolName(), *MAI);
576   unsigned Opc = MI->getOpcode();
577   switch (Opc) {
578   default:
579     // pseudo-instruction sizes are zero.
580     return 0;
581   case TargetOpcode::BUNDLE:
582     return getInstBundleLength(MI);
583   case ARM::MOVi16_ga_pcrel:
584   case ARM::MOVTi16_ga_pcrel:
585   case ARM::t2MOVi16_ga_pcrel:
586   case ARM::t2MOVTi16_ga_pcrel:
587     return 4;
588   case ARM::MOVi32imm:
589   case ARM::t2MOVi32imm:
590     return 8;
591   case ARM::CONSTPOOL_ENTRY:
592     // If this machine instr is a constant pool entry, its size is recorded as
593     // operand #2.
594     return MI->getOperand(2).getImm();
595   case ARM::Int_eh_sjlj_longjmp:
596     return 16;
597   case ARM::tInt_eh_sjlj_longjmp:
598     return 10;
599   case ARM::Int_eh_sjlj_setjmp:
600   case ARM::Int_eh_sjlj_setjmp_nofp:
601     return 20;
602   case ARM::tInt_eh_sjlj_setjmp:
603   case ARM::t2Int_eh_sjlj_setjmp:
604   case ARM::t2Int_eh_sjlj_setjmp_nofp:
605     return 12;
606   case ARM::BR_JTr:
607   case ARM::BR_JTm:
608   case ARM::BR_JTadd:
609   case ARM::tBR_JTr:
610   case ARM::t2BR_JT:
611   case ARM::t2TBB_JT:
612   case ARM::t2TBH_JT: {
613     // These are jumptable branches, i.e. a branch followed by an inlined
614     // jumptable. The size is 4 + 4 * number of entries. For TBB, each
615     // entry is one byte; TBH two byte each.
616     unsigned EntrySize = (Opc == ARM::t2TBB_JT)
617       ? 1 : ((Opc == ARM::t2TBH_JT) ? 2 : 4);
618     unsigned NumOps = MCID.getNumOperands();
619     MachineOperand JTOP =
620       MI->getOperand(NumOps - (MI->isPredicable() ? 3 : 2));
621     unsigned JTI = JTOP.getIndex();
622     const MachineJumpTableInfo *MJTI = MF->getJumpTableInfo();
623     assert(MJTI != 0);
624     const std::vector<MachineJumpTableEntry> &JT = MJTI->getJumpTables();
625     assert(JTI < JT.size());
626     // Thumb instructions are 2 byte aligned, but JT entries are 4 byte
627     // 4 aligned. The assembler / linker may add 2 byte padding just before
628     // the JT entries.  The size does not include this padding; the
629     // constant islands pass does separate bookkeeping for it.
630     // FIXME: If we know the size of the function is less than (1 << 16) *2
631     // bytes, we can use 16-bit entries instead. Then there won't be an
632     // alignment issue.
633     unsigned InstSize = (Opc == ARM::tBR_JTr || Opc == ARM::t2BR_JT) ? 2 : 4;
634     unsigned NumEntries = getNumJTEntries(JT, JTI);
635     if (Opc == ARM::t2TBB_JT && (NumEntries & 1))
636       // Make sure the instruction that follows TBB is 2-byte aligned.
637       // FIXME: Constant island pass should insert an "ALIGN" instruction
638       // instead.
639       ++NumEntries;
640     return NumEntries * EntrySize + InstSize;
641   }
642   }
643 }
644
645 unsigned ARMBaseInstrInfo::getInstBundleLength(const MachineInstr *MI) const {
646   unsigned Size = 0;
647   MachineBasicBlock::const_instr_iterator I = MI;
648   MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
649   while (++I != E && I->isInsideBundle()) {
650     assert(!I->isBundle() && "No nested bundle!");
651     Size += GetInstSizeInBytes(&*I);
652   }
653   return Size;
654 }
655
656 void ARMBaseInstrInfo::copyPhysReg(MachineBasicBlock &MBB,
657                                    MachineBasicBlock::iterator I, DebugLoc DL,
658                                    unsigned DestReg, unsigned SrcReg,
659                                    bool KillSrc) const {
660   bool GPRDest = ARM::GPRRegClass.contains(DestReg);
661   bool GPRSrc = ARM::GPRRegClass.contains(SrcReg);
662
663   if (GPRDest && GPRSrc) {
664     AddDefaultCC(AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::MOVr), DestReg)
665                                     .addReg(SrcReg, getKillRegState(KillSrc))));
666     return;
667   }
668
669   bool SPRDest = ARM::SPRRegClass.contains(DestReg);
670   bool SPRSrc = ARM::SPRRegClass.contains(SrcReg);
671
672   unsigned Opc = 0;
673   if (SPRDest && SPRSrc)
674     Opc = ARM::VMOVS;
675   else if (GPRDest && SPRSrc)
676     Opc = ARM::VMOVRS;
677   else if (SPRDest && GPRSrc)
678     Opc = ARM::VMOVSR;
679   else if (ARM::DPRRegClass.contains(DestReg, SrcReg))
680     Opc = ARM::VMOVD;
681   else if (ARM::QPRRegClass.contains(DestReg, SrcReg))
682     Opc = ARM::VORRq;
683
684   if (Opc) {
685     MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opc), DestReg);
686     MIB.addReg(SrcReg, getKillRegState(KillSrc));
687     if (Opc == ARM::VORRq)
688       MIB.addReg(SrcReg, getKillRegState(KillSrc));
689     AddDefaultPred(MIB);
690     return;
691   }
692
693   // Handle register classes that require multiple instructions.
694   unsigned BeginIdx = 0;
695   unsigned SubRegs = 0;
696   int Spacing = 1;
697
698   // Use VORRq when possible.
699   if (ARM::QQPRRegClass.contains(DestReg, SrcReg)) {
700     Opc = ARM::VORRq;
701     BeginIdx = ARM::qsub_0;
702     SubRegs = 2;
703   } else if (ARM::QQQQPRRegClass.contains(DestReg, SrcReg)) {
704     Opc = ARM::VORRq;
705     BeginIdx = ARM::qsub_0;
706     SubRegs = 4;
707   // Fall back to VMOVD.
708   } else if (ARM::DPairRegClass.contains(DestReg, SrcReg)) {
709     Opc = ARM::VMOVD;
710     BeginIdx = ARM::dsub_0;
711     SubRegs = 2;
712   } else if (ARM::DTripleRegClass.contains(DestReg, SrcReg)) {
713     Opc = ARM::VMOVD;
714     BeginIdx = ARM::dsub_0;
715     SubRegs = 3;
716   } else if (ARM::DQuadRegClass.contains(DestReg, SrcReg)) {
717     Opc = ARM::VMOVD;
718     BeginIdx = ARM::dsub_0;
719     SubRegs = 4;
720   } else if (ARM::GPRPairRegClass.contains(DestReg, SrcReg)) {
721     Opc = Subtarget.isThumb2() ? ARM::tMOVr : ARM::MOVr;
722     BeginIdx = ARM::gsub_0;
723     SubRegs = 2;
724   } else if (ARM::DPairSpcRegClass.contains(DestReg, SrcReg)) {
725     Opc = ARM::VMOVD;
726     BeginIdx = ARM::dsub_0;
727     SubRegs = 2;
728     Spacing = 2;
729   } else if (ARM::DTripleSpcRegClass.contains(DestReg, SrcReg)) {
730     Opc = ARM::VMOVD;
731     BeginIdx = ARM::dsub_0;
732     SubRegs = 3;
733     Spacing = 2;
734   } else if (ARM::DQuadSpcRegClass.contains(DestReg, SrcReg)) {
735     Opc = ARM::VMOVD;
736     BeginIdx = ARM::dsub_0;
737     SubRegs = 4;
738     Spacing = 2;
739   }
740
741   assert(Opc && "Impossible reg-to-reg copy");
742
743   const TargetRegisterInfo *TRI = &getRegisterInfo();
744   MachineInstrBuilder Mov;
745
746   // Copy register tuples backward when the first Dest reg overlaps with SrcReg.
747   if (TRI->regsOverlap(SrcReg, TRI->getSubReg(DestReg, BeginIdx))) {
748     BeginIdx = BeginIdx + ((SubRegs - 1) * Spacing);
749     Spacing = -Spacing;
750   }
751 #ifndef NDEBUG
752   SmallSet<unsigned, 4> DstRegs;
753 #endif
754   for (unsigned i = 0; i != SubRegs; ++i) {
755     unsigned Dst = TRI->getSubReg(DestReg, BeginIdx + i * Spacing);
756     unsigned Src = TRI->getSubReg(SrcReg, BeginIdx + i * Spacing);
757     assert(Dst && Src && "Bad sub-register");
758 #ifndef NDEBUG
759     assert(!DstRegs.count(Src) && "destructive vector copy");
760     DstRegs.insert(Dst);
761 #endif
762     Mov = BuildMI(MBB, I, I->getDebugLoc(), get(Opc), Dst).addReg(Src);
763     // VORR takes two source operands.
764     if (Opc == ARM::VORRq)
765       Mov.addReg(Src);
766     Mov = AddDefaultPred(Mov);
767     // MOVr can set CC.
768     if (Opc == ARM::MOVr)
769       Mov = AddDefaultCC(Mov);
770   }
771   // Add implicit super-register defs and kills to the last instruction.
772   Mov->addRegisterDefined(DestReg, TRI);
773   if (KillSrc)
774     Mov->addRegisterKilled(SrcReg, TRI);
775 }
776
777 const MachineInstrBuilder &
778 ARMBaseInstrInfo::AddDReg(MachineInstrBuilder &MIB, unsigned Reg,
779                           unsigned SubIdx, unsigned State,
780                           const TargetRegisterInfo *TRI) const {
781   if (!SubIdx)
782     return MIB.addReg(Reg, State);
783
784   if (TargetRegisterInfo::isPhysicalRegister(Reg))
785     return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
786   return MIB.addReg(Reg, State, SubIdx);
787 }
788
789 void ARMBaseInstrInfo::
790 storeRegToStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
791                     unsigned SrcReg, bool isKill, int FI,
792                     const TargetRegisterClass *RC,
793                     const TargetRegisterInfo *TRI) const {
794   DebugLoc DL;
795   if (I != MBB.end()) DL = I->getDebugLoc();
796   MachineFunction &MF = *MBB.getParent();
797   MachineFrameInfo &MFI = *MF.getFrameInfo();
798   unsigned Align = MFI.getObjectAlignment(FI);
799
800   MachineMemOperand *MMO =
801     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
802                             MachineMemOperand::MOStore,
803                             MFI.getObjectSize(FI),
804                             Align);
805
806   switch (RC->getSize()) {
807     case 4:
808       if (ARM::GPRRegClass.hasSubClassEq(RC)) {
809         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STRi12))
810                    .addReg(SrcReg, getKillRegState(isKill))
811                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
812       } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
813         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRS))
814                    .addReg(SrcReg, getKillRegState(isKill))
815                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
816       } else
817         llvm_unreachable("Unknown reg class!");
818       break;
819     case 8:
820       if (ARM::DPRRegClass.hasSubClassEq(RC)) {
821         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTRD))
822                    .addReg(SrcReg, getKillRegState(isKill))
823                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
824       } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
825         if (Subtarget.hasV5TEOps()) {
826           MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(ARM::STRD));
827           AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
828           AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
829           MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO);
830
831           AddDefaultPred(MIB);
832         } else {
833           // Fallback to STM instruction, which has existed since the dawn of
834           // time.
835           MachineInstrBuilder MIB =
836             AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::STMIA))
837                              .addFrameIndex(FI).addMemOperand(MMO));
838           AddDReg(MIB, SrcReg, ARM::gsub_0, getKillRegState(isKill), TRI);
839           AddDReg(MIB, SrcReg, ARM::gsub_1, 0, TRI);
840         }
841       } else
842         llvm_unreachable("Unknown reg class!");
843       break;
844     case 16:
845       if (ARM::DPairRegClass.hasSubClassEq(RC)) {
846         // Use aligned spills if the stack can be realigned.
847         if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
848           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1q64))
849                      .addFrameIndex(FI).addImm(16)
850                      .addReg(SrcReg, getKillRegState(isKill))
851                      .addMemOperand(MMO));
852         } else {
853           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMQIA))
854                      .addReg(SrcReg, getKillRegState(isKill))
855                      .addFrameIndex(FI)
856                      .addMemOperand(MMO));
857         }
858       } else
859         llvm_unreachable("Unknown reg class!");
860       break;
861     case 24:
862       if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
863         // Use aligned spills if the stack can be realigned.
864         if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
865           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64TPseudo))
866                      .addFrameIndex(FI).addImm(16)
867                      .addReg(SrcReg, getKillRegState(isKill))
868                      .addMemOperand(MMO));
869         } else {
870           MachineInstrBuilder MIB =
871           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
872                        .addFrameIndex(FI))
873                        .addMemOperand(MMO);
874           MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
875           MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
876           AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
877         }
878       } else
879         llvm_unreachable("Unknown reg class!");
880       break;
881     case 32:
882       if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
883         if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
884           // FIXME: It's possible to only store part of the QQ register if the
885           // spilled def has a sub-register index.
886           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VST1d64QPseudo))
887                      .addFrameIndex(FI).addImm(16)
888                      .addReg(SrcReg, getKillRegState(isKill))
889                      .addMemOperand(MMO));
890         } else {
891           MachineInstrBuilder MIB =
892           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
893                        .addFrameIndex(FI))
894                        .addMemOperand(MMO);
895           MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
896           MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
897           MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
898                 AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
899         }
900       } else
901         llvm_unreachable("Unknown reg class!");
902       break;
903     case 64:
904       if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
905         MachineInstrBuilder MIB =
906           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VSTMDIA))
907                          .addFrameIndex(FI))
908                          .addMemOperand(MMO);
909         MIB = AddDReg(MIB, SrcReg, ARM::dsub_0, getKillRegState(isKill), TRI);
910         MIB = AddDReg(MIB, SrcReg, ARM::dsub_1, 0, TRI);
911         MIB = AddDReg(MIB, SrcReg, ARM::dsub_2, 0, TRI);
912         MIB = AddDReg(MIB, SrcReg, ARM::dsub_3, 0, TRI);
913         MIB = AddDReg(MIB, SrcReg, ARM::dsub_4, 0, TRI);
914         MIB = AddDReg(MIB, SrcReg, ARM::dsub_5, 0, TRI);
915         MIB = AddDReg(MIB, SrcReg, ARM::dsub_6, 0, TRI);
916               AddDReg(MIB, SrcReg, ARM::dsub_7, 0, TRI);
917       } else
918         llvm_unreachable("Unknown reg class!");
919       break;
920     default:
921       llvm_unreachable("Unknown reg class!");
922   }
923 }
924
925 unsigned
926 ARMBaseInstrInfo::isStoreToStackSlot(const MachineInstr *MI,
927                                      int &FrameIndex) const {
928   switch (MI->getOpcode()) {
929   default: break;
930   case ARM::STRrs:
931   case ARM::t2STRs: // FIXME: don't use t2STRs to access frame.
932     if (MI->getOperand(1).isFI() &&
933         MI->getOperand(2).isReg() &&
934         MI->getOperand(3).isImm() &&
935         MI->getOperand(2).getReg() == 0 &&
936         MI->getOperand(3).getImm() == 0) {
937       FrameIndex = MI->getOperand(1).getIndex();
938       return MI->getOperand(0).getReg();
939     }
940     break;
941   case ARM::STRi12:
942   case ARM::t2STRi12:
943   case ARM::tSTRspi:
944   case ARM::VSTRD:
945   case ARM::VSTRS:
946     if (MI->getOperand(1).isFI() &&
947         MI->getOperand(2).isImm() &&
948         MI->getOperand(2).getImm() == 0) {
949       FrameIndex = MI->getOperand(1).getIndex();
950       return MI->getOperand(0).getReg();
951     }
952     break;
953   case ARM::VST1q64:
954   case ARM::VST1d64TPseudo:
955   case ARM::VST1d64QPseudo:
956     if (MI->getOperand(0).isFI() &&
957         MI->getOperand(2).getSubReg() == 0) {
958       FrameIndex = MI->getOperand(0).getIndex();
959       return MI->getOperand(2).getReg();
960     }
961     break;
962   case ARM::VSTMQIA:
963     if (MI->getOperand(1).isFI() &&
964         MI->getOperand(0).getSubReg() == 0) {
965       FrameIndex = MI->getOperand(1).getIndex();
966       return MI->getOperand(0).getReg();
967     }
968     break;
969   }
970
971   return 0;
972 }
973
974 unsigned ARMBaseInstrInfo::isStoreToStackSlotPostFE(const MachineInstr *MI,
975                                                     int &FrameIndex) const {
976   const MachineMemOperand *Dummy;
977   return MI->mayStore() && hasStoreToStackSlot(MI, Dummy, FrameIndex);
978 }
979
980 void ARMBaseInstrInfo::
981 loadRegFromStackSlot(MachineBasicBlock &MBB, MachineBasicBlock::iterator I,
982                      unsigned DestReg, int FI,
983                      const TargetRegisterClass *RC,
984                      const TargetRegisterInfo *TRI) const {
985   DebugLoc DL;
986   if (I != MBB.end()) DL = I->getDebugLoc();
987   MachineFunction &MF = *MBB.getParent();
988   MachineFrameInfo &MFI = *MF.getFrameInfo();
989   unsigned Align = MFI.getObjectAlignment(FI);
990   MachineMemOperand *MMO =
991     MF.getMachineMemOperand(
992                     MachinePointerInfo::getFixedStack(FI),
993                             MachineMemOperand::MOLoad,
994                             MFI.getObjectSize(FI),
995                             Align);
996
997   switch (RC->getSize()) {
998   case 4:
999     if (ARM::GPRRegClass.hasSubClassEq(RC)) {
1000       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDRi12), DestReg)
1001                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
1002
1003     } else if (ARM::SPRRegClass.hasSubClassEq(RC)) {
1004       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRS), DestReg)
1005                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
1006     } else
1007       llvm_unreachable("Unknown reg class!");
1008     break;
1009   case 8:
1010     if (ARM::DPRRegClass.hasSubClassEq(RC)) {
1011       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDRD), DestReg)
1012                    .addFrameIndex(FI).addImm(0).addMemOperand(MMO));
1013     } else if (ARM::GPRPairRegClass.hasSubClassEq(RC)) {
1014       MachineInstrBuilder MIB;
1015
1016       if (Subtarget.hasV5TEOps()) {
1017         MIB = BuildMI(MBB, I, DL, get(ARM::LDRD));
1018         AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1019         AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1020         MIB.addFrameIndex(FI).addReg(0).addImm(0).addMemOperand(MMO);
1021
1022         AddDefaultPred(MIB);
1023       } else {
1024         // Fallback to LDM instruction, which has existed since the dawn of
1025         // time.
1026         MIB = AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::LDMIA))
1027                                  .addFrameIndex(FI).addMemOperand(MMO));
1028         MIB = AddDReg(MIB, DestReg, ARM::gsub_0, RegState::DefineNoRead, TRI);
1029         MIB = AddDReg(MIB, DestReg, ARM::gsub_1, RegState::DefineNoRead, TRI);
1030       }
1031
1032       if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1033         MIB.addReg(DestReg, RegState::ImplicitDefine);
1034     } else
1035       llvm_unreachable("Unknown reg class!");
1036     break;
1037   case 16:
1038     if (ARM::DPairRegClass.hasSubClassEq(RC)) {
1039       if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1040         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1q64), DestReg)
1041                      .addFrameIndex(FI).addImm(16)
1042                      .addMemOperand(MMO));
1043       } else {
1044         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMQIA), DestReg)
1045                        .addFrameIndex(FI)
1046                        .addMemOperand(MMO));
1047       }
1048     } else
1049       llvm_unreachable("Unknown reg class!");
1050     break;
1051   case 24:
1052     if (ARM::DTripleRegClass.hasSubClassEq(RC)) {
1053       if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1054         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64TPseudo), DestReg)
1055                      .addFrameIndex(FI).addImm(16)
1056                      .addMemOperand(MMO));
1057       } else {
1058         MachineInstrBuilder MIB =
1059           AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1060                          .addFrameIndex(FI)
1061                          .addMemOperand(MMO));
1062         MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1063         MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1064         MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1065         if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1066           MIB.addReg(DestReg, RegState::ImplicitDefine);
1067       }
1068     } else
1069       llvm_unreachable("Unknown reg class!");
1070     break;
1071    case 32:
1072     if (ARM::QQPRRegClass.hasSubClassEq(RC) || ARM::DQuadRegClass.hasSubClassEq(RC)) {
1073       if (Align >= 16 && getRegisterInfo().canRealignStack(MF)) {
1074         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLD1d64QPseudo), DestReg)
1075                      .addFrameIndex(FI).addImm(16)
1076                      .addMemOperand(MMO));
1077       } else {
1078         MachineInstrBuilder MIB =
1079         AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1080                        .addFrameIndex(FI))
1081                        .addMemOperand(MMO);
1082         MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1083         MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1084         MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1085         MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1086         if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1087           MIB.addReg(DestReg, RegState::ImplicitDefine);
1088       }
1089     } else
1090       llvm_unreachable("Unknown reg class!");
1091     break;
1092   case 64:
1093     if (ARM::QQQQPRRegClass.hasSubClassEq(RC)) {
1094       MachineInstrBuilder MIB =
1095       AddDefaultPred(BuildMI(MBB, I, DL, get(ARM::VLDMDIA))
1096                      .addFrameIndex(FI))
1097                      .addMemOperand(MMO);
1098       MIB = AddDReg(MIB, DestReg, ARM::dsub_0, RegState::DefineNoRead, TRI);
1099       MIB = AddDReg(MIB, DestReg, ARM::dsub_1, RegState::DefineNoRead, TRI);
1100       MIB = AddDReg(MIB, DestReg, ARM::dsub_2, RegState::DefineNoRead, TRI);
1101       MIB = AddDReg(MIB, DestReg, ARM::dsub_3, RegState::DefineNoRead, TRI);
1102       MIB = AddDReg(MIB, DestReg, ARM::dsub_4, RegState::DefineNoRead, TRI);
1103       MIB = AddDReg(MIB, DestReg, ARM::dsub_5, RegState::DefineNoRead, TRI);
1104       MIB = AddDReg(MIB, DestReg, ARM::dsub_6, RegState::DefineNoRead, TRI);
1105       MIB = AddDReg(MIB, DestReg, ARM::dsub_7, RegState::DefineNoRead, TRI);
1106       if (TargetRegisterInfo::isPhysicalRegister(DestReg))
1107         MIB.addReg(DestReg, RegState::ImplicitDefine);
1108     } else
1109       llvm_unreachable("Unknown reg class!");
1110     break;
1111   default:
1112     llvm_unreachable("Unknown regclass!");
1113   }
1114 }
1115
1116 unsigned
1117 ARMBaseInstrInfo::isLoadFromStackSlot(const MachineInstr *MI,
1118                                       int &FrameIndex) const {
1119   switch (MI->getOpcode()) {
1120   default: break;
1121   case ARM::LDRrs:
1122   case ARM::t2LDRs:  // FIXME: don't use t2LDRs to access frame.
1123     if (MI->getOperand(1).isFI() &&
1124         MI->getOperand(2).isReg() &&
1125         MI->getOperand(3).isImm() &&
1126         MI->getOperand(2).getReg() == 0 &&
1127         MI->getOperand(3).getImm() == 0) {
1128       FrameIndex = MI->getOperand(1).getIndex();
1129       return MI->getOperand(0).getReg();
1130     }
1131     break;
1132   case ARM::LDRi12:
1133   case ARM::t2LDRi12:
1134   case ARM::tLDRspi:
1135   case ARM::VLDRD:
1136   case ARM::VLDRS:
1137     if (MI->getOperand(1).isFI() &&
1138         MI->getOperand(2).isImm() &&
1139         MI->getOperand(2).getImm() == 0) {
1140       FrameIndex = MI->getOperand(1).getIndex();
1141       return MI->getOperand(0).getReg();
1142     }
1143     break;
1144   case ARM::VLD1q64:
1145   case ARM::VLD1d64TPseudo:
1146   case ARM::VLD1d64QPseudo:
1147     if (MI->getOperand(1).isFI() &&
1148         MI->getOperand(0).getSubReg() == 0) {
1149       FrameIndex = MI->getOperand(1).getIndex();
1150       return MI->getOperand(0).getReg();
1151     }
1152     break;
1153   case ARM::VLDMQIA:
1154     if (MI->getOperand(1).isFI() &&
1155         MI->getOperand(0).getSubReg() == 0) {
1156       FrameIndex = MI->getOperand(1).getIndex();
1157       return MI->getOperand(0).getReg();
1158     }
1159     break;
1160   }
1161
1162   return 0;
1163 }
1164
1165 unsigned ARMBaseInstrInfo::isLoadFromStackSlotPostFE(const MachineInstr *MI,
1166                                              int &FrameIndex) const {
1167   const MachineMemOperand *Dummy;
1168   return MI->mayLoad() && hasLoadFromStackSlot(MI, Dummy, FrameIndex);
1169 }
1170
1171 bool ARMBaseInstrInfo::expandPostRAPseudo(MachineBasicBlock::iterator MI) const{
1172   // This hook gets to expand COPY instructions before they become
1173   // copyPhysReg() calls.  Look for VMOVS instructions that can legally be
1174   // widened to VMOVD.  We prefer the VMOVD when possible because it may be
1175   // changed into a VORR that can go down the NEON pipeline.
1176   if (!WidenVMOVS || !MI->isCopy() || Subtarget.isCortexA15())
1177     return false;
1178
1179   // Look for a copy between even S-registers.  That is where we keep floats
1180   // when using NEON v2f32 instructions for f32 arithmetic.
1181   unsigned DstRegS = MI->getOperand(0).getReg();
1182   unsigned SrcRegS = MI->getOperand(1).getReg();
1183   if (!ARM::SPRRegClass.contains(DstRegS, SrcRegS))
1184     return false;
1185
1186   const TargetRegisterInfo *TRI = &getRegisterInfo();
1187   unsigned DstRegD = TRI->getMatchingSuperReg(DstRegS, ARM::ssub_0,
1188                                               &ARM::DPRRegClass);
1189   unsigned SrcRegD = TRI->getMatchingSuperReg(SrcRegS, ARM::ssub_0,
1190                                               &ARM::DPRRegClass);
1191   if (!DstRegD || !SrcRegD)
1192     return false;
1193
1194   // We want to widen this into a DstRegD = VMOVD SrcRegD copy.  This is only
1195   // legal if the COPY already defines the full DstRegD, and it isn't a
1196   // sub-register insertion.
1197   if (!MI->definesRegister(DstRegD, TRI) || MI->readsRegister(DstRegD, TRI))
1198     return false;
1199
1200   // A dead copy shouldn't show up here, but reject it just in case.
1201   if (MI->getOperand(0).isDead())
1202     return false;
1203
1204   // All clear, widen the COPY.
1205   DEBUG(dbgs() << "widening:    " << *MI);
1206   MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI);
1207
1208   // Get rid of the old <imp-def> of DstRegD.  Leave it if it defines a Q-reg
1209   // or some other super-register.
1210   int ImpDefIdx = MI->findRegisterDefOperandIdx(DstRegD);
1211   if (ImpDefIdx != -1)
1212     MI->RemoveOperand(ImpDefIdx);
1213
1214   // Change the opcode and operands.
1215   MI->setDesc(get(ARM::VMOVD));
1216   MI->getOperand(0).setReg(DstRegD);
1217   MI->getOperand(1).setReg(SrcRegD);
1218   AddDefaultPred(MIB);
1219
1220   // We are now reading SrcRegD instead of SrcRegS.  This may upset the
1221   // register scavenger and machine verifier, so we need to indicate that we
1222   // are reading an undefined value from SrcRegD, but a proper value from
1223   // SrcRegS.
1224   MI->getOperand(1).setIsUndef();
1225   MIB.addReg(SrcRegS, RegState::Implicit);
1226
1227   // SrcRegD may actually contain an unrelated value in the ssub_1
1228   // sub-register.  Don't kill it.  Only kill the ssub_0 sub-register.
1229   if (MI->getOperand(1).isKill()) {
1230     MI->getOperand(1).setIsKill(false);
1231     MI->addRegisterKilled(SrcRegS, TRI, true);
1232   }
1233
1234   DEBUG(dbgs() << "replaced by: " << *MI);
1235   return true;
1236 }
1237
1238 /// Create a copy of a const pool value. Update CPI to the new index and return
1239 /// the label UID.
1240 static unsigned duplicateCPV(MachineFunction &MF, unsigned &CPI) {
1241   MachineConstantPool *MCP = MF.getConstantPool();
1242   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1243
1244   const MachineConstantPoolEntry &MCPE = MCP->getConstants()[CPI];
1245   assert(MCPE.isMachineConstantPoolEntry() &&
1246          "Expecting a machine constantpool entry!");
1247   ARMConstantPoolValue *ACPV =
1248     static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
1249
1250   unsigned PCLabelId = AFI->createPICLabelUId();
1251   ARMConstantPoolValue *NewCPV = 0;
1252
1253   // FIXME: The below assumes PIC relocation model and that the function
1254   // is Thumb mode (t1 or t2). PCAdjustment would be 8 for ARM mode PIC, and
1255   // zero for non-PIC in ARM or Thumb. The callers are all of thumb LDR
1256   // instructions, so that's probably OK, but is PIC always correct when
1257   // we get here?
1258   if (ACPV->isGlobalValue())
1259     NewCPV = ARMConstantPoolConstant::
1260       Create(cast<ARMConstantPoolConstant>(ACPV)->getGV(), PCLabelId,
1261              ARMCP::CPValue, 4);
1262   else if (ACPV->isExtSymbol())
1263     NewCPV = ARMConstantPoolSymbol::
1264       Create(MF.getFunction()->getContext(),
1265              cast<ARMConstantPoolSymbol>(ACPV)->getSymbol(), PCLabelId, 4);
1266   else if (ACPV->isBlockAddress())
1267     NewCPV = ARMConstantPoolConstant::
1268       Create(cast<ARMConstantPoolConstant>(ACPV)->getBlockAddress(), PCLabelId,
1269              ARMCP::CPBlockAddress, 4);
1270   else if (ACPV->isLSDA())
1271     NewCPV = ARMConstantPoolConstant::Create(MF.getFunction(), PCLabelId,
1272                                              ARMCP::CPLSDA, 4);
1273   else if (ACPV->isMachineBasicBlock())
1274     NewCPV = ARMConstantPoolMBB::
1275       Create(MF.getFunction()->getContext(),
1276              cast<ARMConstantPoolMBB>(ACPV)->getMBB(), PCLabelId, 4);
1277   else
1278     llvm_unreachable("Unexpected ARM constantpool value type!!");
1279   CPI = MCP->getConstantPoolIndex(NewCPV, MCPE.getAlignment());
1280   return PCLabelId;
1281 }
1282
1283 void ARMBaseInstrInfo::
1284 reMaterialize(MachineBasicBlock &MBB,
1285               MachineBasicBlock::iterator I,
1286               unsigned DestReg, unsigned SubIdx,
1287               const MachineInstr *Orig,
1288               const TargetRegisterInfo &TRI) const {
1289   unsigned Opcode = Orig->getOpcode();
1290   switch (Opcode) {
1291   default: {
1292     MachineInstr *MI = MBB.getParent()->CloneMachineInstr(Orig);
1293     MI->substituteRegister(Orig->getOperand(0).getReg(), DestReg, SubIdx, TRI);
1294     MBB.insert(I, MI);
1295     break;
1296   }
1297   case ARM::tLDRpci_pic:
1298   case ARM::t2LDRpci_pic: {
1299     MachineFunction &MF = *MBB.getParent();
1300     unsigned CPI = Orig->getOperand(1).getIndex();
1301     unsigned PCLabelId = duplicateCPV(MF, CPI);
1302     MachineInstrBuilder MIB = BuildMI(MBB, I, Orig->getDebugLoc(), get(Opcode),
1303                                       DestReg)
1304       .addConstantPoolIndex(CPI).addImm(PCLabelId);
1305     MIB->setMemRefs(Orig->memoperands_begin(), Orig->memoperands_end());
1306     break;
1307   }
1308   }
1309 }
1310
1311 MachineInstr *
1312 ARMBaseInstrInfo::duplicate(MachineInstr *Orig, MachineFunction &MF) const {
1313   MachineInstr *MI = TargetInstrInfo::duplicate(Orig, MF);
1314   switch(Orig->getOpcode()) {
1315   case ARM::tLDRpci_pic:
1316   case ARM::t2LDRpci_pic: {
1317     unsigned CPI = Orig->getOperand(1).getIndex();
1318     unsigned PCLabelId = duplicateCPV(MF, CPI);
1319     Orig->getOperand(1).setIndex(CPI);
1320     Orig->getOperand(2).setImm(PCLabelId);
1321     break;
1322   }
1323   }
1324   return MI;
1325 }
1326
1327 bool ARMBaseInstrInfo::produceSameValue(const MachineInstr *MI0,
1328                                         const MachineInstr *MI1,
1329                                         const MachineRegisterInfo *MRI) const {
1330   int Opcode = MI0->getOpcode();
1331   if (Opcode == ARM::t2LDRpci ||
1332       Opcode == ARM::t2LDRpci_pic ||
1333       Opcode == ARM::tLDRpci ||
1334       Opcode == ARM::tLDRpci_pic ||
1335       Opcode == ARM::LDRLIT_ga_pcrel ||
1336       Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
1337       Opcode == ARM::tLDRLIT_ga_pcrel ||
1338       Opcode == ARM::MOV_ga_pcrel ||
1339       Opcode == ARM::MOV_ga_pcrel_ldr ||
1340       Opcode == ARM::t2MOV_ga_pcrel) {
1341     if (MI1->getOpcode() != Opcode)
1342       return false;
1343     if (MI0->getNumOperands() != MI1->getNumOperands())
1344       return false;
1345
1346     const MachineOperand &MO0 = MI0->getOperand(1);
1347     const MachineOperand &MO1 = MI1->getOperand(1);
1348     if (MO0.getOffset() != MO1.getOffset())
1349       return false;
1350
1351     if (Opcode == ARM::LDRLIT_ga_pcrel ||
1352         Opcode == ARM::LDRLIT_ga_pcrel_ldr ||
1353         Opcode == ARM::tLDRLIT_ga_pcrel ||
1354         Opcode == ARM::MOV_ga_pcrel ||
1355         Opcode == ARM::MOV_ga_pcrel_ldr ||
1356         Opcode == ARM::t2MOV_ga_pcrel)
1357       // Ignore the PC labels.
1358       return MO0.getGlobal() == MO1.getGlobal();
1359
1360     const MachineFunction *MF = MI0->getParent()->getParent();
1361     const MachineConstantPool *MCP = MF->getConstantPool();
1362     int CPI0 = MO0.getIndex();
1363     int CPI1 = MO1.getIndex();
1364     const MachineConstantPoolEntry &MCPE0 = MCP->getConstants()[CPI0];
1365     const MachineConstantPoolEntry &MCPE1 = MCP->getConstants()[CPI1];
1366     bool isARMCP0 = MCPE0.isMachineConstantPoolEntry();
1367     bool isARMCP1 = MCPE1.isMachineConstantPoolEntry();
1368     if (isARMCP0 && isARMCP1) {
1369       ARMConstantPoolValue *ACPV0 =
1370         static_cast<ARMConstantPoolValue*>(MCPE0.Val.MachineCPVal);
1371       ARMConstantPoolValue *ACPV1 =
1372         static_cast<ARMConstantPoolValue*>(MCPE1.Val.MachineCPVal);
1373       return ACPV0->hasSameValue(ACPV1);
1374     } else if (!isARMCP0 && !isARMCP1) {
1375       return MCPE0.Val.ConstVal == MCPE1.Val.ConstVal;
1376     }
1377     return false;
1378   } else if (Opcode == ARM::PICLDR) {
1379     if (MI1->getOpcode() != Opcode)
1380       return false;
1381     if (MI0->getNumOperands() != MI1->getNumOperands())
1382       return false;
1383
1384     unsigned Addr0 = MI0->getOperand(1).getReg();
1385     unsigned Addr1 = MI1->getOperand(1).getReg();
1386     if (Addr0 != Addr1) {
1387       if (!MRI ||
1388           !TargetRegisterInfo::isVirtualRegister(Addr0) ||
1389           !TargetRegisterInfo::isVirtualRegister(Addr1))
1390         return false;
1391
1392       // This assumes SSA form.
1393       MachineInstr *Def0 = MRI->getVRegDef(Addr0);
1394       MachineInstr *Def1 = MRI->getVRegDef(Addr1);
1395       // Check if the loaded value, e.g. a constantpool of a global address, are
1396       // the same.
1397       if (!produceSameValue(Def0, Def1, MRI))
1398         return false;
1399     }
1400
1401     for (unsigned i = 3, e = MI0->getNumOperands(); i != e; ++i) {
1402       // %vreg12<def> = PICLDR %vreg11, 0, pred:14, pred:%noreg
1403       const MachineOperand &MO0 = MI0->getOperand(i);
1404       const MachineOperand &MO1 = MI1->getOperand(i);
1405       if (!MO0.isIdenticalTo(MO1))
1406         return false;
1407     }
1408     return true;
1409   }
1410
1411   return MI0->isIdenticalTo(MI1, MachineInstr::IgnoreVRegDefs);
1412 }
1413
1414 /// areLoadsFromSameBasePtr - This is used by the pre-regalloc scheduler to
1415 /// determine if two loads are loading from the same base address. It should
1416 /// only return true if the base pointers are the same and the only differences
1417 /// between the two addresses is the offset. It also returns the offsets by
1418 /// reference.
1419 ///
1420 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1421 /// is permanently disabled.
1422 bool ARMBaseInstrInfo::areLoadsFromSameBasePtr(SDNode *Load1, SDNode *Load2,
1423                                                int64_t &Offset1,
1424                                                int64_t &Offset2) const {
1425   // Don't worry about Thumb: just ARM and Thumb2.
1426   if (Subtarget.isThumb1Only()) return false;
1427
1428   if (!Load1->isMachineOpcode() || !Load2->isMachineOpcode())
1429     return false;
1430
1431   switch (Load1->getMachineOpcode()) {
1432   default:
1433     return false;
1434   case ARM::LDRi12:
1435   case ARM::LDRBi12:
1436   case ARM::LDRD:
1437   case ARM::LDRH:
1438   case ARM::LDRSB:
1439   case ARM::LDRSH:
1440   case ARM::VLDRD:
1441   case ARM::VLDRS:
1442   case ARM::t2LDRi8:
1443   case ARM::t2LDRBi8:
1444   case ARM::t2LDRDi8:
1445   case ARM::t2LDRSHi8:
1446   case ARM::t2LDRi12:
1447   case ARM::t2LDRBi12:
1448   case ARM::t2LDRSHi12:
1449     break;
1450   }
1451
1452   switch (Load2->getMachineOpcode()) {
1453   default:
1454     return false;
1455   case ARM::LDRi12:
1456   case ARM::LDRBi12:
1457   case ARM::LDRD:
1458   case ARM::LDRH:
1459   case ARM::LDRSB:
1460   case ARM::LDRSH:
1461   case ARM::VLDRD:
1462   case ARM::VLDRS:
1463   case ARM::t2LDRi8:
1464   case ARM::t2LDRBi8:
1465   case ARM::t2LDRSHi8:
1466   case ARM::t2LDRi12:
1467   case ARM::t2LDRBi12:
1468   case ARM::t2LDRSHi12:
1469     break;
1470   }
1471
1472   // Check if base addresses and chain operands match.
1473   if (Load1->getOperand(0) != Load2->getOperand(0) ||
1474       Load1->getOperand(4) != Load2->getOperand(4))
1475     return false;
1476
1477   // Index should be Reg0.
1478   if (Load1->getOperand(3) != Load2->getOperand(3))
1479     return false;
1480
1481   // Determine the offsets.
1482   if (isa<ConstantSDNode>(Load1->getOperand(1)) &&
1483       isa<ConstantSDNode>(Load2->getOperand(1))) {
1484     Offset1 = cast<ConstantSDNode>(Load1->getOperand(1))->getSExtValue();
1485     Offset2 = cast<ConstantSDNode>(Load2->getOperand(1))->getSExtValue();
1486     return true;
1487   }
1488
1489   return false;
1490 }
1491
1492 /// shouldScheduleLoadsNear - This is a used by the pre-regalloc scheduler to
1493 /// determine (in conjunction with areLoadsFromSameBasePtr) if two loads should
1494 /// be scheduled togther. On some targets if two loads are loading from
1495 /// addresses in the same cache line, it's better if they are scheduled
1496 /// together. This function takes two integers that represent the load offsets
1497 /// from the common base address. It returns true if it decides it's desirable
1498 /// to schedule the two loads together. "NumLoads" is the number of loads that
1499 /// have already been scheduled after Load1.
1500 ///
1501 /// FIXME: remove this in favor of the MachineInstr interface once pre-RA-sched
1502 /// is permanently disabled.
1503 bool ARMBaseInstrInfo::shouldScheduleLoadsNear(SDNode *Load1, SDNode *Load2,
1504                                                int64_t Offset1, int64_t Offset2,
1505                                                unsigned NumLoads) const {
1506   // Don't worry about Thumb: just ARM and Thumb2.
1507   if (Subtarget.isThumb1Only()) return false;
1508
1509   assert(Offset2 > Offset1);
1510
1511   if ((Offset2 - Offset1) / 8 > 64)
1512     return false;
1513
1514   // Check if the machine opcodes are different. If they are different
1515   // then we consider them to not be of the same base address,
1516   // EXCEPT in the case of Thumb2 byte loads where one is LDRBi8 and the other LDRBi12.
1517   // In this case, they are considered to be the same because they are different
1518   // encoding forms of the same basic instruction.
1519   if ((Load1->getMachineOpcode() != Load2->getMachineOpcode()) &&
1520       !((Load1->getMachineOpcode() == ARM::t2LDRBi8 &&
1521          Load2->getMachineOpcode() == ARM::t2LDRBi12) ||
1522         (Load1->getMachineOpcode() == ARM::t2LDRBi12 &&
1523          Load2->getMachineOpcode() == ARM::t2LDRBi8)))
1524     return false;  // FIXME: overly conservative?
1525
1526   // Four loads in a row should be sufficient.
1527   if (NumLoads >= 3)
1528     return false;
1529
1530   return true;
1531 }
1532
1533 bool ARMBaseInstrInfo::isSchedulingBoundary(const MachineInstr *MI,
1534                                             const MachineBasicBlock *MBB,
1535                                             const MachineFunction &MF) const {
1536   // Debug info is never a scheduling boundary. It's necessary to be explicit
1537   // due to the special treatment of IT instructions below, otherwise a
1538   // dbg_value followed by an IT will result in the IT instruction being
1539   // considered a scheduling hazard, which is wrong. It should be the actual
1540   // instruction preceding the dbg_value instruction(s), just like it is
1541   // when debug info is not present.
1542   if (MI->isDebugValue())
1543     return false;
1544
1545   // Terminators and labels can't be scheduled around.
1546   if (MI->isTerminator() || MI->isPosition())
1547     return true;
1548
1549   // Treat the start of the IT block as a scheduling boundary, but schedule
1550   // t2IT along with all instructions following it.
1551   // FIXME: This is a big hammer. But the alternative is to add all potential
1552   // true and anti dependencies to IT block instructions as implicit operands
1553   // to the t2IT instruction. The added compile time and complexity does not
1554   // seem worth it.
1555   MachineBasicBlock::const_iterator I = MI;
1556   // Make sure to skip any dbg_value instructions
1557   while (++I != MBB->end() && I->isDebugValue())
1558     ;
1559   if (I != MBB->end() && I->getOpcode() == ARM::t2IT)
1560     return true;
1561
1562   // Don't attempt to schedule around any instruction that defines
1563   // a stack-oriented pointer, as it's unlikely to be profitable. This
1564   // saves compile time, because it doesn't require every single
1565   // stack slot reference to depend on the instruction that does the
1566   // modification.
1567   // Calls don't actually change the stack pointer, even if they have imp-defs.
1568   // No ARM calling conventions change the stack pointer. (X86 calling
1569   // conventions sometimes do).
1570   if (!MI->isCall() && MI->definesRegister(ARM::SP))
1571     return true;
1572
1573   return false;
1574 }
1575
1576 bool ARMBaseInstrInfo::
1577 isProfitableToIfCvt(MachineBasicBlock &MBB,
1578                     unsigned NumCycles, unsigned ExtraPredCycles,
1579                     const BranchProbability &Probability) const {
1580   if (!NumCycles)
1581     return false;
1582
1583   // Attempt to estimate the relative costs of predication versus branching.
1584   unsigned UnpredCost = Probability.getNumerator() * NumCycles;
1585   UnpredCost /= Probability.getDenominator();
1586   UnpredCost += 1; // The branch itself
1587   UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1588
1589   return (NumCycles + ExtraPredCycles) <= UnpredCost;
1590 }
1591
1592 bool ARMBaseInstrInfo::
1593 isProfitableToIfCvt(MachineBasicBlock &TMBB,
1594                     unsigned TCycles, unsigned TExtra,
1595                     MachineBasicBlock &FMBB,
1596                     unsigned FCycles, unsigned FExtra,
1597                     const BranchProbability &Probability) const {
1598   if (!TCycles || !FCycles)
1599     return false;
1600
1601   // Attempt to estimate the relative costs of predication versus branching.
1602   unsigned TUnpredCost = Probability.getNumerator() * TCycles;
1603   TUnpredCost /= Probability.getDenominator();
1604
1605   uint32_t Comp = Probability.getDenominator() - Probability.getNumerator();
1606   unsigned FUnpredCost = Comp * FCycles;
1607   FUnpredCost /= Probability.getDenominator();
1608
1609   unsigned UnpredCost = TUnpredCost + FUnpredCost;
1610   UnpredCost += 1; // The branch itself
1611   UnpredCost += Subtarget.getMispredictionPenalty() / 10;
1612
1613   return (TCycles + FCycles + TExtra + FExtra) <= UnpredCost;
1614 }
1615
1616 bool
1617 ARMBaseInstrInfo::isProfitableToUnpredicate(MachineBasicBlock &TMBB,
1618                                             MachineBasicBlock &FMBB) const {
1619   // Reduce false anti-dependencies to let Swift's out-of-order execution
1620   // engine do its thing.
1621   return Subtarget.isSwift();
1622 }
1623
1624 /// getInstrPredicate - If instruction is predicated, returns its predicate
1625 /// condition, otherwise returns AL. It also returns the condition code
1626 /// register by reference.
1627 ARMCC::CondCodes
1628 llvm::getInstrPredicate(const MachineInstr *MI, unsigned &PredReg) {
1629   int PIdx = MI->findFirstPredOperandIdx();
1630   if (PIdx == -1) {
1631     PredReg = 0;
1632     return ARMCC::AL;
1633   }
1634
1635   PredReg = MI->getOperand(PIdx+1).getReg();
1636   return (ARMCC::CondCodes)MI->getOperand(PIdx).getImm();
1637 }
1638
1639
1640 int llvm::getMatchingCondBranchOpcode(int Opc) {
1641   if (Opc == ARM::B)
1642     return ARM::Bcc;
1643   if (Opc == ARM::tB)
1644     return ARM::tBcc;
1645   if (Opc == ARM::t2B)
1646     return ARM::t2Bcc;
1647
1648   llvm_unreachable("Unknown unconditional branch opcode!");
1649 }
1650
1651 /// commuteInstruction - Handle commutable instructions.
1652 MachineInstr *
1653 ARMBaseInstrInfo::commuteInstruction(MachineInstr *MI, bool NewMI) const {
1654   switch (MI->getOpcode()) {
1655   case ARM::MOVCCr:
1656   case ARM::t2MOVCCr: {
1657     // MOVCC can be commuted by inverting the condition.
1658     unsigned PredReg = 0;
1659     ARMCC::CondCodes CC = getInstrPredicate(MI, PredReg);
1660     // MOVCC AL can't be inverted. Shouldn't happen.
1661     if (CC == ARMCC::AL || PredReg != ARM::CPSR)
1662       return NULL;
1663     MI = TargetInstrInfo::commuteInstruction(MI, NewMI);
1664     if (!MI)
1665       return NULL;
1666     // After swapping the MOVCC operands, also invert the condition.
1667     MI->getOperand(MI->findFirstPredOperandIdx())
1668       .setImm(ARMCC::getOppositeCondition(CC));
1669     return MI;
1670   }
1671   }
1672   return TargetInstrInfo::commuteInstruction(MI, NewMI);
1673 }
1674
1675 /// Identify instructions that can be folded into a MOVCC instruction, and
1676 /// return the defining instruction.
1677 static MachineInstr *canFoldIntoMOVCC(unsigned Reg,
1678                                       const MachineRegisterInfo &MRI,
1679                                       const TargetInstrInfo *TII) {
1680   if (!TargetRegisterInfo::isVirtualRegister(Reg))
1681     return 0;
1682   if (!MRI.hasOneNonDBGUse(Reg))
1683     return 0;
1684   MachineInstr *MI = MRI.getVRegDef(Reg);
1685   if (!MI)
1686     return 0;
1687   // MI is folded into the MOVCC by predicating it.
1688   if (!MI->isPredicable())
1689     return 0;
1690   // Check if MI has any non-dead defs or physreg uses. This also detects
1691   // predicated instructions which will be reading CPSR.
1692   for (unsigned i = 1, e = MI->getNumOperands(); i != e; ++i) {
1693     const MachineOperand &MO = MI->getOperand(i);
1694     // Reject frame index operands, PEI can't handle the predicated pseudos.
1695     if (MO.isFI() || MO.isCPI() || MO.isJTI())
1696       return 0;
1697     if (!MO.isReg())
1698       continue;
1699     // MI can't have any tied operands, that would conflict with predication.
1700     if (MO.isTied())
1701       return 0;
1702     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
1703       return 0;
1704     if (MO.isDef() && !MO.isDead())
1705       return 0;
1706   }
1707   bool DontMoveAcrossStores = true;
1708   if (!MI->isSafeToMove(TII, /* AliasAnalysis = */ 0, DontMoveAcrossStores))
1709     return 0;
1710   return MI;
1711 }
1712
1713 bool ARMBaseInstrInfo::analyzeSelect(const MachineInstr *MI,
1714                                      SmallVectorImpl<MachineOperand> &Cond,
1715                                      unsigned &TrueOp, unsigned &FalseOp,
1716                                      bool &Optimizable) const {
1717   assert((MI->getOpcode() == ARM::MOVCCr || MI->getOpcode() == ARM::t2MOVCCr) &&
1718          "Unknown select instruction");
1719   // MOVCC operands:
1720   // 0: Def.
1721   // 1: True use.
1722   // 2: False use.
1723   // 3: Condition code.
1724   // 4: CPSR use.
1725   TrueOp = 1;
1726   FalseOp = 2;
1727   Cond.push_back(MI->getOperand(3));
1728   Cond.push_back(MI->getOperand(4));
1729   // We can always fold a def.
1730   Optimizable = true;
1731   return false;
1732 }
1733
1734 MachineInstr *ARMBaseInstrInfo::optimizeSelect(MachineInstr *MI,
1735                                                bool PreferFalse) const {
1736   assert((MI->getOpcode() == ARM::MOVCCr || MI->getOpcode() == ARM::t2MOVCCr) &&
1737          "Unknown select instruction");
1738   MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo();
1739   MachineInstr *DefMI = canFoldIntoMOVCC(MI->getOperand(2).getReg(), MRI, this);
1740   bool Invert = !DefMI;
1741   if (!DefMI)
1742     DefMI = canFoldIntoMOVCC(MI->getOperand(1).getReg(), MRI, this);
1743   if (!DefMI)
1744     return 0;
1745
1746   // Find new register class to use.
1747   MachineOperand FalseReg = MI->getOperand(Invert ? 2 : 1);
1748   unsigned       DestReg  = MI->getOperand(0).getReg();
1749   const TargetRegisterClass *PreviousClass = MRI.getRegClass(FalseReg.getReg());
1750   if (!MRI.constrainRegClass(DestReg, PreviousClass))
1751     return 0;
1752
1753   // Create a new predicated version of DefMI.
1754   // Rfalse is the first use.
1755   MachineInstrBuilder NewMI = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
1756                                       DefMI->getDesc(), DestReg);
1757
1758   // Copy all the DefMI operands, excluding its (null) predicate.
1759   const MCInstrDesc &DefDesc = DefMI->getDesc();
1760   for (unsigned i = 1, e = DefDesc.getNumOperands();
1761        i != e && !DefDesc.OpInfo[i].isPredicate(); ++i)
1762     NewMI.addOperand(DefMI->getOperand(i));
1763
1764   unsigned CondCode = MI->getOperand(3).getImm();
1765   if (Invert)
1766     NewMI.addImm(ARMCC::getOppositeCondition(ARMCC::CondCodes(CondCode)));
1767   else
1768     NewMI.addImm(CondCode);
1769   NewMI.addOperand(MI->getOperand(4));
1770
1771   // DefMI is not the -S version that sets CPSR, so add an optional %noreg.
1772   if (NewMI->hasOptionalDef())
1773     AddDefaultCC(NewMI);
1774
1775   // The output register value when the predicate is false is an implicit
1776   // register operand tied to the first def.
1777   // The tie makes the register allocator ensure the FalseReg is allocated the
1778   // same register as operand 0.
1779   FalseReg.setImplicit();
1780   NewMI.addOperand(FalseReg);
1781   NewMI->tieOperands(0, NewMI->getNumOperands() - 1);
1782
1783   // The caller will erase MI, but not DefMI.
1784   DefMI->eraseFromParent();
1785   return NewMI;
1786 }
1787
1788 /// Map pseudo instructions that imply an 'S' bit onto real opcodes. Whether the
1789 /// instruction is encoded with an 'S' bit is determined by the optional CPSR
1790 /// def operand.
1791 ///
1792 /// This will go away once we can teach tblgen how to set the optional CPSR def
1793 /// operand itself.
1794 struct AddSubFlagsOpcodePair {
1795   uint16_t PseudoOpc;
1796   uint16_t MachineOpc;
1797 };
1798
1799 static const AddSubFlagsOpcodePair AddSubFlagsOpcodeMap[] = {
1800   {ARM::ADDSri, ARM::ADDri},
1801   {ARM::ADDSrr, ARM::ADDrr},
1802   {ARM::ADDSrsi, ARM::ADDrsi},
1803   {ARM::ADDSrsr, ARM::ADDrsr},
1804
1805   {ARM::SUBSri, ARM::SUBri},
1806   {ARM::SUBSrr, ARM::SUBrr},
1807   {ARM::SUBSrsi, ARM::SUBrsi},
1808   {ARM::SUBSrsr, ARM::SUBrsr},
1809
1810   {ARM::RSBSri, ARM::RSBri},
1811   {ARM::RSBSrsi, ARM::RSBrsi},
1812   {ARM::RSBSrsr, ARM::RSBrsr},
1813
1814   {ARM::t2ADDSri, ARM::t2ADDri},
1815   {ARM::t2ADDSrr, ARM::t2ADDrr},
1816   {ARM::t2ADDSrs, ARM::t2ADDrs},
1817
1818   {ARM::t2SUBSri, ARM::t2SUBri},
1819   {ARM::t2SUBSrr, ARM::t2SUBrr},
1820   {ARM::t2SUBSrs, ARM::t2SUBrs},
1821
1822   {ARM::t2RSBSri, ARM::t2RSBri},
1823   {ARM::t2RSBSrs, ARM::t2RSBrs},
1824 };
1825
1826 unsigned llvm::convertAddSubFlagsOpcode(unsigned OldOpc) {
1827   for (unsigned i = 0, e = array_lengthof(AddSubFlagsOpcodeMap); i != e; ++i)
1828     if (OldOpc == AddSubFlagsOpcodeMap[i].PseudoOpc)
1829       return AddSubFlagsOpcodeMap[i].MachineOpc;
1830   return 0;
1831 }
1832
1833 void llvm::emitARMRegPlusImmediate(MachineBasicBlock &MBB,
1834                                MachineBasicBlock::iterator &MBBI, DebugLoc dl,
1835                                unsigned DestReg, unsigned BaseReg, int NumBytes,
1836                                ARMCC::CondCodes Pred, unsigned PredReg,
1837                                const ARMBaseInstrInfo &TII, unsigned MIFlags) {
1838   if (NumBytes == 0 && DestReg != BaseReg) {
1839     BuildMI(MBB, MBBI, dl, TII.get(ARM::MOVr), DestReg)
1840       .addReg(BaseReg, RegState::Kill)
1841       .addImm((unsigned)Pred).addReg(PredReg).addReg(0)
1842       .setMIFlags(MIFlags);
1843     return;
1844   }
1845
1846   bool isSub = NumBytes < 0;
1847   if (isSub) NumBytes = -NumBytes;
1848
1849   while (NumBytes) {
1850     unsigned RotAmt = ARM_AM::getSOImmValRotate(NumBytes);
1851     unsigned ThisVal = NumBytes & ARM_AM::rotr32(0xFF, RotAmt);
1852     assert(ThisVal && "Didn't extract field correctly");
1853
1854     // We will handle these bits from offset, clear them.
1855     NumBytes &= ~ThisVal;
1856
1857     assert(ARM_AM::getSOImmVal(ThisVal) != -1 && "Bit extraction didn't work?");
1858
1859     // Build the new ADD / SUB.
1860     unsigned Opc = isSub ? ARM::SUBri : ARM::ADDri;
1861     BuildMI(MBB, MBBI, dl, TII.get(Opc), DestReg)
1862       .addReg(BaseReg, RegState::Kill).addImm(ThisVal)
1863       .addImm((unsigned)Pred).addReg(PredReg).addReg(0)
1864       .setMIFlags(MIFlags);
1865     BaseReg = DestReg;
1866   }
1867 }
1868
1869 bool llvm::tryFoldSPUpdateIntoPushPop(const ARMSubtarget &Subtarget,
1870                                       MachineFunction &MF, MachineInstr *MI,
1871                                       unsigned NumBytes) {
1872   // This optimisation potentially adds lots of load and store
1873   // micro-operations, it's only really a great benefit to code-size.
1874   if (!Subtarget.isMinSize())
1875     return false;
1876
1877   // If only one register is pushed/popped, LLVM can use an LDR/STR
1878   // instead. We can't modify those so make sure we're dealing with an
1879   // instruction we understand.
1880   bool IsPop = isPopOpcode(MI->getOpcode());
1881   bool IsPush = isPushOpcode(MI->getOpcode());
1882   if (!IsPush && !IsPop)
1883     return false;
1884
1885   bool IsVFPPushPop = MI->getOpcode() == ARM::VSTMDDB_UPD ||
1886                       MI->getOpcode() == ARM::VLDMDIA_UPD;
1887   bool IsT1PushPop = MI->getOpcode() == ARM::tPUSH ||
1888                      MI->getOpcode() == ARM::tPOP ||
1889                      MI->getOpcode() == ARM::tPOP_RET;
1890
1891   assert((IsT1PushPop || (MI->getOperand(0).getReg() == ARM::SP &&
1892                           MI->getOperand(1).getReg() == ARM::SP)) &&
1893          "trying to fold sp update into non-sp-updating push/pop");
1894
1895   // The VFP push & pop act on D-registers, so we can only fold an adjustment
1896   // by a multiple of 8 bytes in correctly. Similarly rN is 4-bytes. Don't try
1897   // if this is violated.
1898   if (NumBytes % (IsVFPPushPop ? 8 : 4) != 0)
1899     return false;
1900
1901   // ARM and Thumb2 push/pop insts have explicit "sp, sp" operands (+
1902   // pred) so the list starts at 4. Thumb1 starts after the predicate.
1903   int RegListIdx = IsT1PushPop ? 2 : 4;
1904
1905   // Calculate the space we'll need in terms of registers.
1906   unsigned FirstReg = MI->getOperand(RegListIdx).getReg();
1907   unsigned RD0Reg, RegsNeeded;
1908   if (IsVFPPushPop) {
1909     RD0Reg = ARM::D0;
1910     RegsNeeded = NumBytes / 8;
1911   } else {
1912     RD0Reg = ARM::R0;
1913     RegsNeeded = NumBytes / 4;
1914   }
1915
1916   // We're going to have to strip all list operands off before
1917   // re-adding them since the order matters, so save the existing ones
1918   // for later.
1919   SmallVector<MachineOperand, 4> RegList;
1920   for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i)
1921     RegList.push_back(MI->getOperand(i));
1922
1923   MachineBasicBlock *MBB = MI->getParent();
1924   const TargetRegisterInfo *TRI = MF.getRegInfo().getTargetRegisterInfo();
1925   const MCPhysReg *CSRegs = TRI->getCalleeSavedRegs(&MF);
1926
1927   // Now try to find enough space in the reglist to allocate NumBytes.
1928   for (unsigned CurReg = FirstReg - 1; CurReg >= RD0Reg && RegsNeeded;
1929        --CurReg) {
1930     if (!IsPop) {
1931       // Pushing any register is completely harmless, mark the
1932       // register involved as undef since we don't care about it in
1933       // the slightest.
1934       RegList.push_back(MachineOperand::CreateReg(CurReg, false, false,
1935                                                   false, false, true));
1936       --RegsNeeded;
1937       continue;
1938     }
1939
1940     // However, we can only pop an extra register if it's not live. For
1941     // registers live within the function we might clobber a return value
1942     // register; the other way a register can be live here is if it's
1943     // callee-saved.
1944     if (isCalleeSavedRegister(CurReg, CSRegs) ||
1945         MBB->computeRegisterLiveness(TRI, CurReg, MI) !=
1946             MachineBasicBlock::LQR_Dead) {
1947       // VFP pops don't allow holes in the register list, so any skip is fatal
1948       // for our transformation. GPR pops do, so we should just keep looking.
1949       if (IsVFPPushPop)
1950         return false;
1951       else
1952         continue;
1953     }
1954
1955     // Mark the unimportant registers as <def,dead> in the POP.
1956     RegList.push_back(MachineOperand::CreateReg(CurReg, true, false, false,
1957                                                 true));
1958     --RegsNeeded;
1959   }
1960
1961   if (RegsNeeded > 0)
1962     return false;
1963
1964   // Finally we know we can profitably perform the optimisation so go
1965   // ahead: strip all existing registers off and add them back again
1966   // in the right order.
1967   for (int i = MI->getNumOperands() - 1; i >= RegListIdx; --i)
1968     MI->RemoveOperand(i);
1969
1970   // Add the complete list back in.
1971   MachineInstrBuilder MIB(MF, &*MI);
1972   for (int i = RegList.size() - 1; i >= 0; --i)
1973     MIB.addOperand(RegList[i]);
1974
1975   return true;
1976 }
1977
1978 bool llvm::rewriteARMFrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
1979                                 unsigned FrameReg, int &Offset,
1980                                 const ARMBaseInstrInfo &TII) {
1981   unsigned Opcode = MI.getOpcode();
1982   const MCInstrDesc &Desc = MI.getDesc();
1983   unsigned AddrMode = (Desc.TSFlags & ARMII::AddrModeMask);
1984   bool isSub = false;
1985
1986   // Memory operands in inline assembly always use AddrMode2.
1987   if (Opcode == ARM::INLINEASM)
1988     AddrMode = ARMII::AddrMode2;
1989
1990   if (Opcode == ARM::ADDri) {
1991     Offset += MI.getOperand(FrameRegIdx+1).getImm();
1992     if (Offset == 0) {
1993       // Turn it into a move.
1994       MI.setDesc(TII.get(ARM::MOVr));
1995       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
1996       MI.RemoveOperand(FrameRegIdx+1);
1997       Offset = 0;
1998       return true;
1999     } else if (Offset < 0) {
2000       Offset = -Offset;
2001       isSub = true;
2002       MI.setDesc(TII.get(ARM::SUBri));
2003     }
2004
2005     // Common case: small offset, fits into instruction.
2006     if (ARM_AM::getSOImmVal(Offset) != -1) {
2007       // Replace the FrameIndex with sp / fp
2008       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2009       MI.getOperand(FrameRegIdx+1).ChangeToImmediate(Offset);
2010       Offset = 0;
2011       return true;
2012     }
2013
2014     // Otherwise, pull as much of the immedidate into this ADDri/SUBri
2015     // as possible.
2016     unsigned RotAmt = ARM_AM::getSOImmValRotate(Offset);
2017     unsigned ThisImmVal = Offset & ARM_AM::rotr32(0xFF, RotAmt);
2018
2019     // We will handle these bits from offset, clear them.
2020     Offset &= ~ThisImmVal;
2021
2022     // Get the properly encoded SOImmVal field.
2023     assert(ARM_AM::getSOImmVal(ThisImmVal) != -1 &&
2024            "Bit extraction didn't work?");
2025     MI.getOperand(FrameRegIdx+1).ChangeToImmediate(ThisImmVal);
2026  } else {
2027     unsigned ImmIdx = 0;
2028     int InstrOffs = 0;
2029     unsigned NumBits = 0;
2030     unsigned Scale = 1;
2031     switch (AddrMode) {
2032     case ARMII::AddrMode_i12: {
2033       ImmIdx = FrameRegIdx + 1;
2034       InstrOffs = MI.getOperand(ImmIdx).getImm();
2035       NumBits = 12;
2036       break;
2037     }
2038     case ARMII::AddrMode2: {
2039       ImmIdx = FrameRegIdx+2;
2040       InstrOffs = ARM_AM::getAM2Offset(MI.getOperand(ImmIdx).getImm());
2041       if (ARM_AM::getAM2Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2042         InstrOffs *= -1;
2043       NumBits = 12;
2044       break;
2045     }
2046     case ARMII::AddrMode3: {
2047       ImmIdx = FrameRegIdx+2;
2048       InstrOffs = ARM_AM::getAM3Offset(MI.getOperand(ImmIdx).getImm());
2049       if (ARM_AM::getAM3Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2050         InstrOffs *= -1;
2051       NumBits = 8;
2052       break;
2053     }
2054     case ARMII::AddrMode4:
2055     case ARMII::AddrMode6:
2056       // Can't fold any offset even if it's zero.
2057       return false;
2058     case ARMII::AddrMode5: {
2059       ImmIdx = FrameRegIdx+1;
2060       InstrOffs = ARM_AM::getAM5Offset(MI.getOperand(ImmIdx).getImm());
2061       if (ARM_AM::getAM5Op(MI.getOperand(ImmIdx).getImm()) == ARM_AM::sub)
2062         InstrOffs *= -1;
2063       NumBits = 8;
2064       Scale = 4;
2065       break;
2066     }
2067     default:
2068       llvm_unreachable("Unsupported addressing mode!");
2069     }
2070
2071     Offset += InstrOffs * Scale;
2072     assert((Offset & (Scale-1)) == 0 && "Can't encode this offset!");
2073     if (Offset < 0) {
2074       Offset = -Offset;
2075       isSub = true;
2076     }
2077
2078     // Attempt to fold address comp. if opcode has offset bits
2079     if (NumBits > 0) {
2080       // Common case: small offset, fits into instruction.
2081       MachineOperand &ImmOp = MI.getOperand(ImmIdx);
2082       int ImmedOffset = Offset / Scale;
2083       unsigned Mask = (1 << NumBits) - 1;
2084       if ((unsigned)Offset <= Mask * Scale) {
2085         // Replace the FrameIndex with sp
2086         MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
2087         // FIXME: When addrmode2 goes away, this will simplify (like the
2088         // T2 version), as the LDR.i12 versions don't need the encoding
2089         // tricks for the offset value.
2090         if (isSub) {
2091           if (AddrMode == ARMII::AddrMode_i12)
2092             ImmedOffset = -ImmedOffset;
2093           else
2094             ImmedOffset |= 1 << NumBits;
2095         }
2096         ImmOp.ChangeToImmediate(ImmedOffset);
2097         Offset = 0;
2098         return true;
2099       }
2100
2101       // Otherwise, it didn't fit. Pull in what we can to simplify the immed.
2102       ImmedOffset = ImmedOffset & Mask;
2103       if (isSub) {
2104         if (AddrMode == ARMII::AddrMode_i12)
2105           ImmedOffset = -ImmedOffset;
2106         else
2107           ImmedOffset |= 1 << NumBits;
2108       }
2109       ImmOp.ChangeToImmediate(ImmedOffset);
2110       Offset &= ~(Mask*Scale);
2111     }
2112   }
2113
2114   Offset = (isSub) ? -Offset : Offset;
2115   return Offset == 0;
2116 }
2117
2118 /// analyzeCompare - For a comparison instruction, return the source registers
2119 /// in SrcReg and SrcReg2 if having two register operands, and the value it
2120 /// compares against in CmpValue. Return true if the comparison instruction
2121 /// can be analyzed.
2122 bool ARMBaseInstrInfo::
2123 analyzeCompare(const MachineInstr *MI, unsigned &SrcReg, unsigned &SrcReg2,
2124                int &CmpMask, int &CmpValue) const {
2125   switch (MI->getOpcode()) {
2126   default: break;
2127   case ARM::CMPri:
2128   case ARM::t2CMPri:
2129     SrcReg = MI->getOperand(0).getReg();
2130     SrcReg2 = 0;
2131     CmpMask = ~0;
2132     CmpValue = MI->getOperand(1).getImm();
2133     return true;
2134   case ARM::CMPrr:
2135   case ARM::t2CMPrr:
2136     SrcReg = MI->getOperand(0).getReg();
2137     SrcReg2 = MI->getOperand(1).getReg();
2138     CmpMask = ~0;
2139     CmpValue = 0;
2140     return true;
2141   case ARM::TSTri:
2142   case ARM::t2TSTri:
2143     SrcReg = MI->getOperand(0).getReg();
2144     SrcReg2 = 0;
2145     CmpMask = MI->getOperand(1).getImm();
2146     CmpValue = 0;
2147     return true;
2148   }
2149
2150   return false;
2151 }
2152
2153 /// isSuitableForMask - Identify a suitable 'and' instruction that
2154 /// operates on the given source register and applies the same mask
2155 /// as a 'tst' instruction. Provide a limited look-through for copies.
2156 /// When successful, MI will hold the found instruction.
2157 static bool isSuitableForMask(MachineInstr *&MI, unsigned SrcReg,
2158                               int CmpMask, bool CommonUse) {
2159   switch (MI->getOpcode()) {
2160     case ARM::ANDri:
2161     case ARM::t2ANDri:
2162       if (CmpMask != MI->getOperand(2).getImm())
2163         return false;
2164       if (SrcReg == MI->getOperand(CommonUse ? 1 : 0).getReg())
2165         return true;
2166       break;
2167     case ARM::COPY: {
2168       // Walk down one instruction which is potentially an 'and'.
2169       const MachineInstr &Copy = *MI;
2170       MachineBasicBlock::iterator AND(
2171         std::next(MachineBasicBlock::iterator(MI)));
2172       if (AND == MI->getParent()->end()) return false;
2173       MI = AND;
2174       return isSuitableForMask(MI, Copy.getOperand(0).getReg(),
2175                                CmpMask, true);
2176     }
2177   }
2178
2179   return false;
2180 }
2181
2182 /// getSwappedCondition - assume the flags are set by MI(a,b), return
2183 /// the condition code if we modify the instructions such that flags are
2184 /// set by MI(b,a).
2185 inline static ARMCC::CondCodes getSwappedCondition(ARMCC::CondCodes CC) {
2186   switch (CC) {
2187   default: return ARMCC::AL;
2188   case ARMCC::EQ: return ARMCC::EQ;
2189   case ARMCC::NE: return ARMCC::NE;
2190   case ARMCC::HS: return ARMCC::LS;
2191   case ARMCC::LO: return ARMCC::HI;
2192   case ARMCC::HI: return ARMCC::LO;
2193   case ARMCC::LS: return ARMCC::HS;
2194   case ARMCC::GE: return ARMCC::LE;
2195   case ARMCC::LT: return ARMCC::GT;
2196   case ARMCC::GT: return ARMCC::LT;
2197   case ARMCC::LE: return ARMCC::GE;
2198   }
2199 }
2200
2201 /// isRedundantFlagInstr - check whether the first instruction, whose only
2202 /// purpose is to update flags, can be made redundant.
2203 /// CMPrr can be made redundant by SUBrr if the operands are the same.
2204 /// CMPri can be made redundant by SUBri if the operands are the same.
2205 /// This function can be extended later on.
2206 inline static bool isRedundantFlagInstr(MachineInstr *CmpI, unsigned SrcReg,
2207                                         unsigned SrcReg2, int ImmValue,
2208                                         MachineInstr *OI) {
2209   if ((CmpI->getOpcode() == ARM::CMPrr ||
2210        CmpI->getOpcode() == ARM::t2CMPrr) &&
2211       (OI->getOpcode() == ARM::SUBrr ||
2212        OI->getOpcode() == ARM::t2SUBrr) &&
2213       ((OI->getOperand(1).getReg() == SrcReg &&
2214         OI->getOperand(2).getReg() == SrcReg2) ||
2215        (OI->getOperand(1).getReg() == SrcReg2 &&
2216         OI->getOperand(2).getReg() == SrcReg)))
2217     return true;
2218
2219   if ((CmpI->getOpcode() == ARM::CMPri ||
2220        CmpI->getOpcode() == ARM::t2CMPri) &&
2221       (OI->getOpcode() == ARM::SUBri ||
2222        OI->getOpcode() == ARM::t2SUBri) &&
2223       OI->getOperand(1).getReg() == SrcReg &&
2224       OI->getOperand(2).getImm() == ImmValue)
2225     return true;
2226   return false;
2227 }
2228
2229 /// optimizeCompareInstr - Convert the instruction supplying the argument to the
2230 /// comparison into one that sets the zero bit in the flags register;
2231 /// Remove a redundant Compare instruction if an earlier instruction can set the
2232 /// flags in the same way as Compare.
2233 /// E.g. SUBrr(r1,r2) and CMPrr(r1,r2). We also handle the case where two
2234 /// operands are swapped: SUBrr(r1,r2) and CMPrr(r2,r1), by updating the
2235 /// condition code of instructions which use the flags.
2236 bool ARMBaseInstrInfo::
2237 optimizeCompareInstr(MachineInstr *CmpInstr, unsigned SrcReg, unsigned SrcReg2,
2238                      int CmpMask, int CmpValue,
2239                      const MachineRegisterInfo *MRI) const {
2240   // Get the unique definition of SrcReg.
2241   MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg);
2242   if (!MI) return false;
2243
2244   // Masked compares sometimes use the same register as the corresponding 'and'.
2245   if (CmpMask != ~0) {
2246     if (!isSuitableForMask(MI, SrcReg, CmpMask, false) || isPredicated(MI)) {
2247       MI = 0;
2248       for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(SrcReg),
2249            UE = MRI->use_end(); UI != UE; ++UI) {
2250         if (UI->getParent() != CmpInstr->getParent()) continue;
2251         MachineInstr *PotentialAND = &*UI;
2252         if (!isSuitableForMask(PotentialAND, SrcReg, CmpMask, true) ||
2253             isPredicated(PotentialAND))
2254           continue;
2255         MI = PotentialAND;
2256         break;
2257       }
2258       if (!MI) return false;
2259     }
2260   }
2261
2262   // Get ready to iterate backward from CmpInstr.
2263   MachineBasicBlock::iterator I = CmpInstr, E = MI,
2264                               B = CmpInstr->getParent()->begin();
2265
2266   // Early exit if CmpInstr is at the beginning of the BB.
2267   if (I == B) return false;
2268
2269   // There are two possible candidates which can be changed to set CPSR:
2270   // One is MI, the other is a SUB instruction.
2271   // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1).
2272   // For CMPri(r1, CmpValue), we are looking for SUBri(r1, CmpValue).
2273   MachineInstr *Sub = NULL;
2274   if (SrcReg2 != 0)
2275     // MI is not a candidate for CMPrr.
2276     MI = NULL;
2277   else if (MI->getParent() != CmpInstr->getParent() || CmpValue != 0) {
2278     // Conservatively refuse to convert an instruction which isn't in the same
2279     // BB as the comparison.
2280     // For CMPri, we need to check Sub, thus we can't return here.
2281     if (CmpInstr->getOpcode() == ARM::CMPri ||
2282        CmpInstr->getOpcode() == ARM::t2CMPri)
2283       MI = NULL;
2284     else
2285       return false;
2286   }
2287
2288   // Check that CPSR isn't set between the comparison instruction and the one we
2289   // want to change. At the same time, search for Sub.
2290   const TargetRegisterInfo *TRI = &getRegisterInfo();
2291   --I;
2292   for (; I != E; --I) {
2293     const MachineInstr &Instr = *I;
2294
2295     if (Instr.modifiesRegister(ARM::CPSR, TRI) ||
2296         Instr.readsRegister(ARM::CPSR, TRI))
2297       // This instruction modifies or uses CPSR after the one we want to
2298       // change. We can't do this transformation.
2299       return false;
2300
2301     // Check whether CmpInstr can be made redundant by the current instruction.
2302     if (isRedundantFlagInstr(CmpInstr, SrcReg, SrcReg2, CmpValue, &*I)) {
2303       Sub = &*I;
2304       break;
2305     }
2306
2307     if (I == B)
2308       // The 'and' is below the comparison instruction.
2309       return false;
2310   }
2311
2312   // Return false if no candidates exist.
2313   if (!MI && !Sub)
2314     return false;
2315
2316   // The single candidate is called MI.
2317   if (!MI) MI = Sub;
2318
2319   // We can't use a predicated instruction - it doesn't always write the flags.
2320   if (isPredicated(MI))
2321     return false;
2322
2323   switch (MI->getOpcode()) {
2324   default: break;
2325   case ARM::RSBrr:
2326   case ARM::RSBri:
2327   case ARM::RSCrr:
2328   case ARM::RSCri:
2329   case ARM::ADDrr:
2330   case ARM::ADDri:
2331   case ARM::ADCrr:
2332   case ARM::ADCri:
2333   case ARM::SUBrr:
2334   case ARM::SUBri:
2335   case ARM::SBCrr:
2336   case ARM::SBCri:
2337   case ARM::t2RSBri:
2338   case ARM::t2ADDrr:
2339   case ARM::t2ADDri:
2340   case ARM::t2ADCrr:
2341   case ARM::t2ADCri:
2342   case ARM::t2SUBrr:
2343   case ARM::t2SUBri:
2344   case ARM::t2SBCrr:
2345   case ARM::t2SBCri:
2346   case ARM::ANDrr:
2347   case ARM::ANDri:
2348   case ARM::t2ANDrr:
2349   case ARM::t2ANDri:
2350   case ARM::ORRrr:
2351   case ARM::ORRri:
2352   case ARM::t2ORRrr:
2353   case ARM::t2ORRri:
2354   case ARM::EORrr:
2355   case ARM::EORri:
2356   case ARM::t2EORrr:
2357   case ARM::t2EORri: {
2358     // Scan forward for the use of CPSR
2359     // When checking against MI: if it's a conditional code requires
2360     // checking of V bit, then this is not safe to do.
2361     // It is safe to remove CmpInstr if CPSR is redefined or killed.
2362     // If we are done with the basic block, we need to check whether CPSR is
2363     // live-out.
2364     SmallVector<std::pair<MachineOperand*, ARMCC::CondCodes>, 4>
2365         OperandsToUpdate;
2366     bool isSafe = false;
2367     I = CmpInstr;
2368     E = CmpInstr->getParent()->end();
2369     while (!isSafe && ++I != E) {
2370       const MachineInstr &Instr = *I;
2371       for (unsigned IO = 0, EO = Instr.getNumOperands();
2372            !isSafe && IO != EO; ++IO) {
2373         const MachineOperand &MO = Instr.getOperand(IO);
2374         if (MO.isRegMask() && MO.clobbersPhysReg(ARM::CPSR)) {
2375           isSafe = true;
2376           break;
2377         }
2378         if (!MO.isReg() || MO.getReg() != ARM::CPSR)
2379           continue;
2380         if (MO.isDef()) {
2381           isSafe = true;
2382           break;
2383         }
2384         // Condition code is after the operand before CPSR except for VSELs.
2385         ARMCC::CondCodes CC;
2386         bool IsInstrVSel = true;
2387         switch (Instr.getOpcode()) {
2388         default:
2389           IsInstrVSel = false;
2390           CC = (ARMCC::CondCodes)Instr.getOperand(IO - 1).getImm();
2391           break;
2392         case ARM::VSELEQD:
2393         case ARM::VSELEQS:
2394           CC = ARMCC::EQ;
2395           break;
2396         case ARM::VSELGTD:
2397         case ARM::VSELGTS:
2398           CC = ARMCC::GT;
2399           break;
2400         case ARM::VSELGED:
2401         case ARM::VSELGES:
2402           CC = ARMCC::GE;
2403           break;
2404         case ARM::VSELVSS:
2405         case ARM::VSELVSD:
2406           CC = ARMCC::VS;
2407           break;
2408         }
2409
2410         if (Sub) {
2411           ARMCC::CondCodes NewCC = getSwappedCondition(CC);
2412           if (NewCC == ARMCC::AL)
2413             return false;
2414           // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based
2415           // on CMP needs to be updated to be based on SUB.
2416           // Push the condition code operands to OperandsToUpdate.
2417           // If it is safe to remove CmpInstr, the condition code of these
2418           // operands will be modified.
2419           if (SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 &&
2420               Sub->getOperand(2).getReg() == SrcReg) {
2421             // VSel doesn't support condition code update.
2422             if (IsInstrVSel)
2423               return false;
2424             OperandsToUpdate.push_back(
2425                 std::make_pair(&((*I).getOperand(IO - 1)), NewCC));
2426           }
2427         } else
2428           switch (CC) {
2429           default:
2430             // CPSR can be used multiple times, we should continue.
2431             break;
2432           case ARMCC::VS:
2433           case ARMCC::VC:
2434           case ARMCC::GE:
2435           case ARMCC::LT:
2436           case ARMCC::GT:
2437           case ARMCC::LE:
2438             return false;
2439           }
2440       }
2441     }
2442
2443     // If CPSR is not killed nor re-defined, we should check whether it is
2444     // live-out. If it is live-out, do not optimize.
2445     if (!isSafe) {
2446       MachineBasicBlock *MBB = CmpInstr->getParent();
2447       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
2448                SE = MBB->succ_end(); SI != SE; ++SI)
2449         if ((*SI)->isLiveIn(ARM::CPSR))
2450           return false;
2451     }
2452
2453     // Toggle the optional operand to CPSR.
2454     MI->getOperand(5).setReg(ARM::CPSR);
2455     MI->getOperand(5).setIsDef(true);
2456     assert(!isPredicated(MI) && "Can't use flags from predicated instruction");
2457     CmpInstr->eraseFromParent();
2458
2459     // Modify the condition code of operands in OperandsToUpdate.
2460     // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to
2461     // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc.
2462     for (unsigned i = 0, e = OperandsToUpdate.size(); i < e; i++)
2463       OperandsToUpdate[i].first->setImm(OperandsToUpdate[i].second);
2464     return true;
2465   }
2466   }
2467
2468   return false;
2469 }
2470
2471 bool ARMBaseInstrInfo::FoldImmediate(MachineInstr *UseMI,
2472                                      MachineInstr *DefMI, unsigned Reg,
2473                                      MachineRegisterInfo *MRI) const {
2474   // Fold large immediates into add, sub, or, xor.
2475   unsigned DefOpc = DefMI->getOpcode();
2476   if (DefOpc != ARM::t2MOVi32imm && DefOpc != ARM::MOVi32imm)
2477     return false;
2478   if (!DefMI->getOperand(1).isImm())
2479     // Could be t2MOVi32imm <ga:xx>
2480     return false;
2481
2482   if (!MRI->hasOneNonDBGUse(Reg))
2483     return false;
2484
2485   const MCInstrDesc &DefMCID = DefMI->getDesc();
2486   if (DefMCID.hasOptionalDef()) {
2487     unsigned NumOps = DefMCID.getNumOperands();
2488     const MachineOperand &MO = DefMI->getOperand(NumOps-1);
2489     if (MO.getReg() == ARM::CPSR && !MO.isDead())
2490       // If DefMI defines CPSR and it is not dead, it's obviously not safe
2491       // to delete DefMI.
2492       return false;
2493   }
2494
2495   const MCInstrDesc &UseMCID = UseMI->getDesc();
2496   if (UseMCID.hasOptionalDef()) {
2497     unsigned NumOps = UseMCID.getNumOperands();
2498     if (UseMI->getOperand(NumOps-1).getReg() == ARM::CPSR)
2499       // If the instruction sets the flag, do not attempt this optimization
2500       // since it may change the semantics of the code.
2501       return false;
2502   }
2503
2504   unsigned UseOpc = UseMI->getOpcode();
2505   unsigned NewUseOpc = 0;
2506   uint32_t ImmVal = (uint32_t)DefMI->getOperand(1).getImm();
2507   uint32_t SOImmValV1 = 0, SOImmValV2 = 0;
2508   bool Commute = false;
2509   switch (UseOpc) {
2510   default: return false;
2511   case ARM::SUBrr:
2512   case ARM::ADDrr:
2513   case ARM::ORRrr:
2514   case ARM::EORrr:
2515   case ARM::t2SUBrr:
2516   case ARM::t2ADDrr:
2517   case ARM::t2ORRrr:
2518   case ARM::t2EORrr: {
2519     Commute = UseMI->getOperand(2).getReg() != Reg;
2520     switch (UseOpc) {
2521     default: break;
2522     case ARM::SUBrr: {
2523       if (Commute)
2524         return false;
2525       ImmVal = -ImmVal;
2526       NewUseOpc = ARM::SUBri;
2527       // Fallthrough
2528     }
2529     case ARM::ADDrr:
2530     case ARM::ORRrr:
2531     case ARM::EORrr: {
2532       if (!ARM_AM::isSOImmTwoPartVal(ImmVal))
2533         return false;
2534       SOImmValV1 = (uint32_t)ARM_AM::getSOImmTwoPartFirst(ImmVal);
2535       SOImmValV2 = (uint32_t)ARM_AM::getSOImmTwoPartSecond(ImmVal);
2536       switch (UseOpc) {
2537       default: break;
2538       case ARM::ADDrr: NewUseOpc = ARM::ADDri; break;
2539       case ARM::ORRrr: NewUseOpc = ARM::ORRri; break;
2540       case ARM::EORrr: NewUseOpc = ARM::EORri; break;
2541       }
2542       break;
2543     }
2544     case ARM::t2SUBrr: {
2545       if (Commute)
2546         return false;
2547       ImmVal = -ImmVal;
2548       NewUseOpc = ARM::t2SUBri;
2549       // Fallthrough
2550     }
2551     case ARM::t2ADDrr:
2552     case ARM::t2ORRrr:
2553     case ARM::t2EORrr: {
2554       if (!ARM_AM::isT2SOImmTwoPartVal(ImmVal))
2555         return false;
2556       SOImmValV1 = (uint32_t)ARM_AM::getT2SOImmTwoPartFirst(ImmVal);
2557       SOImmValV2 = (uint32_t)ARM_AM::getT2SOImmTwoPartSecond(ImmVal);
2558       switch (UseOpc) {
2559       default: break;
2560       case ARM::t2ADDrr: NewUseOpc = ARM::t2ADDri; break;
2561       case ARM::t2ORRrr: NewUseOpc = ARM::t2ORRri; break;
2562       case ARM::t2EORrr: NewUseOpc = ARM::t2EORri; break;
2563       }
2564       break;
2565     }
2566     }
2567   }
2568   }
2569
2570   unsigned OpIdx = Commute ? 2 : 1;
2571   unsigned Reg1 = UseMI->getOperand(OpIdx).getReg();
2572   bool isKill = UseMI->getOperand(OpIdx).isKill();
2573   unsigned NewReg = MRI->createVirtualRegister(MRI->getRegClass(Reg));
2574   AddDefaultCC(AddDefaultPred(BuildMI(*UseMI->getParent(),
2575                                       UseMI, UseMI->getDebugLoc(),
2576                                       get(NewUseOpc), NewReg)
2577                               .addReg(Reg1, getKillRegState(isKill))
2578                               .addImm(SOImmValV1)));
2579   UseMI->setDesc(get(NewUseOpc));
2580   UseMI->getOperand(1).setReg(NewReg);
2581   UseMI->getOperand(1).setIsKill();
2582   UseMI->getOperand(2).ChangeToImmediate(SOImmValV2);
2583   DefMI->eraseFromParent();
2584   return true;
2585 }
2586
2587 static unsigned getNumMicroOpsSwiftLdSt(const InstrItineraryData *ItinData,
2588                                         const MachineInstr *MI) {
2589   switch (MI->getOpcode()) {
2590   default: {
2591     const MCInstrDesc &Desc = MI->getDesc();
2592     int UOps = ItinData->getNumMicroOps(Desc.getSchedClass());
2593     assert(UOps >= 0 && "bad # UOps");
2594     return UOps;
2595   }
2596
2597   case ARM::LDRrs:
2598   case ARM::LDRBrs:
2599   case ARM::STRrs:
2600   case ARM::STRBrs: {
2601     unsigned ShOpVal = MI->getOperand(3).getImm();
2602     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2603     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2604     if (!isSub &&
2605         (ShImm == 0 ||
2606          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2607           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2608       return 1;
2609     return 2;
2610   }
2611
2612   case ARM::LDRH:
2613   case ARM::STRH: {
2614     if (!MI->getOperand(2).getReg())
2615       return 1;
2616
2617     unsigned ShOpVal = MI->getOperand(3).getImm();
2618     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2619     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2620     if (!isSub &&
2621         (ShImm == 0 ||
2622          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2623           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2624       return 1;
2625     return 2;
2626   }
2627
2628   case ARM::LDRSB:
2629   case ARM::LDRSH:
2630     return (ARM_AM::getAM3Op(MI->getOperand(3).getImm()) == ARM_AM::sub) ? 3:2;
2631
2632   case ARM::LDRSB_POST:
2633   case ARM::LDRSH_POST: {
2634     unsigned Rt = MI->getOperand(0).getReg();
2635     unsigned Rm = MI->getOperand(3).getReg();
2636     return (Rt == Rm) ? 4 : 3;
2637   }
2638
2639   case ARM::LDR_PRE_REG:
2640   case ARM::LDRB_PRE_REG: {
2641     unsigned Rt = MI->getOperand(0).getReg();
2642     unsigned Rm = MI->getOperand(3).getReg();
2643     if (Rt == Rm)
2644       return 3;
2645     unsigned ShOpVal = MI->getOperand(4).getImm();
2646     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2647     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2648     if (!isSub &&
2649         (ShImm == 0 ||
2650          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2651           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2652       return 2;
2653     return 3;
2654   }
2655
2656   case ARM::STR_PRE_REG:
2657   case ARM::STRB_PRE_REG: {
2658     unsigned ShOpVal = MI->getOperand(4).getImm();
2659     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2660     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2661     if (!isSub &&
2662         (ShImm == 0 ||
2663          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2664           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2665       return 2;
2666     return 3;
2667   }
2668
2669   case ARM::LDRH_PRE:
2670   case ARM::STRH_PRE: {
2671     unsigned Rt = MI->getOperand(0).getReg();
2672     unsigned Rm = MI->getOperand(3).getReg();
2673     if (!Rm)
2674       return 2;
2675     if (Rt == Rm)
2676       return 3;
2677     return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub)
2678       ? 3 : 2;
2679   }
2680
2681   case ARM::LDR_POST_REG:
2682   case ARM::LDRB_POST_REG:
2683   case ARM::LDRH_POST: {
2684     unsigned Rt = MI->getOperand(0).getReg();
2685     unsigned Rm = MI->getOperand(3).getReg();
2686     return (Rt == Rm) ? 3 : 2;
2687   }
2688
2689   case ARM::LDR_PRE_IMM:
2690   case ARM::LDRB_PRE_IMM:
2691   case ARM::LDR_POST_IMM:
2692   case ARM::LDRB_POST_IMM:
2693   case ARM::STRB_POST_IMM:
2694   case ARM::STRB_POST_REG:
2695   case ARM::STRB_PRE_IMM:
2696   case ARM::STRH_POST:
2697   case ARM::STR_POST_IMM:
2698   case ARM::STR_POST_REG:
2699   case ARM::STR_PRE_IMM:
2700     return 2;
2701
2702   case ARM::LDRSB_PRE:
2703   case ARM::LDRSH_PRE: {
2704     unsigned Rm = MI->getOperand(3).getReg();
2705     if (Rm == 0)
2706       return 3;
2707     unsigned Rt = MI->getOperand(0).getReg();
2708     if (Rt == Rm)
2709       return 4;
2710     unsigned ShOpVal = MI->getOperand(4).getImm();
2711     bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
2712     unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
2713     if (!isSub &&
2714         (ShImm == 0 ||
2715          ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
2716           ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
2717       return 3;
2718     return 4;
2719   }
2720
2721   case ARM::LDRD: {
2722     unsigned Rt = MI->getOperand(0).getReg();
2723     unsigned Rn = MI->getOperand(2).getReg();
2724     unsigned Rm = MI->getOperand(3).getReg();
2725     if (Rm)
2726       return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub) ?4:3;
2727     return (Rt == Rn) ? 3 : 2;
2728   }
2729
2730   case ARM::STRD: {
2731     unsigned Rm = MI->getOperand(3).getReg();
2732     if (Rm)
2733       return (ARM_AM::getAM3Op(MI->getOperand(4).getImm()) == ARM_AM::sub) ?4:3;
2734     return 2;
2735   }
2736
2737   case ARM::LDRD_POST:
2738   case ARM::t2LDRD_POST:
2739     return 3;
2740
2741   case ARM::STRD_POST:
2742   case ARM::t2STRD_POST:
2743     return 4;
2744
2745   case ARM::LDRD_PRE: {
2746     unsigned Rt = MI->getOperand(0).getReg();
2747     unsigned Rn = MI->getOperand(3).getReg();
2748     unsigned Rm = MI->getOperand(4).getReg();
2749     if (Rm)
2750       return (ARM_AM::getAM3Op(MI->getOperand(5).getImm()) == ARM_AM::sub) ?5:4;
2751     return (Rt == Rn) ? 4 : 3;
2752   }
2753
2754   case ARM::t2LDRD_PRE: {
2755     unsigned Rt = MI->getOperand(0).getReg();
2756     unsigned Rn = MI->getOperand(3).getReg();
2757     return (Rt == Rn) ? 4 : 3;
2758   }
2759
2760   case ARM::STRD_PRE: {
2761     unsigned Rm = MI->getOperand(4).getReg();
2762     if (Rm)
2763       return (ARM_AM::getAM3Op(MI->getOperand(5).getImm()) == ARM_AM::sub) ?5:4;
2764     return 3;
2765   }
2766
2767   case ARM::t2STRD_PRE:
2768     return 3;
2769
2770   case ARM::t2LDR_POST:
2771   case ARM::t2LDRB_POST:
2772   case ARM::t2LDRB_PRE:
2773   case ARM::t2LDRSBi12:
2774   case ARM::t2LDRSBi8:
2775   case ARM::t2LDRSBpci:
2776   case ARM::t2LDRSBs:
2777   case ARM::t2LDRH_POST:
2778   case ARM::t2LDRH_PRE:
2779   case ARM::t2LDRSBT:
2780   case ARM::t2LDRSB_POST:
2781   case ARM::t2LDRSB_PRE:
2782   case ARM::t2LDRSH_POST:
2783   case ARM::t2LDRSH_PRE:
2784   case ARM::t2LDRSHi12:
2785   case ARM::t2LDRSHi8:
2786   case ARM::t2LDRSHpci:
2787   case ARM::t2LDRSHs:
2788     return 2;
2789
2790   case ARM::t2LDRDi8: {
2791     unsigned Rt = MI->getOperand(0).getReg();
2792     unsigned Rn = MI->getOperand(2).getReg();
2793     return (Rt == Rn) ? 3 : 2;
2794   }
2795
2796   case ARM::t2STRB_POST:
2797   case ARM::t2STRB_PRE:
2798   case ARM::t2STRBs:
2799   case ARM::t2STRDi8:
2800   case ARM::t2STRH_POST:
2801   case ARM::t2STRH_PRE:
2802   case ARM::t2STRHs:
2803   case ARM::t2STR_POST:
2804   case ARM::t2STR_PRE:
2805   case ARM::t2STRs:
2806     return 2;
2807   }
2808 }
2809
2810 // Return the number of 32-bit words loaded by LDM or stored by STM. If this
2811 // can't be easily determined return 0 (missing MachineMemOperand).
2812 //
2813 // FIXME: The current MachineInstr design does not support relying on machine
2814 // mem operands to determine the width of a memory access. Instead, we expect
2815 // the target to provide this information based on the instruction opcode and
2816 // operands. However, using MachineMemOperand is a the best solution now for
2817 // two reasons:
2818 //
2819 // 1) getNumMicroOps tries to infer LDM memory width from the total number of MI
2820 // operands. This is much more dangerous than using the MachineMemOperand
2821 // sizes because CodeGen passes can insert/remove optional machine operands. In
2822 // fact, it's totally incorrect for preRA passes and appears to be wrong for
2823 // postRA passes as well.
2824 //
2825 // 2) getNumLDMAddresses is only used by the scheduling machine model and any
2826 // machine model that calls this should handle the unknown (zero size) case.
2827 //
2828 // Long term, we should require a target hook that verifies MachineMemOperand
2829 // sizes during MC lowering. That target hook should be local to MC lowering
2830 // because we can't ensure that it is aware of other MI forms. Doing this will
2831 // ensure that MachineMemOperands are correctly propagated through all passes.
2832 unsigned ARMBaseInstrInfo::getNumLDMAddresses(const MachineInstr *MI) const {
2833   unsigned Size = 0;
2834   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
2835          E = MI->memoperands_end(); I != E; ++I) {
2836     Size += (*I)->getSize();
2837   }
2838   return Size / 4;
2839 }
2840
2841 unsigned
2842 ARMBaseInstrInfo::getNumMicroOps(const InstrItineraryData *ItinData,
2843                                  const MachineInstr *MI) const {
2844   if (!ItinData || ItinData->isEmpty())
2845     return 1;
2846
2847   const MCInstrDesc &Desc = MI->getDesc();
2848   unsigned Class = Desc.getSchedClass();
2849   int ItinUOps = ItinData->getNumMicroOps(Class);
2850   if (ItinUOps >= 0) {
2851     if (Subtarget.isSwift() && (Desc.mayLoad() || Desc.mayStore()))
2852       return getNumMicroOpsSwiftLdSt(ItinData, MI);
2853
2854     return ItinUOps;
2855   }
2856
2857   unsigned Opc = MI->getOpcode();
2858   switch (Opc) {
2859   default:
2860     llvm_unreachable("Unexpected multi-uops instruction!");
2861   case ARM::VLDMQIA:
2862   case ARM::VSTMQIA:
2863     return 2;
2864
2865   // The number of uOps for load / store multiple are determined by the number
2866   // registers.
2867   //
2868   // On Cortex-A8, each pair of register loads / stores can be scheduled on the
2869   // same cycle. The scheduling for the first load / store must be done
2870   // separately by assuming the address is not 64-bit aligned.
2871   //
2872   // On Cortex-A9, the formula is simply (#reg / 2) + (#reg % 2). If the address
2873   // is not 64-bit aligned, then AGU would take an extra cycle.  For VFP / NEON
2874   // load / store multiple, the formula is (#reg / 2) + (#reg % 2) + 1.
2875   case ARM::VLDMDIA:
2876   case ARM::VLDMDIA_UPD:
2877   case ARM::VLDMDDB_UPD:
2878   case ARM::VLDMSIA:
2879   case ARM::VLDMSIA_UPD:
2880   case ARM::VLDMSDB_UPD:
2881   case ARM::VSTMDIA:
2882   case ARM::VSTMDIA_UPD:
2883   case ARM::VSTMDDB_UPD:
2884   case ARM::VSTMSIA:
2885   case ARM::VSTMSIA_UPD:
2886   case ARM::VSTMSDB_UPD: {
2887     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands();
2888     return (NumRegs / 2) + (NumRegs % 2) + 1;
2889   }
2890
2891   case ARM::LDMIA_RET:
2892   case ARM::LDMIA:
2893   case ARM::LDMDA:
2894   case ARM::LDMDB:
2895   case ARM::LDMIB:
2896   case ARM::LDMIA_UPD:
2897   case ARM::LDMDA_UPD:
2898   case ARM::LDMDB_UPD:
2899   case ARM::LDMIB_UPD:
2900   case ARM::STMIA:
2901   case ARM::STMDA:
2902   case ARM::STMDB:
2903   case ARM::STMIB:
2904   case ARM::STMIA_UPD:
2905   case ARM::STMDA_UPD:
2906   case ARM::STMDB_UPD:
2907   case ARM::STMIB_UPD:
2908   case ARM::tLDMIA:
2909   case ARM::tLDMIA_UPD:
2910   case ARM::tSTMIA_UPD:
2911   case ARM::tPOP_RET:
2912   case ARM::tPOP:
2913   case ARM::tPUSH:
2914   case ARM::t2LDMIA_RET:
2915   case ARM::t2LDMIA:
2916   case ARM::t2LDMDB:
2917   case ARM::t2LDMIA_UPD:
2918   case ARM::t2LDMDB_UPD:
2919   case ARM::t2STMIA:
2920   case ARM::t2STMDB:
2921   case ARM::t2STMIA_UPD:
2922   case ARM::t2STMDB_UPD: {
2923     unsigned NumRegs = MI->getNumOperands() - Desc.getNumOperands() + 1;
2924     if (Subtarget.isSwift()) {
2925       int UOps = 1 + NumRegs;  // One for address computation, one for each ld / st.
2926       switch (Opc) {
2927       default: break;
2928       case ARM::VLDMDIA_UPD:
2929       case ARM::VLDMDDB_UPD:
2930       case ARM::VLDMSIA_UPD:
2931       case ARM::VLDMSDB_UPD:
2932       case ARM::VSTMDIA_UPD:
2933       case ARM::VSTMDDB_UPD:
2934       case ARM::VSTMSIA_UPD:
2935       case ARM::VSTMSDB_UPD:
2936       case ARM::LDMIA_UPD:
2937       case ARM::LDMDA_UPD:
2938       case ARM::LDMDB_UPD:
2939       case ARM::LDMIB_UPD:
2940       case ARM::STMIA_UPD:
2941       case ARM::STMDA_UPD:
2942       case ARM::STMDB_UPD:
2943       case ARM::STMIB_UPD:
2944       case ARM::tLDMIA_UPD:
2945       case ARM::tSTMIA_UPD:
2946       case ARM::t2LDMIA_UPD:
2947       case ARM::t2LDMDB_UPD:
2948       case ARM::t2STMIA_UPD:
2949       case ARM::t2STMDB_UPD:
2950         ++UOps; // One for base register writeback.
2951         break;
2952       case ARM::LDMIA_RET:
2953       case ARM::tPOP_RET:
2954       case ARM::t2LDMIA_RET:
2955         UOps += 2; // One for base reg wb, one for write to pc.
2956         break;
2957       }
2958       return UOps;
2959     } else if (Subtarget.isCortexA8()) {
2960       if (NumRegs < 4)
2961         return 2;
2962       // 4 registers would be issued: 2, 2.
2963       // 5 registers would be issued: 2, 2, 1.
2964       int A8UOps = (NumRegs / 2);
2965       if (NumRegs % 2)
2966         ++A8UOps;
2967       return A8UOps;
2968     } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
2969       int A9UOps = (NumRegs / 2);
2970       // If there are odd number of registers or if it's not 64-bit aligned,
2971       // then it takes an extra AGU (Address Generation Unit) cycle.
2972       if ((NumRegs % 2) ||
2973           !MI->hasOneMemOperand() ||
2974           (*MI->memoperands_begin())->getAlignment() < 8)
2975         ++A9UOps;
2976       return A9UOps;
2977     } else {
2978       // Assume the worst.
2979       return NumRegs;
2980     }
2981   }
2982   }
2983 }
2984
2985 int
2986 ARMBaseInstrInfo::getVLDMDefCycle(const InstrItineraryData *ItinData,
2987                                   const MCInstrDesc &DefMCID,
2988                                   unsigned DefClass,
2989                                   unsigned DefIdx, unsigned DefAlign) const {
2990   int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
2991   if (RegNo <= 0)
2992     // Def is the address writeback.
2993     return ItinData->getOperandCycle(DefClass, DefIdx);
2994
2995   int DefCycle;
2996   if (Subtarget.isCortexA8()) {
2997     // (regno / 2) + (regno % 2) + 1
2998     DefCycle = RegNo / 2 + 1;
2999     if (RegNo % 2)
3000       ++DefCycle;
3001   } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3002     DefCycle = RegNo;
3003     bool isSLoad = false;
3004
3005     switch (DefMCID.getOpcode()) {
3006     default: break;
3007     case ARM::VLDMSIA:
3008     case ARM::VLDMSIA_UPD:
3009     case ARM::VLDMSDB_UPD:
3010       isSLoad = true;
3011       break;
3012     }
3013
3014     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
3015     // then it takes an extra cycle.
3016     if ((isSLoad && (RegNo % 2)) || DefAlign < 8)
3017       ++DefCycle;
3018   } else {
3019     // Assume the worst.
3020     DefCycle = RegNo + 2;
3021   }
3022
3023   return DefCycle;
3024 }
3025
3026 int
3027 ARMBaseInstrInfo::getLDMDefCycle(const InstrItineraryData *ItinData,
3028                                  const MCInstrDesc &DefMCID,
3029                                  unsigned DefClass,
3030                                  unsigned DefIdx, unsigned DefAlign) const {
3031   int RegNo = (int)(DefIdx+1) - DefMCID.getNumOperands() + 1;
3032   if (RegNo <= 0)
3033     // Def is the address writeback.
3034     return ItinData->getOperandCycle(DefClass, DefIdx);
3035
3036   int DefCycle;
3037   if (Subtarget.isCortexA8()) {
3038     // 4 registers would be issued: 1, 2, 1.
3039     // 5 registers would be issued: 1, 2, 2.
3040     DefCycle = RegNo / 2;
3041     if (DefCycle < 1)
3042       DefCycle = 1;
3043     // Result latency is issue cycle + 2: E2.
3044     DefCycle += 2;
3045   } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3046     DefCycle = (RegNo / 2);
3047     // If there are odd number of registers or if it's not 64-bit aligned,
3048     // then it takes an extra AGU (Address Generation Unit) cycle.
3049     if ((RegNo % 2) || DefAlign < 8)
3050       ++DefCycle;
3051     // Result latency is AGU cycles + 2.
3052     DefCycle += 2;
3053   } else {
3054     // Assume the worst.
3055     DefCycle = RegNo + 2;
3056   }
3057
3058   return DefCycle;
3059 }
3060
3061 int
3062 ARMBaseInstrInfo::getVSTMUseCycle(const InstrItineraryData *ItinData,
3063                                   const MCInstrDesc &UseMCID,
3064                                   unsigned UseClass,
3065                                   unsigned UseIdx, unsigned UseAlign) const {
3066   int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
3067   if (RegNo <= 0)
3068     return ItinData->getOperandCycle(UseClass, UseIdx);
3069
3070   int UseCycle;
3071   if (Subtarget.isCortexA8()) {
3072     // (regno / 2) + (regno % 2) + 1
3073     UseCycle = RegNo / 2 + 1;
3074     if (RegNo % 2)
3075       ++UseCycle;
3076   } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3077     UseCycle = RegNo;
3078     bool isSStore = false;
3079
3080     switch (UseMCID.getOpcode()) {
3081     default: break;
3082     case ARM::VSTMSIA:
3083     case ARM::VSTMSIA_UPD:
3084     case ARM::VSTMSDB_UPD:
3085       isSStore = true;
3086       break;
3087     }
3088
3089     // If there are odd number of 'S' registers or if it's not 64-bit aligned,
3090     // then it takes an extra cycle.
3091     if ((isSStore && (RegNo % 2)) || UseAlign < 8)
3092       ++UseCycle;
3093   } else {
3094     // Assume the worst.
3095     UseCycle = RegNo + 2;
3096   }
3097
3098   return UseCycle;
3099 }
3100
3101 int
3102 ARMBaseInstrInfo::getSTMUseCycle(const InstrItineraryData *ItinData,
3103                                  const MCInstrDesc &UseMCID,
3104                                  unsigned UseClass,
3105                                  unsigned UseIdx, unsigned UseAlign) const {
3106   int RegNo = (int)(UseIdx+1) - UseMCID.getNumOperands() + 1;
3107   if (RegNo <= 0)
3108     return ItinData->getOperandCycle(UseClass, UseIdx);
3109
3110   int UseCycle;
3111   if (Subtarget.isCortexA8()) {
3112     UseCycle = RegNo / 2;
3113     if (UseCycle < 2)
3114       UseCycle = 2;
3115     // Read in E3.
3116     UseCycle += 2;
3117   } else if (Subtarget.isLikeA9() || Subtarget.isSwift()) {
3118     UseCycle = (RegNo / 2);
3119     // If there are odd number of registers or if it's not 64-bit aligned,
3120     // then it takes an extra AGU (Address Generation Unit) cycle.
3121     if ((RegNo % 2) || UseAlign < 8)
3122       ++UseCycle;
3123   } else {
3124     // Assume the worst.
3125     UseCycle = 1;
3126   }
3127   return UseCycle;
3128 }
3129
3130 int
3131 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3132                                     const MCInstrDesc &DefMCID,
3133                                     unsigned DefIdx, unsigned DefAlign,
3134                                     const MCInstrDesc &UseMCID,
3135                                     unsigned UseIdx, unsigned UseAlign) const {
3136   unsigned DefClass = DefMCID.getSchedClass();
3137   unsigned UseClass = UseMCID.getSchedClass();
3138
3139   if (DefIdx < DefMCID.getNumDefs() && UseIdx < UseMCID.getNumOperands())
3140     return ItinData->getOperandLatency(DefClass, DefIdx, UseClass, UseIdx);
3141
3142   // This may be a def / use of a variable_ops instruction, the operand
3143   // latency might be determinable dynamically. Let the target try to
3144   // figure it out.
3145   int DefCycle = -1;
3146   bool LdmBypass = false;
3147   switch (DefMCID.getOpcode()) {
3148   default:
3149     DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
3150     break;
3151
3152   case ARM::VLDMDIA:
3153   case ARM::VLDMDIA_UPD:
3154   case ARM::VLDMDDB_UPD:
3155   case ARM::VLDMSIA:
3156   case ARM::VLDMSIA_UPD:
3157   case ARM::VLDMSDB_UPD:
3158     DefCycle = getVLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
3159     break;
3160
3161   case ARM::LDMIA_RET:
3162   case ARM::LDMIA:
3163   case ARM::LDMDA:
3164   case ARM::LDMDB:
3165   case ARM::LDMIB:
3166   case ARM::LDMIA_UPD:
3167   case ARM::LDMDA_UPD:
3168   case ARM::LDMDB_UPD:
3169   case ARM::LDMIB_UPD:
3170   case ARM::tLDMIA:
3171   case ARM::tLDMIA_UPD:
3172   case ARM::tPUSH:
3173   case ARM::t2LDMIA_RET:
3174   case ARM::t2LDMIA:
3175   case ARM::t2LDMDB:
3176   case ARM::t2LDMIA_UPD:
3177   case ARM::t2LDMDB_UPD:
3178     LdmBypass = 1;
3179     DefCycle = getLDMDefCycle(ItinData, DefMCID, DefClass, DefIdx, DefAlign);
3180     break;
3181   }
3182
3183   if (DefCycle == -1)
3184     // We can't seem to determine the result latency of the def, assume it's 2.
3185     DefCycle = 2;
3186
3187   int UseCycle = -1;
3188   switch (UseMCID.getOpcode()) {
3189   default:
3190     UseCycle = ItinData->getOperandCycle(UseClass, UseIdx);
3191     break;
3192
3193   case ARM::VSTMDIA:
3194   case ARM::VSTMDIA_UPD:
3195   case ARM::VSTMDDB_UPD:
3196   case ARM::VSTMSIA:
3197   case ARM::VSTMSIA_UPD:
3198   case ARM::VSTMSDB_UPD:
3199     UseCycle = getVSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
3200     break;
3201
3202   case ARM::STMIA:
3203   case ARM::STMDA:
3204   case ARM::STMDB:
3205   case ARM::STMIB:
3206   case ARM::STMIA_UPD:
3207   case ARM::STMDA_UPD:
3208   case ARM::STMDB_UPD:
3209   case ARM::STMIB_UPD:
3210   case ARM::tSTMIA_UPD:
3211   case ARM::tPOP_RET:
3212   case ARM::tPOP:
3213   case ARM::t2STMIA:
3214   case ARM::t2STMDB:
3215   case ARM::t2STMIA_UPD:
3216   case ARM::t2STMDB_UPD:
3217     UseCycle = getSTMUseCycle(ItinData, UseMCID, UseClass, UseIdx, UseAlign);
3218     break;
3219   }
3220
3221   if (UseCycle == -1)
3222     // Assume it's read in the first stage.
3223     UseCycle = 1;
3224
3225   UseCycle = DefCycle - UseCycle + 1;
3226   if (UseCycle > 0) {
3227     if (LdmBypass) {
3228       // It's a variable_ops instruction so we can't use DefIdx here. Just use
3229       // first def operand.
3230       if (ItinData->hasPipelineForwarding(DefClass, DefMCID.getNumOperands()-1,
3231                                           UseClass, UseIdx))
3232         --UseCycle;
3233     } else if (ItinData->hasPipelineForwarding(DefClass, DefIdx,
3234                                                UseClass, UseIdx)) {
3235       --UseCycle;
3236     }
3237   }
3238
3239   return UseCycle;
3240 }
3241
3242 static const MachineInstr *getBundledDefMI(const TargetRegisterInfo *TRI,
3243                                            const MachineInstr *MI, unsigned Reg,
3244                                            unsigned &DefIdx, unsigned &Dist) {
3245   Dist = 0;
3246
3247   MachineBasicBlock::const_iterator I = MI; ++I;
3248   MachineBasicBlock::const_instr_iterator II = std::prev(I.getInstrIterator());
3249   assert(II->isInsideBundle() && "Empty bundle?");
3250
3251   int Idx = -1;
3252   while (II->isInsideBundle()) {
3253     Idx = II->findRegisterDefOperandIdx(Reg, false, true, TRI);
3254     if (Idx != -1)
3255       break;
3256     --II;
3257     ++Dist;
3258   }
3259
3260   assert(Idx != -1 && "Cannot find bundled definition!");
3261   DefIdx = Idx;
3262   return II;
3263 }
3264
3265 static const MachineInstr *getBundledUseMI(const TargetRegisterInfo *TRI,
3266                                            const MachineInstr *MI, unsigned Reg,
3267                                            unsigned &UseIdx, unsigned &Dist) {
3268   Dist = 0;
3269
3270   MachineBasicBlock::const_instr_iterator II = MI; ++II;
3271   assert(II->isInsideBundle() && "Empty bundle?");
3272   MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
3273
3274   // FIXME: This doesn't properly handle multiple uses.
3275   int Idx = -1;
3276   while (II != E && II->isInsideBundle()) {
3277     Idx = II->findRegisterUseOperandIdx(Reg, false, TRI);
3278     if (Idx != -1)
3279       break;
3280     if (II->getOpcode() != ARM::t2IT)
3281       ++Dist;
3282     ++II;
3283   }
3284
3285   if (Idx == -1) {
3286     Dist = 0;
3287     return 0;
3288   }
3289
3290   UseIdx = Idx;
3291   return II;
3292 }
3293
3294 /// Return the number of cycles to add to (or subtract from) the static
3295 /// itinerary based on the def opcode and alignment. The caller will ensure that
3296 /// adjusted latency is at least one cycle.
3297 static int adjustDefLatency(const ARMSubtarget &Subtarget,
3298                             const MachineInstr *DefMI,
3299                             const MCInstrDesc *DefMCID, unsigned DefAlign) {
3300   int Adjust = 0;
3301   if (Subtarget.isCortexA8() || Subtarget.isLikeA9()) {
3302     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
3303     // variants are one cycle cheaper.
3304     switch (DefMCID->getOpcode()) {
3305     default: break;
3306     case ARM::LDRrs:
3307     case ARM::LDRBrs: {
3308       unsigned ShOpVal = DefMI->getOperand(3).getImm();
3309       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3310       if (ShImm == 0 ||
3311           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
3312         --Adjust;
3313       break;
3314     }
3315     case ARM::t2LDRs:
3316     case ARM::t2LDRBs:
3317     case ARM::t2LDRHs:
3318     case ARM::t2LDRSHs: {
3319       // Thumb2 mode: lsl only.
3320       unsigned ShAmt = DefMI->getOperand(3).getImm();
3321       if (ShAmt == 0 || ShAmt == 2)
3322         --Adjust;
3323       break;
3324     }
3325     }
3326   } else if (Subtarget.isSwift()) {
3327     // FIXME: Properly handle all of the latency adjustments for address
3328     // writeback.
3329     switch (DefMCID->getOpcode()) {
3330     default: break;
3331     case ARM::LDRrs:
3332     case ARM::LDRBrs: {
3333       unsigned ShOpVal = DefMI->getOperand(3).getImm();
3334       bool isSub = ARM_AM::getAM2Op(ShOpVal) == ARM_AM::sub;
3335       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3336       if (!isSub &&
3337           (ShImm == 0 ||
3338            ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3339             ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl)))
3340         Adjust -= 2;
3341       else if (!isSub &&
3342                ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
3343         --Adjust;
3344       break;
3345     }
3346     case ARM::t2LDRs:
3347     case ARM::t2LDRBs:
3348     case ARM::t2LDRHs:
3349     case ARM::t2LDRSHs: {
3350       // Thumb2 mode: lsl only.
3351       unsigned ShAmt = DefMI->getOperand(3).getImm();
3352       if (ShAmt == 0 || ShAmt == 1 || ShAmt == 2 || ShAmt == 3)
3353         Adjust -= 2;
3354       break;
3355     }
3356     }
3357   }
3358
3359   if (DefAlign < 8 && Subtarget.isLikeA9()) {
3360     switch (DefMCID->getOpcode()) {
3361     default: break;
3362     case ARM::VLD1q8:
3363     case ARM::VLD1q16:
3364     case ARM::VLD1q32:
3365     case ARM::VLD1q64:
3366     case ARM::VLD1q8wb_fixed:
3367     case ARM::VLD1q16wb_fixed:
3368     case ARM::VLD1q32wb_fixed:
3369     case ARM::VLD1q64wb_fixed:
3370     case ARM::VLD1q8wb_register:
3371     case ARM::VLD1q16wb_register:
3372     case ARM::VLD1q32wb_register:
3373     case ARM::VLD1q64wb_register:
3374     case ARM::VLD2d8:
3375     case ARM::VLD2d16:
3376     case ARM::VLD2d32:
3377     case ARM::VLD2q8:
3378     case ARM::VLD2q16:
3379     case ARM::VLD2q32:
3380     case ARM::VLD2d8wb_fixed:
3381     case ARM::VLD2d16wb_fixed:
3382     case ARM::VLD2d32wb_fixed:
3383     case ARM::VLD2q8wb_fixed:
3384     case ARM::VLD2q16wb_fixed:
3385     case ARM::VLD2q32wb_fixed:
3386     case ARM::VLD2d8wb_register:
3387     case ARM::VLD2d16wb_register:
3388     case ARM::VLD2d32wb_register:
3389     case ARM::VLD2q8wb_register:
3390     case ARM::VLD2q16wb_register:
3391     case ARM::VLD2q32wb_register:
3392     case ARM::VLD3d8:
3393     case ARM::VLD3d16:
3394     case ARM::VLD3d32:
3395     case ARM::VLD1d64T:
3396     case ARM::VLD3d8_UPD:
3397     case ARM::VLD3d16_UPD:
3398     case ARM::VLD3d32_UPD:
3399     case ARM::VLD1d64Twb_fixed:
3400     case ARM::VLD1d64Twb_register:
3401     case ARM::VLD3q8_UPD:
3402     case ARM::VLD3q16_UPD:
3403     case ARM::VLD3q32_UPD:
3404     case ARM::VLD4d8:
3405     case ARM::VLD4d16:
3406     case ARM::VLD4d32:
3407     case ARM::VLD1d64Q:
3408     case ARM::VLD4d8_UPD:
3409     case ARM::VLD4d16_UPD:
3410     case ARM::VLD4d32_UPD:
3411     case ARM::VLD1d64Qwb_fixed:
3412     case ARM::VLD1d64Qwb_register:
3413     case ARM::VLD4q8_UPD:
3414     case ARM::VLD4q16_UPD:
3415     case ARM::VLD4q32_UPD:
3416     case ARM::VLD1DUPq8:
3417     case ARM::VLD1DUPq16:
3418     case ARM::VLD1DUPq32:
3419     case ARM::VLD1DUPq8wb_fixed:
3420     case ARM::VLD1DUPq16wb_fixed:
3421     case ARM::VLD1DUPq32wb_fixed:
3422     case ARM::VLD1DUPq8wb_register:
3423     case ARM::VLD1DUPq16wb_register:
3424     case ARM::VLD1DUPq32wb_register:
3425     case ARM::VLD2DUPd8:
3426     case ARM::VLD2DUPd16:
3427     case ARM::VLD2DUPd32:
3428     case ARM::VLD2DUPd8wb_fixed:
3429     case ARM::VLD2DUPd16wb_fixed:
3430     case ARM::VLD2DUPd32wb_fixed:
3431     case ARM::VLD2DUPd8wb_register:
3432     case ARM::VLD2DUPd16wb_register:
3433     case ARM::VLD2DUPd32wb_register:
3434     case ARM::VLD4DUPd8:
3435     case ARM::VLD4DUPd16:
3436     case ARM::VLD4DUPd32:
3437     case ARM::VLD4DUPd8_UPD:
3438     case ARM::VLD4DUPd16_UPD:
3439     case ARM::VLD4DUPd32_UPD:
3440     case ARM::VLD1LNd8:
3441     case ARM::VLD1LNd16:
3442     case ARM::VLD1LNd32:
3443     case ARM::VLD1LNd8_UPD:
3444     case ARM::VLD1LNd16_UPD:
3445     case ARM::VLD1LNd32_UPD:
3446     case ARM::VLD2LNd8:
3447     case ARM::VLD2LNd16:
3448     case ARM::VLD2LNd32:
3449     case ARM::VLD2LNq16:
3450     case ARM::VLD2LNq32:
3451     case ARM::VLD2LNd8_UPD:
3452     case ARM::VLD2LNd16_UPD:
3453     case ARM::VLD2LNd32_UPD:
3454     case ARM::VLD2LNq16_UPD:
3455     case ARM::VLD2LNq32_UPD:
3456     case ARM::VLD4LNd8:
3457     case ARM::VLD4LNd16:
3458     case ARM::VLD4LNd32:
3459     case ARM::VLD4LNq16:
3460     case ARM::VLD4LNq32:
3461     case ARM::VLD4LNd8_UPD:
3462     case ARM::VLD4LNd16_UPD:
3463     case ARM::VLD4LNd32_UPD:
3464     case ARM::VLD4LNq16_UPD:
3465     case ARM::VLD4LNq32_UPD:
3466       // If the address is not 64-bit aligned, the latencies of these
3467       // instructions increases by one.
3468       ++Adjust;
3469       break;
3470     }
3471   }
3472   return Adjust;
3473 }
3474
3475
3476
3477 int
3478 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3479                                     const MachineInstr *DefMI, unsigned DefIdx,
3480                                     const MachineInstr *UseMI,
3481                                     unsigned UseIdx) const {
3482   // No operand latency. The caller may fall back to getInstrLatency.
3483   if (!ItinData || ItinData->isEmpty())
3484     return -1;
3485
3486   const MachineOperand &DefMO = DefMI->getOperand(DefIdx);
3487   unsigned Reg = DefMO.getReg();
3488   const MCInstrDesc *DefMCID = &DefMI->getDesc();
3489   const MCInstrDesc *UseMCID = &UseMI->getDesc();
3490
3491   unsigned DefAdj = 0;
3492   if (DefMI->isBundle()) {
3493     DefMI = getBundledDefMI(&getRegisterInfo(), DefMI, Reg, DefIdx, DefAdj);
3494     DefMCID = &DefMI->getDesc();
3495   }
3496   if (DefMI->isCopyLike() || DefMI->isInsertSubreg() ||
3497       DefMI->isRegSequence() || DefMI->isImplicitDef()) {
3498     return 1;
3499   }
3500
3501   unsigned UseAdj = 0;
3502   if (UseMI->isBundle()) {
3503     unsigned NewUseIdx;
3504     const MachineInstr *NewUseMI = getBundledUseMI(&getRegisterInfo(), UseMI,
3505                                                    Reg, NewUseIdx, UseAdj);
3506     if (!NewUseMI)
3507       return -1;
3508
3509     UseMI = NewUseMI;
3510     UseIdx = NewUseIdx;
3511     UseMCID = &UseMI->getDesc();
3512   }
3513
3514   if (Reg == ARM::CPSR) {
3515     if (DefMI->getOpcode() == ARM::FMSTAT) {
3516       // fpscr -> cpsr stalls over 20 cycles on A8 (and earlier?)
3517       return Subtarget.isLikeA9() ? 1 : 20;
3518     }
3519
3520     // CPSR set and branch can be paired in the same cycle.
3521     if (UseMI->isBranch())
3522       return 0;
3523
3524     // Otherwise it takes the instruction latency (generally one).
3525     unsigned Latency = getInstrLatency(ItinData, DefMI);
3526
3527     // For Thumb2 and -Os, prefer scheduling CPSR setting instruction close to
3528     // its uses. Instructions which are otherwise scheduled between them may
3529     // incur a code size penalty (not able to use the CPSR setting 16-bit
3530     // instructions).
3531     if (Latency > 0 && Subtarget.isThumb2()) {
3532       const MachineFunction *MF = DefMI->getParent()->getParent();
3533       if (MF->getFunction()->getAttributes().
3534             hasAttribute(AttributeSet::FunctionIndex,
3535                          Attribute::OptimizeForSize))
3536         --Latency;
3537     }
3538     return Latency;
3539   }
3540
3541   if (DefMO.isImplicit() || UseMI->getOperand(UseIdx).isImplicit())
3542     return -1;
3543
3544   unsigned DefAlign = DefMI->hasOneMemOperand()
3545     ? (*DefMI->memoperands_begin())->getAlignment() : 0;
3546   unsigned UseAlign = UseMI->hasOneMemOperand()
3547     ? (*UseMI->memoperands_begin())->getAlignment() : 0;
3548
3549   // Get the itinerary's latency if possible, and handle variable_ops.
3550   int Latency = getOperandLatency(ItinData, *DefMCID, DefIdx, DefAlign,
3551                                   *UseMCID, UseIdx, UseAlign);
3552   // Unable to find operand latency. The caller may resort to getInstrLatency.
3553   if (Latency < 0)
3554     return Latency;
3555
3556   // Adjust for IT block position.
3557   int Adj = DefAdj + UseAdj;
3558
3559   // Adjust for dynamic def-side opcode variants not captured by the itinerary.
3560   Adj += adjustDefLatency(Subtarget, DefMI, DefMCID, DefAlign);
3561   if (Adj >= 0 || (int)Latency > -Adj) {
3562     return Latency + Adj;
3563   }
3564   // Return the itinerary latency, which may be zero but not less than zero.
3565   return Latency;
3566 }
3567
3568 int
3569 ARMBaseInstrInfo::getOperandLatency(const InstrItineraryData *ItinData,
3570                                     SDNode *DefNode, unsigned DefIdx,
3571                                     SDNode *UseNode, unsigned UseIdx) const {
3572   if (!DefNode->isMachineOpcode())
3573     return 1;
3574
3575   const MCInstrDesc &DefMCID = get(DefNode->getMachineOpcode());
3576
3577   if (isZeroCost(DefMCID.Opcode))
3578     return 0;
3579
3580   if (!ItinData || ItinData->isEmpty())
3581     return DefMCID.mayLoad() ? 3 : 1;
3582
3583   if (!UseNode->isMachineOpcode()) {
3584     int Latency = ItinData->getOperandCycle(DefMCID.getSchedClass(), DefIdx);
3585     if (Subtarget.isLikeA9() || Subtarget.isSwift())
3586       return Latency <= 2 ? 1 : Latency - 1;
3587     else
3588       return Latency <= 3 ? 1 : Latency - 2;
3589   }
3590
3591   const MCInstrDesc &UseMCID = get(UseNode->getMachineOpcode());
3592   const MachineSDNode *DefMN = dyn_cast<MachineSDNode>(DefNode);
3593   unsigned DefAlign = !DefMN->memoperands_empty()
3594     ? (*DefMN->memoperands_begin())->getAlignment() : 0;
3595   const MachineSDNode *UseMN = dyn_cast<MachineSDNode>(UseNode);
3596   unsigned UseAlign = !UseMN->memoperands_empty()
3597     ? (*UseMN->memoperands_begin())->getAlignment() : 0;
3598   int Latency = getOperandLatency(ItinData, DefMCID, DefIdx, DefAlign,
3599                                   UseMCID, UseIdx, UseAlign);
3600
3601   if (Latency > 1 &&
3602       (Subtarget.isCortexA8() || Subtarget.isLikeA9())) {
3603     // FIXME: Shifter op hack: no shift (i.e. [r +/- r]) or [r + r << 2]
3604     // variants are one cycle cheaper.
3605     switch (DefMCID.getOpcode()) {
3606     default: break;
3607     case ARM::LDRrs:
3608     case ARM::LDRBrs: {
3609       unsigned ShOpVal =
3610         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
3611       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3612       if (ShImm == 0 ||
3613           (ShImm == 2 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
3614         --Latency;
3615       break;
3616     }
3617     case ARM::t2LDRs:
3618     case ARM::t2LDRBs:
3619     case ARM::t2LDRHs:
3620     case ARM::t2LDRSHs: {
3621       // Thumb2 mode: lsl only.
3622       unsigned ShAmt =
3623         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
3624       if (ShAmt == 0 || ShAmt == 2)
3625         --Latency;
3626       break;
3627     }
3628     }
3629   } else if (DefIdx == 0 && Latency > 2 && Subtarget.isSwift()) {
3630     // FIXME: Properly handle all of the latency adjustments for address
3631     // writeback.
3632     switch (DefMCID.getOpcode()) {
3633     default: break;
3634     case ARM::LDRrs:
3635     case ARM::LDRBrs: {
3636       unsigned ShOpVal =
3637         cast<ConstantSDNode>(DefNode->getOperand(2))->getZExtValue();
3638       unsigned ShImm = ARM_AM::getAM2Offset(ShOpVal);
3639       if (ShImm == 0 ||
3640           ((ShImm == 1 || ShImm == 2 || ShImm == 3) &&
3641            ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsl))
3642         Latency -= 2;
3643       else if (ShImm == 1 && ARM_AM::getAM2ShiftOpc(ShOpVal) == ARM_AM::lsr)
3644         --Latency;
3645       break;
3646     }
3647     case ARM::t2LDRs:
3648     case ARM::t2LDRBs:
3649     case ARM::t2LDRHs:
3650     case ARM::t2LDRSHs: {
3651       // Thumb2 mode: lsl 0-3 only.
3652       Latency -= 2;
3653       break;
3654     }
3655     }
3656   }
3657
3658   if (DefAlign < 8 && Subtarget.isLikeA9())
3659     switch (DefMCID.getOpcode()) {
3660     default: break;
3661     case ARM::VLD1q8:
3662     case ARM::VLD1q16:
3663     case ARM::VLD1q32:
3664     case ARM::VLD1q64:
3665     case ARM::VLD1q8wb_register:
3666     case ARM::VLD1q16wb_register:
3667     case ARM::VLD1q32wb_register:
3668     case ARM::VLD1q64wb_register:
3669     case ARM::VLD1q8wb_fixed:
3670     case ARM::VLD1q16wb_fixed:
3671     case ARM::VLD1q32wb_fixed:
3672     case ARM::VLD1q64wb_fixed:
3673     case ARM::VLD2d8:
3674     case ARM::VLD2d16:
3675     case ARM::VLD2d32:
3676     case ARM::VLD2q8Pseudo:
3677     case ARM::VLD2q16Pseudo:
3678     case ARM::VLD2q32Pseudo:
3679     case ARM::VLD2d8wb_fixed:
3680     case ARM::VLD2d16wb_fixed:
3681     case ARM::VLD2d32wb_fixed:
3682     case ARM::VLD2q8PseudoWB_fixed:
3683     case ARM::VLD2q16PseudoWB_fixed:
3684     case ARM::VLD2q32PseudoWB_fixed:
3685     case ARM::VLD2d8wb_register:
3686     case ARM::VLD2d16wb_register:
3687     case ARM::VLD2d32wb_register:
3688     case ARM::VLD2q8PseudoWB_register:
3689     case ARM::VLD2q16PseudoWB_register:
3690     case ARM::VLD2q32PseudoWB_register:
3691     case ARM::VLD3d8Pseudo:
3692     case ARM::VLD3d16Pseudo:
3693     case ARM::VLD3d32Pseudo:
3694     case ARM::VLD1d64TPseudo:
3695     case ARM::VLD1d64TPseudoWB_fixed:
3696     case ARM::VLD3d8Pseudo_UPD:
3697     case ARM::VLD3d16Pseudo_UPD:
3698     case ARM::VLD3d32Pseudo_UPD:
3699     case ARM::VLD3q8Pseudo_UPD:
3700     case ARM::VLD3q16Pseudo_UPD:
3701     case ARM::VLD3q32Pseudo_UPD:
3702     case ARM::VLD3q8oddPseudo:
3703     case ARM::VLD3q16oddPseudo:
3704     case ARM::VLD3q32oddPseudo:
3705     case ARM::VLD3q8oddPseudo_UPD:
3706     case ARM::VLD3q16oddPseudo_UPD:
3707     case ARM::VLD3q32oddPseudo_UPD:
3708     case ARM::VLD4d8Pseudo:
3709     case ARM::VLD4d16Pseudo:
3710     case ARM::VLD4d32Pseudo:
3711     case ARM::VLD1d64QPseudo:
3712     case ARM::VLD1d64QPseudoWB_fixed:
3713     case ARM::VLD4d8Pseudo_UPD:
3714     case ARM::VLD4d16Pseudo_UPD:
3715     case ARM::VLD4d32Pseudo_UPD:
3716     case ARM::VLD4q8Pseudo_UPD:
3717     case ARM::VLD4q16Pseudo_UPD:
3718     case ARM::VLD4q32Pseudo_UPD:
3719     case ARM::VLD4q8oddPseudo:
3720     case ARM::VLD4q16oddPseudo:
3721     case ARM::VLD4q32oddPseudo:
3722     case ARM::VLD4q8oddPseudo_UPD:
3723     case ARM::VLD4q16oddPseudo_UPD:
3724     case ARM::VLD4q32oddPseudo_UPD:
3725     case ARM::VLD1DUPq8:
3726     case ARM::VLD1DUPq16:
3727     case ARM::VLD1DUPq32:
3728     case ARM::VLD1DUPq8wb_fixed:
3729     case ARM::VLD1DUPq16wb_fixed:
3730     case ARM::VLD1DUPq32wb_fixed:
3731     case ARM::VLD1DUPq8wb_register:
3732     case ARM::VLD1DUPq16wb_register:
3733     case ARM::VLD1DUPq32wb_register:
3734     case ARM::VLD2DUPd8:
3735     case ARM::VLD2DUPd16:
3736     case ARM::VLD2DUPd32:
3737     case ARM::VLD2DUPd8wb_fixed:
3738     case ARM::VLD2DUPd16wb_fixed:
3739     case ARM::VLD2DUPd32wb_fixed:
3740     case ARM::VLD2DUPd8wb_register:
3741     case ARM::VLD2DUPd16wb_register:
3742     case ARM::VLD2DUPd32wb_register:
3743     case ARM::VLD4DUPd8Pseudo:
3744     case ARM::VLD4DUPd16Pseudo:
3745     case ARM::VLD4DUPd32Pseudo:
3746     case ARM::VLD4DUPd8Pseudo_UPD:
3747     case ARM::VLD4DUPd16Pseudo_UPD:
3748     case ARM::VLD4DUPd32Pseudo_UPD:
3749     case ARM::VLD1LNq8Pseudo:
3750     case ARM::VLD1LNq16Pseudo:
3751     case ARM::VLD1LNq32Pseudo:
3752     case ARM::VLD1LNq8Pseudo_UPD:
3753     case ARM::VLD1LNq16Pseudo_UPD:
3754     case ARM::VLD1LNq32Pseudo_UPD:
3755     case ARM::VLD2LNd8Pseudo:
3756     case ARM::VLD2LNd16Pseudo:
3757     case ARM::VLD2LNd32Pseudo:
3758     case ARM::VLD2LNq16Pseudo:
3759     case ARM::VLD2LNq32Pseudo:
3760     case ARM::VLD2LNd8Pseudo_UPD:
3761     case ARM::VLD2LNd16Pseudo_UPD:
3762     case ARM::VLD2LNd32Pseudo_UPD:
3763     case ARM::VLD2LNq16Pseudo_UPD:
3764     case ARM::VLD2LNq32Pseudo_UPD:
3765     case ARM::VLD4LNd8Pseudo:
3766     case ARM::VLD4LNd16Pseudo:
3767     case ARM::VLD4LNd32Pseudo:
3768     case ARM::VLD4LNq16Pseudo:
3769     case ARM::VLD4LNq32Pseudo:
3770     case ARM::VLD4LNd8Pseudo_UPD:
3771     case ARM::VLD4LNd16Pseudo_UPD:
3772     case ARM::VLD4LNd32Pseudo_UPD:
3773     case ARM::VLD4LNq16Pseudo_UPD:
3774     case ARM::VLD4LNq32Pseudo_UPD:
3775       // If the address is not 64-bit aligned, the latencies of these
3776       // instructions increases by one.
3777       ++Latency;
3778       break;
3779     }
3780
3781   return Latency;
3782 }
3783
3784 unsigned ARMBaseInstrInfo::getPredicationCost(const MachineInstr *MI) const {
3785    if (MI->isCopyLike() || MI->isInsertSubreg() ||
3786       MI->isRegSequence() || MI->isImplicitDef())
3787     return 0;
3788
3789   if (MI->isBundle())
3790     return 0;
3791
3792   const MCInstrDesc &MCID = MI->getDesc();
3793
3794   if (MCID.isCall() || MCID.hasImplicitDefOfPhysReg(ARM::CPSR)) {
3795     // When predicated, CPSR is an additional source operand for CPSR updating
3796     // instructions, this apparently increases their latencies.
3797     return 1;
3798   }
3799   return 0;
3800 }
3801
3802 unsigned ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
3803                                            const MachineInstr *MI,
3804                                            unsigned *PredCost) const {
3805   if (MI->isCopyLike() || MI->isInsertSubreg() ||
3806       MI->isRegSequence() || MI->isImplicitDef())
3807     return 1;
3808
3809   // An instruction scheduler typically runs on unbundled instructions, however
3810   // other passes may query the latency of a bundled instruction.
3811   if (MI->isBundle()) {
3812     unsigned Latency = 0;
3813     MachineBasicBlock::const_instr_iterator I = MI;
3814     MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
3815     while (++I != E && I->isInsideBundle()) {
3816       if (I->getOpcode() != ARM::t2IT)
3817         Latency += getInstrLatency(ItinData, I, PredCost);
3818     }
3819     return Latency;
3820   }
3821
3822   const MCInstrDesc &MCID = MI->getDesc();
3823   if (PredCost && (MCID.isCall() || MCID.hasImplicitDefOfPhysReg(ARM::CPSR))) {
3824     // When predicated, CPSR is an additional source operand for CPSR updating
3825     // instructions, this apparently increases their latencies.
3826     *PredCost = 1;
3827   }
3828   // Be sure to call getStageLatency for an empty itinerary in case it has a
3829   // valid MinLatency property.
3830   if (!ItinData)
3831     return MI->mayLoad() ? 3 : 1;
3832
3833   unsigned Class = MCID.getSchedClass();
3834
3835   // For instructions with variable uops, use uops as latency.
3836   if (!ItinData->isEmpty() && ItinData->getNumMicroOps(Class) < 0)
3837     return getNumMicroOps(ItinData, MI);
3838
3839   // For the common case, fall back on the itinerary's latency.
3840   unsigned Latency = ItinData->getStageLatency(Class);
3841
3842   // Adjust for dynamic def-side opcode variants not captured by the itinerary.
3843   unsigned DefAlign = MI->hasOneMemOperand()
3844     ? (*MI->memoperands_begin())->getAlignment() : 0;
3845   int Adj = adjustDefLatency(Subtarget, MI, &MCID, DefAlign);
3846   if (Adj >= 0 || (int)Latency > -Adj) {
3847     return Latency + Adj;
3848   }
3849   return Latency;
3850 }
3851
3852 int ARMBaseInstrInfo::getInstrLatency(const InstrItineraryData *ItinData,
3853                                       SDNode *Node) const {
3854   if (!Node->isMachineOpcode())
3855     return 1;
3856
3857   if (!ItinData || ItinData->isEmpty())
3858     return 1;
3859
3860   unsigned Opcode = Node->getMachineOpcode();
3861   switch (Opcode) {
3862   default:
3863     return ItinData->getStageLatency(get(Opcode).getSchedClass());
3864   case ARM::VLDMQIA:
3865   case ARM::VSTMQIA:
3866     return 2;
3867   }
3868 }
3869
3870 bool ARMBaseInstrInfo::
3871 hasHighOperandLatency(const InstrItineraryData *ItinData,
3872                       const MachineRegisterInfo *MRI,
3873                       const MachineInstr *DefMI, unsigned DefIdx,
3874                       const MachineInstr *UseMI, unsigned UseIdx) const {
3875   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
3876   unsigned UDomain = UseMI->getDesc().TSFlags & ARMII::DomainMask;
3877   if (Subtarget.isCortexA8() &&
3878       (DDomain == ARMII::DomainVFP || UDomain == ARMII::DomainVFP))
3879     // CortexA8 VFP instructions are not pipelined.
3880     return true;
3881
3882   // Hoist VFP / NEON instructions with 4 or higher latency.
3883   int Latency = computeOperandLatency(ItinData, DefMI, DefIdx, UseMI, UseIdx);
3884   if (Latency < 0)
3885     Latency = getInstrLatency(ItinData, DefMI);
3886   if (Latency <= 3)
3887     return false;
3888   return DDomain == ARMII::DomainVFP || DDomain == ARMII::DomainNEON ||
3889          UDomain == ARMII::DomainVFP || UDomain == ARMII::DomainNEON;
3890 }
3891
3892 bool ARMBaseInstrInfo::
3893 hasLowDefLatency(const InstrItineraryData *ItinData,
3894                  const MachineInstr *DefMI, unsigned DefIdx) const {
3895   if (!ItinData || ItinData->isEmpty())
3896     return false;
3897
3898   unsigned DDomain = DefMI->getDesc().TSFlags & ARMII::DomainMask;
3899   if (DDomain == ARMII::DomainGeneral) {
3900     unsigned DefClass = DefMI->getDesc().getSchedClass();
3901     int DefCycle = ItinData->getOperandCycle(DefClass, DefIdx);
3902     return (DefCycle != -1 && DefCycle <= 2);
3903   }
3904   return false;
3905 }
3906
3907 bool ARMBaseInstrInfo::verifyInstruction(const MachineInstr *MI,
3908                                          StringRef &ErrInfo) const {
3909   if (convertAddSubFlagsOpcode(MI->getOpcode())) {
3910     ErrInfo = "Pseudo flag setting opcodes only exist in Selection DAG";
3911     return false;
3912   }
3913   return true;
3914 }
3915
3916 bool
3917 ARMBaseInstrInfo::isFpMLxInstruction(unsigned Opcode, unsigned &MulOpc,
3918                                      unsigned &AddSubOpc,
3919                                      bool &NegAcc, bool &HasLane) const {
3920   DenseMap<unsigned, unsigned>::const_iterator I = MLxEntryMap.find(Opcode);
3921   if (I == MLxEntryMap.end())
3922     return false;
3923
3924   const ARM_MLxEntry &Entry = ARM_MLxTable[I->second];
3925   MulOpc = Entry.MulOpc;
3926   AddSubOpc = Entry.AddSubOpc;
3927   NegAcc = Entry.NegAcc;
3928   HasLane = Entry.HasLane;
3929   return true;
3930 }
3931
3932 //===----------------------------------------------------------------------===//
3933 // Execution domains.
3934 //===----------------------------------------------------------------------===//
3935 //
3936 // Some instructions go down the NEON pipeline, some go down the VFP pipeline,
3937 // and some can go down both.  The vmov instructions go down the VFP pipeline,
3938 // but they can be changed to vorr equivalents that are executed by the NEON
3939 // pipeline.
3940 //
3941 // We use the following execution domain numbering:
3942 //
3943 enum ARMExeDomain {
3944   ExeGeneric = 0,
3945   ExeVFP = 1,
3946   ExeNEON = 2
3947 };
3948 //
3949 // Also see ARMInstrFormats.td and Domain* enums in ARMBaseInfo.h
3950 //
3951 std::pair<uint16_t, uint16_t>
3952 ARMBaseInstrInfo::getExecutionDomain(const MachineInstr *MI) const {
3953   // VMOVD, VMOVRS and VMOVSR are VFP instructions, but can be changed to NEON
3954   // if they are not predicated.
3955   if (MI->getOpcode() == ARM::VMOVD && !isPredicated(MI))
3956     return std::make_pair(ExeVFP, (1<<ExeVFP) | (1<<ExeNEON));
3957
3958   // CortexA9 is particularly picky about mixing the two and wants these
3959   // converted.
3960   if (Subtarget.isCortexA9() && !isPredicated(MI) &&
3961       (MI->getOpcode() == ARM::VMOVRS ||
3962        MI->getOpcode() == ARM::VMOVSR ||
3963        MI->getOpcode() == ARM::VMOVS))
3964     return std::make_pair(ExeVFP, (1<<ExeVFP) | (1<<ExeNEON));
3965
3966   // No other instructions can be swizzled, so just determine their domain.
3967   unsigned Domain = MI->getDesc().TSFlags & ARMII::DomainMask;
3968
3969   if (Domain & ARMII::DomainNEON)
3970     return std::make_pair(ExeNEON, 0);
3971
3972   // Certain instructions can go either way on Cortex-A8.
3973   // Treat them as NEON instructions.
3974   if ((Domain & ARMII::DomainNEONA8) && Subtarget.isCortexA8())
3975     return std::make_pair(ExeNEON, 0);
3976
3977   if (Domain & ARMII::DomainVFP)
3978     return std::make_pair(ExeVFP, 0);
3979
3980   return std::make_pair(ExeGeneric, 0);
3981 }
3982
3983 static unsigned getCorrespondingDRegAndLane(const TargetRegisterInfo *TRI,
3984                                             unsigned SReg, unsigned &Lane) {
3985   unsigned DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_0, &ARM::DPRRegClass);
3986   Lane = 0;
3987
3988   if (DReg != ARM::NoRegister)
3989    return DReg;
3990
3991   Lane = 1;
3992   DReg = TRI->getMatchingSuperReg(SReg, ARM::ssub_1, &ARM::DPRRegClass);
3993
3994   assert(DReg && "S-register with no D super-register?");
3995   return DReg;
3996 }
3997
3998 /// getImplicitSPRUseForDPRUse - Given a use of a DPR register and lane,
3999 /// set ImplicitSReg to a register number that must be marked as implicit-use or
4000 /// zero if no register needs to be defined as implicit-use.
4001 ///
4002 /// If the function cannot determine if an SPR should be marked implicit use or
4003 /// not, it returns false.
4004 ///
4005 /// This function handles cases where an instruction is being modified from taking
4006 /// an SPR to a DPR[Lane]. A use of the DPR is being added, which may conflict
4007 /// with an earlier def of an SPR corresponding to DPR[Lane^1] (i.e. the other
4008 /// lane of the DPR).
4009 ///
4010 /// If the other SPR is defined, an implicit-use of it should be added. Else,
4011 /// (including the case where the DPR itself is defined), it should not.
4012 ///
4013 static bool getImplicitSPRUseForDPRUse(const TargetRegisterInfo *TRI,
4014                                        MachineInstr *MI,
4015                                        unsigned DReg, unsigned Lane,
4016                                        unsigned &ImplicitSReg) {
4017   // If the DPR is defined or used already, the other SPR lane will be chained
4018   // correctly, so there is nothing to be done.
4019   if (MI->definesRegister(DReg, TRI) || MI->readsRegister(DReg, TRI)) {
4020     ImplicitSReg = 0;
4021     return true;
4022   }
4023
4024   // Otherwise we need to go searching to see if the SPR is set explicitly.
4025   ImplicitSReg = TRI->getSubReg(DReg,
4026                                 (Lane & 1) ? ARM::ssub_0 : ARM::ssub_1);
4027   MachineBasicBlock::LivenessQueryResult LQR =
4028     MI->getParent()->computeRegisterLiveness(TRI, ImplicitSReg, MI);
4029
4030   if (LQR == MachineBasicBlock::LQR_Live)
4031     return true;
4032   else if (LQR == MachineBasicBlock::LQR_Unknown)
4033     return false;
4034
4035   // If the register is known not to be live, there is no need to add an
4036   // implicit-use.
4037   ImplicitSReg = 0;
4038   return true;
4039 }
4040
4041 void
4042 ARMBaseInstrInfo::setExecutionDomain(MachineInstr *MI, unsigned Domain) const {
4043   unsigned DstReg, SrcReg, DReg;
4044   unsigned Lane;
4045   MachineInstrBuilder MIB(*MI->getParent()->getParent(), MI);
4046   const TargetRegisterInfo *TRI = &getRegisterInfo();
4047   switch (MI->getOpcode()) {
4048     default:
4049       llvm_unreachable("cannot handle opcode!");
4050       break;
4051     case ARM::VMOVD:
4052       if (Domain != ExeNEON)
4053         break;
4054
4055       // Zap the predicate operands.
4056       assert(!isPredicated(MI) && "Cannot predicate a VORRd");
4057
4058       // Source instruction is %DDst = VMOVD %DSrc, 14, %noreg (; implicits)
4059       DstReg = MI->getOperand(0).getReg();
4060       SrcReg = MI->getOperand(1).getReg();
4061
4062       for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
4063         MI->RemoveOperand(i-1);
4064
4065       // Change to a %DDst = VORRd %DSrc, %DSrc, 14, %noreg (; implicits)
4066       MI->setDesc(get(ARM::VORRd));
4067       AddDefaultPred(MIB.addReg(DstReg, RegState::Define)
4068                         .addReg(SrcReg)
4069                         .addReg(SrcReg));
4070       break;
4071     case ARM::VMOVRS:
4072       if (Domain != ExeNEON)
4073         break;
4074       assert(!isPredicated(MI) && "Cannot predicate a VGETLN");
4075
4076       // Source instruction is %RDst = VMOVRS %SSrc, 14, %noreg (; implicits)
4077       DstReg = MI->getOperand(0).getReg();
4078       SrcReg = MI->getOperand(1).getReg();
4079
4080       for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
4081         MI->RemoveOperand(i-1);
4082
4083       DReg = getCorrespondingDRegAndLane(TRI, SrcReg, Lane);
4084
4085       // Convert to %RDst = VGETLNi32 %DSrc, Lane, 14, %noreg (; imps)
4086       // Note that DSrc has been widened and the other lane may be undef, which
4087       // contaminates the entire register.
4088       MI->setDesc(get(ARM::VGETLNi32));
4089       AddDefaultPred(MIB.addReg(DstReg, RegState::Define)
4090                         .addReg(DReg, RegState::Undef)
4091                         .addImm(Lane));
4092
4093       // The old source should be an implicit use, otherwise we might think it
4094       // was dead before here.
4095       MIB.addReg(SrcReg, RegState::Implicit);
4096       break;
4097     case ARM::VMOVSR: {
4098       if (Domain != ExeNEON)
4099         break;
4100       assert(!isPredicated(MI) && "Cannot predicate a VSETLN");
4101
4102       // Source instruction is %SDst = VMOVSR %RSrc, 14, %noreg (; implicits)
4103       DstReg = MI->getOperand(0).getReg();
4104       SrcReg = MI->getOperand(1).getReg();
4105
4106       DReg = getCorrespondingDRegAndLane(TRI, DstReg, Lane);
4107
4108       unsigned ImplicitSReg;
4109       if (!getImplicitSPRUseForDPRUse(TRI, MI, DReg, Lane, ImplicitSReg))
4110         break;
4111
4112       for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
4113         MI->RemoveOperand(i-1);
4114
4115       // Convert to %DDst = VSETLNi32 %DDst, %RSrc, Lane, 14, %noreg (; imps)
4116       // Again DDst may be undefined at the beginning of this instruction.
4117       MI->setDesc(get(ARM::VSETLNi32));
4118       MIB.addReg(DReg, RegState::Define)
4119          .addReg(DReg, getUndefRegState(!MI->readsRegister(DReg, TRI)))
4120          .addReg(SrcReg)
4121          .addImm(Lane);
4122       AddDefaultPred(MIB);
4123
4124       // The narrower destination must be marked as set to keep previous chains
4125       // in place.
4126       MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
4127       if (ImplicitSReg != 0)
4128         MIB.addReg(ImplicitSReg, RegState::Implicit);
4129       break;
4130     }
4131     case ARM::VMOVS: {
4132       if (Domain != ExeNEON)
4133         break;
4134
4135       // Source instruction is %SDst = VMOVS %SSrc, 14, %noreg (; implicits)
4136       DstReg = MI->getOperand(0).getReg();
4137       SrcReg = MI->getOperand(1).getReg();
4138
4139       unsigned DstLane = 0, SrcLane = 0, DDst, DSrc;
4140       DDst = getCorrespondingDRegAndLane(TRI, DstReg, DstLane);
4141       DSrc = getCorrespondingDRegAndLane(TRI, SrcReg, SrcLane);
4142
4143       unsigned ImplicitSReg;
4144       if (!getImplicitSPRUseForDPRUse(TRI, MI, DSrc, SrcLane, ImplicitSReg))
4145         break;
4146
4147       for (unsigned i = MI->getDesc().getNumOperands(); i; --i)
4148         MI->RemoveOperand(i-1);
4149
4150       if (DSrc == DDst) {
4151         // Destination can be:
4152         //     %DDst = VDUPLN32d %DDst, Lane, 14, %noreg (; implicits)
4153         MI->setDesc(get(ARM::VDUPLN32d));
4154         MIB.addReg(DDst, RegState::Define)
4155            .addReg(DDst, getUndefRegState(!MI->readsRegister(DDst, TRI)))
4156            .addImm(SrcLane);
4157         AddDefaultPred(MIB);
4158
4159         // Neither the source or the destination are naturally represented any
4160         // more, so add them in manually.
4161         MIB.addReg(DstReg, RegState::Implicit | RegState::Define);
4162         MIB.addReg(SrcReg, RegState::Implicit);
4163         if (ImplicitSReg != 0)
4164           MIB.addReg(ImplicitSReg, RegState::Implicit);
4165         break;
4166       }
4167
4168       // In general there's no single instruction that can perform an S <-> S
4169       // move in NEON space, but a pair of VEXT instructions *can* do the
4170       // job. It turns out that the VEXTs needed will only use DSrc once, with
4171       // the position based purely on the combination of lane-0 and lane-1
4172       // involved. For example
4173       //     vmov s0, s2 -> vext.32 d0, d0, d1, #1  vext.32 d0, d0, d0, #1
4174       //     vmov s1, s3 -> vext.32 d0, d1, d0, #1  vext.32 d0, d0, d0, #1
4175       //     vmov s0, s3 -> vext.32 d0, d0, d0, #1  vext.32 d0, d1, d0, #1
4176       //     vmov s1, s2 -> vext.32 d0, d0, d0, #1  vext.32 d0, d0, d1, #1
4177       //
4178       // Pattern of the MachineInstrs is:
4179       //     %DDst = VEXTd32 %DSrc1, %DSrc2, Lane, 14, %noreg (;implicits)
4180       MachineInstrBuilder NewMIB;
4181       NewMIB = BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
4182                        get(ARM::VEXTd32), DDst);
4183
4184       // On the first instruction, both DSrc and DDst may be <undef> if present.
4185       // Specifically when the original instruction didn't have them as an
4186       // <imp-use>.
4187       unsigned CurReg = SrcLane == 1 && DstLane == 1 ? DSrc : DDst;
4188       bool CurUndef = !MI->readsRegister(CurReg, TRI);
4189       NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
4190
4191       CurReg = SrcLane == 0 && DstLane == 0 ? DSrc : DDst;
4192       CurUndef = !MI->readsRegister(CurReg, TRI);
4193       NewMIB.addReg(CurReg, getUndefRegState(CurUndef));
4194
4195       NewMIB.addImm(1);
4196       AddDefaultPred(NewMIB);
4197
4198       if (SrcLane == DstLane)
4199         NewMIB.addReg(SrcReg, RegState::Implicit);
4200
4201       MI->setDesc(get(ARM::VEXTd32));
4202       MIB.addReg(DDst, RegState::Define);
4203
4204       // On the second instruction, DDst has definitely been defined above, so
4205       // it is not <undef>. DSrc, if present, can be <undef> as above.
4206       CurReg = SrcLane == 1 && DstLane == 0 ? DSrc : DDst;
4207       CurUndef = CurReg == DSrc && !MI->readsRegister(CurReg, TRI);
4208       MIB.addReg(CurReg, getUndefRegState(CurUndef));
4209
4210       CurReg = SrcLane == 0 && DstLane == 1 ? DSrc : DDst;
4211       CurUndef = CurReg == DSrc && !MI->readsRegister(CurReg, TRI);
4212       MIB.addReg(CurReg, getUndefRegState(CurUndef));
4213
4214       MIB.addImm(1);
4215       AddDefaultPred(MIB);
4216
4217       if (SrcLane != DstLane)
4218         MIB.addReg(SrcReg, RegState::Implicit);
4219
4220       // As before, the original destination is no longer represented, add it
4221       // implicitly.
4222       MIB.addReg(DstReg, RegState::Define | RegState::Implicit);
4223       if (ImplicitSReg != 0)
4224         MIB.addReg(ImplicitSReg, RegState::Implicit);
4225       break;
4226     }
4227   }
4228
4229 }
4230
4231 //===----------------------------------------------------------------------===//
4232 // Partial register updates
4233 //===----------------------------------------------------------------------===//
4234 //
4235 // Swift renames NEON registers with 64-bit granularity.  That means any
4236 // instruction writing an S-reg implicitly reads the containing D-reg.  The
4237 // problem is mostly avoided by translating f32 operations to v2f32 operations
4238 // on D-registers, but f32 loads are still a problem.
4239 //
4240 // These instructions can load an f32 into a NEON register:
4241 //
4242 // VLDRS - Only writes S, partial D update.
4243 // VLD1LNd32 - Writes all D-regs, explicit partial D update, 2 uops.
4244 // VLD1DUPd32 - Writes all D-regs, no partial reg update, 2 uops.
4245 //
4246 // FCONSTD can be used as a dependency-breaking instruction.
4247 unsigned ARMBaseInstrInfo::
4248 getPartialRegUpdateClearance(const MachineInstr *MI,
4249                              unsigned OpNum,
4250                              const TargetRegisterInfo *TRI) const {
4251   if (!SwiftPartialUpdateClearance ||
4252       !(Subtarget.isSwift() || Subtarget.isCortexA15()))
4253     return 0;
4254
4255   assert(TRI && "Need TRI instance");
4256
4257   const MachineOperand &MO = MI->getOperand(OpNum);
4258   if (MO.readsReg())
4259     return 0;
4260   unsigned Reg = MO.getReg();
4261   int UseOp = -1;
4262
4263   switch(MI->getOpcode()) {
4264     // Normal instructions writing only an S-register.
4265   case ARM::VLDRS:
4266   case ARM::FCONSTS:
4267   case ARM::VMOVSR:
4268   case ARM::VMOVv8i8:
4269   case ARM::VMOVv4i16:
4270   case ARM::VMOVv2i32:
4271   case ARM::VMOVv2f32:
4272   case ARM::VMOVv1i64:
4273     UseOp = MI->findRegisterUseOperandIdx(Reg, false, TRI);
4274     break;
4275
4276     // Explicitly reads the dependency.
4277   case ARM::VLD1LNd32:
4278     UseOp = 3;
4279     break;
4280   default:
4281     return 0;
4282   }
4283
4284   // If this instruction actually reads a value from Reg, there is no unwanted
4285   // dependency.
4286   if (UseOp != -1 && MI->getOperand(UseOp).readsReg())
4287     return 0;
4288
4289   // We must be able to clobber the whole D-reg.
4290   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
4291     // Virtual register must be a foo:ssub_0<def,undef> operand.
4292     if (!MO.getSubReg() || MI->readsVirtualRegister(Reg))
4293       return 0;
4294   } else if (ARM::SPRRegClass.contains(Reg)) {
4295     // Physical register: MI must define the full D-reg.
4296     unsigned DReg = TRI->getMatchingSuperReg(Reg, ARM::ssub_0,
4297                                              &ARM::DPRRegClass);
4298     if (!DReg || !MI->definesRegister(DReg, TRI))
4299       return 0;
4300   }
4301
4302   // MI has an unwanted D-register dependency.
4303   // Avoid defs in the previous N instructrions.
4304   return SwiftPartialUpdateClearance;
4305 }
4306
4307 // Break a partial register dependency after getPartialRegUpdateClearance
4308 // returned non-zero.
4309 void ARMBaseInstrInfo::
4310 breakPartialRegDependency(MachineBasicBlock::iterator MI,
4311                           unsigned OpNum,
4312                           const TargetRegisterInfo *TRI) const {
4313   assert(MI && OpNum < MI->getDesc().getNumDefs() && "OpNum is not a def");
4314   assert(TRI && "Need TRI instance");
4315
4316   const MachineOperand &MO = MI->getOperand(OpNum);
4317   unsigned Reg = MO.getReg();
4318   assert(TargetRegisterInfo::isPhysicalRegister(Reg) &&
4319          "Can't break virtual register dependencies.");
4320   unsigned DReg = Reg;
4321
4322   // If MI defines an S-reg, find the corresponding D super-register.
4323   if (ARM::SPRRegClass.contains(Reg)) {
4324     DReg = ARM::D0 + (Reg - ARM::S0) / 2;
4325     assert(TRI->isSuperRegister(Reg, DReg) && "Register enums broken");
4326   }
4327
4328   assert(ARM::DPRRegClass.contains(DReg) && "Can only break D-reg deps");
4329   assert(MI->definesRegister(DReg, TRI) && "MI doesn't clobber full D-reg");
4330
4331   // FIXME: In some cases, VLDRS can be changed to a VLD1DUPd32 which defines
4332   // the full D-register by loading the same value to both lanes.  The
4333   // instruction is micro-coded with 2 uops, so don't do this until we can
4334   // properly schedule micro-coded instructions.  The dispatcher stalls cause
4335   // too big regressions.
4336
4337   // Insert the dependency-breaking FCONSTD before MI.
4338   // 96 is the encoding of 0.5, but the actual value doesn't matter here.
4339   AddDefaultPred(BuildMI(*MI->getParent(), MI, MI->getDebugLoc(),
4340                          get(ARM::FCONSTD), DReg).addImm(96));
4341   MI->addRegisterKilled(DReg, TRI, true);
4342 }
4343
4344 bool ARMBaseInstrInfo::hasNOP() const {
4345   return (Subtarget.getFeatureBits() & ARM::HasV6T2Ops) != 0;
4346 }
4347
4348 bool ARMBaseInstrInfo::isSwiftFastImmShift(const MachineInstr *MI) const {
4349   if (MI->getNumOperands() < 4)
4350     return true;
4351   unsigned ShOpVal = MI->getOperand(3).getImm();
4352   unsigned ShImm = ARM_AM::getSORegOffset(ShOpVal);
4353   // Swift supports faster shifts for: lsl 2, lsl 1, and lsr 1.
4354   if ((ShImm == 1 && ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsr) ||
4355       ((ShImm == 1 || ShImm == 2) &&
4356        ARM_AM::getSORegShOp(ShOpVal) == ARM_AM::lsl))
4357     return true;
4358
4359   return false;
4360 }