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