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