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