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