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