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