1 //===-- AArch64ISelDAGToDAG.cpp - A dag to dag inst selector for AArch64 --===//
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 defines an instruction selector for the AArch64 target.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "AArch64TargetMachine.h"
14 #include "MCTargetDesc/AArch64AddressingModes.h"
15 #include "llvm/ADT/APSInt.h"
16 #include "llvm/CodeGen/SelectionDAGISel.h"
17 #include "llvm/IR/Function.h" // To access function attributes.
18 #include "llvm/IR/GlobalValue.h"
19 #include "llvm/IR/Intrinsics.h"
20 #include "llvm/IR/IntrinsicsAArch64.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/KnownBits.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Support/raw_ostream.h"
26 
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "aarch64-isel"
30 
31 //===--------------------------------------------------------------------===//
32 /// AArch64DAGToDAGISel - AArch64 specific code to select AArch64 machine
33 /// instructions for SelectionDAG operations.
34 ///
35 namespace {
36 
37 class AArch64DAGToDAGISel : public SelectionDAGISel {
38 
39   /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
40   /// make the right decision when generating code for different targets.
41   const AArch64Subtarget *Subtarget;
42 
43 public:
44   explicit AArch64DAGToDAGISel(AArch64TargetMachine &tm,
45                                CodeGenOpt::Level OptLevel)
46       : SelectionDAGISel(tm, OptLevel), Subtarget(nullptr) {}
47 
48   StringRef getPassName() const override {
49     return "AArch64 Instruction Selection";
50   }
51 
52   bool runOnMachineFunction(MachineFunction &MF) override {
53     Subtarget = &MF.getSubtarget<AArch64Subtarget>();
54     return SelectionDAGISel::runOnMachineFunction(MF);
55   }
56 
57   void Select(SDNode *Node) override;
58 
59   /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
60   /// inline asm expressions.
61   bool SelectInlineAsmMemoryOperand(const SDValue &Op,
62                                     unsigned ConstraintID,
63                                     std::vector<SDValue> &OutOps) override;
64 
65   template <signed Low, signed High, signed Scale>
66   bool SelectRDVLImm(SDValue N, SDValue &Imm);
67 
68   bool tryMLAV64LaneV128(SDNode *N);
69   bool tryMULLV64LaneV128(unsigned IntNo, SDNode *N);
70   bool SelectArithExtendedRegister(SDValue N, SDValue &Reg, SDValue &Shift);
71   bool SelectArithImmed(SDValue N, SDValue &Val, SDValue &Shift);
72   bool SelectNegArithImmed(SDValue N, SDValue &Val, SDValue &Shift);
73   bool SelectArithShiftedRegister(SDValue N, SDValue &Reg, SDValue &Shift) {
74     return SelectShiftedRegister(N, false, Reg, Shift);
75   }
76   bool SelectLogicalShiftedRegister(SDValue N, SDValue &Reg, SDValue &Shift) {
77     return SelectShiftedRegister(N, true, Reg, Shift);
78   }
79   bool SelectAddrModeIndexed7S8(SDValue N, SDValue &Base, SDValue &OffImm) {
80     return SelectAddrModeIndexed7S(N, 1, Base, OffImm);
81   }
82   bool SelectAddrModeIndexed7S16(SDValue N, SDValue &Base, SDValue &OffImm) {
83     return SelectAddrModeIndexed7S(N, 2, Base, OffImm);
84   }
85   bool SelectAddrModeIndexed7S32(SDValue N, SDValue &Base, SDValue &OffImm) {
86     return SelectAddrModeIndexed7S(N, 4, Base, OffImm);
87   }
88   bool SelectAddrModeIndexed7S64(SDValue N, SDValue &Base, SDValue &OffImm) {
89     return SelectAddrModeIndexed7S(N, 8, Base, OffImm);
90   }
91   bool SelectAddrModeIndexed7S128(SDValue N, SDValue &Base, SDValue &OffImm) {
92     return SelectAddrModeIndexed7S(N, 16, Base, OffImm);
93   }
94   bool SelectAddrModeIndexedS9S128(SDValue N, SDValue &Base, SDValue &OffImm) {
95     return SelectAddrModeIndexedBitWidth(N, true, 9, 16, Base, OffImm);
96   }
97   bool SelectAddrModeIndexedU6S128(SDValue N, SDValue &Base, SDValue &OffImm) {
98     return SelectAddrModeIndexedBitWidth(N, false, 6, 16, Base, OffImm);
99   }
100   bool SelectAddrModeIndexed8(SDValue N, SDValue &Base, SDValue &OffImm) {
101     return SelectAddrModeIndexed(N, 1, Base, OffImm);
102   }
103   bool SelectAddrModeIndexed16(SDValue N, SDValue &Base, SDValue &OffImm) {
104     return SelectAddrModeIndexed(N, 2, Base, OffImm);
105   }
106   bool SelectAddrModeIndexed32(SDValue N, SDValue &Base, SDValue &OffImm) {
107     return SelectAddrModeIndexed(N, 4, Base, OffImm);
108   }
109   bool SelectAddrModeIndexed64(SDValue N, SDValue &Base, SDValue &OffImm) {
110     return SelectAddrModeIndexed(N, 8, Base, OffImm);
111   }
112   bool SelectAddrModeIndexed128(SDValue N, SDValue &Base, SDValue &OffImm) {
113     return SelectAddrModeIndexed(N, 16, Base, OffImm);
114   }
115   bool SelectAddrModeUnscaled8(SDValue N, SDValue &Base, SDValue &OffImm) {
116     return SelectAddrModeUnscaled(N, 1, Base, OffImm);
117   }
118   bool SelectAddrModeUnscaled16(SDValue N, SDValue &Base, SDValue &OffImm) {
119     return SelectAddrModeUnscaled(N, 2, Base, OffImm);
120   }
121   bool SelectAddrModeUnscaled32(SDValue N, SDValue &Base, SDValue &OffImm) {
122     return SelectAddrModeUnscaled(N, 4, Base, OffImm);
123   }
124   bool SelectAddrModeUnscaled64(SDValue N, SDValue &Base, SDValue &OffImm) {
125     return SelectAddrModeUnscaled(N, 8, Base, OffImm);
126   }
127   bool SelectAddrModeUnscaled128(SDValue N, SDValue &Base, SDValue &OffImm) {
128     return SelectAddrModeUnscaled(N, 16, Base, OffImm);
129   }
130 
131   template<int Width>
132   bool SelectAddrModeWRO(SDValue N, SDValue &Base, SDValue &Offset,
133                          SDValue &SignExtend, SDValue &DoShift) {
134     return SelectAddrModeWRO(N, Width / 8, Base, Offset, SignExtend, DoShift);
135   }
136 
137   template<int Width>
138   bool SelectAddrModeXRO(SDValue N, SDValue &Base, SDValue &Offset,
139                          SDValue &SignExtend, SDValue &DoShift) {
140     return SelectAddrModeXRO(N, Width / 8, Base, Offset, SignExtend, DoShift);
141   }
142 
143   bool SelectDupZeroOrUndef(SDValue N) {
144     switch(N->getOpcode()) {
145     case ISD::UNDEF:
146       return true;
147     case AArch64ISD::DUP:
148     case ISD::SPLAT_VECTOR: {
149       auto Opnd0 = N->getOperand(0);
150       if (auto CN = dyn_cast<ConstantSDNode>(Opnd0))
151         if (CN->isNullValue())
152           return true;
153       if (auto CN = dyn_cast<ConstantFPSDNode>(Opnd0))
154         if (CN->isZero())
155           return true;
156       break;
157     }
158     default:
159       break;
160     }
161 
162     return false;
163   }
164 
165   bool SelectDupZero(SDValue N) {
166     switch(N->getOpcode()) {
167     case AArch64ISD::DUP:
168     case ISD::SPLAT_VECTOR: {
169       auto Opnd0 = N->getOperand(0);
170       if (auto CN = dyn_cast<ConstantSDNode>(Opnd0))
171         if (CN->isNullValue())
172           return true;
173       if (auto CN = dyn_cast<ConstantFPSDNode>(Opnd0))
174         if (CN->isZero())
175           return true;
176       break;
177     }
178     }
179 
180     return false;
181   }
182 
183   template<MVT::SimpleValueType VT>
184   bool SelectSVEAddSubImm(SDValue N, SDValue &Imm, SDValue &Shift) {
185     return SelectSVEAddSubImm(N, VT, Imm, Shift);
186   }
187 
188   template<MVT::SimpleValueType VT>
189   bool SelectSVELogicalImm(SDValue N, SDValue &Imm) {
190     return SelectSVELogicalImm(N, VT, Imm);
191   }
192 
193   template <unsigned Low, unsigned High>
194   bool SelectSVEShiftImm64(SDValue N, SDValue &Imm) {
195     return SelectSVEShiftImm64(N, Low, High, Imm);
196   }
197 
198   // Returns a suitable CNT/INC/DEC/RDVL multiplier to calculate VSCALE*N.
199   template<signed Min, signed Max, signed Scale, bool Shift>
200   bool SelectCntImm(SDValue N, SDValue &Imm) {
201     if (!isa<ConstantSDNode>(N))
202       return false;
203 
204     int64_t MulImm = cast<ConstantSDNode>(N)->getSExtValue();
205     if (Shift)
206       MulImm = 1LL << MulImm;
207 
208     if ((MulImm % std::abs(Scale)) != 0)
209       return false;
210 
211     MulImm /= Scale;
212     if ((MulImm >= Min) && (MulImm <= Max)) {
213       Imm = CurDAG->getTargetConstant(MulImm, SDLoc(N), MVT::i32);
214       return true;
215     }
216 
217     return false;
218   }
219 
220   /// Form sequences of consecutive 64/128-bit registers for use in NEON
221   /// instructions making use of a vector-list (e.g. ldN, tbl). Vecs must have
222   /// between 1 and 4 elements. If it contains a single element that is returned
223   /// unchanged; otherwise a REG_SEQUENCE value is returned.
224   SDValue createDTuple(ArrayRef<SDValue> Vecs);
225   SDValue createQTuple(ArrayRef<SDValue> Vecs);
226   // Form a sequence of SVE registers for instructions using list of vectors,
227   // e.g. structured loads and stores (ldN, stN).
228   SDValue createZTuple(ArrayRef<SDValue> Vecs);
229 
230   /// Generic helper for the createDTuple/createQTuple
231   /// functions. Those should almost always be called instead.
232   SDValue createTuple(ArrayRef<SDValue> Vecs, const unsigned RegClassIDs[],
233                       const unsigned SubRegs[]);
234 
235   void SelectTable(SDNode *N, unsigned NumVecs, unsigned Opc, bool isExt);
236 
237   bool tryIndexedLoad(SDNode *N);
238 
239   bool trySelectStackSlotTagP(SDNode *N);
240   void SelectTagP(SDNode *N);
241 
242   void SelectLoad(SDNode *N, unsigned NumVecs, unsigned Opc,
243                      unsigned SubRegIdx);
244   void SelectPostLoad(SDNode *N, unsigned NumVecs, unsigned Opc,
245                          unsigned SubRegIdx);
246   void SelectLoadLane(SDNode *N, unsigned NumVecs, unsigned Opc);
247   void SelectPostLoadLane(SDNode *N, unsigned NumVecs, unsigned Opc);
248 
249   bool SelectAddrModeFrameIndexSVE(SDValue N, SDValue &Base, SDValue &OffImm);
250   /// SVE Reg+Imm addressing mode.
251   template <int64_t Min, int64_t Max>
252   bool SelectAddrModeIndexedSVE(SDNode *Root, SDValue N, SDValue &Base,
253                                 SDValue &OffImm);
254   /// SVE Reg+Reg address mode.
255   template <unsigned Scale>
256   bool SelectSVERegRegAddrMode(SDValue N, SDValue &Base, SDValue &Offset) {
257     return SelectSVERegRegAddrMode(N, Scale, Base, Offset);
258   }
259 
260   void SelectStore(SDNode *N, unsigned NumVecs, unsigned Opc);
261   void SelectPostStore(SDNode *N, unsigned NumVecs, unsigned Opc);
262   void SelectStoreLane(SDNode *N, unsigned NumVecs, unsigned Opc);
263   void SelectPostStoreLane(SDNode *N, unsigned NumVecs, unsigned Opc);
264   template <unsigned Scale>
265   void SelectPredicatedStore(SDNode *N, unsigned NumVecs, const unsigned Opc_rr,
266                              const unsigned Opc_ri);
267   template <unsigned Scale>
268   std::tuple<unsigned, SDValue, SDValue>
269   findAddrModeSVELoadStore(SDNode *N, const unsigned Opc_rr,
270                            const unsigned Opc_ri, const SDValue &OldBase,
271                            const SDValue &OldOffset);
272 
273   bool tryBitfieldExtractOp(SDNode *N);
274   bool tryBitfieldExtractOpFromSExt(SDNode *N);
275   bool tryBitfieldInsertOp(SDNode *N);
276   bool tryBitfieldInsertInZeroOp(SDNode *N);
277   bool tryShiftAmountMod(SDNode *N);
278   bool tryHighFPExt(SDNode *N);
279 
280   bool tryReadRegister(SDNode *N);
281   bool tryWriteRegister(SDNode *N);
282 
283 // Include the pieces autogenerated from the target description.
284 #include "AArch64GenDAGISel.inc"
285 
286 private:
287   bool SelectShiftedRegister(SDValue N, bool AllowROR, SDValue &Reg,
288                              SDValue &Shift);
289   bool SelectAddrModeIndexed7S(SDValue N, unsigned Size, SDValue &Base,
290                                SDValue &OffImm) {
291     return SelectAddrModeIndexedBitWidth(N, true, 7, Size, Base, OffImm);
292   }
293   bool SelectAddrModeIndexedBitWidth(SDValue N, bool IsSignedImm, unsigned BW,
294                                      unsigned Size, SDValue &Base,
295                                      SDValue &OffImm);
296   bool SelectAddrModeIndexed(SDValue N, unsigned Size, SDValue &Base,
297                              SDValue &OffImm);
298   bool SelectAddrModeUnscaled(SDValue N, unsigned Size, SDValue &Base,
299                               SDValue &OffImm);
300   bool SelectAddrModeWRO(SDValue N, unsigned Size, SDValue &Base,
301                          SDValue &Offset, SDValue &SignExtend,
302                          SDValue &DoShift);
303   bool SelectAddrModeXRO(SDValue N, unsigned Size, SDValue &Base,
304                          SDValue &Offset, SDValue &SignExtend,
305                          SDValue &DoShift);
306   bool isWorthFolding(SDValue V) const;
307   bool SelectExtendedSHL(SDValue N, unsigned Size, bool WantExtend,
308                          SDValue &Offset, SDValue &SignExtend);
309 
310   template<unsigned RegWidth>
311   bool SelectCVTFixedPosOperand(SDValue N, SDValue &FixedPos) {
312     return SelectCVTFixedPosOperand(N, FixedPos, RegWidth);
313   }
314 
315   bool SelectCVTFixedPosOperand(SDValue N, SDValue &FixedPos, unsigned Width);
316 
317   bool SelectCMP_SWAP(SDNode *N);
318 
319   bool SelectSVE8BitLslImm(SDValue N, SDValue &Imm, SDValue &Shift);
320 
321   bool SelectSVEAddSubImm(SDValue N, MVT VT, SDValue &Imm, SDValue &Shift);
322 
323   bool SelectSVELogicalImm(SDValue N, MVT VT, SDValue &Imm);
324 
325   bool SelectSVESignedArithImm(SDValue N, SDValue &Imm);
326   bool SelectSVEShiftImm64(SDValue N, uint64_t Low, uint64_t High,
327                            SDValue &Imm);
328 
329   bool SelectSVEArithImm(SDValue N, SDValue &Imm);
330   bool SelectSVERegRegAddrMode(SDValue N, unsigned Scale, SDValue &Base,
331                                SDValue &Offset);
332 };
333 } // end anonymous namespace
334 
335 /// isIntImmediate - This method tests to see if the node is a constant
336 /// operand. If so Imm will receive the 32-bit value.
337 static bool isIntImmediate(const SDNode *N, uint64_t &Imm) {
338   if (const ConstantSDNode *C = dyn_cast<const ConstantSDNode>(N)) {
339     Imm = C->getZExtValue();
340     return true;
341   }
342   return false;
343 }
344 
345 // isIntImmediate - This method tests to see if a constant operand.
346 // If so Imm will receive the value.
347 static bool isIntImmediate(SDValue N, uint64_t &Imm) {
348   return isIntImmediate(N.getNode(), Imm);
349 }
350 
351 // isOpcWithIntImmediate - This method tests to see if the node is a specific
352 // opcode and that it has a immediate integer right operand.
353 // If so Imm will receive the 32 bit value.
354 static bool isOpcWithIntImmediate(const SDNode *N, unsigned Opc,
355                                   uint64_t &Imm) {
356   return N->getOpcode() == Opc &&
357          isIntImmediate(N->getOperand(1).getNode(), Imm);
358 }
359 
360 bool AArch64DAGToDAGISel::SelectInlineAsmMemoryOperand(
361     const SDValue &Op, unsigned ConstraintID, std::vector<SDValue> &OutOps) {
362   switch(ConstraintID) {
363   default:
364     llvm_unreachable("Unexpected asm memory constraint");
365   case InlineAsm::Constraint_m:
366   case InlineAsm::Constraint_Q:
367     // We need to make sure that this one operand does not end up in XZR, thus
368     // require the address to be in a PointerRegClass register.
369     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
370     const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF);
371     SDLoc dl(Op);
372     SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i64);
373     SDValue NewOp =
374         SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
375                                        dl, Op.getValueType(),
376                                        Op, RC), 0);
377     OutOps.push_back(NewOp);
378     return false;
379   }
380   return true;
381 }
382 
383 /// SelectArithImmed - Select an immediate value that can be represented as
384 /// a 12-bit value shifted left by either 0 or 12.  If so, return true with
385 /// Val set to the 12-bit value and Shift set to the shifter operand.
386 bool AArch64DAGToDAGISel::SelectArithImmed(SDValue N, SDValue &Val,
387                                            SDValue &Shift) {
388   // This function is called from the addsub_shifted_imm ComplexPattern,
389   // which lists [imm] as the list of opcode it's interested in, however
390   // we still need to check whether the operand is actually an immediate
391   // here because the ComplexPattern opcode list is only used in
392   // root-level opcode matching.
393   if (!isa<ConstantSDNode>(N.getNode()))
394     return false;
395 
396   uint64_t Immed = cast<ConstantSDNode>(N.getNode())->getZExtValue();
397   unsigned ShiftAmt;
398 
399   if (Immed >> 12 == 0) {
400     ShiftAmt = 0;
401   } else if ((Immed & 0xfff) == 0 && Immed >> 24 == 0) {
402     ShiftAmt = 12;
403     Immed = Immed >> 12;
404   } else
405     return false;
406 
407   unsigned ShVal = AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftAmt);
408   SDLoc dl(N);
409   Val = CurDAG->getTargetConstant(Immed, dl, MVT::i32);
410   Shift = CurDAG->getTargetConstant(ShVal, dl, MVT::i32);
411   return true;
412 }
413 
414 /// SelectNegArithImmed - As above, but negates the value before trying to
415 /// select it.
416 bool AArch64DAGToDAGISel::SelectNegArithImmed(SDValue N, SDValue &Val,
417                                               SDValue &Shift) {
418   // This function is called from the addsub_shifted_imm ComplexPattern,
419   // which lists [imm] as the list of opcode it's interested in, however
420   // we still need to check whether the operand is actually an immediate
421   // here because the ComplexPattern opcode list is only used in
422   // root-level opcode matching.
423   if (!isa<ConstantSDNode>(N.getNode()))
424     return false;
425 
426   // The immediate operand must be a 24-bit zero-extended immediate.
427   uint64_t Immed = cast<ConstantSDNode>(N.getNode())->getZExtValue();
428 
429   // This negation is almost always valid, but "cmp wN, #0" and "cmn wN, #0"
430   // have the opposite effect on the C flag, so this pattern mustn't match under
431   // those circumstances.
432   if (Immed == 0)
433     return false;
434 
435   if (N.getValueType() == MVT::i32)
436     Immed = ~((uint32_t)Immed) + 1;
437   else
438     Immed = ~Immed + 1ULL;
439   if (Immed & 0xFFFFFFFFFF000000ULL)
440     return false;
441 
442   Immed &= 0xFFFFFFULL;
443   return SelectArithImmed(CurDAG->getConstant(Immed, SDLoc(N), MVT::i32), Val,
444                           Shift);
445 }
446 
447 /// getShiftTypeForNode - Translate a shift node to the corresponding
448 /// ShiftType value.
449 static AArch64_AM::ShiftExtendType getShiftTypeForNode(SDValue N) {
450   switch (N.getOpcode()) {
451   default:
452     return AArch64_AM::InvalidShiftExtend;
453   case ISD::SHL:
454     return AArch64_AM::LSL;
455   case ISD::SRL:
456     return AArch64_AM::LSR;
457   case ISD::SRA:
458     return AArch64_AM::ASR;
459   case ISD::ROTR:
460     return AArch64_AM::ROR;
461   }
462 }
463 
464 /// Determine whether it is worth it to fold SHL into the addressing
465 /// mode.
466 static bool isWorthFoldingSHL(SDValue V) {
467   assert(V.getOpcode() == ISD::SHL && "invalid opcode");
468   // It is worth folding logical shift of up to three places.
469   auto *CSD = dyn_cast<ConstantSDNode>(V.getOperand(1));
470   if (!CSD)
471     return false;
472   unsigned ShiftVal = CSD->getZExtValue();
473   if (ShiftVal > 3)
474     return false;
475 
476   // Check if this particular node is reused in any non-memory related
477   // operation.  If yes, do not try to fold this node into the address
478   // computation, since the computation will be kept.
479   const SDNode *Node = V.getNode();
480   for (SDNode *UI : Node->uses())
481     if (!isa<MemSDNode>(*UI))
482       for (SDNode *UII : UI->uses())
483         if (!isa<MemSDNode>(*UII))
484           return false;
485   return true;
486 }
487 
488 /// Determine whether it is worth to fold V into an extended register.
489 bool AArch64DAGToDAGISel::isWorthFolding(SDValue V) const {
490   // Trivial if we are optimizing for code size or if there is only
491   // one use of the value.
492   if (CurDAG->shouldOptForSize() || V.hasOneUse())
493     return true;
494   // If a subtarget has a fastpath LSL we can fold a logical shift into
495   // the addressing mode and save a cycle.
496   if (Subtarget->hasLSLFast() && V.getOpcode() == ISD::SHL &&
497       isWorthFoldingSHL(V))
498     return true;
499   if (Subtarget->hasLSLFast() && V.getOpcode() == ISD::ADD) {
500     const SDValue LHS = V.getOperand(0);
501     const SDValue RHS = V.getOperand(1);
502     if (LHS.getOpcode() == ISD::SHL && isWorthFoldingSHL(LHS))
503       return true;
504     if (RHS.getOpcode() == ISD::SHL && isWorthFoldingSHL(RHS))
505       return true;
506   }
507 
508   // It hurts otherwise, since the value will be reused.
509   return false;
510 }
511 
512 /// SelectShiftedRegister - Select a "shifted register" operand.  If the value
513 /// is not shifted, set the Shift operand to default of "LSL 0".  The logical
514 /// instructions allow the shifted register to be rotated, but the arithmetic
515 /// instructions do not.  The AllowROR parameter specifies whether ROR is
516 /// supported.
517 bool AArch64DAGToDAGISel::SelectShiftedRegister(SDValue N, bool AllowROR,
518                                                 SDValue &Reg, SDValue &Shift) {
519   AArch64_AM::ShiftExtendType ShType = getShiftTypeForNode(N);
520   if (ShType == AArch64_AM::InvalidShiftExtend)
521     return false;
522   if (!AllowROR && ShType == AArch64_AM::ROR)
523     return false;
524 
525   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
526     unsigned BitSize = N.getValueSizeInBits();
527     unsigned Val = RHS->getZExtValue() & (BitSize - 1);
528     unsigned ShVal = AArch64_AM::getShifterImm(ShType, Val);
529 
530     Reg = N.getOperand(0);
531     Shift = CurDAG->getTargetConstant(ShVal, SDLoc(N), MVT::i32);
532     return isWorthFolding(N);
533   }
534 
535   return false;
536 }
537 
538 /// getExtendTypeForNode - Translate an extend node to the corresponding
539 /// ExtendType value.
540 static AArch64_AM::ShiftExtendType
541 getExtendTypeForNode(SDValue N, bool IsLoadStore = false) {
542   if (N.getOpcode() == ISD::SIGN_EXTEND ||
543       N.getOpcode() == ISD::SIGN_EXTEND_INREG) {
544     EVT SrcVT;
545     if (N.getOpcode() == ISD::SIGN_EXTEND_INREG)
546       SrcVT = cast<VTSDNode>(N.getOperand(1))->getVT();
547     else
548       SrcVT = N.getOperand(0).getValueType();
549 
550     if (!IsLoadStore && SrcVT == MVT::i8)
551       return AArch64_AM::SXTB;
552     else if (!IsLoadStore && SrcVT == MVT::i16)
553       return AArch64_AM::SXTH;
554     else if (SrcVT == MVT::i32)
555       return AArch64_AM::SXTW;
556     assert(SrcVT != MVT::i64 && "extend from 64-bits?");
557 
558     return AArch64_AM::InvalidShiftExtend;
559   } else if (N.getOpcode() == ISD::ZERO_EXTEND ||
560              N.getOpcode() == ISD::ANY_EXTEND) {
561     EVT SrcVT = N.getOperand(0).getValueType();
562     if (!IsLoadStore && SrcVT == MVT::i8)
563       return AArch64_AM::UXTB;
564     else if (!IsLoadStore && SrcVT == MVT::i16)
565       return AArch64_AM::UXTH;
566     else if (SrcVT == MVT::i32)
567       return AArch64_AM::UXTW;
568     assert(SrcVT != MVT::i64 && "extend from 64-bits?");
569 
570     return AArch64_AM::InvalidShiftExtend;
571   } else if (N.getOpcode() == ISD::AND) {
572     ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
573     if (!CSD)
574       return AArch64_AM::InvalidShiftExtend;
575     uint64_t AndMask = CSD->getZExtValue();
576 
577     switch (AndMask) {
578     default:
579       return AArch64_AM::InvalidShiftExtend;
580     case 0xFF:
581       return !IsLoadStore ? AArch64_AM::UXTB : AArch64_AM::InvalidShiftExtend;
582     case 0xFFFF:
583       return !IsLoadStore ? AArch64_AM::UXTH : AArch64_AM::InvalidShiftExtend;
584     case 0xFFFFFFFF:
585       return AArch64_AM::UXTW;
586     }
587   }
588 
589   return AArch64_AM::InvalidShiftExtend;
590 }
591 
592 // Helper for SelectMLAV64LaneV128 - Recognize high lane extracts.
593 static bool checkHighLaneIndex(SDNode *DL, SDValue &LaneOp, int &LaneIdx) {
594   if (DL->getOpcode() != AArch64ISD::DUPLANE16 &&
595       DL->getOpcode() != AArch64ISD::DUPLANE32)
596     return false;
597 
598   SDValue SV = DL->getOperand(0);
599   if (SV.getOpcode() != ISD::INSERT_SUBVECTOR)
600     return false;
601 
602   SDValue EV = SV.getOperand(1);
603   if (EV.getOpcode() != ISD::EXTRACT_SUBVECTOR)
604     return false;
605 
606   ConstantSDNode *DLidx = cast<ConstantSDNode>(DL->getOperand(1).getNode());
607   ConstantSDNode *EVidx = cast<ConstantSDNode>(EV.getOperand(1).getNode());
608   LaneIdx = DLidx->getSExtValue() + EVidx->getSExtValue();
609   LaneOp = EV.getOperand(0);
610 
611   return true;
612 }
613 
614 // Helper for SelectOpcV64LaneV128 - Recognize operations where one operand is a
615 // high lane extract.
616 static bool checkV64LaneV128(SDValue Op0, SDValue Op1, SDValue &StdOp,
617                              SDValue &LaneOp, int &LaneIdx) {
618 
619   if (!checkHighLaneIndex(Op0.getNode(), LaneOp, LaneIdx)) {
620     std::swap(Op0, Op1);
621     if (!checkHighLaneIndex(Op0.getNode(), LaneOp, LaneIdx))
622       return false;
623   }
624   StdOp = Op1;
625   return true;
626 }
627 
628 /// SelectMLAV64LaneV128 - AArch64 supports vector MLAs where one multiplicand
629 /// is a lane in the upper half of a 128-bit vector.  Recognize and select this
630 /// so that we don't emit unnecessary lane extracts.
631 bool AArch64DAGToDAGISel::tryMLAV64LaneV128(SDNode *N) {
632   SDLoc dl(N);
633   SDValue Op0 = N->getOperand(0);
634   SDValue Op1 = N->getOperand(1);
635   SDValue MLAOp1;   // Will hold ordinary multiplicand for MLA.
636   SDValue MLAOp2;   // Will hold lane-accessed multiplicand for MLA.
637   int LaneIdx = -1; // Will hold the lane index.
638 
639   if (Op1.getOpcode() != ISD::MUL ||
640       !checkV64LaneV128(Op1.getOperand(0), Op1.getOperand(1), MLAOp1, MLAOp2,
641                         LaneIdx)) {
642     std::swap(Op0, Op1);
643     if (Op1.getOpcode() != ISD::MUL ||
644         !checkV64LaneV128(Op1.getOperand(0), Op1.getOperand(1), MLAOp1, MLAOp2,
645                           LaneIdx))
646       return false;
647   }
648 
649   SDValue LaneIdxVal = CurDAG->getTargetConstant(LaneIdx, dl, MVT::i64);
650 
651   SDValue Ops[] = { Op0, MLAOp1, MLAOp2, LaneIdxVal };
652 
653   unsigned MLAOpc = ~0U;
654 
655   switch (N->getSimpleValueType(0).SimpleTy) {
656   default:
657     llvm_unreachable("Unrecognized MLA.");
658   case MVT::v4i16:
659     MLAOpc = AArch64::MLAv4i16_indexed;
660     break;
661   case MVT::v8i16:
662     MLAOpc = AArch64::MLAv8i16_indexed;
663     break;
664   case MVT::v2i32:
665     MLAOpc = AArch64::MLAv2i32_indexed;
666     break;
667   case MVT::v4i32:
668     MLAOpc = AArch64::MLAv4i32_indexed;
669     break;
670   }
671 
672   ReplaceNode(N, CurDAG->getMachineNode(MLAOpc, dl, N->getValueType(0), Ops));
673   return true;
674 }
675 
676 bool AArch64DAGToDAGISel::tryMULLV64LaneV128(unsigned IntNo, SDNode *N) {
677   SDLoc dl(N);
678   SDValue SMULLOp0;
679   SDValue SMULLOp1;
680   int LaneIdx;
681 
682   if (!checkV64LaneV128(N->getOperand(1), N->getOperand(2), SMULLOp0, SMULLOp1,
683                         LaneIdx))
684     return false;
685 
686   SDValue LaneIdxVal = CurDAG->getTargetConstant(LaneIdx, dl, MVT::i64);
687 
688   SDValue Ops[] = { SMULLOp0, SMULLOp1, LaneIdxVal };
689 
690   unsigned SMULLOpc = ~0U;
691 
692   if (IntNo == Intrinsic::aarch64_neon_smull) {
693     switch (N->getSimpleValueType(0).SimpleTy) {
694     default:
695       llvm_unreachable("Unrecognized SMULL.");
696     case MVT::v4i32:
697       SMULLOpc = AArch64::SMULLv4i16_indexed;
698       break;
699     case MVT::v2i64:
700       SMULLOpc = AArch64::SMULLv2i32_indexed;
701       break;
702     }
703   } else if (IntNo == Intrinsic::aarch64_neon_umull) {
704     switch (N->getSimpleValueType(0).SimpleTy) {
705     default:
706       llvm_unreachable("Unrecognized SMULL.");
707     case MVT::v4i32:
708       SMULLOpc = AArch64::UMULLv4i16_indexed;
709       break;
710     case MVT::v2i64:
711       SMULLOpc = AArch64::UMULLv2i32_indexed;
712       break;
713     }
714   } else
715     llvm_unreachable("Unrecognized intrinsic.");
716 
717   ReplaceNode(N, CurDAG->getMachineNode(SMULLOpc, dl, N->getValueType(0), Ops));
718   return true;
719 }
720 
721 /// Instructions that accept extend modifiers like UXTW expect the register
722 /// being extended to be a GPR32, but the incoming DAG might be acting on a
723 /// GPR64 (either via SEXT_INREG or AND). Extract the appropriate low bits if
724 /// this is the case.
725 static SDValue narrowIfNeeded(SelectionDAG *CurDAG, SDValue N) {
726   if (N.getValueType() == MVT::i32)
727     return N;
728 
729   SDLoc dl(N);
730   SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, dl, MVT::i32);
731   MachineSDNode *Node = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
732                                                dl, MVT::i32, N, SubReg);
733   return SDValue(Node, 0);
734 }
735 
736 // Returns a suitable CNT/INC/DEC/RDVL multiplier to calculate VSCALE*N.
737 template<signed Low, signed High, signed Scale>
738 bool AArch64DAGToDAGISel::SelectRDVLImm(SDValue N, SDValue &Imm) {
739   if (!isa<ConstantSDNode>(N))
740     return false;
741 
742   int64_t MulImm = cast<ConstantSDNode>(N)->getSExtValue();
743   if ((MulImm % std::abs(Scale)) == 0) {
744     int64_t RDVLImm = MulImm / Scale;
745     if ((RDVLImm >= Low) && (RDVLImm <= High)) {
746       Imm = CurDAG->getTargetConstant(RDVLImm, SDLoc(N), MVT::i32);
747       return true;
748     }
749   }
750 
751   return false;
752 }
753 
754 /// SelectArithExtendedRegister - Select a "extended register" operand.  This
755 /// operand folds in an extend followed by an optional left shift.
756 bool AArch64DAGToDAGISel::SelectArithExtendedRegister(SDValue N, SDValue &Reg,
757                                                       SDValue &Shift) {
758   unsigned ShiftVal = 0;
759   AArch64_AM::ShiftExtendType Ext;
760 
761   if (N.getOpcode() == ISD::SHL) {
762     ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
763     if (!CSD)
764       return false;
765     ShiftVal = CSD->getZExtValue();
766     if (ShiftVal > 4)
767       return false;
768 
769     Ext = getExtendTypeForNode(N.getOperand(0));
770     if (Ext == AArch64_AM::InvalidShiftExtend)
771       return false;
772 
773     Reg = N.getOperand(0).getOperand(0);
774   } else {
775     Ext = getExtendTypeForNode(N);
776     if (Ext == AArch64_AM::InvalidShiftExtend)
777       return false;
778 
779     Reg = N.getOperand(0);
780 
781     // Don't match if free 32-bit -> 64-bit zext can be used instead.
782     if (Ext == AArch64_AM::UXTW &&
783         Reg->getValueType(0).getSizeInBits() == 32 && isDef32(*Reg.getNode()))
784       return false;
785   }
786 
787   // AArch64 mandates that the RHS of the operation must use the smallest
788   // register class that could contain the size being extended from.  Thus,
789   // if we're folding a (sext i8), we need the RHS to be a GPR32, even though
790   // there might not be an actual 32-bit value in the program.  We can
791   // (harmlessly) synthesize one by injected an EXTRACT_SUBREG here.
792   assert(Ext != AArch64_AM::UXTX && Ext != AArch64_AM::SXTX);
793   Reg = narrowIfNeeded(CurDAG, Reg);
794   Shift = CurDAG->getTargetConstant(getArithExtendImm(Ext, ShiftVal), SDLoc(N),
795                                     MVT::i32);
796   return isWorthFolding(N);
797 }
798 
799 /// If there's a use of this ADDlow that's not itself a load/store then we'll
800 /// need to create a real ADD instruction from it anyway and there's no point in
801 /// folding it into the mem op. Theoretically, it shouldn't matter, but there's
802 /// a single pseudo-instruction for an ADRP/ADD pair so over-aggressive folding
803 /// leads to duplicated ADRP instructions.
804 static bool isWorthFoldingADDlow(SDValue N) {
805   for (auto Use : N->uses()) {
806     if (Use->getOpcode() != ISD::LOAD && Use->getOpcode() != ISD::STORE &&
807         Use->getOpcode() != ISD::ATOMIC_LOAD &&
808         Use->getOpcode() != ISD::ATOMIC_STORE)
809       return false;
810 
811     // ldar and stlr have much more restrictive addressing modes (just a
812     // register).
813     if (isStrongerThanMonotonic(cast<MemSDNode>(Use)->getOrdering()))
814       return false;
815   }
816 
817   return true;
818 }
819 
820 /// SelectAddrModeIndexedBitWidth - Select a "register plus scaled (un)signed BW-bit
821 /// immediate" address.  The "Size" argument is the size in bytes of the memory
822 /// reference, which determines the scale.
823 bool AArch64DAGToDAGISel::SelectAddrModeIndexedBitWidth(SDValue N, bool IsSignedImm,
824                                                         unsigned BW, unsigned Size,
825                                                         SDValue &Base,
826                                                         SDValue &OffImm) {
827   SDLoc dl(N);
828   const DataLayout &DL = CurDAG->getDataLayout();
829   const TargetLowering *TLI = getTargetLowering();
830   if (N.getOpcode() == ISD::FrameIndex) {
831     int FI = cast<FrameIndexSDNode>(N)->getIndex();
832     Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
833     OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
834     return true;
835   }
836 
837   // As opposed to the (12-bit) Indexed addressing mode below, the 7/9-bit signed
838   // selected here doesn't support labels/immediates, only base+offset.
839   if (CurDAG->isBaseWithConstantOffset(N)) {
840     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
841       if (IsSignedImm) {
842         int64_t RHSC = RHS->getSExtValue();
843         unsigned Scale = Log2_32(Size);
844         int64_t Range = 0x1LL << (BW - 1);
845 
846         if ((RHSC & (Size - 1)) == 0 && RHSC >= -(Range << Scale) &&
847             RHSC < (Range << Scale)) {
848           Base = N.getOperand(0);
849           if (Base.getOpcode() == ISD::FrameIndex) {
850             int FI = cast<FrameIndexSDNode>(Base)->getIndex();
851             Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
852           }
853           OffImm = CurDAG->getTargetConstant(RHSC >> Scale, dl, MVT::i64);
854           return true;
855         }
856       } else {
857         // unsigned Immediate
858         uint64_t RHSC = RHS->getZExtValue();
859         unsigned Scale = Log2_32(Size);
860         uint64_t Range = 0x1ULL << BW;
861 
862         if ((RHSC & (Size - 1)) == 0 && RHSC < (Range << Scale)) {
863           Base = N.getOperand(0);
864           if (Base.getOpcode() == ISD::FrameIndex) {
865             int FI = cast<FrameIndexSDNode>(Base)->getIndex();
866             Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
867           }
868           OffImm = CurDAG->getTargetConstant(RHSC >> Scale, dl, MVT::i64);
869           return true;
870         }
871       }
872     }
873   }
874   // Base only. The address will be materialized into a register before
875   // the memory is accessed.
876   //    add x0, Xbase, #offset
877   //    stp x1, x2, [x0]
878   Base = N;
879   OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
880   return true;
881 }
882 
883 /// SelectAddrModeIndexed - Select a "register plus scaled unsigned 12-bit
884 /// immediate" address.  The "Size" argument is the size in bytes of the memory
885 /// reference, which determines the scale.
886 bool AArch64DAGToDAGISel::SelectAddrModeIndexed(SDValue N, unsigned Size,
887                                               SDValue &Base, SDValue &OffImm) {
888   SDLoc dl(N);
889   const DataLayout &DL = CurDAG->getDataLayout();
890   const TargetLowering *TLI = getTargetLowering();
891   if (N.getOpcode() == ISD::FrameIndex) {
892     int FI = cast<FrameIndexSDNode>(N)->getIndex();
893     Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
894     OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
895     return true;
896   }
897 
898   if (N.getOpcode() == AArch64ISD::ADDlow && isWorthFoldingADDlow(N)) {
899     GlobalAddressSDNode *GAN =
900         dyn_cast<GlobalAddressSDNode>(N.getOperand(1).getNode());
901     Base = N.getOperand(0);
902     OffImm = N.getOperand(1);
903     if (!GAN)
904       return true;
905 
906     if (GAN->getOffset() % Size == 0) {
907       const GlobalValue *GV = GAN->getGlobal();
908       unsigned Alignment = GV->getAlignment();
909       Type *Ty = GV->getValueType();
910       if (Alignment == 0 && Ty->isSized())
911         Alignment = DL.getABITypeAlignment(Ty);
912 
913       if (Alignment >= Size)
914         return true;
915     }
916   }
917 
918   if (CurDAG->isBaseWithConstantOffset(N)) {
919     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
920       int64_t RHSC = (int64_t)RHS->getZExtValue();
921       unsigned Scale = Log2_32(Size);
922       if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 && RHSC < (0x1000 << Scale)) {
923         Base = N.getOperand(0);
924         if (Base.getOpcode() == ISD::FrameIndex) {
925           int FI = cast<FrameIndexSDNode>(Base)->getIndex();
926           Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
927         }
928         OffImm = CurDAG->getTargetConstant(RHSC >> Scale, dl, MVT::i64);
929         return true;
930       }
931     }
932   }
933 
934   // Before falling back to our general case, check if the unscaled
935   // instructions can handle this. If so, that's preferable.
936   if (SelectAddrModeUnscaled(N, Size, Base, OffImm))
937     return false;
938 
939   // Base only. The address will be materialized into a register before
940   // the memory is accessed.
941   //    add x0, Xbase, #offset
942   //    ldr x0, [x0]
943   Base = N;
944   OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
945   return true;
946 }
947 
948 /// SelectAddrModeUnscaled - Select a "register plus unscaled signed 9-bit
949 /// immediate" address.  This should only match when there is an offset that
950 /// is not valid for a scaled immediate addressing mode.  The "Size" argument
951 /// is the size in bytes of the memory reference, which is needed here to know
952 /// what is valid for a scaled immediate.
953 bool AArch64DAGToDAGISel::SelectAddrModeUnscaled(SDValue N, unsigned Size,
954                                                  SDValue &Base,
955                                                  SDValue &OffImm) {
956   if (!CurDAG->isBaseWithConstantOffset(N))
957     return false;
958   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
959     int64_t RHSC = RHS->getSExtValue();
960     // If the offset is valid as a scaled immediate, don't match here.
961     if ((RHSC & (Size - 1)) == 0 && RHSC >= 0 &&
962         RHSC < (0x1000 << Log2_32(Size)))
963       return false;
964     if (RHSC >= -256 && RHSC < 256) {
965       Base = N.getOperand(0);
966       if (Base.getOpcode() == ISD::FrameIndex) {
967         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
968         const TargetLowering *TLI = getTargetLowering();
969         Base = CurDAG->getTargetFrameIndex(
970             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
971       }
972       OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i64);
973       return true;
974     }
975   }
976   return false;
977 }
978 
979 static SDValue Widen(SelectionDAG *CurDAG, SDValue N) {
980   SDLoc dl(N);
981   SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, dl, MVT::i32);
982   SDValue ImpDef = SDValue(
983       CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, MVT::i64), 0);
984   MachineSDNode *Node = CurDAG->getMachineNode(
985       TargetOpcode::INSERT_SUBREG, dl, MVT::i64, ImpDef, N, SubReg);
986   return SDValue(Node, 0);
987 }
988 
989 /// Check if the given SHL node (\p N), can be used to form an
990 /// extended register for an addressing mode.
991 bool AArch64DAGToDAGISel::SelectExtendedSHL(SDValue N, unsigned Size,
992                                             bool WantExtend, SDValue &Offset,
993                                             SDValue &SignExtend) {
994   assert(N.getOpcode() == ISD::SHL && "Invalid opcode.");
995   ConstantSDNode *CSD = dyn_cast<ConstantSDNode>(N.getOperand(1));
996   if (!CSD || (CSD->getZExtValue() & 0x7) != CSD->getZExtValue())
997     return false;
998 
999   SDLoc dl(N);
1000   if (WantExtend) {
1001     AArch64_AM::ShiftExtendType Ext =
1002         getExtendTypeForNode(N.getOperand(0), true);
1003     if (Ext == AArch64_AM::InvalidShiftExtend)
1004       return false;
1005 
1006     Offset = narrowIfNeeded(CurDAG, N.getOperand(0).getOperand(0));
1007     SignExtend = CurDAG->getTargetConstant(Ext == AArch64_AM::SXTW, dl,
1008                                            MVT::i32);
1009   } else {
1010     Offset = N.getOperand(0);
1011     SignExtend = CurDAG->getTargetConstant(0, dl, MVT::i32);
1012   }
1013 
1014   unsigned LegalShiftVal = Log2_32(Size);
1015   unsigned ShiftVal = CSD->getZExtValue();
1016 
1017   if (ShiftVal != 0 && ShiftVal != LegalShiftVal)
1018     return false;
1019 
1020   return isWorthFolding(N);
1021 }
1022 
1023 bool AArch64DAGToDAGISel::SelectAddrModeWRO(SDValue N, unsigned Size,
1024                                             SDValue &Base, SDValue &Offset,
1025                                             SDValue &SignExtend,
1026                                             SDValue &DoShift) {
1027   if (N.getOpcode() != ISD::ADD)
1028     return false;
1029   SDValue LHS = N.getOperand(0);
1030   SDValue RHS = N.getOperand(1);
1031   SDLoc dl(N);
1032 
1033   // We don't want to match immediate adds here, because they are better lowered
1034   // to the register-immediate addressing modes.
1035   if (isa<ConstantSDNode>(LHS) || isa<ConstantSDNode>(RHS))
1036     return false;
1037 
1038   // Check if this particular node is reused in any non-memory related
1039   // operation.  If yes, do not try to fold this node into the address
1040   // computation, since the computation will be kept.
1041   const SDNode *Node = N.getNode();
1042   for (SDNode *UI : Node->uses()) {
1043     if (!isa<MemSDNode>(*UI))
1044       return false;
1045   }
1046 
1047   // Remember if it is worth folding N when it produces extended register.
1048   bool IsExtendedRegisterWorthFolding = isWorthFolding(N);
1049 
1050   // Try to match a shifted extend on the RHS.
1051   if (IsExtendedRegisterWorthFolding && RHS.getOpcode() == ISD::SHL &&
1052       SelectExtendedSHL(RHS, Size, true, Offset, SignExtend)) {
1053     Base = LHS;
1054     DoShift = CurDAG->getTargetConstant(true, dl, MVT::i32);
1055     return true;
1056   }
1057 
1058   // Try to match a shifted extend on the LHS.
1059   if (IsExtendedRegisterWorthFolding && LHS.getOpcode() == ISD::SHL &&
1060       SelectExtendedSHL(LHS, Size, true, Offset, SignExtend)) {
1061     Base = RHS;
1062     DoShift = CurDAG->getTargetConstant(true, dl, MVT::i32);
1063     return true;
1064   }
1065 
1066   // There was no shift, whatever else we find.
1067   DoShift = CurDAG->getTargetConstant(false, dl, MVT::i32);
1068 
1069   AArch64_AM::ShiftExtendType Ext = AArch64_AM::InvalidShiftExtend;
1070   // Try to match an unshifted extend on the LHS.
1071   if (IsExtendedRegisterWorthFolding &&
1072       (Ext = getExtendTypeForNode(LHS, true)) !=
1073           AArch64_AM::InvalidShiftExtend) {
1074     Base = RHS;
1075     Offset = narrowIfNeeded(CurDAG, LHS.getOperand(0));
1076     SignExtend = CurDAG->getTargetConstant(Ext == AArch64_AM::SXTW, dl,
1077                                            MVT::i32);
1078     if (isWorthFolding(LHS))
1079       return true;
1080   }
1081 
1082   // Try to match an unshifted extend on the RHS.
1083   if (IsExtendedRegisterWorthFolding &&
1084       (Ext = getExtendTypeForNode(RHS, true)) !=
1085           AArch64_AM::InvalidShiftExtend) {
1086     Base = LHS;
1087     Offset = narrowIfNeeded(CurDAG, RHS.getOperand(0));
1088     SignExtend = CurDAG->getTargetConstant(Ext == AArch64_AM::SXTW, dl,
1089                                            MVT::i32);
1090     if (isWorthFolding(RHS))
1091       return true;
1092   }
1093 
1094   return false;
1095 }
1096 
1097 // Check if the given immediate is preferred by ADD. If an immediate can be
1098 // encoded in an ADD, or it can be encoded in an "ADD LSL #12" and can not be
1099 // encoded by one MOVZ, return true.
1100 static bool isPreferredADD(int64_t ImmOff) {
1101   // Constant in [0x0, 0xfff] can be encoded in ADD.
1102   if ((ImmOff & 0xfffffffffffff000LL) == 0x0LL)
1103     return true;
1104   // Check if it can be encoded in an "ADD LSL #12".
1105   if ((ImmOff & 0xffffffffff000fffLL) == 0x0LL)
1106     // As a single MOVZ is faster than a "ADD of LSL #12", ignore such constant.
1107     return (ImmOff & 0xffffffffff00ffffLL) != 0x0LL &&
1108            (ImmOff & 0xffffffffffff0fffLL) != 0x0LL;
1109   return false;
1110 }
1111 
1112 bool AArch64DAGToDAGISel::SelectAddrModeXRO(SDValue N, unsigned Size,
1113                                             SDValue &Base, SDValue &Offset,
1114                                             SDValue &SignExtend,
1115                                             SDValue &DoShift) {
1116   if (N.getOpcode() != ISD::ADD)
1117     return false;
1118   SDValue LHS = N.getOperand(0);
1119   SDValue RHS = N.getOperand(1);
1120   SDLoc DL(N);
1121 
1122   // Check if this particular node is reused in any non-memory related
1123   // operation.  If yes, do not try to fold this node into the address
1124   // computation, since the computation will be kept.
1125   const SDNode *Node = N.getNode();
1126   for (SDNode *UI : Node->uses()) {
1127     if (!isa<MemSDNode>(*UI))
1128       return false;
1129   }
1130 
1131   // Watch out if RHS is a wide immediate, it can not be selected into
1132   // [BaseReg+Imm] addressing mode. Also it may not be able to be encoded into
1133   // ADD/SUB. Instead it will use [BaseReg + 0] address mode and generate
1134   // instructions like:
1135   //     MOV  X0, WideImmediate
1136   //     ADD  X1, BaseReg, X0
1137   //     LDR  X2, [X1, 0]
1138   // For such situation, using [BaseReg, XReg] addressing mode can save one
1139   // ADD/SUB:
1140   //     MOV  X0, WideImmediate
1141   //     LDR  X2, [BaseReg, X0]
1142   if (isa<ConstantSDNode>(RHS)) {
1143     int64_t ImmOff = (int64_t)cast<ConstantSDNode>(RHS)->getZExtValue();
1144     unsigned Scale = Log2_32(Size);
1145     // Skip the immediate can be selected by load/store addressing mode.
1146     // Also skip the immediate can be encoded by a single ADD (SUB is also
1147     // checked by using -ImmOff).
1148     if ((ImmOff % Size == 0 && ImmOff >= 0 && ImmOff < (0x1000 << Scale)) ||
1149         isPreferredADD(ImmOff) || isPreferredADD(-ImmOff))
1150       return false;
1151 
1152     SDValue Ops[] = { RHS };
1153     SDNode *MOVI =
1154         CurDAG->getMachineNode(AArch64::MOVi64imm, DL, MVT::i64, Ops);
1155     SDValue MOVIV = SDValue(MOVI, 0);
1156     // This ADD of two X register will be selected into [Reg+Reg] mode.
1157     N = CurDAG->getNode(ISD::ADD, DL, MVT::i64, LHS, MOVIV);
1158   }
1159 
1160   // Remember if it is worth folding N when it produces extended register.
1161   bool IsExtendedRegisterWorthFolding = isWorthFolding(N);
1162 
1163   // Try to match a shifted extend on the RHS.
1164   if (IsExtendedRegisterWorthFolding && RHS.getOpcode() == ISD::SHL &&
1165       SelectExtendedSHL(RHS, Size, false, Offset, SignExtend)) {
1166     Base = LHS;
1167     DoShift = CurDAG->getTargetConstant(true, DL, MVT::i32);
1168     return true;
1169   }
1170 
1171   // Try to match a shifted extend on the LHS.
1172   if (IsExtendedRegisterWorthFolding && LHS.getOpcode() == ISD::SHL &&
1173       SelectExtendedSHL(LHS, Size, false, Offset, SignExtend)) {
1174     Base = RHS;
1175     DoShift = CurDAG->getTargetConstant(true, DL, MVT::i32);
1176     return true;
1177   }
1178 
1179   // Match any non-shifted, non-extend, non-immediate add expression.
1180   Base = LHS;
1181   Offset = RHS;
1182   SignExtend = CurDAG->getTargetConstant(false, DL, MVT::i32);
1183   DoShift = CurDAG->getTargetConstant(false, DL, MVT::i32);
1184   // Reg1 + Reg2 is free: no check needed.
1185   return true;
1186 }
1187 
1188 SDValue AArch64DAGToDAGISel::createDTuple(ArrayRef<SDValue> Regs) {
1189   static const unsigned RegClassIDs[] = {
1190       AArch64::DDRegClassID, AArch64::DDDRegClassID, AArch64::DDDDRegClassID};
1191   static const unsigned SubRegs[] = {AArch64::dsub0, AArch64::dsub1,
1192                                      AArch64::dsub2, AArch64::dsub3};
1193 
1194   return createTuple(Regs, RegClassIDs, SubRegs);
1195 }
1196 
1197 SDValue AArch64DAGToDAGISel::createQTuple(ArrayRef<SDValue> Regs) {
1198   static const unsigned RegClassIDs[] = {
1199       AArch64::QQRegClassID, AArch64::QQQRegClassID, AArch64::QQQQRegClassID};
1200   static const unsigned SubRegs[] = {AArch64::qsub0, AArch64::qsub1,
1201                                      AArch64::qsub2, AArch64::qsub3};
1202 
1203   return createTuple(Regs, RegClassIDs, SubRegs);
1204 }
1205 
1206 SDValue AArch64DAGToDAGISel::createZTuple(ArrayRef<SDValue> Regs) {
1207   static const unsigned RegClassIDs[] = {AArch64::ZPR2RegClassID,
1208                                          AArch64::ZPR3RegClassID,
1209                                          AArch64::ZPR4RegClassID};
1210   static const unsigned SubRegs[] = {AArch64::zsub0, AArch64::zsub1,
1211                                      AArch64::zsub2, AArch64::zsub3};
1212 
1213   return createTuple(Regs, RegClassIDs, SubRegs);
1214 }
1215 
1216 SDValue AArch64DAGToDAGISel::createTuple(ArrayRef<SDValue> Regs,
1217                                          const unsigned RegClassIDs[],
1218                                          const unsigned SubRegs[]) {
1219   // There's no special register-class for a vector-list of 1 element: it's just
1220   // a vector.
1221   if (Regs.size() == 1)
1222     return Regs[0];
1223 
1224   assert(Regs.size() >= 2 && Regs.size() <= 4);
1225 
1226   SDLoc DL(Regs[0]);
1227 
1228   SmallVector<SDValue, 4> Ops;
1229 
1230   // First operand of REG_SEQUENCE is the desired RegClass.
1231   Ops.push_back(
1232       CurDAG->getTargetConstant(RegClassIDs[Regs.size() - 2], DL, MVT::i32));
1233 
1234   // Then we get pairs of source & subregister-position for the components.
1235   for (unsigned i = 0; i < Regs.size(); ++i) {
1236     Ops.push_back(Regs[i]);
1237     Ops.push_back(CurDAG->getTargetConstant(SubRegs[i], DL, MVT::i32));
1238   }
1239 
1240   SDNode *N =
1241       CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, DL, MVT::Untyped, Ops);
1242   return SDValue(N, 0);
1243 }
1244 
1245 void AArch64DAGToDAGISel::SelectTable(SDNode *N, unsigned NumVecs, unsigned Opc,
1246                                       bool isExt) {
1247   SDLoc dl(N);
1248   EVT VT = N->getValueType(0);
1249 
1250   unsigned ExtOff = isExt;
1251 
1252   // Form a REG_SEQUENCE to force register allocation.
1253   unsigned Vec0Off = ExtOff + 1;
1254   SmallVector<SDValue, 4> Regs(N->op_begin() + Vec0Off,
1255                                N->op_begin() + Vec0Off + NumVecs);
1256   SDValue RegSeq = createQTuple(Regs);
1257 
1258   SmallVector<SDValue, 6> Ops;
1259   if (isExt)
1260     Ops.push_back(N->getOperand(1));
1261   Ops.push_back(RegSeq);
1262   Ops.push_back(N->getOperand(NumVecs + ExtOff + 1));
1263   ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, Ops));
1264 }
1265 
1266 bool AArch64DAGToDAGISel::tryIndexedLoad(SDNode *N) {
1267   LoadSDNode *LD = cast<LoadSDNode>(N);
1268   if (LD->isUnindexed())
1269     return false;
1270   EVT VT = LD->getMemoryVT();
1271   EVT DstVT = N->getValueType(0);
1272   ISD::MemIndexedMode AM = LD->getAddressingMode();
1273   bool IsPre = AM == ISD::PRE_INC || AM == ISD::PRE_DEC;
1274 
1275   // We're not doing validity checking here. That was done when checking
1276   // if we should mark the load as indexed or not. We're just selecting
1277   // the right instruction.
1278   unsigned Opcode = 0;
1279 
1280   ISD::LoadExtType ExtType = LD->getExtensionType();
1281   bool InsertTo64 = false;
1282   if (VT == MVT::i64)
1283     Opcode = IsPre ? AArch64::LDRXpre : AArch64::LDRXpost;
1284   else if (VT == MVT::i32) {
1285     if (ExtType == ISD::NON_EXTLOAD)
1286       Opcode = IsPre ? AArch64::LDRWpre : AArch64::LDRWpost;
1287     else if (ExtType == ISD::SEXTLOAD)
1288       Opcode = IsPre ? AArch64::LDRSWpre : AArch64::LDRSWpost;
1289     else {
1290       Opcode = IsPre ? AArch64::LDRWpre : AArch64::LDRWpost;
1291       InsertTo64 = true;
1292       // The result of the load is only i32. It's the subreg_to_reg that makes
1293       // it into an i64.
1294       DstVT = MVT::i32;
1295     }
1296   } else if (VT == MVT::i16) {
1297     if (ExtType == ISD::SEXTLOAD) {
1298       if (DstVT == MVT::i64)
1299         Opcode = IsPre ? AArch64::LDRSHXpre : AArch64::LDRSHXpost;
1300       else
1301         Opcode = IsPre ? AArch64::LDRSHWpre : AArch64::LDRSHWpost;
1302     } else {
1303       Opcode = IsPre ? AArch64::LDRHHpre : AArch64::LDRHHpost;
1304       InsertTo64 = DstVT == MVT::i64;
1305       // The result of the load is only i32. It's the subreg_to_reg that makes
1306       // it into an i64.
1307       DstVT = MVT::i32;
1308     }
1309   } else if (VT == MVT::i8) {
1310     if (ExtType == ISD::SEXTLOAD) {
1311       if (DstVT == MVT::i64)
1312         Opcode = IsPre ? AArch64::LDRSBXpre : AArch64::LDRSBXpost;
1313       else
1314         Opcode = IsPre ? AArch64::LDRSBWpre : AArch64::LDRSBWpost;
1315     } else {
1316       Opcode = IsPre ? AArch64::LDRBBpre : AArch64::LDRBBpost;
1317       InsertTo64 = DstVT == MVT::i64;
1318       // The result of the load is only i32. It's the subreg_to_reg that makes
1319       // it into an i64.
1320       DstVT = MVT::i32;
1321     }
1322   } else if (VT == MVT::f16) {
1323     Opcode = IsPre ? AArch64::LDRHpre : AArch64::LDRHpost;
1324   } else if (VT == MVT::f32) {
1325     Opcode = IsPre ? AArch64::LDRSpre : AArch64::LDRSpost;
1326   } else if (VT == MVT::f64 || VT.is64BitVector()) {
1327     Opcode = IsPre ? AArch64::LDRDpre : AArch64::LDRDpost;
1328   } else if (VT.is128BitVector()) {
1329     Opcode = IsPre ? AArch64::LDRQpre : AArch64::LDRQpost;
1330   } else
1331     return false;
1332   SDValue Chain = LD->getChain();
1333   SDValue Base = LD->getBasePtr();
1334   ConstantSDNode *OffsetOp = cast<ConstantSDNode>(LD->getOffset());
1335   int OffsetVal = (int)OffsetOp->getZExtValue();
1336   SDLoc dl(N);
1337   SDValue Offset = CurDAG->getTargetConstant(OffsetVal, dl, MVT::i64);
1338   SDValue Ops[] = { Base, Offset, Chain };
1339   SDNode *Res = CurDAG->getMachineNode(Opcode, dl, MVT::i64, DstVT,
1340                                        MVT::Other, Ops);
1341   // Either way, we're replacing the node, so tell the caller that.
1342   SDValue LoadedVal = SDValue(Res, 1);
1343   if (InsertTo64) {
1344     SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, dl, MVT::i32);
1345     LoadedVal =
1346         SDValue(CurDAG->getMachineNode(
1347                     AArch64::SUBREG_TO_REG, dl, MVT::i64,
1348                     CurDAG->getTargetConstant(0, dl, MVT::i64), LoadedVal,
1349                     SubReg),
1350                 0);
1351   }
1352 
1353   ReplaceUses(SDValue(N, 0), LoadedVal);
1354   ReplaceUses(SDValue(N, 1), SDValue(Res, 0));
1355   ReplaceUses(SDValue(N, 2), SDValue(Res, 2));
1356   CurDAG->RemoveDeadNode(N);
1357   return true;
1358 }
1359 
1360 void AArch64DAGToDAGISel::SelectLoad(SDNode *N, unsigned NumVecs, unsigned Opc,
1361                                      unsigned SubRegIdx) {
1362   SDLoc dl(N);
1363   EVT VT = N->getValueType(0);
1364   SDValue Chain = N->getOperand(0);
1365 
1366   SDValue Ops[] = {N->getOperand(2), // Mem operand;
1367                    Chain};
1368 
1369   const EVT ResTys[] = {MVT::Untyped, MVT::Other};
1370 
1371   SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1372   SDValue SuperReg = SDValue(Ld, 0);
1373   for (unsigned i = 0; i < NumVecs; ++i)
1374     ReplaceUses(SDValue(N, i),
1375         CurDAG->getTargetExtractSubreg(SubRegIdx + i, dl, VT, SuperReg));
1376 
1377   ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 1));
1378 
1379   // Transfer memoperands.
1380   MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
1381   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Ld), {MemOp});
1382 
1383   CurDAG->RemoveDeadNode(N);
1384 }
1385 
1386 void AArch64DAGToDAGISel::SelectPostLoad(SDNode *N, unsigned NumVecs,
1387                                          unsigned Opc, unsigned SubRegIdx) {
1388   SDLoc dl(N);
1389   EVT VT = N->getValueType(0);
1390   SDValue Chain = N->getOperand(0);
1391 
1392   SDValue Ops[] = {N->getOperand(1), // Mem operand
1393                    N->getOperand(2), // Incremental
1394                    Chain};
1395 
1396   const EVT ResTys[] = {MVT::i64, // Type of the write back register
1397                         MVT::Untyped, MVT::Other};
1398 
1399   SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1400 
1401   // Update uses of write back register
1402   ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 0));
1403 
1404   // Update uses of vector list
1405   SDValue SuperReg = SDValue(Ld, 1);
1406   if (NumVecs == 1)
1407     ReplaceUses(SDValue(N, 0), SuperReg);
1408   else
1409     for (unsigned i = 0; i < NumVecs; ++i)
1410       ReplaceUses(SDValue(N, i),
1411           CurDAG->getTargetExtractSubreg(SubRegIdx + i, dl, VT, SuperReg));
1412 
1413   // Update the chain
1414   ReplaceUses(SDValue(N, NumVecs + 1), SDValue(Ld, 2));
1415   CurDAG->RemoveDeadNode(N);
1416 }
1417 
1418 /// Optimize \param OldBase and \param OldOffset selecting the best addressing
1419 /// mode. Returns a tuple consisting of an Opcode, an SDValue representing the
1420 /// new Base and an SDValue representing the new offset.
1421 template <unsigned Scale>
1422 std::tuple<unsigned, SDValue, SDValue>
1423 AArch64DAGToDAGISel::findAddrModeSVELoadStore(SDNode *N, const unsigned Opc_rr,
1424                                               const unsigned Opc_ri,
1425                                               const SDValue &OldBase,
1426                                               const SDValue &OldOffset) {
1427   SDValue NewBase = OldBase;
1428   SDValue NewOffset = OldOffset;
1429   // Detect a possible Reg+Imm addressing mode.
1430   const bool IsRegImm = SelectAddrModeIndexedSVE</*Min=*/-8, /*Max=*/7>(
1431       N, OldBase, NewBase, NewOffset);
1432 
1433   // Detect a possible reg+reg addressing mode, but only if we haven't already
1434   // detected a Reg+Imm one.
1435   const bool IsRegReg =
1436       !IsRegImm && SelectSVERegRegAddrMode<Scale>(OldBase, NewBase, NewOffset);
1437 
1438   // Select the instruction.
1439   return std::make_tuple(IsRegReg ? Opc_rr : Opc_ri, NewBase, NewOffset);
1440 }
1441 
1442 void AArch64DAGToDAGISel::SelectStore(SDNode *N, unsigned NumVecs,
1443                                       unsigned Opc) {
1444   SDLoc dl(N);
1445   EVT VT = N->getOperand(2)->getValueType(0);
1446 
1447   // Form a REG_SEQUENCE to force register allocation.
1448   bool Is128Bit = VT.getSizeInBits() == 128;
1449   SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
1450   SDValue RegSeq = Is128Bit ? createQTuple(Regs) : createDTuple(Regs);
1451 
1452   SDValue Ops[] = {RegSeq, N->getOperand(NumVecs + 2), N->getOperand(0)};
1453   SDNode *St = CurDAG->getMachineNode(Opc, dl, N->getValueType(0), Ops);
1454 
1455   // Transfer memoperands.
1456   MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
1457   CurDAG->setNodeMemRefs(cast<MachineSDNode>(St), {MemOp});
1458 
1459   ReplaceNode(N, St);
1460 }
1461 
1462 template <unsigned Scale>
1463 void AArch64DAGToDAGISel::SelectPredicatedStore(SDNode *N, unsigned NumVecs,
1464                                                 const unsigned Opc_rr,
1465                                                 const unsigned Opc_ri) {
1466   SDLoc dl(N);
1467 
1468   // Form a REG_SEQUENCE to force register allocation.
1469   SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
1470   SDValue RegSeq = createZTuple(Regs);
1471 
1472   // Optimize addressing mode.
1473   unsigned Opc;
1474   SDValue Offset, Base;
1475   std::tie(Opc, Base, Offset) = findAddrModeSVELoadStore<Scale>(
1476       N, Opc_rr, Opc_ri, N->getOperand(NumVecs + 3),
1477       CurDAG->getTargetConstant(0, dl, MVT::i64));
1478 
1479   SDValue Ops[] = {RegSeq, N->getOperand(NumVecs + 2), // predicate
1480                    Base,                               // address
1481                    Offset,                             // offset
1482                    N->getOperand(0)};                  // chain
1483   SDNode *St = CurDAG->getMachineNode(Opc, dl, N->getValueType(0), Ops);
1484 
1485   ReplaceNode(N, St);
1486 }
1487 
1488 bool AArch64DAGToDAGISel::SelectAddrModeFrameIndexSVE(SDValue N, SDValue &Base,
1489                                                       SDValue &OffImm) {
1490   SDLoc dl(N);
1491   const DataLayout &DL = CurDAG->getDataLayout();
1492   const TargetLowering *TLI = getTargetLowering();
1493 
1494   // Try to match it for the frame address
1495   if (auto FINode = dyn_cast<FrameIndexSDNode>(N)) {
1496     int FI = FINode->getIndex();
1497     Base = CurDAG->getTargetFrameIndex(FI, TLI->getPointerTy(DL));
1498     OffImm = CurDAG->getTargetConstant(0, dl, MVT::i64);
1499     return true;
1500   }
1501 
1502   return false;
1503 }
1504 
1505 void AArch64DAGToDAGISel::SelectPostStore(SDNode *N, unsigned NumVecs,
1506                                           unsigned Opc) {
1507   SDLoc dl(N);
1508   EVT VT = N->getOperand(2)->getValueType(0);
1509   const EVT ResTys[] = {MVT::i64,    // Type of the write back register
1510                         MVT::Other}; // Type for the Chain
1511 
1512   // Form a REG_SEQUENCE to force register allocation.
1513   bool Is128Bit = VT.getSizeInBits() == 128;
1514   SmallVector<SDValue, 4> Regs(N->op_begin() + 1, N->op_begin() + 1 + NumVecs);
1515   SDValue RegSeq = Is128Bit ? createQTuple(Regs) : createDTuple(Regs);
1516 
1517   SDValue Ops[] = {RegSeq,
1518                    N->getOperand(NumVecs + 1), // base register
1519                    N->getOperand(NumVecs + 2), // Incremental
1520                    N->getOperand(0)};          // Chain
1521   SDNode *St = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1522 
1523   ReplaceNode(N, St);
1524 }
1525 
1526 namespace {
1527 /// WidenVector - Given a value in the V64 register class, produce the
1528 /// equivalent value in the V128 register class.
1529 class WidenVector {
1530   SelectionDAG &DAG;
1531 
1532 public:
1533   WidenVector(SelectionDAG &DAG) : DAG(DAG) {}
1534 
1535   SDValue operator()(SDValue V64Reg) {
1536     EVT VT = V64Reg.getValueType();
1537     unsigned NarrowSize = VT.getVectorNumElements();
1538     MVT EltTy = VT.getVectorElementType().getSimpleVT();
1539     MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
1540     SDLoc DL(V64Reg);
1541 
1542     SDValue Undef =
1543         SDValue(DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF, DL, WideTy), 0);
1544     return DAG.getTargetInsertSubreg(AArch64::dsub, DL, WideTy, Undef, V64Reg);
1545   }
1546 };
1547 } // namespace
1548 
1549 /// NarrowVector - Given a value in the V128 register class, produce the
1550 /// equivalent value in the V64 register class.
1551 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
1552   EVT VT = V128Reg.getValueType();
1553   unsigned WideSize = VT.getVectorNumElements();
1554   MVT EltTy = VT.getVectorElementType().getSimpleVT();
1555   MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
1556 
1557   return DAG.getTargetExtractSubreg(AArch64::dsub, SDLoc(V128Reg), NarrowTy,
1558                                     V128Reg);
1559 }
1560 
1561 void AArch64DAGToDAGISel::SelectLoadLane(SDNode *N, unsigned NumVecs,
1562                                          unsigned Opc) {
1563   SDLoc dl(N);
1564   EVT VT = N->getValueType(0);
1565   bool Narrow = VT.getSizeInBits() == 64;
1566 
1567   // Form a REG_SEQUENCE to force register allocation.
1568   SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
1569 
1570   if (Narrow)
1571     transform(Regs, Regs.begin(),
1572                    WidenVector(*CurDAG));
1573 
1574   SDValue RegSeq = createQTuple(Regs);
1575 
1576   const EVT ResTys[] = {MVT::Untyped, MVT::Other};
1577 
1578   unsigned LaneNo =
1579       cast<ConstantSDNode>(N->getOperand(NumVecs + 2))->getZExtValue();
1580 
1581   SDValue Ops[] = {RegSeq, CurDAG->getTargetConstant(LaneNo, dl, MVT::i64),
1582                    N->getOperand(NumVecs + 3), N->getOperand(0)};
1583   SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1584   SDValue SuperReg = SDValue(Ld, 0);
1585 
1586   EVT WideVT = RegSeq.getOperand(1)->getValueType(0);
1587   static const unsigned QSubs[] = { AArch64::qsub0, AArch64::qsub1,
1588                                     AArch64::qsub2, AArch64::qsub3 };
1589   for (unsigned i = 0; i < NumVecs; ++i) {
1590     SDValue NV = CurDAG->getTargetExtractSubreg(QSubs[i], dl, WideVT, SuperReg);
1591     if (Narrow)
1592       NV = NarrowVector(NV, *CurDAG);
1593     ReplaceUses(SDValue(N, i), NV);
1594   }
1595 
1596   ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 1));
1597   CurDAG->RemoveDeadNode(N);
1598 }
1599 
1600 void AArch64DAGToDAGISel::SelectPostLoadLane(SDNode *N, unsigned NumVecs,
1601                                              unsigned Opc) {
1602   SDLoc dl(N);
1603   EVT VT = N->getValueType(0);
1604   bool Narrow = VT.getSizeInBits() == 64;
1605 
1606   // Form a REG_SEQUENCE to force register allocation.
1607   SmallVector<SDValue, 4> Regs(N->op_begin() + 1, N->op_begin() + 1 + NumVecs);
1608 
1609   if (Narrow)
1610     transform(Regs, Regs.begin(),
1611                    WidenVector(*CurDAG));
1612 
1613   SDValue RegSeq = createQTuple(Regs);
1614 
1615   const EVT ResTys[] = {MVT::i64, // Type of the write back register
1616                         RegSeq->getValueType(0), MVT::Other};
1617 
1618   unsigned LaneNo =
1619       cast<ConstantSDNode>(N->getOperand(NumVecs + 1))->getZExtValue();
1620 
1621   SDValue Ops[] = {RegSeq,
1622                    CurDAG->getTargetConstant(LaneNo, dl,
1623                                              MVT::i64),         // Lane Number
1624                    N->getOperand(NumVecs + 2),                  // Base register
1625                    N->getOperand(NumVecs + 3),                  // Incremental
1626                    N->getOperand(0)};
1627   SDNode *Ld = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1628 
1629   // Update uses of the write back register
1630   ReplaceUses(SDValue(N, NumVecs), SDValue(Ld, 0));
1631 
1632   // Update uses of the vector list
1633   SDValue SuperReg = SDValue(Ld, 1);
1634   if (NumVecs == 1) {
1635     ReplaceUses(SDValue(N, 0),
1636                 Narrow ? NarrowVector(SuperReg, *CurDAG) : SuperReg);
1637   } else {
1638     EVT WideVT = RegSeq.getOperand(1)->getValueType(0);
1639     static const unsigned QSubs[] = { AArch64::qsub0, AArch64::qsub1,
1640                                       AArch64::qsub2, AArch64::qsub3 };
1641     for (unsigned i = 0; i < NumVecs; ++i) {
1642       SDValue NV = CurDAG->getTargetExtractSubreg(QSubs[i], dl, WideVT,
1643                                                   SuperReg);
1644       if (Narrow)
1645         NV = NarrowVector(NV, *CurDAG);
1646       ReplaceUses(SDValue(N, i), NV);
1647     }
1648   }
1649 
1650   // Update the Chain
1651   ReplaceUses(SDValue(N, NumVecs + 1), SDValue(Ld, 2));
1652   CurDAG->RemoveDeadNode(N);
1653 }
1654 
1655 void AArch64DAGToDAGISel::SelectStoreLane(SDNode *N, unsigned NumVecs,
1656                                           unsigned Opc) {
1657   SDLoc dl(N);
1658   EVT VT = N->getOperand(2)->getValueType(0);
1659   bool Narrow = VT.getSizeInBits() == 64;
1660 
1661   // Form a REG_SEQUENCE to force register allocation.
1662   SmallVector<SDValue, 4> Regs(N->op_begin() + 2, N->op_begin() + 2 + NumVecs);
1663 
1664   if (Narrow)
1665     transform(Regs, Regs.begin(),
1666                    WidenVector(*CurDAG));
1667 
1668   SDValue RegSeq = createQTuple(Regs);
1669 
1670   unsigned LaneNo =
1671       cast<ConstantSDNode>(N->getOperand(NumVecs + 2))->getZExtValue();
1672 
1673   SDValue Ops[] = {RegSeq, CurDAG->getTargetConstant(LaneNo, dl, MVT::i64),
1674                    N->getOperand(NumVecs + 3), N->getOperand(0)};
1675   SDNode *St = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
1676 
1677   // Transfer memoperands.
1678   MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
1679   CurDAG->setNodeMemRefs(cast<MachineSDNode>(St), {MemOp});
1680 
1681   ReplaceNode(N, St);
1682 }
1683 
1684 void AArch64DAGToDAGISel::SelectPostStoreLane(SDNode *N, unsigned NumVecs,
1685                                               unsigned Opc) {
1686   SDLoc dl(N);
1687   EVT VT = N->getOperand(2)->getValueType(0);
1688   bool Narrow = VT.getSizeInBits() == 64;
1689 
1690   // Form a REG_SEQUENCE to force register allocation.
1691   SmallVector<SDValue, 4> Regs(N->op_begin() + 1, N->op_begin() + 1 + NumVecs);
1692 
1693   if (Narrow)
1694     transform(Regs, Regs.begin(),
1695                    WidenVector(*CurDAG));
1696 
1697   SDValue RegSeq = createQTuple(Regs);
1698 
1699   const EVT ResTys[] = {MVT::i64, // Type of the write back register
1700                         MVT::Other};
1701 
1702   unsigned LaneNo =
1703       cast<ConstantSDNode>(N->getOperand(NumVecs + 1))->getZExtValue();
1704 
1705   SDValue Ops[] = {RegSeq, CurDAG->getTargetConstant(LaneNo, dl, MVT::i64),
1706                    N->getOperand(NumVecs + 2), // Base Register
1707                    N->getOperand(NumVecs + 3), // Incremental
1708                    N->getOperand(0)};
1709   SDNode *St = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
1710 
1711   // Transfer memoperands.
1712   MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
1713   CurDAG->setNodeMemRefs(cast<MachineSDNode>(St), {MemOp});
1714 
1715   ReplaceNode(N, St);
1716 }
1717 
1718 static bool isBitfieldExtractOpFromAnd(SelectionDAG *CurDAG, SDNode *N,
1719                                        unsigned &Opc, SDValue &Opd0,
1720                                        unsigned &LSB, unsigned &MSB,
1721                                        unsigned NumberOfIgnoredLowBits,
1722                                        bool BiggerPattern) {
1723   assert(N->getOpcode() == ISD::AND &&
1724          "N must be a AND operation to call this function");
1725 
1726   EVT VT = N->getValueType(0);
1727 
1728   // Here we can test the type of VT and return false when the type does not
1729   // match, but since it is done prior to that call in the current context
1730   // we turned that into an assert to avoid redundant code.
1731   assert((VT == MVT::i32 || VT == MVT::i64) &&
1732          "Type checking must have been done before calling this function");
1733 
1734   // FIXME: simplify-demanded-bits in DAGCombine will probably have
1735   // changed the AND node to a 32-bit mask operation. We'll have to
1736   // undo that as part of the transform here if we want to catch all
1737   // the opportunities.
1738   // Currently the NumberOfIgnoredLowBits argument helps to recover
1739   // form these situations when matching bigger pattern (bitfield insert).
1740 
1741   // For unsigned extracts, check for a shift right and mask
1742   uint64_t AndImm = 0;
1743   if (!isOpcWithIntImmediate(N, ISD::AND, AndImm))
1744     return false;
1745 
1746   const SDNode *Op0 = N->getOperand(0).getNode();
1747 
1748   // Because of simplify-demanded-bits in DAGCombine, the mask may have been
1749   // simplified. Try to undo that
1750   AndImm |= maskTrailingOnes<uint64_t>(NumberOfIgnoredLowBits);
1751 
1752   // The immediate is a mask of the low bits iff imm & (imm+1) == 0
1753   if (AndImm & (AndImm + 1))
1754     return false;
1755 
1756   bool ClampMSB = false;
1757   uint64_t SrlImm = 0;
1758   // Handle the SRL + ANY_EXTEND case.
1759   if (VT == MVT::i64 && Op0->getOpcode() == ISD::ANY_EXTEND &&
1760       isOpcWithIntImmediate(Op0->getOperand(0).getNode(), ISD::SRL, SrlImm)) {
1761     // Extend the incoming operand of the SRL to 64-bit.
1762     Opd0 = Widen(CurDAG, Op0->getOperand(0).getOperand(0));
1763     // Make sure to clamp the MSB so that we preserve the semantics of the
1764     // original operations.
1765     ClampMSB = true;
1766   } else if (VT == MVT::i32 && Op0->getOpcode() == ISD::TRUNCATE &&
1767              isOpcWithIntImmediate(Op0->getOperand(0).getNode(), ISD::SRL,
1768                                    SrlImm)) {
1769     // If the shift result was truncated, we can still combine them.
1770     Opd0 = Op0->getOperand(0).getOperand(0);
1771 
1772     // Use the type of SRL node.
1773     VT = Opd0->getValueType(0);
1774   } else if (isOpcWithIntImmediate(Op0, ISD::SRL, SrlImm)) {
1775     Opd0 = Op0->getOperand(0);
1776   } else if (BiggerPattern) {
1777     // Let's pretend a 0 shift right has been performed.
1778     // The resulting code will be at least as good as the original one
1779     // plus it may expose more opportunities for bitfield insert pattern.
1780     // FIXME: Currently we limit this to the bigger pattern, because
1781     // some optimizations expect AND and not UBFM.
1782     Opd0 = N->getOperand(0);
1783   } else
1784     return false;
1785 
1786   // Bail out on large immediates. This happens when no proper
1787   // combining/constant folding was performed.
1788   if (!BiggerPattern && (SrlImm <= 0 || SrlImm >= VT.getSizeInBits())) {
1789     LLVM_DEBUG(
1790         (dbgs() << N
1791                 << ": Found large shift immediate, this should not happen\n"));
1792     return false;
1793   }
1794 
1795   LSB = SrlImm;
1796   MSB = SrlImm + (VT == MVT::i32 ? countTrailingOnes<uint32_t>(AndImm)
1797                                  : countTrailingOnes<uint64_t>(AndImm)) -
1798         1;
1799   if (ClampMSB)
1800     // Since we're moving the extend before the right shift operation, we need
1801     // to clamp the MSB to make sure we don't shift in undefined bits instead of
1802     // the zeros which would get shifted in with the original right shift
1803     // operation.
1804     MSB = MSB > 31 ? 31 : MSB;
1805 
1806   Opc = VT == MVT::i32 ? AArch64::UBFMWri : AArch64::UBFMXri;
1807   return true;
1808 }
1809 
1810 static bool isBitfieldExtractOpFromSExtInReg(SDNode *N, unsigned &Opc,
1811                                              SDValue &Opd0, unsigned &Immr,
1812                                              unsigned &Imms) {
1813   assert(N->getOpcode() == ISD::SIGN_EXTEND_INREG);
1814 
1815   EVT VT = N->getValueType(0);
1816   unsigned BitWidth = VT.getSizeInBits();
1817   assert((VT == MVT::i32 || VT == MVT::i64) &&
1818          "Type checking must have been done before calling this function");
1819 
1820   SDValue Op = N->getOperand(0);
1821   if (Op->getOpcode() == ISD::TRUNCATE) {
1822     Op = Op->getOperand(0);
1823     VT = Op->getValueType(0);
1824     BitWidth = VT.getSizeInBits();
1825   }
1826 
1827   uint64_t ShiftImm;
1828   if (!isOpcWithIntImmediate(Op.getNode(), ISD::SRL, ShiftImm) &&
1829       !isOpcWithIntImmediate(Op.getNode(), ISD::SRA, ShiftImm))
1830     return false;
1831 
1832   unsigned Width = cast<VTSDNode>(N->getOperand(1))->getVT().getSizeInBits();
1833   if (ShiftImm + Width > BitWidth)
1834     return false;
1835 
1836   Opc = (VT == MVT::i32) ? AArch64::SBFMWri : AArch64::SBFMXri;
1837   Opd0 = Op.getOperand(0);
1838   Immr = ShiftImm;
1839   Imms = ShiftImm + Width - 1;
1840   return true;
1841 }
1842 
1843 static bool isSeveralBitsExtractOpFromShr(SDNode *N, unsigned &Opc,
1844                                           SDValue &Opd0, unsigned &LSB,
1845                                           unsigned &MSB) {
1846   // We are looking for the following pattern which basically extracts several
1847   // continuous bits from the source value and places it from the LSB of the
1848   // destination value, all other bits of the destination value or set to zero:
1849   //
1850   // Value2 = AND Value, MaskImm
1851   // SRL Value2, ShiftImm
1852   //
1853   // with MaskImm >> ShiftImm to search for the bit width.
1854   //
1855   // This gets selected into a single UBFM:
1856   //
1857   // UBFM Value, ShiftImm, BitWide + SrlImm -1
1858   //
1859 
1860   if (N->getOpcode() != ISD::SRL)
1861     return false;
1862 
1863   uint64_t AndMask = 0;
1864   if (!isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, AndMask))
1865     return false;
1866 
1867   Opd0 = N->getOperand(0).getOperand(0);
1868 
1869   uint64_t SrlImm = 0;
1870   if (!isIntImmediate(N->getOperand(1), SrlImm))
1871     return false;
1872 
1873   // Check whether we really have several bits extract here.
1874   unsigned BitWide = 64 - countLeadingOnes(~(AndMask >> SrlImm));
1875   if (BitWide && isMask_64(AndMask >> SrlImm)) {
1876     if (N->getValueType(0) == MVT::i32)
1877       Opc = AArch64::UBFMWri;
1878     else
1879       Opc = AArch64::UBFMXri;
1880 
1881     LSB = SrlImm;
1882     MSB = BitWide + SrlImm - 1;
1883     return true;
1884   }
1885 
1886   return false;
1887 }
1888 
1889 static bool isBitfieldExtractOpFromShr(SDNode *N, unsigned &Opc, SDValue &Opd0,
1890                                        unsigned &Immr, unsigned &Imms,
1891                                        bool BiggerPattern) {
1892   assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
1893          "N must be a SHR/SRA operation to call this function");
1894 
1895   EVT VT = N->getValueType(0);
1896 
1897   // Here we can test the type of VT and return false when the type does not
1898   // match, but since it is done prior to that call in the current context
1899   // we turned that into an assert to avoid redundant code.
1900   assert((VT == MVT::i32 || VT == MVT::i64) &&
1901          "Type checking must have been done before calling this function");
1902 
1903   // Check for AND + SRL doing several bits extract.
1904   if (isSeveralBitsExtractOpFromShr(N, Opc, Opd0, Immr, Imms))
1905     return true;
1906 
1907   // We're looking for a shift of a shift.
1908   uint64_t ShlImm = 0;
1909   uint64_t TruncBits = 0;
1910   if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SHL, ShlImm)) {
1911     Opd0 = N->getOperand(0).getOperand(0);
1912   } else if (VT == MVT::i32 && N->getOpcode() == ISD::SRL &&
1913              N->getOperand(0).getNode()->getOpcode() == ISD::TRUNCATE) {
1914     // We are looking for a shift of truncate. Truncate from i64 to i32 could
1915     // be considered as setting high 32 bits as zero. Our strategy here is to
1916     // always generate 64bit UBFM. This consistency will help the CSE pass
1917     // later find more redundancy.
1918     Opd0 = N->getOperand(0).getOperand(0);
1919     TruncBits = Opd0->getValueType(0).getSizeInBits() - VT.getSizeInBits();
1920     VT = Opd0.getValueType();
1921     assert(VT == MVT::i64 && "the promoted type should be i64");
1922   } else if (BiggerPattern) {
1923     // Let's pretend a 0 shift left has been performed.
1924     // FIXME: Currently we limit this to the bigger pattern case,
1925     // because some optimizations expect AND and not UBFM
1926     Opd0 = N->getOperand(0);
1927   } else
1928     return false;
1929 
1930   // Missing combines/constant folding may have left us with strange
1931   // constants.
1932   if (ShlImm >= VT.getSizeInBits()) {
1933     LLVM_DEBUG(
1934         (dbgs() << N
1935                 << ": Found large shift immediate, this should not happen\n"));
1936     return false;
1937   }
1938 
1939   uint64_t SrlImm = 0;
1940   if (!isIntImmediate(N->getOperand(1), SrlImm))
1941     return false;
1942 
1943   assert(SrlImm > 0 && SrlImm < VT.getSizeInBits() &&
1944          "bad amount in shift node!");
1945   int immr = SrlImm - ShlImm;
1946   Immr = immr < 0 ? immr + VT.getSizeInBits() : immr;
1947   Imms = VT.getSizeInBits() - ShlImm - TruncBits - 1;
1948   // SRA requires a signed extraction
1949   if (VT == MVT::i32)
1950     Opc = N->getOpcode() == ISD::SRA ? AArch64::SBFMWri : AArch64::UBFMWri;
1951   else
1952     Opc = N->getOpcode() == ISD::SRA ? AArch64::SBFMXri : AArch64::UBFMXri;
1953   return true;
1954 }
1955 
1956 bool AArch64DAGToDAGISel::tryBitfieldExtractOpFromSExt(SDNode *N) {
1957   assert(N->getOpcode() == ISD::SIGN_EXTEND);
1958 
1959   EVT VT = N->getValueType(0);
1960   EVT NarrowVT = N->getOperand(0)->getValueType(0);
1961   if (VT != MVT::i64 || NarrowVT != MVT::i32)
1962     return false;
1963 
1964   uint64_t ShiftImm;
1965   SDValue Op = N->getOperand(0);
1966   if (!isOpcWithIntImmediate(Op.getNode(), ISD::SRA, ShiftImm))
1967     return false;
1968 
1969   SDLoc dl(N);
1970   // Extend the incoming operand of the shift to 64-bits.
1971   SDValue Opd0 = Widen(CurDAG, Op.getOperand(0));
1972   unsigned Immr = ShiftImm;
1973   unsigned Imms = NarrowVT.getSizeInBits() - 1;
1974   SDValue Ops[] = {Opd0, CurDAG->getTargetConstant(Immr, dl, VT),
1975                    CurDAG->getTargetConstant(Imms, dl, VT)};
1976   CurDAG->SelectNodeTo(N, AArch64::SBFMXri, VT, Ops);
1977   return true;
1978 }
1979 
1980 /// Try to form fcvtl2 instructions from a floating-point extend of a high-half
1981 /// extract of a subvector.
1982 bool AArch64DAGToDAGISel::tryHighFPExt(SDNode *N) {
1983   assert(N->getOpcode() == ISD::FP_EXTEND);
1984 
1985   // There are 2 forms of fcvtl2 - extend to double or extend to float.
1986   SDValue Extract = N->getOperand(0);
1987   EVT VT = N->getValueType(0);
1988   EVT NarrowVT = Extract.getValueType();
1989   if ((VT != MVT::v2f64 || NarrowVT != MVT::v2f32) &&
1990       (VT != MVT::v4f32 || NarrowVT != MVT::v4f16))
1991     return false;
1992 
1993   // Optionally look past a bitcast.
1994   Extract = peekThroughBitcasts(Extract);
1995   if (Extract.getOpcode() != ISD::EXTRACT_SUBVECTOR)
1996     return false;
1997 
1998   // Match extract from start of high half index.
1999   // Example: v8i16 -> v4i16 means the extract must begin at index 4.
2000   unsigned ExtractIndex = Extract.getConstantOperandVal(1);
2001   if (ExtractIndex != Extract.getValueType().getVectorNumElements())
2002     return false;
2003 
2004   auto Opcode = VT == MVT::v2f64 ? AArch64::FCVTLv4i32 : AArch64::FCVTLv8i16;
2005   CurDAG->SelectNodeTo(N, Opcode, VT, Extract.getOperand(0));
2006   return true;
2007 }
2008 
2009 static bool isBitfieldExtractOp(SelectionDAG *CurDAG, SDNode *N, unsigned &Opc,
2010                                 SDValue &Opd0, unsigned &Immr, unsigned &Imms,
2011                                 unsigned NumberOfIgnoredLowBits = 0,
2012                                 bool BiggerPattern = false) {
2013   if (N->getValueType(0) != MVT::i32 && N->getValueType(0) != MVT::i64)
2014     return false;
2015 
2016   switch (N->getOpcode()) {
2017   default:
2018     if (!N->isMachineOpcode())
2019       return false;
2020     break;
2021   case ISD::AND:
2022     return isBitfieldExtractOpFromAnd(CurDAG, N, Opc, Opd0, Immr, Imms,
2023                                       NumberOfIgnoredLowBits, BiggerPattern);
2024   case ISD::SRL:
2025   case ISD::SRA:
2026     return isBitfieldExtractOpFromShr(N, Opc, Opd0, Immr, Imms, BiggerPattern);
2027 
2028   case ISD::SIGN_EXTEND_INREG:
2029     return isBitfieldExtractOpFromSExtInReg(N, Opc, Opd0, Immr, Imms);
2030   }
2031 
2032   unsigned NOpc = N->getMachineOpcode();
2033   switch (NOpc) {
2034   default:
2035     return false;
2036   case AArch64::SBFMWri:
2037   case AArch64::UBFMWri:
2038   case AArch64::SBFMXri:
2039   case AArch64::UBFMXri:
2040     Opc = NOpc;
2041     Opd0 = N->getOperand(0);
2042     Immr = cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
2043     Imms = cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
2044     return true;
2045   }
2046   // Unreachable
2047   return false;
2048 }
2049 
2050 bool AArch64DAGToDAGISel::tryBitfieldExtractOp(SDNode *N) {
2051   unsigned Opc, Immr, Imms;
2052   SDValue Opd0;
2053   if (!isBitfieldExtractOp(CurDAG, N, Opc, Opd0, Immr, Imms))
2054     return false;
2055 
2056   EVT VT = N->getValueType(0);
2057   SDLoc dl(N);
2058 
2059   // If the bit extract operation is 64bit but the original type is 32bit, we
2060   // need to add one EXTRACT_SUBREG.
2061   if ((Opc == AArch64::SBFMXri || Opc == AArch64::UBFMXri) && VT == MVT::i32) {
2062     SDValue Ops64[] = {Opd0, CurDAG->getTargetConstant(Immr, dl, MVT::i64),
2063                        CurDAG->getTargetConstant(Imms, dl, MVT::i64)};
2064 
2065     SDNode *BFM = CurDAG->getMachineNode(Opc, dl, MVT::i64, Ops64);
2066     SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, dl, MVT::i32);
2067     ReplaceNode(N, CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
2068                                           MVT::i32, SDValue(BFM, 0), SubReg));
2069     return true;
2070   }
2071 
2072   SDValue Ops[] = {Opd0, CurDAG->getTargetConstant(Immr, dl, VT),
2073                    CurDAG->getTargetConstant(Imms, dl, VT)};
2074   CurDAG->SelectNodeTo(N, Opc, VT, Ops);
2075   return true;
2076 }
2077 
2078 /// Does DstMask form a complementary pair with the mask provided by
2079 /// BitsToBeInserted, suitable for use in a BFI instruction. Roughly speaking,
2080 /// this asks whether DstMask zeroes precisely those bits that will be set by
2081 /// the other half.
2082 static bool isBitfieldDstMask(uint64_t DstMask, const APInt &BitsToBeInserted,
2083                               unsigned NumberOfIgnoredHighBits, EVT VT) {
2084   assert((VT == MVT::i32 || VT == MVT::i64) &&
2085          "i32 or i64 mask type expected!");
2086   unsigned BitWidth = VT.getSizeInBits() - NumberOfIgnoredHighBits;
2087 
2088   APInt SignificantDstMask = APInt(BitWidth, DstMask);
2089   APInt SignificantBitsToBeInserted = BitsToBeInserted.zextOrTrunc(BitWidth);
2090 
2091   return (SignificantDstMask & SignificantBitsToBeInserted) == 0 &&
2092          (SignificantDstMask | SignificantBitsToBeInserted).isAllOnesValue();
2093 }
2094 
2095 // Look for bits that will be useful for later uses.
2096 // A bit is consider useless as soon as it is dropped and never used
2097 // before it as been dropped.
2098 // E.g., looking for useful bit of x
2099 // 1. y = x & 0x7
2100 // 2. z = y >> 2
2101 // After #1, x useful bits are 0x7, then the useful bits of x, live through
2102 // y.
2103 // After #2, the useful bits of x are 0x4.
2104 // However, if x is used on an unpredicatable instruction, then all its bits
2105 // are useful.
2106 // E.g.
2107 // 1. y = x & 0x7
2108 // 2. z = y >> 2
2109 // 3. str x, [@x]
2110 static void getUsefulBits(SDValue Op, APInt &UsefulBits, unsigned Depth = 0);
2111 
2112 static void getUsefulBitsFromAndWithImmediate(SDValue Op, APInt &UsefulBits,
2113                                               unsigned Depth) {
2114   uint64_t Imm =
2115       cast<const ConstantSDNode>(Op.getOperand(1).getNode())->getZExtValue();
2116   Imm = AArch64_AM::decodeLogicalImmediate(Imm, UsefulBits.getBitWidth());
2117   UsefulBits &= APInt(UsefulBits.getBitWidth(), Imm);
2118   getUsefulBits(Op, UsefulBits, Depth + 1);
2119 }
2120 
2121 static void getUsefulBitsFromBitfieldMoveOpd(SDValue Op, APInt &UsefulBits,
2122                                              uint64_t Imm, uint64_t MSB,
2123                                              unsigned Depth) {
2124   // inherit the bitwidth value
2125   APInt OpUsefulBits(UsefulBits);
2126   OpUsefulBits = 1;
2127 
2128   if (MSB >= Imm) {
2129     OpUsefulBits <<= MSB - Imm + 1;
2130     --OpUsefulBits;
2131     // The interesting part will be in the lower part of the result
2132     getUsefulBits(Op, OpUsefulBits, Depth + 1);
2133     // The interesting part was starting at Imm in the argument
2134     OpUsefulBits <<= Imm;
2135   } else {
2136     OpUsefulBits <<= MSB + 1;
2137     --OpUsefulBits;
2138     // The interesting part will be shifted in the result
2139     OpUsefulBits <<= OpUsefulBits.getBitWidth() - Imm;
2140     getUsefulBits(Op, OpUsefulBits, Depth + 1);
2141     // The interesting part was at zero in the argument
2142     OpUsefulBits.lshrInPlace(OpUsefulBits.getBitWidth() - Imm);
2143   }
2144 
2145   UsefulBits &= OpUsefulBits;
2146 }
2147 
2148 static void getUsefulBitsFromUBFM(SDValue Op, APInt &UsefulBits,
2149                                   unsigned Depth) {
2150   uint64_t Imm =
2151       cast<const ConstantSDNode>(Op.getOperand(1).getNode())->getZExtValue();
2152   uint64_t MSB =
2153       cast<const ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
2154 
2155   getUsefulBitsFromBitfieldMoveOpd(Op, UsefulBits, Imm, MSB, Depth);
2156 }
2157 
2158 static void getUsefulBitsFromOrWithShiftedReg(SDValue Op, APInt &UsefulBits,
2159                                               unsigned Depth) {
2160   uint64_t ShiftTypeAndValue =
2161       cast<const ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
2162   APInt Mask(UsefulBits);
2163   Mask.clearAllBits();
2164   Mask.flipAllBits();
2165 
2166   if (AArch64_AM::getShiftType(ShiftTypeAndValue) == AArch64_AM::LSL) {
2167     // Shift Left
2168     uint64_t ShiftAmt = AArch64_AM::getShiftValue(ShiftTypeAndValue);
2169     Mask <<= ShiftAmt;
2170     getUsefulBits(Op, Mask, Depth + 1);
2171     Mask.lshrInPlace(ShiftAmt);
2172   } else if (AArch64_AM::getShiftType(ShiftTypeAndValue) == AArch64_AM::LSR) {
2173     // Shift Right
2174     // We do not handle AArch64_AM::ASR, because the sign will change the
2175     // number of useful bits
2176     uint64_t ShiftAmt = AArch64_AM::getShiftValue(ShiftTypeAndValue);
2177     Mask.lshrInPlace(ShiftAmt);
2178     getUsefulBits(Op, Mask, Depth + 1);
2179     Mask <<= ShiftAmt;
2180   } else
2181     return;
2182 
2183   UsefulBits &= Mask;
2184 }
2185 
2186 static void getUsefulBitsFromBFM(SDValue Op, SDValue Orig, APInt &UsefulBits,
2187                                  unsigned Depth) {
2188   uint64_t Imm =
2189       cast<const ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue();
2190   uint64_t MSB =
2191       cast<const ConstantSDNode>(Op.getOperand(3).getNode())->getZExtValue();
2192 
2193   APInt OpUsefulBits(UsefulBits);
2194   OpUsefulBits = 1;
2195 
2196   APInt ResultUsefulBits(UsefulBits.getBitWidth(), 0);
2197   ResultUsefulBits.flipAllBits();
2198   APInt Mask(UsefulBits.getBitWidth(), 0);
2199 
2200   getUsefulBits(Op, ResultUsefulBits, Depth + 1);
2201 
2202   if (MSB >= Imm) {
2203     // The instruction is a BFXIL.
2204     uint64_t Width = MSB - Imm + 1;
2205     uint64_t LSB = Imm;
2206 
2207     OpUsefulBits <<= Width;
2208     --OpUsefulBits;
2209 
2210     if (Op.getOperand(1) == Orig) {
2211       // Copy the low bits from the result to bits starting from LSB.
2212       Mask = ResultUsefulBits & OpUsefulBits;
2213       Mask <<= LSB;
2214     }
2215 
2216     if (Op.getOperand(0) == Orig)
2217       // Bits starting from LSB in the input contribute to the result.
2218       Mask |= (ResultUsefulBits & ~OpUsefulBits);
2219   } else {
2220     // The instruction is a BFI.
2221     uint64_t Width = MSB + 1;
2222     uint64_t LSB = UsefulBits.getBitWidth() - Imm;
2223 
2224     OpUsefulBits <<= Width;
2225     --OpUsefulBits;
2226     OpUsefulBits <<= LSB;
2227 
2228     if (Op.getOperand(1) == Orig) {
2229       // Copy the bits from the result to the zero bits.
2230       Mask = ResultUsefulBits & OpUsefulBits;
2231       Mask.lshrInPlace(LSB);
2232     }
2233 
2234     if (Op.getOperand(0) == Orig)
2235       Mask |= (ResultUsefulBits & ~OpUsefulBits);
2236   }
2237 
2238   UsefulBits &= Mask;
2239 }
2240 
2241 static void getUsefulBitsForUse(SDNode *UserNode, APInt &UsefulBits,
2242                                 SDValue Orig, unsigned Depth) {
2243 
2244   // Users of this node should have already been instruction selected
2245   // FIXME: Can we turn that into an assert?
2246   if (!UserNode->isMachineOpcode())
2247     return;
2248 
2249   switch (UserNode->getMachineOpcode()) {
2250   default:
2251     return;
2252   case AArch64::ANDSWri:
2253   case AArch64::ANDSXri:
2254   case AArch64::ANDWri:
2255   case AArch64::ANDXri:
2256     // We increment Depth only when we call the getUsefulBits
2257     return getUsefulBitsFromAndWithImmediate(SDValue(UserNode, 0), UsefulBits,
2258                                              Depth);
2259   case AArch64::UBFMWri:
2260   case AArch64::UBFMXri:
2261     return getUsefulBitsFromUBFM(SDValue(UserNode, 0), UsefulBits, Depth);
2262 
2263   case AArch64::ORRWrs:
2264   case AArch64::ORRXrs:
2265     if (UserNode->getOperand(1) != Orig)
2266       return;
2267     return getUsefulBitsFromOrWithShiftedReg(SDValue(UserNode, 0), UsefulBits,
2268                                              Depth);
2269   case AArch64::BFMWri:
2270   case AArch64::BFMXri:
2271     return getUsefulBitsFromBFM(SDValue(UserNode, 0), Orig, UsefulBits, Depth);
2272 
2273   case AArch64::STRBBui:
2274   case AArch64::STURBBi:
2275     if (UserNode->getOperand(0) != Orig)
2276       return;
2277     UsefulBits &= APInt(UsefulBits.getBitWidth(), 0xff);
2278     return;
2279 
2280   case AArch64::STRHHui:
2281   case AArch64::STURHHi:
2282     if (UserNode->getOperand(0) != Orig)
2283       return;
2284     UsefulBits &= APInt(UsefulBits.getBitWidth(), 0xffff);
2285     return;
2286   }
2287 }
2288 
2289 static void getUsefulBits(SDValue Op, APInt &UsefulBits, unsigned Depth) {
2290   if (Depth >= SelectionDAG::MaxRecursionDepth)
2291     return;
2292   // Initialize UsefulBits
2293   if (!Depth) {
2294     unsigned Bitwidth = Op.getScalarValueSizeInBits();
2295     // At the beginning, assume every produced bits is useful
2296     UsefulBits = APInt(Bitwidth, 0);
2297     UsefulBits.flipAllBits();
2298   }
2299   APInt UsersUsefulBits(UsefulBits.getBitWidth(), 0);
2300 
2301   for (SDNode *Node : Op.getNode()->uses()) {
2302     // A use cannot produce useful bits
2303     APInt UsefulBitsForUse = APInt(UsefulBits);
2304     getUsefulBitsForUse(Node, UsefulBitsForUse, Op, Depth);
2305     UsersUsefulBits |= UsefulBitsForUse;
2306   }
2307   // UsefulBits contains the produced bits that are meaningful for the
2308   // current definition, thus a user cannot make a bit meaningful at
2309   // this point
2310   UsefulBits &= UsersUsefulBits;
2311 }
2312 
2313 /// Create a machine node performing a notional SHL of Op by ShlAmount. If
2314 /// ShlAmount is negative, do a (logical) right-shift instead. If ShlAmount is
2315 /// 0, return Op unchanged.
2316 static SDValue getLeftShift(SelectionDAG *CurDAG, SDValue Op, int ShlAmount) {
2317   if (ShlAmount == 0)
2318     return Op;
2319 
2320   EVT VT = Op.getValueType();
2321   SDLoc dl(Op);
2322   unsigned BitWidth = VT.getSizeInBits();
2323   unsigned UBFMOpc = BitWidth == 32 ? AArch64::UBFMWri : AArch64::UBFMXri;
2324 
2325   SDNode *ShiftNode;
2326   if (ShlAmount > 0) {
2327     // LSL wD, wN, #Amt == UBFM wD, wN, #32-Amt, #31-Amt
2328     ShiftNode = CurDAG->getMachineNode(
2329         UBFMOpc, dl, VT, Op,
2330         CurDAG->getTargetConstant(BitWidth - ShlAmount, dl, VT),
2331         CurDAG->getTargetConstant(BitWidth - 1 - ShlAmount, dl, VT));
2332   } else {
2333     // LSR wD, wN, #Amt == UBFM wD, wN, #Amt, #32-1
2334     assert(ShlAmount < 0 && "expected right shift");
2335     int ShrAmount = -ShlAmount;
2336     ShiftNode = CurDAG->getMachineNode(
2337         UBFMOpc, dl, VT, Op, CurDAG->getTargetConstant(ShrAmount, dl, VT),
2338         CurDAG->getTargetConstant(BitWidth - 1, dl, VT));
2339   }
2340 
2341   return SDValue(ShiftNode, 0);
2342 }
2343 
2344 /// Does this tree qualify as an attempt to move a bitfield into position,
2345 /// essentially "(and (shl VAL, N), Mask)".
2346 static bool isBitfieldPositioningOp(SelectionDAG *CurDAG, SDValue Op,
2347                                     bool BiggerPattern,
2348                                     SDValue &Src, int &ShiftAmount,
2349                                     int &MaskWidth) {
2350   EVT VT = Op.getValueType();
2351   unsigned BitWidth = VT.getSizeInBits();
2352   (void)BitWidth;
2353   assert(BitWidth == 32 || BitWidth == 64);
2354 
2355   KnownBits Known = CurDAG->computeKnownBits(Op);
2356 
2357   // Non-zero in the sense that they're not provably zero, which is the key
2358   // point if we want to use this value
2359   uint64_t NonZeroBits = (~Known.Zero).getZExtValue();
2360 
2361   // Discard a constant AND mask if present. It's safe because the node will
2362   // already have been factored into the computeKnownBits calculation above.
2363   uint64_t AndImm;
2364   if (isOpcWithIntImmediate(Op.getNode(), ISD::AND, AndImm)) {
2365     assert((~APInt(BitWidth, AndImm) & ~Known.Zero) == 0);
2366     Op = Op.getOperand(0);
2367   }
2368 
2369   // Don't match if the SHL has more than one use, since then we'll end up
2370   // generating SHL+UBFIZ instead of just keeping SHL+AND.
2371   if (!BiggerPattern && !Op.hasOneUse())
2372     return false;
2373 
2374   uint64_t ShlImm;
2375   if (!isOpcWithIntImmediate(Op.getNode(), ISD::SHL, ShlImm))
2376     return false;
2377   Op = Op.getOperand(0);
2378 
2379   if (!isShiftedMask_64(NonZeroBits))
2380     return false;
2381 
2382   ShiftAmount = countTrailingZeros(NonZeroBits);
2383   MaskWidth = countTrailingOnes(NonZeroBits >> ShiftAmount);
2384 
2385   // BFI encompasses sufficiently many nodes that it's worth inserting an extra
2386   // LSL/LSR if the mask in NonZeroBits doesn't quite match up with the ISD::SHL
2387   // amount.  BiggerPattern is true when this pattern is being matched for BFI,
2388   // BiggerPattern is false when this pattern is being matched for UBFIZ, in
2389   // which case it is not profitable to insert an extra shift.
2390   if (ShlImm - ShiftAmount != 0 && !BiggerPattern)
2391     return false;
2392   Src = getLeftShift(CurDAG, Op, ShlImm - ShiftAmount);
2393 
2394   return true;
2395 }
2396 
2397 static bool isShiftedMask(uint64_t Mask, EVT VT) {
2398   assert(VT == MVT::i32 || VT == MVT::i64);
2399   if (VT == MVT::i32)
2400     return isShiftedMask_32(Mask);
2401   return isShiftedMask_64(Mask);
2402 }
2403 
2404 // Generate a BFI/BFXIL from 'or (and X, MaskImm), OrImm' iff the value being
2405 // inserted only sets known zero bits.
2406 static bool tryBitfieldInsertOpFromOrAndImm(SDNode *N, SelectionDAG *CurDAG) {
2407   assert(N->getOpcode() == ISD::OR && "Expect a OR operation");
2408 
2409   EVT VT = N->getValueType(0);
2410   if (VT != MVT::i32 && VT != MVT::i64)
2411     return false;
2412 
2413   unsigned BitWidth = VT.getSizeInBits();
2414 
2415   uint64_t OrImm;
2416   if (!isOpcWithIntImmediate(N, ISD::OR, OrImm))
2417     return false;
2418 
2419   // Skip this transformation if the ORR immediate can be encoded in the ORR.
2420   // Otherwise, we'll trade an AND+ORR for ORR+BFI/BFXIL, which is most likely
2421   // performance neutral.
2422   if (AArch64_AM::isLogicalImmediate(OrImm, BitWidth))
2423     return false;
2424 
2425   uint64_t MaskImm;
2426   SDValue And = N->getOperand(0);
2427   // Must be a single use AND with an immediate operand.
2428   if (!And.hasOneUse() ||
2429       !isOpcWithIntImmediate(And.getNode(), ISD::AND, MaskImm))
2430     return false;
2431 
2432   // Compute the Known Zero for the AND as this allows us to catch more general
2433   // cases than just looking for AND with imm.
2434   KnownBits Known = CurDAG->computeKnownBits(And);
2435 
2436   // Non-zero in the sense that they're not provably zero, which is the key
2437   // point if we want to use this value.
2438   uint64_t NotKnownZero = (~Known.Zero).getZExtValue();
2439 
2440   // The KnownZero mask must be a shifted mask (e.g., 1110..011, 11100..00).
2441   if (!isShiftedMask(Known.Zero.getZExtValue(), VT))
2442     return false;
2443 
2444   // The bits being inserted must only set those bits that are known to be zero.
2445   if ((OrImm & NotKnownZero) != 0) {
2446     // FIXME:  It's okay if the OrImm sets NotKnownZero bits to 1, but we don't
2447     // currently handle this case.
2448     return false;
2449   }
2450 
2451   // BFI/BFXIL dst, src, #lsb, #width.
2452   int LSB = countTrailingOnes(NotKnownZero);
2453   int Width = BitWidth - APInt(BitWidth, NotKnownZero).countPopulation();
2454 
2455   // BFI/BFXIL is an alias of BFM, so translate to BFM operands.
2456   unsigned ImmR = (BitWidth - LSB) % BitWidth;
2457   unsigned ImmS = Width - 1;
2458 
2459   // If we're creating a BFI instruction avoid cases where we need more
2460   // instructions to materialize the BFI constant as compared to the original
2461   // ORR.  A BFXIL will use the same constant as the original ORR, so the code
2462   // should be no worse in this case.
2463   bool IsBFI = LSB != 0;
2464   uint64_t BFIImm = OrImm >> LSB;
2465   if (IsBFI && !AArch64_AM::isLogicalImmediate(BFIImm, BitWidth)) {
2466     // We have a BFI instruction and we know the constant can't be materialized
2467     // with a ORR-immediate with the zero register.
2468     unsigned OrChunks = 0, BFIChunks = 0;
2469     for (unsigned Shift = 0; Shift < BitWidth; Shift += 16) {
2470       if (((OrImm >> Shift) & 0xFFFF) != 0)
2471         ++OrChunks;
2472       if (((BFIImm >> Shift) & 0xFFFF) != 0)
2473         ++BFIChunks;
2474     }
2475     if (BFIChunks > OrChunks)
2476       return false;
2477   }
2478 
2479   // Materialize the constant to be inserted.
2480   SDLoc DL(N);
2481   unsigned MOVIOpc = VT == MVT::i32 ? AArch64::MOVi32imm : AArch64::MOVi64imm;
2482   SDNode *MOVI = CurDAG->getMachineNode(
2483       MOVIOpc, DL, VT, CurDAG->getTargetConstant(BFIImm, DL, VT));
2484 
2485   // Create the BFI/BFXIL instruction.
2486   SDValue Ops[] = {And.getOperand(0), SDValue(MOVI, 0),
2487                    CurDAG->getTargetConstant(ImmR, DL, VT),
2488                    CurDAG->getTargetConstant(ImmS, DL, VT)};
2489   unsigned Opc = (VT == MVT::i32) ? AArch64::BFMWri : AArch64::BFMXri;
2490   CurDAG->SelectNodeTo(N, Opc, VT, Ops);
2491   return true;
2492 }
2493 
2494 static bool tryBitfieldInsertOpFromOr(SDNode *N, const APInt &UsefulBits,
2495                                       SelectionDAG *CurDAG) {
2496   assert(N->getOpcode() == ISD::OR && "Expect a OR operation");
2497 
2498   EVT VT = N->getValueType(0);
2499   if (VT != MVT::i32 && VT != MVT::i64)
2500     return false;
2501 
2502   unsigned BitWidth = VT.getSizeInBits();
2503 
2504   // Because of simplify-demanded-bits in DAGCombine, involved masks may not
2505   // have the expected shape. Try to undo that.
2506 
2507   unsigned NumberOfIgnoredLowBits = UsefulBits.countTrailingZeros();
2508   unsigned NumberOfIgnoredHighBits = UsefulBits.countLeadingZeros();
2509 
2510   // Given a OR operation, check if we have the following pattern
2511   // ubfm c, b, imm, imm2 (or something that does the same jobs, see
2512   //                       isBitfieldExtractOp)
2513   // d = e & mask2 ; where mask is a binary sequence of 1..10..0 and
2514   //                 countTrailingZeros(mask2) == imm2 - imm + 1
2515   // f = d | c
2516   // if yes, replace the OR instruction with:
2517   // f = BFM Opd0, Opd1, LSB, MSB ; where LSB = imm, and MSB = imm2
2518 
2519   // OR is commutative, check all combinations of operand order and values of
2520   // BiggerPattern, i.e.
2521   //     Opd0, Opd1, BiggerPattern=false
2522   //     Opd1, Opd0, BiggerPattern=false
2523   //     Opd0, Opd1, BiggerPattern=true
2524   //     Opd1, Opd0, BiggerPattern=true
2525   // Several of these combinations may match, so check with BiggerPattern=false
2526   // first since that will produce better results by matching more instructions
2527   // and/or inserting fewer extra instructions.
2528   for (int I = 0; I < 4; ++I) {
2529 
2530     SDValue Dst, Src;
2531     unsigned ImmR, ImmS;
2532     bool BiggerPattern = I / 2;
2533     SDValue OrOpd0Val = N->getOperand(I % 2);
2534     SDNode *OrOpd0 = OrOpd0Val.getNode();
2535     SDValue OrOpd1Val = N->getOperand((I + 1) % 2);
2536     SDNode *OrOpd1 = OrOpd1Val.getNode();
2537 
2538     unsigned BFXOpc;
2539     int DstLSB, Width;
2540     if (isBitfieldExtractOp(CurDAG, OrOpd0, BFXOpc, Src, ImmR, ImmS,
2541                             NumberOfIgnoredLowBits, BiggerPattern)) {
2542       // Check that the returned opcode is compatible with the pattern,
2543       // i.e., same type and zero extended (U and not S)
2544       if ((BFXOpc != AArch64::UBFMXri && VT == MVT::i64) ||
2545           (BFXOpc != AArch64::UBFMWri && VT == MVT::i32))
2546         continue;
2547 
2548       // Compute the width of the bitfield insertion
2549       DstLSB = 0;
2550       Width = ImmS - ImmR + 1;
2551       // FIXME: This constraint is to catch bitfield insertion we may
2552       // want to widen the pattern if we want to grab general bitfied
2553       // move case
2554       if (Width <= 0)
2555         continue;
2556 
2557       // If the mask on the insertee is correct, we have a BFXIL operation. We
2558       // can share the ImmR and ImmS values from the already-computed UBFM.
2559     } else if (isBitfieldPositioningOp(CurDAG, OrOpd0Val,
2560                                        BiggerPattern,
2561                                        Src, DstLSB, Width)) {
2562       ImmR = (BitWidth - DstLSB) % BitWidth;
2563       ImmS = Width - 1;
2564     } else
2565       continue;
2566 
2567     // Check the second part of the pattern
2568     EVT VT = OrOpd1Val.getValueType();
2569     assert((VT == MVT::i32 || VT == MVT::i64) && "unexpected OR operand");
2570 
2571     // Compute the Known Zero for the candidate of the first operand.
2572     // This allows to catch more general case than just looking for
2573     // AND with imm. Indeed, simplify-demanded-bits may have removed
2574     // the AND instruction because it proves it was useless.
2575     KnownBits Known = CurDAG->computeKnownBits(OrOpd1Val);
2576 
2577     // Check if there is enough room for the second operand to appear
2578     // in the first one
2579     APInt BitsToBeInserted =
2580         APInt::getBitsSet(Known.getBitWidth(), DstLSB, DstLSB + Width);
2581 
2582     if ((BitsToBeInserted & ~Known.Zero) != 0)
2583       continue;
2584 
2585     // Set the first operand
2586     uint64_t Imm;
2587     if (isOpcWithIntImmediate(OrOpd1, ISD::AND, Imm) &&
2588         isBitfieldDstMask(Imm, BitsToBeInserted, NumberOfIgnoredHighBits, VT))
2589       // In that case, we can eliminate the AND
2590       Dst = OrOpd1->getOperand(0);
2591     else
2592       // Maybe the AND has been removed by simplify-demanded-bits
2593       // or is useful because it discards more bits
2594       Dst = OrOpd1Val;
2595 
2596     // both parts match
2597     SDLoc DL(N);
2598     SDValue Ops[] = {Dst, Src, CurDAG->getTargetConstant(ImmR, DL, VT),
2599                      CurDAG->getTargetConstant(ImmS, DL, VT)};
2600     unsigned Opc = (VT == MVT::i32) ? AArch64::BFMWri : AArch64::BFMXri;
2601     CurDAG->SelectNodeTo(N, Opc, VT, Ops);
2602     return true;
2603   }
2604 
2605   // Generate a BFXIL from 'or (and X, Mask0Imm), (and Y, Mask1Imm)' iff
2606   // Mask0Imm and ~Mask1Imm are equivalent and one of the MaskImms is a shifted
2607   // mask (e.g., 0x000ffff0).
2608   uint64_t Mask0Imm, Mask1Imm;
2609   SDValue And0 = N->getOperand(0);
2610   SDValue And1 = N->getOperand(1);
2611   if (And0.hasOneUse() && And1.hasOneUse() &&
2612       isOpcWithIntImmediate(And0.getNode(), ISD::AND, Mask0Imm) &&
2613       isOpcWithIntImmediate(And1.getNode(), ISD::AND, Mask1Imm) &&
2614       APInt(BitWidth, Mask0Imm) == ~APInt(BitWidth, Mask1Imm) &&
2615       (isShiftedMask(Mask0Imm, VT) || isShiftedMask(Mask1Imm, VT))) {
2616 
2617     // ORR is commutative, so canonicalize to the form 'or (and X, Mask0Imm),
2618     // (and Y, Mask1Imm)' where Mask1Imm is the shifted mask masking off the
2619     // bits to be inserted.
2620     if (isShiftedMask(Mask0Imm, VT)) {
2621       std::swap(And0, And1);
2622       std::swap(Mask0Imm, Mask1Imm);
2623     }
2624 
2625     SDValue Src = And1->getOperand(0);
2626     SDValue Dst = And0->getOperand(0);
2627     unsigned LSB = countTrailingZeros(Mask1Imm);
2628     int Width = BitWidth - APInt(BitWidth, Mask0Imm).countPopulation();
2629 
2630     // The BFXIL inserts the low-order bits from a source register, so right
2631     // shift the needed bits into place.
2632     SDLoc DL(N);
2633     unsigned ShiftOpc = (VT == MVT::i32) ? AArch64::UBFMWri : AArch64::UBFMXri;
2634     SDNode *LSR = CurDAG->getMachineNode(
2635         ShiftOpc, DL, VT, Src, CurDAG->getTargetConstant(LSB, DL, VT),
2636         CurDAG->getTargetConstant(BitWidth - 1, DL, VT));
2637 
2638     // BFXIL is an alias of BFM, so translate to BFM operands.
2639     unsigned ImmR = (BitWidth - LSB) % BitWidth;
2640     unsigned ImmS = Width - 1;
2641 
2642     // Create the BFXIL instruction.
2643     SDValue Ops[] = {Dst, SDValue(LSR, 0),
2644                      CurDAG->getTargetConstant(ImmR, DL, VT),
2645                      CurDAG->getTargetConstant(ImmS, DL, VT)};
2646     unsigned Opc = (VT == MVT::i32) ? AArch64::BFMWri : AArch64::BFMXri;
2647     CurDAG->SelectNodeTo(N, Opc, VT, Ops);
2648     return true;
2649   }
2650 
2651   return false;
2652 }
2653 
2654 bool AArch64DAGToDAGISel::tryBitfieldInsertOp(SDNode *N) {
2655   if (N->getOpcode() != ISD::OR)
2656     return false;
2657 
2658   APInt NUsefulBits;
2659   getUsefulBits(SDValue(N, 0), NUsefulBits);
2660 
2661   // If all bits are not useful, just return UNDEF.
2662   if (!NUsefulBits) {
2663     CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
2664     return true;
2665   }
2666 
2667   if (tryBitfieldInsertOpFromOr(N, NUsefulBits, CurDAG))
2668     return true;
2669 
2670   return tryBitfieldInsertOpFromOrAndImm(N, CurDAG);
2671 }
2672 
2673 /// SelectBitfieldInsertInZeroOp - Match a UBFIZ instruction that is the
2674 /// equivalent of a left shift by a constant amount followed by an and masking
2675 /// out a contiguous set of bits.
2676 bool AArch64DAGToDAGISel::tryBitfieldInsertInZeroOp(SDNode *N) {
2677   if (N->getOpcode() != ISD::AND)
2678     return false;
2679 
2680   EVT VT = N->getValueType(0);
2681   if (VT != MVT::i32 && VT != MVT::i64)
2682     return false;
2683 
2684   SDValue Op0;
2685   int DstLSB, Width;
2686   if (!isBitfieldPositioningOp(CurDAG, SDValue(N, 0), /*BiggerPattern=*/false,
2687                                Op0, DstLSB, Width))
2688     return false;
2689 
2690   // ImmR is the rotate right amount.
2691   unsigned ImmR = (VT.getSizeInBits() - DstLSB) % VT.getSizeInBits();
2692   // ImmS is the most significant bit of the source to be moved.
2693   unsigned ImmS = Width - 1;
2694 
2695   SDLoc DL(N);
2696   SDValue Ops[] = {Op0, CurDAG->getTargetConstant(ImmR, DL, VT),
2697                    CurDAG->getTargetConstant(ImmS, DL, VT)};
2698   unsigned Opc = (VT == MVT::i32) ? AArch64::UBFMWri : AArch64::UBFMXri;
2699   CurDAG->SelectNodeTo(N, Opc, VT, Ops);
2700   return true;
2701 }
2702 
2703 /// tryShiftAmountMod - Take advantage of built-in mod of shift amount in
2704 /// variable shift/rotate instructions.
2705 bool AArch64DAGToDAGISel::tryShiftAmountMod(SDNode *N) {
2706   EVT VT = N->getValueType(0);
2707 
2708   unsigned Opc;
2709   switch (N->getOpcode()) {
2710   case ISD::ROTR:
2711     Opc = (VT == MVT::i32) ? AArch64::RORVWr : AArch64::RORVXr;
2712     break;
2713   case ISD::SHL:
2714     Opc = (VT == MVT::i32) ? AArch64::LSLVWr : AArch64::LSLVXr;
2715     break;
2716   case ISD::SRL:
2717     Opc = (VT == MVT::i32) ? AArch64::LSRVWr : AArch64::LSRVXr;
2718     break;
2719   case ISD::SRA:
2720     Opc = (VT == MVT::i32) ? AArch64::ASRVWr : AArch64::ASRVXr;
2721     break;
2722   default:
2723     return false;
2724   }
2725 
2726   uint64_t Size;
2727   uint64_t Bits;
2728   if (VT == MVT::i32) {
2729     Bits = 5;
2730     Size = 32;
2731   } else if (VT == MVT::i64) {
2732     Bits = 6;
2733     Size = 64;
2734   } else
2735     return false;
2736 
2737   SDValue ShiftAmt = N->getOperand(1);
2738   SDLoc DL(N);
2739   SDValue NewShiftAmt;
2740 
2741   // Skip over an extend of the shift amount.
2742   if (ShiftAmt->getOpcode() == ISD::ZERO_EXTEND ||
2743       ShiftAmt->getOpcode() == ISD::ANY_EXTEND)
2744     ShiftAmt = ShiftAmt->getOperand(0);
2745 
2746   if (ShiftAmt->getOpcode() == ISD::ADD || ShiftAmt->getOpcode() == ISD::SUB) {
2747     SDValue Add0 = ShiftAmt->getOperand(0);
2748     SDValue Add1 = ShiftAmt->getOperand(1);
2749     uint64_t Add0Imm;
2750     uint64_t Add1Imm;
2751     // If we are shifting by X+/-N where N == 0 mod Size, then just shift by X
2752     // to avoid the ADD/SUB.
2753     if (isIntImmediate(Add1, Add1Imm) && (Add1Imm % Size == 0))
2754       NewShiftAmt = Add0;
2755     // If we are shifting by N-X where N == 0 mod Size, then just shift by -X to
2756     // generate a NEG instead of a SUB of a constant.
2757     else if (ShiftAmt->getOpcode() == ISD::SUB &&
2758              isIntImmediate(Add0, Add0Imm) && Add0Imm != 0 &&
2759              (Add0Imm % Size == 0)) {
2760       unsigned NegOpc;
2761       unsigned ZeroReg;
2762       EVT SubVT = ShiftAmt->getValueType(0);
2763       if (SubVT == MVT::i32) {
2764         NegOpc = AArch64::SUBWrr;
2765         ZeroReg = AArch64::WZR;
2766       } else {
2767         assert(SubVT == MVT::i64);
2768         NegOpc = AArch64::SUBXrr;
2769         ZeroReg = AArch64::XZR;
2770       }
2771       SDValue Zero =
2772           CurDAG->getCopyFromReg(CurDAG->getEntryNode(), DL, ZeroReg, SubVT);
2773       MachineSDNode *Neg =
2774           CurDAG->getMachineNode(NegOpc, DL, SubVT, Zero, Add1);
2775       NewShiftAmt = SDValue(Neg, 0);
2776     } else
2777       return false;
2778   } else {
2779     // If the shift amount is masked with an AND, check that the mask covers the
2780     // bits that are implicitly ANDed off by the above opcodes and if so, skip
2781     // the AND.
2782     uint64_t MaskImm;
2783     if (!isOpcWithIntImmediate(ShiftAmt.getNode(), ISD::AND, MaskImm) &&
2784         !isOpcWithIntImmediate(ShiftAmt.getNode(), AArch64ISD::ANDS, MaskImm))
2785       return false;
2786 
2787     if (countTrailingOnes(MaskImm) < Bits)
2788       return false;
2789 
2790     NewShiftAmt = ShiftAmt->getOperand(0);
2791   }
2792 
2793   // Narrow/widen the shift amount to match the size of the shift operation.
2794   if (VT == MVT::i32)
2795     NewShiftAmt = narrowIfNeeded(CurDAG, NewShiftAmt);
2796   else if (VT == MVT::i64 && NewShiftAmt->getValueType(0) == MVT::i32) {
2797     SDValue SubReg = CurDAG->getTargetConstant(AArch64::sub_32, DL, MVT::i32);
2798     MachineSDNode *Ext = CurDAG->getMachineNode(
2799         AArch64::SUBREG_TO_REG, DL, VT,
2800         CurDAG->getTargetConstant(0, DL, MVT::i64), NewShiftAmt, SubReg);
2801     NewShiftAmt = SDValue(Ext, 0);
2802   }
2803 
2804   SDValue Ops[] = {N->getOperand(0), NewShiftAmt};
2805   CurDAG->SelectNodeTo(N, Opc, VT, Ops);
2806   return true;
2807 }
2808 
2809 bool
2810 AArch64DAGToDAGISel::SelectCVTFixedPosOperand(SDValue N, SDValue &FixedPos,
2811                                               unsigned RegWidth) {
2812   APFloat FVal(0.0);
2813   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
2814     FVal = CN->getValueAPF();
2815   else if (LoadSDNode *LN = dyn_cast<LoadSDNode>(N)) {
2816     // Some otherwise illegal constants are allowed in this case.
2817     if (LN->getOperand(1).getOpcode() != AArch64ISD::ADDlow ||
2818         !isa<ConstantPoolSDNode>(LN->getOperand(1)->getOperand(1)))
2819       return false;
2820 
2821     ConstantPoolSDNode *CN =
2822         dyn_cast<ConstantPoolSDNode>(LN->getOperand(1)->getOperand(1));
2823     FVal = cast<ConstantFP>(CN->getConstVal())->getValueAPF();
2824   } else
2825     return false;
2826 
2827   // An FCVT[SU] instruction performs: convertToInt(Val * 2^fbits) where fbits
2828   // is between 1 and 32 for a destination w-register, or 1 and 64 for an
2829   // x-register.
2830   //
2831   // By this stage, we've detected (fp_to_[su]int (fmul Val, THIS_NODE)) so we
2832   // want THIS_NODE to be 2^fbits. This is much easier to deal with using
2833   // integers.
2834   bool IsExact;
2835 
2836   // fbits is between 1 and 64 in the worst-case, which means the fmul
2837   // could have 2^64 as an actual operand. Need 65 bits of precision.
2838   APSInt IntVal(65, true);
2839   FVal.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact);
2840 
2841   // N.b. isPowerOf2 also checks for > 0.
2842   if (!IsExact || !IntVal.isPowerOf2()) return false;
2843   unsigned FBits = IntVal.logBase2();
2844 
2845   // Checks above should have guaranteed that we haven't lost information in
2846   // finding FBits, but it must still be in range.
2847   if (FBits == 0 || FBits > RegWidth) return false;
2848 
2849   FixedPos = CurDAG->getTargetConstant(FBits, SDLoc(N), MVT::i32);
2850   return true;
2851 }
2852 
2853 // Inspects a register string of the form o0:op1:CRn:CRm:op2 gets the fields
2854 // of the string and obtains the integer values from them and combines these
2855 // into a single value to be used in the MRS/MSR instruction.
2856 static int getIntOperandFromRegisterString(StringRef RegString) {
2857   SmallVector<StringRef, 5> Fields;
2858   RegString.split(Fields, ':');
2859 
2860   if (Fields.size() == 1)
2861     return -1;
2862 
2863   assert(Fields.size() == 5
2864             && "Invalid number of fields in read register string");
2865 
2866   SmallVector<int, 5> Ops;
2867   bool AllIntFields = true;
2868 
2869   for (StringRef Field : Fields) {
2870     unsigned IntField;
2871     AllIntFields &= !Field.getAsInteger(10, IntField);
2872     Ops.push_back(IntField);
2873   }
2874 
2875   assert(AllIntFields &&
2876           "Unexpected non-integer value in special register string.");
2877 
2878   // Need to combine the integer fields of the string into a single value
2879   // based on the bit encoding of MRS/MSR instruction.
2880   return (Ops[0] << 14) | (Ops[1] << 11) | (Ops[2] << 7) |
2881          (Ops[3] << 3) | (Ops[4]);
2882 }
2883 
2884 // Lower the read_register intrinsic to an MRS instruction node if the special
2885 // register string argument is either of the form detailed in the ALCE (the
2886 // form described in getIntOperandsFromRegsterString) or is a named register
2887 // known by the MRS SysReg mapper.
2888 bool AArch64DAGToDAGISel::tryReadRegister(SDNode *N) {
2889   const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(N->getOperand(1));
2890   const MDString *RegString = dyn_cast<MDString>(MD->getMD()->getOperand(0));
2891   SDLoc DL(N);
2892 
2893   int Reg = getIntOperandFromRegisterString(RegString->getString());
2894   if (Reg != -1) {
2895     ReplaceNode(N, CurDAG->getMachineNode(
2896                        AArch64::MRS, DL, N->getSimpleValueType(0), MVT::Other,
2897                        CurDAG->getTargetConstant(Reg, DL, MVT::i32),
2898                        N->getOperand(0)));
2899     return true;
2900   }
2901 
2902   // Use the sysreg mapper to map the remaining possible strings to the
2903   // value for the register to be used for the instruction operand.
2904   auto TheReg = AArch64SysReg::lookupSysRegByName(RegString->getString());
2905   if (TheReg && TheReg->Readable &&
2906       TheReg->haveFeatures(Subtarget->getFeatureBits()))
2907     Reg = TheReg->Encoding;
2908   else
2909     Reg = AArch64SysReg::parseGenericRegister(RegString->getString());
2910 
2911   if (Reg != -1) {
2912     ReplaceNode(N, CurDAG->getMachineNode(
2913                        AArch64::MRS, DL, N->getSimpleValueType(0), MVT::Other,
2914                        CurDAG->getTargetConstant(Reg, DL, MVT::i32),
2915                        N->getOperand(0)));
2916     return true;
2917   }
2918 
2919   if (RegString->getString() == "pc") {
2920     ReplaceNode(N, CurDAG->getMachineNode(
2921                        AArch64::ADR, DL, N->getSimpleValueType(0), MVT::Other,
2922                        CurDAG->getTargetConstant(0, DL, MVT::i32),
2923                        N->getOperand(0)));
2924     return true;
2925   }
2926 
2927   return false;
2928 }
2929 
2930 // Lower the write_register intrinsic to an MSR instruction node if the special
2931 // register string argument is either of the form detailed in the ALCE (the
2932 // form described in getIntOperandsFromRegsterString) or is a named register
2933 // known by the MSR SysReg mapper.
2934 bool AArch64DAGToDAGISel::tryWriteRegister(SDNode *N) {
2935   const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(N->getOperand(1));
2936   const MDString *RegString = dyn_cast<MDString>(MD->getMD()->getOperand(0));
2937   SDLoc DL(N);
2938 
2939   int Reg = getIntOperandFromRegisterString(RegString->getString());
2940   if (Reg != -1) {
2941     ReplaceNode(
2942         N, CurDAG->getMachineNode(AArch64::MSR, DL, MVT::Other,
2943                                   CurDAG->getTargetConstant(Reg, DL, MVT::i32),
2944                                   N->getOperand(2), N->getOperand(0)));
2945     return true;
2946   }
2947 
2948   // Check if the register was one of those allowed as the pstatefield value in
2949   // the MSR (immediate) instruction. To accept the values allowed in the
2950   // pstatefield for the MSR (immediate) instruction, we also require that an
2951   // immediate value has been provided as an argument, we know that this is
2952   // the case as it has been ensured by semantic checking.
2953   auto PMapper = AArch64PState::lookupPStateByName(RegString->getString());
2954   if (PMapper) {
2955     assert (isa<ConstantSDNode>(N->getOperand(2))
2956               && "Expected a constant integer expression.");
2957     unsigned Reg = PMapper->Encoding;
2958     uint64_t Immed = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
2959     unsigned State;
2960     if (Reg == AArch64PState::PAN || Reg == AArch64PState::UAO || Reg == AArch64PState::SSBS) {
2961       assert(Immed < 2 && "Bad imm");
2962       State = AArch64::MSRpstateImm1;
2963     } else {
2964       assert(Immed < 16 && "Bad imm");
2965       State = AArch64::MSRpstateImm4;
2966     }
2967     ReplaceNode(N, CurDAG->getMachineNode(
2968                        State, DL, MVT::Other,
2969                        CurDAG->getTargetConstant(Reg, DL, MVT::i32),
2970                        CurDAG->getTargetConstant(Immed, DL, MVT::i16),
2971                        N->getOperand(0)));
2972     return true;
2973   }
2974 
2975   // Use the sysreg mapper to attempt to map the remaining possible strings
2976   // to the value for the register to be used for the MSR (register)
2977   // instruction operand.
2978   auto TheReg = AArch64SysReg::lookupSysRegByName(RegString->getString());
2979   if (TheReg && TheReg->Writeable &&
2980       TheReg->haveFeatures(Subtarget->getFeatureBits()))
2981     Reg = TheReg->Encoding;
2982   else
2983     Reg = AArch64SysReg::parseGenericRegister(RegString->getString());
2984   if (Reg != -1) {
2985     ReplaceNode(N, CurDAG->getMachineNode(
2986                        AArch64::MSR, DL, MVT::Other,
2987                        CurDAG->getTargetConstant(Reg, DL, MVT::i32),
2988                        N->getOperand(2), N->getOperand(0)));
2989     return true;
2990   }
2991 
2992   return false;
2993 }
2994 
2995 /// We've got special pseudo-instructions for these
2996 bool AArch64DAGToDAGISel::SelectCMP_SWAP(SDNode *N) {
2997   unsigned Opcode;
2998   EVT MemTy = cast<MemSDNode>(N)->getMemoryVT();
2999 
3000   // Leave IR for LSE if subtarget supports it.
3001   if (Subtarget->hasLSE()) return false;
3002 
3003   if (MemTy == MVT::i8)
3004     Opcode = AArch64::CMP_SWAP_8;
3005   else if (MemTy == MVT::i16)
3006     Opcode = AArch64::CMP_SWAP_16;
3007   else if (MemTy == MVT::i32)
3008     Opcode = AArch64::CMP_SWAP_32;
3009   else if (MemTy == MVT::i64)
3010     Opcode = AArch64::CMP_SWAP_64;
3011   else
3012     llvm_unreachable("Unknown AtomicCmpSwap type");
3013 
3014   MVT RegTy = MemTy == MVT::i64 ? MVT::i64 : MVT::i32;
3015   SDValue Ops[] = {N->getOperand(1), N->getOperand(2), N->getOperand(3),
3016                    N->getOperand(0)};
3017   SDNode *CmpSwap = CurDAG->getMachineNode(
3018       Opcode, SDLoc(N),
3019       CurDAG->getVTList(RegTy, MVT::i32, MVT::Other), Ops);
3020 
3021   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
3022   CurDAG->setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
3023 
3024   ReplaceUses(SDValue(N, 0), SDValue(CmpSwap, 0));
3025   ReplaceUses(SDValue(N, 1), SDValue(CmpSwap, 2));
3026   CurDAG->RemoveDeadNode(N);
3027 
3028   return true;
3029 }
3030 
3031 bool AArch64DAGToDAGISel::SelectSVE8BitLslImm(SDValue N, SDValue &Base,
3032                                                   SDValue &Offset) {
3033   auto C = dyn_cast<ConstantSDNode>(N);
3034   if (!C)
3035     return false;
3036 
3037   auto Ty = N->getValueType(0);
3038 
3039   int64_t Imm = C->getSExtValue();
3040   SDLoc DL(N);
3041 
3042   if ((Imm >= -128) && (Imm <= 127)) {
3043     Base = CurDAG->getTargetConstant(Imm, DL, Ty);
3044     Offset = CurDAG->getTargetConstant(0, DL, Ty);
3045     return true;
3046   }
3047 
3048   if (((Imm % 256) == 0) && (Imm >= -32768) && (Imm <= 32512)) {
3049     Base = CurDAG->getTargetConstant(Imm/256, DL, Ty);
3050     Offset = CurDAG->getTargetConstant(8, DL, Ty);
3051     return true;
3052   }
3053 
3054   return false;
3055 }
3056 
3057 bool AArch64DAGToDAGISel::SelectSVEAddSubImm(SDValue N, MVT VT, SDValue &Imm, SDValue &Shift) {
3058   if (auto CNode = dyn_cast<ConstantSDNode>(N)) {
3059     const int64_t ImmVal = CNode->getZExtValue();
3060     SDLoc DL(N);
3061 
3062     switch (VT.SimpleTy) {
3063     case MVT::i8:
3064       if ((ImmVal & 0xFF) == ImmVal) {
3065         Shift = CurDAG->getTargetConstant(0, DL, MVT::i32);
3066         Imm = CurDAG->getTargetConstant(ImmVal, DL, MVT::i32);
3067         return true;
3068       }
3069       break;
3070     case MVT::i16:
3071     case MVT::i32:
3072     case MVT::i64:
3073       if ((ImmVal & 0xFF) == ImmVal) {
3074         Shift = CurDAG->getTargetConstant(0, DL, MVT::i32);
3075         Imm = CurDAG->getTargetConstant(ImmVal, DL, MVT::i32);
3076         return true;
3077       } else if ((ImmVal & 0xFF00) == ImmVal) {
3078         Shift = CurDAG->getTargetConstant(8, DL, MVT::i32);
3079         Imm = CurDAG->getTargetConstant(ImmVal >> 8, DL, MVT::i32);
3080         return true;
3081       }
3082       break;
3083     default:
3084       break;
3085     }
3086   }
3087 
3088   return false;
3089 }
3090 
3091 bool AArch64DAGToDAGISel::SelectSVESignedArithImm(SDValue N, SDValue &Imm) {
3092   if (auto CNode = dyn_cast<ConstantSDNode>(N)) {
3093     int64_t ImmVal = CNode->getSExtValue();
3094     SDLoc DL(N);
3095     if (ImmVal >= -127 && ImmVal < 127) {
3096       Imm = CurDAG->getTargetConstant(ImmVal, DL, MVT::i32);
3097       return true;
3098     }
3099   }
3100   return false;
3101 }
3102 
3103 bool AArch64DAGToDAGISel::SelectSVEArithImm(SDValue N, SDValue &Imm) {
3104   if (auto CNode = dyn_cast<ConstantSDNode>(N)) {
3105     uint64_t ImmVal = CNode->getSExtValue();
3106     SDLoc DL(N);
3107     ImmVal = ImmVal & 0xFF;
3108     if (ImmVal < 256) {
3109       Imm = CurDAG->getTargetConstant(ImmVal, DL, MVT::i32);
3110       return true;
3111     }
3112   }
3113   return false;
3114 }
3115 
3116 bool AArch64DAGToDAGISel::SelectSVELogicalImm(SDValue N, MVT VT, SDValue &Imm) {
3117   if (auto CNode = dyn_cast<ConstantSDNode>(N)) {
3118     uint64_t ImmVal = CNode->getZExtValue();
3119     SDLoc DL(N);
3120 
3121     // Shift mask depending on type size.
3122     switch (VT.SimpleTy) {
3123       case MVT::i8:
3124         ImmVal &= 0xFF;
3125         ImmVal |= ImmVal << 8;
3126         ImmVal |= ImmVal << 16;
3127         ImmVal |= ImmVal << 32;
3128         break;
3129       case MVT::i16:
3130         ImmVal &= 0xFFFF;
3131         ImmVal |= ImmVal << 16;
3132         ImmVal |= ImmVal << 32;
3133         break;
3134       case MVT::i32:
3135         ImmVal &= 0xFFFFFFFF;
3136         ImmVal |= ImmVal << 32;
3137         break;
3138       case MVT::i64:
3139         break;
3140       default:
3141         llvm_unreachable("Unexpected type");
3142     }
3143 
3144     uint64_t encoding;
3145     if (AArch64_AM::processLogicalImmediate(ImmVal, 64, encoding)) {
3146       Imm = CurDAG->getTargetConstant(encoding, DL, MVT::i64);
3147       return true;
3148     }
3149   }
3150   return false;
3151 }
3152 
3153 // This method is only needed to "cast" i64s into i32s when the value
3154 // is a valid shift which has been splatted into a vector with i64 elements.
3155 // Every other type is fine in tablegen.
3156 bool AArch64DAGToDAGISel::SelectSVEShiftImm64(SDValue N, uint64_t Low,
3157                                               uint64_t High, SDValue &Imm) {
3158   if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
3159     uint64_t ImmVal = CN->getZExtValue();
3160     SDLoc DL(N);
3161 
3162     if (ImmVal >= Low && ImmVal <= High) {
3163       Imm = CurDAG->getTargetConstant(ImmVal, DL, MVT::i32);
3164       return true;
3165     }
3166   }
3167 
3168   return false;
3169 }
3170 
3171 bool AArch64DAGToDAGISel::trySelectStackSlotTagP(SDNode *N) {
3172   // tagp(FrameIndex, IRGstack, tag_offset):
3173   // since the offset between FrameIndex and IRGstack is a compile-time
3174   // constant, this can be lowered to a single ADDG instruction.
3175   if (!(isa<FrameIndexSDNode>(N->getOperand(1)))) {
3176     return false;
3177   }
3178 
3179   SDValue IRG_SP = N->getOperand(2);
3180   if (IRG_SP->getOpcode() != ISD::INTRINSIC_W_CHAIN ||
3181       cast<ConstantSDNode>(IRG_SP->getOperand(1))->getZExtValue() !=
3182           Intrinsic::aarch64_irg_sp) {
3183     return false;
3184   }
3185 
3186   const TargetLowering *TLI = getTargetLowering();
3187   SDLoc DL(N);
3188   int FI = cast<FrameIndexSDNode>(N->getOperand(1))->getIndex();
3189   SDValue FiOp = CurDAG->getTargetFrameIndex(
3190       FI, TLI->getPointerTy(CurDAG->getDataLayout()));
3191   int TagOffset = cast<ConstantSDNode>(N->getOperand(3))->getZExtValue();
3192 
3193   SDNode *Out = CurDAG->getMachineNode(
3194       AArch64::TAGPstack, DL, MVT::i64,
3195       {FiOp, CurDAG->getTargetConstant(0, DL, MVT::i64), N->getOperand(2),
3196        CurDAG->getTargetConstant(TagOffset, DL, MVT::i64)});
3197   ReplaceNode(N, Out);
3198   return true;
3199 }
3200 
3201 void AArch64DAGToDAGISel::SelectTagP(SDNode *N) {
3202   assert(isa<ConstantSDNode>(N->getOperand(3)) &&
3203          "llvm.aarch64.tagp third argument must be an immediate");
3204   if (trySelectStackSlotTagP(N))
3205     return;
3206   // FIXME: above applies in any case when offset between Op1 and Op2 is a
3207   // compile-time constant, not just for stack allocations.
3208 
3209   // General case for unrelated pointers in Op1 and Op2.
3210   SDLoc DL(N);
3211   int TagOffset = cast<ConstantSDNode>(N->getOperand(3))->getZExtValue();
3212   SDNode *N1 = CurDAG->getMachineNode(AArch64::SUBP, DL, MVT::i64,
3213                                       {N->getOperand(1), N->getOperand(2)});
3214   SDNode *N2 = CurDAG->getMachineNode(AArch64::ADDXrr, DL, MVT::i64,
3215                                       {SDValue(N1, 0), N->getOperand(2)});
3216   SDNode *N3 = CurDAG->getMachineNode(
3217       AArch64::ADDG, DL, MVT::i64,
3218       {SDValue(N2, 0), CurDAG->getTargetConstant(0, DL, MVT::i64),
3219        CurDAG->getTargetConstant(TagOffset, DL, MVT::i64)});
3220   ReplaceNode(N, N3);
3221 }
3222 
3223 void AArch64DAGToDAGISel::Select(SDNode *Node) {
3224   // If we have a custom node, we already have selected!
3225   if (Node->isMachineOpcode()) {
3226     LLVM_DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
3227     Node->setNodeId(-1);
3228     return;
3229   }
3230 
3231   // Few custom selection stuff.
3232   EVT VT = Node->getValueType(0);
3233 
3234   switch (Node->getOpcode()) {
3235   default:
3236     break;
3237 
3238   case ISD::ATOMIC_CMP_SWAP:
3239     if (SelectCMP_SWAP(Node))
3240       return;
3241     break;
3242 
3243   case ISD::READ_REGISTER:
3244     if (tryReadRegister(Node))
3245       return;
3246     break;
3247 
3248   case ISD::WRITE_REGISTER:
3249     if (tryWriteRegister(Node))
3250       return;
3251     break;
3252 
3253   case ISD::ADD:
3254     if (tryMLAV64LaneV128(Node))
3255       return;
3256     break;
3257 
3258   case ISD::LOAD: {
3259     // Try to select as an indexed load. Fall through to normal processing
3260     // if we can't.
3261     if (tryIndexedLoad(Node))
3262       return;
3263     break;
3264   }
3265 
3266   case ISD::SRL:
3267   case ISD::AND:
3268   case ISD::SRA:
3269   case ISD::SIGN_EXTEND_INREG:
3270     if (tryBitfieldExtractOp(Node))
3271       return;
3272     if (tryBitfieldInsertInZeroOp(Node))
3273       return;
3274     LLVM_FALLTHROUGH;
3275   case ISD::ROTR:
3276   case ISD::SHL:
3277     if (tryShiftAmountMod(Node))
3278       return;
3279     break;
3280 
3281   case ISD::SIGN_EXTEND:
3282     if (tryBitfieldExtractOpFromSExt(Node))
3283       return;
3284     break;
3285 
3286   case ISD::FP_EXTEND:
3287     if (tryHighFPExt(Node))
3288       return;
3289     break;
3290 
3291   case ISD::OR:
3292     if (tryBitfieldInsertOp(Node))
3293       return;
3294     break;
3295 
3296   case ISD::Constant: {
3297     // Materialize zero constants as copies from WZR/XZR.  This allows
3298     // the coalescer to propagate these into other instructions.
3299     ConstantSDNode *ConstNode = cast<ConstantSDNode>(Node);
3300     if (ConstNode->isNullValue()) {
3301       if (VT == MVT::i32) {
3302         SDValue New = CurDAG->getCopyFromReg(
3303             CurDAG->getEntryNode(), SDLoc(Node), AArch64::WZR, MVT::i32);
3304         ReplaceNode(Node, New.getNode());
3305         return;
3306       } else if (VT == MVT::i64) {
3307         SDValue New = CurDAG->getCopyFromReg(
3308             CurDAG->getEntryNode(), SDLoc(Node), AArch64::XZR, MVT::i64);
3309         ReplaceNode(Node, New.getNode());
3310         return;
3311       }
3312     }
3313     break;
3314   }
3315 
3316   case ISD::FrameIndex: {
3317     // Selects to ADDXri FI, 0 which in turn will become ADDXri SP, imm.
3318     int FI = cast<FrameIndexSDNode>(Node)->getIndex();
3319     unsigned Shifter = AArch64_AM::getShifterImm(AArch64_AM::LSL, 0);
3320     const TargetLowering *TLI = getTargetLowering();
3321     SDValue TFI = CurDAG->getTargetFrameIndex(
3322         FI, TLI->getPointerTy(CurDAG->getDataLayout()));
3323     SDLoc DL(Node);
3324     SDValue Ops[] = { TFI, CurDAG->getTargetConstant(0, DL, MVT::i32),
3325                       CurDAG->getTargetConstant(Shifter, DL, MVT::i32) };
3326     CurDAG->SelectNodeTo(Node, AArch64::ADDXri, MVT::i64, Ops);
3327     return;
3328   }
3329   case ISD::INTRINSIC_W_CHAIN: {
3330     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
3331     switch (IntNo) {
3332     default:
3333       break;
3334     case Intrinsic::aarch64_ldaxp:
3335     case Intrinsic::aarch64_ldxp: {
3336       unsigned Op =
3337           IntNo == Intrinsic::aarch64_ldaxp ? AArch64::LDAXPX : AArch64::LDXPX;
3338       SDValue MemAddr = Node->getOperand(2);
3339       SDLoc DL(Node);
3340       SDValue Chain = Node->getOperand(0);
3341 
3342       SDNode *Ld = CurDAG->getMachineNode(Op, DL, MVT::i64, MVT::i64,
3343                                           MVT::Other, MemAddr, Chain);
3344 
3345       // Transfer memoperands.
3346       MachineMemOperand *MemOp =
3347           cast<MemIntrinsicSDNode>(Node)->getMemOperand();
3348       CurDAG->setNodeMemRefs(cast<MachineSDNode>(Ld), {MemOp});
3349       ReplaceNode(Node, Ld);
3350       return;
3351     }
3352     case Intrinsic::aarch64_stlxp:
3353     case Intrinsic::aarch64_stxp: {
3354       unsigned Op =
3355           IntNo == Intrinsic::aarch64_stlxp ? AArch64::STLXPX : AArch64::STXPX;
3356       SDLoc DL(Node);
3357       SDValue Chain = Node->getOperand(0);
3358       SDValue ValLo = Node->getOperand(2);
3359       SDValue ValHi = Node->getOperand(3);
3360       SDValue MemAddr = Node->getOperand(4);
3361 
3362       // Place arguments in the right order.
3363       SDValue Ops[] = {ValLo, ValHi, MemAddr, Chain};
3364 
3365       SDNode *St = CurDAG->getMachineNode(Op, DL, MVT::i32, MVT::Other, Ops);
3366       // Transfer memoperands.
3367       MachineMemOperand *MemOp =
3368           cast<MemIntrinsicSDNode>(Node)->getMemOperand();
3369       CurDAG->setNodeMemRefs(cast<MachineSDNode>(St), {MemOp});
3370 
3371       ReplaceNode(Node, St);
3372       return;
3373     }
3374     case Intrinsic::aarch64_neon_ld1x2:
3375       if (VT == MVT::v8i8) {
3376         SelectLoad(Node, 2, AArch64::LD1Twov8b, AArch64::dsub0);
3377         return;
3378       } else if (VT == MVT::v16i8) {
3379         SelectLoad(Node, 2, AArch64::LD1Twov16b, AArch64::qsub0);
3380         return;
3381       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3382         SelectLoad(Node, 2, AArch64::LD1Twov4h, AArch64::dsub0);
3383         return;
3384       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3385         SelectLoad(Node, 2, AArch64::LD1Twov8h, AArch64::qsub0);
3386         return;
3387       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3388         SelectLoad(Node, 2, AArch64::LD1Twov2s, AArch64::dsub0);
3389         return;
3390       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3391         SelectLoad(Node, 2, AArch64::LD1Twov4s, AArch64::qsub0);
3392         return;
3393       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3394         SelectLoad(Node, 2, AArch64::LD1Twov1d, AArch64::dsub0);
3395         return;
3396       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3397         SelectLoad(Node, 2, AArch64::LD1Twov2d, AArch64::qsub0);
3398         return;
3399       }
3400       break;
3401     case Intrinsic::aarch64_neon_ld1x3:
3402       if (VT == MVT::v8i8) {
3403         SelectLoad(Node, 3, AArch64::LD1Threev8b, AArch64::dsub0);
3404         return;
3405       } else if (VT == MVT::v16i8) {
3406         SelectLoad(Node, 3, AArch64::LD1Threev16b, AArch64::qsub0);
3407         return;
3408       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3409         SelectLoad(Node, 3, AArch64::LD1Threev4h, AArch64::dsub0);
3410         return;
3411       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3412         SelectLoad(Node, 3, AArch64::LD1Threev8h, AArch64::qsub0);
3413         return;
3414       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3415         SelectLoad(Node, 3, AArch64::LD1Threev2s, AArch64::dsub0);
3416         return;
3417       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3418         SelectLoad(Node, 3, AArch64::LD1Threev4s, AArch64::qsub0);
3419         return;
3420       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3421         SelectLoad(Node, 3, AArch64::LD1Threev1d, AArch64::dsub0);
3422         return;
3423       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3424         SelectLoad(Node, 3, AArch64::LD1Threev2d, AArch64::qsub0);
3425         return;
3426       }
3427       break;
3428     case Intrinsic::aarch64_neon_ld1x4:
3429       if (VT == MVT::v8i8) {
3430         SelectLoad(Node, 4, AArch64::LD1Fourv8b, AArch64::dsub0);
3431         return;
3432       } else if (VT == MVT::v16i8) {
3433         SelectLoad(Node, 4, AArch64::LD1Fourv16b, AArch64::qsub0);
3434         return;
3435       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3436         SelectLoad(Node, 4, AArch64::LD1Fourv4h, AArch64::dsub0);
3437         return;
3438       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3439         SelectLoad(Node, 4, AArch64::LD1Fourv8h, AArch64::qsub0);
3440         return;
3441       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3442         SelectLoad(Node, 4, AArch64::LD1Fourv2s, AArch64::dsub0);
3443         return;
3444       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3445         SelectLoad(Node, 4, AArch64::LD1Fourv4s, AArch64::qsub0);
3446         return;
3447       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3448         SelectLoad(Node, 4, AArch64::LD1Fourv1d, AArch64::dsub0);
3449         return;
3450       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3451         SelectLoad(Node, 4, AArch64::LD1Fourv2d, AArch64::qsub0);
3452         return;
3453       }
3454       break;
3455     case Intrinsic::aarch64_neon_ld2:
3456       if (VT == MVT::v8i8) {
3457         SelectLoad(Node, 2, AArch64::LD2Twov8b, AArch64::dsub0);
3458         return;
3459       } else if (VT == MVT::v16i8) {
3460         SelectLoad(Node, 2, AArch64::LD2Twov16b, AArch64::qsub0);
3461         return;
3462       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3463         SelectLoad(Node, 2, AArch64::LD2Twov4h, AArch64::dsub0);
3464         return;
3465       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3466         SelectLoad(Node, 2, AArch64::LD2Twov8h, AArch64::qsub0);
3467         return;
3468       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3469         SelectLoad(Node, 2, AArch64::LD2Twov2s, AArch64::dsub0);
3470         return;
3471       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3472         SelectLoad(Node, 2, AArch64::LD2Twov4s, AArch64::qsub0);
3473         return;
3474       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3475         SelectLoad(Node, 2, AArch64::LD1Twov1d, AArch64::dsub0);
3476         return;
3477       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3478         SelectLoad(Node, 2, AArch64::LD2Twov2d, AArch64::qsub0);
3479         return;
3480       }
3481       break;
3482     case Intrinsic::aarch64_neon_ld3:
3483       if (VT == MVT::v8i8) {
3484         SelectLoad(Node, 3, AArch64::LD3Threev8b, AArch64::dsub0);
3485         return;
3486       } else if (VT == MVT::v16i8) {
3487         SelectLoad(Node, 3, AArch64::LD3Threev16b, AArch64::qsub0);
3488         return;
3489       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3490         SelectLoad(Node, 3, AArch64::LD3Threev4h, AArch64::dsub0);
3491         return;
3492       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3493         SelectLoad(Node, 3, AArch64::LD3Threev8h, AArch64::qsub0);
3494         return;
3495       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3496         SelectLoad(Node, 3, AArch64::LD3Threev2s, AArch64::dsub0);
3497         return;
3498       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3499         SelectLoad(Node, 3, AArch64::LD3Threev4s, AArch64::qsub0);
3500         return;
3501       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3502         SelectLoad(Node, 3, AArch64::LD1Threev1d, AArch64::dsub0);
3503         return;
3504       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3505         SelectLoad(Node, 3, AArch64::LD3Threev2d, AArch64::qsub0);
3506         return;
3507       }
3508       break;
3509     case Intrinsic::aarch64_neon_ld4:
3510       if (VT == MVT::v8i8) {
3511         SelectLoad(Node, 4, AArch64::LD4Fourv8b, AArch64::dsub0);
3512         return;
3513       } else if (VT == MVT::v16i8) {
3514         SelectLoad(Node, 4, AArch64::LD4Fourv16b, AArch64::qsub0);
3515         return;
3516       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3517         SelectLoad(Node, 4, AArch64::LD4Fourv4h, AArch64::dsub0);
3518         return;
3519       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3520         SelectLoad(Node, 4, AArch64::LD4Fourv8h, AArch64::qsub0);
3521         return;
3522       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3523         SelectLoad(Node, 4, AArch64::LD4Fourv2s, AArch64::dsub0);
3524         return;
3525       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3526         SelectLoad(Node, 4, AArch64::LD4Fourv4s, AArch64::qsub0);
3527         return;
3528       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3529         SelectLoad(Node, 4, AArch64::LD1Fourv1d, AArch64::dsub0);
3530         return;
3531       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3532         SelectLoad(Node, 4, AArch64::LD4Fourv2d, AArch64::qsub0);
3533         return;
3534       }
3535       break;
3536     case Intrinsic::aarch64_neon_ld2r:
3537       if (VT == MVT::v8i8) {
3538         SelectLoad(Node, 2, AArch64::LD2Rv8b, AArch64::dsub0);
3539         return;
3540       } else if (VT == MVT::v16i8) {
3541         SelectLoad(Node, 2, AArch64::LD2Rv16b, AArch64::qsub0);
3542         return;
3543       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3544         SelectLoad(Node, 2, AArch64::LD2Rv4h, AArch64::dsub0);
3545         return;
3546       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3547         SelectLoad(Node, 2, AArch64::LD2Rv8h, AArch64::qsub0);
3548         return;
3549       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3550         SelectLoad(Node, 2, AArch64::LD2Rv2s, AArch64::dsub0);
3551         return;
3552       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3553         SelectLoad(Node, 2, AArch64::LD2Rv4s, AArch64::qsub0);
3554         return;
3555       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3556         SelectLoad(Node, 2, AArch64::LD2Rv1d, AArch64::dsub0);
3557         return;
3558       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3559         SelectLoad(Node, 2, AArch64::LD2Rv2d, AArch64::qsub0);
3560         return;
3561       }
3562       break;
3563     case Intrinsic::aarch64_neon_ld3r:
3564       if (VT == MVT::v8i8) {
3565         SelectLoad(Node, 3, AArch64::LD3Rv8b, AArch64::dsub0);
3566         return;
3567       } else if (VT == MVT::v16i8) {
3568         SelectLoad(Node, 3, AArch64::LD3Rv16b, AArch64::qsub0);
3569         return;
3570       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3571         SelectLoad(Node, 3, AArch64::LD3Rv4h, AArch64::dsub0);
3572         return;
3573       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3574         SelectLoad(Node, 3, AArch64::LD3Rv8h, AArch64::qsub0);
3575         return;
3576       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3577         SelectLoad(Node, 3, AArch64::LD3Rv2s, AArch64::dsub0);
3578         return;
3579       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3580         SelectLoad(Node, 3, AArch64::LD3Rv4s, AArch64::qsub0);
3581         return;
3582       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3583         SelectLoad(Node, 3, AArch64::LD3Rv1d, AArch64::dsub0);
3584         return;
3585       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3586         SelectLoad(Node, 3, AArch64::LD3Rv2d, AArch64::qsub0);
3587         return;
3588       }
3589       break;
3590     case Intrinsic::aarch64_neon_ld4r:
3591       if (VT == MVT::v8i8) {
3592         SelectLoad(Node, 4, AArch64::LD4Rv8b, AArch64::dsub0);
3593         return;
3594       } else if (VT == MVT::v16i8) {
3595         SelectLoad(Node, 4, AArch64::LD4Rv16b, AArch64::qsub0);
3596         return;
3597       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3598         SelectLoad(Node, 4, AArch64::LD4Rv4h, AArch64::dsub0);
3599         return;
3600       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3601         SelectLoad(Node, 4, AArch64::LD4Rv8h, AArch64::qsub0);
3602         return;
3603       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3604         SelectLoad(Node, 4, AArch64::LD4Rv2s, AArch64::dsub0);
3605         return;
3606       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3607         SelectLoad(Node, 4, AArch64::LD4Rv4s, AArch64::qsub0);
3608         return;
3609       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3610         SelectLoad(Node, 4, AArch64::LD4Rv1d, AArch64::dsub0);
3611         return;
3612       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3613         SelectLoad(Node, 4, AArch64::LD4Rv2d, AArch64::qsub0);
3614         return;
3615       }
3616       break;
3617     case Intrinsic::aarch64_neon_ld2lane:
3618       if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3619         SelectLoadLane(Node, 2, AArch64::LD2i8);
3620         return;
3621       } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3622                  VT == MVT::v8f16) {
3623         SelectLoadLane(Node, 2, AArch64::LD2i16);
3624         return;
3625       } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3626                  VT == MVT::v2f32) {
3627         SelectLoadLane(Node, 2, AArch64::LD2i32);
3628         return;
3629       } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3630                  VT == MVT::v1f64) {
3631         SelectLoadLane(Node, 2, AArch64::LD2i64);
3632         return;
3633       }
3634       break;
3635     case Intrinsic::aarch64_neon_ld3lane:
3636       if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3637         SelectLoadLane(Node, 3, AArch64::LD3i8);
3638         return;
3639       } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3640                  VT == MVT::v8f16) {
3641         SelectLoadLane(Node, 3, AArch64::LD3i16);
3642         return;
3643       } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3644                  VT == MVT::v2f32) {
3645         SelectLoadLane(Node, 3, AArch64::LD3i32);
3646         return;
3647       } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3648                  VT == MVT::v1f64) {
3649         SelectLoadLane(Node, 3, AArch64::LD3i64);
3650         return;
3651       }
3652       break;
3653     case Intrinsic::aarch64_neon_ld4lane:
3654       if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3655         SelectLoadLane(Node, 4, AArch64::LD4i8);
3656         return;
3657       } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3658                  VT == MVT::v8f16) {
3659         SelectLoadLane(Node, 4, AArch64::LD4i16);
3660         return;
3661       } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3662                  VT == MVT::v2f32) {
3663         SelectLoadLane(Node, 4, AArch64::LD4i32);
3664         return;
3665       } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3666                  VT == MVT::v1f64) {
3667         SelectLoadLane(Node, 4, AArch64::LD4i64);
3668         return;
3669       }
3670       break;
3671     }
3672   } break;
3673   case ISD::INTRINSIC_WO_CHAIN: {
3674     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(0))->getZExtValue();
3675     switch (IntNo) {
3676     default:
3677       break;
3678     case Intrinsic::aarch64_tagp:
3679       SelectTagP(Node);
3680       return;
3681     case Intrinsic::aarch64_neon_tbl2:
3682       SelectTable(Node, 2,
3683                   VT == MVT::v8i8 ? AArch64::TBLv8i8Two : AArch64::TBLv16i8Two,
3684                   false);
3685       return;
3686     case Intrinsic::aarch64_neon_tbl3:
3687       SelectTable(Node, 3, VT == MVT::v8i8 ? AArch64::TBLv8i8Three
3688                                            : AArch64::TBLv16i8Three,
3689                   false);
3690       return;
3691     case Intrinsic::aarch64_neon_tbl4:
3692       SelectTable(Node, 4, VT == MVT::v8i8 ? AArch64::TBLv8i8Four
3693                                            : AArch64::TBLv16i8Four,
3694                   false);
3695       return;
3696     case Intrinsic::aarch64_neon_tbx2:
3697       SelectTable(Node, 2,
3698                   VT == MVT::v8i8 ? AArch64::TBXv8i8Two : AArch64::TBXv16i8Two,
3699                   true);
3700       return;
3701     case Intrinsic::aarch64_neon_tbx3:
3702       SelectTable(Node, 3, VT == MVT::v8i8 ? AArch64::TBXv8i8Three
3703                                            : AArch64::TBXv16i8Three,
3704                   true);
3705       return;
3706     case Intrinsic::aarch64_neon_tbx4:
3707       SelectTable(Node, 4, VT == MVT::v8i8 ? AArch64::TBXv8i8Four
3708                                            : AArch64::TBXv16i8Four,
3709                   true);
3710       return;
3711     case Intrinsic::aarch64_neon_smull:
3712     case Intrinsic::aarch64_neon_umull:
3713       if (tryMULLV64LaneV128(IntNo, Node))
3714         return;
3715       break;
3716     }
3717     break;
3718   }
3719   case ISD::INTRINSIC_VOID: {
3720     unsigned IntNo = cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue();
3721     if (Node->getNumOperands() >= 3)
3722       VT = Node->getOperand(2)->getValueType(0);
3723     switch (IntNo) {
3724     default:
3725       break;
3726     case Intrinsic::aarch64_neon_st1x2: {
3727       if (VT == MVT::v8i8) {
3728         SelectStore(Node, 2, AArch64::ST1Twov8b);
3729         return;
3730       } else if (VT == MVT::v16i8) {
3731         SelectStore(Node, 2, AArch64::ST1Twov16b);
3732         return;
3733       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3734         SelectStore(Node, 2, AArch64::ST1Twov4h);
3735         return;
3736       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3737         SelectStore(Node, 2, AArch64::ST1Twov8h);
3738         return;
3739       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3740         SelectStore(Node, 2, AArch64::ST1Twov2s);
3741         return;
3742       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3743         SelectStore(Node, 2, AArch64::ST1Twov4s);
3744         return;
3745       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3746         SelectStore(Node, 2, AArch64::ST1Twov2d);
3747         return;
3748       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3749         SelectStore(Node, 2, AArch64::ST1Twov1d);
3750         return;
3751       }
3752       break;
3753     }
3754     case Intrinsic::aarch64_neon_st1x3: {
3755       if (VT == MVT::v8i8) {
3756         SelectStore(Node, 3, AArch64::ST1Threev8b);
3757         return;
3758       } else if (VT == MVT::v16i8) {
3759         SelectStore(Node, 3, AArch64::ST1Threev16b);
3760         return;
3761       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3762         SelectStore(Node, 3, AArch64::ST1Threev4h);
3763         return;
3764       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3765         SelectStore(Node, 3, AArch64::ST1Threev8h);
3766         return;
3767       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3768         SelectStore(Node, 3, AArch64::ST1Threev2s);
3769         return;
3770       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3771         SelectStore(Node, 3, AArch64::ST1Threev4s);
3772         return;
3773       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3774         SelectStore(Node, 3, AArch64::ST1Threev2d);
3775         return;
3776       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3777         SelectStore(Node, 3, AArch64::ST1Threev1d);
3778         return;
3779       }
3780       break;
3781     }
3782     case Intrinsic::aarch64_neon_st1x4: {
3783       if (VT == MVT::v8i8) {
3784         SelectStore(Node, 4, AArch64::ST1Fourv8b);
3785         return;
3786       } else if (VT == MVT::v16i8) {
3787         SelectStore(Node, 4, AArch64::ST1Fourv16b);
3788         return;
3789       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3790         SelectStore(Node, 4, AArch64::ST1Fourv4h);
3791         return;
3792       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3793         SelectStore(Node, 4, AArch64::ST1Fourv8h);
3794         return;
3795       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3796         SelectStore(Node, 4, AArch64::ST1Fourv2s);
3797         return;
3798       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3799         SelectStore(Node, 4, AArch64::ST1Fourv4s);
3800         return;
3801       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3802         SelectStore(Node, 4, AArch64::ST1Fourv2d);
3803         return;
3804       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3805         SelectStore(Node, 4, AArch64::ST1Fourv1d);
3806         return;
3807       }
3808       break;
3809     }
3810     case Intrinsic::aarch64_neon_st2: {
3811       if (VT == MVT::v8i8) {
3812         SelectStore(Node, 2, AArch64::ST2Twov8b);
3813         return;
3814       } else if (VT == MVT::v16i8) {
3815         SelectStore(Node, 2, AArch64::ST2Twov16b);
3816         return;
3817       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3818         SelectStore(Node, 2, AArch64::ST2Twov4h);
3819         return;
3820       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3821         SelectStore(Node, 2, AArch64::ST2Twov8h);
3822         return;
3823       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3824         SelectStore(Node, 2, AArch64::ST2Twov2s);
3825         return;
3826       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3827         SelectStore(Node, 2, AArch64::ST2Twov4s);
3828         return;
3829       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3830         SelectStore(Node, 2, AArch64::ST2Twov2d);
3831         return;
3832       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3833         SelectStore(Node, 2, AArch64::ST1Twov1d);
3834         return;
3835       }
3836       break;
3837     }
3838     case Intrinsic::aarch64_neon_st3: {
3839       if (VT == MVT::v8i8) {
3840         SelectStore(Node, 3, AArch64::ST3Threev8b);
3841         return;
3842       } else if (VT == MVT::v16i8) {
3843         SelectStore(Node, 3, AArch64::ST3Threev16b);
3844         return;
3845       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3846         SelectStore(Node, 3, AArch64::ST3Threev4h);
3847         return;
3848       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3849         SelectStore(Node, 3, AArch64::ST3Threev8h);
3850         return;
3851       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3852         SelectStore(Node, 3, AArch64::ST3Threev2s);
3853         return;
3854       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3855         SelectStore(Node, 3, AArch64::ST3Threev4s);
3856         return;
3857       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3858         SelectStore(Node, 3, AArch64::ST3Threev2d);
3859         return;
3860       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3861         SelectStore(Node, 3, AArch64::ST1Threev1d);
3862         return;
3863       }
3864       break;
3865     }
3866     case Intrinsic::aarch64_neon_st4: {
3867       if (VT == MVT::v8i8) {
3868         SelectStore(Node, 4, AArch64::ST4Fourv8b);
3869         return;
3870       } else if (VT == MVT::v16i8) {
3871         SelectStore(Node, 4, AArch64::ST4Fourv16b);
3872         return;
3873       } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
3874         SelectStore(Node, 4, AArch64::ST4Fourv4h);
3875         return;
3876       } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
3877         SelectStore(Node, 4, AArch64::ST4Fourv8h);
3878         return;
3879       } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
3880         SelectStore(Node, 4, AArch64::ST4Fourv2s);
3881         return;
3882       } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
3883         SelectStore(Node, 4, AArch64::ST4Fourv4s);
3884         return;
3885       } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
3886         SelectStore(Node, 4, AArch64::ST4Fourv2d);
3887         return;
3888       } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
3889         SelectStore(Node, 4, AArch64::ST1Fourv1d);
3890         return;
3891       }
3892       break;
3893     }
3894     case Intrinsic::aarch64_neon_st2lane: {
3895       if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3896         SelectStoreLane(Node, 2, AArch64::ST2i8);
3897         return;
3898       } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3899                  VT == MVT::v8f16) {
3900         SelectStoreLane(Node, 2, AArch64::ST2i16);
3901         return;
3902       } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3903                  VT == MVT::v2f32) {
3904         SelectStoreLane(Node, 2, AArch64::ST2i32);
3905         return;
3906       } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3907                  VT == MVT::v1f64) {
3908         SelectStoreLane(Node, 2, AArch64::ST2i64);
3909         return;
3910       }
3911       break;
3912     }
3913     case Intrinsic::aarch64_neon_st3lane: {
3914       if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3915         SelectStoreLane(Node, 3, AArch64::ST3i8);
3916         return;
3917       } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3918                  VT == MVT::v8f16) {
3919         SelectStoreLane(Node, 3, AArch64::ST3i16);
3920         return;
3921       } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3922                  VT == MVT::v2f32) {
3923         SelectStoreLane(Node, 3, AArch64::ST3i32);
3924         return;
3925       } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3926                  VT == MVT::v1f64) {
3927         SelectStoreLane(Node, 3, AArch64::ST3i64);
3928         return;
3929       }
3930       break;
3931     }
3932     case Intrinsic::aarch64_neon_st4lane: {
3933       if (VT == MVT::v16i8 || VT == MVT::v8i8) {
3934         SelectStoreLane(Node, 4, AArch64::ST4i8);
3935         return;
3936       } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
3937                  VT == MVT::v8f16) {
3938         SelectStoreLane(Node, 4, AArch64::ST4i16);
3939         return;
3940       } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
3941                  VT == MVT::v2f32) {
3942         SelectStoreLane(Node, 4, AArch64::ST4i32);
3943         return;
3944       } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
3945                  VT == MVT::v1f64) {
3946         SelectStoreLane(Node, 4, AArch64::ST4i64);
3947         return;
3948       }
3949       break;
3950     }
3951     case Intrinsic::aarch64_sve_st2: {
3952       if (VT == MVT::nxv16i8) {
3953         SelectPredicatedStore</*Scale=*/0>(Node, 2, AArch64::ST2B,
3954                                            AArch64::ST2B_IMM);
3955         return;
3956       } else if (VT == MVT::nxv8i16 || VT == MVT::nxv8f16) {
3957         SelectPredicatedStore</*Scale=*/1>(Node, 2, AArch64::ST2H,
3958                                            AArch64::ST2H_IMM);
3959         return;
3960       } else if (VT == MVT::nxv4i32 || VT == MVT::nxv4f32) {
3961         SelectPredicatedStore</*Scale=*/2>(Node, 2, AArch64::ST2W,
3962                                            AArch64::ST2W_IMM);
3963         return;
3964       } else if (VT == MVT::nxv2i64 || VT == MVT::nxv2f64) {
3965         SelectPredicatedStore</*Scale=*/3>(Node, 2, AArch64::ST2D,
3966                                            AArch64::ST2D_IMM);
3967         return;
3968       }
3969       break;
3970     }
3971     case Intrinsic::aarch64_sve_st3: {
3972       if (VT == MVT::nxv16i8) {
3973         SelectPredicatedStore</*Scale=*/0>(Node, 3, AArch64::ST3B,
3974                                            AArch64::ST3B_IMM);
3975         return;
3976       } else if (VT == MVT::nxv8i16 || VT == MVT::nxv8f16) {
3977         SelectPredicatedStore</*Scale=*/1>(Node, 3, AArch64::ST3H,
3978                                            AArch64::ST3H_IMM);
3979         return;
3980       } else if (VT == MVT::nxv4i32 || VT == MVT::nxv4f32) {
3981         SelectPredicatedStore</*Scale=*/2>(Node, 3, AArch64::ST3W,
3982                                            AArch64::ST3W_IMM);
3983         return;
3984       } else if (VT == MVT::nxv2i64 || VT == MVT::nxv2f64) {
3985         SelectPredicatedStore</*Scale=*/3>(Node, 3, AArch64::ST3D,
3986                                            AArch64::ST3D_IMM);
3987         return;
3988       }
3989       break;
3990     }
3991     case Intrinsic::aarch64_sve_st4: {
3992       if (VT == MVT::nxv16i8) {
3993         SelectPredicatedStore</*Scale=*/0>(Node, 4, AArch64::ST4B,
3994                                            AArch64::ST4B_IMM);
3995         return;
3996       } else if (VT == MVT::nxv8i16 || VT == MVT::nxv8f16) {
3997         SelectPredicatedStore</*Scale=*/1>(Node, 4, AArch64::ST4H,
3998                                            AArch64::ST4H_IMM);
3999         return;
4000       } else if (VT == MVT::nxv4i32 || VT == MVT::nxv4f32) {
4001         SelectPredicatedStore</*Scale=*/2>(Node, 4, AArch64::ST4W,
4002                                            AArch64::ST4W_IMM);
4003         return;
4004       } else if (VT == MVT::nxv2i64 || VT == MVT::nxv2f64) {
4005         SelectPredicatedStore</*Scale=*/3>(Node, 4, AArch64::ST4D,
4006                                            AArch64::ST4D_IMM);
4007         return;
4008       }
4009       break;
4010     }
4011     }
4012     break;
4013   }
4014   case AArch64ISD::LD2post: {
4015     if (VT == MVT::v8i8) {
4016       SelectPostLoad(Node, 2, AArch64::LD2Twov8b_POST, AArch64::dsub0);
4017       return;
4018     } else if (VT == MVT::v16i8) {
4019       SelectPostLoad(Node, 2, AArch64::LD2Twov16b_POST, AArch64::qsub0);
4020       return;
4021     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4022       SelectPostLoad(Node, 2, AArch64::LD2Twov4h_POST, AArch64::dsub0);
4023       return;
4024     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4025       SelectPostLoad(Node, 2, AArch64::LD2Twov8h_POST, AArch64::qsub0);
4026       return;
4027     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4028       SelectPostLoad(Node, 2, AArch64::LD2Twov2s_POST, AArch64::dsub0);
4029       return;
4030     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4031       SelectPostLoad(Node, 2, AArch64::LD2Twov4s_POST, AArch64::qsub0);
4032       return;
4033     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4034       SelectPostLoad(Node, 2, AArch64::LD1Twov1d_POST, AArch64::dsub0);
4035       return;
4036     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4037       SelectPostLoad(Node, 2, AArch64::LD2Twov2d_POST, AArch64::qsub0);
4038       return;
4039     }
4040     break;
4041   }
4042   case AArch64ISD::LD3post: {
4043     if (VT == MVT::v8i8) {
4044       SelectPostLoad(Node, 3, AArch64::LD3Threev8b_POST, AArch64::dsub0);
4045       return;
4046     } else if (VT == MVT::v16i8) {
4047       SelectPostLoad(Node, 3, AArch64::LD3Threev16b_POST, AArch64::qsub0);
4048       return;
4049     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4050       SelectPostLoad(Node, 3, AArch64::LD3Threev4h_POST, AArch64::dsub0);
4051       return;
4052     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4053       SelectPostLoad(Node, 3, AArch64::LD3Threev8h_POST, AArch64::qsub0);
4054       return;
4055     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4056       SelectPostLoad(Node, 3, AArch64::LD3Threev2s_POST, AArch64::dsub0);
4057       return;
4058     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4059       SelectPostLoad(Node, 3, AArch64::LD3Threev4s_POST, AArch64::qsub0);
4060       return;
4061     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4062       SelectPostLoad(Node, 3, AArch64::LD1Threev1d_POST, AArch64::dsub0);
4063       return;
4064     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4065       SelectPostLoad(Node, 3, AArch64::LD3Threev2d_POST, AArch64::qsub0);
4066       return;
4067     }
4068     break;
4069   }
4070   case AArch64ISD::LD4post: {
4071     if (VT == MVT::v8i8) {
4072       SelectPostLoad(Node, 4, AArch64::LD4Fourv8b_POST, AArch64::dsub0);
4073       return;
4074     } else if (VT == MVT::v16i8) {
4075       SelectPostLoad(Node, 4, AArch64::LD4Fourv16b_POST, AArch64::qsub0);
4076       return;
4077     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4078       SelectPostLoad(Node, 4, AArch64::LD4Fourv4h_POST, AArch64::dsub0);
4079       return;
4080     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4081       SelectPostLoad(Node, 4, AArch64::LD4Fourv8h_POST, AArch64::qsub0);
4082       return;
4083     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4084       SelectPostLoad(Node, 4, AArch64::LD4Fourv2s_POST, AArch64::dsub0);
4085       return;
4086     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4087       SelectPostLoad(Node, 4, AArch64::LD4Fourv4s_POST, AArch64::qsub0);
4088       return;
4089     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4090       SelectPostLoad(Node, 4, AArch64::LD1Fourv1d_POST, AArch64::dsub0);
4091       return;
4092     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4093       SelectPostLoad(Node, 4, AArch64::LD4Fourv2d_POST, AArch64::qsub0);
4094       return;
4095     }
4096     break;
4097   }
4098   case AArch64ISD::LD1x2post: {
4099     if (VT == MVT::v8i8) {
4100       SelectPostLoad(Node, 2, AArch64::LD1Twov8b_POST, AArch64::dsub0);
4101       return;
4102     } else if (VT == MVT::v16i8) {
4103       SelectPostLoad(Node, 2, AArch64::LD1Twov16b_POST, AArch64::qsub0);
4104       return;
4105     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4106       SelectPostLoad(Node, 2, AArch64::LD1Twov4h_POST, AArch64::dsub0);
4107       return;
4108     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4109       SelectPostLoad(Node, 2, AArch64::LD1Twov8h_POST, AArch64::qsub0);
4110       return;
4111     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4112       SelectPostLoad(Node, 2, AArch64::LD1Twov2s_POST, AArch64::dsub0);
4113       return;
4114     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4115       SelectPostLoad(Node, 2, AArch64::LD1Twov4s_POST, AArch64::qsub0);
4116       return;
4117     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4118       SelectPostLoad(Node, 2, AArch64::LD1Twov1d_POST, AArch64::dsub0);
4119       return;
4120     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4121       SelectPostLoad(Node, 2, AArch64::LD1Twov2d_POST, AArch64::qsub0);
4122       return;
4123     }
4124     break;
4125   }
4126   case AArch64ISD::LD1x3post: {
4127     if (VT == MVT::v8i8) {
4128       SelectPostLoad(Node, 3, AArch64::LD1Threev8b_POST, AArch64::dsub0);
4129       return;
4130     } else if (VT == MVT::v16i8) {
4131       SelectPostLoad(Node, 3, AArch64::LD1Threev16b_POST, AArch64::qsub0);
4132       return;
4133     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4134       SelectPostLoad(Node, 3, AArch64::LD1Threev4h_POST, AArch64::dsub0);
4135       return;
4136     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4137       SelectPostLoad(Node, 3, AArch64::LD1Threev8h_POST, AArch64::qsub0);
4138       return;
4139     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4140       SelectPostLoad(Node, 3, AArch64::LD1Threev2s_POST, AArch64::dsub0);
4141       return;
4142     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4143       SelectPostLoad(Node, 3, AArch64::LD1Threev4s_POST, AArch64::qsub0);
4144       return;
4145     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4146       SelectPostLoad(Node, 3, AArch64::LD1Threev1d_POST, AArch64::dsub0);
4147       return;
4148     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4149       SelectPostLoad(Node, 3, AArch64::LD1Threev2d_POST, AArch64::qsub0);
4150       return;
4151     }
4152     break;
4153   }
4154   case AArch64ISD::LD1x4post: {
4155     if (VT == MVT::v8i8) {
4156       SelectPostLoad(Node, 4, AArch64::LD1Fourv8b_POST, AArch64::dsub0);
4157       return;
4158     } else if (VT == MVT::v16i8) {
4159       SelectPostLoad(Node, 4, AArch64::LD1Fourv16b_POST, AArch64::qsub0);
4160       return;
4161     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4162       SelectPostLoad(Node, 4, AArch64::LD1Fourv4h_POST, AArch64::dsub0);
4163       return;
4164     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4165       SelectPostLoad(Node, 4, AArch64::LD1Fourv8h_POST, AArch64::qsub0);
4166       return;
4167     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4168       SelectPostLoad(Node, 4, AArch64::LD1Fourv2s_POST, AArch64::dsub0);
4169       return;
4170     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4171       SelectPostLoad(Node, 4, AArch64::LD1Fourv4s_POST, AArch64::qsub0);
4172       return;
4173     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4174       SelectPostLoad(Node, 4, AArch64::LD1Fourv1d_POST, AArch64::dsub0);
4175       return;
4176     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4177       SelectPostLoad(Node, 4, AArch64::LD1Fourv2d_POST, AArch64::qsub0);
4178       return;
4179     }
4180     break;
4181   }
4182   case AArch64ISD::LD1DUPpost: {
4183     if (VT == MVT::v8i8) {
4184       SelectPostLoad(Node, 1, AArch64::LD1Rv8b_POST, AArch64::dsub0);
4185       return;
4186     } else if (VT == MVT::v16i8) {
4187       SelectPostLoad(Node, 1, AArch64::LD1Rv16b_POST, AArch64::qsub0);
4188       return;
4189     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4190       SelectPostLoad(Node, 1, AArch64::LD1Rv4h_POST, AArch64::dsub0);
4191       return;
4192     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4193       SelectPostLoad(Node, 1, AArch64::LD1Rv8h_POST, AArch64::qsub0);
4194       return;
4195     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4196       SelectPostLoad(Node, 1, AArch64::LD1Rv2s_POST, AArch64::dsub0);
4197       return;
4198     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4199       SelectPostLoad(Node, 1, AArch64::LD1Rv4s_POST, AArch64::qsub0);
4200       return;
4201     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4202       SelectPostLoad(Node, 1, AArch64::LD1Rv1d_POST, AArch64::dsub0);
4203       return;
4204     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4205       SelectPostLoad(Node, 1, AArch64::LD1Rv2d_POST, AArch64::qsub0);
4206       return;
4207     }
4208     break;
4209   }
4210   case AArch64ISD::LD2DUPpost: {
4211     if (VT == MVT::v8i8) {
4212       SelectPostLoad(Node, 2, AArch64::LD2Rv8b_POST, AArch64::dsub0);
4213       return;
4214     } else if (VT == MVT::v16i8) {
4215       SelectPostLoad(Node, 2, AArch64::LD2Rv16b_POST, AArch64::qsub0);
4216       return;
4217     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4218       SelectPostLoad(Node, 2, AArch64::LD2Rv4h_POST, AArch64::dsub0);
4219       return;
4220     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4221       SelectPostLoad(Node, 2, AArch64::LD2Rv8h_POST, AArch64::qsub0);
4222       return;
4223     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4224       SelectPostLoad(Node, 2, AArch64::LD2Rv2s_POST, AArch64::dsub0);
4225       return;
4226     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4227       SelectPostLoad(Node, 2, AArch64::LD2Rv4s_POST, AArch64::qsub0);
4228       return;
4229     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4230       SelectPostLoad(Node, 2, AArch64::LD2Rv1d_POST, AArch64::dsub0);
4231       return;
4232     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4233       SelectPostLoad(Node, 2, AArch64::LD2Rv2d_POST, AArch64::qsub0);
4234       return;
4235     }
4236     break;
4237   }
4238   case AArch64ISD::LD3DUPpost: {
4239     if (VT == MVT::v8i8) {
4240       SelectPostLoad(Node, 3, AArch64::LD3Rv8b_POST, AArch64::dsub0);
4241       return;
4242     } else if (VT == MVT::v16i8) {
4243       SelectPostLoad(Node, 3, AArch64::LD3Rv16b_POST, AArch64::qsub0);
4244       return;
4245     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4246       SelectPostLoad(Node, 3, AArch64::LD3Rv4h_POST, AArch64::dsub0);
4247       return;
4248     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4249       SelectPostLoad(Node, 3, AArch64::LD3Rv8h_POST, AArch64::qsub0);
4250       return;
4251     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4252       SelectPostLoad(Node, 3, AArch64::LD3Rv2s_POST, AArch64::dsub0);
4253       return;
4254     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4255       SelectPostLoad(Node, 3, AArch64::LD3Rv4s_POST, AArch64::qsub0);
4256       return;
4257     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4258       SelectPostLoad(Node, 3, AArch64::LD3Rv1d_POST, AArch64::dsub0);
4259       return;
4260     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4261       SelectPostLoad(Node, 3, AArch64::LD3Rv2d_POST, AArch64::qsub0);
4262       return;
4263     }
4264     break;
4265   }
4266   case AArch64ISD::LD4DUPpost: {
4267     if (VT == MVT::v8i8) {
4268       SelectPostLoad(Node, 4, AArch64::LD4Rv8b_POST, AArch64::dsub0);
4269       return;
4270     } else if (VT == MVT::v16i8) {
4271       SelectPostLoad(Node, 4, AArch64::LD4Rv16b_POST, AArch64::qsub0);
4272       return;
4273     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4274       SelectPostLoad(Node, 4, AArch64::LD4Rv4h_POST, AArch64::dsub0);
4275       return;
4276     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4277       SelectPostLoad(Node, 4, AArch64::LD4Rv8h_POST, AArch64::qsub0);
4278       return;
4279     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4280       SelectPostLoad(Node, 4, AArch64::LD4Rv2s_POST, AArch64::dsub0);
4281       return;
4282     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4283       SelectPostLoad(Node, 4, AArch64::LD4Rv4s_POST, AArch64::qsub0);
4284       return;
4285     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4286       SelectPostLoad(Node, 4, AArch64::LD4Rv1d_POST, AArch64::dsub0);
4287       return;
4288     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4289       SelectPostLoad(Node, 4, AArch64::LD4Rv2d_POST, AArch64::qsub0);
4290       return;
4291     }
4292     break;
4293   }
4294   case AArch64ISD::LD1LANEpost: {
4295     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
4296       SelectPostLoadLane(Node, 1, AArch64::LD1i8_POST);
4297       return;
4298     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
4299                VT == MVT::v8f16) {
4300       SelectPostLoadLane(Node, 1, AArch64::LD1i16_POST);
4301       return;
4302     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
4303                VT == MVT::v2f32) {
4304       SelectPostLoadLane(Node, 1, AArch64::LD1i32_POST);
4305       return;
4306     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
4307                VT == MVT::v1f64) {
4308       SelectPostLoadLane(Node, 1, AArch64::LD1i64_POST);
4309       return;
4310     }
4311     break;
4312   }
4313   case AArch64ISD::LD2LANEpost: {
4314     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
4315       SelectPostLoadLane(Node, 2, AArch64::LD2i8_POST);
4316       return;
4317     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
4318                VT == MVT::v8f16) {
4319       SelectPostLoadLane(Node, 2, AArch64::LD2i16_POST);
4320       return;
4321     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
4322                VT == MVT::v2f32) {
4323       SelectPostLoadLane(Node, 2, AArch64::LD2i32_POST);
4324       return;
4325     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
4326                VT == MVT::v1f64) {
4327       SelectPostLoadLane(Node, 2, AArch64::LD2i64_POST);
4328       return;
4329     }
4330     break;
4331   }
4332   case AArch64ISD::LD3LANEpost: {
4333     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
4334       SelectPostLoadLane(Node, 3, AArch64::LD3i8_POST);
4335       return;
4336     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
4337                VT == MVT::v8f16) {
4338       SelectPostLoadLane(Node, 3, AArch64::LD3i16_POST);
4339       return;
4340     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
4341                VT == MVT::v2f32) {
4342       SelectPostLoadLane(Node, 3, AArch64::LD3i32_POST);
4343       return;
4344     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
4345                VT == MVT::v1f64) {
4346       SelectPostLoadLane(Node, 3, AArch64::LD3i64_POST);
4347       return;
4348     }
4349     break;
4350   }
4351   case AArch64ISD::LD4LANEpost: {
4352     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
4353       SelectPostLoadLane(Node, 4, AArch64::LD4i8_POST);
4354       return;
4355     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
4356                VT == MVT::v8f16) {
4357       SelectPostLoadLane(Node, 4, AArch64::LD4i16_POST);
4358       return;
4359     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
4360                VT == MVT::v2f32) {
4361       SelectPostLoadLane(Node, 4, AArch64::LD4i32_POST);
4362       return;
4363     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
4364                VT == MVT::v1f64) {
4365       SelectPostLoadLane(Node, 4, AArch64::LD4i64_POST);
4366       return;
4367     }
4368     break;
4369   }
4370   case AArch64ISD::ST2post: {
4371     VT = Node->getOperand(1).getValueType();
4372     if (VT == MVT::v8i8) {
4373       SelectPostStore(Node, 2, AArch64::ST2Twov8b_POST);
4374       return;
4375     } else if (VT == MVT::v16i8) {
4376       SelectPostStore(Node, 2, AArch64::ST2Twov16b_POST);
4377       return;
4378     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4379       SelectPostStore(Node, 2, AArch64::ST2Twov4h_POST);
4380       return;
4381     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4382       SelectPostStore(Node, 2, AArch64::ST2Twov8h_POST);
4383       return;
4384     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4385       SelectPostStore(Node, 2, AArch64::ST2Twov2s_POST);
4386       return;
4387     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4388       SelectPostStore(Node, 2, AArch64::ST2Twov4s_POST);
4389       return;
4390     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4391       SelectPostStore(Node, 2, AArch64::ST2Twov2d_POST);
4392       return;
4393     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4394       SelectPostStore(Node, 2, AArch64::ST1Twov1d_POST);
4395       return;
4396     }
4397     break;
4398   }
4399   case AArch64ISD::ST3post: {
4400     VT = Node->getOperand(1).getValueType();
4401     if (VT == MVT::v8i8) {
4402       SelectPostStore(Node, 3, AArch64::ST3Threev8b_POST);
4403       return;
4404     } else if (VT == MVT::v16i8) {
4405       SelectPostStore(Node, 3, AArch64::ST3Threev16b_POST);
4406       return;
4407     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4408       SelectPostStore(Node, 3, AArch64::ST3Threev4h_POST);
4409       return;
4410     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4411       SelectPostStore(Node, 3, AArch64::ST3Threev8h_POST);
4412       return;
4413     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4414       SelectPostStore(Node, 3, AArch64::ST3Threev2s_POST);
4415       return;
4416     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4417       SelectPostStore(Node, 3, AArch64::ST3Threev4s_POST);
4418       return;
4419     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4420       SelectPostStore(Node, 3, AArch64::ST3Threev2d_POST);
4421       return;
4422     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4423       SelectPostStore(Node, 3, AArch64::ST1Threev1d_POST);
4424       return;
4425     }
4426     break;
4427   }
4428   case AArch64ISD::ST4post: {
4429     VT = Node->getOperand(1).getValueType();
4430     if (VT == MVT::v8i8) {
4431       SelectPostStore(Node, 4, AArch64::ST4Fourv8b_POST);
4432       return;
4433     } else if (VT == MVT::v16i8) {
4434       SelectPostStore(Node, 4, AArch64::ST4Fourv16b_POST);
4435       return;
4436     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4437       SelectPostStore(Node, 4, AArch64::ST4Fourv4h_POST);
4438       return;
4439     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4440       SelectPostStore(Node, 4, AArch64::ST4Fourv8h_POST);
4441       return;
4442     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4443       SelectPostStore(Node, 4, AArch64::ST4Fourv2s_POST);
4444       return;
4445     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4446       SelectPostStore(Node, 4, AArch64::ST4Fourv4s_POST);
4447       return;
4448     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4449       SelectPostStore(Node, 4, AArch64::ST4Fourv2d_POST);
4450       return;
4451     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4452       SelectPostStore(Node, 4, AArch64::ST1Fourv1d_POST);
4453       return;
4454     }
4455     break;
4456   }
4457   case AArch64ISD::ST1x2post: {
4458     VT = Node->getOperand(1).getValueType();
4459     if (VT == MVT::v8i8) {
4460       SelectPostStore(Node, 2, AArch64::ST1Twov8b_POST);
4461       return;
4462     } else if (VT == MVT::v16i8) {
4463       SelectPostStore(Node, 2, AArch64::ST1Twov16b_POST);
4464       return;
4465     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4466       SelectPostStore(Node, 2, AArch64::ST1Twov4h_POST);
4467       return;
4468     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4469       SelectPostStore(Node, 2, AArch64::ST1Twov8h_POST);
4470       return;
4471     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4472       SelectPostStore(Node, 2, AArch64::ST1Twov2s_POST);
4473       return;
4474     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4475       SelectPostStore(Node, 2, AArch64::ST1Twov4s_POST);
4476       return;
4477     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4478       SelectPostStore(Node, 2, AArch64::ST1Twov1d_POST);
4479       return;
4480     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4481       SelectPostStore(Node, 2, AArch64::ST1Twov2d_POST);
4482       return;
4483     }
4484     break;
4485   }
4486   case AArch64ISD::ST1x3post: {
4487     VT = Node->getOperand(1).getValueType();
4488     if (VT == MVT::v8i8) {
4489       SelectPostStore(Node, 3, AArch64::ST1Threev8b_POST);
4490       return;
4491     } else if (VT == MVT::v16i8) {
4492       SelectPostStore(Node, 3, AArch64::ST1Threev16b_POST);
4493       return;
4494     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4495       SelectPostStore(Node, 3, AArch64::ST1Threev4h_POST);
4496       return;
4497     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4498       SelectPostStore(Node, 3, AArch64::ST1Threev8h_POST);
4499       return;
4500     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4501       SelectPostStore(Node, 3, AArch64::ST1Threev2s_POST);
4502       return;
4503     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4504       SelectPostStore(Node, 3, AArch64::ST1Threev4s_POST);
4505       return;
4506     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4507       SelectPostStore(Node, 3, AArch64::ST1Threev1d_POST);
4508       return;
4509     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4510       SelectPostStore(Node, 3, AArch64::ST1Threev2d_POST);
4511       return;
4512     }
4513     break;
4514   }
4515   case AArch64ISD::ST1x4post: {
4516     VT = Node->getOperand(1).getValueType();
4517     if (VT == MVT::v8i8) {
4518       SelectPostStore(Node, 4, AArch64::ST1Fourv8b_POST);
4519       return;
4520     } else if (VT == MVT::v16i8) {
4521       SelectPostStore(Node, 4, AArch64::ST1Fourv16b_POST);
4522       return;
4523     } else if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4524       SelectPostStore(Node, 4, AArch64::ST1Fourv4h_POST);
4525       return;
4526     } else if (VT == MVT::v8i16 || VT == MVT::v8f16) {
4527       SelectPostStore(Node, 4, AArch64::ST1Fourv8h_POST);
4528       return;
4529     } else if (VT == MVT::v2i32 || VT == MVT::v2f32) {
4530       SelectPostStore(Node, 4, AArch64::ST1Fourv2s_POST);
4531       return;
4532     } else if (VT == MVT::v4i32 || VT == MVT::v4f32) {
4533       SelectPostStore(Node, 4, AArch64::ST1Fourv4s_POST);
4534       return;
4535     } else if (VT == MVT::v1i64 || VT == MVT::v1f64) {
4536       SelectPostStore(Node, 4, AArch64::ST1Fourv1d_POST);
4537       return;
4538     } else if (VT == MVT::v2i64 || VT == MVT::v2f64) {
4539       SelectPostStore(Node, 4, AArch64::ST1Fourv2d_POST);
4540       return;
4541     }
4542     break;
4543   }
4544   case AArch64ISD::ST2LANEpost: {
4545     VT = Node->getOperand(1).getValueType();
4546     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
4547       SelectPostStoreLane(Node, 2, AArch64::ST2i8_POST);
4548       return;
4549     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
4550                VT == MVT::v8f16) {
4551       SelectPostStoreLane(Node, 2, AArch64::ST2i16_POST);
4552       return;
4553     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
4554                VT == MVT::v2f32) {
4555       SelectPostStoreLane(Node, 2, AArch64::ST2i32_POST);
4556       return;
4557     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
4558                VT == MVT::v1f64) {
4559       SelectPostStoreLane(Node, 2, AArch64::ST2i64_POST);
4560       return;
4561     }
4562     break;
4563   }
4564   case AArch64ISD::ST3LANEpost: {
4565     VT = Node->getOperand(1).getValueType();
4566     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
4567       SelectPostStoreLane(Node, 3, AArch64::ST3i8_POST);
4568       return;
4569     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
4570                VT == MVT::v8f16) {
4571       SelectPostStoreLane(Node, 3, AArch64::ST3i16_POST);
4572       return;
4573     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
4574                VT == MVT::v2f32) {
4575       SelectPostStoreLane(Node, 3, AArch64::ST3i32_POST);
4576       return;
4577     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
4578                VT == MVT::v1f64) {
4579       SelectPostStoreLane(Node, 3, AArch64::ST3i64_POST);
4580       return;
4581     }
4582     break;
4583   }
4584   case AArch64ISD::ST4LANEpost: {
4585     VT = Node->getOperand(1).getValueType();
4586     if (VT == MVT::v16i8 || VT == MVT::v8i8) {
4587       SelectPostStoreLane(Node, 4, AArch64::ST4i8_POST);
4588       return;
4589     } else if (VT == MVT::v8i16 || VT == MVT::v4i16 || VT == MVT::v4f16 ||
4590                VT == MVT::v8f16) {
4591       SelectPostStoreLane(Node, 4, AArch64::ST4i16_POST);
4592       return;
4593     } else if (VT == MVT::v4i32 || VT == MVT::v2i32 || VT == MVT::v4f32 ||
4594                VT == MVT::v2f32) {
4595       SelectPostStoreLane(Node, 4, AArch64::ST4i32_POST);
4596       return;
4597     } else if (VT == MVT::v2i64 || VT == MVT::v1i64 || VT == MVT::v2f64 ||
4598                VT == MVT::v1f64) {
4599       SelectPostStoreLane(Node, 4, AArch64::ST4i64_POST);
4600       return;
4601     }
4602     break;
4603   }
4604   }
4605 
4606   // Select the default instruction
4607   SelectCode(Node);
4608 }
4609 
4610 /// createAArch64ISelDag - This pass converts a legalized DAG into a
4611 /// AArch64-specific DAG, ready for instruction scheduling.
4612 FunctionPass *llvm::createAArch64ISelDag(AArch64TargetMachine &TM,
4613                                          CodeGenOpt::Level OptLevel) {
4614   return new AArch64DAGToDAGISel(TM, OptLevel);
4615 }
4616 
4617 /// When \p PredVT is a scalable vector predicate in the form
4618 /// MVT::nx<M>xi1, it builds the correspondent scalable vector of
4619 /// integers MVT::nx<M>xi<bits> s.t. M x bits = 128. If the input
4620 /// PredVT is not in the form MVT::nx<M>xi1, it returns an invalid
4621 /// EVT.
4622 static EVT getPackedVectorTypeFromPredicateType(LLVMContext &Ctx, EVT PredVT) {
4623   if (!PredVT.isScalableVector() || PredVT.getVectorElementType() != MVT::i1)
4624     return EVT();
4625 
4626   const unsigned NumElts = PredVT.getVectorNumElements();
4627 
4628   if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
4629     return EVT();
4630 
4631   EVT ScalarVT = EVT::getIntegerVT(Ctx, AArch64::SVEBitsPerBlock / NumElts);
4632   EVT MemVT = EVT::getVectorVT(Ctx, ScalarVT, NumElts, /*IsScalable=*/true);
4633   return MemVT;
4634 }
4635 
4636 /// Return the EVT of the data associated to a memory operation in \p
4637 /// Root. If such EVT cannot be retrived, it returns an invalid EVT.
4638 static EVT getMemVTFromNode(LLVMContext &Ctx, SDNode *Root) {
4639   if (isa<MemSDNode>(Root))
4640     return cast<MemSDNode>(Root)->getMemoryVT();
4641 
4642   if (isa<MemIntrinsicSDNode>(Root))
4643     return cast<MemIntrinsicSDNode>(Root)->getMemoryVT();
4644 
4645   const unsigned Opcode = Root->getOpcode();
4646   // For custom ISD nodes, we have to look at them individually to extract the
4647   // type of the data moved to/from memory.
4648   switch (Opcode) {
4649   case AArch64ISD::LD1:
4650   case AArch64ISD::LD1S:
4651   case AArch64ISD::LDNF1:
4652   case AArch64ISD::LDNF1S:
4653     return cast<VTSDNode>(Root->getOperand(3))->getVT();
4654   case AArch64ISD::ST1:
4655     return cast<VTSDNode>(Root->getOperand(4))->getVT();
4656   default:
4657     break;
4658   }
4659 
4660   if (Opcode != ISD::INTRINSIC_VOID)
4661     return EVT();
4662 
4663   const unsigned IntNo =
4664       cast<ConstantSDNode>(Root->getOperand(1))->getZExtValue();
4665   if (IntNo != Intrinsic::aarch64_sve_prf)
4666     return EVT();
4667 
4668   // We are using an SVE prefetch intrinsic. Type must be inferred
4669   // from the width of the predicate.
4670   return getPackedVectorTypeFromPredicateType(
4671       Ctx, Root->getOperand(2)->getValueType(0));
4672 }
4673 
4674 /// SelectAddrModeIndexedSVE - Attempt selection of the addressing mode:
4675 /// Base + OffImm * sizeof(MemVT) for Min >= OffImm <= Max
4676 /// where Root is the memory access using N for its address.
4677 template <int64_t Min, int64_t Max>
4678 bool AArch64DAGToDAGISel::SelectAddrModeIndexedSVE(SDNode *Root, SDValue N,
4679                                                    SDValue &Base,
4680                                                    SDValue &OffImm) {
4681   const EVT MemVT = getMemVTFromNode(*(CurDAG->getContext()), Root);
4682 
4683   if (MemVT == EVT())
4684     return false;
4685 
4686   if (N.getOpcode() != ISD::ADD)
4687     return false;
4688 
4689   SDValue VScale = N.getOperand(1);
4690   if (VScale.getOpcode() != ISD::VSCALE)
4691     return false;
4692 
4693   TypeSize TS = MemVT.getSizeInBits();
4694   int64_t MemWidthBytes = static_cast<int64_t>(TS.getKnownMinSize()) / 8;
4695   int64_t MulImm = cast<ConstantSDNode>(VScale.getOperand(0))->getSExtValue();
4696 
4697   if ((MulImm % MemWidthBytes) != 0)
4698     return false;
4699 
4700   int64_t Offset = MulImm / MemWidthBytes;
4701   if (Offset < Min || Offset > Max)
4702     return false;
4703 
4704   Base = N.getOperand(0);
4705   OffImm = CurDAG->getTargetConstant(Offset, SDLoc(N), MVT::i64);
4706   return true;
4707 }
4708 
4709 /// Select register plus register addressing mode for SVE, with scaled
4710 /// offset.
4711 bool AArch64DAGToDAGISel::SelectSVERegRegAddrMode(SDValue N, unsigned Scale,
4712                                                   SDValue &Base,
4713                                                   SDValue &Offset) {
4714   if (N.getOpcode() != ISD::ADD)
4715     return false;
4716 
4717   // Process an ADD node.
4718   const SDValue LHS = N.getOperand(0);
4719   const SDValue RHS = N.getOperand(1);
4720 
4721   // 8 bit data does not come with the SHL node, so it is treated
4722   // separately.
4723   if (Scale == 0) {
4724     Base = LHS;
4725     Offset = RHS;
4726     return true;
4727   }
4728 
4729   // Check if the RHS is a shift node with a constant.
4730   if (RHS.getOpcode() != ISD::SHL)
4731     return false;
4732 
4733   const SDValue ShiftRHS = RHS.getOperand(1);
4734   if (auto *C = dyn_cast<ConstantSDNode>(ShiftRHS))
4735     if (C->getZExtValue() == Scale) {
4736       Base = LHS;
4737       Offset = RHS.getOperand(0);
4738       return true;
4739     }
4740 
4741   return false;
4742 }
4743