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