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