1 //===- AArch64InstrInfo.cpp - AArch64 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 AArch64 implementation of the TargetInstrInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "AArch64InstrInfo.h"
14 #include "AArch64MachineFunctionInfo.h"
15 #include "AArch64Subtarget.h"
16 #include "MCTargetDesc/AArch64AddressingModes.h"
17 #include "Utils/AArch64BaseInfo.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/CodeGen/MachineBasicBlock.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineMemOperand.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineOperand.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/StackMaps.h"
31 #include "llvm/CodeGen/TargetRegisterInfo.h"
32 #include "llvm/CodeGen/TargetSubtargetInfo.h"
33 #include "llvm/IR/DebugInfoMetadata.h"
34 #include "llvm/IR/DebugLoc.h"
35 #include "llvm/IR/GlobalValue.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCInst.h"
38 #include "llvm/MC/MCInstBuilder.h"
39 #include "llvm/MC/MCInstrDesc.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CodeGen.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Compiler.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include <cassert>
49 #include <cstdint>
50 #include <iterator>
51 #include <utility>
52 
53 using namespace llvm;
54 
55 #define GET_INSTRINFO_CTOR_DTOR
56 #include "AArch64GenInstrInfo.inc"
57 
58 static cl::opt<unsigned> TBZDisplacementBits(
59     "aarch64-tbz-offset-bits", cl::Hidden, cl::init(14),
60     cl::desc("Restrict range of TB[N]Z instructions (DEBUG)"));
61 
62 static cl::opt<unsigned> CBZDisplacementBits(
63     "aarch64-cbz-offset-bits", cl::Hidden, cl::init(19),
64     cl::desc("Restrict range of CB[N]Z instructions (DEBUG)"));
65 
66 static cl::opt<unsigned>
67     BCCDisplacementBits("aarch64-bcc-offset-bits", cl::Hidden, cl::init(19),
68                         cl::desc("Restrict range of Bcc instructions (DEBUG)"));
69 
70 AArch64InstrInfo::AArch64InstrInfo(const AArch64Subtarget &STI)
71     : AArch64GenInstrInfo(AArch64::ADJCALLSTACKDOWN, AArch64::ADJCALLSTACKUP,
72                           AArch64::CATCHRET),
73       RI(STI.getTargetTriple()), Subtarget(STI) {}
74 
75 /// GetInstSize - Return the number of bytes of code the specified
76 /// instruction may be.  This returns the maximum number of bytes.
77 unsigned AArch64InstrInfo::getInstSizeInBytes(const MachineInstr &MI) const {
78   const MachineBasicBlock &MBB = *MI.getParent();
79   const MachineFunction *MF = MBB.getParent();
80   const MCAsmInfo *MAI = MF->getTarget().getMCAsmInfo();
81 
82   {
83     auto Op = MI.getOpcode();
84     if (Op == AArch64::INLINEASM || Op == AArch64::INLINEASM_BR)
85       return getInlineAsmLength(MI.getOperand(0).getSymbolName(), *MAI);
86   }
87 
88   // Meta-instructions emit no code.
89   if (MI.isMetaInstruction())
90     return 0;
91 
92   // FIXME: We currently only handle pseudoinstructions that don't get expanded
93   //        before the assembly printer.
94   unsigned NumBytes = 0;
95   const MCInstrDesc &Desc = MI.getDesc();
96 
97   // Size should be preferably set in
98   // llvm/lib/Target/AArch64/AArch64InstrInfo.td (default case).
99   // Specific cases handle instructions of variable sizes
100   switch (Desc.getOpcode()) {
101   default:
102     if (Desc.getSize())
103       return Desc.getSize();
104 
105     // Anything not explicitly designated otherwise (i.e. pseudo-instructions
106     // with fixed constant size but not specified in .td file) is a normal
107     // 4-byte insn.
108     NumBytes = 4;
109     break;
110   case TargetOpcode::STACKMAP:
111     // The upper bound for a stackmap intrinsic is the full length of its shadow
112     NumBytes = StackMapOpers(&MI).getNumPatchBytes();
113     assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
114     break;
115   case TargetOpcode::PATCHPOINT:
116     // The size of the patchpoint intrinsic is the number of bytes requested
117     NumBytes = PatchPointOpers(&MI).getNumPatchBytes();
118     assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
119     break;
120   case TargetOpcode::STATEPOINT:
121     NumBytes = StatepointOpers(&MI).getNumPatchBytes();
122     assert(NumBytes % 4 == 0 && "Invalid number of NOP bytes requested!");
123     // No patch bytes means a normal call inst is emitted
124     if (NumBytes == 0)
125       NumBytes = 4;
126     break;
127   case AArch64::SPACE:
128     NumBytes = MI.getOperand(1).getImm();
129     break;
130   case TargetOpcode::BUNDLE:
131     NumBytes = getInstBundleLength(MI);
132     break;
133   }
134 
135   return NumBytes;
136 }
137 
138 unsigned AArch64InstrInfo::getInstBundleLength(const MachineInstr &MI) const {
139   unsigned Size = 0;
140   MachineBasicBlock::const_instr_iterator I = MI.getIterator();
141   MachineBasicBlock::const_instr_iterator E = MI.getParent()->instr_end();
142   while (++I != E && I->isInsideBundle()) {
143     assert(!I->isBundle() && "No nested bundle!");
144     Size += getInstSizeInBytes(*I);
145   }
146   return Size;
147 }
148 
149 static void parseCondBranch(MachineInstr *LastInst, MachineBasicBlock *&Target,
150                             SmallVectorImpl<MachineOperand> &Cond) {
151   // Block ends with fall-through condbranch.
152   switch (LastInst->getOpcode()) {
153   default:
154     llvm_unreachable("Unknown branch instruction?");
155   case AArch64::Bcc:
156     Target = LastInst->getOperand(1).getMBB();
157     Cond.push_back(LastInst->getOperand(0));
158     break;
159   case AArch64::CBZW:
160   case AArch64::CBZX:
161   case AArch64::CBNZW:
162   case AArch64::CBNZX:
163     Target = LastInst->getOperand(1).getMBB();
164     Cond.push_back(MachineOperand::CreateImm(-1));
165     Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
166     Cond.push_back(LastInst->getOperand(0));
167     break;
168   case AArch64::TBZW:
169   case AArch64::TBZX:
170   case AArch64::TBNZW:
171   case AArch64::TBNZX:
172     Target = LastInst->getOperand(2).getMBB();
173     Cond.push_back(MachineOperand::CreateImm(-1));
174     Cond.push_back(MachineOperand::CreateImm(LastInst->getOpcode()));
175     Cond.push_back(LastInst->getOperand(0));
176     Cond.push_back(LastInst->getOperand(1));
177   }
178 }
179 
180 static unsigned getBranchDisplacementBits(unsigned Opc) {
181   switch (Opc) {
182   default:
183     llvm_unreachable("unexpected opcode!");
184   case AArch64::B:
185     return 64;
186   case AArch64::TBNZW:
187   case AArch64::TBZW:
188   case AArch64::TBNZX:
189   case AArch64::TBZX:
190     return TBZDisplacementBits;
191   case AArch64::CBNZW:
192   case AArch64::CBZW:
193   case AArch64::CBNZX:
194   case AArch64::CBZX:
195     return CBZDisplacementBits;
196   case AArch64::Bcc:
197     return BCCDisplacementBits;
198   }
199 }
200 
201 bool AArch64InstrInfo::isBranchOffsetInRange(unsigned BranchOp,
202                                              int64_t BrOffset) const {
203   unsigned Bits = getBranchDisplacementBits(BranchOp);
204   assert(Bits >= 3 && "max branch displacement must be enough to jump"
205                       "over conditional branch expansion");
206   return isIntN(Bits, BrOffset / 4);
207 }
208 
209 MachineBasicBlock *
210 AArch64InstrInfo::getBranchDestBlock(const MachineInstr &MI) const {
211   switch (MI.getOpcode()) {
212   default:
213     llvm_unreachable("unexpected opcode!");
214   case AArch64::B:
215     return MI.getOperand(0).getMBB();
216   case AArch64::TBZW:
217   case AArch64::TBNZW:
218   case AArch64::TBZX:
219   case AArch64::TBNZX:
220     return MI.getOperand(2).getMBB();
221   case AArch64::CBZW:
222   case AArch64::CBNZW:
223   case AArch64::CBZX:
224   case AArch64::CBNZX:
225   case AArch64::Bcc:
226     return MI.getOperand(1).getMBB();
227   }
228 }
229 
230 // Branch analysis.
231 bool AArch64InstrInfo::analyzeBranch(MachineBasicBlock &MBB,
232                                      MachineBasicBlock *&TBB,
233                                      MachineBasicBlock *&FBB,
234                                      SmallVectorImpl<MachineOperand> &Cond,
235                                      bool AllowModify) const {
236   // If the block has no terminators, it just falls into the block after it.
237   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
238   if (I == MBB.end())
239     return false;
240 
241   // Skip over SpeculationBarrierEndBB terminators
242   if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB ||
243       I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) {
244     --I;
245   }
246 
247   if (!isUnpredicatedTerminator(*I))
248     return false;
249 
250   // Get the last instruction in the block.
251   MachineInstr *LastInst = &*I;
252 
253   // If there is only one terminator instruction, process it.
254   unsigned LastOpc = LastInst->getOpcode();
255   if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
256     if (isUncondBranchOpcode(LastOpc)) {
257       TBB = LastInst->getOperand(0).getMBB();
258       return false;
259     }
260     if (isCondBranchOpcode(LastOpc)) {
261       // Block ends with fall-through condbranch.
262       parseCondBranch(LastInst, TBB, Cond);
263       return false;
264     }
265     return true; // Can't handle indirect branch.
266   }
267 
268   // Get the instruction before it if it is a terminator.
269   MachineInstr *SecondLastInst = &*I;
270   unsigned SecondLastOpc = SecondLastInst->getOpcode();
271 
272   // If AllowModify is true and the block ends with two or more unconditional
273   // branches, delete all but the first unconditional branch.
274   if (AllowModify && isUncondBranchOpcode(LastOpc)) {
275     while (isUncondBranchOpcode(SecondLastOpc)) {
276       LastInst->eraseFromParent();
277       LastInst = SecondLastInst;
278       LastOpc = LastInst->getOpcode();
279       if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
280         // Return now the only terminator is an unconditional branch.
281         TBB = LastInst->getOperand(0).getMBB();
282         return false;
283       } else {
284         SecondLastInst = &*I;
285         SecondLastOpc = SecondLastInst->getOpcode();
286       }
287     }
288   }
289 
290   // If we're allowed to modify and the block ends in a unconditional branch
291   // which could simply fallthrough, remove the branch.  (Note: This case only
292   // matters when we can't understand the whole sequence, otherwise it's also
293   // handled by BranchFolding.cpp.)
294   if (AllowModify && isUncondBranchOpcode(LastOpc) &&
295       MBB.isLayoutSuccessor(getBranchDestBlock(*LastInst))) {
296     LastInst->eraseFromParent();
297     LastInst = SecondLastInst;
298     LastOpc = LastInst->getOpcode();
299     if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) {
300       assert(!isUncondBranchOpcode(LastOpc) &&
301              "unreachable unconditional branches removed above");
302 
303       if (isCondBranchOpcode(LastOpc)) {
304         // Block ends with fall-through condbranch.
305         parseCondBranch(LastInst, TBB, Cond);
306         return false;
307       }
308       return true; // Can't handle indirect branch.
309     } else {
310       SecondLastInst = &*I;
311       SecondLastOpc = SecondLastInst->getOpcode();
312     }
313   }
314 
315   // If there are three terminators, we don't know what sort of block this is.
316   if (SecondLastInst && I != MBB.begin() && isUnpredicatedTerminator(*--I))
317     return true;
318 
319   // If the block ends with a B and a Bcc, handle it.
320   if (isCondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
321     parseCondBranch(SecondLastInst, TBB, Cond);
322     FBB = LastInst->getOperand(0).getMBB();
323     return false;
324   }
325 
326   // If the block ends with two unconditional branches, handle it.  The second
327   // one is not executed, so remove it.
328   if (isUncondBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
329     TBB = SecondLastInst->getOperand(0).getMBB();
330     I = LastInst;
331     if (AllowModify)
332       I->eraseFromParent();
333     return false;
334   }
335 
336   // ...likewise if it ends with an indirect branch followed by an unconditional
337   // branch.
338   if (isIndirectBranchOpcode(SecondLastOpc) && isUncondBranchOpcode(LastOpc)) {
339     I = LastInst;
340     if (AllowModify)
341       I->eraseFromParent();
342     return true;
343   }
344 
345   // Otherwise, can't handle this.
346   return true;
347 }
348 
349 bool AArch64InstrInfo::analyzeBranchPredicate(MachineBasicBlock &MBB,
350                                               MachineBranchPredicate &MBP,
351                                               bool AllowModify) const {
352   // For the moment, handle only a block which ends with a cb(n)zx followed by
353   // a fallthrough.  Why this?  Because it is a common form.
354   // TODO: Should we handle b.cc?
355 
356   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
357   if (I == MBB.end())
358     return true;
359 
360   // Skip over SpeculationBarrierEndBB terminators
361   if (I->getOpcode() == AArch64::SpeculationBarrierISBDSBEndBB ||
362       I->getOpcode() == AArch64::SpeculationBarrierSBEndBB) {
363     --I;
364   }
365 
366   if (!isUnpredicatedTerminator(*I))
367     return true;
368 
369   // Get the last instruction in the block.
370   MachineInstr *LastInst = &*I;
371   unsigned LastOpc = LastInst->getOpcode();
372   if (!isCondBranchOpcode(LastOpc))
373     return true;
374 
375   switch (LastOpc) {
376   default:
377     return true;
378   case AArch64::CBZW:
379   case AArch64::CBZX:
380   case AArch64::CBNZW:
381   case AArch64::CBNZX:
382     break;
383   };
384 
385   MBP.TrueDest = LastInst->getOperand(1).getMBB();
386   assert(MBP.TrueDest && "expected!");
387   MBP.FalseDest = MBB.getNextNode();
388 
389   MBP.ConditionDef = nullptr;
390   MBP.SingleUseCondition = false;
391 
392   MBP.LHS = LastInst->getOperand(0);
393   MBP.RHS = MachineOperand::CreateImm(0);
394   MBP.Predicate = LastOpc == AArch64::CBNZX ? MachineBranchPredicate::PRED_NE
395                                             : MachineBranchPredicate::PRED_EQ;
396   return false;
397 }
398 
399 bool AArch64InstrInfo::reverseBranchCondition(
400     SmallVectorImpl<MachineOperand> &Cond) const {
401   if (Cond[0].getImm() != -1) {
402     // Regular Bcc
403     AArch64CC::CondCode CC = (AArch64CC::CondCode)(int)Cond[0].getImm();
404     Cond[0].setImm(AArch64CC::getInvertedCondCode(CC));
405   } else {
406     // Folded compare-and-branch
407     switch (Cond[1].getImm()) {
408     default:
409       llvm_unreachable("Unknown conditional branch!");
410     case AArch64::CBZW:
411       Cond[1].setImm(AArch64::CBNZW);
412       break;
413     case AArch64::CBNZW:
414       Cond[1].setImm(AArch64::CBZW);
415       break;
416     case AArch64::CBZX:
417       Cond[1].setImm(AArch64::CBNZX);
418       break;
419     case AArch64::CBNZX:
420       Cond[1].setImm(AArch64::CBZX);
421       break;
422     case AArch64::TBZW:
423       Cond[1].setImm(AArch64::TBNZW);
424       break;
425     case AArch64::TBNZW:
426       Cond[1].setImm(AArch64::TBZW);
427       break;
428     case AArch64::TBZX:
429       Cond[1].setImm(AArch64::TBNZX);
430       break;
431     case AArch64::TBNZX:
432       Cond[1].setImm(AArch64::TBZX);
433       break;
434     }
435   }
436 
437   return false;
438 }
439 
440 unsigned AArch64InstrInfo::removeBranch(MachineBasicBlock &MBB,
441                                         int *BytesRemoved) const {
442   MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr();
443   if (I == MBB.end())
444     return 0;
445 
446   if (!isUncondBranchOpcode(I->getOpcode()) &&
447       !isCondBranchOpcode(I->getOpcode()))
448     return 0;
449 
450   // Remove the branch.
451   I->eraseFromParent();
452 
453   I = MBB.end();
454 
455   if (I == MBB.begin()) {
456     if (BytesRemoved)
457       *BytesRemoved = 4;
458     return 1;
459   }
460   --I;
461   if (!isCondBranchOpcode(I->getOpcode())) {
462     if (BytesRemoved)
463       *BytesRemoved = 4;
464     return 1;
465   }
466 
467   // Remove the branch.
468   I->eraseFromParent();
469   if (BytesRemoved)
470     *BytesRemoved = 8;
471 
472   return 2;
473 }
474 
475 void AArch64InstrInfo::instantiateCondBranch(
476     MachineBasicBlock &MBB, const DebugLoc &DL, MachineBasicBlock *TBB,
477     ArrayRef<MachineOperand> Cond) const {
478   if (Cond[0].getImm() != -1) {
479     // Regular Bcc
480     BuildMI(&MBB, DL, get(AArch64::Bcc)).addImm(Cond[0].getImm()).addMBB(TBB);
481   } else {
482     // Folded compare-and-branch
483     // Note that we use addOperand instead of addReg to keep the flags.
484     const MachineInstrBuilder MIB =
485         BuildMI(&MBB, DL, get(Cond[1].getImm())).add(Cond[2]);
486     if (Cond.size() > 3)
487       MIB.addImm(Cond[3].getImm());
488     MIB.addMBB(TBB);
489   }
490 }
491 
492 unsigned AArch64InstrInfo::insertBranch(
493     MachineBasicBlock &MBB, MachineBasicBlock *TBB, MachineBasicBlock *FBB,
494     ArrayRef<MachineOperand> Cond, const DebugLoc &DL, int *BytesAdded) const {
495   // Shouldn't be a fall through.
496   assert(TBB && "insertBranch must not be told to insert a fallthrough");
497 
498   if (!FBB) {
499     if (Cond.empty()) // Unconditional branch?
500       BuildMI(&MBB, DL, get(AArch64::B)).addMBB(TBB);
501     else
502       instantiateCondBranch(MBB, DL, TBB, Cond);
503 
504     if (BytesAdded)
505       *BytesAdded = 4;
506 
507     return 1;
508   }
509 
510   // Two-way conditional branch.
511   instantiateCondBranch(MBB, DL, TBB, Cond);
512   BuildMI(&MBB, DL, get(AArch64::B)).addMBB(FBB);
513 
514   if (BytesAdded)
515     *BytesAdded = 8;
516 
517   return 2;
518 }
519 
520 // Find the original register that VReg is copied from.
521 static unsigned removeCopies(const MachineRegisterInfo &MRI, unsigned VReg) {
522   while (Register::isVirtualRegister(VReg)) {
523     const MachineInstr *DefMI = MRI.getVRegDef(VReg);
524     if (!DefMI->isFullCopy())
525       return VReg;
526     VReg = DefMI->getOperand(1).getReg();
527   }
528   return VReg;
529 }
530 
531 // Determine if VReg is defined by an instruction that can be folded into a
532 // csel instruction. If so, return the folded opcode, and the replacement
533 // register.
534 static unsigned canFoldIntoCSel(const MachineRegisterInfo &MRI, unsigned VReg,
535                                 unsigned *NewVReg = nullptr) {
536   VReg = removeCopies(MRI, VReg);
537   if (!Register::isVirtualRegister(VReg))
538     return 0;
539 
540   bool Is64Bit = AArch64::GPR64allRegClass.hasSubClassEq(MRI.getRegClass(VReg));
541   const MachineInstr *DefMI = MRI.getVRegDef(VReg);
542   unsigned Opc = 0;
543   unsigned SrcOpNum = 0;
544   switch (DefMI->getOpcode()) {
545   case AArch64::ADDSXri:
546   case AArch64::ADDSWri:
547     // if NZCV is used, do not fold.
548     if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, true) == -1)
549       return 0;
550     // fall-through to ADDXri and ADDWri.
551     LLVM_FALLTHROUGH;
552   case AArch64::ADDXri:
553   case AArch64::ADDWri:
554     // add x, 1 -> csinc.
555     if (!DefMI->getOperand(2).isImm() || DefMI->getOperand(2).getImm() != 1 ||
556         DefMI->getOperand(3).getImm() != 0)
557       return 0;
558     SrcOpNum = 1;
559     Opc = Is64Bit ? AArch64::CSINCXr : AArch64::CSINCWr;
560     break;
561 
562   case AArch64::ORNXrr:
563   case AArch64::ORNWrr: {
564     // not x -> csinv, represented as orn dst, xzr, src.
565     unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
566     if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
567       return 0;
568     SrcOpNum = 2;
569     Opc = Is64Bit ? AArch64::CSINVXr : AArch64::CSINVWr;
570     break;
571   }
572 
573   case AArch64::SUBSXrr:
574   case AArch64::SUBSWrr:
575     // if NZCV is used, do not fold.
576     if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, true) == -1)
577       return 0;
578     // fall-through to SUBXrr and SUBWrr.
579     LLVM_FALLTHROUGH;
580   case AArch64::SUBXrr:
581   case AArch64::SUBWrr: {
582     // neg x -> csneg, represented as sub dst, xzr, src.
583     unsigned ZReg = removeCopies(MRI, DefMI->getOperand(1).getReg());
584     if (ZReg != AArch64::XZR && ZReg != AArch64::WZR)
585       return 0;
586     SrcOpNum = 2;
587     Opc = Is64Bit ? AArch64::CSNEGXr : AArch64::CSNEGWr;
588     break;
589   }
590   default:
591     return 0;
592   }
593   assert(Opc && SrcOpNum && "Missing parameters");
594 
595   if (NewVReg)
596     *NewVReg = DefMI->getOperand(SrcOpNum).getReg();
597   return Opc;
598 }
599 
600 bool AArch64InstrInfo::canInsertSelect(const MachineBasicBlock &MBB,
601                                        ArrayRef<MachineOperand> Cond,
602                                        Register DstReg, Register TrueReg,
603                                        Register FalseReg, int &CondCycles,
604                                        int &TrueCycles,
605                                        int &FalseCycles) const {
606   // Check register classes.
607   const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
608   const TargetRegisterClass *RC =
609       RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg));
610   if (!RC)
611     return false;
612 
613   // Also need to check the dest regclass, in case we're trying to optimize
614   // something like:
615   // %1(gpr) = PHI %2(fpr), bb1, %(fpr), bb2
616   if (!RI.getCommonSubClass(RC, MRI.getRegClass(DstReg)))
617     return false;
618 
619   // Expanding cbz/tbz requires an extra cycle of latency on the condition.
620   unsigned ExtraCondLat = Cond.size() != 1;
621 
622   // GPRs are handled by csel.
623   // FIXME: Fold in x+1, -x, and ~x when applicable.
624   if (AArch64::GPR64allRegClass.hasSubClassEq(RC) ||
625       AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
626     // Single-cycle csel, csinc, csinv, and csneg.
627     CondCycles = 1 + ExtraCondLat;
628     TrueCycles = FalseCycles = 1;
629     if (canFoldIntoCSel(MRI, TrueReg))
630       TrueCycles = 0;
631     else if (canFoldIntoCSel(MRI, FalseReg))
632       FalseCycles = 0;
633     return true;
634   }
635 
636   // Scalar floating point is handled by fcsel.
637   // FIXME: Form fabs, fmin, and fmax when applicable.
638   if (AArch64::FPR64RegClass.hasSubClassEq(RC) ||
639       AArch64::FPR32RegClass.hasSubClassEq(RC)) {
640     CondCycles = 5 + ExtraCondLat;
641     TrueCycles = FalseCycles = 2;
642     return true;
643   }
644 
645   // Can't do vectors.
646   return false;
647 }
648 
649 void AArch64InstrInfo::insertSelect(MachineBasicBlock &MBB,
650                                     MachineBasicBlock::iterator I,
651                                     const DebugLoc &DL, Register DstReg,
652                                     ArrayRef<MachineOperand> Cond,
653                                     Register TrueReg, Register FalseReg) const {
654   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
655 
656   // Parse the condition code, see parseCondBranch() above.
657   AArch64CC::CondCode CC;
658   switch (Cond.size()) {
659   default:
660     llvm_unreachable("Unknown condition opcode in Cond");
661   case 1: // b.cc
662     CC = AArch64CC::CondCode(Cond[0].getImm());
663     break;
664   case 3: { // cbz/cbnz
665     // We must insert a compare against 0.
666     bool Is64Bit;
667     switch (Cond[1].getImm()) {
668     default:
669       llvm_unreachable("Unknown branch opcode in Cond");
670     case AArch64::CBZW:
671       Is64Bit = false;
672       CC = AArch64CC::EQ;
673       break;
674     case AArch64::CBZX:
675       Is64Bit = true;
676       CC = AArch64CC::EQ;
677       break;
678     case AArch64::CBNZW:
679       Is64Bit = false;
680       CC = AArch64CC::NE;
681       break;
682     case AArch64::CBNZX:
683       Is64Bit = true;
684       CC = AArch64CC::NE;
685       break;
686     }
687     Register SrcReg = Cond[2].getReg();
688     if (Is64Bit) {
689       // cmp reg, #0 is actually subs xzr, reg, #0.
690       MRI.constrainRegClass(SrcReg, &AArch64::GPR64spRegClass);
691       BuildMI(MBB, I, DL, get(AArch64::SUBSXri), AArch64::XZR)
692           .addReg(SrcReg)
693           .addImm(0)
694           .addImm(0);
695     } else {
696       MRI.constrainRegClass(SrcReg, &AArch64::GPR32spRegClass);
697       BuildMI(MBB, I, DL, get(AArch64::SUBSWri), AArch64::WZR)
698           .addReg(SrcReg)
699           .addImm(0)
700           .addImm(0);
701     }
702     break;
703   }
704   case 4: { // tbz/tbnz
705     // We must insert a tst instruction.
706     switch (Cond[1].getImm()) {
707     default:
708       llvm_unreachable("Unknown branch opcode in Cond");
709     case AArch64::TBZW:
710     case AArch64::TBZX:
711       CC = AArch64CC::EQ;
712       break;
713     case AArch64::TBNZW:
714     case AArch64::TBNZX:
715       CC = AArch64CC::NE;
716       break;
717     }
718     // cmp reg, #foo is actually ands xzr, reg, #1<<foo.
719     if (Cond[1].getImm() == AArch64::TBZW || Cond[1].getImm() == AArch64::TBNZW)
720       BuildMI(MBB, I, DL, get(AArch64::ANDSWri), AArch64::WZR)
721           .addReg(Cond[2].getReg())
722           .addImm(
723               AArch64_AM::encodeLogicalImmediate(1ull << Cond[3].getImm(), 32));
724     else
725       BuildMI(MBB, I, DL, get(AArch64::ANDSXri), AArch64::XZR)
726           .addReg(Cond[2].getReg())
727           .addImm(
728               AArch64_AM::encodeLogicalImmediate(1ull << Cond[3].getImm(), 64));
729     break;
730   }
731   }
732 
733   unsigned Opc = 0;
734   const TargetRegisterClass *RC = nullptr;
735   bool TryFold = false;
736   if (MRI.constrainRegClass(DstReg, &AArch64::GPR64RegClass)) {
737     RC = &AArch64::GPR64RegClass;
738     Opc = AArch64::CSELXr;
739     TryFold = true;
740   } else if (MRI.constrainRegClass(DstReg, &AArch64::GPR32RegClass)) {
741     RC = &AArch64::GPR32RegClass;
742     Opc = AArch64::CSELWr;
743     TryFold = true;
744   } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR64RegClass)) {
745     RC = &AArch64::FPR64RegClass;
746     Opc = AArch64::FCSELDrrr;
747   } else if (MRI.constrainRegClass(DstReg, &AArch64::FPR32RegClass)) {
748     RC = &AArch64::FPR32RegClass;
749     Opc = AArch64::FCSELSrrr;
750   }
751   assert(RC && "Unsupported regclass");
752 
753   // Try folding simple instructions into the csel.
754   if (TryFold) {
755     unsigned NewVReg = 0;
756     unsigned FoldedOpc = canFoldIntoCSel(MRI, TrueReg, &NewVReg);
757     if (FoldedOpc) {
758       // The folded opcodes csinc, csinc and csneg apply the operation to
759       // FalseReg, so we need to invert the condition.
760       CC = AArch64CC::getInvertedCondCode(CC);
761       TrueReg = FalseReg;
762     } else
763       FoldedOpc = canFoldIntoCSel(MRI, FalseReg, &NewVReg);
764 
765     // Fold the operation. Leave any dead instructions for DCE to clean up.
766     if (FoldedOpc) {
767       FalseReg = NewVReg;
768       Opc = FoldedOpc;
769       // The extends the live range of NewVReg.
770       MRI.clearKillFlags(NewVReg);
771     }
772   }
773 
774   // Pull all virtual register into the appropriate class.
775   MRI.constrainRegClass(TrueReg, RC);
776   MRI.constrainRegClass(FalseReg, RC);
777 
778   // Insert the csel.
779   BuildMI(MBB, I, DL, get(Opc), DstReg)
780       .addReg(TrueReg)
781       .addReg(FalseReg)
782       .addImm(CC);
783 }
784 
785 /// Returns true if a MOVi32imm or MOVi64imm can be expanded to an  ORRxx.
786 static bool canBeExpandedToORR(const MachineInstr &MI, unsigned BitSize) {
787   uint64_t Imm = MI.getOperand(1).getImm();
788   uint64_t UImm = Imm << (64 - BitSize) >> (64 - BitSize);
789   uint64_t Encoding;
790   return AArch64_AM::processLogicalImmediate(UImm, BitSize, Encoding);
791 }
792 
793 // FIXME: this implementation should be micro-architecture dependent, so a
794 // micro-architecture target hook should be introduced here in future.
795 bool AArch64InstrInfo::isAsCheapAsAMove(const MachineInstr &MI) const {
796   if (!Subtarget.hasCustomCheapAsMoveHandling())
797     return MI.isAsCheapAsAMove();
798 
799   const unsigned Opcode = MI.getOpcode();
800 
801   // Firstly, check cases gated by features.
802 
803   if (Subtarget.hasZeroCycleZeroingFP()) {
804     if (Opcode == AArch64::FMOVH0 ||
805         Opcode == AArch64::FMOVS0 ||
806         Opcode == AArch64::FMOVD0)
807       return true;
808   }
809 
810   if (Subtarget.hasZeroCycleZeroingGP()) {
811     if (Opcode == TargetOpcode::COPY &&
812         (MI.getOperand(1).getReg() == AArch64::WZR ||
813          MI.getOperand(1).getReg() == AArch64::XZR))
814       return true;
815   }
816 
817   // Secondly, check cases specific to sub-targets.
818 
819   if (Subtarget.hasExynosCheapAsMoveHandling()) {
820     if (isExynosCheapAsMove(MI))
821       return true;
822 
823     return MI.isAsCheapAsAMove();
824   }
825 
826   // Finally, check generic cases.
827 
828   switch (Opcode) {
829   default:
830     return false;
831 
832   // add/sub on register without shift
833   case AArch64::ADDWri:
834   case AArch64::ADDXri:
835   case AArch64::SUBWri:
836   case AArch64::SUBXri:
837     return (MI.getOperand(3).getImm() == 0);
838 
839   // logical ops on immediate
840   case AArch64::ANDWri:
841   case AArch64::ANDXri:
842   case AArch64::EORWri:
843   case AArch64::EORXri:
844   case AArch64::ORRWri:
845   case AArch64::ORRXri:
846     return true;
847 
848   // logical ops on register without shift
849   case AArch64::ANDWrr:
850   case AArch64::ANDXrr:
851   case AArch64::BICWrr:
852   case AArch64::BICXrr:
853   case AArch64::EONWrr:
854   case AArch64::EONXrr:
855   case AArch64::EORWrr:
856   case AArch64::EORXrr:
857   case AArch64::ORNWrr:
858   case AArch64::ORNXrr:
859   case AArch64::ORRWrr:
860   case AArch64::ORRXrr:
861     return true;
862 
863   // If MOVi32imm or MOVi64imm can be expanded into ORRWri or
864   // ORRXri, it is as cheap as MOV
865   case AArch64::MOVi32imm:
866     return canBeExpandedToORR(MI, 32);
867   case AArch64::MOVi64imm:
868     return canBeExpandedToORR(MI, 64);
869   }
870 
871   llvm_unreachable("Unknown opcode to check as cheap as a move!");
872 }
873 
874 bool AArch64InstrInfo::isFalkorShiftExtFast(const MachineInstr &MI) {
875   switch (MI.getOpcode()) {
876   default:
877     return false;
878 
879   case AArch64::ADDWrs:
880   case AArch64::ADDXrs:
881   case AArch64::ADDSWrs:
882   case AArch64::ADDSXrs: {
883     unsigned Imm = MI.getOperand(3).getImm();
884     unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
885     if (ShiftVal == 0)
886       return true;
887     return AArch64_AM::getShiftType(Imm) == AArch64_AM::LSL && ShiftVal <= 5;
888   }
889 
890   case AArch64::ADDWrx:
891   case AArch64::ADDXrx:
892   case AArch64::ADDXrx64:
893   case AArch64::ADDSWrx:
894   case AArch64::ADDSXrx:
895   case AArch64::ADDSXrx64: {
896     unsigned Imm = MI.getOperand(3).getImm();
897     switch (AArch64_AM::getArithExtendType(Imm)) {
898     default:
899       return false;
900     case AArch64_AM::UXTB:
901     case AArch64_AM::UXTH:
902     case AArch64_AM::UXTW:
903     case AArch64_AM::UXTX:
904       return AArch64_AM::getArithShiftValue(Imm) <= 4;
905     }
906   }
907 
908   case AArch64::SUBWrs:
909   case AArch64::SUBSWrs: {
910     unsigned Imm = MI.getOperand(3).getImm();
911     unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
912     return ShiftVal == 0 ||
913            (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 31);
914   }
915 
916   case AArch64::SUBXrs:
917   case AArch64::SUBSXrs: {
918     unsigned Imm = MI.getOperand(3).getImm();
919     unsigned ShiftVal = AArch64_AM::getShiftValue(Imm);
920     return ShiftVal == 0 ||
921            (AArch64_AM::getShiftType(Imm) == AArch64_AM::ASR && ShiftVal == 63);
922   }
923 
924   case AArch64::SUBWrx:
925   case AArch64::SUBXrx:
926   case AArch64::SUBXrx64:
927   case AArch64::SUBSWrx:
928   case AArch64::SUBSXrx:
929   case AArch64::SUBSXrx64: {
930     unsigned Imm = MI.getOperand(3).getImm();
931     switch (AArch64_AM::getArithExtendType(Imm)) {
932     default:
933       return false;
934     case AArch64_AM::UXTB:
935     case AArch64_AM::UXTH:
936     case AArch64_AM::UXTW:
937     case AArch64_AM::UXTX:
938       return AArch64_AM::getArithShiftValue(Imm) == 0;
939     }
940   }
941 
942   case AArch64::LDRBBroW:
943   case AArch64::LDRBBroX:
944   case AArch64::LDRBroW:
945   case AArch64::LDRBroX:
946   case AArch64::LDRDroW:
947   case AArch64::LDRDroX:
948   case AArch64::LDRHHroW:
949   case AArch64::LDRHHroX:
950   case AArch64::LDRHroW:
951   case AArch64::LDRHroX:
952   case AArch64::LDRQroW:
953   case AArch64::LDRQroX:
954   case AArch64::LDRSBWroW:
955   case AArch64::LDRSBWroX:
956   case AArch64::LDRSBXroW:
957   case AArch64::LDRSBXroX:
958   case AArch64::LDRSHWroW:
959   case AArch64::LDRSHWroX:
960   case AArch64::LDRSHXroW:
961   case AArch64::LDRSHXroX:
962   case AArch64::LDRSWroW:
963   case AArch64::LDRSWroX:
964   case AArch64::LDRSroW:
965   case AArch64::LDRSroX:
966   case AArch64::LDRWroW:
967   case AArch64::LDRWroX:
968   case AArch64::LDRXroW:
969   case AArch64::LDRXroX:
970   case AArch64::PRFMroW:
971   case AArch64::PRFMroX:
972   case AArch64::STRBBroW:
973   case AArch64::STRBBroX:
974   case AArch64::STRBroW:
975   case AArch64::STRBroX:
976   case AArch64::STRDroW:
977   case AArch64::STRDroX:
978   case AArch64::STRHHroW:
979   case AArch64::STRHHroX:
980   case AArch64::STRHroW:
981   case AArch64::STRHroX:
982   case AArch64::STRQroW:
983   case AArch64::STRQroX:
984   case AArch64::STRSroW:
985   case AArch64::STRSroX:
986   case AArch64::STRWroW:
987   case AArch64::STRWroX:
988   case AArch64::STRXroW:
989   case AArch64::STRXroX: {
990     unsigned IsSigned = MI.getOperand(3).getImm();
991     return !IsSigned;
992   }
993   }
994 }
995 
996 bool AArch64InstrInfo::isSEHInstruction(const MachineInstr &MI) {
997   unsigned Opc = MI.getOpcode();
998   switch (Opc) {
999     default:
1000       return false;
1001     case AArch64::SEH_StackAlloc:
1002     case AArch64::SEH_SaveFPLR:
1003     case AArch64::SEH_SaveFPLR_X:
1004     case AArch64::SEH_SaveReg:
1005     case AArch64::SEH_SaveReg_X:
1006     case AArch64::SEH_SaveRegP:
1007     case AArch64::SEH_SaveRegP_X:
1008     case AArch64::SEH_SaveFReg:
1009     case AArch64::SEH_SaveFReg_X:
1010     case AArch64::SEH_SaveFRegP:
1011     case AArch64::SEH_SaveFRegP_X:
1012     case AArch64::SEH_SetFP:
1013     case AArch64::SEH_AddFP:
1014     case AArch64::SEH_Nop:
1015     case AArch64::SEH_PrologEnd:
1016     case AArch64::SEH_EpilogStart:
1017     case AArch64::SEH_EpilogEnd:
1018       return true;
1019   }
1020 }
1021 
1022 bool AArch64InstrInfo::isCoalescableExtInstr(const MachineInstr &MI,
1023                                              Register &SrcReg, Register &DstReg,
1024                                              unsigned &SubIdx) const {
1025   switch (MI.getOpcode()) {
1026   default:
1027     return false;
1028   case AArch64::SBFMXri: // aka sxtw
1029   case AArch64::UBFMXri: // aka uxtw
1030     // Check for the 32 -> 64 bit extension case, these instructions can do
1031     // much more.
1032     if (MI.getOperand(2).getImm() != 0 || MI.getOperand(3).getImm() != 31)
1033       return false;
1034     // This is a signed or unsigned 32 -> 64 bit extension.
1035     SrcReg = MI.getOperand(1).getReg();
1036     DstReg = MI.getOperand(0).getReg();
1037     SubIdx = AArch64::sub_32;
1038     return true;
1039   }
1040 }
1041 
1042 bool AArch64InstrInfo::areMemAccessesTriviallyDisjoint(
1043     const MachineInstr &MIa, const MachineInstr &MIb) const {
1044   const TargetRegisterInfo *TRI = &getRegisterInfo();
1045   const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr;
1046   int64_t OffsetA = 0, OffsetB = 0;
1047   unsigned WidthA = 0, WidthB = 0;
1048   bool OffsetAIsScalable = false, OffsetBIsScalable = false;
1049 
1050   assert(MIa.mayLoadOrStore() && "MIa must be a load or store.");
1051   assert(MIb.mayLoadOrStore() && "MIb must be a load or store.");
1052 
1053   if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() ||
1054       MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef())
1055     return false;
1056 
1057   // Retrieve the base, offset from the base and width. Width
1058   // is the size of memory that is being loaded/stored (e.g. 1, 2, 4, 8).  If
1059   // base are identical, and the offset of a lower memory access +
1060   // the width doesn't overlap the offset of a higher memory access,
1061   // then the memory accesses are different.
1062   // If OffsetAIsScalable and OffsetBIsScalable are both true, they
1063   // are assumed to have the same scale (vscale).
1064   if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, OffsetAIsScalable,
1065                                    WidthA, TRI) &&
1066       getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, OffsetBIsScalable,
1067                                    WidthB, TRI)) {
1068     if (BaseOpA->isIdenticalTo(*BaseOpB) &&
1069         OffsetAIsScalable == OffsetBIsScalable) {
1070       int LowOffset = OffsetA < OffsetB ? OffsetA : OffsetB;
1071       int HighOffset = OffsetA < OffsetB ? OffsetB : OffsetA;
1072       int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB;
1073       if (LowOffset + LowWidth <= HighOffset)
1074         return true;
1075     }
1076   }
1077   return false;
1078 }
1079 
1080 bool AArch64InstrInfo::isSchedulingBoundary(const MachineInstr &MI,
1081                                             const MachineBasicBlock *MBB,
1082                                             const MachineFunction &MF) const {
1083   if (TargetInstrInfo::isSchedulingBoundary(MI, MBB, MF))
1084     return true;
1085   switch (MI.getOpcode()) {
1086   case AArch64::HINT:
1087     // CSDB hints are scheduling barriers.
1088     if (MI.getOperand(0).getImm() == 0x14)
1089       return true;
1090     break;
1091   case AArch64::DSB:
1092   case AArch64::ISB:
1093     // DSB and ISB also are scheduling barriers.
1094     return true;
1095   default:;
1096   }
1097   return isSEHInstruction(MI);
1098 }
1099 
1100 /// analyzeCompare - For a comparison instruction, return the source registers
1101 /// in SrcReg and SrcReg2, and the value it compares against in CmpValue.
1102 /// Return true if the comparison instruction can be analyzed.
1103 bool AArch64InstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg,
1104                                       Register &SrcReg2, int64_t &CmpMask,
1105                                       int64_t &CmpValue) const {
1106   // The first operand can be a frame index where we'd normally expect a
1107   // register.
1108   assert(MI.getNumOperands() >= 2 && "All AArch64 cmps should have 2 operands");
1109   if (!MI.getOperand(1).isReg())
1110     return false;
1111 
1112   switch (MI.getOpcode()) {
1113   default:
1114     break;
1115   case AArch64::PTEST_PP:
1116     SrcReg = MI.getOperand(0).getReg();
1117     SrcReg2 = MI.getOperand(1).getReg();
1118     // Not sure about the mask and value for now...
1119     CmpMask = ~0;
1120     CmpValue = 0;
1121     return true;
1122   case AArch64::SUBSWrr:
1123   case AArch64::SUBSWrs:
1124   case AArch64::SUBSWrx:
1125   case AArch64::SUBSXrr:
1126   case AArch64::SUBSXrs:
1127   case AArch64::SUBSXrx:
1128   case AArch64::ADDSWrr:
1129   case AArch64::ADDSWrs:
1130   case AArch64::ADDSWrx:
1131   case AArch64::ADDSXrr:
1132   case AArch64::ADDSXrs:
1133   case AArch64::ADDSXrx:
1134     // Replace SUBSWrr with SUBWrr if NZCV is not used.
1135     SrcReg = MI.getOperand(1).getReg();
1136     SrcReg2 = MI.getOperand(2).getReg();
1137     CmpMask = ~0;
1138     CmpValue = 0;
1139     return true;
1140   case AArch64::SUBSWri:
1141   case AArch64::ADDSWri:
1142   case AArch64::SUBSXri:
1143   case AArch64::ADDSXri:
1144     SrcReg = MI.getOperand(1).getReg();
1145     SrcReg2 = 0;
1146     CmpMask = ~0;
1147     CmpValue = MI.getOperand(2).getImm();
1148     return true;
1149   case AArch64::ANDSWri:
1150   case AArch64::ANDSXri:
1151     // ANDS does not use the same encoding scheme as the others xxxS
1152     // instructions.
1153     SrcReg = MI.getOperand(1).getReg();
1154     SrcReg2 = 0;
1155     CmpMask = ~0;
1156     CmpValue = AArch64_AM::decodeLogicalImmediate(
1157                    MI.getOperand(2).getImm(),
1158                    MI.getOpcode() == AArch64::ANDSWri ? 32 : 64);
1159     return true;
1160   }
1161 
1162   return false;
1163 }
1164 
1165 static bool UpdateOperandRegClass(MachineInstr &Instr) {
1166   MachineBasicBlock *MBB = Instr.getParent();
1167   assert(MBB && "Can't get MachineBasicBlock here");
1168   MachineFunction *MF = MBB->getParent();
1169   assert(MF && "Can't get MachineFunction here");
1170   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
1171   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
1172   MachineRegisterInfo *MRI = &MF->getRegInfo();
1173 
1174   for (unsigned OpIdx = 0, EndIdx = Instr.getNumOperands(); OpIdx < EndIdx;
1175        ++OpIdx) {
1176     MachineOperand &MO = Instr.getOperand(OpIdx);
1177     const TargetRegisterClass *OpRegCstraints =
1178         Instr.getRegClassConstraint(OpIdx, TII, TRI);
1179 
1180     // If there's no constraint, there's nothing to do.
1181     if (!OpRegCstraints)
1182       continue;
1183     // If the operand is a frame index, there's nothing to do here.
1184     // A frame index operand will resolve correctly during PEI.
1185     if (MO.isFI())
1186       continue;
1187 
1188     assert(MO.isReg() &&
1189            "Operand has register constraints without being a register!");
1190 
1191     Register Reg = MO.getReg();
1192     if (Register::isPhysicalRegister(Reg)) {
1193       if (!OpRegCstraints->contains(Reg))
1194         return false;
1195     } else if (!OpRegCstraints->hasSubClassEq(MRI->getRegClass(Reg)) &&
1196                !MRI->constrainRegClass(Reg, OpRegCstraints))
1197       return false;
1198   }
1199 
1200   return true;
1201 }
1202 
1203 /// Return the opcode that does not set flags when possible - otherwise
1204 /// return the original opcode. The caller is responsible to do the actual
1205 /// substitution and legality checking.
1206 static unsigned convertToNonFlagSettingOpc(const MachineInstr &MI) {
1207   // Don't convert all compare instructions, because for some the zero register
1208   // encoding becomes the sp register.
1209   bool MIDefinesZeroReg = false;
1210   if (MI.definesRegister(AArch64::WZR) || MI.definesRegister(AArch64::XZR))
1211     MIDefinesZeroReg = true;
1212 
1213   switch (MI.getOpcode()) {
1214   default:
1215     return MI.getOpcode();
1216   case AArch64::ADDSWrr:
1217     return AArch64::ADDWrr;
1218   case AArch64::ADDSWri:
1219     return MIDefinesZeroReg ? AArch64::ADDSWri : AArch64::ADDWri;
1220   case AArch64::ADDSWrs:
1221     return MIDefinesZeroReg ? AArch64::ADDSWrs : AArch64::ADDWrs;
1222   case AArch64::ADDSWrx:
1223     return AArch64::ADDWrx;
1224   case AArch64::ADDSXrr:
1225     return AArch64::ADDXrr;
1226   case AArch64::ADDSXri:
1227     return MIDefinesZeroReg ? AArch64::ADDSXri : AArch64::ADDXri;
1228   case AArch64::ADDSXrs:
1229     return MIDefinesZeroReg ? AArch64::ADDSXrs : AArch64::ADDXrs;
1230   case AArch64::ADDSXrx:
1231     return AArch64::ADDXrx;
1232   case AArch64::SUBSWrr:
1233     return AArch64::SUBWrr;
1234   case AArch64::SUBSWri:
1235     return MIDefinesZeroReg ? AArch64::SUBSWri : AArch64::SUBWri;
1236   case AArch64::SUBSWrs:
1237     return MIDefinesZeroReg ? AArch64::SUBSWrs : AArch64::SUBWrs;
1238   case AArch64::SUBSWrx:
1239     return AArch64::SUBWrx;
1240   case AArch64::SUBSXrr:
1241     return AArch64::SUBXrr;
1242   case AArch64::SUBSXri:
1243     return MIDefinesZeroReg ? AArch64::SUBSXri : AArch64::SUBXri;
1244   case AArch64::SUBSXrs:
1245     return MIDefinesZeroReg ? AArch64::SUBSXrs : AArch64::SUBXrs;
1246   case AArch64::SUBSXrx:
1247     return AArch64::SUBXrx;
1248   }
1249 }
1250 
1251 enum AccessKind { AK_Write = 0x01, AK_Read = 0x10, AK_All = 0x11 };
1252 
1253 /// True when condition flags are accessed (either by writing or reading)
1254 /// on the instruction trace starting at From and ending at To.
1255 ///
1256 /// Note: If From and To are from different blocks it's assumed CC are accessed
1257 ///       on the path.
1258 static bool areCFlagsAccessedBetweenInstrs(
1259     MachineBasicBlock::iterator From, MachineBasicBlock::iterator To,
1260     const TargetRegisterInfo *TRI, const AccessKind AccessToCheck = AK_All) {
1261   // Early exit if To is at the beginning of the BB.
1262   if (To == To->getParent()->begin())
1263     return true;
1264 
1265   // Check whether the instructions are in the same basic block
1266   // If not, assume the condition flags might get modified somewhere.
1267   if (To->getParent() != From->getParent())
1268     return true;
1269 
1270   // From must be above To.
1271   assert(std::any_of(
1272       ++To.getReverse(), To->getParent()->rend(),
1273       [From](MachineInstr &MI) { return MI.getIterator() == From; }));
1274 
1275   // We iterate backward starting at \p To until we hit \p From.
1276   for (const MachineInstr &Instr :
1277        instructionsWithoutDebug(++To.getReverse(), From.getReverse())) {
1278     if (((AccessToCheck & AK_Write) &&
1279          Instr.modifiesRegister(AArch64::NZCV, TRI)) ||
1280         ((AccessToCheck & AK_Read) && Instr.readsRegister(AArch64::NZCV, TRI)))
1281       return true;
1282   }
1283   return false;
1284 }
1285 
1286 /// optimizePTestInstr - Attempt to remove a ptest of a predicate-generating
1287 /// operation which could set the flags in an identical manner
1288 bool AArch64InstrInfo::optimizePTestInstr(
1289     MachineInstr *PTest, unsigned MaskReg, unsigned PredReg,
1290     const MachineRegisterInfo *MRI) const {
1291   auto *Mask = MRI->getUniqueVRegDef(MaskReg);
1292   auto *Pred = MRI->getUniqueVRegDef(PredReg);
1293   auto NewOp = Pred->getOpcode();
1294   bool OpChanged = false;
1295 
1296   unsigned MaskOpcode = Mask->getOpcode();
1297   unsigned PredOpcode = Pred->getOpcode();
1298   bool PredIsPTestLike = isPTestLikeOpcode(PredOpcode);
1299   bool PredIsWhileLike = isWhileOpcode(PredOpcode);
1300 
1301   if (isPTrueOpcode(MaskOpcode) && (PredIsPTestLike || PredIsWhileLike)) {
1302     // For PTEST(PTRUE, OTHER_INST), PTEST is redundant when PTRUE doesn't
1303     // deactivate any lanes OTHER_INST might set.
1304     uint64_t MaskElementSize = getElementSizeForOpcode(MaskOpcode);
1305     uint64_t PredElementSize = getElementSizeForOpcode(PredOpcode);
1306 
1307     // Must be an all active predicate of matching element size.
1308     if ((PredElementSize != MaskElementSize) ||
1309         (Mask->getOperand(1).getImm() != 31))
1310       return false;
1311 
1312     // Fallthough to simply remove the PTEST.
1313   } else if ((Mask == Pred) && (PredIsPTestLike || PredIsWhileLike)) {
1314     // For PTEST(PG, PG), PTEST is redundant when PG is the result of an
1315     // instruction that sets the flags as PTEST would.
1316 
1317     // Fallthough to simply remove the PTEST.
1318   } else if (PredIsPTestLike) {
1319     // For PTEST(PG_1, PTEST_LIKE(PG2, ...)), PTEST is redundant when both
1320     // instructions use the same predicate.
1321     auto PTestLikeMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1322     if (Mask != PTestLikeMask)
1323       return false;
1324 
1325     // Fallthough to simply remove the PTEST.
1326   } else {
1327     switch (Pred->getOpcode()) {
1328     case AArch64::BRKB_PPzP:
1329     case AArch64::BRKPB_PPzPP: {
1330       // Op 0 is chain, 1 is the mask, 2 the previous predicate to
1331       // propagate, 3 the new predicate.
1332 
1333       // Check to see if our mask is the same as the brkpb's. If
1334       // not the resulting flag bits may be different and we
1335       // can't remove the ptest.
1336       auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1337       if (Mask != PredMask)
1338         return false;
1339 
1340       // Switch to the new opcode
1341       NewOp = Pred->getOpcode() == AArch64::BRKB_PPzP ? AArch64::BRKBS_PPzP
1342                                                       : AArch64::BRKPBS_PPzPP;
1343       OpChanged = true;
1344       break;
1345     }
1346     case AArch64::BRKN_PPzP: {
1347       auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1348       if (Mask != PredMask)
1349         return false;
1350 
1351       NewOp = AArch64::BRKNS_PPzP;
1352       OpChanged = true;
1353       break;
1354     }
1355     case AArch64::RDFFR_PPz: {
1356       // rdffr   p1.b, PredMask=p0/z <--- Definition of Pred
1357       // ptest   Mask=p0, Pred=p1.b  <--- If equal masks, remove this and use
1358       //                                  `rdffrs p1.b, p0/z` above.
1359       auto *PredMask = MRI->getUniqueVRegDef(Pred->getOperand(1).getReg());
1360       if (Mask != PredMask)
1361         return false;
1362 
1363       NewOp = AArch64::RDFFRS_PPz;
1364       OpChanged = true;
1365       break;
1366     }
1367     default:
1368       // Bail out if we don't recognize the input
1369       return false;
1370     }
1371   }
1372 
1373   const TargetRegisterInfo *TRI = &getRegisterInfo();
1374 
1375   // If another instruction between Pred and PTest accesses flags, don't remove
1376   // the ptest or update the earlier instruction to modify them.
1377   if (areCFlagsAccessedBetweenInstrs(Pred, PTest, TRI))
1378     return false;
1379 
1380   // If we pass all the checks, it's safe to remove the PTEST and use the flags
1381   // as they are prior to PTEST. Sometimes this requires the tested PTEST
1382   // operand to be replaced with an equivalent instruction that also sets the
1383   // flags.
1384   Pred->setDesc(get(NewOp));
1385   PTest->eraseFromParent();
1386   if (OpChanged) {
1387     bool succeeded = UpdateOperandRegClass(*Pred);
1388     (void)succeeded;
1389     assert(succeeded && "Operands have incompatible register classes!");
1390     Pred->addRegisterDefined(AArch64::NZCV, TRI);
1391   }
1392 
1393   // Ensure that the flags def is live.
1394   if (Pred->registerDefIsDead(AArch64::NZCV, TRI)) {
1395     unsigned i = 0, e = Pred->getNumOperands();
1396     for (; i != e; ++i) {
1397       MachineOperand &MO = Pred->getOperand(i);
1398       if (MO.isReg() && MO.isDef() && MO.getReg() == AArch64::NZCV) {
1399         MO.setIsDead(false);
1400         break;
1401       }
1402     }
1403   }
1404   return true;
1405 }
1406 
1407 /// Try to optimize a compare instruction. A compare instruction is an
1408 /// instruction which produces AArch64::NZCV. It can be truly compare
1409 /// instruction
1410 /// when there are no uses of its destination register.
1411 ///
1412 /// The following steps are tried in order:
1413 /// 1. Convert CmpInstr into an unconditional version.
1414 /// 2. Remove CmpInstr if above there is an instruction producing a needed
1415 ///    condition code or an instruction which can be converted into such an
1416 ///    instruction.
1417 ///    Only comparison with zero is supported.
1418 bool AArch64InstrInfo::optimizeCompareInstr(
1419     MachineInstr &CmpInstr, Register SrcReg, Register SrcReg2, int64_t CmpMask,
1420     int64_t CmpValue, const MachineRegisterInfo *MRI) const {
1421   assert(CmpInstr.getParent());
1422   assert(MRI);
1423 
1424   // Replace SUBSWrr with SUBWrr if NZCV is not used.
1425   int DeadNZCVIdx = CmpInstr.findRegisterDefOperandIdx(AArch64::NZCV, true);
1426   if (DeadNZCVIdx != -1) {
1427     if (CmpInstr.definesRegister(AArch64::WZR) ||
1428         CmpInstr.definesRegister(AArch64::XZR)) {
1429       CmpInstr.eraseFromParent();
1430       return true;
1431     }
1432     unsigned Opc = CmpInstr.getOpcode();
1433     unsigned NewOpc = convertToNonFlagSettingOpc(CmpInstr);
1434     if (NewOpc == Opc)
1435       return false;
1436     const MCInstrDesc &MCID = get(NewOpc);
1437     CmpInstr.setDesc(MCID);
1438     CmpInstr.RemoveOperand(DeadNZCVIdx);
1439     bool succeeded = UpdateOperandRegClass(CmpInstr);
1440     (void)succeeded;
1441     assert(succeeded && "Some operands reg class are incompatible!");
1442     return true;
1443   }
1444 
1445   if (CmpInstr.getOpcode() == AArch64::PTEST_PP)
1446     return optimizePTestInstr(&CmpInstr, SrcReg, SrcReg2, MRI);
1447 
1448   if (SrcReg2 != 0)
1449     return false;
1450 
1451   // CmpInstr is a Compare instruction if destination register is not used.
1452   if (!MRI->use_nodbg_empty(CmpInstr.getOperand(0).getReg()))
1453     return false;
1454 
1455   if (CmpValue == 0 && substituteCmpToZero(CmpInstr, SrcReg, *MRI))
1456     return true;
1457   return (CmpValue == 0 || CmpValue == 1) &&
1458          removeCmpToZeroOrOne(CmpInstr, SrcReg, CmpValue, *MRI);
1459 }
1460 
1461 /// Get opcode of S version of Instr.
1462 /// If Instr is S version its opcode is returned.
1463 /// AArch64::INSTRUCTION_LIST_END is returned if Instr does not have S version
1464 /// or we are not interested in it.
1465 static unsigned sForm(MachineInstr &Instr) {
1466   switch (Instr.getOpcode()) {
1467   default:
1468     return AArch64::INSTRUCTION_LIST_END;
1469 
1470   case AArch64::ADDSWrr:
1471   case AArch64::ADDSWri:
1472   case AArch64::ADDSXrr:
1473   case AArch64::ADDSXri:
1474   case AArch64::SUBSWrr:
1475   case AArch64::SUBSWri:
1476   case AArch64::SUBSXrr:
1477   case AArch64::SUBSXri:
1478     return Instr.getOpcode();
1479 
1480   case AArch64::ADDWrr:
1481     return AArch64::ADDSWrr;
1482   case AArch64::ADDWri:
1483     return AArch64::ADDSWri;
1484   case AArch64::ADDXrr:
1485     return AArch64::ADDSXrr;
1486   case AArch64::ADDXri:
1487     return AArch64::ADDSXri;
1488   case AArch64::ADCWr:
1489     return AArch64::ADCSWr;
1490   case AArch64::ADCXr:
1491     return AArch64::ADCSXr;
1492   case AArch64::SUBWrr:
1493     return AArch64::SUBSWrr;
1494   case AArch64::SUBWri:
1495     return AArch64::SUBSWri;
1496   case AArch64::SUBXrr:
1497     return AArch64::SUBSXrr;
1498   case AArch64::SUBXri:
1499     return AArch64::SUBSXri;
1500   case AArch64::SBCWr:
1501     return AArch64::SBCSWr;
1502   case AArch64::SBCXr:
1503     return AArch64::SBCSXr;
1504   case AArch64::ANDWri:
1505     return AArch64::ANDSWri;
1506   case AArch64::ANDXri:
1507     return AArch64::ANDSXri;
1508   }
1509 }
1510 
1511 /// Check if AArch64::NZCV should be alive in successors of MBB.
1512 static bool areCFlagsAliveInSuccessors(const MachineBasicBlock *MBB) {
1513   for (auto *BB : MBB->successors())
1514     if (BB->isLiveIn(AArch64::NZCV))
1515       return true;
1516   return false;
1517 }
1518 
1519 /// \returns The condition code operand index for \p Instr if it is a branch
1520 /// or select and -1 otherwise.
1521 static int
1522 findCondCodeUseOperandIdxForBranchOrSelect(const MachineInstr &Instr) {
1523   switch (Instr.getOpcode()) {
1524   default:
1525     return -1;
1526 
1527   case AArch64::Bcc: {
1528     int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV);
1529     assert(Idx >= 2);
1530     return Idx - 2;
1531   }
1532 
1533   case AArch64::CSINVWr:
1534   case AArch64::CSINVXr:
1535   case AArch64::CSINCWr:
1536   case AArch64::CSINCXr:
1537   case AArch64::CSELWr:
1538   case AArch64::CSELXr:
1539   case AArch64::CSNEGWr:
1540   case AArch64::CSNEGXr:
1541   case AArch64::FCSELSrrr:
1542   case AArch64::FCSELDrrr: {
1543     int Idx = Instr.findRegisterUseOperandIdx(AArch64::NZCV);
1544     assert(Idx >= 1);
1545     return Idx - 1;
1546   }
1547   }
1548 }
1549 
1550 namespace {
1551 
1552 struct UsedNZCV {
1553   bool N = false;
1554   bool Z = false;
1555   bool C = false;
1556   bool V = false;
1557 
1558   UsedNZCV() = default;
1559 
1560   UsedNZCV &operator|=(const UsedNZCV &UsedFlags) {
1561     this->N |= UsedFlags.N;
1562     this->Z |= UsedFlags.Z;
1563     this->C |= UsedFlags.C;
1564     this->V |= UsedFlags.V;
1565     return *this;
1566   }
1567 };
1568 
1569 } // end anonymous namespace
1570 
1571 /// Find a condition code used by the instruction.
1572 /// Returns AArch64CC::Invalid if either the instruction does not use condition
1573 /// codes or we don't optimize CmpInstr in the presence of such instructions.
1574 static AArch64CC::CondCode findCondCodeUsedByInstr(const MachineInstr &Instr) {
1575   int CCIdx = findCondCodeUseOperandIdxForBranchOrSelect(Instr);
1576   return CCIdx >= 0 ? static_cast<AArch64CC::CondCode>(
1577                           Instr.getOperand(CCIdx).getImm())
1578                     : AArch64CC::Invalid;
1579 }
1580 
1581 static UsedNZCV getUsedNZCV(AArch64CC::CondCode CC) {
1582   assert(CC != AArch64CC::Invalid);
1583   UsedNZCV UsedFlags;
1584   switch (CC) {
1585   default:
1586     break;
1587 
1588   case AArch64CC::EQ: // Z set
1589   case AArch64CC::NE: // Z clear
1590     UsedFlags.Z = true;
1591     break;
1592 
1593   case AArch64CC::HI: // Z clear and C set
1594   case AArch64CC::LS: // Z set   or  C clear
1595     UsedFlags.Z = true;
1596     LLVM_FALLTHROUGH;
1597   case AArch64CC::HS: // C set
1598   case AArch64CC::LO: // C clear
1599     UsedFlags.C = true;
1600     break;
1601 
1602   case AArch64CC::MI: // N set
1603   case AArch64CC::PL: // N clear
1604     UsedFlags.N = true;
1605     break;
1606 
1607   case AArch64CC::VS: // V set
1608   case AArch64CC::VC: // V clear
1609     UsedFlags.V = true;
1610     break;
1611 
1612   case AArch64CC::GT: // Z clear, N and V the same
1613   case AArch64CC::LE: // Z set,   N and V differ
1614     UsedFlags.Z = true;
1615     LLVM_FALLTHROUGH;
1616   case AArch64CC::GE: // N and V the same
1617   case AArch64CC::LT: // N and V differ
1618     UsedFlags.N = true;
1619     UsedFlags.V = true;
1620     break;
1621   }
1622   return UsedFlags;
1623 }
1624 
1625 /// \returns Conditions flags used after \p CmpInstr in its MachineBB if they
1626 /// are not containing C or V flags and NZCV flags are not alive in successors
1627 /// of the same \p CmpInstr and \p MI parent. \returns None otherwise.
1628 ///
1629 /// Collect instructions using that flags in \p CCUseInstrs if provided.
1630 static Optional<UsedNZCV>
1631 examineCFlagsUse(MachineInstr &MI, MachineInstr &CmpInstr,
1632                  const TargetRegisterInfo &TRI,
1633                  SmallVectorImpl<MachineInstr *> *CCUseInstrs = nullptr) {
1634   MachineBasicBlock *CmpParent = CmpInstr.getParent();
1635   if (MI.getParent() != CmpParent)
1636     return None;
1637 
1638   if (areCFlagsAliveInSuccessors(CmpParent))
1639     return None;
1640 
1641   UsedNZCV NZCVUsedAfterCmp;
1642   for (MachineInstr &Instr : instructionsWithoutDebug(
1643            std::next(CmpInstr.getIterator()), CmpParent->instr_end())) {
1644     if (Instr.readsRegister(AArch64::NZCV, &TRI)) {
1645       AArch64CC::CondCode CC = findCondCodeUsedByInstr(Instr);
1646       if (CC == AArch64CC::Invalid) // Unsupported conditional instruction
1647         return None;
1648       NZCVUsedAfterCmp |= getUsedNZCV(CC);
1649       if (CCUseInstrs)
1650         CCUseInstrs->push_back(&Instr);
1651     }
1652     if (Instr.modifiesRegister(AArch64::NZCV, &TRI))
1653       break;
1654   }
1655   if (NZCVUsedAfterCmp.C || NZCVUsedAfterCmp.V)
1656     return None;
1657   return NZCVUsedAfterCmp;
1658 }
1659 
1660 static bool isADDSRegImm(unsigned Opcode) {
1661   return Opcode == AArch64::ADDSWri || Opcode == AArch64::ADDSXri;
1662 }
1663 
1664 static bool isSUBSRegImm(unsigned Opcode) {
1665   return Opcode == AArch64::SUBSWri || Opcode == AArch64::SUBSXri;
1666 }
1667 
1668 /// Check if CmpInstr can be substituted by MI.
1669 ///
1670 /// CmpInstr can be substituted:
1671 /// - CmpInstr is either 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
1672 /// - and, MI and CmpInstr are from the same MachineBB
1673 /// - and, condition flags are not alive in successors of the CmpInstr parent
1674 /// - and, if MI opcode is the S form there must be no defs of flags between
1675 ///        MI and CmpInstr
1676 ///        or if MI opcode is not the S form there must be neither defs of flags
1677 ///        nor uses of flags between MI and CmpInstr.
1678 /// - and  C/V flags are not used after CmpInstr
1679 static bool canInstrSubstituteCmpInstr(MachineInstr &MI, MachineInstr &CmpInstr,
1680                                        const TargetRegisterInfo &TRI) {
1681   assert(sForm(MI) != AArch64::INSTRUCTION_LIST_END);
1682 
1683   const unsigned CmpOpcode = CmpInstr.getOpcode();
1684   if (!isADDSRegImm(CmpOpcode) && !isSUBSRegImm(CmpOpcode))
1685     return false;
1686 
1687   if (!examineCFlagsUse(MI, CmpInstr, TRI))
1688     return false;
1689 
1690   AccessKind AccessToCheck = AK_Write;
1691   if (sForm(MI) != MI.getOpcode())
1692     AccessToCheck = AK_All;
1693   return !areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AccessToCheck);
1694 }
1695 
1696 /// Substitute an instruction comparing to zero with another instruction
1697 /// which produces needed condition flags.
1698 ///
1699 /// Return true on success.
1700 bool AArch64InstrInfo::substituteCmpToZero(
1701     MachineInstr &CmpInstr, unsigned SrcReg,
1702     const MachineRegisterInfo &MRI) const {
1703   // Get the unique definition of SrcReg.
1704   MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
1705   if (!MI)
1706     return false;
1707 
1708   const TargetRegisterInfo &TRI = getRegisterInfo();
1709 
1710   unsigned NewOpc = sForm(*MI);
1711   if (NewOpc == AArch64::INSTRUCTION_LIST_END)
1712     return false;
1713 
1714   if (!canInstrSubstituteCmpInstr(*MI, CmpInstr, TRI))
1715     return false;
1716 
1717   // Update the instruction to set NZCV.
1718   MI->setDesc(get(NewOpc));
1719   CmpInstr.eraseFromParent();
1720   bool succeeded = UpdateOperandRegClass(*MI);
1721   (void)succeeded;
1722   assert(succeeded && "Some operands reg class are incompatible!");
1723   MI->addRegisterDefined(AArch64::NZCV, &TRI);
1724   return true;
1725 }
1726 
1727 /// \returns True if \p CmpInstr can be removed.
1728 ///
1729 /// \p IsInvertCC is true if, after removing \p CmpInstr, condition
1730 /// codes used in \p CCUseInstrs must be inverted.
1731 static bool canCmpInstrBeRemoved(MachineInstr &MI, MachineInstr &CmpInstr,
1732                                  int CmpValue, const TargetRegisterInfo &TRI,
1733                                  SmallVectorImpl<MachineInstr *> &CCUseInstrs,
1734                                  bool &IsInvertCC) {
1735   assert((CmpValue == 0 || CmpValue == 1) &&
1736          "Only comparisons to 0 or 1 considered for removal!");
1737 
1738   // MI is 'CSINCWr %vreg, wzr, wzr, <cc>' or 'CSINCXr %vreg, xzr, xzr, <cc>'
1739   unsigned MIOpc = MI.getOpcode();
1740   if (MIOpc == AArch64::CSINCWr) {
1741     if (MI.getOperand(1).getReg() != AArch64::WZR ||
1742         MI.getOperand(2).getReg() != AArch64::WZR)
1743       return false;
1744   } else if (MIOpc == AArch64::CSINCXr) {
1745     if (MI.getOperand(1).getReg() != AArch64::XZR ||
1746         MI.getOperand(2).getReg() != AArch64::XZR)
1747       return false;
1748   } else {
1749     return false;
1750   }
1751   AArch64CC::CondCode MICC = findCondCodeUsedByInstr(MI);
1752   if (MICC == AArch64CC::Invalid)
1753     return false;
1754 
1755   // NZCV needs to be defined
1756   if (MI.findRegisterDefOperandIdx(AArch64::NZCV, true) != -1)
1757     return false;
1758 
1759   // CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0' or 'SUBS %vreg, 1'
1760   const unsigned CmpOpcode = CmpInstr.getOpcode();
1761   bool IsSubsRegImm = isSUBSRegImm(CmpOpcode);
1762   if (CmpValue && !IsSubsRegImm)
1763     return false;
1764   if (!CmpValue && !IsSubsRegImm && !isADDSRegImm(CmpOpcode))
1765     return false;
1766 
1767   // MI conditions allowed: eq, ne, mi, pl
1768   UsedNZCV MIUsedNZCV = getUsedNZCV(MICC);
1769   if (MIUsedNZCV.C || MIUsedNZCV.V)
1770     return false;
1771 
1772   Optional<UsedNZCV> NZCVUsedAfterCmp =
1773       examineCFlagsUse(MI, CmpInstr, TRI, &CCUseInstrs);
1774   // Condition flags are not used in CmpInstr basic block successors and only
1775   // Z or N flags allowed to be used after CmpInstr within its basic block
1776   if (!NZCVUsedAfterCmp)
1777     return false;
1778   // Z or N flag used after CmpInstr must correspond to the flag used in MI
1779   if ((MIUsedNZCV.Z && NZCVUsedAfterCmp->N) ||
1780       (MIUsedNZCV.N && NZCVUsedAfterCmp->Z))
1781     return false;
1782   // If CmpInstr is comparison to zero MI conditions are limited to eq, ne
1783   if (MIUsedNZCV.N && !CmpValue)
1784     return false;
1785 
1786   // There must be no defs of flags between MI and CmpInstr
1787   if (areCFlagsAccessedBetweenInstrs(&MI, &CmpInstr, &TRI, AK_Write))
1788     return false;
1789 
1790   // Condition code is inverted in the following cases:
1791   // 1. MI condition is ne; CmpInstr is 'ADDS %vreg, 0' or 'SUBS %vreg, 0'
1792   // 2. MI condition is eq, pl; CmpInstr is 'SUBS %vreg, 1'
1793   IsInvertCC = (CmpValue && (MICC == AArch64CC::EQ || MICC == AArch64CC::PL)) ||
1794                (!CmpValue && MICC == AArch64CC::NE);
1795   return true;
1796 }
1797 
1798 /// Remove comparision in csinc-cmp sequence
1799 ///
1800 /// Examples:
1801 /// 1. \code
1802 ///   csinc w9, wzr, wzr, ne
1803 ///   cmp   w9, #0
1804 ///   b.eq
1805 ///    \endcode
1806 /// to
1807 ///    \code
1808 ///   csinc w9, wzr, wzr, ne
1809 ///   b.ne
1810 ///    \endcode
1811 ///
1812 /// 2. \code
1813 ///   csinc x2, xzr, xzr, mi
1814 ///   cmp   x2, #1
1815 ///   b.pl
1816 ///    \endcode
1817 /// to
1818 ///    \code
1819 ///   csinc x2, xzr, xzr, mi
1820 ///   b.pl
1821 ///    \endcode
1822 ///
1823 /// \param  CmpInstr comparison instruction
1824 /// \return True when comparison removed
1825 bool AArch64InstrInfo::removeCmpToZeroOrOne(
1826     MachineInstr &CmpInstr, unsigned SrcReg, int CmpValue,
1827     const MachineRegisterInfo &MRI) const {
1828   MachineInstr *MI = MRI.getUniqueVRegDef(SrcReg);
1829   if (!MI)
1830     return false;
1831   const TargetRegisterInfo &TRI = getRegisterInfo();
1832   SmallVector<MachineInstr *, 4> CCUseInstrs;
1833   bool IsInvertCC = false;
1834   if (!canCmpInstrBeRemoved(*MI, CmpInstr, CmpValue, TRI, CCUseInstrs,
1835                             IsInvertCC))
1836     return false;
1837   // Make transformation
1838   CmpInstr.eraseFromParent();
1839   if (IsInvertCC) {
1840     // Invert condition codes in CmpInstr CC users
1841     for (MachineInstr *CCUseInstr : CCUseInstrs) {
1842       int Idx = findCondCodeUseOperandIdxForBranchOrSelect(*CCUseInstr);
1843       assert(Idx >= 0 && "Unexpected instruction using CC.");
1844       MachineOperand &CCOperand = CCUseInstr->getOperand(Idx);
1845       AArch64CC::CondCode CCUse = AArch64CC::getInvertedCondCode(
1846           static_cast<AArch64CC::CondCode>(CCOperand.getImm()));
1847       CCOperand.setImm(CCUse);
1848     }
1849   }
1850   return true;
1851 }
1852 
1853 bool AArch64InstrInfo::expandPostRAPseudo(MachineInstr &MI) const {
1854   if (MI.getOpcode() != TargetOpcode::LOAD_STACK_GUARD &&
1855       MI.getOpcode() != AArch64::CATCHRET)
1856     return false;
1857 
1858   MachineBasicBlock &MBB = *MI.getParent();
1859   auto &Subtarget = MBB.getParent()->getSubtarget<AArch64Subtarget>();
1860   auto TRI = Subtarget.getRegisterInfo();
1861   DebugLoc DL = MI.getDebugLoc();
1862 
1863   if (MI.getOpcode() == AArch64::CATCHRET) {
1864     // Skip to the first instruction before the epilog.
1865     const TargetInstrInfo *TII =
1866       MBB.getParent()->getSubtarget().getInstrInfo();
1867     MachineBasicBlock *TargetMBB = MI.getOperand(0).getMBB();
1868     auto MBBI = MachineBasicBlock::iterator(MI);
1869     MachineBasicBlock::iterator FirstEpilogSEH = std::prev(MBBI);
1870     while (FirstEpilogSEH->getFlag(MachineInstr::FrameDestroy) &&
1871            FirstEpilogSEH != MBB.begin())
1872       FirstEpilogSEH = std::prev(FirstEpilogSEH);
1873     if (FirstEpilogSEH != MBB.begin())
1874       FirstEpilogSEH = std::next(FirstEpilogSEH);
1875     BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADRP))
1876         .addReg(AArch64::X0, RegState::Define)
1877         .addMBB(TargetMBB);
1878     BuildMI(MBB, FirstEpilogSEH, DL, TII->get(AArch64::ADDXri))
1879         .addReg(AArch64::X0, RegState::Define)
1880         .addReg(AArch64::X0)
1881         .addMBB(TargetMBB)
1882         .addImm(0);
1883     return true;
1884   }
1885 
1886   Register Reg = MI.getOperand(0).getReg();
1887   Module &M = *MBB.getParent()->getFunction().getParent();
1888   if (M.getStackProtectorGuard() == "sysreg") {
1889     const AArch64SysReg::SysReg *SrcReg =
1890         AArch64SysReg::lookupSysRegByName(M.getStackProtectorGuardReg());
1891     if (!SrcReg)
1892       report_fatal_error("Unknown SysReg for Stack Protector Guard Register");
1893 
1894     // mrs xN, sysreg
1895     BuildMI(MBB, MI, DL, get(AArch64::MRS))
1896         .addDef(Reg, RegState::Renamable)
1897         .addImm(SrcReg->Encoding);
1898     int Offset = M.getStackProtectorGuardOffset();
1899     if (Offset >= 0 && Offset <= 32760 && Offset % 8 == 0) {
1900       // ldr xN, [xN, #offset]
1901       BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
1902           .addDef(Reg)
1903           .addUse(Reg, RegState::Kill)
1904           .addImm(Offset / 8);
1905     } else if (Offset >= -256 && Offset <= 255) {
1906       // ldur xN, [xN, #offset]
1907       BuildMI(MBB, MI, DL, get(AArch64::LDURXi))
1908           .addDef(Reg)
1909           .addUse(Reg, RegState::Kill)
1910           .addImm(Offset);
1911     } else if (Offset >= -4095 && Offset <= 4095) {
1912       if (Offset > 0) {
1913         // add xN, xN, #offset
1914         BuildMI(MBB, MI, DL, get(AArch64::ADDXri))
1915             .addDef(Reg)
1916             .addUse(Reg, RegState::Kill)
1917             .addImm(Offset)
1918             .addImm(0);
1919       } else {
1920         // sub xN, xN, #offset
1921         BuildMI(MBB, MI, DL, get(AArch64::SUBXri))
1922             .addDef(Reg)
1923             .addUse(Reg, RegState::Kill)
1924             .addImm(-Offset)
1925             .addImm(0);
1926       }
1927       // ldr xN, [xN]
1928       BuildMI(MBB, MI, DL, get(AArch64::LDRXui))
1929           .addDef(Reg)
1930           .addUse(Reg, RegState::Kill)
1931           .addImm(0);
1932     } else {
1933       // Cases that are larger than +/- 4095 and not a multiple of 8, or larger
1934       // than 23760.
1935       // It might be nice to use AArch64::MOVi32imm here, which would get
1936       // expanded in PreSched2 after PostRA, but our lone scratch Reg already
1937       // contains the MRS result. findScratchNonCalleeSaveRegister() in
1938       // AArch64FrameLowering might help us find such a scratch register
1939       // though. If we failed to find a scratch register, we could emit a
1940       // stream of add instructions to build up the immediate. Or, we could try
1941       // to insert a AArch64::MOVi32imm before register allocation so that we
1942       // didn't need to scavenge for a scratch register.
1943       report_fatal_error("Unable to encode Stack Protector Guard Offset");
1944     }
1945     MBB.erase(MI);
1946     return true;
1947   }
1948 
1949   const GlobalValue *GV =
1950       cast<GlobalValue>((*MI.memoperands_begin())->getValue());
1951   const TargetMachine &TM = MBB.getParent()->getTarget();
1952   unsigned OpFlags = Subtarget.ClassifyGlobalReference(GV, TM);
1953   const unsigned char MO_NC = AArch64II::MO_NC;
1954 
1955   if ((OpFlags & AArch64II::MO_GOT) != 0) {
1956     BuildMI(MBB, MI, DL, get(AArch64::LOADgot), Reg)
1957         .addGlobalAddress(GV, 0, OpFlags);
1958     if (Subtarget.isTargetILP32()) {
1959       unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
1960       BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
1961           .addDef(Reg32, RegState::Dead)
1962           .addUse(Reg, RegState::Kill)
1963           .addImm(0)
1964           .addMemOperand(*MI.memoperands_begin())
1965           .addDef(Reg, RegState::Implicit);
1966     } else {
1967       BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
1968           .addReg(Reg, RegState::Kill)
1969           .addImm(0)
1970           .addMemOperand(*MI.memoperands_begin());
1971     }
1972   } else if (TM.getCodeModel() == CodeModel::Large) {
1973     assert(!Subtarget.isTargetILP32() && "how can large exist in ILP32?");
1974     BuildMI(MBB, MI, DL, get(AArch64::MOVZXi), Reg)
1975         .addGlobalAddress(GV, 0, AArch64II::MO_G0 | MO_NC)
1976         .addImm(0);
1977     BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
1978         .addReg(Reg, RegState::Kill)
1979         .addGlobalAddress(GV, 0, AArch64II::MO_G1 | MO_NC)
1980         .addImm(16);
1981     BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
1982         .addReg(Reg, RegState::Kill)
1983         .addGlobalAddress(GV, 0, AArch64II::MO_G2 | MO_NC)
1984         .addImm(32);
1985     BuildMI(MBB, MI, DL, get(AArch64::MOVKXi), Reg)
1986         .addReg(Reg, RegState::Kill)
1987         .addGlobalAddress(GV, 0, AArch64II::MO_G3)
1988         .addImm(48);
1989     BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
1990         .addReg(Reg, RegState::Kill)
1991         .addImm(0)
1992         .addMemOperand(*MI.memoperands_begin());
1993   } else if (TM.getCodeModel() == CodeModel::Tiny) {
1994     BuildMI(MBB, MI, DL, get(AArch64::ADR), Reg)
1995         .addGlobalAddress(GV, 0, OpFlags);
1996   } else {
1997     BuildMI(MBB, MI, DL, get(AArch64::ADRP), Reg)
1998         .addGlobalAddress(GV, 0, OpFlags | AArch64II::MO_PAGE);
1999     unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | MO_NC;
2000     if (Subtarget.isTargetILP32()) {
2001       unsigned Reg32 = TRI->getSubReg(Reg, AArch64::sub_32);
2002       BuildMI(MBB, MI, DL, get(AArch64::LDRWui))
2003           .addDef(Reg32, RegState::Dead)
2004           .addUse(Reg, RegState::Kill)
2005           .addGlobalAddress(GV, 0, LoFlags)
2006           .addMemOperand(*MI.memoperands_begin())
2007           .addDef(Reg, RegState::Implicit);
2008     } else {
2009       BuildMI(MBB, MI, DL, get(AArch64::LDRXui), Reg)
2010           .addReg(Reg, RegState::Kill)
2011           .addGlobalAddress(GV, 0, LoFlags)
2012           .addMemOperand(*MI.memoperands_begin());
2013     }
2014   }
2015 
2016   MBB.erase(MI);
2017 
2018   return true;
2019 }
2020 
2021 // Return true if this instruction simply sets its single destination register
2022 // to zero. This is equivalent to a register rename of the zero-register.
2023 bool AArch64InstrInfo::isGPRZero(const MachineInstr &MI) {
2024   switch (MI.getOpcode()) {
2025   default:
2026     break;
2027   case AArch64::MOVZWi:
2028   case AArch64::MOVZXi: // movz Rd, #0 (LSL #0)
2029     if (MI.getOperand(1).isImm() && MI.getOperand(1).getImm() == 0) {
2030       assert(MI.getDesc().getNumOperands() == 3 &&
2031              MI.getOperand(2).getImm() == 0 && "invalid MOVZi operands");
2032       return true;
2033     }
2034     break;
2035   case AArch64::ANDWri: // and Rd, Rzr, #imm
2036     return MI.getOperand(1).getReg() == AArch64::WZR;
2037   case AArch64::ANDXri:
2038     return MI.getOperand(1).getReg() == AArch64::XZR;
2039   case TargetOpcode::COPY:
2040     return MI.getOperand(1).getReg() == AArch64::WZR;
2041   }
2042   return false;
2043 }
2044 
2045 // Return true if this instruction simply renames a general register without
2046 // modifying bits.
2047 bool AArch64InstrInfo::isGPRCopy(const MachineInstr &MI) {
2048   switch (MI.getOpcode()) {
2049   default:
2050     break;
2051   case TargetOpcode::COPY: {
2052     // GPR32 copies will by lowered to ORRXrs
2053     Register DstReg = MI.getOperand(0).getReg();
2054     return (AArch64::GPR32RegClass.contains(DstReg) ||
2055             AArch64::GPR64RegClass.contains(DstReg));
2056   }
2057   case AArch64::ORRXrs: // orr Xd, Xzr, Xm (LSL #0)
2058     if (MI.getOperand(1).getReg() == AArch64::XZR) {
2059       assert(MI.getDesc().getNumOperands() == 4 &&
2060              MI.getOperand(3).getImm() == 0 && "invalid ORRrs operands");
2061       return true;
2062     }
2063     break;
2064   case AArch64::ADDXri: // add Xd, Xn, #0 (LSL #0)
2065     if (MI.getOperand(2).getImm() == 0) {
2066       assert(MI.getDesc().getNumOperands() == 4 &&
2067              MI.getOperand(3).getImm() == 0 && "invalid ADDXri operands");
2068       return true;
2069     }
2070     break;
2071   }
2072   return false;
2073 }
2074 
2075 // Return true if this instruction simply renames a general register without
2076 // modifying bits.
2077 bool AArch64InstrInfo::isFPRCopy(const MachineInstr &MI) {
2078   switch (MI.getOpcode()) {
2079   default:
2080     break;
2081   case TargetOpcode::COPY: {
2082     Register DstReg = MI.getOperand(0).getReg();
2083     return AArch64::FPR128RegClass.contains(DstReg);
2084   }
2085   case AArch64::ORRv16i8:
2086     if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) {
2087       assert(MI.getDesc().getNumOperands() == 3 && MI.getOperand(0).isReg() &&
2088              "invalid ORRv16i8 operands");
2089       return true;
2090     }
2091     break;
2092   }
2093   return false;
2094 }
2095 
2096 unsigned AArch64InstrInfo::isLoadFromStackSlot(const MachineInstr &MI,
2097                                                int &FrameIndex) const {
2098   switch (MI.getOpcode()) {
2099   default:
2100     break;
2101   case AArch64::LDRWui:
2102   case AArch64::LDRXui:
2103   case AArch64::LDRBui:
2104   case AArch64::LDRHui:
2105   case AArch64::LDRSui:
2106   case AArch64::LDRDui:
2107   case AArch64::LDRQui:
2108     if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2109         MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2110       FrameIndex = MI.getOperand(1).getIndex();
2111       return MI.getOperand(0).getReg();
2112     }
2113     break;
2114   }
2115 
2116   return 0;
2117 }
2118 
2119 unsigned AArch64InstrInfo::isStoreToStackSlot(const MachineInstr &MI,
2120                                               int &FrameIndex) const {
2121   switch (MI.getOpcode()) {
2122   default:
2123     break;
2124   case AArch64::STRWui:
2125   case AArch64::STRXui:
2126   case AArch64::STRBui:
2127   case AArch64::STRHui:
2128   case AArch64::STRSui:
2129   case AArch64::STRDui:
2130   case AArch64::STRQui:
2131   case AArch64::LDR_PXI:
2132   case AArch64::STR_PXI:
2133     if (MI.getOperand(0).getSubReg() == 0 && MI.getOperand(1).isFI() &&
2134         MI.getOperand(2).isImm() && MI.getOperand(2).getImm() == 0) {
2135       FrameIndex = MI.getOperand(1).getIndex();
2136       return MI.getOperand(0).getReg();
2137     }
2138     break;
2139   }
2140   return 0;
2141 }
2142 
2143 /// Check all MachineMemOperands for a hint to suppress pairing.
2144 bool AArch64InstrInfo::isLdStPairSuppressed(const MachineInstr &MI) {
2145   return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2146     return MMO->getFlags() & MOSuppressPair;
2147   });
2148 }
2149 
2150 /// Set a flag on the first MachineMemOperand to suppress pairing.
2151 void AArch64InstrInfo::suppressLdStPair(MachineInstr &MI) {
2152   if (MI.memoperands_empty())
2153     return;
2154   (*MI.memoperands_begin())->setFlags(MOSuppressPair);
2155 }
2156 
2157 /// Check all MachineMemOperands for a hint that the load/store is strided.
2158 bool AArch64InstrInfo::isStridedAccess(const MachineInstr &MI) {
2159   return llvm::any_of(MI.memoperands(), [](MachineMemOperand *MMO) {
2160     return MMO->getFlags() & MOStridedAccess;
2161   });
2162 }
2163 
2164 bool AArch64InstrInfo::hasUnscaledLdStOffset(unsigned Opc) {
2165   switch (Opc) {
2166   default:
2167     return false;
2168   case AArch64::STURSi:
2169   case AArch64::STRSpre:
2170   case AArch64::STURDi:
2171   case AArch64::STRDpre:
2172   case AArch64::STURQi:
2173   case AArch64::STRQpre:
2174   case AArch64::STURBBi:
2175   case AArch64::STURHHi:
2176   case AArch64::STURWi:
2177   case AArch64::STRWpre:
2178   case AArch64::STURXi:
2179   case AArch64::STRXpre:
2180   case AArch64::LDURSi:
2181   case AArch64::LDRSpre:
2182   case AArch64::LDURDi:
2183   case AArch64::LDRDpre:
2184   case AArch64::LDURQi:
2185   case AArch64::LDRQpre:
2186   case AArch64::LDURWi:
2187   case AArch64::LDRWpre:
2188   case AArch64::LDURXi:
2189   case AArch64::LDRXpre:
2190   case AArch64::LDURSWi:
2191   case AArch64::LDURHHi:
2192   case AArch64::LDURBBi:
2193   case AArch64::LDURSBWi:
2194   case AArch64::LDURSHWi:
2195     return true;
2196   }
2197 }
2198 
2199 Optional<unsigned> AArch64InstrInfo::getUnscaledLdSt(unsigned Opc) {
2200   switch (Opc) {
2201   default: return {};
2202   case AArch64::PRFMui: return AArch64::PRFUMi;
2203   case AArch64::LDRXui: return AArch64::LDURXi;
2204   case AArch64::LDRWui: return AArch64::LDURWi;
2205   case AArch64::LDRBui: return AArch64::LDURBi;
2206   case AArch64::LDRHui: return AArch64::LDURHi;
2207   case AArch64::LDRSui: return AArch64::LDURSi;
2208   case AArch64::LDRDui: return AArch64::LDURDi;
2209   case AArch64::LDRQui: return AArch64::LDURQi;
2210   case AArch64::LDRBBui: return AArch64::LDURBBi;
2211   case AArch64::LDRHHui: return AArch64::LDURHHi;
2212   case AArch64::LDRSBXui: return AArch64::LDURSBXi;
2213   case AArch64::LDRSBWui: return AArch64::LDURSBWi;
2214   case AArch64::LDRSHXui: return AArch64::LDURSHXi;
2215   case AArch64::LDRSHWui: return AArch64::LDURSHWi;
2216   case AArch64::LDRSWui: return AArch64::LDURSWi;
2217   case AArch64::STRXui: return AArch64::STURXi;
2218   case AArch64::STRWui: return AArch64::STURWi;
2219   case AArch64::STRBui: return AArch64::STURBi;
2220   case AArch64::STRHui: return AArch64::STURHi;
2221   case AArch64::STRSui: return AArch64::STURSi;
2222   case AArch64::STRDui: return AArch64::STURDi;
2223   case AArch64::STRQui: return AArch64::STURQi;
2224   case AArch64::STRBBui: return AArch64::STURBBi;
2225   case AArch64::STRHHui: return AArch64::STURHHi;
2226   }
2227 }
2228 
2229 unsigned AArch64InstrInfo::getLoadStoreImmIdx(unsigned Opc) {
2230   switch (Opc) {
2231   default:
2232     return 2;
2233   case AArch64::LDPXi:
2234   case AArch64::LDPDi:
2235   case AArch64::STPXi:
2236   case AArch64::STPDi:
2237   case AArch64::LDNPXi:
2238   case AArch64::LDNPDi:
2239   case AArch64::STNPXi:
2240   case AArch64::STNPDi:
2241   case AArch64::LDPQi:
2242   case AArch64::STPQi:
2243   case AArch64::LDNPQi:
2244   case AArch64::STNPQi:
2245   case AArch64::LDPWi:
2246   case AArch64::LDPSi:
2247   case AArch64::STPWi:
2248   case AArch64::STPSi:
2249   case AArch64::LDNPWi:
2250   case AArch64::LDNPSi:
2251   case AArch64::STNPWi:
2252   case AArch64::STNPSi:
2253   case AArch64::LDG:
2254   case AArch64::STGPi:
2255 
2256   case AArch64::LD1B_IMM:
2257   case AArch64::LD1B_H_IMM:
2258   case AArch64::LD1B_S_IMM:
2259   case AArch64::LD1B_D_IMM:
2260   case AArch64::LD1SB_H_IMM:
2261   case AArch64::LD1SB_S_IMM:
2262   case AArch64::LD1SB_D_IMM:
2263   case AArch64::LD1H_IMM:
2264   case AArch64::LD1H_S_IMM:
2265   case AArch64::LD1H_D_IMM:
2266   case AArch64::LD1SH_S_IMM:
2267   case AArch64::LD1SH_D_IMM:
2268   case AArch64::LD1W_IMM:
2269   case AArch64::LD1W_D_IMM:
2270   case AArch64::LD1SW_D_IMM:
2271   case AArch64::LD1D_IMM:
2272 
2273   case AArch64::ST1B_IMM:
2274   case AArch64::ST1B_H_IMM:
2275   case AArch64::ST1B_S_IMM:
2276   case AArch64::ST1B_D_IMM:
2277   case AArch64::ST1H_IMM:
2278   case AArch64::ST1H_S_IMM:
2279   case AArch64::ST1H_D_IMM:
2280   case AArch64::ST1W_IMM:
2281   case AArch64::ST1W_D_IMM:
2282   case AArch64::ST1D_IMM:
2283 
2284   case AArch64::LD1RB_IMM:
2285   case AArch64::LD1RB_H_IMM:
2286   case AArch64::LD1RB_S_IMM:
2287   case AArch64::LD1RB_D_IMM:
2288   case AArch64::LD1RSB_H_IMM:
2289   case AArch64::LD1RSB_S_IMM:
2290   case AArch64::LD1RSB_D_IMM:
2291   case AArch64::LD1RH_IMM:
2292   case AArch64::LD1RH_S_IMM:
2293   case AArch64::LD1RH_D_IMM:
2294   case AArch64::LD1RSH_S_IMM:
2295   case AArch64::LD1RSH_D_IMM:
2296   case AArch64::LD1RW_IMM:
2297   case AArch64::LD1RW_D_IMM:
2298   case AArch64::LD1RSW_IMM:
2299   case AArch64::LD1RD_IMM:
2300 
2301   case AArch64::LDNT1B_ZRI:
2302   case AArch64::LDNT1H_ZRI:
2303   case AArch64::LDNT1W_ZRI:
2304   case AArch64::LDNT1D_ZRI:
2305   case AArch64::STNT1B_ZRI:
2306   case AArch64::STNT1H_ZRI:
2307   case AArch64::STNT1W_ZRI:
2308   case AArch64::STNT1D_ZRI:
2309 
2310   case AArch64::LDNF1B_IMM:
2311   case AArch64::LDNF1B_H_IMM:
2312   case AArch64::LDNF1B_S_IMM:
2313   case AArch64::LDNF1B_D_IMM:
2314   case AArch64::LDNF1SB_H_IMM:
2315   case AArch64::LDNF1SB_S_IMM:
2316   case AArch64::LDNF1SB_D_IMM:
2317   case AArch64::LDNF1H_IMM:
2318   case AArch64::LDNF1H_S_IMM:
2319   case AArch64::LDNF1H_D_IMM:
2320   case AArch64::LDNF1SH_S_IMM:
2321   case AArch64::LDNF1SH_D_IMM:
2322   case AArch64::LDNF1W_IMM:
2323   case AArch64::LDNF1W_D_IMM:
2324   case AArch64::LDNF1SW_D_IMM:
2325   case AArch64::LDNF1D_IMM:
2326     return 3;
2327   case AArch64::ADDG:
2328   case AArch64::STGOffset:
2329   case AArch64::LDR_PXI:
2330   case AArch64::STR_PXI:
2331     return 2;
2332   }
2333 }
2334 
2335 bool AArch64InstrInfo::isPairableLdStInst(const MachineInstr &MI) {
2336   switch (MI.getOpcode()) {
2337   default:
2338     return false;
2339   // Scaled instructions.
2340   case AArch64::STRSui:
2341   case AArch64::STRDui:
2342   case AArch64::STRQui:
2343   case AArch64::STRXui:
2344   case AArch64::STRWui:
2345   case AArch64::LDRSui:
2346   case AArch64::LDRDui:
2347   case AArch64::LDRQui:
2348   case AArch64::LDRXui:
2349   case AArch64::LDRWui:
2350   case AArch64::LDRSWui:
2351   // Unscaled instructions.
2352   case AArch64::STURSi:
2353   case AArch64::STRSpre:
2354   case AArch64::STURDi:
2355   case AArch64::STRDpre:
2356   case AArch64::STURQi:
2357   case AArch64::STRQpre:
2358   case AArch64::STURWi:
2359   case AArch64::STRWpre:
2360   case AArch64::STURXi:
2361   case AArch64::STRXpre:
2362   case AArch64::LDURSi:
2363   case AArch64::LDRSpre:
2364   case AArch64::LDURDi:
2365   case AArch64::LDRDpre:
2366   case AArch64::LDURQi:
2367   case AArch64::LDRQpre:
2368   case AArch64::LDURWi:
2369   case AArch64::LDRWpre:
2370   case AArch64::LDURXi:
2371   case AArch64::LDRXpre:
2372   case AArch64::LDURSWi:
2373     return true;
2374   }
2375 }
2376 
2377 unsigned AArch64InstrInfo::convertToFlagSettingOpc(unsigned Opc,
2378                                                    bool &Is64Bit) {
2379   switch (Opc) {
2380   default:
2381     llvm_unreachable("Opcode has no flag setting equivalent!");
2382   // 32-bit cases:
2383   case AArch64::ADDWri:
2384     Is64Bit = false;
2385     return AArch64::ADDSWri;
2386   case AArch64::ADDWrr:
2387     Is64Bit = false;
2388     return AArch64::ADDSWrr;
2389   case AArch64::ADDWrs:
2390     Is64Bit = false;
2391     return AArch64::ADDSWrs;
2392   case AArch64::ADDWrx:
2393     Is64Bit = false;
2394     return AArch64::ADDSWrx;
2395   case AArch64::ANDWri:
2396     Is64Bit = false;
2397     return AArch64::ANDSWri;
2398   case AArch64::ANDWrr:
2399     Is64Bit = false;
2400     return AArch64::ANDSWrr;
2401   case AArch64::ANDWrs:
2402     Is64Bit = false;
2403     return AArch64::ANDSWrs;
2404   case AArch64::BICWrr:
2405     Is64Bit = false;
2406     return AArch64::BICSWrr;
2407   case AArch64::BICWrs:
2408     Is64Bit = false;
2409     return AArch64::BICSWrs;
2410   case AArch64::SUBWri:
2411     Is64Bit = false;
2412     return AArch64::SUBSWri;
2413   case AArch64::SUBWrr:
2414     Is64Bit = false;
2415     return AArch64::SUBSWrr;
2416   case AArch64::SUBWrs:
2417     Is64Bit = false;
2418     return AArch64::SUBSWrs;
2419   case AArch64::SUBWrx:
2420     Is64Bit = false;
2421     return AArch64::SUBSWrx;
2422   // 64-bit cases:
2423   case AArch64::ADDXri:
2424     Is64Bit = true;
2425     return AArch64::ADDSXri;
2426   case AArch64::ADDXrr:
2427     Is64Bit = true;
2428     return AArch64::ADDSXrr;
2429   case AArch64::ADDXrs:
2430     Is64Bit = true;
2431     return AArch64::ADDSXrs;
2432   case AArch64::ADDXrx:
2433     Is64Bit = true;
2434     return AArch64::ADDSXrx;
2435   case AArch64::ANDXri:
2436     Is64Bit = true;
2437     return AArch64::ANDSXri;
2438   case AArch64::ANDXrr:
2439     Is64Bit = true;
2440     return AArch64::ANDSXrr;
2441   case AArch64::ANDXrs:
2442     Is64Bit = true;
2443     return AArch64::ANDSXrs;
2444   case AArch64::BICXrr:
2445     Is64Bit = true;
2446     return AArch64::BICSXrr;
2447   case AArch64::BICXrs:
2448     Is64Bit = true;
2449     return AArch64::BICSXrs;
2450   case AArch64::SUBXri:
2451     Is64Bit = true;
2452     return AArch64::SUBSXri;
2453   case AArch64::SUBXrr:
2454     Is64Bit = true;
2455     return AArch64::SUBSXrr;
2456   case AArch64::SUBXrs:
2457     Is64Bit = true;
2458     return AArch64::SUBSXrs;
2459   case AArch64::SUBXrx:
2460     Is64Bit = true;
2461     return AArch64::SUBSXrx;
2462   }
2463 }
2464 
2465 // Is this a candidate for ld/st merging or pairing?  For example, we don't
2466 // touch volatiles or load/stores that have a hint to avoid pair formation.
2467 bool AArch64InstrInfo::isCandidateToMergeOrPair(const MachineInstr &MI) const {
2468 
2469   bool IsPreLdSt = isPreLdSt(MI);
2470 
2471   // If this is a volatile load/store, don't mess with it.
2472   if (MI.hasOrderedMemoryRef())
2473     return false;
2474 
2475   // Make sure this is a reg/fi+imm (as opposed to an address reloc).
2476   // For Pre-inc LD/ST, the operand is shifted by one.
2477   assert((MI.getOperand(IsPreLdSt ? 2 : 1).isReg() ||
2478           MI.getOperand(IsPreLdSt ? 2 : 1).isFI()) &&
2479          "Expected a reg or frame index operand.");
2480 
2481   // For Pre-indexed addressing quadword instructions, the third operand is the
2482   // immediate value.
2483   bool IsImmPreLdSt = IsPreLdSt && MI.getOperand(3).isImm();
2484 
2485   if (!MI.getOperand(2).isImm() && !IsImmPreLdSt)
2486     return false;
2487 
2488   // Can't merge/pair if the instruction modifies the base register.
2489   // e.g., ldr x0, [x0]
2490   // This case will never occur with an FI base.
2491   // However, if the instruction is an LDR/STR<S,D,Q,W,X>pre, it can be merged.
2492   // For example:
2493   //   ldr q0, [x11, #32]!
2494   //   ldr q1, [x11, #16]
2495   //   to
2496   //   ldp q0, q1, [x11, #32]!
2497   if (MI.getOperand(1).isReg() && !IsPreLdSt) {
2498     Register BaseReg = MI.getOperand(1).getReg();
2499     const TargetRegisterInfo *TRI = &getRegisterInfo();
2500     if (MI.modifiesRegister(BaseReg, TRI))
2501       return false;
2502   }
2503 
2504   // Check if this load/store has a hint to avoid pair formation.
2505   // MachineMemOperands hints are set by the AArch64StorePairSuppress pass.
2506   if (isLdStPairSuppressed(MI))
2507     return false;
2508 
2509   // Do not pair any callee-save store/reload instructions in the
2510   // prologue/epilogue if the CFI information encoded the operations as separate
2511   // instructions, as that will cause the size of the actual prologue to mismatch
2512   // with the prologue size recorded in the Windows CFI.
2513   const MCAsmInfo *MAI = MI.getMF()->getTarget().getMCAsmInfo();
2514   bool NeedsWinCFI = MAI->usesWindowsCFI() &&
2515                      MI.getMF()->getFunction().needsUnwindTableEntry();
2516   if (NeedsWinCFI && (MI.getFlag(MachineInstr::FrameSetup) ||
2517                       MI.getFlag(MachineInstr::FrameDestroy)))
2518     return false;
2519 
2520   // On some CPUs quad load/store pairs are slower than two single load/stores.
2521   if (Subtarget.isPaired128Slow()) {
2522     switch (MI.getOpcode()) {
2523     default:
2524       break;
2525     case AArch64::LDURQi:
2526     case AArch64::STURQi:
2527     case AArch64::LDRQui:
2528     case AArch64::STRQui:
2529       return false;
2530     }
2531   }
2532 
2533   return true;
2534 }
2535 
2536 bool AArch64InstrInfo::getMemOperandsWithOffsetWidth(
2537     const MachineInstr &LdSt, SmallVectorImpl<const MachineOperand *> &BaseOps,
2538     int64_t &Offset, bool &OffsetIsScalable, unsigned &Width,
2539     const TargetRegisterInfo *TRI) const {
2540   if (!LdSt.mayLoadOrStore())
2541     return false;
2542 
2543   const MachineOperand *BaseOp;
2544   if (!getMemOperandWithOffsetWidth(LdSt, BaseOp, Offset, OffsetIsScalable,
2545                                     Width, TRI))
2546     return false;
2547   BaseOps.push_back(BaseOp);
2548   return true;
2549 }
2550 
2551 Optional<ExtAddrMode>
2552 AArch64InstrInfo::getAddrModeFromMemoryOp(const MachineInstr &MemI,
2553                                           const TargetRegisterInfo *TRI) const {
2554   const MachineOperand *Base; // Filled with the base operand of MI.
2555   int64_t Offset;             // Filled with the offset of MI.
2556   bool OffsetIsScalable;
2557   if (!getMemOperandWithOffset(MemI, Base, Offset, OffsetIsScalable, TRI))
2558     return None;
2559 
2560   if (!Base->isReg())
2561     return None;
2562   ExtAddrMode AM;
2563   AM.BaseReg = Base->getReg();
2564   AM.Displacement = Offset;
2565   AM.ScaledReg = 0;
2566   AM.Scale = 0;
2567   return AM;
2568 }
2569 
2570 bool AArch64InstrInfo::getMemOperandWithOffsetWidth(
2571     const MachineInstr &LdSt, const MachineOperand *&BaseOp, int64_t &Offset,
2572     bool &OffsetIsScalable, unsigned &Width,
2573     const TargetRegisterInfo *TRI) const {
2574   assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
2575   // Handle only loads/stores with base register followed by immediate offset.
2576   if (LdSt.getNumExplicitOperands() == 3) {
2577     // Non-paired instruction (e.g., ldr x1, [x0, #8]).
2578     if ((!LdSt.getOperand(1).isReg() && !LdSt.getOperand(1).isFI()) ||
2579         !LdSt.getOperand(2).isImm())
2580       return false;
2581   } else if (LdSt.getNumExplicitOperands() == 4) {
2582     // Paired instruction (e.g., ldp x1, x2, [x0, #8]).
2583     if (!LdSt.getOperand(1).isReg() ||
2584         (!LdSt.getOperand(2).isReg() && !LdSt.getOperand(2).isFI()) ||
2585         !LdSt.getOperand(3).isImm())
2586       return false;
2587   } else
2588     return false;
2589 
2590   // Get the scaling factor for the instruction and set the width for the
2591   // instruction.
2592   TypeSize Scale(0U, false);
2593   int64_t Dummy1, Dummy2;
2594 
2595   // If this returns false, then it's an instruction we don't want to handle.
2596   if (!getMemOpInfo(LdSt.getOpcode(), Scale, Width, Dummy1, Dummy2))
2597     return false;
2598 
2599   // Compute the offset. Offset is calculated as the immediate operand
2600   // multiplied by the scaling factor. Unscaled instructions have scaling factor
2601   // set to 1.
2602   if (LdSt.getNumExplicitOperands() == 3) {
2603     BaseOp = &LdSt.getOperand(1);
2604     Offset = LdSt.getOperand(2).getImm() * Scale.getKnownMinSize();
2605   } else {
2606     assert(LdSt.getNumExplicitOperands() == 4 && "invalid number of operands");
2607     BaseOp = &LdSt.getOperand(2);
2608     Offset = LdSt.getOperand(3).getImm() * Scale.getKnownMinSize();
2609   }
2610   OffsetIsScalable = Scale.isScalable();
2611 
2612   if (!BaseOp->isReg() && !BaseOp->isFI())
2613     return false;
2614 
2615   return true;
2616 }
2617 
2618 MachineOperand &
2619 AArch64InstrInfo::getMemOpBaseRegImmOfsOffsetOperand(MachineInstr &LdSt) const {
2620   assert(LdSt.mayLoadOrStore() && "Expected a memory operation.");
2621   MachineOperand &OfsOp = LdSt.getOperand(LdSt.getNumExplicitOperands() - 1);
2622   assert(OfsOp.isImm() && "Offset operand wasn't immediate.");
2623   return OfsOp;
2624 }
2625 
2626 bool AArch64InstrInfo::getMemOpInfo(unsigned Opcode, TypeSize &Scale,
2627                                     unsigned &Width, int64_t &MinOffset,
2628                                     int64_t &MaxOffset) {
2629   const unsigned SVEMaxBytesPerVector = AArch64::SVEMaxBitsPerVector / 8;
2630   switch (Opcode) {
2631   // Not a memory operation or something we want to handle.
2632   default:
2633     Scale = TypeSize::Fixed(0);
2634     Width = 0;
2635     MinOffset = MaxOffset = 0;
2636     return false;
2637   case AArch64::STRWpost:
2638   case AArch64::LDRWpost:
2639     Width = 32;
2640     Scale = TypeSize::Fixed(4);
2641     MinOffset = -256;
2642     MaxOffset = 255;
2643     break;
2644   case AArch64::LDURQi:
2645   case AArch64::STURQi:
2646     Width = 16;
2647     Scale = TypeSize::Fixed(1);
2648     MinOffset = -256;
2649     MaxOffset = 255;
2650     break;
2651   case AArch64::PRFUMi:
2652   case AArch64::LDURXi:
2653   case AArch64::LDURDi:
2654   case AArch64::STURXi:
2655   case AArch64::STURDi:
2656     Width = 8;
2657     Scale = TypeSize::Fixed(1);
2658     MinOffset = -256;
2659     MaxOffset = 255;
2660     break;
2661   case AArch64::LDURWi:
2662   case AArch64::LDURSi:
2663   case AArch64::LDURSWi:
2664   case AArch64::STURWi:
2665   case AArch64::STURSi:
2666     Width = 4;
2667     Scale = TypeSize::Fixed(1);
2668     MinOffset = -256;
2669     MaxOffset = 255;
2670     break;
2671   case AArch64::LDURHi:
2672   case AArch64::LDURHHi:
2673   case AArch64::LDURSHXi:
2674   case AArch64::LDURSHWi:
2675   case AArch64::STURHi:
2676   case AArch64::STURHHi:
2677     Width = 2;
2678     Scale = TypeSize::Fixed(1);
2679     MinOffset = -256;
2680     MaxOffset = 255;
2681     break;
2682   case AArch64::LDURBi:
2683   case AArch64::LDURBBi:
2684   case AArch64::LDURSBXi:
2685   case AArch64::LDURSBWi:
2686   case AArch64::STURBi:
2687   case AArch64::STURBBi:
2688     Width = 1;
2689     Scale = TypeSize::Fixed(1);
2690     MinOffset = -256;
2691     MaxOffset = 255;
2692     break;
2693   case AArch64::LDPQi:
2694   case AArch64::LDNPQi:
2695   case AArch64::STPQi:
2696   case AArch64::STNPQi:
2697     Scale = TypeSize::Fixed(16);
2698     Width = 32;
2699     MinOffset = -64;
2700     MaxOffset = 63;
2701     break;
2702   case AArch64::LDRQui:
2703   case AArch64::STRQui:
2704     Scale = TypeSize::Fixed(16);
2705     Width = 16;
2706     MinOffset = 0;
2707     MaxOffset = 4095;
2708     break;
2709   case AArch64::LDPXi:
2710   case AArch64::LDPDi:
2711   case AArch64::LDNPXi:
2712   case AArch64::LDNPDi:
2713   case AArch64::STPXi:
2714   case AArch64::STPDi:
2715   case AArch64::STNPXi:
2716   case AArch64::STNPDi:
2717     Scale = TypeSize::Fixed(8);
2718     Width = 16;
2719     MinOffset = -64;
2720     MaxOffset = 63;
2721     break;
2722   case AArch64::PRFMui:
2723   case AArch64::LDRXui:
2724   case AArch64::LDRDui:
2725   case AArch64::STRXui:
2726   case AArch64::STRDui:
2727     Scale = TypeSize::Fixed(8);
2728     Width = 8;
2729     MinOffset = 0;
2730     MaxOffset = 4095;
2731     break;
2732   case AArch64::StoreSwiftAsyncContext:
2733     // Store is an STRXui, but there might be an ADDXri in the expansion too.
2734     Scale = TypeSize::Fixed(1);
2735     Width = 8;
2736     MinOffset = 0;
2737     MaxOffset = 4095;
2738     break;
2739   case AArch64::LDPWi:
2740   case AArch64::LDPSi:
2741   case AArch64::LDNPWi:
2742   case AArch64::LDNPSi:
2743   case AArch64::STPWi:
2744   case AArch64::STPSi:
2745   case AArch64::STNPWi:
2746   case AArch64::STNPSi:
2747     Scale = TypeSize::Fixed(4);
2748     Width = 8;
2749     MinOffset = -64;
2750     MaxOffset = 63;
2751     break;
2752   case AArch64::LDRWui:
2753   case AArch64::LDRSui:
2754   case AArch64::LDRSWui:
2755   case AArch64::STRWui:
2756   case AArch64::STRSui:
2757     Scale = TypeSize::Fixed(4);
2758     Width = 4;
2759     MinOffset = 0;
2760     MaxOffset = 4095;
2761     break;
2762   case AArch64::LDRHui:
2763   case AArch64::LDRHHui:
2764   case AArch64::LDRSHWui:
2765   case AArch64::LDRSHXui:
2766   case AArch64::STRHui:
2767   case AArch64::STRHHui:
2768     Scale = TypeSize::Fixed(2);
2769     Width = 2;
2770     MinOffset = 0;
2771     MaxOffset = 4095;
2772     break;
2773   case AArch64::LDRBui:
2774   case AArch64::LDRBBui:
2775   case AArch64::LDRSBWui:
2776   case AArch64::LDRSBXui:
2777   case AArch64::STRBui:
2778   case AArch64::STRBBui:
2779     Scale = TypeSize::Fixed(1);
2780     Width = 1;
2781     MinOffset = 0;
2782     MaxOffset = 4095;
2783     break;
2784   case AArch64::STPXpre:
2785   case AArch64::LDPXpost:
2786   case AArch64::STPDpre:
2787   case AArch64::LDPDpost:
2788     Scale = TypeSize::Fixed(8);
2789     Width = 8;
2790     MinOffset = -512;
2791     MaxOffset = 504;
2792     break;
2793   case AArch64::STPQpre:
2794   case AArch64::LDPQpost:
2795     Scale = TypeSize::Fixed(16);
2796     Width = 16;
2797     MinOffset = -1024;
2798     MaxOffset = 1008;
2799     break;
2800   case AArch64::STRXpre:
2801   case AArch64::STRDpre:
2802   case AArch64::LDRXpost:
2803   case AArch64::LDRDpost:
2804     Scale = TypeSize::Fixed(1);
2805     Width = 8;
2806     MinOffset = -256;
2807     MaxOffset = 255;
2808     break;
2809   case AArch64::STRQpre:
2810   case AArch64::LDRQpost:
2811     Scale = TypeSize::Fixed(1);
2812     Width = 16;
2813     MinOffset = -256;
2814     MaxOffset = 255;
2815     break;
2816   case AArch64::ADDG:
2817     Scale = TypeSize::Fixed(16);
2818     Width = 0;
2819     MinOffset = 0;
2820     MaxOffset = 63;
2821     break;
2822   case AArch64::TAGPstack:
2823     Scale = TypeSize::Fixed(16);
2824     Width = 0;
2825     // TAGP with a negative offset turns into SUBP, which has a maximum offset
2826     // of 63 (not 64!).
2827     MinOffset = -63;
2828     MaxOffset = 63;
2829     break;
2830   case AArch64::LDG:
2831   case AArch64::STGOffset:
2832   case AArch64::STZGOffset:
2833     Scale = TypeSize::Fixed(16);
2834     Width = 16;
2835     MinOffset = -256;
2836     MaxOffset = 255;
2837     break;
2838   case AArch64::STR_ZZZZXI:
2839   case AArch64::LDR_ZZZZXI:
2840     Scale = TypeSize::Scalable(16);
2841     Width = SVEMaxBytesPerVector * 4;
2842     MinOffset = -256;
2843     MaxOffset = 252;
2844     break;
2845   case AArch64::STR_ZZZXI:
2846   case AArch64::LDR_ZZZXI:
2847     Scale = TypeSize::Scalable(16);
2848     Width = SVEMaxBytesPerVector * 3;
2849     MinOffset = -256;
2850     MaxOffset = 253;
2851     break;
2852   case AArch64::STR_ZZXI:
2853   case AArch64::LDR_ZZXI:
2854     Scale = TypeSize::Scalable(16);
2855     Width = SVEMaxBytesPerVector * 2;
2856     MinOffset = -256;
2857     MaxOffset = 254;
2858     break;
2859   case AArch64::LDR_PXI:
2860   case AArch64::STR_PXI:
2861     Scale = TypeSize::Scalable(2);
2862     Width = SVEMaxBytesPerVector / 8;
2863     MinOffset = -256;
2864     MaxOffset = 255;
2865     break;
2866   case AArch64::LDR_ZXI:
2867   case AArch64::STR_ZXI:
2868     Scale = TypeSize::Scalable(16);
2869     Width = SVEMaxBytesPerVector;
2870     MinOffset = -256;
2871     MaxOffset = 255;
2872     break;
2873   case AArch64::LD1B_IMM:
2874   case AArch64::LD1H_IMM:
2875   case AArch64::LD1W_IMM:
2876   case AArch64::LD1D_IMM:
2877   case AArch64::LDNT1B_ZRI:
2878   case AArch64::LDNT1H_ZRI:
2879   case AArch64::LDNT1W_ZRI:
2880   case AArch64::LDNT1D_ZRI:
2881   case AArch64::ST1B_IMM:
2882   case AArch64::ST1H_IMM:
2883   case AArch64::ST1W_IMM:
2884   case AArch64::ST1D_IMM:
2885   case AArch64::STNT1B_ZRI:
2886   case AArch64::STNT1H_ZRI:
2887   case AArch64::STNT1W_ZRI:
2888   case AArch64::STNT1D_ZRI:
2889   case AArch64::LDNF1B_IMM:
2890   case AArch64::LDNF1H_IMM:
2891   case AArch64::LDNF1W_IMM:
2892   case AArch64::LDNF1D_IMM:
2893     // A full vectors worth of data
2894     // Width = mbytes * elements
2895     Scale = TypeSize::Scalable(16);
2896     Width = SVEMaxBytesPerVector;
2897     MinOffset = -8;
2898     MaxOffset = 7;
2899     break;
2900   case AArch64::LD1B_H_IMM:
2901   case AArch64::LD1SB_H_IMM:
2902   case AArch64::LD1H_S_IMM:
2903   case AArch64::LD1SH_S_IMM:
2904   case AArch64::LD1W_D_IMM:
2905   case AArch64::LD1SW_D_IMM:
2906   case AArch64::ST1B_H_IMM:
2907   case AArch64::ST1H_S_IMM:
2908   case AArch64::ST1W_D_IMM:
2909   case AArch64::LDNF1B_H_IMM:
2910   case AArch64::LDNF1SB_H_IMM:
2911   case AArch64::LDNF1H_S_IMM:
2912   case AArch64::LDNF1SH_S_IMM:
2913   case AArch64::LDNF1W_D_IMM:
2914   case AArch64::LDNF1SW_D_IMM:
2915     // A half vector worth of data
2916     // Width = mbytes * elements
2917     Scale = TypeSize::Scalable(8);
2918     Width = SVEMaxBytesPerVector / 2;
2919     MinOffset = -8;
2920     MaxOffset = 7;
2921     break;
2922   case AArch64::LD1B_S_IMM:
2923   case AArch64::LD1SB_S_IMM:
2924   case AArch64::LD1H_D_IMM:
2925   case AArch64::LD1SH_D_IMM:
2926   case AArch64::ST1B_S_IMM:
2927   case AArch64::ST1H_D_IMM:
2928   case AArch64::LDNF1B_S_IMM:
2929   case AArch64::LDNF1SB_S_IMM:
2930   case AArch64::LDNF1H_D_IMM:
2931   case AArch64::LDNF1SH_D_IMM:
2932     // A quarter vector worth of data
2933     // Width = mbytes * elements
2934     Scale = TypeSize::Scalable(4);
2935     Width = SVEMaxBytesPerVector / 4;
2936     MinOffset = -8;
2937     MaxOffset = 7;
2938     break;
2939   case AArch64::LD1B_D_IMM:
2940   case AArch64::LD1SB_D_IMM:
2941   case AArch64::ST1B_D_IMM:
2942   case AArch64::LDNF1B_D_IMM:
2943   case AArch64::LDNF1SB_D_IMM:
2944     // A eighth vector worth of data
2945     // Width = mbytes * elements
2946     Scale = TypeSize::Scalable(2);
2947     Width = SVEMaxBytesPerVector / 8;
2948     MinOffset = -8;
2949     MaxOffset = 7;
2950     break;
2951   case AArch64::ST2GOffset:
2952   case AArch64::STZ2GOffset:
2953     Scale = TypeSize::Fixed(16);
2954     Width = 32;
2955     MinOffset = -256;
2956     MaxOffset = 255;
2957     break;
2958   case AArch64::STGPi:
2959     Scale = TypeSize::Fixed(16);
2960     Width = 16;
2961     MinOffset = -64;
2962     MaxOffset = 63;
2963     break;
2964   case AArch64::LD1RB_IMM:
2965   case AArch64::LD1RB_H_IMM:
2966   case AArch64::LD1RB_S_IMM:
2967   case AArch64::LD1RB_D_IMM:
2968   case AArch64::LD1RSB_H_IMM:
2969   case AArch64::LD1RSB_S_IMM:
2970   case AArch64::LD1RSB_D_IMM:
2971     Scale = TypeSize::Fixed(1);
2972     Width = 1;
2973     MinOffset = 0;
2974     MaxOffset = 63;
2975     break;
2976   case AArch64::LD1RH_IMM:
2977   case AArch64::LD1RH_S_IMM:
2978   case AArch64::LD1RH_D_IMM:
2979   case AArch64::LD1RSH_S_IMM:
2980   case AArch64::LD1RSH_D_IMM:
2981     Scale = TypeSize::Fixed(2);
2982     Width = 2;
2983     MinOffset = 0;
2984     MaxOffset = 63;
2985     break;
2986   case AArch64::LD1RW_IMM:
2987   case AArch64::LD1RW_D_IMM:
2988   case AArch64::LD1RSW_IMM:
2989     Scale = TypeSize::Fixed(4);
2990     Width = 4;
2991     MinOffset = 0;
2992     MaxOffset = 63;
2993     break;
2994   case AArch64::LD1RD_IMM:
2995     Scale = TypeSize::Fixed(8);
2996     Width = 8;
2997     MinOffset = 0;
2998     MaxOffset = 63;
2999     break;
3000   }
3001 
3002   return true;
3003 }
3004 
3005 // Scaling factor for unscaled load or store.
3006 int AArch64InstrInfo::getMemScale(unsigned Opc) {
3007   switch (Opc) {
3008   default:
3009     llvm_unreachable("Opcode has unknown scale!");
3010   case AArch64::LDRBBui:
3011   case AArch64::LDURBBi:
3012   case AArch64::LDRSBWui:
3013   case AArch64::LDURSBWi:
3014   case AArch64::STRBBui:
3015   case AArch64::STURBBi:
3016     return 1;
3017   case AArch64::LDRHHui:
3018   case AArch64::LDURHHi:
3019   case AArch64::LDRSHWui:
3020   case AArch64::LDURSHWi:
3021   case AArch64::STRHHui:
3022   case AArch64::STURHHi:
3023     return 2;
3024   case AArch64::LDRSui:
3025   case AArch64::LDURSi:
3026   case AArch64::LDRSpre:
3027   case AArch64::LDRSWui:
3028   case AArch64::LDURSWi:
3029   case AArch64::LDRWpre:
3030   case AArch64::LDRWui:
3031   case AArch64::LDURWi:
3032   case AArch64::STRSui:
3033   case AArch64::STURSi:
3034   case AArch64::STRSpre:
3035   case AArch64::STRWui:
3036   case AArch64::STURWi:
3037   case AArch64::STRWpre:
3038   case AArch64::LDPSi:
3039   case AArch64::LDPSWi:
3040   case AArch64::LDPWi:
3041   case AArch64::STPSi:
3042   case AArch64::STPWi:
3043     return 4;
3044   case AArch64::LDRDui:
3045   case AArch64::LDURDi:
3046   case AArch64::LDRDpre:
3047   case AArch64::LDRXui:
3048   case AArch64::LDURXi:
3049   case AArch64::LDRXpre:
3050   case AArch64::STRDui:
3051   case AArch64::STURDi:
3052   case AArch64::STRDpre:
3053   case AArch64::STRXui:
3054   case AArch64::STURXi:
3055   case AArch64::STRXpre:
3056   case AArch64::LDPDi:
3057   case AArch64::LDPXi:
3058   case AArch64::STPDi:
3059   case AArch64::STPXi:
3060     return 8;
3061   case AArch64::LDRQui:
3062   case AArch64::LDURQi:
3063   case AArch64::STRQui:
3064   case AArch64::STURQi:
3065   case AArch64::STRQpre:
3066   case AArch64::LDPQi:
3067   case AArch64::LDRQpre:
3068   case AArch64::STPQi:
3069   case AArch64::STGOffset:
3070   case AArch64::STZGOffset:
3071   case AArch64::ST2GOffset:
3072   case AArch64::STZ2GOffset:
3073   case AArch64::STGPi:
3074     return 16;
3075   }
3076 }
3077 
3078 bool AArch64InstrInfo::isPreLd(const MachineInstr &MI) {
3079   switch (MI.getOpcode()) {
3080   default:
3081     return false;
3082   case AArch64::LDRWpre:
3083   case AArch64::LDRXpre:
3084   case AArch64::LDRSpre:
3085   case AArch64::LDRDpre:
3086   case AArch64::LDRQpre:
3087     return true;
3088   }
3089 }
3090 
3091 bool AArch64InstrInfo::isPreSt(const MachineInstr &MI) {
3092   switch (MI.getOpcode()) {
3093   default:
3094     return false;
3095   case AArch64::STRWpre:
3096   case AArch64::STRXpre:
3097   case AArch64::STRSpre:
3098   case AArch64::STRDpre:
3099   case AArch64::STRQpre:
3100     return true;
3101   }
3102 }
3103 
3104 bool AArch64InstrInfo::isPreLdSt(const MachineInstr &MI) {
3105   return isPreLd(MI) || isPreSt(MI);
3106 }
3107 
3108 static const TargetRegisterClass *getRegClass(const MachineInstr &MI,
3109                                               Register Reg) {
3110   if (MI.getParent() == nullptr)
3111     return nullptr;
3112   const MachineFunction *MF = MI.getParent()->getParent();
3113   return MF ? MF->getRegInfo().getRegClassOrNull(Reg) : nullptr;
3114 }
3115 
3116 bool AArch64InstrInfo::isQForm(const MachineInstr &MI) {
3117   auto IsQFPR = [&](const MachineOperand &Op) {
3118     if (!Op.isReg())
3119       return false;
3120     auto Reg = Op.getReg();
3121     if (Reg.isPhysical())
3122       return AArch64::FPR128RegClass.contains(Reg);
3123     const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
3124     return TRC == &AArch64::FPR128RegClass ||
3125            TRC == &AArch64::FPR128_loRegClass;
3126   };
3127   return llvm::any_of(MI.operands(), IsQFPR);
3128 }
3129 
3130 bool AArch64InstrInfo::isFpOrNEON(const MachineInstr &MI) {
3131   auto IsFPR = [&](const MachineOperand &Op) {
3132     if (!Op.isReg())
3133       return false;
3134     auto Reg = Op.getReg();
3135     if (Reg.isPhysical())
3136       return AArch64::FPR128RegClass.contains(Reg) ||
3137              AArch64::FPR64RegClass.contains(Reg) ||
3138              AArch64::FPR32RegClass.contains(Reg) ||
3139              AArch64::FPR16RegClass.contains(Reg) ||
3140              AArch64::FPR8RegClass.contains(Reg);
3141 
3142     const TargetRegisterClass *TRC = ::getRegClass(MI, Reg);
3143     return TRC == &AArch64::FPR128RegClass ||
3144            TRC == &AArch64::FPR128_loRegClass ||
3145            TRC == &AArch64::FPR64RegClass ||
3146            TRC == &AArch64::FPR64_loRegClass ||
3147            TRC == &AArch64::FPR32RegClass || TRC == &AArch64::FPR16RegClass ||
3148            TRC == &AArch64::FPR8RegClass;
3149   };
3150   return llvm::any_of(MI.operands(), IsFPR);
3151 }
3152 
3153 // Scale the unscaled offsets.  Returns false if the unscaled offset can't be
3154 // scaled.
3155 static bool scaleOffset(unsigned Opc, int64_t &Offset) {
3156   int Scale = AArch64InstrInfo::getMemScale(Opc);
3157 
3158   // If the byte-offset isn't a multiple of the stride, we can't scale this
3159   // offset.
3160   if (Offset % Scale != 0)
3161     return false;
3162 
3163   // Convert the byte-offset used by unscaled into an "element" offset used
3164   // by the scaled pair load/store instructions.
3165   Offset /= Scale;
3166   return true;
3167 }
3168 
3169 static bool canPairLdStOpc(unsigned FirstOpc, unsigned SecondOpc) {
3170   if (FirstOpc == SecondOpc)
3171     return true;
3172   // We can also pair sign-ext and zero-ext instructions.
3173   switch (FirstOpc) {
3174   default:
3175     return false;
3176   case AArch64::LDRWui:
3177   case AArch64::LDURWi:
3178     return SecondOpc == AArch64::LDRSWui || SecondOpc == AArch64::LDURSWi;
3179   case AArch64::LDRSWui:
3180   case AArch64::LDURSWi:
3181     return SecondOpc == AArch64::LDRWui || SecondOpc == AArch64::LDURWi;
3182   }
3183   // These instructions can't be paired based on their opcodes.
3184   return false;
3185 }
3186 
3187 static bool shouldClusterFI(const MachineFrameInfo &MFI, int FI1,
3188                             int64_t Offset1, unsigned Opcode1, int FI2,
3189                             int64_t Offset2, unsigned Opcode2) {
3190   // Accesses through fixed stack object frame indices may access a different
3191   // fixed stack slot. Check that the object offsets + offsets match.
3192   if (MFI.isFixedObjectIndex(FI1) && MFI.isFixedObjectIndex(FI2)) {
3193     int64_t ObjectOffset1 = MFI.getObjectOffset(FI1);
3194     int64_t ObjectOffset2 = MFI.getObjectOffset(FI2);
3195     assert(ObjectOffset1 <= ObjectOffset2 && "Object offsets are not ordered.");
3196     // Convert to scaled object offsets.
3197     int Scale1 = AArch64InstrInfo::getMemScale(Opcode1);
3198     if (ObjectOffset1 % Scale1 != 0)
3199       return false;
3200     ObjectOffset1 /= Scale1;
3201     int Scale2 = AArch64InstrInfo::getMemScale(Opcode2);
3202     if (ObjectOffset2 % Scale2 != 0)
3203       return false;
3204     ObjectOffset2 /= Scale2;
3205     ObjectOffset1 += Offset1;
3206     ObjectOffset2 += Offset2;
3207     return ObjectOffset1 + 1 == ObjectOffset2;
3208   }
3209 
3210   return FI1 == FI2;
3211 }
3212 
3213 /// Detect opportunities for ldp/stp formation.
3214 ///
3215 /// Only called for LdSt for which getMemOperandWithOffset returns true.
3216 bool AArch64InstrInfo::shouldClusterMemOps(
3217     ArrayRef<const MachineOperand *> BaseOps1,
3218     ArrayRef<const MachineOperand *> BaseOps2, unsigned NumLoads,
3219     unsigned NumBytes) const {
3220   assert(BaseOps1.size() == 1 && BaseOps2.size() == 1);
3221   const MachineOperand &BaseOp1 = *BaseOps1.front();
3222   const MachineOperand &BaseOp2 = *BaseOps2.front();
3223   const MachineInstr &FirstLdSt = *BaseOp1.getParent();
3224   const MachineInstr &SecondLdSt = *BaseOp2.getParent();
3225   if (BaseOp1.getType() != BaseOp2.getType())
3226     return false;
3227 
3228   assert((BaseOp1.isReg() || BaseOp1.isFI()) &&
3229          "Only base registers and frame indices are supported.");
3230 
3231   // Check for both base regs and base FI.
3232   if (BaseOp1.isReg() && BaseOp1.getReg() != BaseOp2.getReg())
3233     return false;
3234 
3235   // Only cluster up to a single pair.
3236   if (NumLoads > 2)
3237     return false;
3238 
3239   if (!isPairableLdStInst(FirstLdSt) || !isPairableLdStInst(SecondLdSt))
3240     return false;
3241 
3242   // Can we pair these instructions based on their opcodes?
3243   unsigned FirstOpc = FirstLdSt.getOpcode();
3244   unsigned SecondOpc = SecondLdSt.getOpcode();
3245   if (!canPairLdStOpc(FirstOpc, SecondOpc))
3246     return false;
3247 
3248   // Can't merge volatiles or load/stores that have a hint to avoid pair
3249   // formation, for example.
3250   if (!isCandidateToMergeOrPair(FirstLdSt) ||
3251       !isCandidateToMergeOrPair(SecondLdSt))
3252     return false;
3253 
3254   // isCandidateToMergeOrPair guarantees that operand 2 is an immediate.
3255   int64_t Offset1 = FirstLdSt.getOperand(2).getImm();
3256   if (hasUnscaledLdStOffset(FirstOpc) && !scaleOffset(FirstOpc, Offset1))
3257     return false;
3258 
3259   int64_t Offset2 = SecondLdSt.getOperand(2).getImm();
3260   if (hasUnscaledLdStOffset(SecondOpc) && !scaleOffset(SecondOpc, Offset2))
3261     return false;
3262 
3263   // Pairwise instructions have a 7-bit signed offset field.
3264   if (Offset1 > 63 || Offset1 < -64)
3265     return false;
3266 
3267   // The caller should already have ordered First/SecondLdSt by offset.
3268   // Note: except for non-equal frame index bases
3269   if (BaseOp1.isFI()) {
3270     assert((!BaseOp1.isIdenticalTo(BaseOp2) || Offset1 <= Offset2) &&
3271            "Caller should have ordered offsets.");
3272 
3273     const MachineFrameInfo &MFI =
3274         FirstLdSt.getParent()->getParent()->getFrameInfo();
3275     return shouldClusterFI(MFI, BaseOp1.getIndex(), Offset1, FirstOpc,
3276                            BaseOp2.getIndex(), Offset2, SecondOpc);
3277   }
3278 
3279   assert(Offset1 <= Offset2 && "Caller should have ordered offsets.");
3280 
3281   return Offset1 + 1 == Offset2;
3282 }
3283 
3284 static const MachineInstrBuilder &AddSubReg(const MachineInstrBuilder &MIB,
3285                                             unsigned Reg, unsigned SubIdx,
3286                                             unsigned State,
3287                                             const TargetRegisterInfo *TRI) {
3288   if (!SubIdx)
3289     return MIB.addReg(Reg, State);
3290 
3291   if (Register::isPhysicalRegister(Reg))
3292     return MIB.addReg(TRI->getSubReg(Reg, SubIdx), State);
3293   return MIB.addReg(Reg, State, SubIdx);
3294 }
3295 
3296 static bool forwardCopyWillClobberTuple(unsigned DestReg, unsigned SrcReg,
3297                                         unsigned NumRegs) {
3298   // We really want the positive remainder mod 32 here, that happens to be
3299   // easily obtainable with a mask.
3300   return ((DestReg - SrcReg) & 0x1f) < NumRegs;
3301 }
3302 
3303 void AArch64InstrInfo::copyPhysRegTuple(MachineBasicBlock &MBB,
3304                                         MachineBasicBlock::iterator I,
3305                                         const DebugLoc &DL, MCRegister DestReg,
3306                                         MCRegister SrcReg, bool KillSrc,
3307                                         unsigned Opcode,
3308                                         ArrayRef<unsigned> Indices) const {
3309   assert(Subtarget.hasNEON() && "Unexpected register copy without NEON");
3310   const TargetRegisterInfo *TRI = &getRegisterInfo();
3311   uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
3312   uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
3313   unsigned NumRegs = Indices.size();
3314 
3315   int SubReg = 0, End = NumRegs, Incr = 1;
3316   if (forwardCopyWillClobberTuple(DestEncoding, SrcEncoding, NumRegs)) {
3317     SubReg = NumRegs - 1;
3318     End = -1;
3319     Incr = -1;
3320   }
3321 
3322   for (; SubReg != End; SubReg += Incr) {
3323     const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
3324     AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
3325     AddSubReg(MIB, SrcReg, Indices[SubReg], 0, TRI);
3326     AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
3327   }
3328 }
3329 
3330 void AArch64InstrInfo::copyGPRRegTuple(MachineBasicBlock &MBB,
3331                                        MachineBasicBlock::iterator I,
3332                                        DebugLoc DL, unsigned DestReg,
3333                                        unsigned SrcReg, bool KillSrc,
3334                                        unsigned Opcode, unsigned ZeroReg,
3335                                        llvm::ArrayRef<unsigned> Indices) const {
3336   const TargetRegisterInfo *TRI = &getRegisterInfo();
3337   unsigned NumRegs = Indices.size();
3338 
3339 #ifndef NDEBUG
3340   uint16_t DestEncoding = TRI->getEncodingValue(DestReg);
3341   uint16_t SrcEncoding = TRI->getEncodingValue(SrcReg);
3342   assert(DestEncoding % NumRegs == 0 && SrcEncoding % NumRegs == 0 &&
3343          "GPR reg sequences should not be able to overlap");
3344 #endif
3345 
3346   for (unsigned SubReg = 0; SubReg != NumRegs; ++SubReg) {
3347     const MachineInstrBuilder MIB = BuildMI(MBB, I, DL, get(Opcode));
3348     AddSubReg(MIB, DestReg, Indices[SubReg], RegState::Define, TRI);
3349     MIB.addReg(ZeroReg);
3350     AddSubReg(MIB, SrcReg, Indices[SubReg], getKillRegState(KillSrc), TRI);
3351     MIB.addImm(0);
3352   }
3353 }
3354 
3355 void AArch64InstrInfo::copyPhysReg(MachineBasicBlock &MBB,
3356                                    MachineBasicBlock::iterator I,
3357                                    const DebugLoc &DL, MCRegister DestReg,
3358                                    MCRegister SrcReg, bool KillSrc) const {
3359   if (AArch64::GPR32spRegClass.contains(DestReg) &&
3360       (AArch64::GPR32spRegClass.contains(SrcReg) || SrcReg == AArch64::WZR)) {
3361     const TargetRegisterInfo *TRI = &getRegisterInfo();
3362 
3363     if (DestReg == AArch64::WSP || SrcReg == AArch64::WSP) {
3364       // If either operand is WSP, expand to ADD #0.
3365       if (Subtarget.hasZeroCycleRegMove()) {
3366         // Cyclone recognizes "ADD Xd, Xn, #0" as a zero-cycle register move.
3367         MCRegister DestRegX = TRI->getMatchingSuperReg(
3368             DestReg, AArch64::sub_32, &AArch64::GPR64spRegClass);
3369         MCRegister SrcRegX = TRI->getMatchingSuperReg(
3370             SrcReg, AArch64::sub_32, &AArch64::GPR64spRegClass);
3371         // This instruction is reading and writing X registers.  This may upset
3372         // the register scavenger and machine verifier, so we need to indicate
3373         // that we are reading an undefined value from SrcRegX, but a proper
3374         // value from SrcReg.
3375         BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestRegX)
3376             .addReg(SrcRegX, RegState::Undef)
3377             .addImm(0)
3378             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0))
3379             .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
3380       } else {
3381         BuildMI(MBB, I, DL, get(AArch64::ADDWri), DestReg)
3382             .addReg(SrcReg, getKillRegState(KillSrc))
3383             .addImm(0)
3384             .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
3385       }
3386     } else if (SrcReg == AArch64::WZR && Subtarget.hasZeroCycleZeroingGP()) {
3387       BuildMI(MBB, I, DL, get(AArch64::MOVZWi), DestReg)
3388           .addImm(0)
3389           .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
3390     } else {
3391       if (Subtarget.hasZeroCycleRegMove()) {
3392         // Cyclone recognizes "ORR Xd, XZR, Xm" as a zero-cycle register move.
3393         MCRegister DestRegX = TRI->getMatchingSuperReg(
3394             DestReg, AArch64::sub_32, &AArch64::GPR64spRegClass);
3395         MCRegister SrcRegX = TRI->getMatchingSuperReg(
3396             SrcReg, AArch64::sub_32, &AArch64::GPR64spRegClass);
3397         // This instruction is reading and writing X registers.  This may upset
3398         // the register scavenger and machine verifier, so we need to indicate
3399         // that we are reading an undefined value from SrcRegX, but a proper
3400         // value from SrcReg.
3401         BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestRegX)
3402             .addReg(AArch64::XZR)
3403             .addReg(SrcRegX, RegState::Undef)
3404             .addReg(SrcReg, RegState::Implicit | getKillRegState(KillSrc));
3405       } else {
3406         // Otherwise, expand to ORR WZR.
3407         BuildMI(MBB, I, DL, get(AArch64::ORRWrr), DestReg)
3408             .addReg(AArch64::WZR)
3409             .addReg(SrcReg, getKillRegState(KillSrc));
3410       }
3411     }
3412     return;
3413   }
3414 
3415   // Copy a Predicate register by ORRing with itself.
3416   if (AArch64::PPRRegClass.contains(DestReg) &&
3417       AArch64::PPRRegClass.contains(SrcReg)) {
3418     assert(Subtarget.hasSVE() && "Unexpected SVE register.");
3419     BuildMI(MBB, I, DL, get(AArch64::ORR_PPzPP), DestReg)
3420       .addReg(SrcReg) // Pg
3421       .addReg(SrcReg)
3422       .addReg(SrcReg, getKillRegState(KillSrc));
3423     return;
3424   }
3425 
3426   // Copy a Z register by ORRing with itself.
3427   if (AArch64::ZPRRegClass.contains(DestReg) &&
3428       AArch64::ZPRRegClass.contains(SrcReg)) {
3429     assert(Subtarget.hasSVE() && "Unexpected SVE register.");
3430     BuildMI(MBB, I, DL, get(AArch64::ORR_ZZZ), DestReg)
3431       .addReg(SrcReg)
3432       .addReg(SrcReg, getKillRegState(KillSrc));
3433     return;
3434   }
3435 
3436   // Copy a Z register pair by copying the individual sub-registers.
3437   if (AArch64::ZPR2RegClass.contains(DestReg) &&
3438       AArch64::ZPR2RegClass.contains(SrcReg)) {
3439     static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1};
3440     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ,
3441                      Indices);
3442     return;
3443   }
3444 
3445   // Copy a Z register triple by copying the individual sub-registers.
3446   if (AArch64::ZPR3RegClass.contains(DestReg) &&
3447       AArch64::ZPR3RegClass.contains(SrcReg)) {
3448     static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
3449                                        AArch64::zsub2};
3450     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ,
3451                      Indices);
3452     return;
3453   }
3454 
3455   // Copy a Z register quad by copying the individual sub-registers.
3456   if (AArch64::ZPR4RegClass.contains(DestReg) &&
3457       AArch64::ZPR4RegClass.contains(SrcReg)) {
3458     static const unsigned Indices[] = {AArch64::zsub0, AArch64::zsub1,
3459                                        AArch64::zsub2, AArch64::zsub3};
3460     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORR_ZZZ,
3461                      Indices);
3462     return;
3463   }
3464 
3465   if (AArch64::GPR64spRegClass.contains(DestReg) &&
3466       (AArch64::GPR64spRegClass.contains(SrcReg) || SrcReg == AArch64::XZR)) {
3467     if (DestReg == AArch64::SP || SrcReg == AArch64::SP) {
3468       // If either operand is SP, expand to ADD #0.
3469       BuildMI(MBB, I, DL, get(AArch64::ADDXri), DestReg)
3470           .addReg(SrcReg, getKillRegState(KillSrc))
3471           .addImm(0)
3472           .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
3473     } else if (SrcReg == AArch64::XZR && Subtarget.hasZeroCycleZeroingGP()) {
3474       BuildMI(MBB, I, DL, get(AArch64::MOVZXi), DestReg)
3475           .addImm(0)
3476           .addImm(AArch64_AM::getShifterImm(AArch64_AM::LSL, 0));
3477     } else {
3478       // Otherwise, expand to ORR XZR.
3479       BuildMI(MBB, I, DL, get(AArch64::ORRXrr), DestReg)
3480           .addReg(AArch64::XZR)
3481           .addReg(SrcReg, getKillRegState(KillSrc));
3482     }
3483     return;
3484   }
3485 
3486   // Copy a DDDD register quad by copying the individual sub-registers.
3487   if (AArch64::DDDDRegClass.contains(DestReg) &&
3488       AArch64::DDDDRegClass.contains(SrcReg)) {
3489     static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
3490                                        AArch64::dsub2, AArch64::dsub3};
3491     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8,
3492                      Indices);
3493     return;
3494   }
3495 
3496   // Copy a DDD register triple by copying the individual sub-registers.
3497   if (AArch64::DDDRegClass.contains(DestReg) &&
3498       AArch64::DDDRegClass.contains(SrcReg)) {
3499     static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1,
3500                                        AArch64::dsub2};
3501     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8,
3502                      Indices);
3503     return;
3504   }
3505 
3506   // Copy a DD register pair by copying the individual sub-registers.
3507   if (AArch64::DDRegClass.contains(DestReg) &&
3508       AArch64::DDRegClass.contains(SrcReg)) {
3509     static const unsigned Indices[] = {AArch64::dsub0, AArch64::dsub1};
3510     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv8i8,
3511                      Indices);
3512     return;
3513   }
3514 
3515   // Copy a QQQQ register quad by copying the individual sub-registers.
3516   if (AArch64::QQQQRegClass.contains(DestReg) &&
3517       AArch64::QQQQRegClass.contains(SrcReg)) {
3518     static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
3519                                        AArch64::qsub2, AArch64::qsub3};
3520     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8,
3521                      Indices);
3522     return;
3523   }
3524 
3525   // Copy a QQQ register triple by copying the individual sub-registers.
3526   if (AArch64::QQQRegClass.contains(DestReg) &&
3527       AArch64::QQQRegClass.contains(SrcReg)) {
3528     static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1,
3529                                        AArch64::qsub2};
3530     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8,
3531                      Indices);
3532     return;
3533   }
3534 
3535   // Copy a QQ register pair by copying the individual sub-registers.
3536   if (AArch64::QQRegClass.contains(DestReg) &&
3537       AArch64::QQRegClass.contains(SrcReg)) {
3538     static const unsigned Indices[] = {AArch64::qsub0, AArch64::qsub1};
3539     copyPhysRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRv16i8,
3540                      Indices);
3541     return;
3542   }
3543 
3544   if (AArch64::XSeqPairsClassRegClass.contains(DestReg) &&
3545       AArch64::XSeqPairsClassRegClass.contains(SrcReg)) {
3546     static const unsigned Indices[] = {AArch64::sube64, AArch64::subo64};
3547     copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRXrs,
3548                     AArch64::XZR, Indices);
3549     return;
3550   }
3551 
3552   if (AArch64::WSeqPairsClassRegClass.contains(DestReg) &&
3553       AArch64::WSeqPairsClassRegClass.contains(SrcReg)) {
3554     static const unsigned Indices[] = {AArch64::sube32, AArch64::subo32};
3555     copyGPRRegTuple(MBB, I, DL, DestReg, SrcReg, KillSrc, AArch64::ORRWrs,
3556                     AArch64::WZR, Indices);
3557     return;
3558   }
3559 
3560   if (AArch64::FPR128RegClass.contains(DestReg) &&
3561       AArch64::FPR128RegClass.contains(SrcReg)) {
3562     if (Subtarget.hasNEON()) {
3563       BuildMI(MBB, I, DL, get(AArch64::ORRv16i8), DestReg)
3564           .addReg(SrcReg)
3565           .addReg(SrcReg, getKillRegState(KillSrc));
3566     } else {
3567       BuildMI(MBB, I, DL, get(AArch64::STRQpre))
3568           .addReg(AArch64::SP, RegState::Define)
3569           .addReg(SrcReg, getKillRegState(KillSrc))
3570           .addReg(AArch64::SP)
3571           .addImm(-16);
3572       BuildMI(MBB, I, DL, get(AArch64::LDRQpre))
3573           .addReg(AArch64::SP, RegState::Define)
3574           .addReg(DestReg, RegState::Define)
3575           .addReg(AArch64::SP)
3576           .addImm(16);
3577     }
3578     return;
3579   }
3580 
3581   if (AArch64::FPR64RegClass.contains(DestReg) &&
3582       AArch64::FPR64RegClass.contains(SrcReg)) {
3583     BuildMI(MBB, I, DL, get(AArch64::FMOVDr), DestReg)
3584         .addReg(SrcReg, getKillRegState(KillSrc));
3585     return;
3586   }
3587 
3588   if (AArch64::FPR32RegClass.contains(DestReg) &&
3589       AArch64::FPR32RegClass.contains(SrcReg)) {
3590     BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
3591         .addReg(SrcReg, getKillRegState(KillSrc));
3592     return;
3593   }
3594 
3595   if (AArch64::FPR16RegClass.contains(DestReg) &&
3596       AArch64::FPR16RegClass.contains(SrcReg)) {
3597     DestReg =
3598         RI.getMatchingSuperReg(DestReg, AArch64::hsub, &AArch64::FPR32RegClass);
3599     SrcReg =
3600         RI.getMatchingSuperReg(SrcReg, AArch64::hsub, &AArch64::FPR32RegClass);
3601     BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
3602         .addReg(SrcReg, getKillRegState(KillSrc));
3603     return;
3604   }
3605 
3606   if (AArch64::FPR8RegClass.contains(DestReg) &&
3607       AArch64::FPR8RegClass.contains(SrcReg)) {
3608     DestReg =
3609         RI.getMatchingSuperReg(DestReg, AArch64::bsub, &AArch64::FPR32RegClass);
3610     SrcReg =
3611         RI.getMatchingSuperReg(SrcReg, AArch64::bsub, &AArch64::FPR32RegClass);
3612     BuildMI(MBB, I, DL, get(AArch64::FMOVSr), DestReg)
3613         .addReg(SrcReg, getKillRegState(KillSrc));
3614     return;
3615   }
3616 
3617   // Copies between GPR64 and FPR64.
3618   if (AArch64::FPR64RegClass.contains(DestReg) &&
3619       AArch64::GPR64RegClass.contains(SrcReg)) {
3620     BuildMI(MBB, I, DL, get(AArch64::FMOVXDr), DestReg)
3621         .addReg(SrcReg, getKillRegState(KillSrc));
3622     return;
3623   }
3624   if (AArch64::GPR64RegClass.contains(DestReg) &&
3625       AArch64::FPR64RegClass.contains(SrcReg)) {
3626     BuildMI(MBB, I, DL, get(AArch64::FMOVDXr), DestReg)
3627         .addReg(SrcReg, getKillRegState(KillSrc));
3628     return;
3629   }
3630   // Copies between GPR32 and FPR32.
3631   if (AArch64::FPR32RegClass.contains(DestReg) &&
3632       AArch64::GPR32RegClass.contains(SrcReg)) {
3633     BuildMI(MBB, I, DL, get(AArch64::FMOVWSr), DestReg)
3634         .addReg(SrcReg, getKillRegState(KillSrc));
3635     return;
3636   }
3637   if (AArch64::GPR32RegClass.contains(DestReg) &&
3638       AArch64::FPR32RegClass.contains(SrcReg)) {
3639     BuildMI(MBB, I, DL, get(AArch64::FMOVSWr), DestReg)
3640         .addReg(SrcReg, getKillRegState(KillSrc));
3641     return;
3642   }
3643 
3644   if (DestReg == AArch64::NZCV) {
3645     assert(AArch64::GPR64RegClass.contains(SrcReg) && "Invalid NZCV copy");
3646     BuildMI(MBB, I, DL, get(AArch64::MSR))
3647         .addImm(AArch64SysReg::NZCV)
3648         .addReg(SrcReg, getKillRegState(KillSrc))
3649         .addReg(AArch64::NZCV, RegState::Implicit | RegState::Define);
3650     return;
3651   }
3652 
3653   if (SrcReg == AArch64::NZCV) {
3654     assert(AArch64::GPR64RegClass.contains(DestReg) && "Invalid NZCV copy");
3655     BuildMI(MBB, I, DL, get(AArch64::MRS), DestReg)
3656         .addImm(AArch64SysReg::NZCV)
3657         .addReg(AArch64::NZCV, RegState::Implicit | getKillRegState(KillSrc));
3658     return;
3659   }
3660 
3661 #ifndef NDEBUG
3662   const TargetRegisterInfo &TRI = getRegisterInfo();
3663   errs() << TRI.getRegAsmName(DestReg) << " = COPY "
3664          << TRI.getRegAsmName(SrcReg) << "\n";
3665 #endif
3666   llvm_unreachable("unimplemented reg-to-reg copy");
3667 }
3668 
3669 static void storeRegPairToStackSlot(const TargetRegisterInfo &TRI,
3670                                     MachineBasicBlock &MBB,
3671                                     MachineBasicBlock::iterator InsertBefore,
3672                                     const MCInstrDesc &MCID,
3673                                     Register SrcReg, bool IsKill,
3674                                     unsigned SubIdx0, unsigned SubIdx1, int FI,
3675                                     MachineMemOperand *MMO) {
3676   Register SrcReg0 = SrcReg;
3677   Register SrcReg1 = SrcReg;
3678   if (Register::isPhysicalRegister(SrcReg)) {
3679     SrcReg0 = TRI.getSubReg(SrcReg, SubIdx0);
3680     SubIdx0 = 0;
3681     SrcReg1 = TRI.getSubReg(SrcReg, SubIdx1);
3682     SubIdx1 = 0;
3683   }
3684   BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
3685       .addReg(SrcReg0, getKillRegState(IsKill), SubIdx0)
3686       .addReg(SrcReg1, getKillRegState(IsKill), SubIdx1)
3687       .addFrameIndex(FI)
3688       .addImm(0)
3689       .addMemOperand(MMO);
3690 }
3691 
3692 void AArch64InstrInfo::storeRegToStackSlot(
3693     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register SrcReg,
3694     bool isKill, int FI, const TargetRegisterClass *RC,
3695     const TargetRegisterInfo *TRI) const {
3696   MachineFunction &MF = *MBB.getParent();
3697   MachineFrameInfo &MFI = MF.getFrameInfo();
3698 
3699   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
3700   MachineMemOperand *MMO =
3701       MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOStore,
3702                               MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
3703   unsigned Opc = 0;
3704   bool Offset = true;
3705   unsigned StackID = TargetStackID::Default;
3706   switch (TRI->getSpillSize(*RC)) {
3707   case 1:
3708     if (AArch64::FPR8RegClass.hasSubClassEq(RC))
3709       Opc = AArch64::STRBui;
3710     break;
3711   case 2:
3712     if (AArch64::FPR16RegClass.hasSubClassEq(RC))
3713       Opc = AArch64::STRHui;
3714     else if (AArch64::PPRRegClass.hasSubClassEq(RC)) {
3715       assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
3716       Opc = AArch64::STR_PXI;
3717       StackID = TargetStackID::ScalableVector;
3718     }
3719     break;
3720   case 4:
3721     if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
3722       Opc = AArch64::STRWui;
3723       if (Register::isVirtualRegister(SrcReg))
3724         MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR32RegClass);
3725       else
3726         assert(SrcReg != AArch64::WSP);
3727     } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
3728       Opc = AArch64::STRSui;
3729     break;
3730   case 8:
3731     if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
3732       Opc = AArch64::STRXui;
3733       if (Register::isVirtualRegister(SrcReg))
3734         MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
3735       else
3736         assert(SrcReg != AArch64::SP);
3737     } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
3738       Opc = AArch64::STRDui;
3739     } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
3740       storeRegPairToStackSlot(getRegisterInfo(), MBB, MBBI,
3741                               get(AArch64::STPWi), SrcReg, isKill,
3742                               AArch64::sube32, AArch64::subo32, FI, MMO);
3743       return;
3744     }
3745     break;
3746   case 16:
3747     if (AArch64::FPR128RegClass.hasSubClassEq(RC))
3748       Opc = AArch64::STRQui;
3749     else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
3750       assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
3751       Opc = AArch64::ST1Twov1d;
3752       Offset = false;
3753     } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
3754       storeRegPairToStackSlot(getRegisterInfo(), MBB, MBBI,
3755                               get(AArch64::STPXi), SrcReg, isKill,
3756                               AArch64::sube64, AArch64::subo64, FI, MMO);
3757       return;
3758     } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
3759       assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
3760       Opc = AArch64::STR_ZXI;
3761       StackID = TargetStackID::ScalableVector;
3762     }
3763     break;
3764   case 24:
3765     if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
3766       assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
3767       Opc = AArch64::ST1Threev1d;
3768       Offset = false;
3769     }
3770     break;
3771   case 32:
3772     if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
3773       assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
3774       Opc = AArch64::ST1Fourv1d;
3775       Offset = false;
3776     } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
3777       assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
3778       Opc = AArch64::ST1Twov2d;
3779       Offset = false;
3780     } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
3781       assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
3782       Opc = AArch64::STR_ZZXI;
3783       StackID = TargetStackID::ScalableVector;
3784     }
3785     break;
3786   case 48:
3787     if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
3788       assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
3789       Opc = AArch64::ST1Threev2d;
3790       Offset = false;
3791     } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
3792       assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
3793       Opc = AArch64::STR_ZZZXI;
3794       StackID = TargetStackID::ScalableVector;
3795     }
3796     break;
3797   case 64:
3798     if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
3799       assert(Subtarget.hasNEON() && "Unexpected register store without NEON");
3800       Opc = AArch64::ST1Fourv2d;
3801       Offset = false;
3802     } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
3803       assert(Subtarget.hasSVE() && "Unexpected register store without SVE");
3804       Opc = AArch64::STR_ZZZZXI;
3805       StackID = TargetStackID::ScalableVector;
3806     }
3807     break;
3808   }
3809   assert(Opc && "Unknown register class");
3810   MFI.setStackID(FI, StackID);
3811 
3812   const MachineInstrBuilder MI = BuildMI(MBB, MBBI, DebugLoc(), get(Opc))
3813                                      .addReg(SrcReg, getKillRegState(isKill))
3814                                      .addFrameIndex(FI);
3815 
3816   if (Offset)
3817     MI.addImm(0);
3818   MI.addMemOperand(MMO);
3819 }
3820 
3821 static void loadRegPairFromStackSlot(const TargetRegisterInfo &TRI,
3822                                      MachineBasicBlock &MBB,
3823                                      MachineBasicBlock::iterator InsertBefore,
3824                                      const MCInstrDesc &MCID,
3825                                      Register DestReg, unsigned SubIdx0,
3826                                      unsigned SubIdx1, int FI,
3827                                      MachineMemOperand *MMO) {
3828   Register DestReg0 = DestReg;
3829   Register DestReg1 = DestReg;
3830   bool IsUndef = true;
3831   if (Register::isPhysicalRegister(DestReg)) {
3832     DestReg0 = TRI.getSubReg(DestReg, SubIdx0);
3833     SubIdx0 = 0;
3834     DestReg1 = TRI.getSubReg(DestReg, SubIdx1);
3835     SubIdx1 = 0;
3836     IsUndef = false;
3837   }
3838   BuildMI(MBB, InsertBefore, DebugLoc(), MCID)
3839       .addReg(DestReg0, RegState::Define | getUndefRegState(IsUndef), SubIdx0)
3840       .addReg(DestReg1, RegState::Define | getUndefRegState(IsUndef), SubIdx1)
3841       .addFrameIndex(FI)
3842       .addImm(0)
3843       .addMemOperand(MMO);
3844 }
3845 
3846 void AArch64InstrInfo::loadRegFromStackSlot(
3847     MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, Register DestReg,
3848     int FI, const TargetRegisterClass *RC,
3849     const TargetRegisterInfo *TRI) const {
3850   MachineFunction &MF = *MBB.getParent();
3851   MachineFrameInfo &MFI = MF.getFrameInfo();
3852   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(MF, FI);
3853   MachineMemOperand *MMO =
3854       MF.getMachineMemOperand(PtrInfo, MachineMemOperand::MOLoad,
3855                               MFI.getObjectSize(FI), MFI.getObjectAlign(FI));
3856 
3857   unsigned Opc = 0;
3858   bool Offset = true;
3859   unsigned StackID = TargetStackID::Default;
3860   switch (TRI->getSpillSize(*RC)) {
3861   case 1:
3862     if (AArch64::FPR8RegClass.hasSubClassEq(RC))
3863       Opc = AArch64::LDRBui;
3864     break;
3865   case 2:
3866     if (AArch64::FPR16RegClass.hasSubClassEq(RC))
3867       Opc = AArch64::LDRHui;
3868     else if (AArch64::PPRRegClass.hasSubClassEq(RC)) {
3869       assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
3870       Opc = AArch64::LDR_PXI;
3871       StackID = TargetStackID::ScalableVector;
3872     }
3873     break;
3874   case 4:
3875     if (AArch64::GPR32allRegClass.hasSubClassEq(RC)) {
3876       Opc = AArch64::LDRWui;
3877       if (Register::isVirtualRegister(DestReg))
3878         MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR32RegClass);
3879       else
3880         assert(DestReg != AArch64::WSP);
3881     } else if (AArch64::FPR32RegClass.hasSubClassEq(RC))
3882       Opc = AArch64::LDRSui;
3883     break;
3884   case 8:
3885     if (AArch64::GPR64allRegClass.hasSubClassEq(RC)) {
3886       Opc = AArch64::LDRXui;
3887       if (Register::isVirtualRegister(DestReg))
3888         MF.getRegInfo().constrainRegClass(DestReg, &AArch64::GPR64RegClass);
3889       else
3890         assert(DestReg != AArch64::SP);
3891     } else if (AArch64::FPR64RegClass.hasSubClassEq(RC)) {
3892       Opc = AArch64::LDRDui;
3893     } else if (AArch64::WSeqPairsClassRegClass.hasSubClassEq(RC)) {
3894       loadRegPairFromStackSlot(getRegisterInfo(), MBB, MBBI,
3895                                get(AArch64::LDPWi), DestReg, AArch64::sube32,
3896                                AArch64::subo32, FI, MMO);
3897       return;
3898     }
3899     break;
3900   case 16:
3901     if (AArch64::FPR128RegClass.hasSubClassEq(RC))
3902       Opc = AArch64::LDRQui;
3903     else if (AArch64::DDRegClass.hasSubClassEq(RC)) {
3904       assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
3905       Opc = AArch64::LD1Twov1d;
3906       Offset = false;
3907     } else if (AArch64::XSeqPairsClassRegClass.hasSubClassEq(RC)) {
3908       loadRegPairFromStackSlot(getRegisterInfo(), MBB, MBBI,
3909                                get(AArch64::LDPXi), DestReg, AArch64::sube64,
3910                                AArch64::subo64, FI, MMO);
3911       return;
3912     } else if (AArch64::ZPRRegClass.hasSubClassEq(RC)) {
3913       assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
3914       Opc = AArch64::LDR_ZXI;
3915       StackID = TargetStackID::ScalableVector;
3916     }
3917     break;
3918   case 24:
3919     if (AArch64::DDDRegClass.hasSubClassEq(RC)) {
3920       assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
3921       Opc = AArch64::LD1Threev1d;
3922       Offset = false;
3923     }
3924     break;
3925   case 32:
3926     if (AArch64::DDDDRegClass.hasSubClassEq(RC)) {
3927       assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
3928       Opc = AArch64::LD1Fourv1d;
3929       Offset = false;
3930     } else if (AArch64::QQRegClass.hasSubClassEq(RC)) {
3931       assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
3932       Opc = AArch64::LD1Twov2d;
3933       Offset = false;
3934     } else if (AArch64::ZPR2RegClass.hasSubClassEq(RC)) {
3935       assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
3936       Opc = AArch64::LDR_ZZXI;
3937       StackID = TargetStackID::ScalableVector;
3938     }
3939     break;
3940   case 48:
3941     if (AArch64::QQQRegClass.hasSubClassEq(RC)) {
3942       assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
3943       Opc = AArch64::LD1Threev2d;
3944       Offset = false;
3945     } else if (AArch64::ZPR3RegClass.hasSubClassEq(RC)) {
3946       assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
3947       Opc = AArch64::LDR_ZZZXI;
3948       StackID = TargetStackID::ScalableVector;
3949     }
3950     break;
3951   case 64:
3952     if (AArch64::QQQQRegClass.hasSubClassEq(RC)) {
3953       assert(Subtarget.hasNEON() && "Unexpected register load without NEON");
3954       Opc = AArch64::LD1Fourv2d;
3955       Offset = false;
3956     } else if (AArch64::ZPR4RegClass.hasSubClassEq(RC)) {
3957       assert(Subtarget.hasSVE() && "Unexpected register load without SVE");
3958       Opc = AArch64::LDR_ZZZZXI;
3959       StackID = TargetStackID::ScalableVector;
3960     }
3961     break;
3962   }
3963 
3964   assert(Opc && "Unknown register class");
3965   MFI.setStackID(FI, StackID);
3966 
3967   const MachineInstrBuilder MI = BuildMI(MBB, MBBI, DebugLoc(), get(Opc))
3968                                      .addReg(DestReg, getDefRegState(true))
3969                                      .addFrameIndex(FI);
3970   if (Offset)
3971     MI.addImm(0);
3972   MI.addMemOperand(MMO);
3973 }
3974 
3975 bool llvm::isNZCVTouchedInInstructionRange(const MachineInstr &DefMI,
3976                                            const MachineInstr &UseMI,
3977                                            const TargetRegisterInfo *TRI) {
3978   return any_of(instructionsWithoutDebug(std::next(DefMI.getIterator()),
3979                                          UseMI.getIterator()),
3980                 [TRI](const MachineInstr &I) {
3981                   return I.modifiesRegister(AArch64::NZCV, TRI) ||
3982                          I.readsRegister(AArch64::NZCV, TRI);
3983                 });
3984 }
3985 
3986 void AArch64InstrInfo::decomposeStackOffsetForDwarfOffsets(
3987     const StackOffset &Offset, int64_t &ByteSized, int64_t &VGSized) {
3988   // The smallest scalable element supported by scaled SVE addressing
3989   // modes are predicates, which are 2 scalable bytes in size. So the scalable
3990   // byte offset must always be a multiple of 2.
3991   assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
3992 
3993   // VGSized offsets are divided by '2', because the VG register is the
3994   // the number of 64bit granules as opposed to 128bit vector chunks,
3995   // which is how the 'n' in e.g. MVT::nxv1i8 is modelled.
3996   // So, for a stack offset of 16 MVT::nxv1i8's, the size is n x 16 bytes.
3997   // VG = n * 2 and the dwarf offset must be VG * 8 bytes.
3998   ByteSized = Offset.getFixed();
3999   VGSized = Offset.getScalable() / 2;
4000 }
4001 
4002 /// Returns the offset in parts to which this frame offset can be
4003 /// decomposed for the purpose of describing a frame offset.
4004 /// For non-scalable offsets this is simply its byte size.
4005 void AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
4006     const StackOffset &Offset, int64_t &NumBytes, int64_t &NumPredicateVectors,
4007     int64_t &NumDataVectors) {
4008   // The smallest scalable element supported by scaled SVE addressing
4009   // modes are predicates, which are 2 scalable bytes in size. So the scalable
4010   // byte offset must always be a multiple of 2.
4011   assert(Offset.getScalable() % 2 == 0 && "Invalid frame offset");
4012 
4013   NumBytes = Offset.getFixed();
4014   NumDataVectors = 0;
4015   NumPredicateVectors = Offset.getScalable() / 2;
4016   // This method is used to get the offsets to adjust the frame offset.
4017   // If the function requires ADDPL to be used and needs more than two ADDPL
4018   // instructions, part of the offset is folded into NumDataVectors so that it
4019   // uses ADDVL for part of it, reducing the number of ADDPL instructions.
4020   if (NumPredicateVectors % 8 == 0 || NumPredicateVectors < -64 ||
4021       NumPredicateVectors > 62) {
4022     NumDataVectors = NumPredicateVectors / 8;
4023     NumPredicateVectors -= NumDataVectors * 8;
4024   }
4025 }
4026 
4027 // Helper function to emit a frame offset adjustment from a given
4028 // pointer (SrcReg), stored into DestReg. This function is explicit
4029 // in that it requires the opcode.
4030 static void emitFrameOffsetAdj(MachineBasicBlock &MBB,
4031                                MachineBasicBlock::iterator MBBI,
4032                                const DebugLoc &DL, unsigned DestReg,
4033                                unsigned SrcReg, int64_t Offset, unsigned Opc,
4034                                const TargetInstrInfo *TII,
4035                                MachineInstr::MIFlag Flag, bool NeedsWinCFI,
4036                                bool *HasWinCFI) {
4037   int Sign = 1;
4038   unsigned MaxEncoding, ShiftSize;
4039   switch (Opc) {
4040   case AArch64::ADDXri:
4041   case AArch64::ADDSXri:
4042   case AArch64::SUBXri:
4043   case AArch64::SUBSXri:
4044     MaxEncoding = 0xfff;
4045     ShiftSize = 12;
4046     break;
4047   case AArch64::ADDVL_XXI:
4048   case AArch64::ADDPL_XXI:
4049     MaxEncoding = 31;
4050     ShiftSize = 0;
4051     if (Offset < 0) {
4052       MaxEncoding = 32;
4053       Sign = -1;
4054       Offset = -Offset;
4055     }
4056     break;
4057   default:
4058     llvm_unreachable("Unsupported opcode");
4059   }
4060 
4061   // FIXME: If the offset won't fit in 24-bits, compute the offset into a
4062   // scratch register.  If DestReg is a virtual register, use it as the
4063   // scratch register; otherwise, create a new virtual register (to be
4064   // replaced by the scavenger at the end of PEI).  That case can be optimized
4065   // slightly if DestReg is SP which is always 16-byte aligned, so the scratch
4066   // register can be loaded with offset%8 and the add/sub can use an extending
4067   // instruction with LSL#3.
4068   // Currently the function handles any offsets but generates a poor sequence
4069   // of code.
4070   //  assert(Offset < (1 << 24) && "unimplemented reg plus immediate");
4071 
4072   const unsigned MaxEncodableValue = MaxEncoding << ShiftSize;
4073   Register TmpReg = DestReg;
4074   if (TmpReg == AArch64::XZR)
4075     TmpReg = MBB.getParent()->getRegInfo().createVirtualRegister(
4076         &AArch64::GPR64RegClass);
4077   do {
4078     uint64_t ThisVal = std::min<uint64_t>(Offset, MaxEncodableValue);
4079     unsigned LocalShiftSize = 0;
4080     if (ThisVal > MaxEncoding) {
4081       ThisVal = ThisVal >> ShiftSize;
4082       LocalShiftSize = ShiftSize;
4083     }
4084     assert((ThisVal >> ShiftSize) <= MaxEncoding &&
4085            "Encoding cannot handle value that big");
4086 
4087     Offset -= ThisVal << LocalShiftSize;
4088     if (Offset == 0)
4089       TmpReg = DestReg;
4090     auto MBI = BuildMI(MBB, MBBI, DL, TII->get(Opc), TmpReg)
4091                    .addReg(SrcReg)
4092                    .addImm(Sign * (int)ThisVal);
4093     if (ShiftSize)
4094       MBI = MBI.addImm(
4095           AArch64_AM::getShifterImm(AArch64_AM::LSL, LocalShiftSize));
4096     MBI = MBI.setMIFlag(Flag);
4097 
4098     if (NeedsWinCFI) {
4099       assert(Sign == 1 && "SEH directives should always have a positive sign");
4100       int Imm = (int)(ThisVal << LocalShiftSize);
4101       if ((DestReg == AArch64::FP && SrcReg == AArch64::SP) ||
4102           (SrcReg == AArch64::FP && DestReg == AArch64::SP)) {
4103         if (HasWinCFI)
4104           *HasWinCFI = true;
4105         if (Imm == 0)
4106           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_SetFP)).setMIFlag(Flag);
4107         else
4108           BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_AddFP))
4109               .addImm(Imm)
4110               .setMIFlag(Flag);
4111         assert(Offset == 0 && "Expected remaining offset to be zero to "
4112                               "emit a single SEH directive");
4113       } else if (DestReg == AArch64::SP) {
4114         if (HasWinCFI)
4115           *HasWinCFI = true;
4116         assert(SrcReg == AArch64::SP && "Unexpected SrcReg for SEH_StackAlloc");
4117         BuildMI(MBB, MBBI, DL, TII->get(AArch64::SEH_StackAlloc))
4118             .addImm(Imm)
4119             .setMIFlag(Flag);
4120       }
4121       if (HasWinCFI)
4122         *HasWinCFI = true;
4123     }
4124 
4125     SrcReg = TmpReg;
4126   } while (Offset);
4127 }
4128 
4129 void llvm::emitFrameOffset(MachineBasicBlock &MBB,
4130                            MachineBasicBlock::iterator MBBI, const DebugLoc &DL,
4131                            unsigned DestReg, unsigned SrcReg,
4132                            StackOffset Offset, const TargetInstrInfo *TII,
4133                            MachineInstr::MIFlag Flag, bool SetNZCV,
4134                            bool NeedsWinCFI, bool *HasWinCFI) {
4135   int64_t Bytes, NumPredicateVectors, NumDataVectors;
4136   AArch64InstrInfo::decomposeStackOffsetForFrameOffsets(
4137       Offset, Bytes, NumPredicateVectors, NumDataVectors);
4138 
4139   // First emit non-scalable frame offsets, or a simple 'mov'.
4140   if (Bytes || (!Offset && SrcReg != DestReg)) {
4141     assert((DestReg != AArch64::SP || Bytes % 8 == 0) &&
4142            "SP increment/decrement not 8-byte aligned");
4143     unsigned Opc = SetNZCV ? AArch64::ADDSXri : AArch64::ADDXri;
4144     if (Bytes < 0) {
4145       Bytes = -Bytes;
4146       Opc = SetNZCV ? AArch64::SUBSXri : AArch64::SUBXri;
4147     }
4148     emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, Bytes, Opc, TII, Flag,
4149                        NeedsWinCFI, HasWinCFI);
4150     SrcReg = DestReg;
4151   }
4152 
4153   assert(!(SetNZCV && (NumPredicateVectors || NumDataVectors)) &&
4154          "SetNZCV not supported with SVE vectors");
4155   assert(!(NeedsWinCFI && (NumPredicateVectors || NumDataVectors)) &&
4156          "WinCFI not supported with SVE vectors");
4157 
4158   if (NumDataVectors) {
4159     emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumDataVectors,
4160                        AArch64::ADDVL_XXI, TII, Flag, NeedsWinCFI, nullptr);
4161     SrcReg = DestReg;
4162   }
4163 
4164   if (NumPredicateVectors) {
4165     assert(DestReg != AArch64::SP && "Unaligned access to SP");
4166     emitFrameOffsetAdj(MBB, MBBI, DL, DestReg, SrcReg, NumPredicateVectors,
4167                        AArch64::ADDPL_XXI, TII, Flag, NeedsWinCFI, nullptr);
4168   }
4169 }
4170 
4171 MachineInstr *AArch64InstrInfo::foldMemoryOperandImpl(
4172     MachineFunction &MF, MachineInstr &MI, ArrayRef<unsigned> Ops,
4173     MachineBasicBlock::iterator InsertPt, int FrameIndex,
4174     LiveIntervals *LIS, VirtRegMap *VRM) const {
4175   // This is a bit of a hack. Consider this instruction:
4176   //
4177   //   %0 = COPY %sp; GPR64all:%0
4178   //
4179   // We explicitly chose GPR64all for the virtual register so such a copy might
4180   // be eliminated by RegisterCoalescer. However, that may not be possible, and
4181   // %0 may even spill. We can't spill %sp, and since it is in the GPR64all
4182   // register class, TargetInstrInfo::foldMemoryOperand() is going to try.
4183   //
4184   // To prevent that, we are going to constrain the %0 register class here.
4185   //
4186   // <rdar://problem/11522048>
4187   //
4188   if (MI.isFullCopy()) {
4189     Register DstReg = MI.getOperand(0).getReg();
4190     Register SrcReg = MI.getOperand(1).getReg();
4191     if (SrcReg == AArch64::SP && Register::isVirtualRegister(DstReg)) {
4192       MF.getRegInfo().constrainRegClass(DstReg, &AArch64::GPR64RegClass);
4193       return nullptr;
4194     }
4195     if (DstReg == AArch64::SP && Register::isVirtualRegister(SrcReg)) {
4196       MF.getRegInfo().constrainRegClass(SrcReg, &AArch64::GPR64RegClass);
4197       return nullptr;
4198     }
4199   }
4200 
4201   // Handle the case where a copy is being spilled or filled but the source
4202   // and destination register class don't match.  For example:
4203   //
4204   //   %0 = COPY %xzr; GPR64common:%0
4205   //
4206   // In this case we can still safely fold away the COPY and generate the
4207   // following spill code:
4208   //
4209   //   STRXui %xzr, %stack.0
4210   //
4211   // This also eliminates spilled cross register class COPYs (e.g. between x and
4212   // d regs) of the same size.  For example:
4213   //
4214   //   %0 = COPY %1; GPR64:%0, FPR64:%1
4215   //
4216   // will be filled as
4217   //
4218   //   LDRDui %0, fi<#0>
4219   //
4220   // instead of
4221   //
4222   //   LDRXui %Temp, fi<#0>
4223   //   %0 = FMOV %Temp
4224   //
4225   if (MI.isCopy() && Ops.size() == 1 &&
4226       // Make sure we're only folding the explicit COPY defs/uses.
4227       (Ops[0] == 0 || Ops[0] == 1)) {
4228     bool IsSpill = Ops[0] == 0;
4229     bool IsFill = !IsSpill;
4230     const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
4231     const MachineRegisterInfo &MRI = MF.getRegInfo();
4232     MachineBasicBlock &MBB = *MI.getParent();
4233     const MachineOperand &DstMO = MI.getOperand(0);
4234     const MachineOperand &SrcMO = MI.getOperand(1);
4235     Register DstReg = DstMO.getReg();
4236     Register SrcReg = SrcMO.getReg();
4237     // This is slightly expensive to compute for physical regs since
4238     // getMinimalPhysRegClass is slow.
4239     auto getRegClass = [&](unsigned Reg) {
4240       return Register::isVirtualRegister(Reg) ? MRI.getRegClass(Reg)
4241                                               : TRI.getMinimalPhysRegClass(Reg);
4242     };
4243 
4244     if (DstMO.getSubReg() == 0 && SrcMO.getSubReg() == 0) {
4245       assert(TRI.getRegSizeInBits(*getRegClass(DstReg)) ==
4246                  TRI.getRegSizeInBits(*getRegClass(SrcReg)) &&
4247              "Mismatched register size in non subreg COPY");
4248       if (IsSpill)
4249         storeRegToStackSlot(MBB, InsertPt, SrcReg, SrcMO.isKill(), FrameIndex,
4250                             getRegClass(SrcReg), &TRI);
4251       else
4252         loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex,
4253                              getRegClass(DstReg), &TRI);
4254       return &*--InsertPt;
4255     }
4256 
4257     // Handle cases like spilling def of:
4258     //
4259     //   %0:sub_32<def,read-undef> = COPY %wzr; GPR64common:%0
4260     //
4261     // where the physical register source can be widened and stored to the full
4262     // virtual reg destination stack slot, in this case producing:
4263     //
4264     //   STRXui %xzr, %stack.0
4265     //
4266     if (IsSpill && DstMO.isUndef() && Register::isPhysicalRegister(SrcReg)) {
4267       assert(SrcMO.getSubReg() == 0 &&
4268              "Unexpected subreg on physical register");
4269       const TargetRegisterClass *SpillRC;
4270       unsigned SpillSubreg;
4271       switch (DstMO.getSubReg()) {
4272       default:
4273         SpillRC = nullptr;
4274         break;
4275       case AArch64::sub_32:
4276       case AArch64::ssub:
4277         if (AArch64::GPR32RegClass.contains(SrcReg)) {
4278           SpillRC = &AArch64::GPR64RegClass;
4279           SpillSubreg = AArch64::sub_32;
4280         } else if (AArch64::FPR32RegClass.contains(SrcReg)) {
4281           SpillRC = &AArch64::FPR64RegClass;
4282           SpillSubreg = AArch64::ssub;
4283         } else
4284           SpillRC = nullptr;
4285         break;
4286       case AArch64::dsub:
4287         if (AArch64::FPR64RegClass.contains(SrcReg)) {
4288           SpillRC = &AArch64::FPR128RegClass;
4289           SpillSubreg = AArch64::dsub;
4290         } else
4291           SpillRC = nullptr;
4292         break;
4293       }
4294 
4295       if (SpillRC)
4296         if (unsigned WidenedSrcReg =
4297                 TRI.getMatchingSuperReg(SrcReg, SpillSubreg, SpillRC)) {
4298           storeRegToStackSlot(MBB, InsertPt, WidenedSrcReg, SrcMO.isKill(),
4299                               FrameIndex, SpillRC, &TRI);
4300           return &*--InsertPt;
4301         }
4302     }
4303 
4304     // Handle cases like filling use of:
4305     //
4306     //   %0:sub_32<def,read-undef> = COPY %1; GPR64:%0, GPR32:%1
4307     //
4308     // where we can load the full virtual reg source stack slot, into the subreg
4309     // destination, in this case producing:
4310     //
4311     //   LDRWui %0:sub_32<def,read-undef>, %stack.0
4312     //
4313     if (IsFill && SrcMO.getSubReg() == 0 && DstMO.isUndef()) {
4314       const TargetRegisterClass *FillRC;
4315       switch (DstMO.getSubReg()) {
4316       default:
4317         FillRC = nullptr;
4318         break;
4319       case AArch64::sub_32:
4320         FillRC = &AArch64::GPR32RegClass;
4321         break;
4322       case AArch64::ssub:
4323         FillRC = &AArch64::FPR32RegClass;
4324         break;
4325       case AArch64::dsub:
4326         FillRC = &AArch64::FPR64RegClass;
4327         break;
4328       }
4329 
4330       if (FillRC) {
4331         assert(TRI.getRegSizeInBits(*getRegClass(SrcReg)) ==
4332                    TRI.getRegSizeInBits(*FillRC) &&
4333                "Mismatched regclass size on folded subreg COPY");
4334         loadRegFromStackSlot(MBB, InsertPt, DstReg, FrameIndex, FillRC, &TRI);
4335         MachineInstr &LoadMI = *--InsertPt;
4336         MachineOperand &LoadDst = LoadMI.getOperand(0);
4337         assert(LoadDst.getSubReg() == 0 && "unexpected subreg on fill load");
4338         LoadDst.setSubReg(DstMO.getSubReg());
4339         LoadDst.setIsUndef();
4340         return &LoadMI;
4341       }
4342     }
4343   }
4344 
4345   // Cannot fold.
4346   return nullptr;
4347 }
4348 
4349 int llvm::isAArch64FrameOffsetLegal(const MachineInstr &MI,
4350                                     StackOffset &SOffset,
4351                                     bool *OutUseUnscaledOp,
4352                                     unsigned *OutUnscaledOp,
4353                                     int64_t *EmittableOffset) {
4354   // Set output values in case of early exit.
4355   if (EmittableOffset)
4356     *EmittableOffset = 0;
4357   if (OutUseUnscaledOp)
4358     *OutUseUnscaledOp = false;
4359   if (OutUnscaledOp)
4360     *OutUnscaledOp = 0;
4361 
4362   // Exit early for structured vector spills/fills as they can't take an
4363   // immediate offset.
4364   switch (MI.getOpcode()) {
4365   default:
4366     break;
4367   case AArch64::LD1Twov2d:
4368   case AArch64::LD1Threev2d:
4369   case AArch64::LD1Fourv2d:
4370   case AArch64::LD1Twov1d:
4371   case AArch64::LD1Threev1d:
4372   case AArch64::LD1Fourv1d:
4373   case AArch64::ST1Twov2d:
4374   case AArch64::ST1Threev2d:
4375   case AArch64::ST1Fourv2d:
4376   case AArch64::ST1Twov1d:
4377   case AArch64::ST1Threev1d:
4378   case AArch64::ST1Fourv1d:
4379   case AArch64::ST1i8:
4380   case AArch64::ST1i16:
4381   case AArch64::ST1i32:
4382   case AArch64::ST1i64:
4383   case AArch64::IRG:
4384   case AArch64::IRGstack:
4385   case AArch64::STGloop:
4386   case AArch64::STZGloop:
4387     return AArch64FrameOffsetCannotUpdate;
4388   }
4389 
4390   // Get the min/max offset and the scale.
4391   TypeSize ScaleValue(0U, false);
4392   unsigned Width;
4393   int64_t MinOff, MaxOff;
4394   if (!AArch64InstrInfo::getMemOpInfo(MI.getOpcode(), ScaleValue, Width, MinOff,
4395                                       MaxOff))
4396     llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
4397 
4398   // Construct the complete offset.
4399   bool IsMulVL = ScaleValue.isScalable();
4400   unsigned Scale = ScaleValue.getKnownMinSize();
4401   int64_t Offset = IsMulVL ? SOffset.getScalable() : SOffset.getFixed();
4402 
4403   const MachineOperand &ImmOpnd =
4404       MI.getOperand(AArch64InstrInfo::getLoadStoreImmIdx(MI.getOpcode()));
4405   Offset += ImmOpnd.getImm() * Scale;
4406 
4407   // If the offset doesn't match the scale, we rewrite the instruction to
4408   // use the unscaled instruction instead. Likewise, if we have a negative
4409   // offset and there is an unscaled op to use.
4410   Optional<unsigned> UnscaledOp =
4411       AArch64InstrInfo::getUnscaledLdSt(MI.getOpcode());
4412   bool useUnscaledOp = UnscaledOp && (Offset % Scale || Offset < 0);
4413   if (useUnscaledOp &&
4414       !AArch64InstrInfo::getMemOpInfo(*UnscaledOp, ScaleValue, Width, MinOff,
4415                                       MaxOff))
4416     llvm_unreachable("unhandled opcode in isAArch64FrameOffsetLegal");
4417 
4418   Scale = ScaleValue.getKnownMinSize();
4419   assert(IsMulVL == ScaleValue.isScalable() &&
4420          "Unscaled opcode has different value for scalable");
4421 
4422   int64_t Remainder = Offset % Scale;
4423   assert(!(Remainder && useUnscaledOp) &&
4424          "Cannot have remainder when using unscaled op");
4425 
4426   assert(MinOff < MaxOff && "Unexpected Min/Max offsets");
4427   int64_t NewOffset = Offset / Scale;
4428   if (MinOff <= NewOffset && NewOffset <= MaxOff)
4429     Offset = Remainder;
4430   else {
4431     NewOffset = NewOffset < 0 ? MinOff : MaxOff;
4432     Offset = Offset - NewOffset * Scale + Remainder;
4433   }
4434 
4435   if (EmittableOffset)
4436     *EmittableOffset = NewOffset;
4437   if (OutUseUnscaledOp)
4438     *OutUseUnscaledOp = useUnscaledOp;
4439   if (OutUnscaledOp && UnscaledOp)
4440     *OutUnscaledOp = *UnscaledOp;
4441 
4442   if (IsMulVL)
4443     SOffset = StackOffset::get(SOffset.getFixed(), Offset);
4444   else
4445     SOffset = StackOffset::get(Offset, SOffset.getScalable());
4446   return AArch64FrameOffsetCanUpdate |
4447          (SOffset ? 0 : AArch64FrameOffsetIsLegal);
4448 }
4449 
4450 bool llvm::rewriteAArch64FrameIndex(MachineInstr &MI, unsigned FrameRegIdx,
4451                                     unsigned FrameReg, StackOffset &Offset,
4452                                     const AArch64InstrInfo *TII) {
4453   unsigned Opcode = MI.getOpcode();
4454   unsigned ImmIdx = FrameRegIdx + 1;
4455 
4456   if (Opcode == AArch64::ADDSXri || Opcode == AArch64::ADDXri) {
4457     Offset += StackOffset::getFixed(MI.getOperand(ImmIdx).getImm());
4458     emitFrameOffset(*MI.getParent(), MI, MI.getDebugLoc(),
4459                     MI.getOperand(0).getReg(), FrameReg, Offset, TII,
4460                     MachineInstr::NoFlags, (Opcode == AArch64::ADDSXri));
4461     MI.eraseFromParent();
4462     Offset = StackOffset();
4463     return true;
4464   }
4465 
4466   int64_t NewOffset;
4467   unsigned UnscaledOp;
4468   bool UseUnscaledOp;
4469   int Status = isAArch64FrameOffsetLegal(MI, Offset, &UseUnscaledOp,
4470                                          &UnscaledOp, &NewOffset);
4471   if (Status & AArch64FrameOffsetCanUpdate) {
4472     if (Status & AArch64FrameOffsetIsLegal)
4473       // Replace the FrameIndex with FrameReg.
4474       MI.getOperand(FrameRegIdx).ChangeToRegister(FrameReg, false);
4475     if (UseUnscaledOp)
4476       MI.setDesc(TII->get(UnscaledOp));
4477 
4478     MI.getOperand(ImmIdx).ChangeToImmediate(NewOffset);
4479     return !Offset;
4480   }
4481 
4482   return false;
4483 }
4484 
4485 MCInst AArch64InstrInfo::getNop() const {
4486   return MCInstBuilder(AArch64::HINT).addImm(0);
4487 }
4488 
4489 // AArch64 supports MachineCombiner.
4490 bool AArch64InstrInfo::useMachineCombiner() const { return true; }
4491 
4492 // True when Opc sets flag
4493 static bool isCombineInstrSettingFlag(unsigned Opc) {
4494   switch (Opc) {
4495   case AArch64::ADDSWrr:
4496   case AArch64::ADDSWri:
4497   case AArch64::ADDSXrr:
4498   case AArch64::ADDSXri:
4499   case AArch64::SUBSWrr:
4500   case AArch64::SUBSXrr:
4501   // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
4502   case AArch64::SUBSWri:
4503   case AArch64::SUBSXri:
4504     return true;
4505   default:
4506     break;
4507   }
4508   return false;
4509 }
4510 
4511 // 32b Opcodes that can be combined with a MUL
4512 static bool isCombineInstrCandidate32(unsigned Opc) {
4513   switch (Opc) {
4514   case AArch64::ADDWrr:
4515   case AArch64::ADDWri:
4516   case AArch64::SUBWrr:
4517   case AArch64::ADDSWrr:
4518   case AArch64::ADDSWri:
4519   case AArch64::SUBSWrr:
4520   // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
4521   case AArch64::SUBWri:
4522   case AArch64::SUBSWri:
4523     return true;
4524   default:
4525     break;
4526   }
4527   return false;
4528 }
4529 
4530 // 64b Opcodes that can be combined with a MUL
4531 static bool isCombineInstrCandidate64(unsigned Opc) {
4532   switch (Opc) {
4533   case AArch64::ADDXrr:
4534   case AArch64::ADDXri:
4535   case AArch64::SUBXrr:
4536   case AArch64::ADDSXrr:
4537   case AArch64::ADDSXri:
4538   case AArch64::SUBSXrr:
4539   // Note: MSUB Wd,Wn,Wm,Wi -> Wd = Wi - WnxWm, not Wd=WnxWm - Wi.
4540   case AArch64::SUBXri:
4541   case AArch64::SUBSXri:
4542   case AArch64::ADDv8i8:
4543   case AArch64::ADDv16i8:
4544   case AArch64::ADDv4i16:
4545   case AArch64::ADDv8i16:
4546   case AArch64::ADDv2i32:
4547   case AArch64::ADDv4i32:
4548   case AArch64::SUBv8i8:
4549   case AArch64::SUBv16i8:
4550   case AArch64::SUBv4i16:
4551   case AArch64::SUBv8i16:
4552   case AArch64::SUBv2i32:
4553   case AArch64::SUBv4i32:
4554     return true;
4555   default:
4556     break;
4557   }
4558   return false;
4559 }
4560 
4561 // FP Opcodes that can be combined with a FMUL.
4562 static bool isCombineInstrCandidateFP(const MachineInstr &Inst) {
4563   switch (Inst.getOpcode()) {
4564   default:
4565     break;
4566   case AArch64::FADDHrr:
4567   case AArch64::FADDSrr:
4568   case AArch64::FADDDrr:
4569   case AArch64::FADDv4f16:
4570   case AArch64::FADDv8f16:
4571   case AArch64::FADDv2f32:
4572   case AArch64::FADDv2f64:
4573   case AArch64::FADDv4f32:
4574   case AArch64::FSUBHrr:
4575   case AArch64::FSUBSrr:
4576   case AArch64::FSUBDrr:
4577   case AArch64::FSUBv4f16:
4578   case AArch64::FSUBv8f16:
4579   case AArch64::FSUBv2f32:
4580   case AArch64::FSUBv2f64:
4581   case AArch64::FSUBv4f32:
4582     TargetOptions Options = Inst.getParent()->getParent()->getTarget().Options;
4583     // We can fuse FADD/FSUB with FMUL, if fusion is either allowed globally by
4584     // the target options or if FADD/FSUB has the contract fast-math flag.
4585     return Options.UnsafeFPMath ||
4586            Options.AllowFPOpFusion == FPOpFusion::Fast ||
4587            Inst.getFlag(MachineInstr::FmContract);
4588     return true;
4589   }
4590   return false;
4591 }
4592 
4593 // Opcodes that can be combined with a MUL
4594 static bool isCombineInstrCandidate(unsigned Opc) {
4595   return (isCombineInstrCandidate32(Opc) || isCombineInstrCandidate64(Opc));
4596 }
4597 
4598 //
4599 // Utility routine that checks if \param MO is defined by an
4600 // \param CombineOpc instruction in the basic block \param MBB
4601 static bool canCombine(MachineBasicBlock &MBB, MachineOperand &MO,
4602                        unsigned CombineOpc, unsigned ZeroReg = 0,
4603                        bool CheckZeroReg = false) {
4604   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4605   MachineInstr *MI = nullptr;
4606 
4607   if (MO.isReg() && Register::isVirtualRegister(MO.getReg()))
4608     MI = MRI.getUniqueVRegDef(MO.getReg());
4609   // And it needs to be in the trace (otherwise, it won't have a depth).
4610   if (!MI || MI->getParent() != &MBB || (unsigned)MI->getOpcode() != CombineOpc)
4611     return false;
4612   // Must only used by the user we combine with.
4613   if (!MRI.hasOneNonDBGUse(MI->getOperand(0).getReg()))
4614     return false;
4615 
4616   if (CheckZeroReg) {
4617     assert(MI->getNumOperands() >= 4 && MI->getOperand(0).isReg() &&
4618            MI->getOperand(1).isReg() && MI->getOperand(2).isReg() &&
4619            MI->getOperand(3).isReg() && "MAdd/MSub must have a least 4 regs");
4620     // The third input reg must be zero.
4621     if (MI->getOperand(3).getReg() != ZeroReg)
4622       return false;
4623   }
4624 
4625   return true;
4626 }
4627 
4628 //
4629 // Is \param MO defined by an integer multiply and can be combined?
4630 static bool canCombineWithMUL(MachineBasicBlock &MBB, MachineOperand &MO,
4631                               unsigned MulOpc, unsigned ZeroReg) {
4632   return canCombine(MBB, MO, MulOpc, ZeroReg, true);
4633 }
4634 
4635 //
4636 // Is \param MO defined by a floating-point multiply and can be combined?
4637 static bool canCombineWithFMUL(MachineBasicBlock &MBB, MachineOperand &MO,
4638                                unsigned MulOpc) {
4639   return canCombine(MBB, MO, MulOpc);
4640 }
4641 
4642 // TODO: There are many more machine instruction opcodes to match:
4643 //       1. Other data types (integer, vectors)
4644 //       2. Other math / logic operations (xor, or)
4645 //       3. Other forms of the same operation (intrinsics and other variants)
4646 bool AArch64InstrInfo::isAssociativeAndCommutative(
4647     const MachineInstr &Inst) const {
4648   switch (Inst.getOpcode()) {
4649   case AArch64::FADDDrr:
4650   case AArch64::FADDSrr:
4651   case AArch64::FADDv2f32:
4652   case AArch64::FADDv2f64:
4653   case AArch64::FADDv4f32:
4654   case AArch64::FMULDrr:
4655   case AArch64::FMULSrr:
4656   case AArch64::FMULX32:
4657   case AArch64::FMULX64:
4658   case AArch64::FMULXv2f32:
4659   case AArch64::FMULXv2f64:
4660   case AArch64::FMULXv4f32:
4661   case AArch64::FMULv2f32:
4662   case AArch64::FMULv2f64:
4663   case AArch64::FMULv4f32:
4664     return Inst.getParent()->getParent()->getTarget().Options.UnsafeFPMath;
4665   default:
4666     return false;
4667   }
4668 }
4669 
4670 /// Find instructions that can be turned into madd.
4671 static bool getMaddPatterns(MachineInstr &Root,
4672                             SmallVectorImpl<MachineCombinerPattern> &Patterns) {
4673   unsigned Opc = Root.getOpcode();
4674   MachineBasicBlock &MBB = *Root.getParent();
4675   bool Found = false;
4676 
4677   if (!isCombineInstrCandidate(Opc))
4678     return false;
4679   if (isCombineInstrSettingFlag(Opc)) {
4680     int Cmp_NZCV = Root.findRegisterDefOperandIdx(AArch64::NZCV, true);
4681     // When NZCV is live bail out.
4682     if (Cmp_NZCV == -1)
4683       return false;
4684     unsigned NewOpc = convertToNonFlagSettingOpc(Root);
4685     // When opcode can't change bail out.
4686     // CHECKME: do we miss any cases for opcode conversion?
4687     if (NewOpc == Opc)
4688       return false;
4689     Opc = NewOpc;
4690   }
4691 
4692   auto setFound = [&](int Opcode, int Operand, unsigned ZeroReg,
4693                       MachineCombinerPattern Pattern) {
4694     if (canCombineWithMUL(MBB, Root.getOperand(Operand), Opcode, ZeroReg)) {
4695       Patterns.push_back(Pattern);
4696       Found = true;
4697     }
4698   };
4699 
4700   auto setVFound = [&](int Opcode, int Operand, MachineCombinerPattern Pattern) {
4701     if (canCombine(MBB, Root.getOperand(Operand), Opcode)) {
4702       Patterns.push_back(Pattern);
4703       Found = true;
4704     }
4705   };
4706 
4707   typedef MachineCombinerPattern MCP;
4708 
4709   switch (Opc) {
4710   default:
4711     break;
4712   case AArch64::ADDWrr:
4713     assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
4714            "ADDWrr does not have register operands");
4715     setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDW_OP1);
4716     setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULADDW_OP2);
4717     break;
4718   case AArch64::ADDXrr:
4719     setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDX_OP1);
4720     setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULADDX_OP2);
4721     break;
4722   case AArch64::SUBWrr:
4723     setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBW_OP1);
4724     setFound(AArch64::MADDWrrr, 2, AArch64::WZR, MCP::MULSUBW_OP2);
4725     break;
4726   case AArch64::SUBXrr:
4727     setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBX_OP1);
4728     setFound(AArch64::MADDXrrr, 2, AArch64::XZR, MCP::MULSUBX_OP2);
4729     break;
4730   case AArch64::ADDWri:
4731     setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULADDWI_OP1);
4732     break;
4733   case AArch64::ADDXri:
4734     setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULADDXI_OP1);
4735     break;
4736   case AArch64::SUBWri:
4737     setFound(AArch64::MADDWrrr, 1, AArch64::WZR, MCP::MULSUBWI_OP1);
4738     break;
4739   case AArch64::SUBXri:
4740     setFound(AArch64::MADDXrrr, 1, AArch64::XZR, MCP::MULSUBXI_OP1);
4741     break;
4742   case AArch64::ADDv8i8:
4743     setVFound(AArch64::MULv8i8, 1, MCP::MULADDv8i8_OP1);
4744     setVFound(AArch64::MULv8i8, 2, MCP::MULADDv8i8_OP2);
4745     break;
4746   case AArch64::ADDv16i8:
4747     setVFound(AArch64::MULv16i8, 1, MCP::MULADDv16i8_OP1);
4748     setVFound(AArch64::MULv16i8, 2, MCP::MULADDv16i8_OP2);
4749     break;
4750   case AArch64::ADDv4i16:
4751     setVFound(AArch64::MULv4i16, 1, MCP::MULADDv4i16_OP1);
4752     setVFound(AArch64::MULv4i16, 2, MCP::MULADDv4i16_OP2);
4753     setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULADDv4i16_indexed_OP1);
4754     setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULADDv4i16_indexed_OP2);
4755     break;
4756   case AArch64::ADDv8i16:
4757     setVFound(AArch64::MULv8i16, 1, MCP::MULADDv8i16_OP1);
4758     setVFound(AArch64::MULv8i16, 2, MCP::MULADDv8i16_OP2);
4759     setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULADDv8i16_indexed_OP1);
4760     setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULADDv8i16_indexed_OP2);
4761     break;
4762   case AArch64::ADDv2i32:
4763     setVFound(AArch64::MULv2i32, 1, MCP::MULADDv2i32_OP1);
4764     setVFound(AArch64::MULv2i32, 2, MCP::MULADDv2i32_OP2);
4765     setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULADDv2i32_indexed_OP1);
4766     setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULADDv2i32_indexed_OP2);
4767     break;
4768   case AArch64::ADDv4i32:
4769     setVFound(AArch64::MULv4i32, 1, MCP::MULADDv4i32_OP1);
4770     setVFound(AArch64::MULv4i32, 2, MCP::MULADDv4i32_OP2);
4771     setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULADDv4i32_indexed_OP1);
4772     setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULADDv4i32_indexed_OP2);
4773     break;
4774   case AArch64::SUBv8i8:
4775     setVFound(AArch64::MULv8i8, 1, MCP::MULSUBv8i8_OP1);
4776     setVFound(AArch64::MULv8i8, 2, MCP::MULSUBv8i8_OP2);
4777     break;
4778   case AArch64::SUBv16i8:
4779     setVFound(AArch64::MULv16i8, 1, MCP::MULSUBv16i8_OP1);
4780     setVFound(AArch64::MULv16i8, 2, MCP::MULSUBv16i8_OP2);
4781     break;
4782   case AArch64::SUBv4i16:
4783     setVFound(AArch64::MULv4i16, 1, MCP::MULSUBv4i16_OP1);
4784     setVFound(AArch64::MULv4i16, 2, MCP::MULSUBv4i16_OP2);
4785     setVFound(AArch64::MULv4i16_indexed, 1, MCP::MULSUBv4i16_indexed_OP1);
4786     setVFound(AArch64::MULv4i16_indexed, 2, MCP::MULSUBv4i16_indexed_OP2);
4787     break;
4788   case AArch64::SUBv8i16:
4789     setVFound(AArch64::MULv8i16, 1, MCP::MULSUBv8i16_OP1);
4790     setVFound(AArch64::MULv8i16, 2, MCP::MULSUBv8i16_OP2);
4791     setVFound(AArch64::MULv8i16_indexed, 1, MCP::MULSUBv8i16_indexed_OP1);
4792     setVFound(AArch64::MULv8i16_indexed, 2, MCP::MULSUBv8i16_indexed_OP2);
4793     break;
4794   case AArch64::SUBv2i32:
4795     setVFound(AArch64::MULv2i32, 1, MCP::MULSUBv2i32_OP1);
4796     setVFound(AArch64::MULv2i32, 2, MCP::MULSUBv2i32_OP2);
4797     setVFound(AArch64::MULv2i32_indexed, 1, MCP::MULSUBv2i32_indexed_OP1);
4798     setVFound(AArch64::MULv2i32_indexed, 2, MCP::MULSUBv2i32_indexed_OP2);
4799     break;
4800   case AArch64::SUBv4i32:
4801     setVFound(AArch64::MULv4i32, 1, MCP::MULSUBv4i32_OP1);
4802     setVFound(AArch64::MULv4i32, 2, MCP::MULSUBv4i32_OP2);
4803     setVFound(AArch64::MULv4i32_indexed, 1, MCP::MULSUBv4i32_indexed_OP1);
4804     setVFound(AArch64::MULv4i32_indexed, 2, MCP::MULSUBv4i32_indexed_OP2);
4805     break;
4806   }
4807   return Found;
4808 }
4809 /// Floating-Point Support
4810 
4811 /// Find instructions that can be turned into madd.
4812 static bool getFMAPatterns(MachineInstr &Root,
4813                            SmallVectorImpl<MachineCombinerPattern> &Patterns) {
4814 
4815   if (!isCombineInstrCandidateFP(Root))
4816     return false;
4817 
4818   MachineBasicBlock &MBB = *Root.getParent();
4819   bool Found = false;
4820 
4821   auto Match = [&](int Opcode, int Operand,
4822                    MachineCombinerPattern Pattern) -> bool {
4823     if (canCombineWithFMUL(MBB, Root.getOperand(Operand), Opcode)) {
4824       Patterns.push_back(Pattern);
4825       return true;
4826     }
4827     return false;
4828   };
4829 
4830   typedef MachineCombinerPattern MCP;
4831 
4832   switch (Root.getOpcode()) {
4833   default:
4834     assert(false && "Unsupported FP instruction in combiner\n");
4835     break;
4836   case AArch64::FADDHrr:
4837     assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
4838            "FADDHrr does not have register operands");
4839 
4840     Found  = Match(AArch64::FMULHrr, 1, MCP::FMULADDH_OP1);
4841     Found |= Match(AArch64::FMULHrr, 2, MCP::FMULADDH_OP2);
4842     break;
4843   case AArch64::FADDSrr:
4844     assert(Root.getOperand(1).isReg() && Root.getOperand(2).isReg() &&
4845            "FADDSrr does not have register operands");
4846 
4847     Found |= Match(AArch64::FMULSrr, 1, MCP::FMULADDS_OP1) ||
4848              Match(AArch64::FMULv1i32_indexed, 1, MCP::FMLAv1i32_indexed_OP1);
4849 
4850     Found |= Match(AArch64::FMULSrr, 2, MCP::FMULADDS_OP2) ||
4851              Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLAv1i32_indexed_OP2);
4852     break;
4853   case AArch64::FADDDrr:
4854     Found |= Match(AArch64::FMULDrr, 1, MCP::FMULADDD_OP1) ||
4855              Match(AArch64::FMULv1i64_indexed, 1, MCP::FMLAv1i64_indexed_OP1);
4856 
4857     Found |= Match(AArch64::FMULDrr, 2, MCP::FMULADDD_OP2) ||
4858              Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLAv1i64_indexed_OP2);
4859     break;
4860   case AArch64::FADDv4f16:
4861     Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLAv4i16_indexed_OP1) ||
4862              Match(AArch64::FMULv4f16, 1, MCP::FMLAv4f16_OP1);
4863 
4864     Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLAv4i16_indexed_OP2) ||
4865              Match(AArch64::FMULv4f16, 2, MCP::FMLAv4f16_OP2);
4866     break;
4867   case AArch64::FADDv8f16:
4868     Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLAv8i16_indexed_OP1) ||
4869              Match(AArch64::FMULv8f16, 1, MCP::FMLAv8f16_OP1);
4870 
4871     Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLAv8i16_indexed_OP2) ||
4872              Match(AArch64::FMULv8f16, 2, MCP::FMLAv8f16_OP2);
4873     break;
4874   case AArch64::FADDv2f32:
4875     Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLAv2i32_indexed_OP1) ||
4876              Match(AArch64::FMULv2f32, 1, MCP::FMLAv2f32_OP1);
4877 
4878     Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLAv2i32_indexed_OP2) ||
4879              Match(AArch64::FMULv2f32, 2, MCP::FMLAv2f32_OP2);
4880     break;
4881   case AArch64::FADDv2f64:
4882     Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLAv2i64_indexed_OP1) ||
4883              Match(AArch64::FMULv2f64, 1, MCP::FMLAv2f64_OP1);
4884 
4885     Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLAv2i64_indexed_OP2) ||
4886              Match(AArch64::FMULv2f64, 2, MCP::FMLAv2f64_OP2);
4887     break;
4888   case AArch64::FADDv4f32:
4889     Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLAv4i32_indexed_OP1) ||
4890              Match(AArch64::FMULv4f32, 1, MCP::FMLAv4f32_OP1);
4891 
4892     Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLAv4i32_indexed_OP2) ||
4893              Match(AArch64::FMULv4f32, 2, MCP::FMLAv4f32_OP2);
4894     break;
4895   case AArch64::FSUBHrr:
4896     Found  = Match(AArch64::FMULHrr, 1, MCP::FMULSUBH_OP1);
4897     Found |= Match(AArch64::FMULHrr, 2, MCP::FMULSUBH_OP2);
4898     Found |= Match(AArch64::FNMULHrr, 1, MCP::FNMULSUBH_OP1);
4899     break;
4900   case AArch64::FSUBSrr:
4901     Found = Match(AArch64::FMULSrr, 1, MCP::FMULSUBS_OP1);
4902 
4903     Found |= Match(AArch64::FMULSrr, 2, MCP::FMULSUBS_OP2) ||
4904              Match(AArch64::FMULv1i32_indexed, 2, MCP::FMLSv1i32_indexed_OP2);
4905 
4906     Found |= Match(AArch64::FNMULSrr, 1, MCP::FNMULSUBS_OP1);
4907     break;
4908   case AArch64::FSUBDrr:
4909     Found = Match(AArch64::FMULDrr, 1, MCP::FMULSUBD_OP1);
4910 
4911     Found |= Match(AArch64::FMULDrr, 2, MCP::FMULSUBD_OP2) ||
4912              Match(AArch64::FMULv1i64_indexed, 2, MCP::FMLSv1i64_indexed_OP2);
4913 
4914     Found |= Match(AArch64::FNMULDrr, 1, MCP::FNMULSUBD_OP1);
4915     break;
4916   case AArch64::FSUBv4f16:
4917     Found |= Match(AArch64::FMULv4i16_indexed, 2, MCP::FMLSv4i16_indexed_OP2) ||
4918              Match(AArch64::FMULv4f16, 2, MCP::FMLSv4f16_OP2);
4919 
4920     Found |= Match(AArch64::FMULv4i16_indexed, 1, MCP::FMLSv4i16_indexed_OP1) ||
4921              Match(AArch64::FMULv4f16, 1, MCP::FMLSv4f16_OP1);
4922     break;
4923   case AArch64::FSUBv8f16:
4924     Found |= Match(AArch64::FMULv8i16_indexed, 2, MCP::FMLSv8i16_indexed_OP2) ||
4925              Match(AArch64::FMULv8f16, 2, MCP::FMLSv8f16_OP2);
4926 
4927     Found |= Match(AArch64::FMULv8i16_indexed, 1, MCP::FMLSv8i16_indexed_OP1) ||
4928              Match(AArch64::FMULv8f16, 1, MCP::FMLSv8f16_OP1);
4929     break;
4930   case AArch64::FSUBv2f32:
4931     Found |= Match(AArch64::FMULv2i32_indexed, 2, MCP::FMLSv2i32_indexed_OP2) ||
4932              Match(AArch64::FMULv2f32, 2, MCP::FMLSv2f32_OP2);
4933 
4934     Found |= Match(AArch64::FMULv2i32_indexed, 1, MCP::FMLSv2i32_indexed_OP1) ||
4935              Match(AArch64::FMULv2f32, 1, MCP::FMLSv2f32_OP1);
4936     break;
4937   case AArch64::FSUBv2f64:
4938     Found |= Match(AArch64::FMULv2i64_indexed, 2, MCP::FMLSv2i64_indexed_OP2) ||
4939              Match(AArch64::FMULv2f64, 2, MCP::FMLSv2f64_OP2);
4940 
4941     Found |= Match(AArch64::FMULv2i64_indexed, 1, MCP::FMLSv2i64_indexed_OP1) ||
4942              Match(AArch64::FMULv2f64, 1, MCP::FMLSv2f64_OP1);
4943     break;
4944   case AArch64::FSUBv4f32:
4945     Found |= Match(AArch64::FMULv4i32_indexed, 2, MCP::FMLSv4i32_indexed_OP2) ||
4946              Match(AArch64::FMULv4f32, 2, MCP::FMLSv4f32_OP2);
4947 
4948     Found |= Match(AArch64::FMULv4i32_indexed, 1, MCP::FMLSv4i32_indexed_OP1) ||
4949              Match(AArch64::FMULv4f32, 1, MCP::FMLSv4f32_OP1);
4950     break;
4951   }
4952   return Found;
4953 }
4954 
4955 static bool getFMULPatterns(MachineInstr &Root,
4956                             SmallVectorImpl<MachineCombinerPattern> &Patterns) {
4957   MachineBasicBlock &MBB = *Root.getParent();
4958   bool Found = false;
4959 
4960   auto Match = [&](unsigned Opcode, int Operand,
4961                    MachineCombinerPattern Pattern) -> bool {
4962     MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
4963     MachineOperand &MO = Root.getOperand(Operand);
4964     MachineInstr *MI = nullptr;
4965     if (MO.isReg() && Register::isVirtualRegister(MO.getReg()))
4966       MI = MRI.getUniqueVRegDef(MO.getReg());
4967     if (MI && MI->getOpcode() == Opcode) {
4968       Patterns.push_back(Pattern);
4969       return true;
4970     }
4971     return false;
4972   };
4973 
4974   typedef MachineCombinerPattern MCP;
4975 
4976   switch (Root.getOpcode()) {
4977   default:
4978     return false;
4979   case AArch64::FMULv2f32:
4980     Found = Match(AArch64::DUPv2i32lane, 1, MCP::FMULv2i32_indexed_OP1);
4981     Found |= Match(AArch64::DUPv2i32lane, 2, MCP::FMULv2i32_indexed_OP2);
4982     break;
4983   case AArch64::FMULv2f64:
4984     Found = Match(AArch64::DUPv2i64lane, 1, MCP::FMULv2i64_indexed_OP1);
4985     Found |= Match(AArch64::DUPv2i64lane, 2, MCP::FMULv2i64_indexed_OP2);
4986     break;
4987   case AArch64::FMULv4f16:
4988     Found = Match(AArch64::DUPv4i16lane, 1, MCP::FMULv4i16_indexed_OP1);
4989     Found |= Match(AArch64::DUPv4i16lane, 2, MCP::FMULv4i16_indexed_OP2);
4990     break;
4991   case AArch64::FMULv4f32:
4992     Found = Match(AArch64::DUPv4i32lane, 1, MCP::FMULv4i32_indexed_OP1);
4993     Found |= Match(AArch64::DUPv4i32lane, 2, MCP::FMULv4i32_indexed_OP2);
4994     break;
4995   case AArch64::FMULv8f16:
4996     Found = Match(AArch64::DUPv8i16lane, 1, MCP::FMULv8i16_indexed_OP1);
4997     Found |= Match(AArch64::DUPv8i16lane, 2, MCP::FMULv8i16_indexed_OP2);
4998     break;
4999   }
5000 
5001   return Found;
5002 }
5003 
5004 /// Return true when a code sequence can improve throughput. It
5005 /// should be called only for instructions in loops.
5006 /// \param Pattern - combiner pattern
5007 bool AArch64InstrInfo::isThroughputPattern(
5008     MachineCombinerPattern Pattern) const {
5009   switch (Pattern) {
5010   default:
5011     break;
5012   case MachineCombinerPattern::FMULADDH_OP1:
5013   case MachineCombinerPattern::FMULADDH_OP2:
5014   case MachineCombinerPattern::FMULSUBH_OP1:
5015   case MachineCombinerPattern::FMULSUBH_OP2:
5016   case MachineCombinerPattern::FMULADDS_OP1:
5017   case MachineCombinerPattern::FMULADDS_OP2:
5018   case MachineCombinerPattern::FMULSUBS_OP1:
5019   case MachineCombinerPattern::FMULSUBS_OP2:
5020   case MachineCombinerPattern::FMULADDD_OP1:
5021   case MachineCombinerPattern::FMULADDD_OP2:
5022   case MachineCombinerPattern::FMULSUBD_OP1:
5023   case MachineCombinerPattern::FMULSUBD_OP2:
5024   case MachineCombinerPattern::FNMULSUBH_OP1:
5025   case MachineCombinerPattern::FNMULSUBS_OP1:
5026   case MachineCombinerPattern::FNMULSUBD_OP1:
5027   case MachineCombinerPattern::FMLAv4i16_indexed_OP1:
5028   case MachineCombinerPattern::FMLAv4i16_indexed_OP2:
5029   case MachineCombinerPattern::FMLAv8i16_indexed_OP1:
5030   case MachineCombinerPattern::FMLAv8i16_indexed_OP2:
5031   case MachineCombinerPattern::FMLAv1i32_indexed_OP1:
5032   case MachineCombinerPattern::FMLAv1i32_indexed_OP2:
5033   case MachineCombinerPattern::FMLAv1i64_indexed_OP1:
5034   case MachineCombinerPattern::FMLAv1i64_indexed_OP2:
5035   case MachineCombinerPattern::FMLAv4f16_OP2:
5036   case MachineCombinerPattern::FMLAv4f16_OP1:
5037   case MachineCombinerPattern::FMLAv8f16_OP1:
5038   case MachineCombinerPattern::FMLAv8f16_OP2:
5039   case MachineCombinerPattern::FMLAv2f32_OP2:
5040   case MachineCombinerPattern::FMLAv2f32_OP1:
5041   case MachineCombinerPattern::FMLAv2f64_OP1:
5042   case MachineCombinerPattern::FMLAv2f64_OP2:
5043   case MachineCombinerPattern::FMLAv2i32_indexed_OP1:
5044   case MachineCombinerPattern::FMLAv2i32_indexed_OP2:
5045   case MachineCombinerPattern::FMLAv2i64_indexed_OP1:
5046   case MachineCombinerPattern::FMLAv2i64_indexed_OP2:
5047   case MachineCombinerPattern::FMLAv4f32_OP1:
5048   case MachineCombinerPattern::FMLAv4f32_OP2:
5049   case MachineCombinerPattern::FMLAv4i32_indexed_OP1:
5050   case MachineCombinerPattern::FMLAv4i32_indexed_OP2:
5051   case MachineCombinerPattern::FMLSv4i16_indexed_OP1:
5052   case MachineCombinerPattern::FMLSv4i16_indexed_OP2:
5053   case MachineCombinerPattern::FMLSv8i16_indexed_OP1:
5054   case MachineCombinerPattern::FMLSv8i16_indexed_OP2:
5055   case MachineCombinerPattern::FMLSv1i32_indexed_OP2:
5056   case MachineCombinerPattern::FMLSv1i64_indexed_OP2:
5057   case MachineCombinerPattern::FMLSv2i32_indexed_OP2:
5058   case MachineCombinerPattern::FMLSv2i64_indexed_OP2:
5059   case MachineCombinerPattern::FMLSv4f16_OP1:
5060   case MachineCombinerPattern::FMLSv4f16_OP2:
5061   case MachineCombinerPattern::FMLSv8f16_OP1:
5062   case MachineCombinerPattern::FMLSv8f16_OP2:
5063   case MachineCombinerPattern::FMLSv2f32_OP2:
5064   case MachineCombinerPattern::FMLSv2f64_OP2:
5065   case MachineCombinerPattern::FMLSv4i32_indexed_OP2:
5066   case MachineCombinerPattern::FMLSv4f32_OP2:
5067   case MachineCombinerPattern::FMULv2i32_indexed_OP1:
5068   case MachineCombinerPattern::FMULv2i32_indexed_OP2:
5069   case MachineCombinerPattern::FMULv2i64_indexed_OP1:
5070   case MachineCombinerPattern::FMULv2i64_indexed_OP2:
5071   case MachineCombinerPattern::FMULv4i16_indexed_OP1:
5072   case MachineCombinerPattern::FMULv4i16_indexed_OP2:
5073   case MachineCombinerPattern::FMULv4i32_indexed_OP1:
5074   case MachineCombinerPattern::FMULv4i32_indexed_OP2:
5075   case MachineCombinerPattern::FMULv8i16_indexed_OP1:
5076   case MachineCombinerPattern::FMULv8i16_indexed_OP2:
5077   case MachineCombinerPattern::MULADDv8i8_OP1:
5078   case MachineCombinerPattern::MULADDv8i8_OP2:
5079   case MachineCombinerPattern::MULADDv16i8_OP1:
5080   case MachineCombinerPattern::MULADDv16i8_OP2:
5081   case MachineCombinerPattern::MULADDv4i16_OP1:
5082   case MachineCombinerPattern::MULADDv4i16_OP2:
5083   case MachineCombinerPattern::MULADDv8i16_OP1:
5084   case MachineCombinerPattern::MULADDv8i16_OP2:
5085   case MachineCombinerPattern::MULADDv2i32_OP1:
5086   case MachineCombinerPattern::MULADDv2i32_OP2:
5087   case MachineCombinerPattern::MULADDv4i32_OP1:
5088   case MachineCombinerPattern::MULADDv4i32_OP2:
5089   case MachineCombinerPattern::MULSUBv8i8_OP1:
5090   case MachineCombinerPattern::MULSUBv8i8_OP2:
5091   case MachineCombinerPattern::MULSUBv16i8_OP1:
5092   case MachineCombinerPattern::MULSUBv16i8_OP2:
5093   case MachineCombinerPattern::MULSUBv4i16_OP1:
5094   case MachineCombinerPattern::MULSUBv4i16_OP2:
5095   case MachineCombinerPattern::MULSUBv8i16_OP1:
5096   case MachineCombinerPattern::MULSUBv8i16_OP2:
5097   case MachineCombinerPattern::MULSUBv2i32_OP1:
5098   case MachineCombinerPattern::MULSUBv2i32_OP2:
5099   case MachineCombinerPattern::MULSUBv4i32_OP1:
5100   case MachineCombinerPattern::MULSUBv4i32_OP2:
5101   case MachineCombinerPattern::MULADDv4i16_indexed_OP1:
5102   case MachineCombinerPattern::MULADDv4i16_indexed_OP2:
5103   case MachineCombinerPattern::MULADDv8i16_indexed_OP1:
5104   case MachineCombinerPattern::MULADDv8i16_indexed_OP2:
5105   case MachineCombinerPattern::MULADDv2i32_indexed_OP1:
5106   case MachineCombinerPattern::MULADDv2i32_indexed_OP2:
5107   case MachineCombinerPattern::MULADDv4i32_indexed_OP1:
5108   case MachineCombinerPattern::MULADDv4i32_indexed_OP2:
5109   case MachineCombinerPattern::MULSUBv4i16_indexed_OP1:
5110   case MachineCombinerPattern::MULSUBv4i16_indexed_OP2:
5111   case MachineCombinerPattern::MULSUBv8i16_indexed_OP1:
5112   case MachineCombinerPattern::MULSUBv8i16_indexed_OP2:
5113   case MachineCombinerPattern::MULSUBv2i32_indexed_OP1:
5114   case MachineCombinerPattern::MULSUBv2i32_indexed_OP2:
5115   case MachineCombinerPattern::MULSUBv4i32_indexed_OP1:
5116   case MachineCombinerPattern::MULSUBv4i32_indexed_OP2:
5117     return true;
5118   } // end switch (Pattern)
5119   return false;
5120 }
5121 /// Return true when there is potentially a faster code sequence for an
5122 /// instruction chain ending in \p Root. All potential patterns are listed in
5123 /// the \p Pattern vector. Pattern should be sorted in priority order since the
5124 /// pattern evaluator stops checking as soon as it finds a faster sequence.
5125 
5126 bool AArch64InstrInfo::getMachineCombinerPatterns(
5127     MachineInstr &Root, SmallVectorImpl<MachineCombinerPattern> &Patterns,
5128     bool DoRegPressureReduce) const {
5129   // Integer patterns
5130   if (getMaddPatterns(Root, Patterns))
5131     return true;
5132   // Floating point patterns
5133   if (getFMULPatterns(Root, Patterns))
5134     return true;
5135   if (getFMAPatterns(Root, Patterns))
5136     return true;
5137 
5138   return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns,
5139                                                      DoRegPressureReduce);
5140 }
5141 
5142 enum class FMAInstKind { Default, Indexed, Accumulator };
5143 /// genFusedMultiply - Generate fused multiply instructions.
5144 /// This function supports both integer and floating point instructions.
5145 /// A typical example:
5146 ///  F|MUL I=A,B,0
5147 ///  F|ADD R,I,C
5148 ///  ==> F|MADD R,A,B,C
5149 /// \param MF Containing MachineFunction
5150 /// \param MRI Register information
5151 /// \param TII Target information
5152 /// \param Root is the F|ADD instruction
5153 /// \param [out] InsInstrs is a vector of machine instructions and will
5154 /// contain the generated madd instruction
5155 /// \param IdxMulOpd is index of operand in Root that is the result of
5156 /// the F|MUL. In the example above IdxMulOpd is 1.
5157 /// \param MaddOpc the opcode fo the f|madd instruction
5158 /// \param RC Register class of operands
5159 /// \param kind of fma instruction (addressing mode) to be generated
5160 /// \param ReplacedAddend is the result register from the instruction
5161 /// replacing the non-combined operand, if any.
5162 static MachineInstr *
5163 genFusedMultiply(MachineFunction &MF, MachineRegisterInfo &MRI,
5164                  const TargetInstrInfo *TII, MachineInstr &Root,
5165                  SmallVectorImpl<MachineInstr *> &InsInstrs, unsigned IdxMulOpd,
5166                  unsigned MaddOpc, const TargetRegisterClass *RC,
5167                  FMAInstKind kind = FMAInstKind::Default,
5168                  const Register *ReplacedAddend = nullptr) {
5169   assert(IdxMulOpd == 1 || IdxMulOpd == 2);
5170 
5171   unsigned IdxOtherOpd = IdxMulOpd == 1 ? 2 : 1;
5172   MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
5173   Register ResultReg = Root.getOperand(0).getReg();
5174   Register SrcReg0 = MUL->getOperand(1).getReg();
5175   bool Src0IsKill = MUL->getOperand(1).isKill();
5176   Register SrcReg1 = MUL->getOperand(2).getReg();
5177   bool Src1IsKill = MUL->getOperand(2).isKill();
5178 
5179   unsigned SrcReg2;
5180   bool Src2IsKill;
5181   if (ReplacedAddend) {
5182     // If we just generated a new addend, we must be it's only use.
5183     SrcReg2 = *ReplacedAddend;
5184     Src2IsKill = true;
5185   } else {
5186     SrcReg2 = Root.getOperand(IdxOtherOpd).getReg();
5187     Src2IsKill = Root.getOperand(IdxOtherOpd).isKill();
5188   }
5189 
5190   if (Register::isVirtualRegister(ResultReg))
5191     MRI.constrainRegClass(ResultReg, RC);
5192   if (Register::isVirtualRegister(SrcReg0))
5193     MRI.constrainRegClass(SrcReg0, RC);
5194   if (Register::isVirtualRegister(SrcReg1))
5195     MRI.constrainRegClass(SrcReg1, RC);
5196   if (Register::isVirtualRegister(SrcReg2))
5197     MRI.constrainRegClass(SrcReg2, RC);
5198 
5199   MachineInstrBuilder MIB;
5200   if (kind == FMAInstKind::Default)
5201     MIB = BuildMI(MF, Root.getDebugLoc(), TII->get(MaddOpc), ResultReg)
5202               .addReg(SrcReg0, getKillRegState(Src0IsKill))
5203               .addReg(SrcReg1, getKillRegState(Src1IsKill))
5204               .addReg(SrcReg2, getKillRegState(Src2IsKill));
5205   else if (kind == FMAInstKind::Indexed)
5206     MIB = BuildMI(MF, Root.getDebugLoc(), TII->get(MaddOpc), ResultReg)
5207               .addReg(SrcReg2, getKillRegState(Src2IsKill))
5208               .addReg(SrcReg0, getKillRegState(Src0IsKill))
5209               .addReg(SrcReg1, getKillRegState(Src1IsKill))
5210               .addImm(MUL->getOperand(3).getImm());
5211   else if (kind == FMAInstKind::Accumulator)
5212     MIB = BuildMI(MF, Root.getDebugLoc(), TII->get(MaddOpc), ResultReg)
5213               .addReg(SrcReg2, getKillRegState(Src2IsKill))
5214               .addReg(SrcReg0, getKillRegState(Src0IsKill))
5215               .addReg(SrcReg1, getKillRegState(Src1IsKill));
5216   else
5217     assert(false && "Invalid FMA instruction kind \n");
5218   // Insert the MADD (MADD, FMA, FMS, FMLA, FMSL)
5219   InsInstrs.push_back(MIB);
5220   return MUL;
5221 }
5222 
5223 /// Fold (FMUL x (DUP y lane)) into (FMUL_indexed x y lane)
5224 static MachineInstr *
5225 genIndexedMultiply(MachineInstr &Root,
5226                    SmallVectorImpl<MachineInstr *> &InsInstrs,
5227                    unsigned IdxDupOp, unsigned MulOpc,
5228                    const TargetRegisterClass *RC, MachineRegisterInfo &MRI) {
5229   assert(((IdxDupOp == 1) || (IdxDupOp == 2)) &&
5230          "Invalid index of FMUL operand");
5231 
5232   MachineFunction &MF = *Root.getMF();
5233   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
5234 
5235   MachineInstr *Dup =
5236       MF.getRegInfo().getUniqueVRegDef(Root.getOperand(IdxDupOp).getReg());
5237 
5238   Register DupSrcReg = Dup->getOperand(1).getReg();
5239   MRI.clearKillFlags(DupSrcReg);
5240   MRI.constrainRegClass(DupSrcReg, RC);
5241 
5242   unsigned DupSrcLane = Dup->getOperand(2).getImm();
5243 
5244   unsigned IdxMulOp = IdxDupOp == 1 ? 2 : 1;
5245   MachineOperand &MulOp = Root.getOperand(IdxMulOp);
5246 
5247   Register ResultReg = Root.getOperand(0).getReg();
5248 
5249   MachineInstrBuilder MIB;
5250   MIB = BuildMI(MF, Root.getDebugLoc(), TII->get(MulOpc), ResultReg)
5251             .add(MulOp)
5252             .addReg(DupSrcReg)
5253             .addImm(DupSrcLane);
5254 
5255   InsInstrs.push_back(MIB);
5256   return &Root;
5257 }
5258 
5259 /// genFusedMultiplyAcc - Helper to generate fused multiply accumulate
5260 /// instructions.
5261 ///
5262 /// \see genFusedMultiply
5263 static MachineInstr *genFusedMultiplyAcc(
5264     MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII,
5265     MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs,
5266     unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
5267   return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
5268                           FMAInstKind::Accumulator);
5269 }
5270 
5271 /// genNeg - Helper to generate an intermediate negation of the second operand
5272 /// of Root
5273 static Register genNeg(MachineFunction &MF, MachineRegisterInfo &MRI,
5274                        const TargetInstrInfo *TII, MachineInstr &Root,
5275                        SmallVectorImpl<MachineInstr *> &InsInstrs,
5276                        DenseMap<unsigned, unsigned> &InstrIdxForVirtReg,
5277                        unsigned MnegOpc, const TargetRegisterClass *RC) {
5278   Register NewVR = MRI.createVirtualRegister(RC);
5279   MachineInstrBuilder MIB =
5280       BuildMI(MF, Root.getDebugLoc(), TII->get(MnegOpc), NewVR)
5281           .add(Root.getOperand(2));
5282   InsInstrs.push_back(MIB);
5283 
5284   assert(InstrIdxForVirtReg.empty());
5285   InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
5286 
5287   return NewVR;
5288 }
5289 
5290 /// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
5291 /// instructions with an additional negation of the accumulator
5292 static MachineInstr *genFusedMultiplyAccNeg(
5293     MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII,
5294     MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs,
5295     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
5296     unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
5297   assert(IdxMulOpd == 1);
5298 
5299   Register NewVR =
5300       genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
5301   return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
5302                           FMAInstKind::Accumulator, &NewVR);
5303 }
5304 
5305 /// genFusedMultiplyIdx - Helper to generate fused multiply accumulate
5306 /// instructions.
5307 ///
5308 /// \see genFusedMultiply
5309 static MachineInstr *genFusedMultiplyIdx(
5310     MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII,
5311     MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs,
5312     unsigned IdxMulOpd, unsigned MaddOpc, const TargetRegisterClass *RC) {
5313   return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
5314                           FMAInstKind::Indexed);
5315 }
5316 
5317 /// genFusedMultiplyAccNeg - Helper to generate fused multiply accumulate
5318 /// instructions with an additional negation of the accumulator
5319 static MachineInstr *genFusedMultiplyIdxNeg(
5320     MachineFunction &MF, MachineRegisterInfo &MRI, const TargetInstrInfo *TII,
5321     MachineInstr &Root, SmallVectorImpl<MachineInstr *> &InsInstrs,
5322     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg, unsigned IdxMulOpd,
5323     unsigned MaddOpc, unsigned MnegOpc, const TargetRegisterClass *RC) {
5324   assert(IdxMulOpd == 1);
5325 
5326   Register NewVR =
5327       genNeg(MF, MRI, TII, Root, InsInstrs, InstrIdxForVirtReg, MnegOpc, RC);
5328 
5329   return genFusedMultiply(MF, MRI, TII, Root, InsInstrs, IdxMulOpd, MaddOpc, RC,
5330                           FMAInstKind::Indexed, &NewVR);
5331 }
5332 
5333 /// genMaddR - Generate madd instruction and combine mul and add using
5334 /// an extra virtual register
5335 /// Example - an ADD intermediate needs to be stored in a register:
5336 ///   MUL I=A,B,0
5337 ///   ADD R,I,Imm
5338 ///   ==> ORR  V, ZR, Imm
5339 ///   ==> MADD R,A,B,V
5340 /// \param MF Containing MachineFunction
5341 /// \param MRI Register information
5342 /// \param TII Target information
5343 /// \param Root is the ADD instruction
5344 /// \param [out] InsInstrs is a vector of machine instructions and will
5345 /// contain the generated madd instruction
5346 /// \param IdxMulOpd is index of operand in Root that is the result of
5347 /// the MUL. In the example above IdxMulOpd is 1.
5348 /// \param MaddOpc the opcode fo the madd instruction
5349 /// \param VR is a virtual register that holds the value of an ADD operand
5350 /// (V in the example above).
5351 /// \param RC Register class of operands
5352 static MachineInstr *genMaddR(MachineFunction &MF, MachineRegisterInfo &MRI,
5353                               const TargetInstrInfo *TII, MachineInstr &Root,
5354                               SmallVectorImpl<MachineInstr *> &InsInstrs,
5355                               unsigned IdxMulOpd, unsigned MaddOpc, unsigned VR,
5356                               const TargetRegisterClass *RC) {
5357   assert(IdxMulOpd == 1 || IdxMulOpd == 2);
5358 
5359   MachineInstr *MUL = MRI.getUniqueVRegDef(Root.getOperand(IdxMulOpd).getReg());
5360   Register ResultReg = Root.getOperand(0).getReg();
5361   Register SrcReg0 = MUL->getOperand(1).getReg();
5362   bool Src0IsKill = MUL->getOperand(1).isKill();
5363   Register SrcReg1 = MUL->getOperand(2).getReg();
5364   bool Src1IsKill = MUL->getOperand(2).isKill();
5365 
5366   if (Register::isVirtualRegister(ResultReg))
5367     MRI.constrainRegClass(ResultReg, RC);
5368   if (Register::isVirtualRegister(SrcReg0))
5369     MRI.constrainRegClass(SrcReg0, RC);
5370   if (Register::isVirtualRegister(SrcReg1))
5371     MRI.constrainRegClass(SrcReg1, RC);
5372   if (Register::isVirtualRegister(VR))
5373     MRI.constrainRegClass(VR, RC);
5374 
5375   MachineInstrBuilder MIB =
5376       BuildMI(MF, Root.getDebugLoc(), TII->get(MaddOpc), ResultReg)
5377           .addReg(SrcReg0, getKillRegState(Src0IsKill))
5378           .addReg(SrcReg1, getKillRegState(Src1IsKill))
5379           .addReg(VR);
5380   // Insert the MADD
5381   InsInstrs.push_back(MIB);
5382   return MUL;
5383 }
5384 
5385 /// When getMachineCombinerPatterns() finds potential patterns,
5386 /// this function generates the instructions that could replace the
5387 /// original code sequence
5388 void AArch64InstrInfo::genAlternativeCodeSequence(
5389     MachineInstr &Root, MachineCombinerPattern Pattern,
5390     SmallVectorImpl<MachineInstr *> &InsInstrs,
5391     SmallVectorImpl<MachineInstr *> &DelInstrs,
5392     DenseMap<unsigned, unsigned> &InstrIdxForVirtReg) const {
5393   MachineBasicBlock &MBB = *Root.getParent();
5394   MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo();
5395   MachineFunction &MF = *MBB.getParent();
5396   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
5397 
5398   MachineInstr *MUL = nullptr;
5399   const TargetRegisterClass *RC;
5400   unsigned Opc;
5401   switch (Pattern) {
5402   default:
5403     // Reassociate instructions.
5404     TargetInstrInfo::genAlternativeCodeSequence(Root, Pattern, InsInstrs,
5405                                                 DelInstrs, InstrIdxForVirtReg);
5406     return;
5407   case MachineCombinerPattern::MULADDW_OP1:
5408   case MachineCombinerPattern::MULADDX_OP1:
5409     // MUL I=A,B,0
5410     // ADD R,I,C
5411     // ==> MADD R,A,B,C
5412     // --- Create(MADD);
5413     if (Pattern == MachineCombinerPattern::MULADDW_OP1) {
5414       Opc = AArch64::MADDWrrr;
5415       RC = &AArch64::GPR32RegClass;
5416     } else {
5417       Opc = AArch64::MADDXrrr;
5418       RC = &AArch64::GPR64RegClass;
5419     }
5420     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5421     break;
5422   case MachineCombinerPattern::MULADDW_OP2:
5423   case MachineCombinerPattern::MULADDX_OP2:
5424     // MUL I=A,B,0
5425     // ADD R,C,I
5426     // ==> MADD R,A,B,C
5427     // --- Create(MADD);
5428     if (Pattern == MachineCombinerPattern::MULADDW_OP2) {
5429       Opc = AArch64::MADDWrrr;
5430       RC = &AArch64::GPR32RegClass;
5431     } else {
5432       Opc = AArch64::MADDXrrr;
5433       RC = &AArch64::GPR64RegClass;
5434     }
5435     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5436     break;
5437   case MachineCombinerPattern::MULADDWI_OP1:
5438   case MachineCombinerPattern::MULADDXI_OP1: {
5439     // MUL I=A,B,0
5440     // ADD R,I,Imm
5441     // ==> ORR  V, ZR, Imm
5442     // ==> MADD R,A,B,V
5443     // --- Create(MADD);
5444     const TargetRegisterClass *OrrRC;
5445     unsigned BitSize, OrrOpc, ZeroReg;
5446     if (Pattern == MachineCombinerPattern::MULADDWI_OP1) {
5447       OrrOpc = AArch64::ORRWri;
5448       OrrRC = &AArch64::GPR32spRegClass;
5449       BitSize = 32;
5450       ZeroReg = AArch64::WZR;
5451       Opc = AArch64::MADDWrrr;
5452       RC = &AArch64::GPR32RegClass;
5453     } else {
5454       OrrOpc = AArch64::ORRXri;
5455       OrrRC = &AArch64::GPR64spRegClass;
5456       BitSize = 64;
5457       ZeroReg = AArch64::XZR;
5458       Opc = AArch64::MADDXrrr;
5459       RC = &AArch64::GPR64RegClass;
5460     }
5461     Register NewVR = MRI.createVirtualRegister(OrrRC);
5462     uint64_t Imm = Root.getOperand(2).getImm();
5463 
5464     if (Root.getOperand(3).isImm()) {
5465       unsigned Val = Root.getOperand(3).getImm();
5466       Imm = Imm << Val;
5467     }
5468     uint64_t UImm = SignExtend64(Imm, BitSize);
5469     uint64_t Encoding;
5470     if (!AArch64_AM::processLogicalImmediate(UImm, BitSize, Encoding))
5471       return;
5472     MachineInstrBuilder MIB1 =
5473         BuildMI(MF, Root.getDebugLoc(), TII->get(OrrOpc), NewVR)
5474             .addReg(ZeroReg)
5475             .addImm(Encoding);
5476     InsInstrs.push_back(MIB1);
5477     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
5478     MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
5479     break;
5480   }
5481   case MachineCombinerPattern::MULSUBW_OP1:
5482   case MachineCombinerPattern::MULSUBX_OP1: {
5483     // MUL I=A,B,0
5484     // SUB R,I, C
5485     // ==> SUB  V, 0, C
5486     // ==> MADD R,A,B,V // = -C + A*B
5487     // --- Create(MADD);
5488     const TargetRegisterClass *SubRC;
5489     unsigned SubOpc, ZeroReg;
5490     if (Pattern == MachineCombinerPattern::MULSUBW_OP1) {
5491       SubOpc = AArch64::SUBWrr;
5492       SubRC = &AArch64::GPR32spRegClass;
5493       ZeroReg = AArch64::WZR;
5494       Opc = AArch64::MADDWrrr;
5495       RC = &AArch64::GPR32RegClass;
5496     } else {
5497       SubOpc = AArch64::SUBXrr;
5498       SubRC = &AArch64::GPR64spRegClass;
5499       ZeroReg = AArch64::XZR;
5500       Opc = AArch64::MADDXrrr;
5501       RC = &AArch64::GPR64RegClass;
5502     }
5503     Register NewVR = MRI.createVirtualRegister(SubRC);
5504     // SUB NewVR, 0, C
5505     MachineInstrBuilder MIB1 =
5506         BuildMI(MF, Root.getDebugLoc(), TII->get(SubOpc), NewVR)
5507             .addReg(ZeroReg)
5508             .add(Root.getOperand(2));
5509     InsInstrs.push_back(MIB1);
5510     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
5511     MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
5512     break;
5513   }
5514   case MachineCombinerPattern::MULSUBW_OP2:
5515   case MachineCombinerPattern::MULSUBX_OP2:
5516     // MUL I=A,B,0
5517     // SUB R,C,I
5518     // ==> MSUB R,A,B,C (computes C - A*B)
5519     // --- Create(MSUB);
5520     if (Pattern == MachineCombinerPattern::MULSUBW_OP2) {
5521       Opc = AArch64::MSUBWrrr;
5522       RC = &AArch64::GPR32RegClass;
5523     } else {
5524       Opc = AArch64::MSUBXrrr;
5525       RC = &AArch64::GPR64RegClass;
5526     }
5527     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5528     break;
5529   case MachineCombinerPattern::MULSUBWI_OP1:
5530   case MachineCombinerPattern::MULSUBXI_OP1: {
5531     // MUL I=A,B,0
5532     // SUB R,I, Imm
5533     // ==> ORR  V, ZR, -Imm
5534     // ==> MADD R,A,B,V // = -Imm + A*B
5535     // --- Create(MADD);
5536     const TargetRegisterClass *OrrRC;
5537     unsigned BitSize, OrrOpc, ZeroReg;
5538     if (Pattern == MachineCombinerPattern::MULSUBWI_OP1) {
5539       OrrOpc = AArch64::ORRWri;
5540       OrrRC = &AArch64::GPR32spRegClass;
5541       BitSize = 32;
5542       ZeroReg = AArch64::WZR;
5543       Opc = AArch64::MADDWrrr;
5544       RC = &AArch64::GPR32RegClass;
5545     } else {
5546       OrrOpc = AArch64::ORRXri;
5547       OrrRC = &AArch64::GPR64spRegClass;
5548       BitSize = 64;
5549       ZeroReg = AArch64::XZR;
5550       Opc = AArch64::MADDXrrr;
5551       RC = &AArch64::GPR64RegClass;
5552     }
5553     Register NewVR = MRI.createVirtualRegister(OrrRC);
5554     uint64_t Imm = Root.getOperand(2).getImm();
5555     if (Root.getOperand(3).isImm()) {
5556       unsigned Val = Root.getOperand(3).getImm();
5557       Imm = Imm << Val;
5558     }
5559     uint64_t UImm = SignExtend64(-Imm, BitSize);
5560     uint64_t Encoding;
5561     if (!AArch64_AM::processLogicalImmediate(UImm, BitSize, Encoding))
5562       return;
5563     MachineInstrBuilder MIB1 =
5564         BuildMI(MF, Root.getDebugLoc(), TII->get(OrrOpc), NewVR)
5565             .addReg(ZeroReg)
5566             .addImm(Encoding);
5567     InsInstrs.push_back(MIB1);
5568     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
5569     MUL = genMaddR(MF, MRI, TII, Root, InsInstrs, 1, Opc, NewVR, RC);
5570     break;
5571   }
5572 
5573   case MachineCombinerPattern::MULADDv8i8_OP1:
5574     Opc = AArch64::MLAv8i8;
5575     RC = &AArch64::FPR64RegClass;
5576     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5577     break;
5578   case MachineCombinerPattern::MULADDv8i8_OP2:
5579     Opc = AArch64::MLAv8i8;
5580     RC = &AArch64::FPR64RegClass;
5581     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5582     break;
5583   case MachineCombinerPattern::MULADDv16i8_OP1:
5584     Opc = AArch64::MLAv16i8;
5585     RC = &AArch64::FPR128RegClass;
5586     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5587     break;
5588   case MachineCombinerPattern::MULADDv16i8_OP2:
5589     Opc = AArch64::MLAv16i8;
5590     RC = &AArch64::FPR128RegClass;
5591     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5592     break;
5593   case MachineCombinerPattern::MULADDv4i16_OP1:
5594     Opc = AArch64::MLAv4i16;
5595     RC = &AArch64::FPR64RegClass;
5596     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5597     break;
5598   case MachineCombinerPattern::MULADDv4i16_OP2:
5599     Opc = AArch64::MLAv4i16;
5600     RC = &AArch64::FPR64RegClass;
5601     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5602     break;
5603   case MachineCombinerPattern::MULADDv8i16_OP1:
5604     Opc = AArch64::MLAv8i16;
5605     RC = &AArch64::FPR128RegClass;
5606     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5607     break;
5608   case MachineCombinerPattern::MULADDv8i16_OP2:
5609     Opc = AArch64::MLAv8i16;
5610     RC = &AArch64::FPR128RegClass;
5611     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5612     break;
5613   case MachineCombinerPattern::MULADDv2i32_OP1:
5614     Opc = AArch64::MLAv2i32;
5615     RC = &AArch64::FPR64RegClass;
5616     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5617     break;
5618   case MachineCombinerPattern::MULADDv2i32_OP2:
5619     Opc = AArch64::MLAv2i32;
5620     RC = &AArch64::FPR64RegClass;
5621     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5622     break;
5623   case MachineCombinerPattern::MULADDv4i32_OP1:
5624     Opc = AArch64::MLAv4i32;
5625     RC = &AArch64::FPR128RegClass;
5626     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5627     break;
5628   case MachineCombinerPattern::MULADDv4i32_OP2:
5629     Opc = AArch64::MLAv4i32;
5630     RC = &AArch64::FPR128RegClass;
5631     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5632     break;
5633 
5634   case MachineCombinerPattern::MULSUBv8i8_OP1:
5635     Opc = AArch64::MLAv8i8;
5636     RC = &AArch64::FPR64RegClass;
5637     MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
5638                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i8,
5639                                  RC);
5640     break;
5641   case MachineCombinerPattern::MULSUBv8i8_OP2:
5642     Opc = AArch64::MLSv8i8;
5643     RC = &AArch64::FPR64RegClass;
5644     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5645     break;
5646   case MachineCombinerPattern::MULSUBv16i8_OP1:
5647     Opc = AArch64::MLAv16i8;
5648     RC = &AArch64::FPR128RegClass;
5649     MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
5650                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv16i8,
5651                                  RC);
5652     break;
5653   case MachineCombinerPattern::MULSUBv16i8_OP2:
5654     Opc = AArch64::MLSv16i8;
5655     RC = &AArch64::FPR128RegClass;
5656     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5657     break;
5658   case MachineCombinerPattern::MULSUBv4i16_OP1:
5659     Opc = AArch64::MLAv4i16;
5660     RC = &AArch64::FPR64RegClass;
5661     MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
5662                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
5663                                  RC);
5664     break;
5665   case MachineCombinerPattern::MULSUBv4i16_OP2:
5666     Opc = AArch64::MLSv4i16;
5667     RC = &AArch64::FPR64RegClass;
5668     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5669     break;
5670   case MachineCombinerPattern::MULSUBv8i16_OP1:
5671     Opc = AArch64::MLAv8i16;
5672     RC = &AArch64::FPR128RegClass;
5673     MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
5674                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
5675                                  RC);
5676     break;
5677   case MachineCombinerPattern::MULSUBv8i16_OP2:
5678     Opc = AArch64::MLSv8i16;
5679     RC = &AArch64::FPR128RegClass;
5680     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5681     break;
5682   case MachineCombinerPattern::MULSUBv2i32_OP1:
5683     Opc = AArch64::MLAv2i32;
5684     RC = &AArch64::FPR64RegClass;
5685     MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
5686                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
5687                                  RC);
5688     break;
5689   case MachineCombinerPattern::MULSUBv2i32_OP2:
5690     Opc = AArch64::MLSv2i32;
5691     RC = &AArch64::FPR64RegClass;
5692     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5693     break;
5694   case MachineCombinerPattern::MULSUBv4i32_OP1:
5695     Opc = AArch64::MLAv4i32;
5696     RC = &AArch64::FPR128RegClass;
5697     MUL = genFusedMultiplyAccNeg(MF, MRI, TII, Root, InsInstrs,
5698                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
5699                                  RC);
5700     break;
5701   case MachineCombinerPattern::MULSUBv4i32_OP2:
5702     Opc = AArch64::MLSv4i32;
5703     RC = &AArch64::FPR128RegClass;
5704     MUL = genFusedMultiplyAcc(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5705     break;
5706 
5707   case MachineCombinerPattern::MULADDv4i16_indexed_OP1:
5708     Opc = AArch64::MLAv4i16_indexed;
5709     RC = &AArch64::FPR64RegClass;
5710     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5711     break;
5712   case MachineCombinerPattern::MULADDv4i16_indexed_OP2:
5713     Opc = AArch64::MLAv4i16_indexed;
5714     RC = &AArch64::FPR64RegClass;
5715     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5716     break;
5717   case MachineCombinerPattern::MULADDv8i16_indexed_OP1:
5718     Opc = AArch64::MLAv8i16_indexed;
5719     RC = &AArch64::FPR128RegClass;
5720     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5721     break;
5722   case MachineCombinerPattern::MULADDv8i16_indexed_OP2:
5723     Opc = AArch64::MLAv8i16_indexed;
5724     RC = &AArch64::FPR128RegClass;
5725     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5726     break;
5727   case MachineCombinerPattern::MULADDv2i32_indexed_OP1:
5728     Opc = AArch64::MLAv2i32_indexed;
5729     RC = &AArch64::FPR64RegClass;
5730     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5731     break;
5732   case MachineCombinerPattern::MULADDv2i32_indexed_OP2:
5733     Opc = AArch64::MLAv2i32_indexed;
5734     RC = &AArch64::FPR64RegClass;
5735     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5736     break;
5737   case MachineCombinerPattern::MULADDv4i32_indexed_OP1:
5738     Opc = AArch64::MLAv4i32_indexed;
5739     RC = &AArch64::FPR128RegClass;
5740     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5741     break;
5742   case MachineCombinerPattern::MULADDv4i32_indexed_OP2:
5743     Opc = AArch64::MLAv4i32_indexed;
5744     RC = &AArch64::FPR128RegClass;
5745     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5746     break;
5747 
5748   case MachineCombinerPattern::MULSUBv4i16_indexed_OP1:
5749     Opc = AArch64::MLAv4i16_indexed;
5750     RC = &AArch64::FPR64RegClass;
5751     MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
5752                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i16,
5753                                  RC);
5754     break;
5755   case MachineCombinerPattern::MULSUBv4i16_indexed_OP2:
5756     Opc = AArch64::MLSv4i16_indexed;
5757     RC = &AArch64::FPR64RegClass;
5758     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5759     break;
5760   case MachineCombinerPattern::MULSUBv8i16_indexed_OP1:
5761     Opc = AArch64::MLAv8i16_indexed;
5762     RC = &AArch64::FPR128RegClass;
5763     MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
5764                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv8i16,
5765                                  RC);
5766     break;
5767   case MachineCombinerPattern::MULSUBv8i16_indexed_OP2:
5768     Opc = AArch64::MLSv8i16_indexed;
5769     RC = &AArch64::FPR128RegClass;
5770     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5771     break;
5772   case MachineCombinerPattern::MULSUBv2i32_indexed_OP1:
5773     Opc = AArch64::MLAv2i32_indexed;
5774     RC = &AArch64::FPR64RegClass;
5775     MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
5776                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv2i32,
5777                                  RC);
5778     break;
5779   case MachineCombinerPattern::MULSUBv2i32_indexed_OP2:
5780     Opc = AArch64::MLSv2i32_indexed;
5781     RC = &AArch64::FPR64RegClass;
5782     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5783     break;
5784   case MachineCombinerPattern::MULSUBv4i32_indexed_OP1:
5785     Opc = AArch64::MLAv4i32_indexed;
5786     RC = &AArch64::FPR128RegClass;
5787     MUL = genFusedMultiplyIdxNeg(MF, MRI, TII, Root, InsInstrs,
5788                                  InstrIdxForVirtReg, 1, Opc, AArch64::NEGv4i32,
5789                                  RC);
5790     break;
5791   case MachineCombinerPattern::MULSUBv4i32_indexed_OP2:
5792     Opc = AArch64::MLSv4i32_indexed;
5793     RC = &AArch64::FPR128RegClass;
5794     MUL = genFusedMultiplyIdx(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5795     break;
5796 
5797   // Floating Point Support
5798   case MachineCombinerPattern::FMULADDH_OP1:
5799     Opc = AArch64::FMADDHrrr;
5800     RC = &AArch64::FPR16RegClass;
5801     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5802     break;
5803   case MachineCombinerPattern::FMULADDS_OP1:
5804     Opc = AArch64::FMADDSrrr;
5805     RC = &AArch64::FPR32RegClass;
5806     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5807     break;
5808   case MachineCombinerPattern::FMULADDD_OP1:
5809     Opc = AArch64::FMADDDrrr;
5810     RC = &AArch64::FPR64RegClass;
5811     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5812     break;
5813 
5814   case MachineCombinerPattern::FMULADDH_OP2:
5815     Opc = AArch64::FMADDHrrr;
5816     RC = &AArch64::FPR16RegClass;
5817     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5818     break;
5819   case MachineCombinerPattern::FMULADDS_OP2:
5820     Opc = AArch64::FMADDSrrr;
5821     RC = &AArch64::FPR32RegClass;
5822     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5823     break;
5824   case MachineCombinerPattern::FMULADDD_OP2:
5825     Opc = AArch64::FMADDDrrr;
5826     RC = &AArch64::FPR64RegClass;
5827     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
5828     break;
5829 
5830   case MachineCombinerPattern::FMLAv1i32_indexed_OP1:
5831     Opc = AArch64::FMLAv1i32_indexed;
5832     RC = &AArch64::FPR32RegClass;
5833     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5834                            FMAInstKind::Indexed);
5835     break;
5836   case MachineCombinerPattern::FMLAv1i32_indexed_OP2:
5837     Opc = AArch64::FMLAv1i32_indexed;
5838     RC = &AArch64::FPR32RegClass;
5839     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5840                            FMAInstKind::Indexed);
5841     break;
5842 
5843   case MachineCombinerPattern::FMLAv1i64_indexed_OP1:
5844     Opc = AArch64::FMLAv1i64_indexed;
5845     RC = &AArch64::FPR64RegClass;
5846     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5847                            FMAInstKind::Indexed);
5848     break;
5849   case MachineCombinerPattern::FMLAv1i64_indexed_OP2:
5850     Opc = AArch64::FMLAv1i64_indexed;
5851     RC = &AArch64::FPR64RegClass;
5852     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5853                            FMAInstKind::Indexed);
5854     break;
5855 
5856   case MachineCombinerPattern::FMLAv4i16_indexed_OP1:
5857     RC = &AArch64::FPR64RegClass;
5858     Opc = AArch64::FMLAv4i16_indexed;
5859     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5860                            FMAInstKind::Indexed);
5861     break;
5862   case MachineCombinerPattern::FMLAv4f16_OP1:
5863     RC = &AArch64::FPR64RegClass;
5864     Opc = AArch64::FMLAv4f16;
5865     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5866                            FMAInstKind::Accumulator);
5867     break;
5868   case MachineCombinerPattern::FMLAv4i16_indexed_OP2:
5869     RC = &AArch64::FPR64RegClass;
5870     Opc = AArch64::FMLAv4i16_indexed;
5871     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5872                            FMAInstKind::Indexed);
5873     break;
5874   case MachineCombinerPattern::FMLAv4f16_OP2:
5875     RC = &AArch64::FPR64RegClass;
5876     Opc = AArch64::FMLAv4f16;
5877     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5878                            FMAInstKind::Accumulator);
5879     break;
5880 
5881   case MachineCombinerPattern::FMLAv2i32_indexed_OP1:
5882   case MachineCombinerPattern::FMLAv2f32_OP1:
5883     RC = &AArch64::FPR64RegClass;
5884     if (Pattern == MachineCombinerPattern::FMLAv2i32_indexed_OP1) {
5885       Opc = AArch64::FMLAv2i32_indexed;
5886       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5887                              FMAInstKind::Indexed);
5888     } else {
5889       Opc = AArch64::FMLAv2f32;
5890       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5891                              FMAInstKind::Accumulator);
5892     }
5893     break;
5894   case MachineCombinerPattern::FMLAv2i32_indexed_OP2:
5895   case MachineCombinerPattern::FMLAv2f32_OP2:
5896     RC = &AArch64::FPR64RegClass;
5897     if (Pattern == MachineCombinerPattern::FMLAv2i32_indexed_OP2) {
5898       Opc = AArch64::FMLAv2i32_indexed;
5899       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5900                              FMAInstKind::Indexed);
5901     } else {
5902       Opc = AArch64::FMLAv2f32;
5903       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5904                              FMAInstKind::Accumulator);
5905     }
5906     break;
5907 
5908   case MachineCombinerPattern::FMLAv8i16_indexed_OP1:
5909     RC = &AArch64::FPR128RegClass;
5910     Opc = AArch64::FMLAv8i16_indexed;
5911     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5912                            FMAInstKind::Indexed);
5913     break;
5914   case MachineCombinerPattern::FMLAv8f16_OP1:
5915     RC = &AArch64::FPR128RegClass;
5916     Opc = AArch64::FMLAv8f16;
5917     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5918                            FMAInstKind::Accumulator);
5919     break;
5920   case MachineCombinerPattern::FMLAv8i16_indexed_OP2:
5921     RC = &AArch64::FPR128RegClass;
5922     Opc = AArch64::FMLAv8i16_indexed;
5923     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5924                            FMAInstKind::Indexed);
5925     break;
5926   case MachineCombinerPattern::FMLAv8f16_OP2:
5927     RC = &AArch64::FPR128RegClass;
5928     Opc = AArch64::FMLAv8f16;
5929     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5930                            FMAInstKind::Accumulator);
5931     break;
5932 
5933   case MachineCombinerPattern::FMLAv2i64_indexed_OP1:
5934   case MachineCombinerPattern::FMLAv2f64_OP1:
5935     RC = &AArch64::FPR128RegClass;
5936     if (Pattern == MachineCombinerPattern::FMLAv2i64_indexed_OP1) {
5937       Opc = AArch64::FMLAv2i64_indexed;
5938       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5939                              FMAInstKind::Indexed);
5940     } else {
5941       Opc = AArch64::FMLAv2f64;
5942       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5943                              FMAInstKind::Accumulator);
5944     }
5945     break;
5946   case MachineCombinerPattern::FMLAv2i64_indexed_OP2:
5947   case MachineCombinerPattern::FMLAv2f64_OP2:
5948     RC = &AArch64::FPR128RegClass;
5949     if (Pattern == MachineCombinerPattern::FMLAv2i64_indexed_OP2) {
5950       Opc = AArch64::FMLAv2i64_indexed;
5951       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5952                              FMAInstKind::Indexed);
5953     } else {
5954       Opc = AArch64::FMLAv2f64;
5955       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5956                              FMAInstKind::Accumulator);
5957     }
5958     break;
5959 
5960   case MachineCombinerPattern::FMLAv4i32_indexed_OP1:
5961   case MachineCombinerPattern::FMLAv4f32_OP1:
5962     RC = &AArch64::FPR128RegClass;
5963     if (Pattern == MachineCombinerPattern::FMLAv4i32_indexed_OP1) {
5964       Opc = AArch64::FMLAv4i32_indexed;
5965       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5966                              FMAInstKind::Indexed);
5967     } else {
5968       Opc = AArch64::FMLAv4f32;
5969       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
5970                              FMAInstKind::Accumulator);
5971     }
5972     break;
5973 
5974   case MachineCombinerPattern::FMLAv4i32_indexed_OP2:
5975   case MachineCombinerPattern::FMLAv4f32_OP2:
5976     RC = &AArch64::FPR128RegClass;
5977     if (Pattern == MachineCombinerPattern::FMLAv4i32_indexed_OP2) {
5978       Opc = AArch64::FMLAv4i32_indexed;
5979       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5980                              FMAInstKind::Indexed);
5981     } else {
5982       Opc = AArch64::FMLAv4f32;
5983       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
5984                              FMAInstKind::Accumulator);
5985     }
5986     break;
5987 
5988   case MachineCombinerPattern::FMULSUBH_OP1:
5989     Opc = AArch64::FNMSUBHrrr;
5990     RC = &AArch64::FPR16RegClass;
5991     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5992     break;
5993   case MachineCombinerPattern::FMULSUBS_OP1:
5994     Opc = AArch64::FNMSUBSrrr;
5995     RC = &AArch64::FPR32RegClass;
5996     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
5997     break;
5998   case MachineCombinerPattern::FMULSUBD_OP1:
5999     Opc = AArch64::FNMSUBDrrr;
6000     RC = &AArch64::FPR64RegClass;
6001     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
6002     break;
6003 
6004   case MachineCombinerPattern::FNMULSUBH_OP1:
6005     Opc = AArch64::FNMADDHrrr;
6006     RC = &AArch64::FPR16RegClass;
6007     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
6008     break;
6009   case MachineCombinerPattern::FNMULSUBS_OP1:
6010     Opc = AArch64::FNMADDSrrr;
6011     RC = &AArch64::FPR32RegClass;
6012     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
6013     break;
6014   case MachineCombinerPattern::FNMULSUBD_OP1:
6015     Opc = AArch64::FNMADDDrrr;
6016     RC = &AArch64::FPR64RegClass;
6017     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC);
6018     break;
6019 
6020   case MachineCombinerPattern::FMULSUBH_OP2:
6021     Opc = AArch64::FMSUBHrrr;
6022     RC = &AArch64::FPR16RegClass;
6023     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
6024     break;
6025   case MachineCombinerPattern::FMULSUBS_OP2:
6026     Opc = AArch64::FMSUBSrrr;
6027     RC = &AArch64::FPR32RegClass;
6028     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
6029     break;
6030   case MachineCombinerPattern::FMULSUBD_OP2:
6031     Opc = AArch64::FMSUBDrrr;
6032     RC = &AArch64::FPR64RegClass;
6033     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC);
6034     break;
6035 
6036   case MachineCombinerPattern::FMLSv1i32_indexed_OP2:
6037     Opc = AArch64::FMLSv1i32_indexed;
6038     RC = &AArch64::FPR32RegClass;
6039     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6040                            FMAInstKind::Indexed);
6041     break;
6042 
6043   case MachineCombinerPattern::FMLSv1i64_indexed_OP2:
6044     Opc = AArch64::FMLSv1i64_indexed;
6045     RC = &AArch64::FPR64RegClass;
6046     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6047                            FMAInstKind::Indexed);
6048     break;
6049 
6050   case MachineCombinerPattern::FMLSv4f16_OP1:
6051   case MachineCombinerPattern::FMLSv4i16_indexed_OP1: {
6052     RC = &AArch64::FPR64RegClass;
6053     Register NewVR = MRI.createVirtualRegister(RC);
6054     MachineInstrBuilder MIB1 =
6055         BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv4f16), NewVR)
6056             .add(Root.getOperand(2));
6057     InsInstrs.push_back(MIB1);
6058     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
6059     if (Pattern == MachineCombinerPattern::FMLSv4f16_OP1) {
6060       Opc = AArch64::FMLAv4f16;
6061       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6062                              FMAInstKind::Accumulator, &NewVR);
6063     } else {
6064       Opc = AArch64::FMLAv4i16_indexed;
6065       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6066                              FMAInstKind::Indexed, &NewVR);
6067     }
6068     break;
6069   }
6070   case MachineCombinerPattern::FMLSv4f16_OP2:
6071     RC = &AArch64::FPR64RegClass;
6072     Opc = AArch64::FMLSv4f16;
6073     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6074                            FMAInstKind::Accumulator);
6075     break;
6076   case MachineCombinerPattern::FMLSv4i16_indexed_OP2:
6077     RC = &AArch64::FPR64RegClass;
6078     Opc = AArch64::FMLSv4i16_indexed;
6079     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6080                            FMAInstKind::Indexed);
6081     break;
6082 
6083   case MachineCombinerPattern::FMLSv2f32_OP2:
6084   case MachineCombinerPattern::FMLSv2i32_indexed_OP2:
6085     RC = &AArch64::FPR64RegClass;
6086     if (Pattern == MachineCombinerPattern::FMLSv2i32_indexed_OP2) {
6087       Opc = AArch64::FMLSv2i32_indexed;
6088       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6089                              FMAInstKind::Indexed);
6090     } else {
6091       Opc = AArch64::FMLSv2f32;
6092       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6093                              FMAInstKind::Accumulator);
6094     }
6095     break;
6096 
6097   case MachineCombinerPattern::FMLSv8f16_OP1:
6098   case MachineCombinerPattern::FMLSv8i16_indexed_OP1: {
6099     RC = &AArch64::FPR128RegClass;
6100     Register NewVR = MRI.createVirtualRegister(RC);
6101     MachineInstrBuilder MIB1 =
6102         BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv8f16), NewVR)
6103             .add(Root.getOperand(2));
6104     InsInstrs.push_back(MIB1);
6105     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
6106     if (Pattern == MachineCombinerPattern::FMLSv8f16_OP1) {
6107       Opc = AArch64::FMLAv8f16;
6108       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6109                              FMAInstKind::Accumulator, &NewVR);
6110     } else {
6111       Opc = AArch64::FMLAv8i16_indexed;
6112       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6113                              FMAInstKind::Indexed, &NewVR);
6114     }
6115     break;
6116   }
6117   case MachineCombinerPattern::FMLSv8f16_OP2:
6118     RC = &AArch64::FPR128RegClass;
6119     Opc = AArch64::FMLSv8f16;
6120     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6121                            FMAInstKind::Accumulator);
6122     break;
6123   case MachineCombinerPattern::FMLSv8i16_indexed_OP2:
6124     RC = &AArch64::FPR128RegClass;
6125     Opc = AArch64::FMLSv8i16_indexed;
6126     MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6127                            FMAInstKind::Indexed);
6128     break;
6129 
6130   case MachineCombinerPattern::FMLSv2f64_OP2:
6131   case MachineCombinerPattern::FMLSv2i64_indexed_OP2:
6132     RC = &AArch64::FPR128RegClass;
6133     if (Pattern == MachineCombinerPattern::FMLSv2i64_indexed_OP2) {
6134       Opc = AArch64::FMLSv2i64_indexed;
6135       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6136                              FMAInstKind::Indexed);
6137     } else {
6138       Opc = AArch64::FMLSv2f64;
6139       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6140                              FMAInstKind::Accumulator);
6141     }
6142     break;
6143 
6144   case MachineCombinerPattern::FMLSv4f32_OP2:
6145   case MachineCombinerPattern::FMLSv4i32_indexed_OP2:
6146     RC = &AArch64::FPR128RegClass;
6147     if (Pattern == MachineCombinerPattern::FMLSv4i32_indexed_OP2) {
6148       Opc = AArch64::FMLSv4i32_indexed;
6149       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6150                              FMAInstKind::Indexed);
6151     } else {
6152       Opc = AArch64::FMLSv4f32;
6153       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 2, Opc, RC,
6154                              FMAInstKind::Accumulator);
6155     }
6156     break;
6157   case MachineCombinerPattern::FMLSv2f32_OP1:
6158   case MachineCombinerPattern::FMLSv2i32_indexed_OP1: {
6159     RC = &AArch64::FPR64RegClass;
6160     Register NewVR = MRI.createVirtualRegister(RC);
6161     MachineInstrBuilder MIB1 =
6162         BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv2f32), NewVR)
6163             .add(Root.getOperand(2));
6164     InsInstrs.push_back(MIB1);
6165     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
6166     if (Pattern == MachineCombinerPattern::FMLSv2i32_indexed_OP1) {
6167       Opc = AArch64::FMLAv2i32_indexed;
6168       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6169                              FMAInstKind::Indexed, &NewVR);
6170     } else {
6171       Opc = AArch64::FMLAv2f32;
6172       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6173                              FMAInstKind::Accumulator, &NewVR);
6174     }
6175     break;
6176   }
6177   case MachineCombinerPattern::FMLSv4f32_OP1:
6178   case MachineCombinerPattern::FMLSv4i32_indexed_OP1: {
6179     RC = &AArch64::FPR128RegClass;
6180     Register NewVR = MRI.createVirtualRegister(RC);
6181     MachineInstrBuilder MIB1 =
6182         BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv4f32), NewVR)
6183             .add(Root.getOperand(2));
6184     InsInstrs.push_back(MIB1);
6185     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
6186     if (Pattern == MachineCombinerPattern::FMLSv4i32_indexed_OP1) {
6187       Opc = AArch64::FMLAv4i32_indexed;
6188       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6189                              FMAInstKind::Indexed, &NewVR);
6190     } else {
6191       Opc = AArch64::FMLAv4f32;
6192       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6193                              FMAInstKind::Accumulator, &NewVR);
6194     }
6195     break;
6196   }
6197   case MachineCombinerPattern::FMLSv2f64_OP1:
6198   case MachineCombinerPattern::FMLSv2i64_indexed_OP1: {
6199     RC = &AArch64::FPR128RegClass;
6200     Register NewVR = MRI.createVirtualRegister(RC);
6201     MachineInstrBuilder MIB1 =
6202         BuildMI(MF, Root.getDebugLoc(), TII->get(AArch64::FNEGv2f64), NewVR)
6203             .add(Root.getOperand(2));
6204     InsInstrs.push_back(MIB1);
6205     InstrIdxForVirtReg.insert(std::make_pair(NewVR, 0));
6206     if (Pattern == MachineCombinerPattern::FMLSv2i64_indexed_OP1) {
6207       Opc = AArch64::FMLAv2i64_indexed;
6208       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6209                              FMAInstKind::Indexed, &NewVR);
6210     } else {
6211       Opc = AArch64::FMLAv2f64;
6212       MUL = genFusedMultiply(MF, MRI, TII, Root, InsInstrs, 1, Opc, RC,
6213                              FMAInstKind::Accumulator, &NewVR);
6214     }
6215     break;
6216   }
6217   case MachineCombinerPattern::FMULv2i32_indexed_OP1:
6218   case MachineCombinerPattern::FMULv2i32_indexed_OP2: {
6219     unsigned IdxDupOp =
6220         (Pattern == MachineCombinerPattern::FMULv2i32_indexed_OP1) ? 1 : 2;
6221     genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i32_indexed,
6222                        &AArch64::FPR128RegClass, MRI);
6223     break;
6224   }
6225   case MachineCombinerPattern::FMULv2i64_indexed_OP1:
6226   case MachineCombinerPattern::FMULv2i64_indexed_OP2: {
6227     unsigned IdxDupOp =
6228         (Pattern == MachineCombinerPattern::FMULv2i64_indexed_OP1) ? 1 : 2;
6229     genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv2i64_indexed,
6230                        &AArch64::FPR128RegClass, MRI);
6231     break;
6232   }
6233   case MachineCombinerPattern::FMULv4i16_indexed_OP1:
6234   case MachineCombinerPattern::FMULv4i16_indexed_OP2: {
6235     unsigned IdxDupOp =
6236         (Pattern == MachineCombinerPattern::FMULv4i16_indexed_OP1) ? 1 : 2;
6237     genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i16_indexed,
6238                        &AArch64::FPR128_loRegClass, MRI);
6239     break;
6240   }
6241   case MachineCombinerPattern::FMULv4i32_indexed_OP1:
6242   case MachineCombinerPattern::FMULv4i32_indexed_OP2: {
6243     unsigned IdxDupOp =
6244         (Pattern == MachineCombinerPattern::FMULv4i32_indexed_OP1) ? 1 : 2;
6245     genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv4i32_indexed,
6246                        &AArch64::FPR128RegClass, MRI);
6247     break;
6248   }
6249   case MachineCombinerPattern::FMULv8i16_indexed_OP1:
6250   case MachineCombinerPattern::FMULv8i16_indexed_OP2: {
6251     unsigned IdxDupOp =
6252         (Pattern == MachineCombinerPattern::FMULv8i16_indexed_OP1) ? 1 : 2;
6253     genIndexedMultiply(Root, InsInstrs, IdxDupOp, AArch64::FMULv8i16_indexed,
6254                        &AArch64::FPR128_loRegClass, MRI);
6255     break;
6256   }
6257   } // end switch (Pattern)
6258   // Record MUL and ADD/SUB for deletion
6259   if (MUL)
6260     DelInstrs.push_back(MUL);
6261   DelInstrs.push_back(&Root);
6262 
6263   // Set the flags on the inserted instructions to be the merged flags of the
6264   // instructions that we have combined.
6265   uint16_t Flags = Root.getFlags();
6266   if (MUL)
6267     Flags = Root.mergeFlagsWith(*MUL);
6268   for (auto *MI : InsInstrs)
6269     MI->setFlags(Flags);
6270 }
6271 
6272 /// Replace csincr-branch sequence by simple conditional branch
6273 ///
6274 /// Examples:
6275 /// 1. \code
6276 ///   csinc  w9, wzr, wzr, <condition code>
6277 ///   tbnz   w9, #0, 0x44
6278 ///    \endcode
6279 /// to
6280 ///    \code
6281 ///   b.<inverted condition code>
6282 ///    \endcode
6283 ///
6284 /// 2. \code
6285 ///   csinc w9, wzr, wzr, <condition code>
6286 ///   tbz   w9, #0, 0x44
6287 ///    \endcode
6288 /// to
6289 ///    \code
6290 ///   b.<condition code>
6291 ///    \endcode
6292 ///
6293 /// Replace compare and branch sequence by TBZ/TBNZ instruction when the
6294 /// compare's constant operand is power of 2.
6295 ///
6296 /// Examples:
6297 ///    \code
6298 ///   and  w8, w8, #0x400
6299 ///   cbnz w8, L1
6300 ///    \endcode
6301 /// to
6302 ///    \code
6303 ///   tbnz w8, #10, L1
6304 ///    \endcode
6305 ///
6306 /// \param  MI Conditional Branch
6307 /// \return True when the simple conditional branch is generated
6308 ///
6309 bool AArch64InstrInfo::optimizeCondBranch(MachineInstr &MI) const {
6310   bool IsNegativeBranch = false;
6311   bool IsTestAndBranch = false;
6312   unsigned TargetBBInMI = 0;
6313   switch (MI.getOpcode()) {
6314   default:
6315     llvm_unreachable("Unknown branch instruction?");
6316   case AArch64::Bcc:
6317     return false;
6318   case AArch64::CBZW:
6319   case AArch64::CBZX:
6320     TargetBBInMI = 1;
6321     break;
6322   case AArch64::CBNZW:
6323   case AArch64::CBNZX:
6324     TargetBBInMI = 1;
6325     IsNegativeBranch = true;
6326     break;
6327   case AArch64::TBZW:
6328   case AArch64::TBZX:
6329     TargetBBInMI = 2;
6330     IsTestAndBranch = true;
6331     break;
6332   case AArch64::TBNZW:
6333   case AArch64::TBNZX:
6334     TargetBBInMI = 2;
6335     IsNegativeBranch = true;
6336     IsTestAndBranch = true;
6337     break;
6338   }
6339   // So we increment a zero register and test for bits other
6340   // than bit 0? Conservatively bail out in case the verifier
6341   // missed this case.
6342   if (IsTestAndBranch && MI.getOperand(1).getImm())
6343     return false;
6344 
6345   // Find Definition.
6346   assert(MI.getParent() && "Incomplete machine instruciton\n");
6347   MachineBasicBlock *MBB = MI.getParent();
6348   MachineFunction *MF = MBB->getParent();
6349   MachineRegisterInfo *MRI = &MF->getRegInfo();
6350   Register VReg = MI.getOperand(0).getReg();
6351   if (!Register::isVirtualRegister(VReg))
6352     return false;
6353 
6354   MachineInstr *DefMI = MRI->getVRegDef(VReg);
6355 
6356   // Look through COPY instructions to find definition.
6357   while (DefMI->isCopy()) {
6358     Register CopyVReg = DefMI->getOperand(1).getReg();
6359     if (!MRI->hasOneNonDBGUse(CopyVReg))
6360       return false;
6361     if (!MRI->hasOneDef(CopyVReg))
6362       return false;
6363     DefMI = MRI->getVRegDef(CopyVReg);
6364   }
6365 
6366   switch (DefMI->getOpcode()) {
6367   default:
6368     return false;
6369   // Fold AND into a TBZ/TBNZ if constant operand is power of 2.
6370   case AArch64::ANDWri:
6371   case AArch64::ANDXri: {
6372     if (IsTestAndBranch)
6373       return false;
6374     if (DefMI->getParent() != MBB)
6375       return false;
6376     if (!MRI->hasOneNonDBGUse(VReg))
6377       return false;
6378 
6379     bool Is32Bit = (DefMI->getOpcode() == AArch64::ANDWri);
6380     uint64_t Mask = AArch64_AM::decodeLogicalImmediate(
6381         DefMI->getOperand(2).getImm(), Is32Bit ? 32 : 64);
6382     if (!isPowerOf2_64(Mask))
6383       return false;
6384 
6385     MachineOperand &MO = DefMI->getOperand(1);
6386     Register NewReg = MO.getReg();
6387     if (!Register::isVirtualRegister(NewReg))
6388       return false;
6389 
6390     assert(!MRI->def_empty(NewReg) && "Register must be defined.");
6391 
6392     MachineBasicBlock &RefToMBB = *MBB;
6393     MachineBasicBlock *TBB = MI.getOperand(1).getMBB();
6394     DebugLoc DL = MI.getDebugLoc();
6395     unsigned Imm = Log2_64(Mask);
6396     unsigned Opc = (Imm < 32)
6397                        ? (IsNegativeBranch ? AArch64::TBNZW : AArch64::TBZW)
6398                        : (IsNegativeBranch ? AArch64::TBNZX : AArch64::TBZX);
6399     MachineInstr *NewMI = BuildMI(RefToMBB, MI, DL, get(Opc))
6400                               .addReg(NewReg)
6401                               .addImm(Imm)
6402                               .addMBB(TBB);
6403     // Register lives on to the CBZ now.
6404     MO.setIsKill(false);
6405 
6406     // For immediate smaller than 32, we need to use the 32-bit
6407     // variant (W) in all cases. Indeed the 64-bit variant does not
6408     // allow to encode them.
6409     // Therefore, if the input register is 64-bit, we need to take the
6410     // 32-bit sub-part.
6411     if (!Is32Bit && Imm < 32)
6412       NewMI->getOperand(0).setSubReg(AArch64::sub_32);
6413     MI.eraseFromParent();
6414     return true;
6415   }
6416   // Look for CSINC
6417   case AArch64::CSINCWr:
6418   case AArch64::CSINCXr: {
6419     if (!(DefMI->getOperand(1).getReg() == AArch64::WZR &&
6420           DefMI->getOperand(2).getReg() == AArch64::WZR) &&
6421         !(DefMI->getOperand(1).getReg() == AArch64::XZR &&
6422           DefMI->getOperand(2).getReg() == AArch64::XZR))
6423       return false;
6424 
6425     if (DefMI->findRegisterDefOperandIdx(AArch64::NZCV, true) != -1)
6426       return false;
6427 
6428     AArch64CC::CondCode CC = (AArch64CC::CondCode)DefMI->getOperand(3).getImm();
6429     // Convert only when the condition code is not modified between
6430     // the CSINC and the branch. The CC may be used by other
6431     // instructions in between.
6432     if (areCFlagsAccessedBetweenInstrs(DefMI, MI, &getRegisterInfo(), AK_Write))
6433       return false;
6434     MachineBasicBlock &RefToMBB = *MBB;
6435     MachineBasicBlock *TBB = MI.getOperand(TargetBBInMI).getMBB();
6436     DebugLoc DL = MI.getDebugLoc();
6437     if (IsNegativeBranch)
6438       CC = AArch64CC::getInvertedCondCode(CC);
6439     BuildMI(RefToMBB, MI, DL, get(AArch64::Bcc)).addImm(CC).addMBB(TBB);
6440     MI.eraseFromParent();
6441     return true;
6442   }
6443   }
6444 }
6445 
6446 std::pair<unsigned, unsigned>
6447 AArch64InstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const {
6448   const unsigned Mask = AArch64II::MO_FRAGMENT;
6449   return std::make_pair(TF & Mask, TF & ~Mask);
6450 }
6451 
6452 ArrayRef<std::pair<unsigned, const char *>>
6453 AArch64InstrInfo::getSerializableDirectMachineOperandTargetFlags() const {
6454   using namespace AArch64II;
6455 
6456   static const std::pair<unsigned, const char *> TargetFlags[] = {
6457       {MO_PAGE, "aarch64-page"}, {MO_PAGEOFF, "aarch64-pageoff"},
6458       {MO_G3, "aarch64-g3"},     {MO_G2, "aarch64-g2"},
6459       {MO_G1, "aarch64-g1"},     {MO_G0, "aarch64-g0"},
6460       {MO_HI12, "aarch64-hi12"}};
6461   return makeArrayRef(TargetFlags);
6462 }
6463 
6464 ArrayRef<std::pair<unsigned, const char *>>
6465 AArch64InstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const {
6466   using namespace AArch64II;
6467 
6468   static const std::pair<unsigned, const char *> TargetFlags[] = {
6469       {MO_COFFSTUB, "aarch64-coffstub"},
6470       {MO_GOT, "aarch64-got"},
6471       {MO_NC, "aarch64-nc"},
6472       {MO_S, "aarch64-s"},
6473       {MO_TLS, "aarch64-tls"},
6474       {MO_DLLIMPORT, "aarch64-dllimport"},
6475       {MO_PREL, "aarch64-prel"},
6476       {MO_TAGGED, "aarch64-tagged"}};
6477   return makeArrayRef(TargetFlags);
6478 }
6479 
6480 ArrayRef<std::pair<MachineMemOperand::Flags, const char *>>
6481 AArch64InstrInfo::getSerializableMachineMemOperandTargetFlags() const {
6482   static const std::pair<MachineMemOperand::Flags, const char *> TargetFlags[] =
6483       {{MOSuppressPair, "aarch64-suppress-pair"},
6484        {MOStridedAccess, "aarch64-strided-access"}};
6485   return makeArrayRef(TargetFlags);
6486 }
6487 
6488 /// Constants defining how certain sequences should be outlined.
6489 /// This encompasses how an outlined function should be called, and what kind of
6490 /// frame should be emitted for that outlined function.
6491 ///
6492 /// \p MachineOutlinerDefault implies that the function should be called with
6493 /// a save and restore of LR to the stack.
6494 ///
6495 /// That is,
6496 ///
6497 /// I1     Save LR                    OUTLINED_FUNCTION:
6498 /// I2 --> BL OUTLINED_FUNCTION       I1
6499 /// I3     Restore LR                 I2
6500 ///                                   I3
6501 ///                                   RET
6502 ///
6503 /// * Call construction overhead: 3 (save + BL + restore)
6504 /// * Frame construction overhead: 1 (ret)
6505 /// * Requires stack fixups? Yes
6506 ///
6507 /// \p MachineOutlinerTailCall implies that the function is being created from
6508 /// a sequence of instructions ending in a return.
6509 ///
6510 /// That is,
6511 ///
6512 /// I1                             OUTLINED_FUNCTION:
6513 /// I2 --> B OUTLINED_FUNCTION     I1
6514 /// RET                            I2
6515 ///                                RET
6516 ///
6517 /// * Call construction overhead: 1 (B)
6518 /// * Frame construction overhead: 0 (Return included in sequence)
6519 /// * Requires stack fixups? No
6520 ///
6521 /// \p MachineOutlinerNoLRSave implies that the function should be called using
6522 /// a BL instruction, but doesn't require LR to be saved and restored. This
6523 /// happens when LR is known to be dead.
6524 ///
6525 /// That is,
6526 ///
6527 /// I1                                OUTLINED_FUNCTION:
6528 /// I2 --> BL OUTLINED_FUNCTION       I1
6529 /// I3                                I2
6530 ///                                   I3
6531 ///                                   RET
6532 ///
6533 /// * Call construction overhead: 1 (BL)
6534 /// * Frame construction overhead: 1 (RET)
6535 /// * Requires stack fixups? No
6536 ///
6537 /// \p MachineOutlinerThunk implies that the function is being created from
6538 /// a sequence of instructions ending in a call. The outlined function is
6539 /// called with a BL instruction, and the outlined function tail-calls the
6540 /// original call destination.
6541 ///
6542 /// That is,
6543 ///
6544 /// I1                                OUTLINED_FUNCTION:
6545 /// I2 --> BL OUTLINED_FUNCTION       I1
6546 /// BL f                              I2
6547 ///                                   B f
6548 /// * Call construction overhead: 1 (BL)
6549 /// * Frame construction overhead: 0
6550 /// * Requires stack fixups? No
6551 ///
6552 /// \p MachineOutlinerRegSave implies that the function should be called with a
6553 /// save and restore of LR to an available register. This allows us to avoid
6554 /// stack fixups. Note that this outlining variant is compatible with the
6555 /// NoLRSave case.
6556 ///
6557 /// That is,
6558 ///
6559 /// I1     Save LR                    OUTLINED_FUNCTION:
6560 /// I2 --> BL OUTLINED_FUNCTION       I1
6561 /// I3     Restore LR                 I2
6562 ///                                   I3
6563 ///                                   RET
6564 ///
6565 /// * Call construction overhead: 3 (save + BL + restore)
6566 /// * Frame construction overhead: 1 (ret)
6567 /// * Requires stack fixups? No
6568 enum MachineOutlinerClass {
6569   MachineOutlinerDefault,  /// Emit a save, restore, call, and return.
6570   MachineOutlinerTailCall, /// Only emit a branch.
6571   MachineOutlinerNoLRSave, /// Emit a call and return.
6572   MachineOutlinerThunk,    /// Emit a call and tail-call.
6573   MachineOutlinerRegSave   /// Same as default, but save to a register.
6574 };
6575 
6576 enum MachineOutlinerMBBFlags {
6577   LRUnavailableSomewhere = 0x2,
6578   HasCalls = 0x4,
6579   UnsafeRegsDead = 0x8
6580 };
6581 
6582 Register
6583 AArch64InstrInfo::findRegisterToSaveLRTo(outliner::Candidate &C) const {
6584   MachineFunction *MF = C.getMF();
6585   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
6586   const AArch64RegisterInfo *ARI =
6587       static_cast<const AArch64RegisterInfo *>(&TRI);
6588   // Check if there is an available register across the sequence that we can
6589   // use.
6590   for (unsigned Reg : AArch64::GPR64RegClass) {
6591     if (!ARI->isReservedReg(*MF, Reg) &&
6592         Reg != AArch64::LR &&  // LR is not reserved, but don't use it.
6593         Reg != AArch64::X16 && // X16 is not guaranteed to be preserved.
6594         Reg != AArch64::X17 && // Ditto for X17.
6595         C.isAvailableAcrossAndOutOfSeq(Reg, TRI) &&
6596         C.isAvailableInsideSeq(Reg, TRI))
6597       return Reg;
6598   }
6599   return Register();
6600 }
6601 
6602 static bool
6603 outliningCandidatesSigningScopeConsensus(const outliner::Candidate &a,
6604                                          const outliner::Candidate &b) {
6605   const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
6606   const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
6607 
6608   return MFIa->shouldSignReturnAddress(false) == MFIb->shouldSignReturnAddress(false) &&
6609          MFIa->shouldSignReturnAddress(true) == MFIb->shouldSignReturnAddress(true);
6610 }
6611 
6612 static bool
6613 outliningCandidatesSigningKeyConsensus(const outliner::Candidate &a,
6614                                        const outliner::Candidate &b) {
6615   const auto &MFIa = a.getMF()->getInfo<AArch64FunctionInfo>();
6616   const auto &MFIb = b.getMF()->getInfo<AArch64FunctionInfo>();
6617 
6618   return MFIa->shouldSignWithBKey() == MFIb->shouldSignWithBKey();
6619 }
6620 
6621 static bool outliningCandidatesV8_3OpsConsensus(const outliner::Candidate &a,
6622                                                 const outliner::Candidate &b) {
6623   const AArch64Subtarget &SubtargetA =
6624       a.getMF()->getSubtarget<AArch64Subtarget>();
6625   const AArch64Subtarget &SubtargetB =
6626       b.getMF()->getSubtarget<AArch64Subtarget>();
6627   return SubtargetA.hasV8_3aOps() == SubtargetB.hasV8_3aOps();
6628 }
6629 
6630 outliner::OutlinedFunction AArch64InstrInfo::getOutliningCandidateInfo(
6631     std::vector<outliner::Candidate> &RepeatedSequenceLocs) const {
6632   outliner::Candidate &FirstCand = RepeatedSequenceLocs[0];
6633   unsigned SequenceSize =
6634       std::accumulate(FirstCand.front(), std::next(FirstCand.back()), 0,
6635                       [this](unsigned Sum, const MachineInstr &MI) {
6636                         return Sum + getInstSizeInBytes(MI);
6637                       });
6638   unsigned NumBytesToCreateFrame = 0;
6639 
6640   // We only allow outlining for functions having exactly matching return
6641   // address signing attributes, i.e., all share the same value for the
6642   // attribute "sign-return-address" and all share the same type of key they
6643   // are signed with.
6644   // Additionally we require all functions to simultaniously either support
6645   // v8.3a features or not. Otherwise an outlined function could get signed
6646   // using dedicated v8.3 instructions and a call from a function that doesn't
6647   // support v8.3 instructions would therefore be invalid.
6648   if (std::adjacent_find(
6649           RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
6650           [](const outliner::Candidate &a, const outliner::Candidate &b) {
6651             // Return true if a and b are non-equal w.r.t. return address
6652             // signing or support of v8.3a features
6653             if (outliningCandidatesSigningScopeConsensus(a, b) &&
6654                 outliningCandidatesSigningKeyConsensus(a, b) &&
6655                 outliningCandidatesV8_3OpsConsensus(a, b)) {
6656               return false;
6657             }
6658             return true;
6659           }) != RepeatedSequenceLocs.end()) {
6660     return outliner::OutlinedFunction();
6661   }
6662 
6663   // Since at this point all candidates agree on their return address signing
6664   // picking just one is fine. If the candidate functions potentially sign their
6665   // return addresses, the outlined function should do the same. Note that in
6666   // the case of "sign-return-address"="non-leaf" this is an assumption: It is
6667   // not certainly true that the outlined function will have to sign its return
6668   // address but this decision is made later, when the decision to outline
6669   // has already been made.
6670   // The same holds for the number of additional instructions we need: On
6671   // v8.3a RET can be replaced by RETAA/RETAB and no AUT instruction is
6672   // necessary. However, at this point we don't know if the outlined function
6673   // will have a RET instruction so we assume the worst.
6674   const TargetRegisterInfo &TRI = getRegisterInfo();
6675   if (FirstCand.getMF()
6676           ->getInfo<AArch64FunctionInfo>()
6677           ->shouldSignReturnAddress(true)) {
6678     // One PAC and one AUT instructions
6679     NumBytesToCreateFrame += 8;
6680 
6681     // We have to check if sp modifying instructions would get outlined.
6682     // If so we only allow outlining if sp is unchanged overall, so matching
6683     // sub and add instructions are okay to outline, all other sp modifications
6684     // are not
6685     auto hasIllegalSPModification = [&TRI](outliner::Candidate &C) {
6686       int SPValue = 0;
6687       MachineBasicBlock::iterator MBBI = C.front();
6688       for (;;) {
6689         if (MBBI->modifiesRegister(AArch64::SP, &TRI)) {
6690           switch (MBBI->getOpcode()) {
6691           case AArch64::ADDXri:
6692           case AArch64::ADDWri:
6693             assert(MBBI->getNumOperands() == 4 && "Wrong number of operands");
6694             assert(MBBI->getOperand(2).isImm() &&
6695                    "Expected operand to be immediate");
6696             assert(MBBI->getOperand(1).isReg() &&
6697                    "Expected operand to be a register");
6698             // Check if the add just increments sp. If so, we search for
6699             // matching sub instructions that decrement sp. If not, the
6700             // modification is illegal
6701             if (MBBI->getOperand(1).getReg() == AArch64::SP)
6702               SPValue += MBBI->getOperand(2).getImm();
6703             else
6704               return true;
6705             break;
6706           case AArch64::SUBXri:
6707           case AArch64::SUBWri:
6708             assert(MBBI->getNumOperands() == 4 && "Wrong number of operands");
6709             assert(MBBI->getOperand(2).isImm() &&
6710                    "Expected operand to be immediate");
6711             assert(MBBI->getOperand(1).isReg() &&
6712                    "Expected operand to be a register");
6713             // Check if the sub just decrements sp. If so, we search for
6714             // matching add instructions that increment sp. If not, the
6715             // modification is illegal
6716             if (MBBI->getOperand(1).getReg() == AArch64::SP)
6717               SPValue -= MBBI->getOperand(2).getImm();
6718             else
6719               return true;
6720             break;
6721           default:
6722             return true;
6723           }
6724         }
6725         if (MBBI == C.back())
6726           break;
6727         ++MBBI;
6728       }
6729       if (SPValue)
6730         return true;
6731       return false;
6732     };
6733     // Remove candidates with illegal stack modifying instructions
6734     llvm::erase_if(RepeatedSequenceLocs, hasIllegalSPModification);
6735 
6736     // If the sequence doesn't have enough candidates left, then we're done.
6737     if (RepeatedSequenceLocs.size() < 2)
6738       return outliner::OutlinedFunction();
6739   }
6740 
6741   // Properties about candidate MBBs that hold for all of them.
6742   unsigned FlagsSetInAll = 0xF;
6743 
6744   // Compute liveness information for each candidate, and set FlagsSetInAll.
6745   std::for_each(RepeatedSequenceLocs.begin(), RepeatedSequenceLocs.end(),
6746                 [&FlagsSetInAll](outliner::Candidate &C) {
6747                   FlagsSetInAll &= C.Flags;
6748                 });
6749 
6750   // According to the AArch64 Procedure Call Standard, the following are
6751   // undefined on entry/exit from a function call:
6752   //
6753   // * Registers x16, x17, (and thus w16, w17)
6754   // * Condition codes (and thus the NZCV register)
6755   //
6756   // Because if this, we can't outline any sequence of instructions where
6757   // one
6758   // of these registers is live into/across it. Thus, we need to delete
6759   // those
6760   // candidates.
6761   auto CantGuaranteeValueAcrossCall = [&TRI](outliner::Candidate &C) {
6762     // If the unsafe registers in this block are all dead, then we don't need
6763     // to compute liveness here.
6764     if (C.Flags & UnsafeRegsDead)
6765       return false;
6766     return C.isAnyUnavailableAcrossOrOutOfSeq(
6767         {AArch64::W16, AArch64::W17, AArch64::NZCV}, TRI);
6768   };
6769 
6770   // Are there any candidates where those registers are live?
6771   if (!(FlagsSetInAll & UnsafeRegsDead)) {
6772     // Erase every candidate that violates the restrictions above. (It could be
6773     // true that we have viable candidates, so it's not worth bailing out in
6774     // the case that, say, 1 out of 20 candidates violate the restructions.)
6775     llvm::erase_if(RepeatedSequenceLocs, CantGuaranteeValueAcrossCall);
6776 
6777     // If the sequence doesn't have enough candidates left, then we're done.
6778     if (RepeatedSequenceLocs.size() < 2)
6779       return outliner::OutlinedFunction();
6780   }
6781 
6782   // At this point, we have only "safe" candidates to outline. Figure out
6783   // frame + call instruction information.
6784 
6785   unsigned LastInstrOpcode = RepeatedSequenceLocs[0].back()->getOpcode();
6786 
6787   // Helper lambda which sets call information for every candidate.
6788   auto SetCandidateCallInfo =
6789       [&RepeatedSequenceLocs](unsigned CallID, unsigned NumBytesForCall) {
6790         for (outliner::Candidate &C : RepeatedSequenceLocs)
6791           C.setCallInfo(CallID, NumBytesForCall);
6792       };
6793 
6794   unsigned FrameID = MachineOutlinerDefault;
6795   NumBytesToCreateFrame += 4;
6796 
6797   bool HasBTI = any_of(RepeatedSequenceLocs, [](outliner::Candidate &C) {
6798     return C.getMF()->getInfo<AArch64FunctionInfo>()->branchTargetEnforcement();
6799   });
6800 
6801   // We check to see if CFI Instructions are present, and if they are
6802   // we find the number of CFI Instructions in the candidates.
6803   unsigned CFICount = 0;
6804   MachineBasicBlock::iterator MBBI = RepeatedSequenceLocs[0].front();
6805   for (unsigned Loc = RepeatedSequenceLocs[0].getStartIdx();
6806        Loc < RepeatedSequenceLocs[0].getEndIdx() + 1; Loc++) {
6807     if (MBBI->isCFIInstruction())
6808       CFICount++;
6809     MBBI++;
6810   }
6811 
6812   // We compare the number of found CFI Instructions to  the number of CFI
6813   // instructions in the parent function for each candidate.  We must check this
6814   // since if we outline one of the CFI instructions in a function, we have to
6815   // outline them all for correctness. If we do not, the address offsets will be
6816   // incorrect between the two sections of the program.
6817   for (outliner::Candidate &C : RepeatedSequenceLocs) {
6818     std::vector<MCCFIInstruction> CFIInstructions =
6819         C.getMF()->getFrameInstructions();
6820 
6821     if (CFICount > 0 && CFICount != CFIInstructions.size())
6822       return outliner::OutlinedFunction();
6823   }
6824 
6825   // Returns true if an instructions is safe to fix up, false otherwise.
6826   auto IsSafeToFixup = [this, &TRI](MachineInstr &MI) {
6827     if (MI.isCall())
6828       return true;
6829 
6830     if (!MI.modifiesRegister(AArch64::SP, &TRI) &&
6831         !MI.readsRegister(AArch64::SP, &TRI))
6832       return true;
6833 
6834     // Any modification of SP will break our code to save/restore LR.
6835     // FIXME: We could handle some instructions which add a constant
6836     // offset to SP, with a bit more work.
6837     if (MI.modifiesRegister(AArch64::SP, &TRI))
6838       return false;
6839 
6840     // At this point, we have a stack instruction that we might need to
6841     // fix up. We'll handle it if it's a load or store.
6842     if (MI.mayLoadOrStore()) {
6843       const MachineOperand *Base; // Filled with the base operand of MI.
6844       int64_t Offset;             // Filled with the offset of MI.
6845       bool OffsetIsScalable;
6846 
6847       // Does it allow us to offset the base operand and is the base the
6848       // register SP?
6849       if (!getMemOperandWithOffset(MI, Base, Offset, OffsetIsScalable, &TRI) ||
6850           !Base->isReg() || Base->getReg() != AArch64::SP)
6851         return false;
6852 
6853       // Fixe-up code below assumes bytes.
6854       if (OffsetIsScalable)
6855         return false;
6856 
6857       // Find the minimum/maximum offset for this instruction and check
6858       // if fixing it up would be in range.
6859       int64_t MinOffset,
6860           MaxOffset;  // Unscaled offsets for the instruction.
6861       TypeSize Scale(0U, false); // The scale to multiply the offsets by.
6862       unsigned DummyWidth;
6863       getMemOpInfo(MI.getOpcode(), Scale, DummyWidth, MinOffset, MaxOffset);
6864 
6865       Offset += 16; // Update the offset to what it would be if we outlined.
6866       if (Offset < MinOffset * (int64_t)Scale.getFixedSize() ||
6867           Offset > MaxOffset * (int64_t)Scale.getFixedSize())
6868         return false;
6869 
6870       // It's in range, so we can outline it.
6871       return true;
6872     }
6873 
6874     // FIXME: Add handling for instructions like "add x0, sp, #8".
6875 
6876     // We can't fix it up, so don't outline it.
6877     return false;
6878   };
6879 
6880   // True if it's possible to fix up each stack instruction in this sequence.
6881   // Important for frames/call variants that modify the stack.
6882   bool AllStackInstrsSafe = std::all_of(
6883       FirstCand.front(), std::next(FirstCand.back()), IsSafeToFixup);
6884 
6885   // If the last instruction in any candidate is a terminator, then we should
6886   // tail call all of the candidates.
6887   if (RepeatedSequenceLocs[0].back()->isTerminator()) {
6888     FrameID = MachineOutlinerTailCall;
6889     NumBytesToCreateFrame = 0;
6890     SetCandidateCallInfo(MachineOutlinerTailCall, 4);
6891   }
6892 
6893   else if (LastInstrOpcode == AArch64::BL ||
6894            ((LastInstrOpcode == AArch64::BLR ||
6895              LastInstrOpcode == AArch64::BLRNoIP) &&
6896             !HasBTI)) {
6897     // FIXME: Do we need to check if the code after this uses the value of LR?
6898     FrameID = MachineOutlinerThunk;
6899     NumBytesToCreateFrame = 0;
6900     SetCandidateCallInfo(MachineOutlinerThunk, 4);
6901   }
6902 
6903   else {
6904     // We need to decide how to emit calls + frames. We can always emit the same
6905     // frame if we don't need to save to the stack. If we have to save to the
6906     // stack, then we need a different frame.
6907     unsigned NumBytesNoStackCalls = 0;
6908     std::vector<outliner::Candidate> CandidatesWithoutStackFixups;
6909 
6910     // Check if we have to save LR.
6911     for (outliner::Candidate &C : RepeatedSequenceLocs) {
6912       // If we have a noreturn caller, then we're going to be conservative and
6913       // say that we have to save LR. If we don't have a ret at the end of the
6914       // block, then we can't reason about liveness accurately.
6915       //
6916       // FIXME: We can probably do better than always disabling this in
6917       // noreturn functions by fixing up the liveness info.
6918       bool IsNoReturn =
6919           C.getMF()->getFunction().hasFnAttribute(Attribute::NoReturn);
6920 
6921       // Is LR available? If so, we don't need a save.
6922       if (C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI) && !IsNoReturn) {
6923         NumBytesNoStackCalls += 4;
6924         C.setCallInfo(MachineOutlinerNoLRSave, 4);
6925         CandidatesWithoutStackFixups.push_back(C);
6926       }
6927 
6928       // Is an unused register available? If so, we won't modify the stack, so
6929       // we can outline with the same frame type as those that don't save LR.
6930       else if (findRegisterToSaveLRTo(C)) {
6931         NumBytesNoStackCalls += 12;
6932         C.setCallInfo(MachineOutlinerRegSave, 12);
6933         CandidatesWithoutStackFixups.push_back(C);
6934       }
6935 
6936       // Is SP used in the sequence at all? If not, we don't have to modify
6937       // the stack, so we are guaranteed to get the same frame.
6938       else if (C.isAvailableInsideSeq(AArch64::SP, TRI)) {
6939         NumBytesNoStackCalls += 12;
6940         C.setCallInfo(MachineOutlinerDefault, 12);
6941         CandidatesWithoutStackFixups.push_back(C);
6942       }
6943 
6944       // If we outline this, we need to modify the stack. Pretend we don't
6945       // outline this by saving all of its bytes.
6946       else {
6947         NumBytesNoStackCalls += SequenceSize;
6948       }
6949     }
6950 
6951     // If there are no places where we have to save LR, then note that we
6952     // don't have to update the stack. Otherwise, give every candidate the
6953     // default call type, as long as it's safe to do so.
6954     if (!AllStackInstrsSafe ||
6955         NumBytesNoStackCalls <= RepeatedSequenceLocs.size() * 12) {
6956       RepeatedSequenceLocs = CandidatesWithoutStackFixups;
6957       FrameID = MachineOutlinerNoLRSave;
6958     } else {
6959       SetCandidateCallInfo(MachineOutlinerDefault, 12);
6960 
6961       // Bugzilla ID: 46767
6962       // TODO: Check if fixing up the stack more than once is safe so we can
6963       // outline these.
6964       //
6965       // An outline resulting in a caller that requires stack fixups at the
6966       // callsite to a callee that also requires stack fixups can happen when
6967       // there are no available registers at the candidate callsite for a
6968       // candidate that itself also has calls.
6969       //
6970       // In other words if function_containing_sequence in the following pseudo
6971       // assembly requires that we save LR at the point of the call, but there
6972       // are no available registers: in this case we save using SP and as a
6973       // result the SP offsets requires stack fixups by multiples of 16.
6974       //
6975       // function_containing_sequence:
6976       //   ...
6977       //   save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
6978       //   call OUTLINED_FUNCTION_N
6979       //   restore LR from SP
6980       //   ...
6981       //
6982       // OUTLINED_FUNCTION_N:
6983       //   save LR to SP <- Requires stack instr fixups in OUTLINED_FUNCTION_N
6984       //   ...
6985       //   bl foo
6986       //   restore LR from SP
6987       //   ret
6988       //
6989       // Because the code to handle more than one stack fixup does not
6990       // currently have the proper checks for legality, these cases will assert
6991       // in the AArch64 MachineOutliner. This is because the code to do this
6992       // needs more hardening, testing, better checks that generated code is
6993       // legal, etc and because it is only verified to handle a single pass of
6994       // stack fixup.
6995       //
6996       // The assert happens in AArch64InstrInfo::buildOutlinedFrame to catch
6997       // these cases until they are known to be handled. Bugzilla 46767 is
6998       // referenced in comments at the assert site.
6999       //
7000       // To avoid asserting (or generating non-legal code on noassert builds)
7001       // we remove all candidates which would need more than one stack fixup by
7002       // pruning the cases where the candidate has calls while also having no
7003       // available LR and having no available general purpose registers to copy
7004       // LR to (ie one extra stack save/restore).
7005       //
7006       if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
7007         erase_if(RepeatedSequenceLocs, [this, &TRI](outliner::Candidate &C) {
7008           return (std::any_of(
7009                      C.front(), std::next(C.back()),
7010                      [](const MachineInstr &MI) { return MI.isCall(); })) &&
7011                  (!C.isAvailableAcrossAndOutOfSeq(AArch64::LR, TRI) ||
7012                   !findRegisterToSaveLRTo(C));
7013         });
7014       }
7015     }
7016 
7017     // If we dropped all of the candidates, bail out here.
7018     if (RepeatedSequenceLocs.size() < 2) {
7019       RepeatedSequenceLocs.clear();
7020       return outliner::OutlinedFunction();
7021     }
7022   }
7023 
7024   // Does every candidate's MBB contain a call? If so, then we might have a call
7025   // in the range.
7026   if (FlagsSetInAll & MachineOutlinerMBBFlags::HasCalls) {
7027     // Check if the range contains a call. These require a save + restore of the
7028     // link register.
7029     bool ModStackToSaveLR = false;
7030     if (std::any_of(FirstCand.front(), FirstCand.back(),
7031                     [](const MachineInstr &MI) { return MI.isCall(); }))
7032       ModStackToSaveLR = true;
7033 
7034     // Handle the last instruction separately. If this is a tail call, then the
7035     // last instruction is a call. We don't want to save + restore in this case.
7036     // However, it could be possible that the last instruction is a call without
7037     // it being valid to tail call this sequence. We should consider this as
7038     // well.
7039     else if (FrameID != MachineOutlinerThunk &&
7040              FrameID != MachineOutlinerTailCall && FirstCand.back()->isCall())
7041       ModStackToSaveLR = true;
7042 
7043     if (ModStackToSaveLR) {
7044       // We can't fix up the stack. Bail out.
7045       if (!AllStackInstrsSafe) {
7046         RepeatedSequenceLocs.clear();
7047         return outliner::OutlinedFunction();
7048       }
7049 
7050       // Save + restore LR.
7051       NumBytesToCreateFrame += 8;
7052     }
7053   }
7054 
7055   // If we have CFI instructions, we can only outline if the outlined section
7056   // can be a tail call
7057   if (FrameID != MachineOutlinerTailCall && CFICount > 0)
7058     return outliner::OutlinedFunction();
7059 
7060   return outliner::OutlinedFunction(RepeatedSequenceLocs, SequenceSize,
7061                                     NumBytesToCreateFrame, FrameID);
7062 }
7063 
7064 bool AArch64InstrInfo::isFunctionSafeToOutlineFrom(
7065     MachineFunction &MF, bool OutlineFromLinkOnceODRs) const {
7066   const Function &F = MF.getFunction();
7067 
7068   // Can F be deduplicated by the linker? If it can, don't outline from it.
7069   if (!OutlineFromLinkOnceODRs && F.hasLinkOnceODRLinkage())
7070     return false;
7071 
7072   // Don't outline from functions with section markings; the program could
7073   // expect that all the code is in the named section.
7074   // FIXME: Allow outlining from multiple functions with the same section
7075   // marking.
7076   if (F.hasSection())
7077     return false;
7078 
7079   // Outlining from functions with redzones is unsafe since the outliner may
7080   // modify the stack. Check if hasRedZone is true or unknown; if yes, don't
7081   // outline from it.
7082   AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
7083   if (!AFI || AFI->hasRedZone().getValueOr(true))
7084     return false;
7085 
7086   // FIXME: Teach the outliner to generate/handle Windows unwind info.
7087   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI())
7088     return false;
7089 
7090   // It's safe to outline from MF.
7091   return true;
7092 }
7093 
7094 bool AArch64InstrInfo::isMBBSafeToOutlineFrom(MachineBasicBlock &MBB,
7095                                               unsigned &Flags) const {
7096   if (!TargetInstrInfo::isMBBSafeToOutlineFrom(MBB, Flags))
7097     return false;
7098   // Check if LR is available through all of the MBB. If it's not, then set
7099   // a flag.
7100   assert(MBB.getParent()->getRegInfo().tracksLiveness() &&
7101          "Suitable Machine Function for outlining must track liveness");
7102   LiveRegUnits LRU(getRegisterInfo());
7103 
7104   std::for_each(MBB.rbegin(), MBB.rend(),
7105                 [&LRU](MachineInstr &MI) { LRU.accumulate(MI); });
7106 
7107   // Check if each of the unsafe registers are available...
7108   bool W16AvailableInBlock = LRU.available(AArch64::W16);
7109   bool W17AvailableInBlock = LRU.available(AArch64::W17);
7110   bool NZCVAvailableInBlock = LRU.available(AArch64::NZCV);
7111 
7112   // If all of these are dead (and not live out), we know we don't have to check
7113   // them later.
7114   if (W16AvailableInBlock && W17AvailableInBlock && NZCVAvailableInBlock)
7115     Flags |= MachineOutlinerMBBFlags::UnsafeRegsDead;
7116 
7117   // Now, add the live outs to the set.
7118   LRU.addLiveOuts(MBB);
7119 
7120   // If any of these registers is available in the MBB, but also a live out of
7121   // the block, then we know outlining is unsafe.
7122   if (W16AvailableInBlock && !LRU.available(AArch64::W16))
7123     return false;
7124   if (W17AvailableInBlock && !LRU.available(AArch64::W17))
7125     return false;
7126   if (NZCVAvailableInBlock && !LRU.available(AArch64::NZCV))
7127     return false;
7128 
7129   // Check if there's a call inside this MachineBasicBlock. If there is, then
7130   // set a flag.
7131   if (any_of(MBB, [](MachineInstr &MI) { return MI.isCall(); }))
7132     Flags |= MachineOutlinerMBBFlags::HasCalls;
7133 
7134   MachineFunction *MF = MBB.getParent();
7135 
7136   // In the event that we outline, we may have to save LR. If there is an
7137   // available register in the MBB, then we'll always save LR there. Check if
7138   // this is true.
7139   bool CanSaveLR = false;
7140   const AArch64RegisterInfo *ARI = static_cast<const AArch64RegisterInfo *>(
7141       MF->getSubtarget().getRegisterInfo());
7142 
7143   // Check if there is an available register across the sequence that we can
7144   // use.
7145   for (unsigned Reg : AArch64::GPR64RegClass) {
7146     if (!ARI->isReservedReg(*MF, Reg) && Reg != AArch64::LR &&
7147         Reg != AArch64::X16 && Reg != AArch64::X17 && LRU.available(Reg)) {
7148       CanSaveLR = true;
7149       break;
7150     }
7151   }
7152 
7153   // Check if we have a register we can save LR to, and if LR was used
7154   // somewhere. If both of those things are true, then we need to evaluate the
7155   // safety of outlining stack instructions later.
7156   if (!CanSaveLR && !LRU.available(AArch64::LR))
7157     Flags |= MachineOutlinerMBBFlags::LRUnavailableSomewhere;
7158 
7159   return true;
7160 }
7161 
7162 outliner::InstrType
7163 AArch64InstrInfo::getOutliningType(MachineBasicBlock::iterator &MIT,
7164                                    unsigned Flags) const {
7165   MachineInstr &MI = *MIT;
7166   MachineBasicBlock *MBB = MI.getParent();
7167   MachineFunction *MF = MBB->getParent();
7168   AArch64FunctionInfo *FuncInfo = MF->getInfo<AArch64FunctionInfo>();
7169 
7170   // Don't outline anything used for return address signing. The outlined
7171   // function will get signed later if needed
7172   switch (MI.getOpcode()) {
7173   case AArch64::PACIASP:
7174   case AArch64::PACIBSP:
7175   case AArch64::AUTIASP:
7176   case AArch64::AUTIBSP:
7177   case AArch64::RETAA:
7178   case AArch64::RETAB:
7179   case AArch64::EMITBKEY:
7180     return outliner::InstrType::Illegal;
7181   }
7182 
7183   // Don't outline LOHs.
7184   if (FuncInfo->getLOHRelated().count(&MI))
7185     return outliner::InstrType::Illegal;
7186 
7187   // We can only outline these if we will tail call the outlined function, or
7188   // fix up the CFI offsets. Currently, CFI instructions are outlined only if
7189   // in a tail call.
7190   //
7191   // FIXME: If the proper fixups for the offset are implemented, this should be
7192   // possible.
7193   if (MI.isCFIInstruction())
7194     return outliner::InstrType::Legal;
7195 
7196   // Don't allow debug values to impact outlining type.
7197   if (MI.isDebugInstr() || MI.isIndirectDebugValue())
7198     return outliner::InstrType::Invisible;
7199 
7200   // At this point, KILL instructions don't really tell us much so we can go
7201   // ahead and skip over them.
7202   if (MI.isKill())
7203     return outliner::InstrType::Invisible;
7204 
7205   // Is this a terminator for a basic block?
7206   if (MI.isTerminator()) {
7207 
7208     // Is this the end of a function?
7209     if (MI.getParent()->succ_empty())
7210       return outliner::InstrType::Legal;
7211 
7212     // It's not, so don't outline it.
7213     return outliner::InstrType::Illegal;
7214   }
7215 
7216   // Make sure none of the operands are un-outlinable.
7217   for (const MachineOperand &MOP : MI.operands()) {
7218     if (MOP.isCPI() || MOP.isJTI() || MOP.isCFIIndex() || MOP.isFI() ||
7219         MOP.isTargetIndex())
7220       return outliner::InstrType::Illegal;
7221 
7222     // If it uses LR or W30 explicitly, then don't touch it.
7223     if (MOP.isReg() && !MOP.isImplicit() &&
7224         (MOP.getReg() == AArch64::LR || MOP.getReg() == AArch64::W30))
7225       return outliner::InstrType::Illegal;
7226   }
7227 
7228   // Special cases for instructions that can always be outlined, but will fail
7229   // the later tests. e.g, ADRPs, which are PC-relative use LR, but can always
7230   // be outlined because they don't require a *specific* value to be in LR.
7231   if (MI.getOpcode() == AArch64::ADRP)
7232     return outliner::InstrType::Legal;
7233 
7234   // If MI is a call we might be able to outline it. We don't want to outline
7235   // any calls that rely on the position of items on the stack. When we outline
7236   // something containing a call, we have to emit a save and restore of LR in
7237   // the outlined function. Currently, this always happens by saving LR to the
7238   // stack. Thus, if we outline, say, half the parameters for a function call
7239   // plus the call, then we'll break the callee's expectations for the layout
7240   // of the stack.
7241   //
7242   // FIXME: Allow calls to functions which construct a stack frame, as long
7243   // as they don't access arguments on the stack.
7244   // FIXME: Figure out some way to analyze functions defined in other modules.
7245   // We should be able to compute the memory usage based on the IR calling
7246   // convention, even if we can't see the definition.
7247   if (MI.isCall()) {
7248     // Get the function associated with the call. Look at each operand and find
7249     // the one that represents the callee and get its name.
7250     const Function *Callee = nullptr;
7251     for (const MachineOperand &MOP : MI.operands()) {
7252       if (MOP.isGlobal()) {
7253         Callee = dyn_cast<Function>(MOP.getGlobal());
7254         break;
7255       }
7256     }
7257 
7258     // Never outline calls to mcount.  There isn't any rule that would require
7259     // this, but the Linux kernel's "ftrace" feature depends on it.
7260     if (Callee && Callee->getName() == "\01_mcount")
7261       return outliner::InstrType::Illegal;
7262 
7263     // If we don't know anything about the callee, assume it depends on the
7264     // stack layout of the caller. In that case, it's only legal to outline
7265     // as a tail-call. Explicitly list the call instructions we know about so we
7266     // don't get unexpected results with call pseudo-instructions.
7267     auto UnknownCallOutlineType = outliner::InstrType::Illegal;
7268     if (MI.getOpcode() == AArch64::BLR ||
7269         MI.getOpcode() == AArch64::BLRNoIP || MI.getOpcode() == AArch64::BL)
7270       UnknownCallOutlineType = outliner::InstrType::LegalTerminator;
7271 
7272     if (!Callee)
7273       return UnknownCallOutlineType;
7274 
7275     // We have a function we have information about. Check it if it's something
7276     // can safely outline.
7277     MachineFunction *CalleeMF = MF->getMMI().getMachineFunction(*Callee);
7278 
7279     // We don't know what's going on with the callee at all. Don't touch it.
7280     if (!CalleeMF)
7281       return UnknownCallOutlineType;
7282 
7283     // Check if we know anything about the callee saves on the function. If we
7284     // don't, then don't touch it, since that implies that we haven't
7285     // computed anything about its stack frame yet.
7286     MachineFrameInfo &MFI = CalleeMF->getFrameInfo();
7287     if (!MFI.isCalleeSavedInfoValid() || MFI.getStackSize() > 0 ||
7288         MFI.getNumObjects() > 0)
7289       return UnknownCallOutlineType;
7290 
7291     // At this point, we can say that CalleeMF ought to not pass anything on the
7292     // stack. Therefore, we can outline it.
7293     return outliner::InstrType::Legal;
7294   }
7295 
7296   // Don't outline positions.
7297   if (MI.isPosition())
7298     return outliner::InstrType::Illegal;
7299 
7300   // Don't touch the link register or W30.
7301   if (MI.readsRegister(AArch64::W30, &getRegisterInfo()) ||
7302       MI.modifiesRegister(AArch64::W30, &getRegisterInfo()))
7303     return outliner::InstrType::Illegal;
7304 
7305   // Don't outline BTI instructions, because that will prevent the outlining
7306   // site from being indirectly callable.
7307   if (MI.getOpcode() == AArch64::HINT) {
7308     int64_t Imm = MI.getOperand(0).getImm();
7309     if (Imm == 32 || Imm == 34 || Imm == 36 || Imm == 38)
7310       return outliner::InstrType::Illegal;
7311   }
7312 
7313   return outliner::InstrType::Legal;
7314 }
7315 
7316 void AArch64InstrInfo::fixupPostOutline(MachineBasicBlock &MBB) const {
7317   for (MachineInstr &MI : MBB) {
7318     const MachineOperand *Base;
7319     unsigned Width;
7320     int64_t Offset;
7321     bool OffsetIsScalable;
7322 
7323     // Is this a load or store with an immediate offset with SP as the base?
7324     if (!MI.mayLoadOrStore() ||
7325         !getMemOperandWithOffsetWidth(MI, Base, Offset, OffsetIsScalable, Width,
7326                                       &RI) ||
7327         (Base->isReg() && Base->getReg() != AArch64::SP))
7328       continue;
7329 
7330     // It is, so we have to fix it up.
7331     TypeSize Scale(0U, false);
7332     int64_t Dummy1, Dummy2;
7333 
7334     MachineOperand &StackOffsetOperand = getMemOpBaseRegImmOfsOffsetOperand(MI);
7335     assert(StackOffsetOperand.isImm() && "Stack offset wasn't immediate!");
7336     getMemOpInfo(MI.getOpcode(), Scale, Width, Dummy1, Dummy2);
7337     assert(Scale != 0 && "Unexpected opcode!");
7338     assert(!OffsetIsScalable && "Expected offset to be a byte offset");
7339 
7340     // We've pushed the return address to the stack, so add 16 to the offset.
7341     // This is safe, since we already checked if it would overflow when we
7342     // checked if this instruction was legal to outline.
7343     int64_t NewImm = (Offset + 16) / (int64_t)Scale.getFixedSize();
7344     StackOffsetOperand.setImm(NewImm);
7345   }
7346 }
7347 
7348 static void signOutlinedFunction(MachineFunction &MF, MachineBasicBlock &MBB,
7349                                  bool ShouldSignReturnAddr,
7350                                  bool ShouldSignReturnAddrWithAKey) {
7351   if (ShouldSignReturnAddr) {
7352     MachineBasicBlock::iterator MBBPAC = MBB.begin();
7353     MachineBasicBlock::iterator MBBAUT = MBB.getFirstTerminator();
7354     const AArch64Subtarget &Subtarget = MF.getSubtarget<AArch64Subtarget>();
7355     const TargetInstrInfo *TII = Subtarget.getInstrInfo();
7356     DebugLoc DL;
7357 
7358     if (MBBAUT != MBB.end())
7359       DL = MBBAUT->getDebugLoc();
7360 
7361     // At the very beginning of the basic block we insert the following
7362     // depending on the key type
7363     //
7364     // a_key:                   b_key:
7365     //    PACIASP                   EMITBKEY
7366     //    CFI_INSTRUCTION           PACIBSP
7367     //                              CFI_INSTRUCTION
7368     unsigned PACI;
7369     if (ShouldSignReturnAddrWithAKey) {
7370       PACI = Subtarget.hasPAuth() ? AArch64::PACIA : AArch64::PACIASP;
7371     } else {
7372       BuildMI(MBB, MBBPAC, DebugLoc(), TII->get(AArch64::EMITBKEY))
7373           .setMIFlag(MachineInstr::FrameSetup);
7374       PACI = Subtarget.hasPAuth() ? AArch64::PACIB : AArch64::PACIBSP;
7375     }
7376 
7377     auto MI = BuildMI(MBB, MBBPAC, DebugLoc(), TII->get(PACI));
7378     if (Subtarget.hasPAuth())
7379       MI.addReg(AArch64::LR, RegState::Define)
7380           .addReg(AArch64::LR)
7381           .addReg(AArch64::SP, RegState::InternalRead);
7382     MI.setMIFlag(MachineInstr::FrameSetup);
7383 
7384     unsigned CFIIndex =
7385         MF.addFrameInst(MCCFIInstruction::createNegateRAState(nullptr));
7386     BuildMI(MBB, MBBPAC, DebugLoc(), TII->get(AArch64::CFI_INSTRUCTION))
7387         .addCFIIndex(CFIIndex)
7388         .setMIFlags(MachineInstr::FrameSetup);
7389 
7390     // If v8.3a features are available we can replace a RET instruction by
7391     // RETAA or RETAB and omit the AUT instructions
7392     if (Subtarget.hasPAuth() && MBBAUT != MBB.end() &&
7393         MBBAUT->getOpcode() == AArch64::RET) {
7394       BuildMI(MBB, MBBAUT, DL,
7395               TII->get(ShouldSignReturnAddrWithAKey ? AArch64::RETAA
7396                                                     : AArch64::RETAB))
7397           .copyImplicitOps(*MBBAUT);
7398       MBB.erase(MBBAUT);
7399     } else {
7400       BuildMI(MBB, MBBAUT, DL,
7401               TII->get(ShouldSignReturnAddrWithAKey ? AArch64::AUTIASP
7402                                                     : AArch64::AUTIBSP))
7403           .setMIFlag(MachineInstr::FrameDestroy);
7404     }
7405   }
7406 }
7407 
7408 void AArch64InstrInfo::buildOutlinedFrame(
7409     MachineBasicBlock &MBB, MachineFunction &MF,
7410     const outliner::OutlinedFunction &OF) const {
7411 
7412   AArch64FunctionInfo *FI = MF.getInfo<AArch64FunctionInfo>();
7413 
7414   if (OF.FrameConstructionID == MachineOutlinerTailCall)
7415     FI->setOutliningStyle("Tail Call");
7416   else if (OF.FrameConstructionID == MachineOutlinerThunk) {
7417     // For thunk outlining, rewrite the last instruction from a call to a
7418     // tail-call.
7419     MachineInstr *Call = &*--MBB.instr_end();
7420     unsigned TailOpcode;
7421     if (Call->getOpcode() == AArch64::BL) {
7422       TailOpcode = AArch64::TCRETURNdi;
7423     } else {
7424       assert(Call->getOpcode() == AArch64::BLR ||
7425              Call->getOpcode() == AArch64::BLRNoIP);
7426       TailOpcode = AArch64::TCRETURNriALL;
7427     }
7428     MachineInstr *TC = BuildMI(MF, DebugLoc(), get(TailOpcode))
7429                            .add(Call->getOperand(0))
7430                            .addImm(0);
7431     MBB.insert(MBB.end(), TC);
7432     Call->eraseFromParent();
7433 
7434     FI->setOutliningStyle("Thunk");
7435   }
7436 
7437   bool IsLeafFunction = true;
7438 
7439   // Is there a call in the outlined range?
7440   auto IsNonTailCall = [](const MachineInstr &MI) {
7441     return MI.isCall() && !MI.isReturn();
7442   };
7443 
7444   if (llvm::any_of(MBB.instrs(), IsNonTailCall)) {
7445     // Fix up the instructions in the range, since we're going to modify the
7446     // stack.
7447 
7448     // Bugzilla ID: 46767
7449     // TODO: Check if fixing up twice is safe so we can outline these.
7450     assert(OF.FrameConstructionID != MachineOutlinerDefault &&
7451            "Can only fix up stack references once");
7452     fixupPostOutline(MBB);
7453 
7454     IsLeafFunction = false;
7455 
7456     // LR has to be a live in so that we can save it.
7457     if (!MBB.isLiveIn(AArch64::LR))
7458       MBB.addLiveIn(AArch64::LR);
7459 
7460     MachineBasicBlock::iterator It = MBB.begin();
7461     MachineBasicBlock::iterator Et = MBB.end();
7462 
7463     if (OF.FrameConstructionID == MachineOutlinerTailCall ||
7464         OF.FrameConstructionID == MachineOutlinerThunk)
7465       Et = std::prev(MBB.end());
7466 
7467     // Insert a save before the outlined region
7468     MachineInstr *STRXpre = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
7469                                 .addReg(AArch64::SP, RegState::Define)
7470                                 .addReg(AArch64::LR)
7471                                 .addReg(AArch64::SP)
7472                                 .addImm(-16);
7473     It = MBB.insert(It, STRXpre);
7474 
7475     const TargetSubtargetInfo &STI = MF.getSubtarget();
7476     const MCRegisterInfo *MRI = STI.getRegisterInfo();
7477     unsigned DwarfReg = MRI->getDwarfRegNum(AArch64::LR, true);
7478 
7479     // Add a CFI saying the stack was moved 16 B down.
7480     int64_t StackPosEntry =
7481         MF.addFrameInst(MCCFIInstruction::cfiDefCfaOffset(nullptr, 16));
7482     BuildMI(MBB, It, DebugLoc(), get(AArch64::CFI_INSTRUCTION))
7483         .addCFIIndex(StackPosEntry)
7484         .setMIFlags(MachineInstr::FrameSetup);
7485 
7486     // Add a CFI saying that the LR that we want to find is now 16 B higher than
7487     // before.
7488     int64_t LRPosEntry =
7489         MF.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg, -16));
7490     BuildMI(MBB, It, DebugLoc(), get(AArch64::CFI_INSTRUCTION))
7491         .addCFIIndex(LRPosEntry)
7492         .setMIFlags(MachineInstr::FrameSetup);
7493 
7494     // Insert a restore before the terminator for the function.
7495     MachineInstr *LDRXpost = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
7496                                  .addReg(AArch64::SP, RegState::Define)
7497                                  .addReg(AArch64::LR, RegState::Define)
7498                                  .addReg(AArch64::SP)
7499                                  .addImm(16);
7500     Et = MBB.insert(Et, LDRXpost);
7501   }
7502 
7503   // If a bunch of candidates reach this point they must agree on their return
7504   // address signing. It is therefore enough to just consider the signing
7505   // behaviour of one of them
7506   const auto &MFI = *OF.Candidates.front().getMF()->getInfo<AArch64FunctionInfo>();
7507   bool ShouldSignReturnAddr = MFI.shouldSignReturnAddress(!IsLeafFunction);
7508 
7509   // a_key is the default
7510   bool ShouldSignReturnAddrWithAKey = !MFI.shouldSignWithBKey();
7511 
7512   // If this is a tail call outlined function, then there's already a return.
7513   if (OF.FrameConstructionID == MachineOutlinerTailCall ||
7514       OF.FrameConstructionID == MachineOutlinerThunk) {
7515     signOutlinedFunction(MF, MBB, ShouldSignReturnAddr,
7516                          ShouldSignReturnAddrWithAKey);
7517     return;
7518   }
7519 
7520   // It's not a tail call, so we have to insert the return ourselves.
7521 
7522   // LR has to be a live in so that we can return to it.
7523   if (!MBB.isLiveIn(AArch64::LR))
7524     MBB.addLiveIn(AArch64::LR);
7525 
7526   MachineInstr *ret = BuildMI(MF, DebugLoc(), get(AArch64::RET))
7527                           .addReg(AArch64::LR);
7528   MBB.insert(MBB.end(), ret);
7529 
7530   signOutlinedFunction(MF, MBB, ShouldSignReturnAddr,
7531                        ShouldSignReturnAddrWithAKey);
7532 
7533   FI->setOutliningStyle("Function");
7534 
7535   // Did we have to modify the stack by saving the link register?
7536   if (OF.FrameConstructionID != MachineOutlinerDefault)
7537     return;
7538 
7539   // We modified the stack.
7540   // Walk over the basic block and fix up all the stack accesses.
7541   fixupPostOutline(MBB);
7542 }
7543 
7544 MachineBasicBlock::iterator AArch64InstrInfo::insertOutlinedCall(
7545     Module &M, MachineBasicBlock &MBB, MachineBasicBlock::iterator &It,
7546     MachineFunction &MF, outliner::Candidate &C) const {
7547 
7548   // Are we tail calling?
7549   if (C.CallConstructionID == MachineOutlinerTailCall) {
7550     // If yes, then we can just branch to the label.
7551     It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::TCRETURNdi))
7552                             .addGlobalAddress(M.getNamedValue(MF.getName()))
7553                             .addImm(0));
7554     return It;
7555   }
7556 
7557   // Are we saving the link register?
7558   if (C.CallConstructionID == MachineOutlinerNoLRSave ||
7559       C.CallConstructionID == MachineOutlinerThunk) {
7560     // No, so just insert the call.
7561     It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
7562                             .addGlobalAddress(M.getNamedValue(MF.getName())));
7563     return It;
7564   }
7565 
7566   // We want to return the spot where we inserted the call.
7567   MachineBasicBlock::iterator CallPt;
7568 
7569   // Instructions for saving and restoring LR around the call instruction we're
7570   // going to insert.
7571   MachineInstr *Save;
7572   MachineInstr *Restore;
7573   // Can we save to a register?
7574   if (C.CallConstructionID == MachineOutlinerRegSave) {
7575     // FIXME: This logic should be sunk into a target-specific interface so that
7576     // we don't have to recompute the register.
7577     Register Reg = findRegisterToSaveLRTo(C);
7578     assert(Reg && "No callee-saved register available?");
7579 
7580     // LR has to be a live in so that we can save it.
7581     if (!MBB.isLiveIn(AArch64::LR))
7582       MBB.addLiveIn(AArch64::LR);
7583 
7584     // Save and restore LR from Reg.
7585     Save = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), Reg)
7586                .addReg(AArch64::XZR)
7587                .addReg(AArch64::LR)
7588                .addImm(0);
7589     Restore = BuildMI(MF, DebugLoc(), get(AArch64::ORRXrs), AArch64::LR)
7590                 .addReg(AArch64::XZR)
7591                 .addReg(Reg)
7592                 .addImm(0);
7593   } else {
7594     // We have the default case. Save and restore from SP.
7595     Save = BuildMI(MF, DebugLoc(), get(AArch64::STRXpre))
7596                .addReg(AArch64::SP, RegState::Define)
7597                .addReg(AArch64::LR)
7598                .addReg(AArch64::SP)
7599                .addImm(-16);
7600     Restore = BuildMI(MF, DebugLoc(), get(AArch64::LDRXpost))
7601                   .addReg(AArch64::SP, RegState::Define)
7602                   .addReg(AArch64::LR, RegState::Define)
7603                   .addReg(AArch64::SP)
7604                   .addImm(16);
7605   }
7606 
7607   It = MBB.insert(It, Save);
7608   It++;
7609 
7610   // Insert the call.
7611   It = MBB.insert(It, BuildMI(MF, DebugLoc(), get(AArch64::BL))
7612                           .addGlobalAddress(M.getNamedValue(MF.getName())));
7613   CallPt = It;
7614   It++;
7615 
7616   It = MBB.insert(It, Restore);
7617   return CallPt;
7618 }
7619 
7620 bool AArch64InstrInfo::shouldOutlineFromFunctionByDefault(
7621   MachineFunction &MF) const {
7622   return MF.getFunction().hasMinSize();
7623 }
7624 
7625 Optional<DestSourcePair>
7626 AArch64InstrInfo::isCopyInstrImpl(const MachineInstr &MI) const {
7627 
7628   // AArch64::ORRWrs and AArch64::ORRXrs with WZR/XZR reg
7629   // and zero immediate operands used as an alias for mov instruction.
7630   if (MI.getOpcode() == AArch64::ORRWrs &&
7631       MI.getOperand(1).getReg() == AArch64::WZR &&
7632       MI.getOperand(3).getImm() == 0x0) {
7633     return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
7634   }
7635 
7636   if (MI.getOpcode() == AArch64::ORRXrs &&
7637       MI.getOperand(1).getReg() == AArch64::XZR &&
7638       MI.getOperand(3).getImm() == 0x0) {
7639     return DestSourcePair{MI.getOperand(0), MI.getOperand(2)};
7640   }
7641 
7642   return None;
7643 }
7644 
7645 Optional<RegImmPair> AArch64InstrInfo::isAddImmediate(const MachineInstr &MI,
7646                                                       Register Reg) const {
7647   int Sign = 1;
7648   int64_t Offset = 0;
7649 
7650   // TODO: Handle cases where Reg is a super- or sub-register of the
7651   // destination register.
7652   const MachineOperand &Op0 = MI.getOperand(0);
7653   if (!Op0.isReg() || Reg != Op0.getReg())
7654     return None;
7655 
7656   switch (MI.getOpcode()) {
7657   default:
7658     return None;
7659   case AArch64::SUBWri:
7660   case AArch64::SUBXri:
7661   case AArch64::SUBSWri:
7662   case AArch64::SUBSXri:
7663     Sign *= -1;
7664     LLVM_FALLTHROUGH;
7665   case AArch64::ADDSWri:
7666   case AArch64::ADDSXri:
7667   case AArch64::ADDWri:
7668   case AArch64::ADDXri: {
7669     // TODO: Third operand can be global address (usually some string).
7670     if (!MI.getOperand(0).isReg() || !MI.getOperand(1).isReg() ||
7671         !MI.getOperand(2).isImm())
7672       return None;
7673     int Shift = MI.getOperand(3).getImm();
7674     assert((Shift == 0 || Shift == 12) && "Shift can be either 0 or 12");
7675     Offset = Sign * (MI.getOperand(2).getImm() << Shift);
7676   }
7677   }
7678   return RegImmPair{MI.getOperand(1).getReg(), Offset};
7679 }
7680 
7681 /// If the given ORR instruction is a copy, and \p DescribedReg overlaps with
7682 /// the destination register then, if possible, describe the value in terms of
7683 /// the source register.
7684 static Optional<ParamLoadedValue>
7685 describeORRLoadedValue(const MachineInstr &MI, Register DescribedReg,
7686                        const TargetInstrInfo *TII,
7687                        const TargetRegisterInfo *TRI) {
7688   auto DestSrc = TII->isCopyInstr(MI);
7689   if (!DestSrc)
7690     return None;
7691 
7692   Register DestReg = DestSrc->Destination->getReg();
7693   Register SrcReg = DestSrc->Source->getReg();
7694 
7695   auto Expr = DIExpression::get(MI.getMF()->getFunction().getContext(), {});
7696 
7697   // If the described register is the destination, just return the source.
7698   if (DestReg == DescribedReg)
7699     return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
7700 
7701   // ORRWrs zero-extends to 64-bits, so we need to consider such cases.
7702   if (MI.getOpcode() == AArch64::ORRWrs &&
7703       TRI->isSuperRegister(DestReg, DescribedReg))
7704     return ParamLoadedValue(MachineOperand::CreateReg(SrcReg, false), Expr);
7705 
7706   // We may need to describe the lower part of a ORRXrs move.
7707   if (MI.getOpcode() == AArch64::ORRXrs &&
7708       TRI->isSubRegister(DestReg, DescribedReg)) {
7709     Register SrcSubReg = TRI->getSubReg(SrcReg, AArch64::sub_32);
7710     return ParamLoadedValue(MachineOperand::CreateReg(SrcSubReg, false), Expr);
7711   }
7712 
7713   assert(!TRI->isSuperOrSubRegisterEq(DestReg, DescribedReg) &&
7714          "Unhandled ORR[XW]rs copy case");
7715 
7716   return None;
7717 }
7718 
7719 Optional<ParamLoadedValue>
7720 AArch64InstrInfo::describeLoadedValue(const MachineInstr &MI,
7721                                       Register Reg) const {
7722   const MachineFunction *MF = MI.getMF();
7723   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
7724   switch (MI.getOpcode()) {
7725   case AArch64::MOVZWi:
7726   case AArch64::MOVZXi: {
7727     // MOVZWi may be used for producing zero-extended 32-bit immediates in
7728     // 64-bit parameters, so we need to consider super-registers.
7729     if (!TRI->isSuperRegisterEq(MI.getOperand(0).getReg(), Reg))
7730       return None;
7731 
7732     if (!MI.getOperand(1).isImm())
7733       return None;
7734     int64_t Immediate = MI.getOperand(1).getImm();
7735     int Shift = MI.getOperand(2).getImm();
7736     return ParamLoadedValue(MachineOperand::CreateImm(Immediate << Shift),
7737                             nullptr);
7738   }
7739   case AArch64::ORRWrs:
7740   case AArch64::ORRXrs:
7741     return describeORRLoadedValue(MI, Reg, this, TRI);
7742   }
7743 
7744   return TargetInstrInfo::describeLoadedValue(MI, Reg);
7745 }
7746 
7747 bool AArch64InstrInfo::isExtendLikelyToBeFolded(
7748     MachineInstr &ExtMI, MachineRegisterInfo &MRI) const {
7749   assert(ExtMI.getOpcode() == TargetOpcode::G_SEXT ||
7750          ExtMI.getOpcode() == TargetOpcode::G_ZEXT ||
7751          ExtMI.getOpcode() == TargetOpcode::G_ANYEXT);
7752 
7753   // Anyexts are nops.
7754   if (ExtMI.getOpcode() == TargetOpcode::G_ANYEXT)
7755     return true;
7756 
7757   Register DefReg = ExtMI.getOperand(0).getReg();
7758   if (!MRI.hasOneNonDBGUse(DefReg))
7759     return false;
7760 
7761   // It's likely that a sext/zext as a G_PTR_ADD offset will be folded into an
7762   // addressing mode.
7763   auto *UserMI = &*MRI.use_instr_nodbg_begin(DefReg);
7764   return UserMI->getOpcode() == TargetOpcode::G_PTR_ADD;
7765 }
7766 
7767 uint64_t AArch64InstrInfo::getElementSizeForOpcode(unsigned Opc) const {
7768   return get(Opc).TSFlags & AArch64::ElementSizeMask;
7769 }
7770 
7771 bool AArch64InstrInfo::isPTestLikeOpcode(unsigned Opc) const {
7772   return get(Opc).TSFlags & AArch64::InstrFlagIsPTestLike;
7773 }
7774 
7775 bool AArch64InstrInfo::isWhileOpcode(unsigned Opc) const {
7776   return get(Opc).TSFlags & AArch64::InstrFlagIsWhile;
7777 }
7778 
7779 unsigned int
7780 AArch64InstrInfo::getTailDuplicateSize(CodeGenOpt::Level OptLevel) const {
7781   return OptLevel >= CodeGenOpt::Aggressive ? 6 : 2;
7782 }
7783 
7784 unsigned llvm::getBLRCallOpcode(const MachineFunction &MF) {
7785   if (MF.getSubtarget<AArch64Subtarget>().hardenSlsBlr())
7786     return AArch64::BLRNoIP;
7787   else
7788     return AArch64::BLR;
7789 }
7790 
7791 #define GET_INSTRINFO_HELPERS
7792 #define GET_INSTRMAP_INFO
7793 #include "AArch64GenInstrInfo.inc"
7794