xref: /llvm-project/llvm/lib/Target/ARM/ARMISelDAGToDAG.cpp (revision e41d383440883fa2f87012b765fcc2d450f6fd55)
1 //===-- ARMISelDAGToDAG.cpp - A dag to dag inst selector for ARM ----------===//
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 ARM target.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ARM.h"
14 #include "ARMBaseInstrInfo.h"
15 #include "ARMTargetMachine.h"
16 #include "MCTargetDesc/ARMAddressingModes.h"
17 #include "Utils/ARMBaseInfo.h"
18 #include "llvm/ADT/APSInt.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/CodeGen/SelectionDAGISel.h"
26 #include "llvm/CodeGen/TargetLowering.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/IntrinsicsARM.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include <optional>
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "arm-isel"
43 #define PASS_NAME "ARM Instruction Selection"
44 
45 static cl::opt<bool>
46 DisableShifterOp("disable-shifter-op", cl::Hidden,
47   cl::desc("Disable isel of shifter-op"),
48   cl::init(false));
49 
50 //===--------------------------------------------------------------------===//
51 /// ARMDAGToDAGISel - ARM specific code to select ARM machine
52 /// instructions for SelectionDAG operations.
53 ///
54 namespace {
55 
56 class ARMDAGToDAGISel : public SelectionDAGISel {
57   /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
58   /// make the right decision when generating code for different targets.
59   const ARMSubtarget *Subtarget;
60 
61 public:
62   static char ID;
63 
64   ARMDAGToDAGISel() = delete;
65 
66   explicit ARMDAGToDAGISel(ARMBaseTargetMachine &tm, CodeGenOpt::Level OptLevel)
67       : SelectionDAGISel(ID, tm, OptLevel) {}
68 
69   bool runOnMachineFunction(MachineFunction &MF) override {
70     // Reset the subtarget each time through.
71     Subtarget = &MF.getSubtarget<ARMSubtarget>();
72     SelectionDAGISel::runOnMachineFunction(MF);
73     return true;
74   }
75 
76   void PreprocessISelDAG() override;
77 
78   /// getI32Imm - Return a target constant of type i32 with the specified
79   /// value.
80   inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
81     return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
82   }
83 
84   void Select(SDNode *N) override;
85 
86   /// Return true as some complex patterns, like those that call
87   /// canExtractShiftFromMul can modify the DAG inplace.
88   bool ComplexPatternFuncMutatesDAG() const override { return true; }
89 
90   bool hasNoVMLxHazardUse(SDNode *N) const;
91   bool isShifterOpProfitable(const SDValue &Shift,
92                              ARM_AM::ShiftOpc ShOpcVal, unsigned ShAmt);
93   bool SelectRegShifterOperand(SDValue N, SDValue &A,
94                                SDValue &B, SDValue &C,
95                                bool CheckProfitability = true);
96   bool SelectImmShifterOperand(SDValue N, SDValue &A,
97                                SDValue &B, bool CheckProfitability = true);
98   bool SelectShiftRegShifterOperand(SDValue N, SDValue &A, SDValue &B,
99                                     SDValue &C) {
100     // Don't apply the profitability check
101     return SelectRegShifterOperand(N, A, B, C, false);
102   }
103   bool SelectShiftImmShifterOperand(SDValue N, SDValue &A, SDValue &B) {
104     // Don't apply the profitability check
105     return SelectImmShifterOperand(N, A, B, false);
106   }
107   bool SelectShiftImmShifterOperandOneUse(SDValue N, SDValue &A, SDValue &B) {
108     if (!N.hasOneUse())
109       return false;
110     return SelectImmShifterOperand(N, A, B, false);
111   }
112 
113   bool SelectAddLikeOr(SDNode *Parent, SDValue N, SDValue &Out);
114 
115   bool SelectAddrModeImm12(SDValue N, SDValue &Base, SDValue &OffImm);
116   bool SelectLdStSOReg(SDValue N, SDValue &Base, SDValue &Offset, SDValue &Opc);
117 
118   bool SelectCMOVPred(SDValue N, SDValue &Pred, SDValue &Reg) {
119     const ConstantSDNode *CN = cast<ConstantSDNode>(N);
120     Pred = CurDAG->getTargetConstant(CN->getZExtValue(), SDLoc(N), MVT::i32);
121     Reg = CurDAG->getRegister(ARM::CPSR, MVT::i32);
122     return true;
123   }
124 
125   bool SelectAddrMode2OffsetReg(SDNode *Op, SDValue N,
126                              SDValue &Offset, SDValue &Opc);
127   bool SelectAddrMode2OffsetImm(SDNode *Op, SDValue N,
128                              SDValue &Offset, SDValue &Opc);
129   bool SelectAddrMode2OffsetImmPre(SDNode *Op, SDValue N,
130                              SDValue &Offset, SDValue &Opc);
131   bool SelectAddrOffsetNone(SDValue N, SDValue &Base);
132   bool SelectAddrMode3(SDValue N, SDValue &Base,
133                        SDValue &Offset, SDValue &Opc);
134   bool SelectAddrMode3Offset(SDNode *Op, SDValue N,
135                              SDValue &Offset, SDValue &Opc);
136   bool IsAddressingMode5(SDValue N, SDValue &Base, SDValue &Offset, bool FP16);
137   bool SelectAddrMode5(SDValue N, SDValue &Base, SDValue &Offset);
138   bool SelectAddrMode5FP16(SDValue N, SDValue &Base, SDValue &Offset);
139   bool SelectAddrMode6(SDNode *Parent, SDValue N, SDValue &Addr,SDValue &Align);
140   bool SelectAddrMode6Offset(SDNode *Op, SDValue N, SDValue &Offset);
141 
142   bool SelectAddrModePC(SDValue N, SDValue &Offset, SDValue &Label);
143 
144   // Thumb Addressing Modes:
145   bool SelectThumbAddrModeRR(SDValue N, SDValue &Base, SDValue &Offset);
146   bool SelectThumbAddrModeRRSext(SDValue N, SDValue &Base, SDValue &Offset);
147   bool SelectThumbAddrModeImm5S(SDValue N, unsigned Scale, SDValue &Base,
148                                 SDValue &OffImm);
149   bool SelectThumbAddrModeImm5S1(SDValue N, SDValue &Base,
150                                  SDValue &OffImm);
151   bool SelectThumbAddrModeImm5S2(SDValue N, SDValue &Base,
152                                  SDValue &OffImm);
153   bool SelectThumbAddrModeImm5S4(SDValue N, SDValue &Base,
154                                  SDValue &OffImm);
155   bool SelectThumbAddrModeSP(SDValue N, SDValue &Base, SDValue &OffImm);
156   template <unsigned Shift>
157   bool SelectTAddrModeImm7(SDValue N, SDValue &Base, SDValue &OffImm);
158 
159   // Thumb 2 Addressing Modes:
160   bool SelectT2AddrModeImm12(SDValue N, SDValue &Base, SDValue &OffImm);
161   template <unsigned Shift>
162   bool SelectT2AddrModeImm8(SDValue N, SDValue &Base, SDValue &OffImm);
163   bool SelectT2AddrModeImm8(SDValue N, SDValue &Base,
164                             SDValue &OffImm);
165   bool SelectT2AddrModeImm8Offset(SDNode *Op, SDValue N,
166                                  SDValue &OffImm);
167   template <unsigned Shift>
168   bool SelectT2AddrModeImm7Offset(SDNode *Op, SDValue N, SDValue &OffImm);
169   bool SelectT2AddrModeImm7Offset(SDNode *Op, SDValue N, SDValue &OffImm,
170                                   unsigned Shift);
171   template <unsigned Shift>
172   bool SelectT2AddrModeImm7(SDValue N, SDValue &Base, SDValue &OffImm);
173   bool SelectT2AddrModeSoReg(SDValue N, SDValue &Base,
174                              SDValue &OffReg, SDValue &ShImm);
175   bool SelectT2AddrModeExclusive(SDValue N, SDValue &Base, SDValue &OffImm);
176 
177   template<int Min, int Max>
178   bool SelectImmediateInRange(SDValue N, SDValue &OffImm);
179 
180   inline bool is_so_imm(unsigned Imm) const {
181     return ARM_AM::getSOImmVal(Imm) != -1;
182   }
183 
184   inline bool is_so_imm_not(unsigned Imm) const {
185     return ARM_AM::getSOImmVal(~Imm) != -1;
186   }
187 
188   inline bool is_t2_so_imm(unsigned Imm) const {
189     return ARM_AM::getT2SOImmVal(Imm) != -1;
190   }
191 
192   inline bool is_t2_so_imm_not(unsigned Imm) const {
193     return ARM_AM::getT2SOImmVal(~Imm) != -1;
194   }
195 
196   // Include the pieces autogenerated from the target description.
197 #include "ARMGenDAGISel.inc"
198 
199 private:
200   void transferMemOperands(SDNode *Src, SDNode *Dst);
201 
202   /// Indexed (pre/post inc/dec) load matching code for ARM.
203   bool tryARMIndexedLoad(SDNode *N);
204   bool tryT1IndexedLoad(SDNode *N);
205   bool tryT2IndexedLoad(SDNode *N);
206   bool tryMVEIndexedLoad(SDNode *N);
207   bool tryFMULFixed(SDNode *N, SDLoc dl);
208   bool tryFP_TO_INT(SDNode *N, SDLoc dl);
209   bool transformFixedFloatingPointConversion(SDNode *N, SDNode *FMul,
210                                              bool IsUnsigned,
211                                              bool FixedToFloat);
212 
213   /// SelectVLD - Select NEON load intrinsics.  NumVecs should be
214   /// 1, 2, 3 or 4.  The opcode arrays specify the instructions used for
215   /// loads of D registers and even subregs and odd subregs of Q registers.
216   /// For NumVecs <= 2, QOpcodes1 is not used.
217   void SelectVLD(SDNode *N, bool isUpdating, unsigned NumVecs,
218                  const uint16_t *DOpcodes, const uint16_t *QOpcodes0,
219                  const uint16_t *QOpcodes1);
220 
221   /// SelectVST - Select NEON store intrinsics.  NumVecs should
222   /// be 1, 2, 3 or 4.  The opcode arrays specify the instructions used for
223   /// stores of D registers and even subregs and odd subregs of Q registers.
224   /// For NumVecs <= 2, QOpcodes1 is not used.
225   void SelectVST(SDNode *N, bool isUpdating, unsigned NumVecs,
226                  const uint16_t *DOpcodes, const uint16_t *QOpcodes0,
227                  const uint16_t *QOpcodes1);
228 
229   /// SelectVLDSTLane - Select NEON load/store lane intrinsics.  NumVecs should
230   /// be 2, 3 or 4.  The opcode arrays specify the instructions used for
231   /// load/store of D registers and Q registers.
232   void SelectVLDSTLane(SDNode *N, bool IsLoad, bool isUpdating,
233                        unsigned NumVecs, const uint16_t *DOpcodes,
234                        const uint16_t *QOpcodes);
235 
236   /// Helper functions for setting up clusters of MVE predication operands.
237   template <typename SDValueVector>
238   void AddMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc,
239                             SDValue PredicateMask);
240   template <typename SDValueVector>
241   void AddMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc,
242                             SDValue PredicateMask, SDValue Inactive);
243 
244   template <typename SDValueVector>
245   void AddEmptyMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc);
246   template <typename SDValueVector>
247   void AddEmptyMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc, EVT InactiveTy);
248 
249   /// SelectMVE_WB - Select MVE writeback load/store intrinsics.
250   void SelectMVE_WB(SDNode *N, const uint16_t *Opcodes, bool Predicated);
251 
252   /// SelectMVE_LongShift - Select MVE 64-bit scalar shift intrinsics.
253   void SelectMVE_LongShift(SDNode *N, uint16_t Opcode, bool Immediate,
254                            bool HasSaturationOperand);
255 
256   /// SelectMVE_VADCSBC - Select MVE vector add/sub-with-carry intrinsics.
257   void SelectMVE_VADCSBC(SDNode *N, uint16_t OpcodeWithCarry,
258                          uint16_t OpcodeWithNoCarry, bool Add, bool Predicated);
259 
260   /// SelectMVE_VSHLC - Select MVE intrinsics for a shift that carries between
261   /// vector lanes.
262   void SelectMVE_VSHLC(SDNode *N, bool Predicated);
263 
264   /// Select long MVE vector reductions with two vector operands
265   /// Stride is the number of vector element widths the instruction can operate
266   /// on:
267   /// 2 for long non-rounding variants, vml{a,s}ldav[a][x]: [i16, i32]
268   /// 1 for long rounding variants: vrml{a,s}ldavh[a][x]: [i32]
269   /// Stride is used when addressing the OpcodesS array which contains multiple
270   /// opcodes for each element width.
271   /// TySize is the index into the list of element types listed above
272   void SelectBaseMVE_VMLLDAV(SDNode *N, bool Predicated,
273                              const uint16_t *OpcodesS, const uint16_t *OpcodesU,
274                              size_t Stride, size_t TySize);
275 
276   /// Select a 64-bit MVE vector reduction with two vector operands
277   /// arm_mve_vmlldava_[predicated]
278   void SelectMVE_VMLLDAV(SDNode *N, bool Predicated, const uint16_t *OpcodesS,
279                          const uint16_t *OpcodesU);
280   /// Select a 72-bit MVE vector rounding reduction with two vector operands
281   /// int_arm_mve_vrmlldavha[_predicated]
282   void SelectMVE_VRMLLDAVH(SDNode *N, bool Predicated, const uint16_t *OpcodesS,
283                            const uint16_t *OpcodesU);
284 
285   /// SelectMVE_VLD - Select MVE interleaving load intrinsics. NumVecs
286   /// should be 2 or 4. The opcode array specifies the instructions
287   /// used for 8, 16 and 32-bit lane sizes respectively, and each
288   /// pointer points to a set of NumVecs sub-opcodes used for the
289   /// different stages (e.g. VLD20 versus VLD21) of each load family.
290   void SelectMVE_VLD(SDNode *N, unsigned NumVecs,
291                      const uint16_t *const *Opcodes, bool HasWriteback);
292 
293   /// SelectMVE_VxDUP - Select MVE incrementing-dup instructions. Opcodes is an
294   /// array of 3 elements for the 8, 16 and 32-bit lane sizes.
295   void SelectMVE_VxDUP(SDNode *N, const uint16_t *Opcodes,
296                        bool Wrapping, bool Predicated);
297 
298   /// Select SelectCDE_CXxD - Select CDE dual-GPR instruction (one of CX1D,
299   /// CX1DA, CX2D, CX2DA, CX3, CX3DA).
300   /// \arg \c NumExtraOps number of extra operands besides the coprocossor,
301   ///                     the accumulator and the immediate operand, i.e. 0
302   ///                     for CX1*, 1 for CX2*, 2 for CX3*
303   /// \arg \c HasAccum whether the instruction has an accumulator operand
304   void SelectCDE_CXxD(SDNode *N, uint16_t Opcode, size_t NumExtraOps,
305                       bool HasAccum);
306 
307   /// SelectVLDDup - Select NEON load-duplicate intrinsics.  NumVecs
308   /// should be 1, 2, 3 or 4.  The opcode array specifies the instructions used
309   /// for loading D registers.
310   void SelectVLDDup(SDNode *N, bool IsIntrinsic, bool isUpdating,
311                     unsigned NumVecs, const uint16_t *DOpcodes,
312                     const uint16_t *QOpcodes0 = nullptr,
313                     const uint16_t *QOpcodes1 = nullptr);
314 
315   /// Try to select SBFX/UBFX instructions for ARM.
316   bool tryV6T2BitfieldExtractOp(SDNode *N, bool isSigned);
317 
318   bool tryInsertVectorElt(SDNode *N);
319 
320   // Select special operations if node forms integer ABS pattern
321   bool tryABSOp(SDNode *N);
322 
323   bool tryReadRegister(SDNode *N);
324   bool tryWriteRegister(SDNode *N);
325 
326   bool tryInlineAsm(SDNode *N);
327 
328   void SelectCMPZ(SDNode *N, bool &SwitchEQNEToPLMI);
329 
330   void SelectCMP_SWAP(SDNode *N);
331 
332   /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
333   /// inline asm expressions.
334   bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
335                                     std::vector<SDValue> &OutOps) override;
336 
337   // Form pairs of consecutive R, S, D, or Q registers.
338   SDNode *createGPRPairNode(EVT VT, SDValue V0, SDValue V1);
339   SDNode *createSRegPairNode(EVT VT, SDValue V0, SDValue V1);
340   SDNode *createDRegPairNode(EVT VT, SDValue V0, SDValue V1);
341   SDNode *createQRegPairNode(EVT VT, SDValue V0, SDValue V1);
342 
343   // Form sequences of 4 consecutive S, D, or Q registers.
344   SDNode *createQuadSRegsNode(EVT VT, SDValue V0, SDValue V1, SDValue V2, SDValue V3);
345   SDNode *createQuadDRegsNode(EVT VT, SDValue V0, SDValue V1, SDValue V2, SDValue V3);
346   SDNode *createQuadQRegsNode(EVT VT, SDValue V0, SDValue V1, SDValue V2, SDValue V3);
347 
348   // Get the alignment operand for a NEON VLD or VST instruction.
349   SDValue GetVLDSTAlign(SDValue Align, const SDLoc &dl, unsigned NumVecs,
350                         bool is64BitVector);
351 
352   /// Checks if N is a multiplication by a constant where we can extract out a
353   /// power of two from the constant so that it can be used in a shift, but only
354   /// if it simplifies the materialization of the constant. Returns true if it
355   /// is, and assigns to PowerOfTwo the power of two that should be extracted
356   /// out and to NewMulConst the new constant to be multiplied by.
357   bool canExtractShiftFromMul(const SDValue &N, unsigned MaxShift,
358                               unsigned &PowerOfTwo, SDValue &NewMulConst) const;
359 
360   /// Replace N with M in CurDAG, in a way that also ensures that M gets
361   /// selected when N would have been selected.
362   void replaceDAGValue(const SDValue &N, SDValue M);
363 };
364 }
365 
366 char ARMDAGToDAGISel::ID = 0;
367 
368 INITIALIZE_PASS(ARMDAGToDAGISel, DEBUG_TYPE, PASS_NAME, false, false)
369 
370 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
371 /// operand. If so Imm will receive the 32-bit value.
372 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
373   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
374     Imm = cast<ConstantSDNode>(N)->getZExtValue();
375     return true;
376   }
377   return false;
378 }
379 
380 // isInt32Immediate - This method tests to see if a constant operand.
381 // If so Imm will receive the 32 bit value.
382 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
383   return isInt32Immediate(N.getNode(), Imm);
384 }
385 
386 // isOpcWithIntImmediate - This method tests to see if the node is a specific
387 // opcode and that it has a immediate integer right operand.
388 // If so Imm will receive the 32 bit value.
389 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
390   return N->getOpcode() == Opc &&
391          isInt32Immediate(N->getOperand(1).getNode(), Imm);
392 }
393 
394 /// Check whether a particular node is a constant value representable as
395 /// (N * Scale) where (N in [\p RangeMin, \p RangeMax).
396 ///
397 /// \param ScaledConstant [out] - On success, the pre-scaled constant value.
398 static bool isScaledConstantInRange(SDValue Node, int Scale,
399                                     int RangeMin, int RangeMax,
400                                     int &ScaledConstant) {
401   assert(Scale > 0 && "Invalid scale!");
402 
403   // Check that this is a constant.
404   const ConstantSDNode *C = dyn_cast<ConstantSDNode>(Node);
405   if (!C)
406     return false;
407 
408   ScaledConstant = (int) C->getZExtValue();
409   if ((ScaledConstant % Scale) != 0)
410     return false;
411 
412   ScaledConstant /= Scale;
413   return ScaledConstant >= RangeMin && ScaledConstant < RangeMax;
414 }
415 
416 void ARMDAGToDAGISel::PreprocessISelDAG() {
417   if (!Subtarget->hasV6T2Ops())
418     return;
419 
420   bool isThumb2 = Subtarget->isThumb();
421   // We use make_early_inc_range to avoid invalidation issues.
422   for (SDNode &N : llvm::make_early_inc_range(CurDAG->allnodes())) {
423     if (N.getOpcode() != ISD::ADD)
424       continue;
425 
426     // Look for (add X1, (and (srl X2, c1), c2)) where c2 is constant with
427     // leading zeros, followed by consecutive set bits, followed by 1 or 2
428     // trailing zeros, e.g. 1020.
429     // Transform the expression to
430     // (add X1, (shl (and (srl X2, c1), (c2>>tz)), tz)) where tz is the number
431     // of trailing zeros of c2. The left shift would be folded as an shifter
432     // operand of 'add' and the 'and' and 'srl' would become a bits extraction
433     // node (UBFX).
434 
435     SDValue N0 = N.getOperand(0);
436     SDValue N1 = N.getOperand(1);
437     unsigned And_imm = 0;
438     if (!isOpcWithIntImmediate(N1.getNode(), ISD::AND, And_imm)) {
439       if (isOpcWithIntImmediate(N0.getNode(), ISD::AND, And_imm))
440         std::swap(N0, N1);
441     }
442     if (!And_imm)
443       continue;
444 
445     // Check if the AND mask is an immediate of the form: 000.....1111111100
446     unsigned TZ = llvm::countr_zero(And_imm);
447     if (TZ != 1 && TZ != 2)
448       // Be conservative here. Shifter operands aren't always free. e.g. On
449       // Swift, left shifter operand of 1 / 2 for free but others are not.
450       // e.g.
451       //  ubfx   r3, r1, #16, #8
452       //  ldr.w  r3, [r0, r3, lsl #2]
453       // vs.
454       //  mov.w  r9, #1020
455       //  and.w  r2, r9, r1, lsr #14
456       //  ldr    r2, [r0, r2]
457       continue;
458     And_imm >>= TZ;
459     if (And_imm & (And_imm + 1))
460       continue;
461 
462     // Look for (and (srl X, c1), c2).
463     SDValue Srl = N1.getOperand(0);
464     unsigned Srl_imm = 0;
465     if (!isOpcWithIntImmediate(Srl.getNode(), ISD::SRL, Srl_imm) ||
466         (Srl_imm <= 2))
467       continue;
468 
469     // Make sure first operand is not a shifter operand which would prevent
470     // folding of the left shift.
471     SDValue CPTmp0;
472     SDValue CPTmp1;
473     SDValue CPTmp2;
474     if (isThumb2) {
475       if (SelectImmShifterOperand(N0, CPTmp0, CPTmp1))
476         continue;
477     } else {
478       if (SelectImmShifterOperand(N0, CPTmp0, CPTmp1) ||
479           SelectRegShifterOperand(N0, CPTmp0, CPTmp1, CPTmp2))
480         continue;
481     }
482 
483     // Now make the transformation.
484     Srl = CurDAG->getNode(ISD::SRL, SDLoc(Srl), MVT::i32,
485                           Srl.getOperand(0),
486                           CurDAG->getConstant(Srl_imm + TZ, SDLoc(Srl),
487                                               MVT::i32));
488     N1 = CurDAG->getNode(ISD::AND, SDLoc(N1), MVT::i32,
489                          Srl,
490                          CurDAG->getConstant(And_imm, SDLoc(Srl), MVT::i32));
491     N1 = CurDAG->getNode(ISD::SHL, SDLoc(N1), MVT::i32,
492                          N1, CurDAG->getConstant(TZ, SDLoc(Srl), MVT::i32));
493     CurDAG->UpdateNodeOperands(&N, N0, N1);
494   }
495 }
496 
497 /// hasNoVMLxHazardUse - Return true if it's desirable to select a FP MLA / MLS
498 /// node. VFP / NEON fp VMLA / VMLS instructions have special RAW hazards (at
499 /// least on current ARM implementations) which should be avoidded.
500 bool ARMDAGToDAGISel::hasNoVMLxHazardUse(SDNode *N) const {
501   if (OptLevel == CodeGenOpt::None)
502     return true;
503 
504   if (!Subtarget->hasVMLxHazards())
505     return true;
506 
507   if (!N->hasOneUse())
508     return false;
509 
510   SDNode *Use = *N->use_begin();
511   if (Use->getOpcode() == ISD::CopyToReg)
512     return true;
513   if (Use->isMachineOpcode()) {
514     const ARMBaseInstrInfo *TII = static_cast<const ARMBaseInstrInfo *>(
515         CurDAG->getSubtarget().getInstrInfo());
516 
517     const MCInstrDesc &MCID = TII->get(Use->getMachineOpcode());
518     if (MCID.mayStore())
519       return true;
520     unsigned Opcode = MCID.getOpcode();
521     if (Opcode == ARM::VMOVRS || Opcode == ARM::VMOVRRD)
522       return true;
523     // vmlx feeding into another vmlx. We actually want to unfold
524     // the use later in the MLxExpansion pass. e.g.
525     // vmla
526     // vmla (stall 8 cycles)
527     //
528     // vmul (5 cycles)
529     // vadd (5 cycles)
530     // vmla
531     // This adds up to about 18 - 19 cycles.
532     //
533     // vmla
534     // vmul (stall 4 cycles)
535     // vadd adds up to about 14 cycles.
536     return TII->isFpMLxInstruction(Opcode);
537   }
538 
539   return false;
540 }
541 
542 bool ARMDAGToDAGISel::isShifterOpProfitable(const SDValue &Shift,
543                                             ARM_AM::ShiftOpc ShOpcVal,
544                                             unsigned ShAmt) {
545   if (!Subtarget->isLikeA9() && !Subtarget->isSwift())
546     return true;
547   if (Shift.hasOneUse())
548     return true;
549   // R << 2 is free.
550   return ShOpcVal == ARM_AM::lsl &&
551          (ShAmt == 2 || (Subtarget->isSwift() && ShAmt == 1));
552 }
553 
554 bool ARMDAGToDAGISel::canExtractShiftFromMul(const SDValue &N,
555                                              unsigned MaxShift,
556                                              unsigned &PowerOfTwo,
557                                              SDValue &NewMulConst) const {
558   assert(N.getOpcode() == ISD::MUL);
559   assert(MaxShift > 0);
560 
561   // If the multiply is used in more than one place then changing the constant
562   // will make other uses incorrect, so don't.
563   if (!N.hasOneUse()) return false;
564   // Check if the multiply is by a constant
565   ConstantSDNode *MulConst = dyn_cast<ConstantSDNode>(N.getOperand(1));
566   if (!MulConst) return false;
567   // If the constant is used in more than one place then modifying it will mean
568   // we need to materialize two constants instead of one, which is a bad idea.
569   if (!MulConst->hasOneUse()) return false;
570   unsigned MulConstVal = MulConst->getZExtValue();
571   if (MulConstVal == 0) return false;
572 
573   // Find the largest power of 2 that MulConstVal is a multiple of
574   PowerOfTwo = MaxShift;
575   while ((MulConstVal % (1 << PowerOfTwo)) != 0) {
576     --PowerOfTwo;
577     if (PowerOfTwo == 0) return false;
578   }
579 
580   // Only optimise if the new cost is better
581   unsigned NewMulConstVal = MulConstVal / (1 << PowerOfTwo);
582   NewMulConst = CurDAG->getConstant(NewMulConstVal, SDLoc(N), MVT::i32);
583   unsigned OldCost = ConstantMaterializationCost(MulConstVal, Subtarget);
584   unsigned NewCost = ConstantMaterializationCost(NewMulConstVal, Subtarget);
585   return NewCost < OldCost;
586 }
587 
588 void ARMDAGToDAGISel::replaceDAGValue(const SDValue &N, SDValue M) {
589   CurDAG->RepositionNode(N.getNode()->getIterator(), M.getNode());
590   ReplaceUses(N, M);
591 }
592 
593 bool ARMDAGToDAGISel::SelectImmShifterOperand(SDValue N,
594                                               SDValue &BaseReg,
595                                               SDValue &Opc,
596                                               bool CheckProfitability) {
597   if (DisableShifterOp)
598     return false;
599 
600   // If N is a multiply-by-constant and it's profitable to extract a shift and
601   // use it in a shifted operand do so.
602   if (N.getOpcode() == ISD::MUL) {
603     unsigned PowerOfTwo = 0;
604     SDValue NewMulConst;
605     if (canExtractShiftFromMul(N, 31, PowerOfTwo, NewMulConst)) {
606       HandleSDNode Handle(N);
607       SDLoc Loc(N);
608       replaceDAGValue(N.getOperand(1), NewMulConst);
609       BaseReg = Handle.getValue();
610       Opc = CurDAG->getTargetConstant(
611           ARM_AM::getSORegOpc(ARM_AM::lsl, PowerOfTwo), Loc, MVT::i32);
612       return true;
613     }
614   }
615 
616   ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOpcode());
617 
618   // Don't match base register only case. That is matched to a separate
619   // lower complexity pattern with explicit register operand.
620   if (ShOpcVal == ARM_AM::no_shift) return false;
621 
622   BaseReg = N.getOperand(0);
623   unsigned ShImmVal = 0;
624   ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1));
625   if (!RHS) return false;
626   ShImmVal = RHS->getZExtValue() & 31;
627   Opc = CurDAG->getTargetConstant(ARM_AM::getSORegOpc(ShOpcVal, ShImmVal),
628                                   SDLoc(N), MVT::i32);
629   return true;
630 }
631 
632 bool ARMDAGToDAGISel::SelectRegShifterOperand(SDValue N,
633                                               SDValue &BaseReg,
634                                               SDValue &ShReg,
635                                               SDValue &Opc,
636                                               bool CheckProfitability) {
637   if (DisableShifterOp)
638     return false;
639 
640   ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOpcode());
641 
642   // Don't match base register only case. That is matched to a separate
643   // lower complexity pattern with explicit register operand.
644   if (ShOpcVal == ARM_AM::no_shift) return false;
645 
646   BaseReg = N.getOperand(0);
647   unsigned ShImmVal = 0;
648   ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1));
649   if (RHS) return false;
650 
651   ShReg = N.getOperand(1);
652   if (CheckProfitability && !isShifterOpProfitable(N, ShOpcVal, ShImmVal))
653     return false;
654   Opc = CurDAG->getTargetConstant(ARM_AM::getSORegOpc(ShOpcVal, ShImmVal),
655                                   SDLoc(N), MVT::i32);
656   return true;
657 }
658 
659 // Determine whether an ISD::OR's operands are suitable to turn the operation
660 // into an addition, which often has more compact encodings.
661 bool ARMDAGToDAGISel::SelectAddLikeOr(SDNode *Parent, SDValue N, SDValue &Out) {
662   assert(Parent->getOpcode() == ISD::OR && "unexpected parent");
663   Out = N;
664   return CurDAG->haveNoCommonBitsSet(N, Parent->getOperand(1));
665 }
666 
667 
668 bool ARMDAGToDAGISel::SelectAddrModeImm12(SDValue N,
669                                           SDValue &Base,
670                                           SDValue &OffImm) {
671   // Match simple R + imm12 operands.
672 
673   // Base only.
674   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
675       !CurDAG->isBaseWithConstantOffset(N)) {
676     if (N.getOpcode() == ISD::FrameIndex) {
677       // Match frame index.
678       int FI = cast<FrameIndexSDNode>(N)->getIndex();
679       Base = CurDAG->getTargetFrameIndex(
680           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
681       OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
682       return true;
683     }
684 
685     if (N.getOpcode() == ARMISD::Wrapper &&
686         N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
687         N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
688         N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
689       Base = N.getOperand(0);
690     } else
691       Base = N;
692     OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
693     return true;
694   }
695 
696   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
697     int RHSC = (int)RHS->getSExtValue();
698     if (N.getOpcode() == ISD::SUB)
699       RHSC = -RHSC;
700 
701     if (RHSC > -0x1000 && RHSC < 0x1000) { // 12 bits
702       Base   = N.getOperand(0);
703       if (Base.getOpcode() == ISD::FrameIndex) {
704         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
705         Base = CurDAG->getTargetFrameIndex(
706             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
707       }
708       OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
709       return true;
710     }
711   }
712 
713   // Base only.
714   Base = N;
715   OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
716   return true;
717 }
718 
719 
720 
721 bool ARMDAGToDAGISel::SelectLdStSOReg(SDValue N, SDValue &Base, SDValue &Offset,
722                                       SDValue &Opc) {
723   if (N.getOpcode() == ISD::MUL &&
724       ((!Subtarget->isLikeA9() && !Subtarget->isSwift()) || N.hasOneUse())) {
725     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
726       // X * [3,5,9] -> X + X * [2,4,8] etc.
727       int RHSC = (int)RHS->getZExtValue();
728       if (RHSC & 1) {
729         RHSC = RHSC & ~1;
730         ARM_AM::AddrOpc AddSub = ARM_AM::add;
731         if (RHSC < 0) {
732           AddSub = ARM_AM::sub;
733           RHSC = - RHSC;
734         }
735         if (isPowerOf2_32(RHSC)) {
736           unsigned ShAmt = Log2_32(RHSC);
737           Base = Offset = N.getOperand(0);
738           Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, ShAmt,
739                                                             ARM_AM::lsl),
740                                           SDLoc(N), MVT::i32);
741           return true;
742         }
743       }
744     }
745   }
746 
747   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
748       // ISD::OR that is equivalent to an ISD::ADD.
749       !CurDAG->isBaseWithConstantOffset(N))
750     return false;
751 
752   // Leave simple R +/- imm12 operands for LDRi12
753   if (N.getOpcode() == ISD::ADD || N.getOpcode() == ISD::OR) {
754     int RHSC;
755     if (isScaledConstantInRange(N.getOperand(1), /*Scale=*/1,
756                                 -0x1000+1, 0x1000, RHSC)) // 12 bits.
757       return false;
758   }
759 
760   // Otherwise this is R +/- [possibly shifted] R.
761   ARM_AM::AddrOpc AddSub = N.getOpcode() == ISD::SUB ? ARM_AM::sub:ARM_AM::add;
762   ARM_AM::ShiftOpc ShOpcVal =
763     ARM_AM::getShiftOpcForNode(N.getOperand(1).getOpcode());
764   unsigned ShAmt = 0;
765 
766   Base   = N.getOperand(0);
767   Offset = N.getOperand(1);
768 
769   if (ShOpcVal != ARM_AM::no_shift) {
770     // Check to see if the RHS of the shift is a constant, if not, we can't fold
771     // it.
772     if (ConstantSDNode *Sh =
773            dyn_cast<ConstantSDNode>(N.getOperand(1).getOperand(1))) {
774       ShAmt = Sh->getZExtValue();
775       if (isShifterOpProfitable(Offset, ShOpcVal, ShAmt))
776         Offset = N.getOperand(1).getOperand(0);
777       else {
778         ShAmt = 0;
779         ShOpcVal = ARM_AM::no_shift;
780       }
781     } else {
782       ShOpcVal = ARM_AM::no_shift;
783     }
784   }
785 
786   // Try matching (R shl C) + (R).
787   if (N.getOpcode() != ISD::SUB && ShOpcVal == ARM_AM::no_shift &&
788       !(Subtarget->isLikeA9() || Subtarget->isSwift() ||
789         N.getOperand(0).hasOneUse())) {
790     ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOperand(0).getOpcode());
791     if (ShOpcVal != ARM_AM::no_shift) {
792       // Check to see if the RHS of the shift is a constant, if not, we can't
793       // fold it.
794       if (ConstantSDNode *Sh =
795           dyn_cast<ConstantSDNode>(N.getOperand(0).getOperand(1))) {
796         ShAmt = Sh->getZExtValue();
797         if (isShifterOpProfitable(N.getOperand(0), ShOpcVal, ShAmt)) {
798           Offset = N.getOperand(0).getOperand(0);
799           Base = N.getOperand(1);
800         } else {
801           ShAmt = 0;
802           ShOpcVal = ARM_AM::no_shift;
803         }
804       } else {
805         ShOpcVal = ARM_AM::no_shift;
806       }
807     }
808   }
809 
810   // If Offset is a multiply-by-constant and it's profitable to extract a shift
811   // and use it in a shifted operand do so.
812   if (Offset.getOpcode() == ISD::MUL && N.hasOneUse()) {
813     unsigned PowerOfTwo = 0;
814     SDValue NewMulConst;
815     if (canExtractShiftFromMul(Offset, 31, PowerOfTwo, NewMulConst)) {
816       HandleSDNode Handle(Offset);
817       replaceDAGValue(Offset.getOperand(1), NewMulConst);
818       Offset = Handle.getValue();
819       ShAmt = PowerOfTwo;
820       ShOpcVal = ARM_AM::lsl;
821     }
822   }
823 
824   Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, ShAmt, ShOpcVal),
825                                   SDLoc(N), MVT::i32);
826   return true;
827 }
828 
829 bool ARMDAGToDAGISel::SelectAddrMode2OffsetReg(SDNode *Op, SDValue N,
830                                             SDValue &Offset, SDValue &Opc) {
831   unsigned Opcode = Op->getOpcode();
832   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
833     ? cast<LoadSDNode>(Op)->getAddressingMode()
834     : cast<StoreSDNode>(Op)->getAddressingMode();
835   ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
836     ? ARM_AM::add : ARM_AM::sub;
837   int Val;
838   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x1000, Val))
839     return false;
840 
841   Offset = N;
842   ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(N.getOpcode());
843   unsigned ShAmt = 0;
844   if (ShOpcVal != ARM_AM::no_shift) {
845     // Check to see if the RHS of the shift is a constant, if not, we can't fold
846     // it.
847     if (ConstantSDNode *Sh = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
848       ShAmt = Sh->getZExtValue();
849       if (isShifterOpProfitable(N, ShOpcVal, ShAmt))
850         Offset = N.getOperand(0);
851       else {
852         ShAmt = 0;
853         ShOpcVal = ARM_AM::no_shift;
854       }
855     } else {
856       ShOpcVal = ARM_AM::no_shift;
857     }
858   }
859 
860   Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, ShAmt, ShOpcVal),
861                                   SDLoc(N), MVT::i32);
862   return true;
863 }
864 
865 bool ARMDAGToDAGISel::SelectAddrMode2OffsetImmPre(SDNode *Op, SDValue N,
866                                             SDValue &Offset, SDValue &Opc) {
867   unsigned Opcode = Op->getOpcode();
868   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
869     ? cast<LoadSDNode>(Op)->getAddressingMode()
870     : cast<StoreSDNode>(Op)->getAddressingMode();
871   ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
872     ? ARM_AM::add : ARM_AM::sub;
873   int Val;
874   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x1000, Val)) { // 12 bits.
875     if (AddSub == ARM_AM::sub) Val *= -1;
876     Offset = CurDAG->getRegister(0, MVT::i32);
877     Opc = CurDAG->getTargetConstant(Val, SDLoc(Op), MVT::i32);
878     return true;
879   }
880 
881   return false;
882 }
883 
884 
885 bool ARMDAGToDAGISel::SelectAddrMode2OffsetImm(SDNode *Op, SDValue N,
886                                             SDValue &Offset, SDValue &Opc) {
887   unsigned Opcode = Op->getOpcode();
888   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
889     ? cast<LoadSDNode>(Op)->getAddressingMode()
890     : cast<StoreSDNode>(Op)->getAddressingMode();
891   ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
892     ? ARM_AM::add : ARM_AM::sub;
893   int Val;
894   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x1000, Val)) { // 12 bits.
895     Offset = CurDAG->getRegister(0, MVT::i32);
896     Opc = CurDAG->getTargetConstant(ARM_AM::getAM2Opc(AddSub, Val,
897                                                       ARM_AM::no_shift),
898                                     SDLoc(Op), MVT::i32);
899     return true;
900   }
901 
902   return false;
903 }
904 
905 bool ARMDAGToDAGISel::SelectAddrOffsetNone(SDValue N, SDValue &Base) {
906   Base = N;
907   return true;
908 }
909 
910 bool ARMDAGToDAGISel::SelectAddrMode3(SDValue N,
911                                       SDValue &Base, SDValue &Offset,
912                                       SDValue &Opc) {
913   if (N.getOpcode() == ISD::SUB) {
914     // X - C  is canonicalize to X + -C, no need to handle it here.
915     Base = N.getOperand(0);
916     Offset = N.getOperand(1);
917     Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(ARM_AM::sub, 0), SDLoc(N),
918                                     MVT::i32);
919     return true;
920   }
921 
922   if (!CurDAG->isBaseWithConstantOffset(N)) {
923     Base = N;
924     if (N.getOpcode() == ISD::FrameIndex) {
925       int FI = cast<FrameIndexSDNode>(N)->getIndex();
926       Base = CurDAG->getTargetFrameIndex(
927           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
928     }
929     Offset = CurDAG->getRegister(0, MVT::i32);
930     Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(ARM_AM::add, 0), SDLoc(N),
931                                     MVT::i32);
932     return true;
933   }
934 
935   // If the RHS is +/- imm8, fold into addr mode.
936   int RHSC;
937   if (isScaledConstantInRange(N.getOperand(1), /*Scale=*/1,
938                               -256 + 1, 256, RHSC)) { // 8 bits.
939     Base = N.getOperand(0);
940     if (Base.getOpcode() == ISD::FrameIndex) {
941       int FI = cast<FrameIndexSDNode>(Base)->getIndex();
942       Base = CurDAG->getTargetFrameIndex(
943           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
944     }
945     Offset = CurDAG->getRegister(0, MVT::i32);
946 
947     ARM_AM::AddrOpc AddSub = ARM_AM::add;
948     if (RHSC < 0) {
949       AddSub = ARM_AM::sub;
950       RHSC = -RHSC;
951     }
952     Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(AddSub, RHSC), SDLoc(N),
953                                     MVT::i32);
954     return true;
955   }
956 
957   Base = N.getOperand(0);
958   Offset = N.getOperand(1);
959   Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(ARM_AM::add, 0), SDLoc(N),
960                                   MVT::i32);
961   return true;
962 }
963 
964 bool ARMDAGToDAGISel::SelectAddrMode3Offset(SDNode *Op, SDValue N,
965                                             SDValue &Offset, SDValue &Opc) {
966   unsigned Opcode = Op->getOpcode();
967   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
968     ? cast<LoadSDNode>(Op)->getAddressingMode()
969     : cast<StoreSDNode>(Op)->getAddressingMode();
970   ARM_AM::AddrOpc AddSub = (AM == ISD::PRE_INC || AM == ISD::POST_INC)
971     ? ARM_AM::add : ARM_AM::sub;
972   int Val;
973   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 256, Val)) { // 12 bits.
974     Offset = CurDAG->getRegister(0, MVT::i32);
975     Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(AddSub, Val), SDLoc(Op),
976                                     MVT::i32);
977     return true;
978   }
979 
980   Offset = N;
981   Opc = CurDAG->getTargetConstant(ARM_AM::getAM3Opc(AddSub, 0), SDLoc(Op),
982                                   MVT::i32);
983   return true;
984 }
985 
986 bool ARMDAGToDAGISel::IsAddressingMode5(SDValue N, SDValue &Base, SDValue &Offset,
987                                         bool FP16) {
988   if (!CurDAG->isBaseWithConstantOffset(N)) {
989     Base = N;
990     if (N.getOpcode() == ISD::FrameIndex) {
991       int FI = cast<FrameIndexSDNode>(N)->getIndex();
992       Base = CurDAG->getTargetFrameIndex(
993           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
994     } else if (N.getOpcode() == ARMISD::Wrapper &&
995                N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
996                N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
997                N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
998       Base = N.getOperand(0);
999     }
1000     Offset = CurDAG->getTargetConstant(ARM_AM::getAM5Opc(ARM_AM::add, 0),
1001                                        SDLoc(N), MVT::i32);
1002     return true;
1003   }
1004 
1005   // If the RHS is +/- imm8, fold into addr mode.
1006   int RHSC;
1007   const int Scale = FP16 ? 2 : 4;
1008 
1009   if (isScaledConstantInRange(N.getOperand(1), Scale, -255, 256, RHSC)) {
1010     Base = N.getOperand(0);
1011     if (Base.getOpcode() == ISD::FrameIndex) {
1012       int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1013       Base = CurDAG->getTargetFrameIndex(
1014           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1015     }
1016 
1017     ARM_AM::AddrOpc AddSub = ARM_AM::add;
1018     if (RHSC < 0) {
1019       AddSub = ARM_AM::sub;
1020       RHSC = -RHSC;
1021     }
1022 
1023     if (FP16)
1024       Offset = CurDAG->getTargetConstant(ARM_AM::getAM5FP16Opc(AddSub, RHSC),
1025                                          SDLoc(N), MVT::i32);
1026     else
1027       Offset = CurDAG->getTargetConstant(ARM_AM::getAM5Opc(AddSub, RHSC),
1028                                          SDLoc(N), MVT::i32);
1029 
1030     return true;
1031   }
1032 
1033   Base = N;
1034 
1035   if (FP16)
1036     Offset = CurDAG->getTargetConstant(ARM_AM::getAM5FP16Opc(ARM_AM::add, 0),
1037                                        SDLoc(N), MVT::i32);
1038   else
1039     Offset = CurDAG->getTargetConstant(ARM_AM::getAM5Opc(ARM_AM::add, 0),
1040                                        SDLoc(N), MVT::i32);
1041 
1042   return true;
1043 }
1044 
1045 bool ARMDAGToDAGISel::SelectAddrMode5(SDValue N,
1046                                       SDValue &Base, SDValue &Offset) {
1047   return IsAddressingMode5(N, Base, Offset, /*FP16=*/ false);
1048 }
1049 
1050 bool ARMDAGToDAGISel::SelectAddrMode5FP16(SDValue N,
1051                                           SDValue &Base, SDValue &Offset) {
1052   return IsAddressingMode5(N, Base, Offset, /*FP16=*/ true);
1053 }
1054 
1055 bool ARMDAGToDAGISel::SelectAddrMode6(SDNode *Parent, SDValue N, SDValue &Addr,
1056                                       SDValue &Align) {
1057   Addr = N;
1058 
1059   unsigned Alignment = 0;
1060 
1061   MemSDNode *MemN = cast<MemSDNode>(Parent);
1062 
1063   if (isa<LSBaseSDNode>(MemN) ||
1064       ((MemN->getOpcode() == ARMISD::VST1_UPD ||
1065         MemN->getOpcode() == ARMISD::VLD1_UPD) &&
1066        MemN->getConstantOperandVal(MemN->getNumOperands() - 1) == 1)) {
1067     // This case occurs only for VLD1-lane/dup and VST1-lane instructions.
1068     // The maximum alignment is equal to the memory size being referenced.
1069     llvm::Align MMOAlign = MemN->getAlign();
1070     unsigned MemSize = MemN->getMemoryVT().getSizeInBits() / 8;
1071     if (MMOAlign.value() >= MemSize && MemSize > 1)
1072       Alignment = MemSize;
1073   } else {
1074     // All other uses of addrmode6 are for intrinsics.  For now just record
1075     // the raw alignment value; it will be refined later based on the legal
1076     // alignment operands for the intrinsic.
1077     Alignment = MemN->getAlign().value();
1078   }
1079 
1080   Align = CurDAG->getTargetConstant(Alignment, SDLoc(N), MVT::i32);
1081   return true;
1082 }
1083 
1084 bool ARMDAGToDAGISel::SelectAddrMode6Offset(SDNode *Op, SDValue N,
1085                                             SDValue &Offset) {
1086   LSBaseSDNode *LdSt = cast<LSBaseSDNode>(Op);
1087   ISD::MemIndexedMode AM = LdSt->getAddressingMode();
1088   if (AM != ISD::POST_INC)
1089     return false;
1090   Offset = N;
1091   if (ConstantSDNode *NC = dyn_cast<ConstantSDNode>(N)) {
1092     if (NC->getZExtValue() * 8 == LdSt->getMemoryVT().getSizeInBits())
1093       Offset = CurDAG->getRegister(0, MVT::i32);
1094   }
1095   return true;
1096 }
1097 
1098 bool ARMDAGToDAGISel::SelectAddrModePC(SDValue N,
1099                                        SDValue &Offset, SDValue &Label) {
1100   if (N.getOpcode() == ARMISD::PIC_ADD && N.hasOneUse()) {
1101     Offset = N.getOperand(0);
1102     SDValue N1 = N.getOperand(1);
1103     Label = CurDAG->getTargetConstant(cast<ConstantSDNode>(N1)->getZExtValue(),
1104                                       SDLoc(N), MVT::i32);
1105     return true;
1106   }
1107 
1108   return false;
1109 }
1110 
1111 
1112 //===----------------------------------------------------------------------===//
1113 //                         Thumb Addressing Modes
1114 //===----------------------------------------------------------------------===//
1115 
1116 static bool shouldUseZeroOffsetLdSt(SDValue N) {
1117   // Negative numbers are difficult to materialise in thumb1. If we are
1118   // selecting the add of a negative, instead try to select ri with a zero
1119   // offset, so create the add node directly which will become a sub.
1120   if (N.getOpcode() != ISD::ADD)
1121     return false;
1122 
1123   // Look for an imm which is not legal for ld/st, but is legal for sub.
1124   if (auto C = dyn_cast<ConstantSDNode>(N.getOperand(1)))
1125     return C->getSExtValue() < 0 && C->getSExtValue() >= -255;
1126 
1127   return false;
1128 }
1129 
1130 bool ARMDAGToDAGISel::SelectThumbAddrModeRRSext(SDValue N, SDValue &Base,
1131                                                 SDValue &Offset) {
1132   if (N.getOpcode() != ISD::ADD && !CurDAG->isBaseWithConstantOffset(N)) {
1133     if (!isNullConstant(N))
1134       return false;
1135 
1136     Base = Offset = N;
1137     return true;
1138   }
1139 
1140   Base = N.getOperand(0);
1141   Offset = N.getOperand(1);
1142   return true;
1143 }
1144 
1145 bool ARMDAGToDAGISel::SelectThumbAddrModeRR(SDValue N, SDValue &Base,
1146                                             SDValue &Offset) {
1147   if (shouldUseZeroOffsetLdSt(N))
1148     return false; // Select ri instead
1149   return SelectThumbAddrModeRRSext(N, Base, Offset);
1150 }
1151 
1152 bool
1153 ARMDAGToDAGISel::SelectThumbAddrModeImm5S(SDValue N, unsigned Scale,
1154                                           SDValue &Base, SDValue &OffImm) {
1155   if (shouldUseZeroOffsetLdSt(N)) {
1156     Base = N;
1157     OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1158     return true;
1159   }
1160 
1161   if (!CurDAG->isBaseWithConstantOffset(N)) {
1162     if (N.getOpcode() == ISD::ADD) {
1163       return false; // We want to select register offset instead
1164     } else if (N.getOpcode() == ARMISD::Wrapper &&
1165         N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
1166         N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
1167         N.getOperand(0).getOpcode() != ISD::TargetConstantPool &&
1168         N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
1169       Base = N.getOperand(0);
1170     } else {
1171       Base = N;
1172     }
1173 
1174     OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1175     return true;
1176   }
1177 
1178   // If the RHS is + imm5 * scale, fold into addr mode.
1179   int RHSC;
1180   if (isScaledConstantInRange(N.getOperand(1), Scale, 0, 32, RHSC)) {
1181     Base = N.getOperand(0);
1182     OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
1183     return true;
1184   }
1185 
1186   // Offset is too large, so use register offset instead.
1187   return false;
1188 }
1189 
1190 bool
1191 ARMDAGToDAGISel::SelectThumbAddrModeImm5S4(SDValue N, SDValue &Base,
1192                                            SDValue &OffImm) {
1193   return SelectThumbAddrModeImm5S(N, 4, Base, OffImm);
1194 }
1195 
1196 bool
1197 ARMDAGToDAGISel::SelectThumbAddrModeImm5S2(SDValue N, SDValue &Base,
1198                                            SDValue &OffImm) {
1199   return SelectThumbAddrModeImm5S(N, 2, Base, OffImm);
1200 }
1201 
1202 bool
1203 ARMDAGToDAGISel::SelectThumbAddrModeImm5S1(SDValue N, SDValue &Base,
1204                                            SDValue &OffImm) {
1205   return SelectThumbAddrModeImm5S(N, 1, Base, OffImm);
1206 }
1207 
1208 bool ARMDAGToDAGISel::SelectThumbAddrModeSP(SDValue N,
1209                                             SDValue &Base, SDValue &OffImm) {
1210   if (N.getOpcode() == ISD::FrameIndex) {
1211     int FI = cast<FrameIndexSDNode>(N)->getIndex();
1212     // Only multiples of 4 are allowed for the offset, so the frame object
1213     // alignment must be at least 4.
1214     MachineFrameInfo &MFI = MF->getFrameInfo();
1215     if (MFI.getObjectAlign(FI) < Align(4))
1216       MFI.setObjectAlignment(FI, Align(4));
1217     Base = CurDAG->getTargetFrameIndex(
1218         FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1219     OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1220     return true;
1221   }
1222 
1223   if (!CurDAG->isBaseWithConstantOffset(N))
1224     return false;
1225 
1226   if (N.getOperand(0).getOpcode() == ISD::FrameIndex) {
1227     // If the RHS is + imm8 * scale, fold into addr mode.
1228     int RHSC;
1229     if (isScaledConstantInRange(N.getOperand(1), /*Scale=*/4, 0, 256, RHSC)) {
1230       Base = N.getOperand(0);
1231       int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1232       // Make sure the offset is inside the object, or we might fail to
1233       // allocate an emergency spill slot. (An out-of-range access is UB, but
1234       // it could show up anyway.)
1235       MachineFrameInfo &MFI = MF->getFrameInfo();
1236       if (RHSC * 4 < MFI.getObjectSize(FI)) {
1237         // For LHS+RHS to result in an offset that's a multiple of 4 the object
1238         // indexed by the LHS must be 4-byte aligned.
1239         if (!MFI.isFixedObjectIndex(FI) && MFI.getObjectAlign(FI) < Align(4))
1240           MFI.setObjectAlignment(FI, Align(4));
1241         if (MFI.getObjectAlign(FI) >= Align(4)) {
1242           Base = CurDAG->getTargetFrameIndex(
1243               FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1244           OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
1245           return true;
1246         }
1247       }
1248     }
1249   }
1250 
1251   return false;
1252 }
1253 
1254 template <unsigned Shift>
1255 bool ARMDAGToDAGISel::SelectTAddrModeImm7(SDValue N, SDValue &Base,
1256                                           SDValue &OffImm) {
1257   if (N.getOpcode() == ISD::SUB || CurDAG->isBaseWithConstantOffset(N)) {
1258     int RHSC;
1259     if (isScaledConstantInRange(N.getOperand(1), 1 << Shift, -0x7f, 0x80,
1260                                 RHSC)) {
1261       Base = N.getOperand(0);
1262       if (N.getOpcode() == ISD::SUB)
1263         RHSC = -RHSC;
1264       OffImm =
1265           CurDAG->getTargetConstant(RHSC * (1 << Shift), SDLoc(N), MVT::i32);
1266       return true;
1267     }
1268   }
1269 
1270   // Base only.
1271   Base = N;
1272   OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1273   return true;
1274 }
1275 
1276 
1277 //===----------------------------------------------------------------------===//
1278 //                        Thumb 2 Addressing Modes
1279 //===----------------------------------------------------------------------===//
1280 
1281 
1282 bool ARMDAGToDAGISel::SelectT2AddrModeImm12(SDValue N,
1283                                             SDValue &Base, SDValue &OffImm) {
1284   // Match simple R + imm12 operands.
1285 
1286   // Base only.
1287   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
1288       !CurDAG->isBaseWithConstantOffset(N)) {
1289     if (N.getOpcode() == ISD::FrameIndex) {
1290       // Match frame index.
1291       int FI = cast<FrameIndexSDNode>(N)->getIndex();
1292       Base = CurDAG->getTargetFrameIndex(
1293           FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1294       OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1295       return true;
1296     }
1297 
1298     if (N.getOpcode() == ARMISD::Wrapper &&
1299         N.getOperand(0).getOpcode() != ISD::TargetGlobalAddress &&
1300         N.getOperand(0).getOpcode() != ISD::TargetExternalSymbol &&
1301         N.getOperand(0).getOpcode() != ISD::TargetGlobalTLSAddress) {
1302       Base = N.getOperand(0);
1303       if (Base.getOpcode() == ISD::TargetConstantPool)
1304         return false;  // We want to select t2LDRpci instead.
1305     } else
1306       Base = N;
1307     OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1308     return true;
1309   }
1310 
1311   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1312     if (SelectT2AddrModeImm8(N, Base, OffImm))
1313       // Let t2LDRi8 handle (R - imm8).
1314       return false;
1315 
1316     int RHSC = (int)RHS->getZExtValue();
1317     if (N.getOpcode() == ISD::SUB)
1318       RHSC = -RHSC;
1319 
1320     if (RHSC >= 0 && RHSC < 0x1000) { // 12 bits (unsigned)
1321       Base   = N.getOperand(0);
1322       if (Base.getOpcode() == ISD::FrameIndex) {
1323         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1324         Base = CurDAG->getTargetFrameIndex(
1325             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1326       }
1327       OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
1328       return true;
1329     }
1330   }
1331 
1332   // Base only.
1333   Base = N;
1334   OffImm  = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1335   return true;
1336 }
1337 
1338 template <unsigned Shift>
1339 bool ARMDAGToDAGISel::SelectT2AddrModeImm8(SDValue N, SDValue &Base,
1340                                            SDValue &OffImm) {
1341   if (N.getOpcode() == ISD::SUB || CurDAG->isBaseWithConstantOffset(N)) {
1342     int RHSC;
1343     if (isScaledConstantInRange(N.getOperand(1), 1 << Shift, -255, 256, RHSC)) {
1344       Base = N.getOperand(0);
1345       if (Base.getOpcode() == ISD::FrameIndex) {
1346         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1347         Base = CurDAG->getTargetFrameIndex(
1348             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1349       }
1350 
1351       if (N.getOpcode() == ISD::SUB)
1352         RHSC = -RHSC;
1353       OffImm =
1354           CurDAG->getTargetConstant(RHSC * (1 << Shift), SDLoc(N), MVT::i32);
1355       return true;
1356     }
1357   }
1358 
1359   // Base only.
1360   Base = N;
1361   OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1362   return true;
1363 }
1364 
1365 bool ARMDAGToDAGISel::SelectT2AddrModeImm8(SDValue N,
1366                                            SDValue &Base, SDValue &OffImm) {
1367   // Match simple R - imm8 operands.
1368   if (N.getOpcode() != ISD::ADD && N.getOpcode() != ISD::SUB &&
1369       !CurDAG->isBaseWithConstantOffset(N))
1370     return false;
1371 
1372   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1373     int RHSC = (int)RHS->getSExtValue();
1374     if (N.getOpcode() == ISD::SUB)
1375       RHSC = -RHSC;
1376 
1377     if ((RHSC >= -255) && (RHSC < 0)) { // 8 bits (always negative)
1378       Base = N.getOperand(0);
1379       if (Base.getOpcode() == ISD::FrameIndex) {
1380         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1381         Base = CurDAG->getTargetFrameIndex(
1382             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1383       }
1384       OffImm = CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32);
1385       return true;
1386     }
1387   }
1388 
1389   return false;
1390 }
1391 
1392 bool ARMDAGToDAGISel::SelectT2AddrModeImm8Offset(SDNode *Op, SDValue N,
1393                                                  SDValue &OffImm){
1394   unsigned Opcode = Op->getOpcode();
1395   ISD::MemIndexedMode AM = (Opcode == ISD::LOAD)
1396     ? cast<LoadSDNode>(Op)->getAddressingMode()
1397     : cast<StoreSDNode>(Op)->getAddressingMode();
1398   int RHSC;
1399   if (isScaledConstantInRange(N, /*Scale=*/1, 0, 0x100, RHSC)) { // 8 bits.
1400     OffImm = ((AM == ISD::PRE_INC) || (AM == ISD::POST_INC))
1401       ? CurDAG->getTargetConstant(RHSC, SDLoc(N), MVT::i32)
1402       : CurDAG->getTargetConstant(-RHSC, SDLoc(N), MVT::i32);
1403     return true;
1404   }
1405 
1406   return false;
1407 }
1408 
1409 template <unsigned Shift>
1410 bool ARMDAGToDAGISel::SelectT2AddrModeImm7(SDValue N, SDValue &Base,
1411                                            SDValue &OffImm) {
1412   if (N.getOpcode() == ISD::SUB || CurDAG->isBaseWithConstantOffset(N)) {
1413     int RHSC;
1414     if (isScaledConstantInRange(N.getOperand(1), 1 << Shift, -0x7f, 0x80,
1415                                 RHSC)) {
1416       Base = N.getOperand(0);
1417       if (Base.getOpcode() == ISD::FrameIndex) {
1418         int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1419         Base = CurDAG->getTargetFrameIndex(
1420             FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1421       }
1422 
1423       if (N.getOpcode() == ISD::SUB)
1424         RHSC = -RHSC;
1425       OffImm =
1426           CurDAG->getTargetConstant(RHSC * (1 << Shift), SDLoc(N), MVT::i32);
1427       return true;
1428     }
1429   }
1430 
1431   // Base only.
1432   Base = N;
1433   OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1434   return true;
1435 }
1436 
1437 template <unsigned Shift>
1438 bool ARMDAGToDAGISel::SelectT2AddrModeImm7Offset(SDNode *Op, SDValue N,
1439                                                  SDValue &OffImm) {
1440   return SelectT2AddrModeImm7Offset(Op, N, OffImm, Shift);
1441 }
1442 
1443 bool ARMDAGToDAGISel::SelectT2AddrModeImm7Offset(SDNode *Op, SDValue N,
1444                                                  SDValue &OffImm,
1445                                                  unsigned Shift) {
1446   unsigned Opcode = Op->getOpcode();
1447   ISD::MemIndexedMode AM;
1448   switch (Opcode) {
1449   case ISD::LOAD:
1450     AM = cast<LoadSDNode>(Op)->getAddressingMode();
1451     break;
1452   case ISD::STORE:
1453     AM = cast<StoreSDNode>(Op)->getAddressingMode();
1454     break;
1455   case ISD::MLOAD:
1456     AM = cast<MaskedLoadSDNode>(Op)->getAddressingMode();
1457     break;
1458   case ISD::MSTORE:
1459     AM = cast<MaskedStoreSDNode>(Op)->getAddressingMode();
1460     break;
1461   default:
1462     llvm_unreachable("Unexpected Opcode for Imm7Offset");
1463   }
1464 
1465   int RHSC;
1466   // 7 bit constant, shifted by Shift.
1467   if (isScaledConstantInRange(N, 1 << Shift, 0, 0x80, RHSC)) {
1468     OffImm =
1469         ((AM == ISD::PRE_INC) || (AM == ISD::POST_INC))
1470             ? CurDAG->getTargetConstant(RHSC * (1 << Shift), SDLoc(N), MVT::i32)
1471             : CurDAG->getTargetConstant(-RHSC * (1 << Shift), SDLoc(N),
1472                                         MVT::i32);
1473     return true;
1474   }
1475   return false;
1476 }
1477 
1478 template <int Min, int Max>
1479 bool ARMDAGToDAGISel::SelectImmediateInRange(SDValue N, SDValue &OffImm) {
1480   int Val;
1481   if (isScaledConstantInRange(N, 1, Min, Max, Val)) {
1482     OffImm = CurDAG->getTargetConstant(Val, SDLoc(N), MVT::i32);
1483     return true;
1484   }
1485   return false;
1486 }
1487 
1488 bool ARMDAGToDAGISel::SelectT2AddrModeSoReg(SDValue N,
1489                                             SDValue &Base,
1490                                             SDValue &OffReg, SDValue &ShImm) {
1491   // (R - imm8) should be handled by t2LDRi8. The rest are handled by t2LDRi12.
1492   if (N.getOpcode() != ISD::ADD && !CurDAG->isBaseWithConstantOffset(N))
1493     return false;
1494 
1495   // Leave (R + imm12) for t2LDRi12, (R - imm8) for t2LDRi8.
1496   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
1497     int RHSC = (int)RHS->getZExtValue();
1498     if (RHSC >= 0 && RHSC < 0x1000) // 12 bits (unsigned)
1499       return false;
1500     else if (RHSC < 0 && RHSC >= -255) // 8 bits
1501       return false;
1502   }
1503 
1504   // Look for (R + R) or (R + (R << [1,2,3])).
1505   unsigned ShAmt = 0;
1506   Base   = N.getOperand(0);
1507   OffReg = N.getOperand(1);
1508 
1509   // Swap if it is ((R << c) + R).
1510   ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(OffReg.getOpcode());
1511   if (ShOpcVal != ARM_AM::lsl) {
1512     ShOpcVal = ARM_AM::getShiftOpcForNode(Base.getOpcode());
1513     if (ShOpcVal == ARM_AM::lsl)
1514       std::swap(Base, OffReg);
1515   }
1516 
1517   if (ShOpcVal == ARM_AM::lsl) {
1518     // Check to see if the RHS of the shift is a constant, if not, we can't fold
1519     // it.
1520     if (ConstantSDNode *Sh = dyn_cast<ConstantSDNode>(OffReg.getOperand(1))) {
1521       ShAmt = Sh->getZExtValue();
1522       if (ShAmt < 4 && isShifterOpProfitable(OffReg, ShOpcVal, ShAmt))
1523         OffReg = OffReg.getOperand(0);
1524       else {
1525         ShAmt = 0;
1526       }
1527     }
1528   }
1529 
1530   // If OffReg is a multiply-by-constant and it's profitable to extract a shift
1531   // and use it in a shifted operand do so.
1532   if (OffReg.getOpcode() == ISD::MUL && N.hasOneUse()) {
1533     unsigned PowerOfTwo = 0;
1534     SDValue NewMulConst;
1535     if (canExtractShiftFromMul(OffReg, 3, PowerOfTwo, NewMulConst)) {
1536       HandleSDNode Handle(OffReg);
1537       replaceDAGValue(OffReg.getOperand(1), NewMulConst);
1538       OffReg = Handle.getValue();
1539       ShAmt = PowerOfTwo;
1540     }
1541   }
1542 
1543   ShImm = CurDAG->getTargetConstant(ShAmt, SDLoc(N), MVT::i32);
1544 
1545   return true;
1546 }
1547 
1548 bool ARMDAGToDAGISel::SelectT2AddrModeExclusive(SDValue N, SDValue &Base,
1549                                                 SDValue &OffImm) {
1550   // This *must* succeed since it's used for the irreplaceable ldrex and strex
1551   // instructions.
1552   Base = N;
1553   OffImm = CurDAG->getTargetConstant(0, SDLoc(N), MVT::i32);
1554 
1555   if (N.getOpcode() != ISD::ADD || !CurDAG->isBaseWithConstantOffset(N))
1556     return true;
1557 
1558   ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(N.getOperand(1));
1559   if (!RHS)
1560     return true;
1561 
1562   uint32_t RHSC = (int)RHS->getZExtValue();
1563   if (RHSC > 1020 || RHSC % 4 != 0)
1564     return true;
1565 
1566   Base = N.getOperand(0);
1567   if (Base.getOpcode() == ISD::FrameIndex) {
1568     int FI = cast<FrameIndexSDNode>(Base)->getIndex();
1569     Base = CurDAG->getTargetFrameIndex(
1570         FI, TLI->getPointerTy(CurDAG->getDataLayout()));
1571   }
1572 
1573   OffImm = CurDAG->getTargetConstant(RHSC/4, SDLoc(N), MVT::i32);
1574   return true;
1575 }
1576 
1577 //===--------------------------------------------------------------------===//
1578 
1579 /// getAL - Returns a ARMCC::AL immediate node.
1580 static inline SDValue getAL(SelectionDAG *CurDAG, const SDLoc &dl) {
1581   return CurDAG->getTargetConstant((uint64_t)ARMCC::AL, dl, MVT::i32);
1582 }
1583 
1584 void ARMDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
1585   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
1586   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp});
1587 }
1588 
1589 bool ARMDAGToDAGISel::tryARMIndexedLoad(SDNode *N) {
1590   LoadSDNode *LD = cast<LoadSDNode>(N);
1591   ISD::MemIndexedMode AM = LD->getAddressingMode();
1592   if (AM == ISD::UNINDEXED)
1593     return false;
1594 
1595   EVT LoadedVT = LD->getMemoryVT();
1596   SDValue Offset, AMOpc;
1597   bool isPre = (AM == ISD::PRE_INC) || (AM == ISD::PRE_DEC);
1598   unsigned Opcode = 0;
1599   bool Match = false;
1600   if (LoadedVT == MVT::i32 && isPre &&
1601       SelectAddrMode2OffsetImmPre(N, LD->getOffset(), Offset, AMOpc)) {
1602     Opcode = ARM::LDR_PRE_IMM;
1603     Match = true;
1604   } else if (LoadedVT == MVT::i32 && !isPre &&
1605       SelectAddrMode2OffsetImm(N, LD->getOffset(), Offset, AMOpc)) {
1606     Opcode = ARM::LDR_POST_IMM;
1607     Match = true;
1608   } else if (LoadedVT == MVT::i32 &&
1609       SelectAddrMode2OffsetReg(N, LD->getOffset(), Offset, AMOpc)) {
1610     Opcode = isPre ? ARM::LDR_PRE_REG : ARM::LDR_POST_REG;
1611     Match = true;
1612 
1613   } else if (LoadedVT == MVT::i16 &&
1614              SelectAddrMode3Offset(N, LD->getOffset(), Offset, AMOpc)) {
1615     Match = true;
1616     Opcode = (LD->getExtensionType() == ISD::SEXTLOAD)
1617       ? (isPre ? ARM::LDRSH_PRE : ARM::LDRSH_POST)
1618       : (isPre ? ARM::LDRH_PRE : ARM::LDRH_POST);
1619   } else if (LoadedVT == MVT::i8 || LoadedVT == MVT::i1) {
1620     if (LD->getExtensionType() == ISD::SEXTLOAD) {
1621       if (SelectAddrMode3Offset(N, LD->getOffset(), Offset, AMOpc)) {
1622         Match = true;
1623         Opcode = isPre ? ARM::LDRSB_PRE : ARM::LDRSB_POST;
1624       }
1625     } else {
1626       if (isPre &&
1627           SelectAddrMode2OffsetImmPre(N, LD->getOffset(), Offset, AMOpc)) {
1628         Match = true;
1629         Opcode = ARM::LDRB_PRE_IMM;
1630       } else if (!isPre &&
1631                   SelectAddrMode2OffsetImm(N, LD->getOffset(), Offset, AMOpc)) {
1632         Match = true;
1633         Opcode = ARM::LDRB_POST_IMM;
1634       } else if (SelectAddrMode2OffsetReg(N, LD->getOffset(), Offset, AMOpc)) {
1635         Match = true;
1636         Opcode = isPre ? ARM::LDRB_PRE_REG : ARM::LDRB_POST_REG;
1637       }
1638     }
1639   }
1640 
1641   if (Match) {
1642     if (Opcode == ARM::LDR_PRE_IMM || Opcode == ARM::LDRB_PRE_IMM) {
1643       SDValue Chain = LD->getChain();
1644       SDValue Base = LD->getBasePtr();
1645       SDValue Ops[]= { Base, AMOpc, getAL(CurDAG, SDLoc(N)),
1646                        CurDAG->getRegister(0, MVT::i32), Chain };
1647       SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32, MVT::i32,
1648                                            MVT::Other, Ops);
1649       transferMemOperands(N, New);
1650       ReplaceNode(N, New);
1651       return true;
1652     } else {
1653       SDValue Chain = LD->getChain();
1654       SDValue Base = LD->getBasePtr();
1655       SDValue Ops[]= { Base, Offset, AMOpc, getAL(CurDAG, SDLoc(N)),
1656                        CurDAG->getRegister(0, MVT::i32), Chain };
1657       SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32, MVT::i32,
1658                                            MVT::Other, Ops);
1659       transferMemOperands(N, New);
1660       ReplaceNode(N, New);
1661       return true;
1662     }
1663   }
1664 
1665   return false;
1666 }
1667 
1668 bool ARMDAGToDAGISel::tryT1IndexedLoad(SDNode *N) {
1669   LoadSDNode *LD = cast<LoadSDNode>(N);
1670   EVT LoadedVT = LD->getMemoryVT();
1671   ISD::MemIndexedMode AM = LD->getAddressingMode();
1672   if (AM != ISD::POST_INC || LD->getExtensionType() != ISD::NON_EXTLOAD ||
1673       LoadedVT.getSimpleVT().SimpleTy != MVT::i32)
1674     return false;
1675 
1676   auto *COffs = dyn_cast<ConstantSDNode>(LD->getOffset());
1677   if (!COffs || COffs->getZExtValue() != 4)
1678     return false;
1679 
1680   // A T1 post-indexed load is just a single register LDM: LDM r0!, {r1}.
1681   // The encoding of LDM is not how the rest of ISel expects a post-inc load to
1682   // look however, so we use a pseudo here and switch it for a tLDMIA_UPD after
1683   // ISel.
1684   SDValue Chain = LD->getChain();
1685   SDValue Base = LD->getBasePtr();
1686   SDValue Ops[]= { Base, getAL(CurDAG, SDLoc(N)),
1687                    CurDAG->getRegister(0, MVT::i32), Chain };
1688   SDNode *New = CurDAG->getMachineNode(ARM::tLDR_postidx, SDLoc(N), MVT::i32,
1689                                        MVT::i32, MVT::Other, Ops);
1690   transferMemOperands(N, New);
1691   ReplaceNode(N, New);
1692   return true;
1693 }
1694 
1695 bool ARMDAGToDAGISel::tryT2IndexedLoad(SDNode *N) {
1696   LoadSDNode *LD = cast<LoadSDNode>(N);
1697   ISD::MemIndexedMode AM = LD->getAddressingMode();
1698   if (AM == ISD::UNINDEXED)
1699     return false;
1700 
1701   EVT LoadedVT = LD->getMemoryVT();
1702   bool isSExtLd = LD->getExtensionType() == ISD::SEXTLOAD;
1703   SDValue Offset;
1704   bool isPre = (AM == ISD::PRE_INC) || (AM == ISD::PRE_DEC);
1705   unsigned Opcode = 0;
1706   bool Match = false;
1707   if (SelectT2AddrModeImm8Offset(N, LD->getOffset(), Offset)) {
1708     switch (LoadedVT.getSimpleVT().SimpleTy) {
1709     case MVT::i32:
1710       Opcode = isPre ? ARM::t2LDR_PRE : ARM::t2LDR_POST;
1711       break;
1712     case MVT::i16:
1713       if (isSExtLd)
1714         Opcode = isPre ? ARM::t2LDRSH_PRE : ARM::t2LDRSH_POST;
1715       else
1716         Opcode = isPre ? ARM::t2LDRH_PRE : ARM::t2LDRH_POST;
1717       break;
1718     case MVT::i8:
1719     case MVT::i1:
1720       if (isSExtLd)
1721         Opcode = isPre ? ARM::t2LDRSB_PRE : ARM::t2LDRSB_POST;
1722       else
1723         Opcode = isPre ? ARM::t2LDRB_PRE : ARM::t2LDRB_POST;
1724       break;
1725     default:
1726       return false;
1727     }
1728     Match = true;
1729   }
1730 
1731   if (Match) {
1732     SDValue Chain = LD->getChain();
1733     SDValue Base = LD->getBasePtr();
1734     SDValue Ops[]= { Base, Offset, getAL(CurDAG, SDLoc(N)),
1735                      CurDAG->getRegister(0, MVT::i32), Chain };
1736     SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32, MVT::i32,
1737                                          MVT::Other, Ops);
1738     transferMemOperands(N, New);
1739     ReplaceNode(N, New);
1740     return true;
1741   }
1742 
1743   return false;
1744 }
1745 
1746 bool ARMDAGToDAGISel::tryMVEIndexedLoad(SDNode *N) {
1747   EVT LoadedVT;
1748   unsigned Opcode = 0;
1749   bool isSExtLd, isPre;
1750   Align Alignment;
1751   ARMVCC::VPTCodes Pred;
1752   SDValue PredReg;
1753   SDValue Chain, Base, Offset;
1754 
1755   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1756     ISD::MemIndexedMode AM = LD->getAddressingMode();
1757     if (AM == ISD::UNINDEXED)
1758       return false;
1759     LoadedVT = LD->getMemoryVT();
1760     if (!LoadedVT.isVector())
1761       return false;
1762 
1763     Chain = LD->getChain();
1764     Base = LD->getBasePtr();
1765     Offset = LD->getOffset();
1766     Alignment = LD->getAlign();
1767     isSExtLd = LD->getExtensionType() == ISD::SEXTLOAD;
1768     isPre = (AM == ISD::PRE_INC) || (AM == ISD::PRE_DEC);
1769     Pred = ARMVCC::None;
1770     PredReg = CurDAG->getRegister(0, MVT::i32);
1771   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
1772     ISD::MemIndexedMode AM = LD->getAddressingMode();
1773     if (AM == ISD::UNINDEXED)
1774       return false;
1775     LoadedVT = LD->getMemoryVT();
1776     if (!LoadedVT.isVector())
1777       return false;
1778 
1779     Chain = LD->getChain();
1780     Base = LD->getBasePtr();
1781     Offset = LD->getOffset();
1782     Alignment = LD->getAlign();
1783     isSExtLd = LD->getExtensionType() == ISD::SEXTLOAD;
1784     isPre = (AM == ISD::PRE_INC) || (AM == ISD::PRE_DEC);
1785     Pred = ARMVCC::Then;
1786     PredReg = LD->getMask();
1787   } else
1788     llvm_unreachable("Expected a Load or a Masked Load!");
1789 
1790   // We allow LE non-masked loads to change the type (for example use a vldrb.8
1791   // as opposed to a vldrw.32). This can allow extra addressing modes or
1792   // alignments for what is otherwise an equivalent instruction.
1793   bool CanChangeType = Subtarget->isLittle() && !isa<MaskedLoadSDNode>(N);
1794 
1795   SDValue NewOffset;
1796   if (Alignment >= Align(2) && LoadedVT == MVT::v4i16 &&
1797       SelectT2AddrModeImm7Offset(N, Offset, NewOffset, 1)) {
1798     if (isSExtLd)
1799       Opcode = isPre ? ARM::MVE_VLDRHS32_pre : ARM::MVE_VLDRHS32_post;
1800     else
1801       Opcode = isPre ? ARM::MVE_VLDRHU32_pre : ARM::MVE_VLDRHU32_post;
1802   } else if (LoadedVT == MVT::v8i8 &&
1803              SelectT2AddrModeImm7Offset(N, Offset, NewOffset, 0)) {
1804     if (isSExtLd)
1805       Opcode = isPre ? ARM::MVE_VLDRBS16_pre : ARM::MVE_VLDRBS16_post;
1806     else
1807       Opcode = isPre ? ARM::MVE_VLDRBU16_pre : ARM::MVE_VLDRBU16_post;
1808   } else if (LoadedVT == MVT::v4i8 &&
1809              SelectT2AddrModeImm7Offset(N, Offset, NewOffset, 0)) {
1810     if (isSExtLd)
1811       Opcode = isPre ? ARM::MVE_VLDRBS32_pre : ARM::MVE_VLDRBS32_post;
1812     else
1813       Opcode = isPre ? ARM::MVE_VLDRBU32_pre : ARM::MVE_VLDRBU32_post;
1814   } else if (Alignment >= Align(4) &&
1815              (CanChangeType || LoadedVT == MVT::v4i32 ||
1816               LoadedVT == MVT::v4f32) &&
1817              SelectT2AddrModeImm7Offset(N, Offset, NewOffset, 2))
1818     Opcode = isPre ? ARM::MVE_VLDRWU32_pre : ARM::MVE_VLDRWU32_post;
1819   else if (Alignment >= Align(2) &&
1820            (CanChangeType || LoadedVT == MVT::v8i16 ||
1821             LoadedVT == MVT::v8f16) &&
1822            SelectT2AddrModeImm7Offset(N, Offset, NewOffset, 1))
1823     Opcode = isPre ? ARM::MVE_VLDRHU16_pre : ARM::MVE_VLDRHU16_post;
1824   else if ((CanChangeType || LoadedVT == MVT::v16i8) &&
1825            SelectT2AddrModeImm7Offset(N, Offset, NewOffset, 0))
1826     Opcode = isPre ? ARM::MVE_VLDRBU8_pre : ARM::MVE_VLDRBU8_post;
1827   else
1828     return false;
1829 
1830   SDValue Ops[] = {Base,
1831                    NewOffset,
1832                    CurDAG->getTargetConstant(Pred, SDLoc(N), MVT::i32),
1833                    PredReg,
1834                    CurDAG->getRegister(0, MVT::i32), // tp_reg
1835                    Chain};
1836   SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), MVT::i32,
1837                                        N->getValueType(0), MVT::Other, Ops);
1838   transferMemOperands(N, New);
1839   ReplaceUses(SDValue(N, 0), SDValue(New, 1));
1840   ReplaceUses(SDValue(N, 1), SDValue(New, 0));
1841   ReplaceUses(SDValue(N, 2), SDValue(New, 2));
1842   CurDAG->RemoveDeadNode(N);
1843   return true;
1844 }
1845 
1846 /// Form a GPRPair pseudo register from a pair of GPR regs.
1847 SDNode *ARMDAGToDAGISel::createGPRPairNode(EVT VT, SDValue V0, SDValue V1) {
1848   SDLoc dl(V0.getNode());
1849   SDValue RegClass =
1850     CurDAG->getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
1851   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::gsub_0, dl, MVT::i32);
1852   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::gsub_1, dl, MVT::i32);
1853   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
1854   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1855 }
1856 
1857 /// Form a D register from a pair of S registers.
1858 SDNode *ARMDAGToDAGISel::createSRegPairNode(EVT VT, SDValue V0, SDValue V1) {
1859   SDLoc dl(V0.getNode());
1860   SDValue RegClass =
1861     CurDAG->getTargetConstant(ARM::DPR_VFP2RegClassID, dl, MVT::i32);
1862   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::ssub_0, dl, MVT::i32);
1863   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::ssub_1, dl, MVT::i32);
1864   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
1865   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1866 }
1867 
1868 /// Form a quad register from a pair of D registers.
1869 SDNode *ARMDAGToDAGISel::createDRegPairNode(EVT VT, SDValue V0, SDValue V1) {
1870   SDLoc dl(V0.getNode());
1871   SDValue RegClass = CurDAG->getTargetConstant(ARM::QPRRegClassID, dl,
1872                                                MVT::i32);
1873   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::dsub_0, dl, MVT::i32);
1874   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::dsub_1, dl, MVT::i32);
1875   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
1876   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1877 }
1878 
1879 /// Form 4 consecutive D registers from a pair of Q registers.
1880 SDNode *ARMDAGToDAGISel::createQRegPairNode(EVT VT, SDValue V0, SDValue V1) {
1881   SDLoc dl(V0.getNode());
1882   SDValue RegClass = CurDAG->getTargetConstant(ARM::QQPRRegClassID, dl,
1883                                                MVT::i32);
1884   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::qsub_0, dl, MVT::i32);
1885   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::qsub_1, dl, MVT::i32);
1886   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1 };
1887   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1888 }
1889 
1890 /// Form 4 consecutive S registers.
1891 SDNode *ARMDAGToDAGISel::createQuadSRegsNode(EVT VT, SDValue V0, SDValue V1,
1892                                    SDValue V2, SDValue V3) {
1893   SDLoc dl(V0.getNode());
1894   SDValue RegClass =
1895     CurDAG->getTargetConstant(ARM::QPR_VFP2RegClassID, dl, MVT::i32);
1896   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::ssub_0, dl, MVT::i32);
1897   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::ssub_1, dl, MVT::i32);
1898   SDValue SubReg2 = CurDAG->getTargetConstant(ARM::ssub_2, dl, MVT::i32);
1899   SDValue SubReg3 = CurDAG->getTargetConstant(ARM::ssub_3, dl, MVT::i32);
1900   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1,
1901                                     V2, SubReg2, V3, SubReg3 };
1902   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1903 }
1904 
1905 /// Form 4 consecutive D registers.
1906 SDNode *ARMDAGToDAGISel::createQuadDRegsNode(EVT VT, SDValue V0, SDValue V1,
1907                                    SDValue V2, SDValue V3) {
1908   SDLoc dl(V0.getNode());
1909   SDValue RegClass = CurDAG->getTargetConstant(ARM::QQPRRegClassID, dl,
1910                                                MVT::i32);
1911   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::dsub_0, dl, MVT::i32);
1912   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::dsub_1, dl, MVT::i32);
1913   SDValue SubReg2 = CurDAG->getTargetConstant(ARM::dsub_2, dl, MVT::i32);
1914   SDValue SubReg3 = CurDAG->getTargetConstant(ARM::dsub_3, dl, MVT::i32);
1915   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1,
1916                                     V2, SubReg2, V3, SubReg3 };
1917   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1918 }
1919 
1920 /// Form 4 consecutive Q registers.
1921 SDNode *ARMDAGToDAGISel::createQuadQRegsNode(EVT VT, SDValue V0, SDValue V1,
1922                                    SDValue V2, SDValue V3) {
1923   SDLoc dl(V0.getNode());
1924   SDValue RegClass = CurDAG->getTargetConstant(ARM::QQQQPRRegClassID, dl,
1925                                                MVT::i32);
1926   SDValue SubReg0 = CurDAG->getTargetConstant(ARM::qsub_0, dl, MVT::i32);
1927   SDValue SubReg1 = CurDAG->getTargetConstant(ARM::qsub_1, dl, MVT::i32);
1928   SDValue SubReg2 = CurDAG->getTargetConstant(ARM::qsub_2, dl, MVT::i32);
1929   SDValue SubReg3 = CurDAG->getTargetConstant(ARM::qsub_3, dl, MVT::i32);
1930   const SDValue Ops[] = { RegClass, V0, SubReg0, V1, SubReg1,
1931                                     V2, SubReg2, V3, SubReg3 };
1932   return CurDAG->getMachineNode(TargetOpcode::REG_SEQUENCE, dl, VT, Ops);
1933 }
1934 
1935 /// GetVLDSTAlign - Get the alignment (in bytes) for the alignment operand
1936 /// of a NEON VLD or VST instruction.  The supported values depend on the
1937 /// number of registers being loaded.
1938 SDValue ARMDAGToDAGISel::GetVLDSTAlign(SDValue Align, const SDLoc &dl,
1939                                        unsigned NumVecs, bool is64BitVector) {
1940   unsigned NumRegs = NumVecs;
1941   if (!is64BitVector && NumVecs < 3)
1942     NumRegs *= 2;
1943 
1944   unsigned Alignment = cast<ConstantSDNode>(Align)->getZExtValue();
1945   if (Alignment >= 32 && NumRegs == 4)
1946     Alignment = 32;
1947   else if (Alignment >= 16 && (NumRegs == 2 || NumRegs == 4))
1948     Alignment = 16;
1949   else if (Alignment >= 8)
1950     Alignment = 8;
1951   else
1952     Alignment = 0;
1953 
1954   return CurDAG->getTargetConstant(Alignment, dl, MVT::i32);
1955 }
1956 
1957 static bool isVLDfixed(unsigned Opc)
1958 {
1959   switch (Opc) {
1960   default: return false;
1961   case ARM::VLD1d8wb_fixed : return true;
1962   case ARM::VLD1d16wb_fixed : return true;
1963   case ARM::VLD1d64Qwb_fixed : return true;
1964   case ARM::VLD1d32wb_fixed : return true;
1965   case ARM::VLD1d64wb_fixed : return true;
1966   case ARM::VLD1d8TPseudoWB_fixed : return true;
1967   case ARM::VLD1d16TPseudoWB_fixed : return true;
1968   case ARM::VLD1d32TPseudoWB_fixed : return true;
1969   case ARM::VLD1d64TPseudoWB_fixed : return true;
1970   case ARM::VLD1d8QPseudoWB_fixed : return true;
1971   case ARM::VLD1d16QPseudoWB_fixed : return true;
1972   case ARM::VLD1d32QPseudoWB_fixed : return true;
1973   case ARM::VLD1d64QPseudoWB_fixed : return true;
1974   case ARM::VLD1q8wb_fixed : return true;
1975   case ARM::VLD1q16wb_fixed : return true;
1976   case ARM::VLD1q32wb_fixed : return true;
1977   case ARM::VLD1q64wb_fixed : return true;
1978   case ARM::VLD1DUPd8wb_fixed : return true;
1979   case ARM::VLD1DUPd16wb_fixed : return true;
1980   case ARM::VLD1DUPd32wb_fixed : return true;
1981   case ARM::VLD1DUPq8wb_fixed : return true;
1982   case ARM::VLD1DUPq16wb_fixed : return true;
1983   case ARM::VLD1DUPq32wb_fixed : return true;
1984   case ARM::VLD2d8wb_fixed : return true;
1985   case ARM::VLD2d16wb_fixed : return true;
1986   case ARM::VLD2d32wb_fixed : return true;
1987   case ARM::VLD2q8PseudoWB_fixed : return true;
1988   case ARM::VLD2q16PseudoWB_fixed : return true;
1989   case ARM::VLD2q32PseudoWB_fixed : return true;
1990   case ARM::VLD2DUPd8wb_fixed : return true;
1991   case ARM::VLD2DUPd16wb_fixed : return true;
1992   case ARM::VLD2DUPd32wb_fixed : return true;
1993   case ARM::VLD2DUPq8OddPseudoWB_fixed: return true;
1994   case ARM::VLD2DUPq16OddPseudoWB_fixed: return true;
1995   case ARM::VLD2DUPq32OddPseudoWB_fixed: return true;
1996   }
1997 }
1998 
1999 static bool isVSTfixed(unsigned Opc)
2000 {
2001   switch (Opc) {
2002   default: return false;
2003   case ARM::VST1d8wb_fixed : return true;
2004   case ARM::VST1d16wb_fixed : return true;
2005   case ARM::VST1d32wb_fixed : return true;
2006   case ARM::VST1d64wb_fixed : return true;
2007   case ARM::VST1q8wb_fixed : return true;
2008   case ARM::VST1q16wb_fixed : return true;
2009   case ARM::VST1q32wb_fixed : return true;
2010   case ARM::VST1q64wb_fixed : return true;
2011   case ARM::VST1d8TPseudoWB_fixed : return true;
2012   case ARM::VST1d16TPseudoWB_fixed : return true;
2013   case ARM::VST1d32TPseudoWB_fixed : return true;
2014   case ARM::VST1d64TPseudoWB_fixed : return true;
2015   case ARM::VST1d8QPseudoWB_fixed : return true;
2016   case ARM::VST1d16QPseudoWB_fixed : return true;
2017   case ARM::VST1d32QPseudoWB_fixed : return true;
2018   case ARM::VST1d64QPseudoWB_fixed : return true;
2019   case ARM::VST2d8wb_fixed : return true;
2020   case ARM::VST2d16wb_fixed : return true;
2021   case ARM::VST2d32wb_fixed : return true;
2022   case ARM::VST2q8PseudoWB_fixed : return true;
2023   case ARM::VST2q16PseudoWB_fixed : return true;
2024   case ARM::VST2q32PseudoWB_fixed : return true;
2025   }
2026 }
2027 
2028 // Get the register stride update opcode of a VLD/VST instruction that
2029 // is otherwise equivalent to the given fixed stride updating instruction.
2030 static unsigned getVLDSTRegisterUpdateOpcode(unsigned Opc) {
2031   assert((isVLDfixed(Opc) || isVSTfixed(Opc))
2032     && "Incorrect fixed stride updating instruction.");
2033   switch (Opc) {
2034   default: break;
2035   case ARM::VLD1d8wb_fixed: return ARM::VLD1d8wb_register;
2036   case ARM::VLD1d16wb_fixed: return ARM::VLD1d16wb_register;
2037   case ARM::VLD1d32wb_fixed: return ARM::VLD1d32wb_register;
2038   case ARM::VLD1d64wb_fixed: return ARM::VLD1d64wb_register;
2039   case ARM::VLD1q8wb_fixed: return ARM::VLD1q8wb_register;
2040   case ARM::VLD1q16wb_fixed: return ARM::VLD1q16wb_register;
2041   case ARM::VLD1q32wb_fixed: return ARM::VLD1q32wb_register;
2042   case ARM::VLD1q64wb_fixed: return ARM::VLD1q64wb_register;
2043   case ARM::VLD1d64Twb_fixed: return ARM::VLD1d64Twb_register;
2044   case ARM::VLD1d64Qwb_fixed: return ARM::VLD1d64Qwb_register;
2045   case ARM::VLD1d8TPseudoWB_fixed: return ARM::VLD1d8TPseudoWB_register;
2046   case ARM::VLD1d16TPseudoWB_fixed: return ARM::VLD1d16TPseudoWB_register;
2047   case ARM::VLD1d32TPseudoWB_fixed: return ARM::VLD1d32TPseudoWB_register;
2048   case ARM::VLD1d64TPseudoWB_fixed: return ARM::VLD1d64TPseudoWB_register;
2049   case ARM::VLD1d8QPseudoWB_fixed: return ARM::VLD1d8QPseudoWB_register;
2050   case ARM::VLD1d16QPseudoWB_fixed: return ARM::VLD1d16QPseudoWB_register;
2051   case ARM::VLD1d32QPseudoWB_fixed: return ARM::VLD1d32QPseudoWB_register;
2052   case ARM::VLD1d64QPseudoWB_fixed: return ARM::VLD1d64QPseudoWB_register;
2053   case ARM::VLD1DUPd8wb_fixed : return ARM::VLD1DUPd8wb_register;
2054   case ARM::VLD1DUPd16wb_fixed : return ARM::VLD1DUPd16wb_register;
2055   case ARM::VLD1DUPd32wb_fixed : return ARM::VLD1DUPd32wb_register;
2056   case ARM::VLD1DUPq8wb_fixed : return ARM::VLD1DUPq8wb_register;
2057   case ARM::VLD1DUPq16wb_fixed : return ARM::VLD1DUPq16wb_register;
2058   case ARM::VLD1DUPq32wb_fixed : return ARM::VLD1DUPq32wb_register;
2059   case ARM::VLD2DUPq8OddPseudoWB_fixed: return ARM::VLD2DUPq8OddPseudoWB_register;
2060   case ARM::VLD2DUPq16OddPseudoWB_fixed: return ARM::VLD2DUPq16OddPseudoWB_register;
2061   case ARM::VLD2DUPq32OddPseudoWB_fixed: return ARM::VLD2DUPq32OddPseudoWB_register;
2062 
2063   case ARM::VST1d8wb_fixed: return ARM::VST1d8wb_register;
2064   case ARM::VST1d16wb_fixed: return ARM::VST1d16wb_register;
2065   case ARM::VST1d32wb_fixed: return ARM::VST1d32wb_register;
2066   case ARM::VST1d64wb_fixed: return ARM::VST1d64wb_register;
2067   case ARM::VST1q8wb_fixed: return ARM::VST1q8wb_register;
2068   case ARM::VST1q16wb_fixed: return ARM::VST1q16wb_register;
2069   case ARM::VST1q32wb_fixed: return ARM::VST1q32wb_register;
2070   case ARM::VST1q64wb_fixed: return ARM::VST1q64wb_register;
2071   case ARM::VST1d8TPseudoWB_fixed: return ARM::VST1d8TPseudoWB_register;
2072   case ARM::VST1d16TPseudoWB_fixed: return ARM::VST1d16TPseudoWB_register;
2073   case ARM::VST1d32TPseudoWB_fixed: return ARM::VST1d32TPseudoWB_register;
2074   case ARM::VST1d64TPseudoWB_fixed: return ARM::VST1d64TPseudoWB_register;
2075   case ARM::VST1d8QPseudoWB_fixed: return ARM::VST1d8QPseudoWB_register;
2076   case ARM::VST1d16QPseudoWB_fixed: return ARM::VST1d16QPseudoWB_register;
2077   case ARM::VST1d32QPseudoWB_fixed: return ARM::VST1d32QPseudoWB_register;
2078   case ARM::VST1d64QPseudoWB_fixed: return ARM::VST1d64QPseudoWB_register;
2079 
2080   case ARM::VLD2d8wb_fixed: return ARM::VLD2d8wb_register;
2081   case ARM::VLD2d16wb_fixed: return ARM::VLD2d16wb_register;
2082   case ARM::VLD2d32wb_fixed: return ARM::VLD2d32wb_register;
2083   case ARM::VLD2q8PseudoWB_fixed: return ARM::VLD2q8PseudoWB_register;
2084   case ARM::VLD2q16PseudoWB_fixed: return ARM::VLD2q16PseudoWB_register;
2085   case ARM::VLD2q32PseudoWB_fixed: return ARM::VLD2q32PseudoWB_register;
2086 
2087   case ARM::VST2d8wb_fixed: return ARM::VST2d8wb_register;
2088   case ARM::VST2d16wb_fixed: return ARM::VST2d16wb_register;
2089   case ARM::VST2d32wb_fixed: return ARM::VST2d32wb_register;
2090   case ARM::VST2q8PseudoWB_fixed: return ARM::VST2q8PseudoWB_register;
2091   case ARM::VST2q16PseudoWB_fixed: return ARM::VST2q16PseudoWB_register;
2092   case ARM::VST2q32PseudoWB_fixed: return ARM::VST2q32PseudoWB_register;
2093 
2094   case ARM::VLD2DUPd8wb_fixed: return ARM::VLD2DUPd8wb_register;
2095   case ARM::VLD2DUPd16wb_fixed: return ARM::VLD2DUPd16wb_register;
2096   case ARM::VLD2DUPd32wb_fixed: return ARM::VLD2DUPd32wb_register;
2097   }
2098   return Opc; // If not one we handle, return it unchanged.
2099 }
2100 
2101 /// Returns true if the given increment is a Constant known to be equal to the
2102 /// access size performed by a NEON load/store. This means the "[rN]!" form can
2103 /// be used.
2104 static bool isPerfectIncrement(SDValue Inc, EVT VecTy, unsigned NumVecs) {
2105   auto C = dyn_cast<ConstantSDNode>(Inc);
2106   return C && C->getZExtValue() == VecTy.getSizeInBits() / 8 * NumVecs;
2107 }
2108 
2109 void ARMDAGToDAGISel::SelectVLD(SDNode *N, bool isUpdating, unsigned NumVecs,
2110                                 const uint16_t *DOpcodes,
2111                                 const uint16_t *QOpcodes0,
2112                                 const uint16_t *QOpcodes1) {
2113   assert(Subtarget->hasNEON());
2114   assert(NumVecs >= 1 && NumVecs <= 4 && "VLD NumVecs out-of-range");
2115   SDLoc dl(N);
2116 
2117   SDValue MemAddr, Align;
2118   bool IsIntrinsic = !isUpdating;  // By coincidence, all supported updating
2119                                    // nodes are not intrinsics.
2120   unsigned AddrOpIdx = IsIntrinsic ? 2 : 1;
2121   if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
2122     return;
2123 
2124   SDValue Chain = N->getOperand(0);
2125   EVT VT = N->getValueType(0);
2126   bool is64BitVector = VT.is64BitVector();
2127   Align = GetVLDSTAlign(Align, dl, NumVecs, is64BitVector);
2128 
2129   unsigned OpcodeIndex;
2130   switch (VT.getSimpleVT().SimpleTy) {
2131   default: llvm_unreachable("unhandled vld type");
2132     // Double-register operations:
2133   case MVT::v8i8:  OpcodeIndex = 0; break;
2134   case MVT::v4f16:
2135   case MVT::v4bf16:
2136   case MVT::v4i16: OpcodeIndex = 1; break;
2137   case MVT::v2f32:
2138   case MVT::v2i32: OpcodeIndex = 2; break;
2139   case MVT::v1i64: OpcodeIndex = 3; break;
2140     // Quad-register operations:
2141   case MVT::v16i8: OpcodeIndex = 0; break;
2142   case MVT::v8f16:
2143   case MVT::v8bf16:
2144   case MVT::v8i16: OpcodeIndex = 1; break;
2145   case MVT::v4f32:
2146   case MVT::v4i32: OpcodeIndex = 2; break;
2147   case MVT::v2f64:
2148   case MVT::v2i64: OpcodeIndex = 3; break;
2149   }
2150 
2151   EVT ResTy;
2152   if (NumVecs == 1)
2153     ResTy = VT;
2154   else {
2155     unsigned ResTyElts = (NumVecs == 3) ? 4 : NumVecs;
2156     if (!is64BitVector)
2157       ResTyElts *= 2;
2158     ResTy = EVT::getVectorVT(*CurDAG->getContext(), MVT::i64, ResTyElts);
2159   }
2160   std::vector<EVT> ResTys;
2161   ResTys.push_back(ResTy);
2162   if (isUpdating)
2163     ResTys.push_back(MVT::i32);
2164   ResTys.push_back(MVT::Other);
2165 
2166   SDValue Pred = getAL(CurDAG, dl);
2167   SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2168   SDNode *VLd;
2169   SmallVector<SDValue, 7> Ops;
2170 
2171   // Double registers and VLD1/VLD2 quad registers are directly supported.
2172   if (is64BitVector || NumVecs <= 2) {
2173     unsigned Opc = (is64BitVector ? DOpcodes[OpcodeIndex] :
2174                     QOpcodes0[OpcodeIndex]);
2175     Ops.push_back(MemAddr);
2176     Ops.push_back(Align);
2177     if (isUpdating) {
2178       SDValue Inc = N->getOperand(AddrOpIdx + 1);
2179       bool IsImmUpdate = isPerfectIncrement(Inc, VT, NumVecs);
2180       if (!IsImmUpdate) {
2181         // We use a VLD1 for v1i64 even if the pseudo says vld2/3/4, so
2182         // check for the opcode rather than the number of vector elements.
2183         if (isVLDfixed(Opc))
2184           Opc = getVLDSTRegisterUpdateOpcode(Opc);
2185         Ops.push_back(Inc);
2186       // VLD1/VLD2 fixed increment does not need Reg0 so only include it in
2187       // the operands if not such an opcode.
2188       } else if (!isVLDfixed(Opc))
2189         Ops.push_back(Reg0);
2190     }
2191     Ops.push_back(Pred);
2192     Ops.push_back(Reg0);
2193     Ops.push_back(Chain);
2194     VLd = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
2195 
2196   } else {
2197     // Otherwise, quad registers are loaded with two separate instructions,
2198     // where one loads the even registers and the other loads the odd registers.
2199     EVT AddrTy = MemAddr.getValueType();
2200 
2201     // Load the even subregs.  This is always an updating load, so that it
2202     // provides the address to the second load for the odd subregs.
2203     SDValue ImplDef =
2204       SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, ResTy), 0);
2205     const SDValue OpsA[] = { MemAddr, Align, Reg0, ImplDef, Pred, Reg0, Chain };
2206     SDNode *VLdA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex], dl,
2207                                           ResTy, AddrTy, MVT::Other, OpsA);
2208     Chain = SDValue(VLdA, 2);
2209 
2210     // Load the odd subregs.
2211     Ops.push_back(SDValue(VLdA, 1));
2212     Ops.push_back(Align);
2213     if (isUpdating) {
2214       SDValue Inc = N->getOperand(AddrOpIdx + 1);
2215       assert(isa<ConstantSDNode>(Inc.getNode()) &&
2216              "only constant post-increment update allowed for VLD3/4");
2217       (void)Inc;
2218       Ops.push_back(Reg0);
2219     }
2220     Ops.push_back(SDValue(VLdA, 0));
2221     Ops.push_back(Pred);
2222     Ops.push_back(Reg0);
2223     Ops.push_back(Chain);
2224     VLd = CurDAG->getMachineNode(QOpcodes1[OpcodeIndex], dl, ResTys, Ops);
2225   }
2226 
2227   // Transfer memoperands.
2228   MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2229   CurDAG->setNodeMemRefs(cast<MachineSDNode>(VLd), {MemOp});
2230 
2231   if (NumVecs == 1) {
2232     ReplaceNode(N, VLd);
2233     return;
2234   }
2235 
2236   // Extract out the subregisters.
2237   SDValue SuperReg = SDValue(VLd, 0);
2238   static_assert(ARM::dsub_7 == ARM::dsub_0 + 7 &&
2239                     ARM::qsub_3 == ARM::qsub_0 + 3,
2240                 "Unexpected subreg numbering");
2241   unsigned Sub0 = (is64BitVector ? ARM::dsub_0 : ARM::qsub_0);
2242   for (unsigned Vec = 0; Vec < NumVecs; ++Vec)
2243     ReplaceUses(SDValue(N, Vec),
2244                 CurDAG->getTargetExtractSubreg(Sub0 + Vec, dl, VT, SuperReg));
2245   ReplaceUses(SDValue(N, NumVecs), SDValue(VLd, 1));
2246   if (isUpdating)
2247     ReplaceUses(SDValue(N, NumVecs + 1), SDValue(VLd, 2));
2248   CurDAG->RemoveDeadNode(N);
2249 }
2250 
2251 void ARMDAGToDAGISel::SelectVST(SDNode *N, bool isUpdating, unsigned NumVecs,
2252                                 const uint16_t *DOpcodes,
2253                                 const uint16_t *QOpcodes0,
2254                                 const uint16_t *QOpcodes1) {
2255   assert(Subtarget->hasNEON());
2256   assert(NumVecs >= 1 && NumVecs <= 4 && "VST NumVecs out-of-range");
2257   SDLoc dl(N);
2258 
2259   SDValue MemAddr, Align;
2260   bool IsIntrinsic = !isUpdating;  // By coincidence, all supported updating
2261                                    // nodes are not intrinsics.
2262   unsigned AddrOpIdx = IsIntrinsic ? 2 : 1;
2263   unsigned Vec0Idx = 3; // AddrOpIdx + (isUpdating ? 2 : 1)
2264   if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
2265     return;
2266 
2267   MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2268 
2269   SDValue Chain = N->getOperand(0);
2270   EVT VT = N->getOperand(Vec0Idx).getValueType();
2271   bool is64BitVector = VT.is64BitVector();
2272   Align = GetVLDSTAlign(Align, dl, NumVecs, is64BitVector);
2273 
2274   unsigned OpcodeIndex;
2275   switch (VT.getSimpleVT().SimpleTy) {
2276   default: llvm_unreachable("unhandled vst type");
2277     // Double-register operations:
2278   case MVT::v8i8:  OpcodeIndex = 0; break;
2279   case MVT::v4f16:
2280   case MVT::v4bf16:
2281   case MVT::v4i16: OpcodeIndex = 1; break;
2282   case MVT::v2f32:
2283   case MVT::v2i32: OpcodeIndex = 2; break;
2284   case MVT::v1i64: OpcodeIndex = 3; break;
2285     // Quad-register operations:
2286   case MVT::v16i8: OpcodeIndex = 0; break;
2287   case MVT::v8f16:
2288   case MVT::v8bf16:
2289   case MVT::v8i16: OpcodeIndex = 1; break;
2290   case MVT::v4f32:
2291   case MVT::v4i32: OpcodeIndex = 2; break;
2292   case MVT::v2f64:
2293   case MVT::v2i64: OpcodeIndex = 3; break;
2294   }
2295 
2296   std::vector<EVT> ResTys;
2297   if (isUpdating)
2298     ResTys.push_back(MVT::i32);
2299   ResTys.push_back(MVT::Other);
2300 
2301   SDValue Pred = getAL(CurDAG, dl);
2302   SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2303   SmallVector<SDValue, 7> Ops;
2304 
2305   // Double registers and VST1/VST2 quad registers are directly supported.
2306   if (is64BitVector || NumVecs <= 2) {
2307     SDValue SrcReg;
2308     if (NumVecs == 1) {
2309       SrcReg = N->getOperand(Vec0Idx);
2310     } else if (is64BitVector) {
2311       // Form a REG_SEQUENCE to force register allocation.
2312       SDValue V0 = N->getOperand(Vec0Idx + 0);
2313       SDValue V1 = N->getOperand(Vec0Idx + 1);
2314       if (NumVecs == 2)
2315         SrcReg = SDValue(createDRegPairNode(MVT::v2i64, V0, V1), 0);
2316       else {
2317         SDValue V2 = N->getOperand(Vec0Idx + 2);
2318         // If it's a vst3, form a quad D-register and leave the last part as
2319         // an undef.
2320         SDValue V3 = (NumVecs == 3)
2321           ? SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF,dl,VT), 0)
2322           : N->getOperand(Vec0Idx + 3);
2323         SrcReg = SDValue(createQuadDRegsNode(MVT::v4i64, V0, V1, V2, V3), 0);
2324       }
2325     } else {
2326       // Form a QQ register.
2327       SDValue Q0 = N->getOperand(Vec0Idx);
2328       SDValue Q1 = N->getOperand(Vec0Idx + 1);
2329       SrcReg = SDValue(createQRegPairNode(MVT::v4i64, Q0, Q1), 0);
2330     }
2331 
2332     unsigned Opc = (is64BitVector ? DOpcodes[OpcodeIndex] :
2333                     QOpcodes0[OpcodeIndex]);
2334     Ops.push_back(MemAddr);
2335     Ops.push_back(Align);
2336     if (isUpdating) {
2337       SDValue Inc = N->getOperand(AddrOpIdx + 1);
2338       bool IsImmUpdate = isPerfectIncrement(Inc, VT, NumVecs);
2339       if (!IsImmUpdate) {
2340         // We use a VST1 for v1i64 even if the pseudo says VST2/3/4, so
2341         // check for the opcode rather than the number of vector elements.
2342         if (isVSTfixed(Opc))
2343           Opc = getVLDSTRegisterUpdateOpcode(Opc);
2344         Ops.push_back(Inc);
2345       }
2346       // VST1/VST2 fixed increment does not need Reg0 so only include it in
2347       // the operands if not such an opcode.
2348       else if (!isVSTfixed(Opc))
2349         Ops.push_back(Reg0);
2350     }
2351     Ops.push_back(SrcReg);
2352     Ops.push_back(Pred);
2353     Ops.push_back(Reg0);
2354     Ops.push_back(Chain);
2355     SDNode *VSt = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
2356 
2357     // Transfer memoperands.
2358     CurDAG->setNodeMemRefs(cast<MachineSDNode>(VSt), {MemOp});
2359 
2360     ReplaceNode(N, VSt);
2361     return;
2362   }
2363 
2364   // Otherwise, quad registers are stored with two separate instructions,
2365   // where one stores the even registers and the other stores the odd registers.
2366 
2367   // Form the QQQQ REG_SEQUENCE.
2368   SDValue V0 = N->getOperand(Vec0Idx + 0);
2369   SDValue V1 = N->getOperand(Vec0Idx + 1);
2370   SDValue V2 = N->getOperand(Vec0Idx + 2);
2371   SDValue V3 = (NumVecs == 3)
2372     ? SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, VT), 0)
2373     : N->getOperand(Vec0Idx + 3);
2374   SDValue RegSeq = SDValue(createQuadQRegsNode(MVT::v8i64, V0, V1, V2, V3), 0);
2375 
2376   // Store the even D registers.  This is always an updating store, so that it
2377   // provides the address to the second store for the odd subregs.
2378   const SDValue OpsA[] = { MemAddr, Align, Reg0, RegSeq, Pred, Reg0, Chain };
2379   SDNode *VStA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex], dl,
2380                                         MemAddr.getValueType(),
2381                                         MVT::Other, OpsA);
2382   CurDAG->setNodeMemRefs(cast<MachineSDNode>(VStA), {MemOp});
2383   Chain = SDValue(VStA, 1);
2384 
2385   // Store the odd D registers.
2386   Ops.push_back(SDValue(VStA, 0));
2387   Ops.push_back(Align);
2388   if (isUpdating) {
2389     SDValue Inc = N->getOperand(AddrOpIdx + 1);
2390     assert(isa<ConstantSDNode>(Inc.getNode()) &&
2391            "only constant post-increment update allowed for VST3/4");
2392     (void)Inc;
2393     Ops.push_back(Reg0);
2394   }
2395   Ops.push_back(RegSeq);
2396   Ops.push_back(Pred);
2397   Ops.push_back(Reg0);
2398   Ops.push_back(Chain);
2399   SDNode *VStB = CurDAG->getMachineNode(QOpcodes1[OpcodeIndex], dl, ResTys,
2400                                         Ops);
2401   CurDAG->setNodeMemRefs(cast<MachineSDNode>(VStB), {MemOp});
2402   ReplaceNode(N, VStB);
2403 }
2404 
2405 void ARMDAGToDAGISel::SelectVLDSTLane(SDNode *N, bool IsLoad, bool isUpdating,
2406                                       unsigned NumVecs,
2407                                       const uint16_t *DOpcodes,
2408                                       const uint16_t *QOpcodes) {
2409   assert(Subtarget->hasNEON());
2410   assert(NumVecs >=2 && NumVecs <= 4 && "VLDSTLane NumVecs out-of-range");
2411   SDLoc dl(N);
2412 
2413   SDValue MemAddr, Align;
2414   bool IsIntrinsic = !isUpdating;  // By coincidence, all supported updating
2415                                    // nodes are not intrinsics.
2416   unsigned AddrOpIdx = IsIntrinsic ? 2 : 1;
2417   unsigned Vec0Idx = 3; // AddrOpIdx + (isUpdating ? 2 : 1)
2418   if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
2419     return;
2420 
2421   MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
2422 
2423   SDValue Chain = N->getOperand(0);
2424   unsigned Lane =
2425     cast<ConstantSDNode>(N->getOperand(Vec0Idx + NumVecs))->getZExtValue();
2426   EVT VT = N->getOperand(Vec0Idx).getValueType();
2427   bool is64BitVector = VT.is64BitVector();
2428 
2429   unsigned Alignment = 0;
2430   if (NumVecs != 3) {
2431     Alignment = cast<ConstantSDNode>(Align)->getZExtValue();
2432     unsigned NumBytes = NumVecs * VT.getScalarSizeInBits() / 8;
2433     if (Alignment > NumBytes)
2434       Alignment = NumBytes;
2435     if (Alignment < 8 && Alignment < NumBytes)
2436       Alignment = 0;
2437     // Alignment must be a power of two; make sure of that.
2438     Alignment = (Alignment & -Alignment);
2439     if (Alignment == 1)
2440       Alignment = 0;
2441   }
2442   Align = CurDAG->getTargetConstant(Alignment, dl, MVT::i32);
2443 
2444   unsigned OpcodeIndex;
2445   switch (VT.getSimpleVT().SimpleTy) {
2446   default: llvm_unreachable("unhandled vld/vst lane type");
2447     // Double-register operations:
2448   case MVT::v8i8:  OpcodeIndex = 0; break;
2449   case MVT::v4f16:
2450   case MVT::v4bf16:
2451   case MVT::v4i16: OpcodeIndex = 1; break;
2452   case MVT::v2f32:
2453   case MVT::v2i32: OpcodeIndex = 2; break;
2454     // Quad-register operations:
2455   case MVT::v8f16:
2456   case MVT::v8bf16:
2457   case MVT::v8i16: OpcodeIndex = 0; break;
2458   case MVT::v4f32:
2459   case MVT::v4i32: OpcodeIndex = 1; break;
2460   }
2461 
2462   std::vector<EVT> ResTys;
2463   if (IsLoad) {
2464     unsigned ResTyElts = (NumVecs == 3) ? 4 : NumVecs;
2465     if (!is64BitVector)
2466       ResTyElts *= 2;
2467     ResTys.push_back(EVT::getVectorVT(*CurDAG->getContext(),
2468                                       MVT::i64, ResTyElts));
2469   }
2470   if (isUpdating)
2471     ResTys.push_back(MVT::i32);
2472   ResTys.push_back(MVT::Other);
2473 
2474   SDValue Pred = getAL(CurDAG, dl);
2475   SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
2476 
2477   SmallVector<SDValue, 8> Ops;
2478   Ops.push_back(MemAddr);
2479   Ops.push_back(Align);
2480   if (isUpdating) {
2481     SDValue Inc = N->getOperand(AddrOpIdx + 1);
2482     bool IsImmUpdate =
2483         isPerfectIncrement(Inc, VT.getVectorElementType(), NumVecs);
2484     Ops.push_back(IsImmUpdate ? Reg0 : Inc);
2485   }
2486 
2487   SDValue SuperReg;
2488   SDValue V0 = N->getOperand(Vec0Idx + 0);
2489   SDValue V1 = N->getOperand(Vec0Idx + 1);
2490   if (NumVecs == 2) {
2491     if (is64BitVector)
2492       SuperReg = SDValue(createDRegPairNode(MVT::v2i64, V0, V1), 0);
2493     else
2494       SuperReg = SDValue(createQRegPairNode(MVT::v4i64, V0, V1), 0);
2495   } else {
2496     SDValue V2 = N->getOperand(Vec0Idx + 2);
2497     SDValue V3 = (NumVecs == 3)
2498       ? SDValue(CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, VT), 0)
2499       : N->getOperand(Vec0Idx + 3);
2500     if (is64BitVector)
2501       SuperReg = SDValue(createQuadDRegsNode(MVT::v4i64, V0, V1, V2, V3), 0);
2502     else
2503       SuperReg = SDValue(createQuadQRegsNode(MVT::v8i64, V0, V1, V2, V3), 0);
2504   }
2505   Ops.push_back(SuperReg);
2506   Ops.push_back(getI32Imm(Lane, dl));
2507   Ops.push_back(Pred);
2508   Ops.push_back(Reg0);
2509   Ops.push_back(Chain);
2510 
2511   unsigned Opc = (is64BitVector ? DOpcodes[OpcodeIndex] :
2512                                   QOpcodes[OpcodeIndex]);
2513   SDNode *VLdLn = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
2514   CurDAG->setNodeMemRefs(cast<MachineSDNode>(VLdLn), {MemOp});
2515   if (!IsLoad) {
2516     ReplaceNode(N, VLdLn);
2517     return;
2518   }
2519 
2520   // Extract the subregisters.
2521   SuperReg = SDValue(VLdLn, 0);
2522   static_assert(ARM::dsub_7 == ARM::dsub_0 + 7 &&
2523                     ARM::qsub_3 == ARM::qsub_0 + 3,
2524                 "Unexpected subreg numbering");
2525   unsigned Sub0 = is64BitVector ? ARM::dsub_0 : ARM::qsub_0;
2526   for (unsigned Vec = 0; Vec < NumVecs; ++Vec)
2527     ReplaceUses(SDValue(N, Vec),
2528                 CurDAG->getTargetExtractSubreg(Sub0 + Vec, dl, VT, SuperReg));
2529   ReplaceUses(SDValue(N, NumVecs), SDValue(VLdLn, 1));
2530   if (isUpdating)
2531     ReplaceUses(SDValue(N, NumVecs + 1), SDValue(VLdLn, 2));
2532   CurDAG->RemoveDeadNode(N);
2533 }
2534 
2535 template <typename SDValueVector>
2536 void ARMDAGToDAGISel::AddMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc,
2537                                            SDValue PredicateMask) {
2538   Ops.push_back(CurDAG->getTargetConstant(ARMVCC::Then, Loc, MVT::i32));
2539   Ops.push_back(PredicateMask);
2540   Ops.push_back(CurDAG->getRegister(0, MVT::i32)); // tp_reg
2541 }
2542 
2543 template <typename SDValueVector>
2544 void ARMDAGToDAGISel::AddMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc,
2545                                            SDValue PredicateMask,
2546                                            SDValue Inactive) {
2547   Ops.push_back(CurDAG->getTargetConstant(ARMVCC::Then, Loc, MVT::i32));
2548   Ops.push_back(PredicateMask);
2549   Ops.push_back(CurDAG->getRegister(0, MVT::i32)); // tp_reg
2550   Ops.push_back(Inactive);
2551 }
2552 
2553 template <typename SDValueVector>
2554 void ARMDAGToDAGISel::AddEmptyMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc) {
2555   Ops.push_back(CurDAG->getTargetConstant(ARMVCC::None, Loc, MVT::i32));
2556   Ops.push_back(CurDAG->getRegister(0, MVT::i32));
2557   Ops.push_back(CurDAG->getRegister(0, MVT::i32)); // tp_reg
2558 }
2559 
2560 template <typename SDValueVector>
2561 void ARMDAGToDAGISel::AddEmptyMVEPredicateToOps(SDValueVector &Ops, SDLoc Loc,
2562                                                 EVT InactiveTy) {
2563   Ops.push_back(CurDAG->getTargetConstant(ARMVCC::None, Loc, MVT::i32));
2564   Ops.push_back(CurDAG->getRegister(0, MVT::i32));
2565   Ops.push_back(CurDAG->getRegister(0, MVT::i32)); // tp_reg
2566   Ops.push_back(SDValue(
2567       CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, Loc, InactiveTy), 0));
2568 }
2569 
2570 void ARMDAGToDAGISel::SelectMVE_WB(SDNode *N, const uint16_t *Opcodes,
2571                                    bool Predicated) {
2572   SDLoc Loc(N);
2573   SmallVector<SDValue, 8> Ops;
2574 
2575   uint16_t Opcode;
2576   switch (N->getValueType(1).getVectorElementType().getSizeInBits()) {
2577   case 32:
2578     Opcode = Opcodes[0];
2579     break;
2580   case 64:
2581     Opcode = Opcodes[1];
2582     break;
2583   default:
2584     llvm_unreachable("bad vector element size in SelectMVE_WB");
2585   }
2586 
2587   Ops.push_back(N->getOperand(2)); // vector of base addresses
2588 
2589   int32_t ImmValue = cast<ConstantSDNode>(N->getOperand(3))->getZExtValue();
2590   Ops.push_back(getI32Imm(ImmValue, Loc)); // immediate offset
2591 
2592   if (Predicated)
2593     AddMVEPredicateToOps(Ops, Loc, N->getOperand(4));
2594   else
2595     AddEmptyMVEPredicateToOps(Ops, Loc);
2596 
2597   Ops.push_back(N->getOperand(0)); // chain
2598 
2599   SmallVector<EVT, 8> VTs;
2600   VTs.push_back(N->getValueType(1));
2601   VTs.push_back(N->getValueType(0));
2602   VTs.push_back(N->getValueType(2));
2603 
2604   SDNode *New = CurDAG->getMachineNode(Opcode, SDLoc(N), VTs, Ops);
2605   ReplaceUses(SDValue(N, 0), SDValue(New, 1));
2606   ReplaceUses(SDValue(N, 1), SDValue(New, 0));
2607   ReplaceUses(SDValue(N, 2), SDValue(New, 2));
2608   transferMemOperands(N, New);
2609   CurDAG->RemoveDeadNode(N);
2610 }
2611 
2612 void ARMDAGToDAGISel::SelectMVE_LongShift(SDNode *N, uint16_t Opcode,
2613                                           bool Immediate,
2614                                           bool HasSaturationOperand) {
2615   SDLoc Loc(N);
2616   SmallVector<SDValue, 8> Ops;
2617 
2618   // Two 32-bit halves of the value to be shifted
2619   Ops.push_back(N->getOperand(1));
2620   Ops.push_back(N->getOperand(2));
2621 
2622   // The shift count
2623   if (Immediate) {
2624     int32_t ImmValue = cast<ConstantSDNode>(N->getOperand(3))->getZExtValue();
2625     Ops.push_back(getI32Imm(ImmValue, Loc)); // immediate shift count
2626   } else {
2627     Ops.push_back(N->getOperand(3));
2628   }
2629 
2630   // The immediate saturation operand, if any
2631   if (HasSaturationOperand) {
2632     int32_t SatOp = cast<ConstantSDNode>(N->getOperand(4))->getZExtValue();
2633     int SatBit = (SatOp == 64 ? 0 : 1);
2634     Ops.push_back(getI32Imm(SatBit, Loc));
2635   }
2636 
2637   // MVE scalar shifts are IT-predicable, so include the standard
2638   // predicate arguments.
2639   Ops.push_back(getAL(CurDAG, Loc));
2640   Ops.push_back(CurDAG->getRegister(0, MVT::i32));
2641 
2642   CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), ArrayRef(Ops));
2643 }
2644 
2645 void ARMDAGToDAGISel::SelectMVE_VADCSBC(SDNode *N, uint16_t OpcodeWithCarry,
2646                                         uint16_t OpcodeWithNoCarry,
2647                                         bool Add, bool Predicated) {
2648   SDLoc Loc(N);
2649   SmallVector<SDValue, 8> Ops;
2650   uint16_t Opcode;
2651 
2652   unsigned FirstInputOp = Predicated ? 2 : 1;
2653 
2654   // Two input vectors and the input carry flag
2655   Ops.push_back(N->getOperand(FirstInputOp));
2656   Ops.push_back(N->getOperand(FirstInputOp + 1));
2657   SDValue CarryIn = N->getOperand(FirstInputOp + 2);
2658   ConstantSDNode *CarryInConstant = dyn_cast<ConstantSDNode>(CarryIn);
2659   uint32_t CarryMask = 1 << 29;
2660   uint32_t CarryExpected = Add ? 0 : CarryMask;
2661   if (CarryInConstant &&
2662       (CarryInConstant->getZExtValue() & CarryMask) == CarryExpected) {
2663     Opcode = OpcodeWithNoCarry;
2664   } else {
2665     Ops.push_back(CarryIn);
2666     Opcode = OpcodeWithCarry;
2667   }
2668 
2669   if (Predicated)
2670     AddMVEPredicateToOps(Ops, Loc,
2671                          N->getOperand(FirstInputOp + 3),  // predicate
2672                          N->getOperand(FirstInputOp - 1)); // inactive
2673   else
2674     AddEmptyMVEPredicateToOps(Ops, Loc, N->getValueType(0));
2675 
2676   CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), ArrayRef(Ops));
2677 }
2678 
2679 void ARMDAGToDAGISel::SelectMVE_VSHLC(SDNode *N, bool Predicated) {
2680   SDLoc Loc(N);
2681   SmallVector<SDValue, 8> Ops;
2682 
2683   // One vector input, followed by a 32-bit word of bits to shift in
2684   // and then an immediate shift count
2685   Ops.push_back(N->getOperand(1));
2686   Ops.push_back(N->getOperand(2));
2687   int32_t ImmValue = cast<ConstantSDNode>(N->getOperand(3))->getZExtValue();
2688   Ops.push_back(getI32Imm(ImmValue, Loc)); // immediate shift count
2689 
2690   if (Predicated)
2691     AddMVEPredicateToOps(Ops, Loc, N->getOperand(4));
2692   else
2693     AddEmptyMVEPredicateToOps(Ops, Loc);
2694 
2695   CurDAG->SelectNodeTo(N, ARM::MVE_VSHLC, N->getVTList(), ArrayRef(Ops));
2696 }
2697 
2698 static bool SDValueToConstBool(SDValue SDVal) {
2699   assert(isa<ConstantSDNode>(SDVal) && "expected a compile-time constant");
2700   ConstantSDNode *SDValConstant = dyn_cast<ConstantSDNode>(SDVal);
2701   uint64_t Value = SDValConstant->getZExtValue();
2702   assert((Value == 0 || Value == 1) && "expected value 0 or 1");
2703   return Value;
2704 }
2705 
2706 void ARMDAGToDAGISel::SelectBaseMVE_VMLLDAV(SDNode *N, bool Predicated,
2707                                             const uint16_t *OpcodesS,
2708                                             const uint16_t *OpcodesU,
2709                                             size_t Stride, size_t TySize) {
2710   assert(TySize < Stride && "Invalid TySize");
2711   bool IsUnsigned = SDValueToConstBool(N->getOperand(1));
2712   bool IsSub = SDValueToConstBool(N->getOperand(2));
2713   bool IsExchange = SDValueToConstBool(N->getOperand(3));
2714   if (IsUnsigned) {
2715     assert(!IsSub &&
2716            "Unsigned versions of vmlsldav[a]/vrmlsldavh[a] do not exist");
2717     assert(!IsExchange &&
2718            "Unsigned versions of vmlaldav[a]x/vrmlaldavh[a]x do not exist");
2719   }
2720 
2721   auto OpIsZero = [N](size_t OpNo) {
2722     return isNullConstant(N->getOperand(OpNo));
2723   };
2724 
2725   // If the input accumulator value is not zero, select an instruction with
2726   // accumulator, otherwise select an instruction without accumulator
2727   bool IsAccum = !(OpIsZero(4) && OpIsZero(5));
2728 
2729   const uint16_t *Opcodes = IsUnsigned ? OpcodesU : OpcodesS;
2730   if (IsSub)
2731     Opcodes += 4 * Stride;
2732   if (IsExchange)
2733     Opcodes += 2 * Stride;
2734   if (IsAccum)
2735     Opcodes += Stride;
2736   uint16_t Opcode = Opcodes[TySize];
2737 
2738   SDLoc Loc(N);
2739   SmallVector<SDValue, 8> Ops;
2740   // Push the accumulator operands, if they are used
2741   if (IsAccum) {
2742     Ops.push_back(N->getOperand(4));
2743     Ops.push_back(N->getOperand(5));
2744   }
2745   // Push the two vector operands
2746   Ops.push_back(N->getOperand(6));
2747   Ops.push_back(N->getOperand(7));
2748 
2749   if (Predicated)
2750     AddMVEPredicateToOps(Ops, Loc, N->getOperand(8));
2751   else
2752     AddEmptyMVEPredicateToOps(Ops, Loc);
2753 
2754   CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), ArrayRef(Ops));
2755 }
2756 
2757 void ARMDAGToDAGISel::SelectMVE_VMLLDAV(SDNode *N, bool Predicated,
2758                                         const uint16_t *OpcodesS,
2759                                         const uint16_t *OpcodesU) {
2760   EVT VecTy = N->getOperand(6).getValueType();
2761   size_t SizeIndex;
2762   switch (VecTy.getVectorElementType().getSizeInBits()) {
2763   case 16:
2764     SizeIndex = 0;
2765     break;
2766   case 32:
2767     SizeIndex = 1;
2768     break;
2769   default:
2770     llvm_unreachable("bad vector element size");
2771   }
2772 
2773   SelectBaseMVE_VMLLDAV(N, Predicated, OpcodesS, OpcodesU, 2, SizeIndex);
2774 }
2775 
2776 void ARMDAGToDAGISel::SelectMVE_VRMLLDAVH(SDNode *N, bool Predicated,
2777                                           const uint16_t *OpcodesS,
2778                                           const uint16_t *OpcodesU) {
2779   assert(
2780       N->getOperand(6).getValueType().getVectorElementType().getSizeInBits() ==
2781           32 &&
2782       "bad vector element size");
2783   SelectBaseMVE_VMLLDAV(N, Predicated, OpcodesS, OpcodesU, 1, 0);
2784 }
2785 
2786 void ARMDAGToDAGISel::SelectMVE_VLD(SDNode *N, unsigned NumVecs,
2787                                     const uint16_t *const *Opcodes,
2788                                     bool HasWriteback) {
2789   EVT VT = N->getValueType(0);
2790   SDLoc Loc(N);
2791 
2792   const uint16_t *OurOpcodes;
2793   switch (VT.getVectorElementType().getSizeInBits()) {
2794   case 8:
2795     OurOpcodes = Opcodes[0];
2796     break;
2797   case 16:
2798     OurOpcodes = Opcodes[1];
2799     break;
2800   case 32:
2801     OurOpcodes = Opcodes[2];
2802     break;
2803   default:
2804     llvm_unreachable("bad vector element size in SelectMVE_VLD");
2805   }
2806 
2807   EVT DataTy = EVT::getVectorVT(*CurDAG->getContext(), MVT::i64, NumVecs * 2);
2808   SmallVector<EVT, 4> ResultTys = {DataTy, MVT::Other};
2809   unsigned PtrOperand = HasWriteback ? 1 : 2;
2810 
2811   auto Data = SDValue(
2812       CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, Loc, DataTy), 0);
2813   SDValue Chain = N->getOperand(0);
2814   // Add a MVE_VLDn instruction for each Vec, except the last
2815   for (unsigned Stage = 0; Stage < NumVecs - 1; ++Stage) {
2816     SDValue Ops[] = {Data, N->getOperand(PtrOperand), Chain};
2817     auto LoadInst =
2818         CurDAG->getMachineNode(OurOpcodes[Stage], Loc, ResultTys, Ops);
2819     Data = SDValue(LoadInst, 0);
2820     Chain = SDValue(LoadInst, 1);
2821     transferMemOperands(N, LoadInst);
2822   }
2823   // The last may need a writeback on it
2824   if (HasWriteback)
2825     ResultTys = {DataTy, MVT::i32, MVT::Other};
2826   SDValue Ops[] = {Data, N->getOperand(PtrOperand), Chain};
2827   auto LoadInst =
2828       CurDAG->getMachineNode(OurOpcodes[NumVecs - 1], Loc, ResultTys, Ops);
2829   transferMemOperands(N, LoadInst);
2830 
2831   unsigned i;
2832   for (i = 0; i < NumVecs; i++)
2833     ReplaceUses(SDValue(N, i),
2834                 CurDAG->getTargetExtractSubreg(ARM::qsub_0 + i, Loc, VT,
2835                                                SDValue(LoadInst, 0)));
2836   if (HasWriteback)
2837     ReplaceUses(SDValue(N, i++), SDValue(LoadInst, 1));
2838   ReplaceUses(SDValue(N, i), SDValue(LoadInst, HasWriteback ? 2 : 1));
2839   CurDAG->RemoveDeadNode(N);
2840 }
2841 
2842 void ARMDAGToDAGISel::SelectMVE_VxDUP(SDNode *N, const uint16_t *Opcodes,
2843                                       bool Wrapping, bool Predicated) {
2844   EVT VT = N->getValueType(0);
2845   SDLoc Loc(N);
2846 
2847   uint16_t Opcode;
2848   switch (VT.getScalarSizeInBits()) {
2849   case 8:
2850     Opcode = Opcodes[0];
2851     break;
2852   case 16:
2853     Opcode = Opcodes[1];
2854     break;
2855   case 32:
2856     Opcode = Opcodes[2];
2857     break;
2858   default:
2859     llvm_unreachable("bad vector element size in SelectMVE_VxDUP");
2860   }
2861 
2862   SmallVector<SDValue, 8> Ops;
2863   unsigned OpIdx = 1;
2864 
2865   SDValue Inactive;
2866   if (Predicated)
2867     Inactive = N->getOperand(OpIdx++);
2868 
2869   Ops.push_back(N->getOperand(OpIdx++));     // base
2870   if (Wrapping)
2871     Ops.push_back(N->getOperand(OpIdx++));   // limit
2872 
2873   SDValue ImmOp = N->getOperand(OpIdx++);    // step
2874   int ImmValue = cast<ConstantSDNode>(ImmOp)->getZExtValue();
2875   Ops.push_back(getI32Imm(ImmValue, Loc));
2876 
2877   if (Predicated)
2878     AddMVEPredicateToOps(Ops, Loc, N->getOperand(OpIdx), Inactive);
2879   else
2880     AddEmptyMVEPredicateToOps(Ops, Loc, N->getValueType(0));
2881 
2882   CurDAG->SelectNodeTo(N, Opcode, N->getVTList(), ArrayRef(Ops));
2883 }
2884 
2885 void ARMDAGToDAGISel::SelectCDE_CXxD(SDNode *N, uint16_t Opcode,
2886                                      size_t NumExtraOps, bool HasAccum) {
2887   bool IsBigEndian = CurDAG->getDataLayout().isBigEndian();
2888   SDLoc Loc(N);
2889   SmallVector<SDValue, 8> Ops;
2890 
2891   unsigned OpIdx = 1;
2892 
2893   // Convert and append the immediate operand designating the coprocessor.
2894   SDValue ImmCorpoc = N->getOperand(OpIdx++);
2895   uint32_t ImmCoprocVal = cast<ConstantSDNode>(ImmCorpoc)->getZExtValue();
2896   Ops.push_back(getI32Imm(ImmCoprocVal, Loc));
2897 
2898   // For accumulating variants copy the low and high order parts of the
2899   // accumulator into a register pair and add it to the operand vector.
2900   if (HasAccum) {
2901     SDValue AccLo = N->getOperand(OpIdx++);
2902     SDValue AccHi = N->getOperand(OpIdx++);
2903     if (IsBigEndian)
2904       std::swap(AccLo, AccHi);
2905     Ops.push_back(SDValue(createGPRPairNode(MVT::Untyped, AccLo, AccHi), 0));
2906   }
2907 
2908   // Copy extra operands as-is.
2909   for (size_t I = 0; I < NumExtraOps; I++)
2910     Ops.push_back(N->getOperand(OpIdx++));
2911 
2912   // Convert and append the immediate operand
2913   SDValue Imm = N->getOperand(OpIdx);
2914   uint32_t ImmVal = cast<ConstantSDNode>(Imm)->getZExtValue();
2915   Ops.push_back(getI32Imm(ImmVal, Loc));
2916 
2917   // Accumulating variants are IT-predicable, add predicate operands.
2918   if (HasAccum) {
2919     SDValue Pred = getAL(CurDAG, Loc);
2920     SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
2921     Ops.push_back(Pred);
2922     Ops.push_back(PredReg);
2923   }
2924 
2925   // Create the CDE intruction
2926   SDNode *InstrNode = CurDAG->getMachineNode(Opcode, Loc, MVT::Untyped, Ops);
2927   SDValue ResultPair = SDValue(InstrNode, 0);
2928 
2929   // The original intrinsic had two outputs, and the output of the dual-register
2930   // CDE instruction is a register pair. We need to extract the two subregisters
2931   // and replace all uses of the original outputs with the extracted
2932   // subregisters.
2933   uint16_t SubRegs[2] = {ARM::gsub_0, ARM::gsub_1};
2934   if (IsBigEndian)
2935     std::swap(SubRegs[0], SubRegs[1]);
2936 
2937   for (size_t ResIdx = 0; ResIdx < 2; ResIdx++) {
2938     if (SDValue(N, ResIdx).use_empty())
2939       continue;
2940     SDValue SubReg = CurDAG->getTargetExtractSubreg(SubRegs[ResIdx], Loc,
2941                                                     MVT::i32, ResultPair);
2942     ReplaceUses(SDValue(N, ResIdx), SubReg);
2943   }
2944 
2945   CurDAG->RemoveDeadNode(N);
2946 }
2947 
2948 void ARMDAGToDAGISel::SelectVLDDup(SDNode *N, bool IsIntrinsic,
2949                                    bool isUpdating, unsigned NumVecs,
2950                                    const uint16_t *DOpcodes,
2951                                    const uint16_t *QOpcodes0,
2952                                    const uint16_t *QOpcodes1) {
2953   assert(Subtarget->hasNEON());
2954   assert(NumVecs >= 1 && NumVecs <= 4 && "VLDDup NumVecs out-of-range");
2955   SDLoc dl(N);
2956 
2957   SDValue MemAddr, Align;
2958   unsigned AddrOpIdx = IsIntrinsic ? 2 : 1;
2959   if (!SelectAddrMode6(N, N->getOperand(AddrOpIdx), MemAddr, Align))
2960     return;
2961 
2962   SDValue Chain = N->getOperand(0);
2963   EVT VT = N->getValueType(0);
2964   bool is64BitVector = VT.is64BitVector();
2965 
2966   unsigned Alignment = 0;
2967   if (NumVecs != 3) {
2968     Alignment = cast<ConstantSDNode>(Align)->getZExtValue();
2969     unsigned NumBytes = NumVecs * VT.getScalarSizeInBits() / 8;
2970     if (Alignment > NumBytes)
2971       Alignment = NumBytes;
2972     if (Alignment < 8 && Alignment < NumBytes)
2973       Alignment = 0;
2974     // Alignment must be a power of two; make sure of that.
2975     Alignment = (Alignment & -Alignment);
2976     if (Alignment == 1)
2977       Alignment = 0;
2978   }
2979   Align = CurDAG->getTargetConstant(Alignment, dl, MVT::i32);
2980 
2981   unsigned OpcodeIndex;
2982   switch (VT.getSimpleVT().SimpleTy) {
2983   default: llvm_unreachable("unhandled vld-dup type");
2984   case MVT::v8i8:
2985   case MVT::v16i8: OpcodeIndex = 0; break;
2986   case MVT::v4i16:
2987   case MVT::v8i16:
2988   case MVT::v4f16:
2989   case MVT::v8f16:
2990   case MVT::v4bf16:
2991   case MVT::v8bf16:
2992                   OpcodeIndex = 1; break;
2993   case MVT::v2f32:
2994   case MVT::v2i32:
2995   case MVT::v4f32:
2996   case MVT::v4i32: OpcodeIndex = 2; break;
2997   case MVT::v1f64:
2998   case MVT::v1i64: OpcodeIndex = 3; break;
2999   }
3000 
3001   unsigned ResTyElts = (NumVecs == 3) ? 4 : NumVecs;
3002   if (!is64BitVector)
3003     ResTyElts *= 2;
3004   EVT ResTy = EVT::getVectorVT(*CurDAG->getContext(), MVT::i64, ResTyElts);
3005 
3006   std::vector<EVT> ResTys;
3007   ResTys.push_back(ResTy);
3008   if (isUpdating)
3009     ResTys.push_back(MVT::i32);
3010   ResTys.push_back(MVT::Other);
3011 
3012   SDValue Pred = getAL(CurDAG, dl);
3013   SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3014 
3015   SmallVector<SDValue, 6> Ops;
3016   Ops.push_back(MemAddr);
3017   Ops.push_back(Align);
3018   unsigned Opc = is64BitVector    ? DOpcodes[OpcodeIndex]
3019                  : (NumVecs == 1) ? QOpcodes0[OpcodeIndex]
3020                                   : QOpcodes1[OpcodeIndex];
3021   if (isUpdating) {
3022     SDValue Inc = N->getOperand(2);
3023     bool IsImmUpdate =
3024         isPerfectIncrement(Inc, VT.getVectorElementType(), NumVecs);
3025     if (IsImmUpdate) {
3026       if (!isVLDfixed(Opc))
3027         Ops.push_back(Reg0);
3028     } else {
3029       if (isVLDfixed(Opc))
3030         Opc = getVLDSTRegisterUpdateOpcode(Opc);
3031       Ops.push_back(Inc);
3032     }
3033   }
3034   if (is64BitVector || NumVecs == 1) {
3035     // Double registers and VLD1 quad registers are directly supported.
3036   } else if (NumVecs == 2) {
3037     const SDValue OpsA[] = {MemAddr, Align, Pred, Reg0, Chain};
3038     SDNode *VLdA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex], dl, ResTy,
3039                                           MVT::Other, OpsA);
3040     Chain = SDValue(VLdA, 1);
3041   } else {
3042     SDValue ImplDef = SDValue(
3043         CurDAG->getMachineNode(TargetOpcode::IMPLICIT_DEF, dl, ResTy), 0);
3044     const SDValue OpsA[] = {MemAddr, Align, ImplDef, Pred, Reg0, Chain};
3045     SDNode *VLdA = CurDAG->getMachineNode(QOpcodes0[OpcodeIndex], dl, ResTy,
3046                                           MVT::Other, OpsA);
3047     Ops.push_back(SDValue(VLdA, 0));
3048     Chain = SDValue(VLdA, 1);
3049   }
3050 
3051   Ops.push_back(Pred);
3052   Ops.push_back(Reg0);
3053   Ops.push_back(Chain);
3054 
3055   SDNode *VLdDup = CurDAG->getMachineNode(Opc, dl, ResTys, Ops);
3056 
3057   // Transfer memoperands.
3058   MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
3059   CurDAG->setNodeMemRefs(cast<MachineSDNode>(VLdDup), {MemOp});
3060 
3061   // Extract the subregisters.
3062   if (NumVecs == 1) {
3063     ReplaceUses(SDValue(N, 0), SDValue(VLdDup, 0));
3064   } else {
3065     SDValue SuperReg = SDValue(VLdDup, 0);
3066     static_assert(ARM::dsub_7 == ARM::dsub_0 + 7, "Unexpected subreg numbering");
3067     unsigned SubIdx = is64BitVector ? ARM::dsub_0 : ARM::qsub_0;
3068     for (unsigned Vec = 0; Vec != NumVecs; ++Vec) {
3069       ReplaceUses(SDValue(N, Vec),
3070                   CurDAG->getTargetExtractSubreg(SubIdx+Vec, dl, VT, SuperReg));
3071     }
3072   }
3073   ReplaceUses(SDValue(N, NumVecs), SDValue(VLdDup, 1));
3074   if (isUpdating)
3075     ReplaceUses(SDValue(N, NumVecs + 1), SDValue(VLdDup, 2));
3076   CurDAG->RemoveDeadNode(N);
3077 }
3078 
3079 bool ARMDAGToDAGISel::tryInsertVectorElt(SDNode *N) {
3080   if (!Subtarget->hasMVEIntegerOps())
3081     return false;
3082 
3083   SDLoc dl(N);
3084 
3085   // We are trying to use VMOV/VMOVX/VINS to more efficiently lower insert and
3086   // extracts of v8f16 and v8i16 vectors. Check that we have two adjacent
3087   // inserts of the correct type:
3088   SDValue Ins1 = SDValue(N, 0);
3089   SDValue Ins2 = N->getOperand(0);
3090   EVT VT = Ins1.getValueType();
3091   if (Ins2.getOpcode() != ISD::INSERT_VECTOR_ELT || !Ins2.hasOneUse() ||
3092       !isa<ConstantSDNode>(Ins1.getOperand(2)) ||
3093       !isa<ConstantSDNode>(Ins2.getOperand(2)) ||
3094       (VT != MVT::v8f16 && VT != MVT::v8i16) || (Ins2.getValueType() != VT))
3095     return false;
3096 
3097   unsigned Lane1 = Ins1.getConstantOperandVal(2);
3098   unsigned Lane2 = Ins2.getConstantOperandVal(2);
3099   if (Lane2 % 2 != 0 || Lane1 != Lane2 + 1)
3100     return false;
3101 
3102   // If the inserted values will be able to use T/B already, leave it to the
3103   // existing tablegen patterns. For example VCVTT/VCVTB.
3104   SDValue Val1 = Ins1.getOperand(1);
3105   SDValue Val2 = Ins2.getOperand(1);
3106   if (Val1.getOpcode() == ISD::FP_ROUND || Val2.getOpcode() == ISD::FP_ROUND)
3107     return false;
3108 
3109   // Check if the inserted values are both extracts.
3110   if ((Val1.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
3111        Val1.getOpcode() == ARMISD::VGETLANEu) &&
3112       (Val2.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
3113        Val2.getOpcode() == ARMISD::VGETLANEu) &&
3114       isa<ConstantSDNode>(Val1.getOperand(1)) &&
3115       isa<ConstantSDNode>(Val2.getOperand(1)) &&
3116       (Val1.getOperand(0).getValueType() == MVT::v8f16 ||
3117        Val1.getOperand(0).getValueType() == MVT::v8i16) &&
3118       (Val2.getOperand(0).getValueType() == MVT::v8f16 ||
3119        Val2.getOperand(0).getValueType() == MVT::v8i16)) {
3120     unsigned ExtractLane1 = Val1.getConstantOperandVal(1);
3121     unsigned ExtractLane2 = Val2.getConstantOperandVal(1);
3122 
3123     // If the two extracted lanes are from the same place and adjacent, this
3124     // simplifies into a f32 lane move.
3125     if (Val1.getOperand(0) == Val2.getOperand(0) && ExtractLane2 % 2 == 0 &&
3126         ExtractLane1 == ExtractLane2 + 1) {
3127       SDValue NewExt = CurDAG->getTargetExtractSubreg(
3128           ARM::ssub_0 + ExtractLane2 / 2, dl, MVT::f32, Val1.getOperand(0));
3129       SDValue NewIns = CurDAG->getTargetInsertSubreg(
3130           ARM::ssub_0 + Lane2 / 2, dl, VT, Ins2.getOperand(0),
3131           NewExt);
3132       ReplaceUses(Ins1, NewIns);
3133       return true;
3134     }
3135 
3136     // Else v8i16 pattern of an extract and an insert, with a optional vmovx for
3137     // extracting odd lanes.
3138     if (VT == MVT::v8i16 && Subtarget->hasFullFP16()) {
3139       SDValue Inp1 = CurDAG->getTargetExtractSubreg(
3140           ARM::ssub_0 + ExtractLane1 / 2, dl, MVT::f32, Val1.getOperand(0));
3141       SDValue Inp2 = CurDAG->getTargetExtractSubreg(
3142           ARM::ssub_0 + ExtractLane2 / 2, dl, MVT::f32, Val2.getOperand(0));
3143       if (ExtractLane1 % 2 != 0)
3144         Inp1 = SDValue(CurDAG->getMachineNode(ARM::VMOVH, dl, MVT::f32, Inp1), 0);
3145       if (ExtractLane2 % 2 != 0)
3146         Inp2 = SDValue(CurDAG->getMachineNode(ARM::VMOVH, dl, MVT::f32, Inp2), 0);
3147       SDNode *VINS = CurDAG->getMachineNode(ARM::VINSH, dl, MVT::f32, Inp2, Inp1);
3148       SDValue NewIns =
3149           CurDAG->getTargetInsertSubreg(ARM::ssub_0 + Lane2 / 2, dl, MVT::v4f32,
3150                                         Ins2.getOperand(0), SDValue(VINS, 0));
3151       ReplaceUses(Ins1, NewIns);
3152       return true;
3153     }
3154   }
3155 
3156   // The inserted values are not extracted - if they are f16 then insert them
3157   // directly using a VINS.
3158   if (VT == MVT::v8f16 && Subtarget->hasFullFP16()) {
3159     SDNode *VINS = CurDAG->getMachineNode(ARM::VINSH, dl, MVT::f32, Val2, Val1);
3160     SDValue NewIns =
3161         CurDAG->getTargetInsertSubreg(ARM::ssub_0 + Lane2 / 2, dl, MVT::v4f32,
3162                                       Ins2.getOperand(0), SDValue(VINS, 0));
3163     ReplaceUses(Ins1, NewIns);
3164     return true;
3165   }
3166 
3167   return false;
3168 }
3169 
3170 bool ARMDAGToDAGISel::transformFixedFloatingPointConversion(SDNode *N,
3171                                                             SDNode *FMul,
3172                                                             bool IsUnsigned,
3173                                                             bool FixedToFloat) {
3174   auto Type = N->getValueType(0);
3175   unsigned ScalarBits = Type.getScalarSizeInBits();
3176   if (ScalarBits > 32)
3177     return false;
3178 
3179   SDNodeFlags FMulFlags = FMul->getFlags();
3180   // The fixed-point vcvt and vcvt+vmul are not always equivalent if inf is
3181   // allowed in 16 bit unsigned floats
3182   if (ScalarBits == 16 && !FMulFlags.hasNoInfs() && IsUnsigned)
3183     return false;
3184 
3185   SDValue ImmNode = FMul->getOperand(1);
3186   SDValue VecVal = FMul->getOperand(0);
3187   if (VecVal->getOpcode() == ISD::UINT_TO_FP ||
3188       VecVal->getOpcode() == ISD::SINT_TO_FP)
3189     VecVal = VecVal->getOperand(0);
3190 
3191   if (VecVal.getValueType().getScalarSizeInBits() != ScalarBits)
3192     return false;
3193 
3194   if (ImmNode.getOpcode() == ISD::BITCAST) {
3195     if (ImmNode.getValueType().getScalarSizeInBits() != ScalarBits)
3196       return false;
3197     ImmNode = ImmNode.getOperand(0);
3198   }
3199 
3200   if (ImmNode.getValueType().getScalarSizeInBits() != ScalarBits)
3201     return false;
3202 
3203   APFloat ImmAPF(0.0f);
3204   switch (ImmNode.getOpcode()) {
3205   case ARMISD::VMOVIMM:
3206   case ARMISD::VDUP: {
3207     if (!isa<ConstantSDNode>(ImmNode.getOperand(0)))
3208       return false;
3209     unsigned Imm = ImmNode.getConstantOperandVal(0);
3210     if (ImmNode.getOpcode() == ARMISD::VMOVIMM)
3211       Imm = ARM_AM::decodeVMOVModImm(Imm, ScalarBits);
3212     ImmAPF =
3213         APFloat(ScalarBits == 32 ? APFloat::IEEEsingle() : APFloat::IEEEhalf(),
3214                 APInt(ScalarBits, Imm));
3215     break;
3216   }
3217   case ARMISD::VMOVFPIMM: {
3218     ImmAPF = APFloat(ARM_AM::getFPImmFloat(ImmNode.getConstantOperandVal(0)));
3219     break;
3220   }
3221   default:
3222     return false;
3223   }
3224 
3225   // Where n is the number of fractional bits, multiplying by 2^n will convert
3226   // from float to fixed and multiplying by 2^-n will convert from fixed to
3227   // float. Taking log2 of the factor (after taking the inverse in the case of
3228   // float to fixed) will give n.
3229   APFloat ToConvert = ImmAPF;
3230   if (FixedToFloat) {
3231     if (!ImmAPF.getExactInverse(&ToConvert))
3232       return false;
3233   }
3234   APSInt Converted(64, false);
3235   bool IsExact;
3236   ToConvert.convertToInteger(Converted, llvm::RoundingMode::NearestTiesToEven,
3237                              &IsExact);
3238   if (!IsExact || !Converted.isPowerOf2())
3239     return false;
3240 
3241   unsigned FracBits = Converted.logBase2();
3242   if (FracBits > ScalarBits)
3243     return false;
3244 
3245   SmallVector<SDValue, 3> Ops{
3246       VecVal, CurDAG->getConstant(FracBits, SDLoc(N), MVT::i32)};
3247   AddEmptyMVEPredicateToOps(Ops, SDLoc(N), Type);
3248 
3249   unsigned int Opcode;
3250   switch (ScalarBits) {
3251   case 16:
3252     if (FixedToFloat)
3253       Opcode = IsUnsigned ? ARM::MVE_VCVTf16u16_fix : ARM::MVE_VCVTf16s16_fix;
3254     else
3255       Opcode = IsUnsigned ? ARM::MVE_VCVTu16f16_fix : ARM::MVE_VCVTs16f16_fix;
3256     break;
3257   case 32:
3258     if (FixedToFloat)
3259       Opcode = IsUnsigned ? ARM::MVE_VCVTf32u32_fix : ARM::MVE_VCVTf32s32_fix;
3260     else
3261       Opcode = IsUnsigned ? ARM::MVE_VCVTu32f32_fix : ARM::MVE_VCVTs32f32_fix;
3262     break;
3263   default:
3264     llvm_unreachable("unexpected number of scalar bits");
3265     break;
3266   }
3267 
3268   ReplaceNode(N, CurDAG->getMachineNode(Opcode, SDLoc(N), Type, Ops));
3269   return true;
3270 }
3271 
3272 bool ARMDAGToDAGISel::tryFP_TO_INT(SDNode *N, SDLoc dl) {
3273   // Transform a floating-point to fixed-point conversion to a VCVT
3274   if (!Subtarget->hasMVEFloatOps())
3275     return false;
3276   EVT Type = N->getValueType(0);
3277   if (!Type.isVector())
3278     return false;
3279   unsigned int ScalarBits = Type.getScalarSizeInBits();
3280 
3281   bool IsUnsigned = N->getOpcode() == ISD::FP_TO_UINT ||
3282                     N->getOpcode() == ISD::FP_TO_UINT_SAT;
3283   SDNode *Node = N->getOperand(0).getNode();
3284 
3285   // floating-point to fixed-point with one fractional bit gets turned into an
3286   // FP_TO_[U|S]INT(FADD (x, x)) rather than an FP_TO_[U|S]INT(FMUL (x, y))
3287   if (Node->getOpcode() == ISD::FADD) {
3288     if (Node->getOperand(0) != Node->getOperand(1))
3289       return false;
3290     SDNodeFlags Flags = Node->getFlags();
3291     // The fixed-point vcvt and vcvt+vmul are not always equivalent if inf is
3292     // allowed in 16 bit unsigned floats
3293     if (ScalarBits == 16 && !Flags.hasNoInfs() && IsUnsigned)
3294       return false;
3295 
3296     unsigned Opcode;
3297     switch (ScalarBits) {
3298     case 16:
3299       Opcode = IsUnsigned ? ARM::MVE_VCVTu16f16_fix : ARM::MVE_VCVTs16f16_fix;
3300       break;
3301     case 32:
3302       Opcode = IsUnsigned ? ARM::MVE_VCVTu32f32_fix : ARM::MVE_VCVTs32f32_fix;
3303       break;
3304     }
3305     SmallVector<SDValue, 3> Ops{Node->getOperand(0),
3306                                 CurDAG->getConstant(1, dl, MVT::i32)};
3307     AddEmptyMVEPredicateToOps(Ops, dl, Type);
3308 
3309     ReplaceNode(N, CurDAG->getMachineNode(Opcode, dl, Type, Ops));
3310     return true;
3311   }
3312 
3313   if (Node->getOpcode() != ISD::FMUL)
3314     return false;
3315 
3316   return transformFixedFloatingPointConversion(N, Node, IsUnsigned, false);
3317 }
3318 
3319 bool ARMDAGToDAGISel::tryFMULFixed(SDNode *N, SDLoc dl) {
3320   // Transform a fixed-point to floating-point conversion to a VCVT
3321   if (!Subtarget->hasMVEFloatOps())
3322     return false;
3323   auto Type = N->getValueType(0);
3324   if (!Type.isVector())
3325     return false;
3326 
3327   auto LHS = N->getOperand(0);
3328   if (LHS.getOpcode() != ISD::SINT_TO_FP && LHS.getOpcode() != ISD::UINT_TO_FP)
3329     return false;
3330 
3331   return transformFixedFloatingPointConversion(
3332       N, N, LHS.getOpcode() == ISD::UINT_TO_FP, true);
3333 }
3334 
3335 bool ARMDAGToDAGISel::tryV6T2BitfieldExtractOp(SDNode *N, bool isSigned) {
3336   if (!Subtarget->hasV6T2Ops())
3337     return false;
3338 
3339   unsigned Opc = isSigned
3340     ? (Subtarget->isThumb() ? ARM::t2SBFX : ARM::SBFX)
3341     : (Subtarget->isThumb() ? ARM::t2UBFX : ARM::UBFX);
3342   SDLoc dl(N);
3343 
3344   // For unsigned extracts, check for a shift right and mask
3345   unsigned And_imm = 0;
3346   if (N->getOpcode() == ISD::AND) {
3347     if (isOpcWithIntImmediate(N, ISD::AND, And_imm)) {
3348 
3349       // The immediate is a mask of the low bits iff imm & (imm+1) == 0
3350       if (And_imm & (And_imm + 1))
3351         return false;
3352 
3353       unsigned Srl_imm = 0;
3354       if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SRL,
3355                                 Srl_imm)) {
3356         assert(Srl_imm > 0 && Srl_imm < 32 && "bad amount in shift node!");
3357 
3358         // Mask off the unnecessary bits of the AND immediate; normally
3359         // DAGCombine will do this, but that might not happen if
3360         // targetShrinkDemandedConstant chooses a different immediate.
3361         And_imm &= -1U >> Srl_imm;
3362 
3363         // Note: The width operand is encoded as width-1.
3364         unsigned Width = llvm::countr_one(And_imm) - 1;
3365         unsigned LSB = Srl_imm;
3366 
3367         SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3368 
3369         if ((LSB + Width + 1) == N->getValueType(0).getSizeInBits()) {
3370           // It's cheaper to use a right shift to extract the top bits.
3371           if (Subtarget->isThumb()) {
3372             Opc = isSigned ? ARM::t2ASRri : ARM::t2LSRri;
3373             SDValue Ops[] = { N->getOperand(0).getOperand(0),
3374                               CurDAG->getTargetConstant(LSB, dl, MVT::i32),
3375                               getAL(CurDAG, dl), Reg0, Reg0 };
3376             CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
3377             return true;
3378           }
3379 
3380           // ARM models shift instructions as MOVsi with shifter operand.
3381           ARM_AM::ShiftOpc ShOpcVal = ARM_AM::getShiftOpcForNode(ISD::SRL);
3382           SDValue ShOpc =
3383             CurDAG->getTargetConstant(ARM_AM::getSORegOpc(ShOpcVal, LSB), dl,
3384                                       MVT::i32);
3385           SDValue Ops[] = { N->getOperand(0).getOperand(0), ShOpc,
3386                             getAL(CurDAG, dl), Reg0, Reg0 };
3387           CurDAG->SelectNodeTo(N, ARM::MOVsi, MVT::i32, Ops);
3388           return true;
3389         }
3390 
3391         assert(LSB + Width + 1 <= 32 && "Shouldn't create an invalid ubfx");
3392         SDValue Ops[] = { N->getOperand(0).getOperand(0),
3393                           CurDAG->getTargetConstant(LSB, dl, MVT::i32),
3394                           CurDAG->getTargetConstant(Width, dl, MVT::i32),
3395                           getAL(CurDAG, dl), Reg0 };
3396         CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
3397         return true;
3398       }
3399     }
3400     return false;
3401   }
3402 
3403   // Otherwise, we're looking for a shift of a shift
3404   unsigned Shl_imm = 0;
3405   if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SHL, Shl_imm)) {
3406     assert(Shl_imm > 0 && Shl_imm < 32 && "bad amount in shift node!");
3407     unsigned Srl_imm = 0;
3408     if (isInt32Immediate(N->getOperand(1), Srl_imm)) {
3409       assert(Srl_imm > 0 && Srl_imm < 32 && "bad amount in shift node!");
3410       // Note: The width operand is encoded as width-1.
3411       unsigned Width = 32 - Srl_imm - 1;
3412       int LSB = Srl_imm - Shl_imm;
3413       if (LSB < 0)
3414         return false;
3415       SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3416       assert(LSB + Width + 1 <= 32 && "Shouldn't create an invalid ubfx");
3417       SDValue Ops[] = { N->getOperand(0).getOperand(0),
3418                         CurDAG->getTargetConstant(LSB, dl, MVT::i32),
3419                         CurDAG->getTargetConstant(Width, dl, MVT::i32),
3420                         getAL(CurDAG, dl), Reg0 };
3421       CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
3422       return true;
3423     }
3424   }
3425 
3426   // Or we are looking for a shift of an and, with a mask operand
3427   if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, And_imm) &&
3428       isShiftedMask_32(And_imm)) {
3429     unsigned Srl_imm = 0;
3430     unsigned LSB = llvm::countr_zero(And_imm);
3431     // Shift must be the same as the ands lsb
3432     if (isInt32Immediate(N->getOperand(1), Srl_imm) && Srl_imm == LSB) {
3433       assert(Srl_imm > 0 && Srl_imm < 32 && "bad amount in shift node!");
3434       unsigned MSB = llvm::Log2_32(And_imm);
3435       // Note: The width operand is encoded as width-1.
3436       unsigned Width = MSB - LSB;
3437       SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3438       assert(Srl_imm + Width + 1 <= 32 && "Shouldn't create an invalid ubfx");
3439       SDValue Ops[] = { N->getOperand(0).getOperand(0),
3440                         CurDAG->getTargetConstant(Srl_imm, dl, MVT::i32),
3441                         CurDAG->getTargetConstant(Width, dl, MVT::i32),
3442                         getAL(CurDAG, dl), Reg0 };
3443       CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
3444       return true;
3445     }
3446   }
3447 
3448   if (N->getOpcode() == ISD::SIGN_EXTEND_INREG) {
3449     unsigned Width = cast<VTSDNode>(N->getOperand(1))->getVT().getSizeInBits();
3450     unsigned LSB = 0;
3451     if (!isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SRL, LSB) &&
3452         !isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::SRA, LSB))
3453       return false;
3454 
3455     if (LSB + Width > 32)
3456       return false;
3457 
3458     SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3459     assert(LSB + Width <= 32 && "Shouldn't create an invalid ubfx");
3460     SDValue Ops[] = { N->getOperand(0).getOperand(0),
3461                       CurDAG->getTargetConstant(LSB, dl, MVT::i32),
3462                       CurDAG->getTargetConstant(Width - 1, dl, MVT::i32),
3463                       getAL(CurDAG, dl), Reg0 };
3464     CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
3465     return true;
3466   }
3467 
3468   return false;
3469 }
3470 
3471 /// Target-specific DAG combining for ISD::SUB.
3472 /// Target-independent combining lowers SELECT_CC nodes of the form
3473 /// select_cc setg[ge] X,  0,  X, -X
3474 /// select_cc setgt    X, -1,  X, -X
3475 /// select_cc setl[te] X,  0, -X,  X
3476 /// select_cc setlt    X,  1, -X,  X
3477 /// which represent Integer ABS into:
3478 /// Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
3479 /// ARM instruction selection detects the latter and matches it to
3480 /// ARM::ABS or ARM::t2ABS machine node.
3481 bool ARMDAGToDAGISel::tryABSOp(SDNode *N){
3482   SDValue SUBSrc0 = N->getOperand(0);
3483   SDValue SUBSrc1 = N->getOperand(1);
3484   EVT VT = N->getValueType(0);
3485 
3486   if (Subtarget->isThumb1Only())
3487     return false;
3488 
3489   if (SUBSrc0.getOpcode() != ISD::XOR || SUBSrc1.getOpcode() != ISD::SRA)
3490     return false;
3491 
3492   SDValue XORSrc0 = SUBSrc0.getOperand(0);
3493   SDValue XORSrc1 = SUBSrc0.getOperand(1);
3494   SDValue SRASrc0 = SUBSrc1.getOperand(0);
3495   SDValue SRASrc1 = SUBSrc1.getOperand(1);
3496   ConstantSDNode *SRAConstant =  dyn_cast<ConstantSDNode>(SRASrc1);
3497   EVT XType = SRASrc0.getValueType();
3498   unsigned Size = XType.getSizeInBits() - 1;
3499 
3500   if (XORSrc1 == SUBSrc1 && XORSrc0 == SRASrc0 && XType.isInteger() &&
3501       SRAConstant != nullptr && Size == SRAConstant->getZExtValue()) {
3502     unsigned Opcode = Subtarget->isThumb2() ? ARM::t2ABS : ARM::ABS;
3503     CurDAG->SelectNodeTo(N, Opcode, VT, XORSrc0);
3504     return true;
3505   }
3506 
3507   return false;
3508 }
3509 
3510 /// We've got special pseudo-instructions for these
3511 void ARMDAGToDAGISel::SelectCMP_SWAP(SDNode *N) {
3512   unsigned Opcode;
3513   EVT MemTy = cast<MemSDNode>(N)->getMemoryVT();
3514   if (MemTy == MVT::i8)
3515     Opcode = Subtarget->isThumb() ? ARM::tCMP_SWAP_8 : ARM::CMP_SWAP_8;
3516   else if (MemTy == MVT::i16)
3517     Opcode = Subtarget->isThumb() ? ARM::tCMP_SWAP_16 : ARM::CMP_SWAP_16;
3518   else if (MemTy == MVT::i32)
3519     Opcode = Subtarget->isThumb() ? ARM::tCMP_SWAP_32 : ARM::CMP_SWAP_32;
3520   else
3521     llvm_unreachable("Unknown AtomicCmpSwap type");
3522 
3523   SDValue Ops[] = {N->getOperand(1), N->getOperand(2), N->getOperand(3),
3524                    N->getOperand(0)};
3525   SDNode *CmpSwap = CurDAG->getMachineNode(
3526       Opcode, SDLoc(N),
3527       CurDAG->getVTList(MVT::i32, MVT::i32, MVT::Other), Ops);
3528 
3529   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
3530   CurDAG->setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
3531 
3532   ReplaceUses(SDValue(N, 0), SDValue(CmpSwap, 0));
3533   ReplaceUses(SDValue(N, 1), SDValue(CmpSwap, 2));
3534   CurDAG->RemoveDeadNode(N);
3535 }
3536 
3537 static std::optional<std::pair<unsigned, unsigned>>
3538 getContiguousRangeOfSetBits(const APInt &A) {
3539   unsigned FirstOne = A.getBitWidth() - A.countl_zero() - 1;
3540   unsigned LastOne = A.countr_zero();
3541   if (A.popcount() != (FirstOne - LastOne + 1))
3542     return std::nullopt;
3543   return std::make_pair(FirstOne, LastOne);
3544 }
3545 
3546 void ARMDAGToDAGISel::SelectCMPZ(SDNode *N, bool &SwitchEQNEToPLMI) {
3547   assert(N->getOpcode() == ARMISD::CMPZ);
3548   SwitchEQNEToPLMI = false;
3549 
3550   if (!Subtarget->isThumb())
3551     // FIXME: Work out whether it is profitable to do this in A32 mode - LSL and
3552     // LSR don't exist as standalone instructions - they need the barrel shifter.
3553     return;
3554 
3555   // select (cmpz (and X, C), #0) -> (LSLS X) or (LSRS X) or (LSRS (LSLS X))
3556   SDValue And = N->getOperand(0);
3557   if (!And->hasOneUse())
3558     return;
3559 
3560   SDValue Zero = N->getOperand(1);
3561   if (!isNullConstant(Zero) || And->getOpcode() != ISD::AND)
3562     return;
3563   SDValue X = And.getOperand(0);
3564   auto C = dyn_cast<ConstantSDNode>(And.getOperand(1));
3565 
3566   if (!C)
3567     return;
3568   auto Range = getContiguousRangeOfSetBits(C->getAPIntValue());
3569   if (!Range)
3570     return;
3571 
3572   // There are several ways to lower this:
3573   SDNode *NewN;
3574   SDLoc dl(N);
3575 
3576   auto EmitShift = [&](unsigned Opc, SDValue Src, unsigned Imm) -> SDNode* {
3577     if (Subtarget->isThumb2()) {
3578       Opc = (Opc == ARM::tLSLri) ? ARM::t2LSLri : ARM::t2LSRri;
3579       SDValue Ops[] = { Src, CurDAG->getTargetConstant(Imm, dl, MVT::i32),
3580                         getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32),
3581                         CurDAG->getRegister(0, MVT::i32) };
3582       return CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops);
3583     } else {
3584       SDValue Ops[] = {CurDAG->getRegister(ARM::CPSR, MVT::i32), Src,
3585                        CurDAG->getTargetConstant(Imm, dl, MVT::i32),
3586                        getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32)};
3587       return CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops);
3588     }
3589   };
3590 
3591   if (Range->second == 0) {
3592     //  1. Mask includes the LSB -> Simply shift the top N bits off
3593     NewN = EmitShift(ARM::tLSLri, X, 31 - Range->first);
3594     ReplaceNode(And.getNode(), NewN);
3595   } else if (Range->first == 31) {
3596     //  2. Mask includes the MSB -> Simply shift the bottom N bits off
3597     NewN = EmitShift(ARM::tLSRri, X, Range->second);
3598     ReplaceNode(And.getNode(), NewN);
3599   } else if (Range->first == Range->second) {
3600     //  3. Only one bit is set. We can shift this into the sign bit and use a
3601     //     PL/MI comparison.
3602     NewN = EmitShift(ARM::tLSLri, X, 31 - Range->first);
3603     ReplaceNode(And.getNode(), NewN);
3604 
3605     SwitchEQNEToPLMI = true;
3606   } else if (!Subtarget->hasV6T2Ops()) {
3607     //  4. Do a double shift to clear bottom and top bits, but only in
3608     //     thumb-1 mode as in thumb-2 we can use UBFX.
3609     NewN = EmitShift(ARM::tLSLri, X, 31 - Range->first);
3610     NewN = EmitShift(ARM::tLSRri, SDValue(NewN, 0),
3611                      Range->second + (31 - Range->first));
3612     ReplaceNode(And.getNode(), NewN);
3613   }
3614 }
3615 
3616 static unsigned getVectorShuffleOpcode(EVT VT, unsigned Opc64[3],
3617                                        unsigned Opc128[3]) {
3618   assert((VT.is64BitVector() || VT.is128BitVector()) &&
3619          "Unexpected vector shuffle length");
3620   switch (VT.getScalarSizeInBits()) {
3621   default:
3622     llvm_unreachable("Unexpected vector shuffle element size");
3623   case 8:
3624     return VT.is64BitVector() ? Opc64[0] : Opc128[0];
3625   case 16:
3626     return VT.is64BitVector() ? Opc64[1] : Opc128[1];
3627   case 32:
3628     return VT.is64BitVector() ? Opc64[2] : Opc128[2];
3629   }
3630 }
3631 
3632 void ARMDAGToDAGISel::Select(SDNode *N) {
3633   SDLoc dl(N);
3634 
3635   if (N->isMachineOpcode()) {
3636     N->setNodeId(-1);
3637     return;   // Already selected.
3638   }
3639 
3640   switch (N->getOpcode()) {
3641   default: break;
3642   case ISD::STORE: {
3643     // For Thumb1, match an sp-relative store in C++. This is a little
3644     // unfortunate, but I don't think I can make the chain check work
3645     // otherwise.  (The chain of the store has to be the same as the chain
3646     // of the CopyFromReg, or else we can't replace the CopyFromReg with
3647     // a direct reference to "SP".)
3648     //
3649     // This is only necessary on Thumb1 because Thumb1 sp-relative stores use
3650     // a different addressing mode from other four-byte stores.
3651     //
3652     // This pattern usually comes up with call arguments.
3653     StoreSDNode *ST = cast<StoreSDNode>(N);
3654     SDValue Ptr = ST->getBasePtr();
3655     if (Subtarget->isThumb1Only() && ST->isUnindexed()) {
3656       int RHSC = 0;
3657       if (Ptr.getOpcode() == ISD::ADD &&
3658           isScaledConstantInRange(Ptr.getOperand(1), /*Scale=*/4, 0, 256, RHSC))
3659         Ptr = Ptr.getOperand(0);
3660 
3661       if (Ptr.getOpcode() == ISD::CopyFromReg &&
3662           cast<RegisterSDNode>(Ptr.getOperand(1))->getReg() == ARM::SP &&
3663           Ptr.getOperand(0) == ST->getChain()) {
3664         SDValue Ops[] = {ST->getValue(),
3665                          CurDAG->getRegister(ARM::SP, MVT::i32),
3666                          CurDAG->getTargetConstant(RHSC, dl, MVT::i32),
3667                          getAL(CurDAG, dl),
3668                          CurDAG->getRegister(0, MVT::i32),
3669                          ST->getChain()};
3670         MachineSDNode *ResNode =
3671             CurDAG->getMachineNode(ARM::tSTRspi, dl, MVT::Other, Ops);
3672         MachineMemOperand *MemOp = ST->getMemOperand();
3673         CurDAG->setNodeMemRefs(cast<MachineSDNode>(ResNode), {MemOp});
3674         ReplaceNode(N, ResNode);
3675         return;
3676       }
3677     }
3678     break;
3679   }
3680   case ISD::WRITE_REGISTER:
3681     if (tryWriteRegister(N))
3682       return;
3683     break;
3684   case ISD::READ_REGISTER:
3685     if (tryReadRegister(N))
3686       return;
3687     break;
3688   case ISD::INLINEASM:
3689   case ISD::INLINEASM_BR:
3690     if (tryInlineAsm(N))
3691       return;
3692     break;
3693   case ISD::SUB:
3694     // Select special operations if SUB node forms integer ABS pattern
3695     if (tryABSOp(N))
3696       return;
3697     // Other cases are autogenerated.
3698     break;
3699   case ISD::Constant: {
3700     unsigned Val = cast<ConstantSDNode>(N)->getZExtValue();
3701     // If we can't materialize the constant we need to use a literal pool
3702     if (ConstantMaterializationCost(Val, Subtarget) > 2 &&
3703         !Subtarget->genExecuteOnly()) {
3704       SDValue CPIdx = CurDAG->getTargetConstantPool(
3705           ConstantInt::get(Type::getInt32Ty(*CurDAG->getContext()), Val),
3706           TLI->getPointerTy(CurDAG->getDataLayout()));
3707 
3708       SDNode *ResNode;
3709       if (Subtarget->isThumb()) {
3710         SDValue Ops[] = {
3711           CPIdx,
3712           getAL(CurDAG, dl),
3713           CurDAG->getRegister(0, MVT::i32),
3714           CurDAG->getEntryNode()
3715         };
3716         ResNode = CurDAG->getMachineNode(ARM::tLDRpci, dl, MVT::i32, MVT::Other,
3717                                          Ops);
3718       } else {
3719         SDValue Ops[] = {
3720           CPIdx,
3721           CurDAG->getTargetConstant(0, dl, MVT::i32),
3722           getAL(CurDAG, dl),
3723           CurDAG->getRegister(0, MVT::i32),
3724           CurDAG->getEntryNode()
3725         };
3726         ResNode = CurDAG->getMachineNode(ARM::LDRcp, dl, MVT::i32, MVT::Other,
3727                                          Ops);
3728       }
3729       // Annotate the Node with memory operand information so that MachineInstr
3730       // queries work properly. This e.g. gives the register allocation the
3731       // required information for rematerialization.
3732       MachineFunction& MF = CurDAG->getMachineFunction();
3733       MachineMemOperand *MemOp =
3734           MF.getMachineMemOperand(MachinePointerInfo::getConstantPool(MF),
3735                                   MachineMemOperand::MOLoad, 4, Align(4));
3736 
3737       CurDAG->setNodeMemRefs(cast<MachineSDNode>(ResNode), {MemOp});
3738 
3739       ReplaceNode(N, ResNode);
3740       return;
3741     }
3742 
3743     // Other cases are autogenerated.
3744     break;
3745   }
3746   case ISD::FrameIndex: {
3747     // Selects to ADDri FI, 0 which in turn will become ADDri SP, imm.
3748     int FI = cast<FrameIndexSDNode>(N)->getIndex();
3749     SDValue TFI = CurDAG->getTargetFrameIndex(
3750         FI, TLI->getPointerTy(CurDAG->getDataLayout()));
3751     if (Subtarget->isThumb1Only()) {
3752       // Set the alignment of the frame object to 4, to avoid having to generate
3753       // more than one ADD
3754       MachineFrameInfo &MFI = MF->getFrameInfo();
3755       if (MFI.getObjectAlign(FI) < Align(4))
3756         MFI.setObjectAlignment(FI, Align(4));
3757       CurDAG->SelectNodeTo(N, ARM::tADDframe, MVT::i32, TFI,
3758                            CurDAG->getTargetConstant(0, dl, MVT::i32));
3759       return;
3760     } else {
3761       unsigned Opc = ((Subtarget->isThumb() && Subtarget->hasThumb2()) ?
3762                       ARM::t2ADDri : ARM::ADDri);
3763       SDValue Ops[] = { TFI, CurDAG->getTargetConstant(0, dl, MVT::i32),
3764                         getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32),
3765                         CurDAG->getRegister(0, MVT::i32) };
3766       CurDAG->SelectNodeTo(N, Opc, MVT::i32, Ops);
3767       return;
3768     }
3769   }
3770   case ISD::INSERT_VECTOR_ELT: {
3771     if (tryInsertVectorElt(N))
3772       return;
3773     break;
3774   }
3775   case ISD::SRL:
3776     if (tryV6T2BitfieldExtractOp(N, false))
3777       return;
3778     break;
3779   case ISD::SIGN_EXTEND_INREG:
3780   case ISD::SRA:
3781     if (tryV6T2BitfieldExtractOp(N, true))
3782       return;
3783     break;
3784   case ISD::FP_TO_UINT:
3785   case ISD::FP_TO_SINT:
3786   case ISD::FP_TO_UINT_SAT:
3787   case ISD::FP_TO_SINT_SAT:
3788     if (tryFP_TO_INT(N, dl))
3789       return;
3790     break;
3791   case ISD::FMUL:
3792     if (tryFMULFixed(N, dl))
3793       return;
3794     break;
3795   case ISD::MUL:
3796     if (Subtarget->isThumb1Only())
3797       break;
3798     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
3799       unsigned RHSV = C->getZExtValue();
3800       if (!RHSV) break;
3801       if (isPowerOf2_32(RHSV-1)) {  // 2^n+1?
3802         unsigned ShImm = Log2_32(RHSV-1);
3803         if (ShImm >= 32)
3804           break;
3805         SDValue V = N->getOperand(0);
3806         ShImm = ARM_AM::getSORegOpc(ARM_AM::lsl, ShImm);
3807         SDValue ShImmOp = CurDAG->getTargetConstant(ShImm, dl, MVT::i32);
3808         SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3809         if (Subtarget->isThumb()) {
3810           SDValue Ops[] = { V, V, ShImmOp, getAL(CurDAG, dl), Reg0, Reg0 };
3811           CurDAG->SelectNodeTo(N, ARM::t2ADDrs, MVT::i32, Ops);
3812           return;
3813         } else {
3814           SDValue Ops[] = { V, V, Reg0, ShImmOp, getAL(CurDAG, dl), Reg0,
3815                             Reg0 };
3816           CurDAG->SelectNodeTo(N, ARM::ADDrsi, MVT::i32, Ops);
3817           return;
3818         }
3819       }
3820       if (isPowerOf2_32(RHSV+1)) {  // 2^n-1?
3821         unsigned ShImm = Log2_32(RHSV+1);
3822         if (ShImm >= 32)
3823           break;
3824         SDValue V = N->getOperand(0);
3825         ShImm = ARM_AM::getSORegOpc(ARM_AM::lsl, ShImm);
3826         SDValue ShImmOp = CurDAG->getTargetConstant(ShImm, dl, MVT::i32);
3827         SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
3828         if (Subtarget->isThumb()) {
3829           SDValue Ops[] = { V, V, ShImmOp, getAL(CurDAG, dl), Reg0, Reg0 };
3830           CurDAG->SelectNodeTo(N, ARM::t2RSBrs, MVT::i32, Ops);
3831           return;
3832         } else {
3833           SDValue Ops[] = { V, V, Reg0, ShImmOp, getAL(CurDAG, dl), Reg0,
3834                             Reg0 };
3835           CurDAG->SelectNodeTo(N, ARM::RSBrsi, MVT::i32, Ops);
3836           return;
3837         }
3838       }
3839     }
3840     break;
3841   case ISD::AND: {
3842     // Check for unsigned bitfield extract
3843     if (tryV6T2BitfieldExtractOp(N, false))
3844       return;
3845 
3846     // If an immediate is used in an AND node, it is possible that the immediate
3847     // can be more optimally materialized when negated. If this is the case we
3848     // can negate the immediate and use a BIC instead.
3849     auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
3850     if (N1C && N1C->hasOneUse() && Subtarget->isThumb()) {
3851       uint32_t Imm = (uint32_t) N1C->getZExtValue();
3852 
3853       // In Thumb2 mode, an AND can take a 12-bit immediate. If this
3854       // immediate can be negated and fit in the immediate operand of
3855       // a t2BIC, don't do any manual transform here as this can be
3856       // handled by the generic ISel machinery.
3857       bool PreferImmediateEncoding =
3858         Subtarget->hasThumb2() && (is_t2_so_imm(Imm) || is_t2_so_imm_not(Imm));
3859       if (!PreferImmediateEncoding &&
3860           ConstantMaterializationCost(Imm, Subtarget) >
3861               ConstantMaterializationCost(~Imm, Subtarget)) {
3862         // The current immediate costs more to materialize than a negated
3863         // immediate, so negate the immediate and use a BIC.
3864         SDValue NewImm =
3865           CurDAG->getConstant(~N1C->getZExtValue(), dl, MVT::i32);
3866         // If the new constant didn't exist before, reposition it in the topological
3867         // ordering so it is just before N. Otherwise, don't touch its location.
3868         if (NewImm->getNodeId() == -1)
3869           CurDAG->RepositionNode(N->getIterator(), NewImm.getNode());
3870 
3871         if (!Subtarget->hasThumb2()) {
3872           SDValue Ops[] = {CurDAG->getRegister(ARM::CPSR, MVT::i32),
3873                            N->getOperand(0), NewImm, getAL(CurDAG, dl),
3874                            CurDAG->getRegister(0, MVT::i32)};
3875           ReplaceNode(N, CurDAG->getMachineNode(ARM::tBIC, dl, MVT::i32, Ops));
3876           return;
3877         } else {
3878           SDValue Ops[] = {N->getOperand(0), NewImm, getAL(CurDAG, dl),
3879                            CurDAG->getRegister(0, MVT::i32),
3880                            CurDAG->getRegister(0, MVT::i32)};
3881           ReplaceNode(N,
3882                       CurDAG->getMachineNode(ARM::t2BICrr, dl, MVT::i32, Ops));
3883           return;
3884         }
3885       }
3886     }
3887 
3888     // (and (or x, c2), c1) and top 16-bits of c1 and c2 match, lower 16-bits
3889     // of c1 are 0xffff, and lower 16-bit of c2 are 0. That is, the top 16-bits
3890     // are entirely contributed by c2 and lower 16-bits are entirely contributed
3891     // by x. That's equal to (or (and x, 0xffff), (and c1, 0xffff0000)).
3892     // Select it to: "movt x, ((c1 & 0xffff) >> 16)
3893     EVT VT = N->getValueType(0);
3894     if (VT != MVT::i32)
3895       break;
3896     unsigned Opc = (Subtarget->isThumb() && Subtarget->hasThumb2())
3897       ? ARM::t2MOVTi16
3898       : (Subtarget->hasV6T2Ops() ? ARM::MOVTi16 : 0);
3899     if (!Opc)
3900       break;
3901     SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
3902     N1C = dyn_cast<ConstantSDNode>(N1);
3903     if (!N1C)
3904       break;
3905     if (N0.getOpcode() == ISD::OR && N0.getNode()->hasOneUse()) {
3906       SDValue N2 = N0.getOperand(1);
3907       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3908       if (!N2C)
3909         break;
3910       unsigned N1CVal = N1C->getZExtValue();
3911       unsigned N2CVal = N2C->getZExtValue();
3912       if ((N1CVal & 0xffff0000U) == (N2CVal & 0xffff0000U) &&
3913           (N1CVal & 0xffffU) == 0xffffU &&
3914           (N2CVal & 0xffffU) == 0x0U) {
3915         SDValue Imm16 = CurDAG->getTargetConstant((N2CVal & 0xFFFF0000U) >> 16,
3916                                                   dl, MVT::i32);
3917         SDValue Ops[] = { N0.getOperand(0), Imm16,
3918                           getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32) };
3919         ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, Ops));
3920         return;
3921       }
3922     }
3923 
3924     break;
3925   }
3926   case ARMISD::UMAAL: {
3927     unsigned Opc = Subtarget->isThumb() ? ARM::t2UMAAL : ARM::UMAAL;
3928     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
3929                       N->getOperand(2), N->getOperand(3),
3930                       getAL(CurDAG, dl),
3931                       CurDAG->getRegister(0, MVT::i32) };
3932     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, MVT::i32, MVT::i32, Ops));
3933     return;
3934   }
3935   case ARMISD::UMLAL:{
3936     if (Subtarget->isThumb()) {
3937       SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
3938                         N->getOperand(3), getAL(CurDAG, dl),
3939                         CurDAG->getRegister(0, MVT::i32)};
3940       ReplaceNode(
3941           N, CurDAG->getMachineNode(ARM::t2UMLAL, dl, MVT::i32, MVT::i32, Ops));
3942       return;
3943     }else{
3944       SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
3945                         N->getOperand(3), getAL(CurDAG, dl),
3946                         CurDAG->getRegister(0, MVT::i32),
3947                         CurDAG->getRegister(0, MVT::i32) };
3948       ReplaceNode(N, CurDAG->getMachineNode(
3949                          Subtarget->hasV6Ops() ? ARM::UMLAL : ARM::UMLALv5, dl,
3950                          MVT::i32, MVT::i32, Ops));
3951       return;
3952     }
3953   }
3954   case ARMISD::SMLAL:{
3955     if (Subtarget->isThumb()) {
3956       SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
3957                         N->getOperand(3), getAL(CurDAG, dl),
3958                         CurDAG->getRegister(0, MVT::i32)};
3959       ReplaceNode(
3960           N, CurDAG->getMachineNode(ARM::t2SMLAL, dl, MVT::i32, MVT::i32, Ops));
3961       return;
3962     }else{
3963       SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2),
3964                         N->getOperand(3), getAL(CurDAG, dl),
3965                         CurDAG->getRegister(0, MVT::i32),
3966                         CurDAG->getRegister(0, MVT::i32) };
3967       ReplaceNode(N, CurDAG->getMachineNode(
3968                          Subtarget->hasV6Ops() ? ARM::SMLAL : ARM::SMLALv5, dl,
3969                          MVT::i32, MVT::i32, Ops));
3970       return;
3971     }
3972   }
3973   case ARMISD::SUBE: {
3974     if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
3975       break;
3976     // Look for a pattern to match SMMLS
3977     // (sube a, (smul_loHi a, b), (subc 0, (smul_LOhi(a, b))))
3978     if (N->getOperand(1).getOpcode() != ISD::SMUL_LOHI ||
3979         N->getOperand(2).getOpcode() != ARMISD::SUBC ||
3980         !SDValue(N, 1).use_empty())
3981       break;
3982 
3983     if (Subtarget->isThumb())
3984       assert(Subtarget->hasThumb2() &&
3985              "This pattern should not be generated for Thumb");
3986 
3987     SDValue SmulLoHi = N->getOperand(1);
3988     SDValue Subc = N->getOperand(2);
3989     SDValue Zero = Subc.getOperand(0);
3990 
3991     if (!isNullConstant(Zero) || Subc.getOperand(1) != SmulLoHi.getValue(0) ||
3992         N->getOperand(1) != SmulLoHi.getValue(1) ||
3993         N->getOperand(2) != Subc.getValue(1))
3994       break;
3995 
3996     unsigned Opc = Subtarget->isThumb2() ? ARM::t2SMMLS : ARM::SMMLS;
3997     SDValue Ops[] = { SmulLoHi.getOperand(0), SmulLoHi.getOperand(1),
3998                       N->getOperand(0), getAL(CurDAG, dl),
3999                       CurDAG->getRegister(0, MVT::i32) };
4000     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops));
4001     return;
4002   }
4003   case ISD::LOAD: {
4004     if (Subtarget->hasMVEIntegerOps() && tryMVEIndexedLoad(N))
4005       return;
4006     if (Subtarget->isThumb() && Subtarget->hasThumb2()) {
4007       if (tryT2IndexedLoad(N))
4008         return;
4009     } else if (Subtarget->isThumb()) {
4010       if (tryT1IndexedLoad(N))
4011         return;
4012     } else if (tryARMIndexedLoad(N))
4013       return;
4014     // Other cases are autogenerated.
4015     break;
4016   }
4017   case ISD::MLOAD:
4018     if (Subtarget->hasMVEIntegerOps() && tryMVEIndexedLoad(N))
4019       return;
4020     // Other cases are autogenerated.
4021     break;
4022   case ARMISD::WLSSETUP: {
4023     SDNode *New = CurDAG->getMachineNode(ARM::t2WhileLoopSetup, dl, MVT::i32,
4024                                          N->getOperand(0));
4025     ReplaceUses(N, New);
4026     CurDAG->RemoveDeadNode(N);
4027     return;
4028   }
4029   case ARMISD::WLS: {
4030     SDNode *New = CurDAG->getMachineNode(ARM::t2WhileLoopStart, dl, MVT::Other,
4031                                          N->getOperand(1), N->getOperand(2),
4032                                          N->getOperand(0));
4033     ReplaceUses(N, New);
4034     CurDAG->RemoveDeadNode(N);
4035     return;
4036   }
4037   case ARMISD::LE: {
4038     SDValue Ops[] = { N->getOperand(1),
4039                       N->getOperand(2),
4040                       N->getOperand(0) };
4041     unsigned Opc = ARM::t2LoopEnd;
4042     SDNode *New = CurDAG->getMachineNode(Opc, dl, MVT::Other, Ops);
4043     ReplaceUses(N, New);
4044     CurDAG->RemoveDeadNode(N);
4045     return;
4046   }
4047   case ARMISD::LDRD: {
4048     if (Subtarget->isThumb2())
4049       break; // TableGen handles isel in this case.
4050     SDValue Base, RegOffset, ImmOffset;
4051     const SDValue &Chain = N->getOperand(0);
4052     const SDValue &Addr = N->getOperand(1);
4053     SelectAddrMode3(Addr, Base, RegOffset, ImmOffset);
4054     if (RegOffset != CurDAG->getRegister(0, MVT::i32)) {
4055       // The register-offset variant of LDRD mandates that the register
4056       // allocated to RegOffset is not reused in any of the remaining operands.
4057       // This restriction is currently not enforced. Therefore emitting this
4058       // variant is explicitly avoided.
4059       Base = Addr;
4060       RegOffset = CurDAG->getRegister(0, MVT::i32);
4061     }
4062     SDValue Ops[] = {Base, RegOffset, ImmOffset, Chain};
4063     SDNode *New = CurDAG->getMachineNode(ARM::LOADDUAL, dl,
4064                                          {MVT::Untyped, MVT::Other}, Ops);
4065     SDValue Lo = CurDAG->getTargetExtractSubreg(ARM::gsub_0, dl, MVT::i32,
4066                                                 SDValue(New, 0));
4067     SDValue Hi = CurDAG->getTargetExtractSubreg(ARM::gsub_1, dl, MVT::i32,
4068                                                 SDValue(New, 0));
4069     transferMemOperands(N, New);
4070     ReplaceUses(SDValue(N, 0), Lo);
4071     ReplaceUses(SDValue(N, 1), Hi);
4072     ReplaceUses(SDValue(N, 2), SDValue(New, 1));
4073     CurDAG->RemoveDeadNode(N);
4074     return;
4075   }
4076   case ARMISD::STRD: {
4077     if (Subtarget->isThumb2())
4078       break; // TableGen handles isel in this case.
4079     SDValue Base, RegOffset, ImmOffset;
4080     const SDValue &Chain = N->getOperand(0);
4081     const SDValue &Addr = N->getOperand(3);
4082     SelectAddrMode3(Addr, Base, RegOffset, ImmOffset);
4083     if (RegOffset != CurDAG->getRegister(0, MVT::i32)) {
4084       // The register-offset variant of STRD mandates that the register
4085       // allocated to RegOffset is not reused in any of the remaining operands.
4086       // This restriction is currently not enforced. Therefore emitting this
4087       // variant is explicitly avoided.
4088       Base = Addr;
4089       RegOffset = CurDAG->getRegister(0, MVT::i32);
4090     }
4091     SDNode *RegPair =
4092         createGPRPairNode(MVT::Untyped, N->getOperand(1), N->getOperand(2));
4093     SDValue Ops[] = {SDValue(RegPair, 0), Base, RegOffset, ImmOffset, Chain};
4094     SDNode *New = CurDAG->getMachineNode(ARM::STOREDUAL, dl, MVT::Other, Ops);
4095     transferMemOperands(N, New);
4096     ReplaceUses(SDValue(N, 0), SDValue(New, 0));
4097     CurDAG->RemoveDeadNode(N);
4098     return;
4099   }
4100   case ARMISD::LOOP_DEC: {
4101     SDValue Ops[] = { N->getOperand(1),
4102                       N->getOperand(2),
4103                       N->getOperand(0) };
4104     SDNode *Dec =
4105       CurDAG->getMachineNode(ARM::t2LoopDec, dl,
4106                              CurDAG->getVTList(MVT::i32, MVT::Other), Ops);
4107     ReplaceUses(N, Dec);
4108     CurDAG->RemoveDeadNode(N);
4109     return;
4110   }
4111   case ARMISD::BRCOND: {
4112     // Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc)
4113     // Emits: (Bcc:void (bb:Other):$dst, (imm:i32):$cc)
4114     // Pattern complexity = 6  cost = 1  size = 0
4115 
4116     // Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc)
4117     // Emits: (tBcc:void (bb:Other):$dst, (imm:i32):$cc)
4118     // Pattern complexity = 6  cost = 1  size = 0
4119 
4120     // Pattern: (ARMbrcond:void (bb:Other):$dst, (imm:i32):$cc)
4121     // Emits: (t2Bcc:void (bb:Other):$dst, (imm:i32):$cc)
4122     // Pattern complexity = 6  cost = 1  size = 0
4123 
4124     unsigned Opc = Subtarget->isThumb() ?
4125       ((Subtarget->hasThumb2()) ? ARM::t2Bcc : ARM::tBcc) : ARM::Bcc;
4126     SDValue Chain = N->getOperand(0);
4127     SDValue N1 = N->getOperand(1);
4128     SDValue N2 = N->getOperand(2);
4129     SDValue N3 = N->getOperand(3);
4130     SDValue InGlue = N->getOperand(4);
4131     assert(N1.getOpcode() == ISD::BasicBlock);
4132     assert(N2.getOpcode() == ISD::Constant);
4133     assert(N3.getOpcode() == ISD::Register);
4134 
4135     unsigned CC = (unsigned) cast<ConstantSDNode>(N2)->getZExtValue();
4136 
4137     if (InGlue.getOpcode() == ARMISD::CMPZ) {
4138       if (InGlue.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4139         SDValue Int = InGlue.getOperand(0);
4140         uint64_t ID = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
4141 
4142         // Handle low-overhead loops.
4143         if (ID == Intrinsic::loop_decrement_reg) {
4144           SDValue Elements = Int.getOperand(2);
4145           SDValue Size = CurDAG->getTargetConstant(
4146             cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl,
4147                                  MVT::i32);
4148 
4149           SDValue Args[] = { Elements, Size, Int.getOperand(0) };
4150           SDNode *LoopDec =
4151             CurDAG->getMachineNode(ARM::t2LoopDec, dl,
4152                                    CurDAG->getVTList(MVT::i32, MVT::Other),
4153                                    Args);
4154           ReplaceUses(Int.getNode(), LoopDec);
4155 
4156           SDValue EndArgs[] = { SDValue(LoopDec, 0), N1, Chain };
4157           SDNode *LoopEnd =
4158             CurDAG->getMachineNode(ARM::t2LoopEnd, dl, MVT::Other, EndArgs);
4159 
4160           ReplaceUses(N, LoopEnd);
4161           CurDAG->RemoveDeadNode(N);
4162           CurDAG->RemoveDeadNode(InGlue.getNode());
4163           CurDAG->RemoveDeadNode(Int.getNode());
4164           return;
4165         }
4166       }
4167 
4168       bool SwitchEQNEToPLMI;
4169       SelectCMPZ(InGlue.getNode(), SwitchEQNEToPLMI);
4170       InGlue = N->getOperand(4);
4171 
4172       if (SwitchEQNEToPLMI) {
4173         switch ((ARMCC::CondCodes)CC) {
4174         default: llvm_unreachable("CMPZ must be either NE or EQ!");
4175         case ARMCC::NE:
4176           CC = (unsigned)ARMCC::MI;
4177           break;
4178         case ARMCC::EQ:
4179           CC = (unsigned)ARMCC::PL;
4180           break;
4181         }
4182       }
4183     }
4184 
4185     SDValue Tmp2 = CurDAG->getTargetConstant(CC, dl, MVT::i32);
4186     SDValue Ops[] = { N1, Tmp2, N3, Chain, InGlue };
4187     SDNode *ResNode = CurDAG->getMachineNode(Opc, dl, MVT::Other,
4188                                              MVT::Glue, Ops);
4189     Chain = SDValue(ResNode, 0);
4190     if (N->getNumValues() == 2) {
4191       InGlue = SDValue(ResNode, 1);
4192       ReplaceUses(SDValue(N, 1), InGlue);
4193     }
4194     ReplaceUses(SDValue(N, 0),
4195                 SDValue(Chain.getNode(), Chain.getResNo()));
4196     CurDAG->RemoveDeadNode(N);
4197     return;
4198   }
4199 
4200   case ARMISD::CMPZ: {
4201     // select (CMPZ X, #-C) -> (CMPZ (ADDS X, #C), #0)
4202     //   This allows us to avoid materializing the expensive negative constant.
4203     //   The CMPZ #0 is useless and will be peepholed away but we need to keep it
4204     //   for its glue output.
4205     SDValue X = N->getOperand(0);
4206     auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1).getNode());
4207     if (C && C->getSExtValue() < 0 && Subtarget->isThumb()) {
4208       int64_t Addend = -C->getSExtValue();
4209 
4210       SDNode *Add = nullptr;
4211       // ADDS can be better than CMN if the immediate fits in a
4212       // 16-bit ADDS, which means either [0,256) for tADDi8 or [0,8) for tADDi3.
4213       // Outside that range we can just use a CMN which is 32-bit but has a
4214       // 12-bit immediate range.
4215       if (Addend < 1<<8) {
4216         if (Subtarget->isThumb2()) {
4217           SDValue Ops[] = { X, CurDAG->getTargetConstant(Addend, dl, MVT::i32),
4218                             getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32),
4219                             CurDAG->getRegister(0, MVT::i32) };
4220           Add = CurDAG->getMachineNode(ARM::t2ADDri, dl, MVT::i32, Ops);
4221         } else {
4222           unsigned Opc = (Addend < 1<<3) ? ARM::tADDi3 : ARM::tADDi8;
4223           SDValue Ops[] = {CurDAG->getRegister(ARM::CPSR, MVT::i32), X,
4224                            CurDAG->getTargetConstant(Addend, dl, MVT::i32),
4225                            getAL(CurDAG, dl), CurDAG->getRegister(0, MVT::i32)};
4226           Add = CurDAG->getMachineNode(Opc, dl, MVT::i32, Ops);
4227         }
4228       }
4229       if (Add) {
4230         SDValue Ops2[] = {SDValue(Add, 0), CurDAG->getConstant(0, dl, MVT::i32)};
4231         CurDAG->MorphNodeTo(N, ARMISD::CMPZ, CurDAG->getVTList(MVT::Glue), Ops2);
4232       }
4233     }
4234     // Other cases are autogenerated.
4235     break;
4236   }
4237 
4238   case ARMISD::CMOV: {
4239     SDValue InGlue = N->getOperand(4);
4240 
4241     if (InGlue.getOpcode() == ARMISD::CMPZ) {
4242       bool SwitchEQNEToPLMI;
4243       SelectCMPZ(InGlue.getNode(), SwitchEQNEToPLMI);
4244 
4245       if (SwitchEQNEToPLMI) {
4246         SDValue ARMcc = N->getOperand(2);
4247         ARMCC::CondCodes CC =
4248           (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
4249 
4250         switch (CC) {
4251         default: llvm_unreachable("CMPZ must be either NE or EQ!");
4252         case ARMCC::NE:
4253           CC = ARMCC::MI;
4254           break;
4255         case ARMCC::EQ:
4256           CC = ARMCC::PL;
4257           break;
4258         }
4259         SDValue NewARMcc = CurDAG->getConstant((unsigned)CC, dl, MVT::i32);
4260         SDValue Ops[] = {N->getOperand(0), N->getOperand(1), NewARMcc,
4261                          N->getOperand(3), N->getOperand(4)};
4262         CurDAG->MorphNodeTo(N, ARMISD::CMOV, N->getVTList(), Ops);
4263       }
4264 
4265     }
4266     // Other cases are autogenerated.
4267     break;
4268   }
4269   case ARMISD::VZIP: {
4270     EVT VT = N->getValueType(0);
4271     // vzip.32 Dd, Dm is a pseudo-instruction expanded to vtrn.32 Dd, Dm.
4272     unsigned Opc64[] = {ARM::VZIPd8, ARM::VZIPd16, ARM::VTRNd32};
4273     unsigned Opc128[] = {ARM::VZIPq8, ARM::VZIPq16, ARM::VZIPq32};
4274     unsigned Opc = getVectorShuffleOpcode(VT, Opc64, Opc128);
4275     SDValue Pred = getAL(CurDAG, dl);
4276     SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
4277     SDValue Ops[] = {N->getOperand(0), N->getOperand(1), Pred, PredReg};
4278     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, VT, Ops));
4279     return;
4280   }
4281   case ARMISD::VUZP: {
4282     EVT VT = N->getValueType(0);
4283     // vuzp.32 Dd, Dm is a pseudo-instruction expanded to vtrn.32 Dd, Dm.
4284     unsigned Opc64[] = {ARM::VUZPd8, ARM::VUZPd16, ARM::VTRNd32};
4285     unsigned Opc128[] = {ARM::VUZPq8, ARM::VUZPq16, ARM::VUZPq32};
4286     unsigned Opc = getVectorShuffleOpcode(VT, Opc64, Opc128);
4287     SDValue Pred = getAL(CurDAG, dl);
4288     SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
4289     SDValue Ops[] = {N->getOperand(0), N->getOperand(1), Pred, PredReg};
4290     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, VT, Ops));
4291     return;
4292   }
4293   case ARMISD::VTRN: {
4294     EVT VT = N->getValueType(0);
4295     unsigned Opc64[] = {ARM::VTRNd8, ARM::VTRNd16, ARM::VTRNd32};
4296     unsigned Opc128[] = {ARM::VTRNq8, ARM::VTRNq16, ARM::VTRNq32};
4297     unsigned Opc = getVectorShuffleOpcode(VT, Opc64, Opc128);
4298     SDValue Pred = getAL(CurDAG, dl);
4299     SDValue PredReg = CurDAG->getRegister(0, MVT::i32);
4300     SDValue Ops[] = {N->getOperand(0), N->getOperand(1), Pred, PredReg};
4301     ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, VT, VT, Ops));
4302     return;
4303   }
4304   case ARMISD::BUILD_VECTOR: {
4305     EVT VecVT = N->getValueType(0);
4306     EVT EltVT = VecVT.getVectorElementType();
4307     unsigned NumElts = VecVT.getVectorNumElements();
4308     if (EltVT == MVT::f64) {
4309       assert(NumElts == 2 && "unexpected type for BUILD_VECTOR");
4310       ReplaceNode(
4311           N, createDRegPairNode(VecVT, N->getOperand(0), N->getOperand(1)));
4312       return;
4313     }
4314     assert(EltVT == MVT::f32 && "unexpected type for BUILD_VECTOR");
4315     if (NumElts == 2) {
4316       ReplaceNode(
4317           N, createSRegPairNode(VecVT, N->getOperand(0), N->getOperand(1)));
4318       return;
4319     }
4320     assert(NumElts == 4 && "unexpected type for BUILD_VECTOR");
4321     ReplaceNode(N,
4322                 createQuadSRegsNode(VecVT, N->getOperand(0), N->getOperand(1),
4323                                     N->getOperand(2), N->getOperand(3)));
4324     return;
4325   }
4326 
4327   case ARMISD::VLD1DUP: {
4328     static const uint16_t DOpcodes[] = { ARM::VLD1DUPd8, ARM::VLD1DUPd16,
4329                                          ARM::VLD1DUPd32 };
4330     static const uint16_t QOpcodes[] = { ARM::VLD1DUPq8, ARM::VLD1DUPq16,
4331                                          ARM::VLD1DUPq32 };
4332     SelectVLDDup(N, /* IsIntrinsic= */ false, false, 1, DOpcodes, QOpcodes);
4333     return;
4334   }
4335 
4336   case ARMISD::VLD2DUP: {
4337     static const uint16_t Opcodes[] = { ARM::VLD2DUPd8, ARM::VLD2DUPd16,
4338                                         ARM::VLD2DUPd32 };
4339     SelectVLDDup(N, /* IsIntrinsic= */ false, false, 2, Opcodes);
4340     return;
4341   }
4342 
4343   case ARMISD::VLD3DUP: {
4344     static const uint16_t Opcodes[] = { ARM::VLD3DUPd8Pseudo,
4345                                         ARM::VLD3DUPd16Pseudo,
4346                                         ARM::VLD3DUPd32Pseudo };
4347     SelectVLDDup(N, /* IsIntrinsic= */ false, false, 3, Opcodes);
4348     return;
4349   }
4350 
4351   case ARMISD::VLD4DUP: {
4352     static const uint16_t Opcodes[] = { ARM::VLD4DUPd8Pseudo,
4353                                         ARM::VLD4DUPd16Pseudo,
4354                                         ARM::VLD4DUPd32Pseudo };
4355     SelectVLDDup(N, /* IsIntrinsic= */ false, false, 4, Opcodes);
4356     return;
4357   }
4358 
4359   case ARMISD::VLD1DUP_UPD: {
4360     static const uint16_t DOpcodes[] = { ARM::VLD1DUPd8wb_fixed,
4361                                          ARM::VLD1DUPd16wb_fixed,
4362                                          ARM::VLD1DUPd32wb_fixed };
4363     static const uint16_t QOpcodes[] = { ARM::VLD1DUPq8wb_fixed,
4364                                          ARM::VLD1DUPq16wb_fixed,
4365                                          ARM::VLD1DUPq32wb_fixed };
4366     SelectVLDDup(N, /* IsIntrinsic= */ false, true, 1, DOpcodes, QOpcodes);
4367     return;
4368   }
4369 
4370   case ARMISD::VLD2DUP_UPD: {
4371     static const uint16_t DOpcodes[] = { ARM::VLD2DUPd8wb_fixed,
4372                                          ARM::VLD2DUPd16wb_fixed,
4373                                          ARM::VLD2DUPd32wb_fixed,
4374                                          ARM::VLD1q64wb_fixed };
4375     static const uint16_t QOpcodes0[] = { ARM::VLD2DUPq8EvenPseudo,
4376                                           ARM::VLD2DUPq16EvenPseudo,
4377                                           ARM::VLD2DUPq32EvenPseudo };
4378     static const uint16_t QOpcodes1[] = { ARM::VLD2DUPq8OddPseudoWB_fixed,
4379                                           ARM::VLD2DUPq16OddPseudoWB_fixed,
4380                                           ARM::VLD2DUPq32OddPseudoWB_fixed };
4381     SelectVLDDup(N, /* IsIntrinsic= */ false, true, 2, DOpcodes, QOpcodes0, QOpcodes1);
4382     return;
4383   }
4384 
4385   case ARMISD::VLD3DUP_UPD: {
4386     static const uint16_t DOpcodes[] = { ARM::VLD3DUPd8Pseudo_UPD,
4387                                          ARM::VLD3DUPd16Pseudo_UPD,
4388                                          ARM::VLD3DUPd32Pseudo_UPD,
4389                                          ARM::VLD1d64TPseudoWB_fixed };
4390     static const uint16_t QOpcodes0[] = { ARM::VLD3DUPq8EvenPseudo,
4391                                           ARM::VLD3DUPq16EvenPseudo,
4392                                           ARM::VLD3DUPq32EvenPseudo };
4393     static const uint16_t QOpcodes1[] = { ARM::VLD3DUPq8OddPseudo_UPD,
4394                                           ARM::VLD3DUPq16OddPseudo_UPD,
4395                                           ARM::VLD3DUPq32OddPseudo_UPD };
4396     SelectVLDDup(N, /* IsIntrinsic= */ false, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
4397     return;
4398   }
4399 
4400   case ARMISD::VLD4DUP_UPD: {
4401     static const uint16_t DOpcodes[] = { ARM::VLD4DUPd8Pseudo_UPD,
4402                                          ARM::VLD4DUPd16Pseudo_UPD,
4403                                          ARM::VLD4DUPd32Pseudo_UPD,
4404                                          ARM::VLD1d64QPseudoWB_fixed };
4405     static const uint16_t QOpcodes0[] = { ARM::VLD4DUPq8EvenPseudo,
4406                                           ARM::VLD4DUPq16EvenPseudo,
4407                                           ARM::VLD4DUPq32EvenPseudo };
4408     static const uint16_t QOpcodes1[] = { ARM::VLD4DUPq8OddPseudo_UPD,
4409                                           ARM::VLD4DUPq16OddPseudo_UPD,
4410                                           ARM::VLD4DUPq32OddPseudo_UPD };
4411     SelectVLDDup(N, /* IsIntrinsic= */ false, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
4412     return;
4413   }
4414 
4415   case ARMISD::VLD1_UPD: {
4416     static const uint16_t DOpcodes[] = { ARM::VLD1d8wb_fixed,
4417                                          ARM::VLD1d16wb_fixed,
4418                                          ARM::VLD1d32wb_fixed,
4419                                          ARM::VLD1d64wb_fixed };
4420     static const uint16_t QOpcodes[] = { ARM::VLD1q8wb_fixed,
4421                                          ARM::VLD1q16wb_fixed,
4422                                          ARM::VLD1q32wb_fixed,
4423                                          ARM::VLD1q64wb_fixed };
4424     SelectVLD(N, true, 1, DOpcodes, QOpcodes, nullptr);
4425     return;
4426   }
4427 
4428   case ARMISD::VLD2_UPD: {
4429     if (Subtarget->hasNEON()) {
4430       static const uint16_t DOpcodes[] = {
4431           ARM::VLD2d8wb_fixed, ARM::VLD2d16wb_fixed, ARM::VLD2d32wb_fixed,
4432           ARM::VLD1q64wb_fixed};
4433       static const uint16_t QOpcodes[] = {ARM::VLD2q8PseudoWB_fixed,
4434                                           ARM::VLD2q16PseudoWB_fixed,
4435                                           ARM::VLD2q32PseudoWB_fixed};
4436       SelectVLD(N, true, 2, DOpcodes, QOpcodes, nullptr);
4437     } else {
4438       static const uint16_t Opcodes8[] = {ARM::MVE_VLD20_8,
4439                                           ARM::MVE_VLD21_8_wb};
4440       static const uint16_t Opcodes16[] = {ARM::MVE_VLD20_16,
4441                                            ARM::MVE_VLD21_16_wb};
4442       static const uint16_t Opcodes32[] = {ARM::MVE_VLD20_32,
4443                                            ARM::MVE_VLD21_32_wb};
4444       static const uint16_t *const Opcodes[] = {Opcodes8, Opcodes16, Opcodes32};
4445       SelectMVE_VLD(N, 2, Opcodes, true);
4446     }
4447     return;
4448   }
4449 
4450   case ARMISD::VLD3_UPD: {
4451     static const uint16_t DOpcodes[] = { ARM::VLD3d8Pseudo_UPD,
4452                                          ARM::VLD3d16Pseudo_UPD,
4453                                          ARM::VLD3d32Pseudo_UPD,
4454                                          ARM::VLD1d64TPseudoWB_fixed};
4455     static const uint16_t QOpcodes0[] = { ARM::VLD3q8Pseudo_UPD,
4456                                           ARM::VLD3q16Pseudo_UPD,
4457                                           ARM::VLD3q32Pseudo_UPD };
4458     static const uint16_t QOpcodes1[] = { ARM::VLD3q8oddPseudo_UPD,
4459                                           ARM::VLD3q16oddPseudo_UPD,
4460                                           ARM::VLD3q32oddPseudo_UPD };
4461     SelectVLD(N, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
4462     return;
4463   }
4464 
4465   case ARMISD::VLD4_UPD: {
4466     if (Subtarget->hasNEON()) {
4467       static const uint16_t DOpcodes[] = {
4468           ARM::VLD4d8Pseudo_UPD, ARM::VLD4d16Pseudo_UPD, ARM::VLD4d32Pseudo_UPD,
4469           ARM::VLD1d64QPseudoWB_fixed};
4470       static const uint16_t QOpcodes0[] = {ARM::VLD4q8Pseudo_UPD,
4471                                            ARM::VLD4q16Pseudo_UPD,
4472                                            ARM::VLD4q32Pseudo_UPD};
4473       static const uint16_t QOpcodes1[] = {ARM::VLD4q8oddPseudo_UPD,
4474                                            ARM::VLD4q16oddPseudo_UPD,
4475                                            ARM::VLD4q32oddPseudo_UPD};
4476       SelectVLD(N, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
4477     } else {
4478       static const uint16_t Opcodes8[] = {ARM::MVE_VLD40_8, ARM::MVE_VLD41_8,
4479                                           ARM::MVE_VLD42_8,
4480                                           ARM::MVE_VLD43_8_wb};
4481       static const uint16_t Opcodes16[] = {ARM::MVE_VLD40_16, ARM::MVE_VLD41_16,
4482                                            ARM::MVE_VLD42_16,
4483                                            ARM::MVE_VLD43_16_wb};
4484       static const uint16_t Opcodes32[] = {ARM::MVE_VLD40_32, ARM::MVE_VLD41_32,
4485                                            ARM::MVE_VLD42_32,
4486                                            ARM::MVE_VLD43_32_wb};
4487       static const uint16_t *const Opcodes[] = {Opcodes8, Opcodes16, Opcodes32};
4488       SelectMVE_VLD(N, 4, Opcodes, true);
4489     }
4490     return;
4491   }
4492 
4493   case ARMISD::VLD1x2_UPD: {
4494     if (Subtarget->hasNEON()) {
4495       static const uint16_t DOpcodes[] = {
4496           ARM::VLD1q8wb_fixed, ARM::VLD1q16wb_fixed, ARM::VLD1q32wb_fixed,
4497           ARM::VLD1q64wb_fixed};
4498       static const uint16_t QOpcodes[] = {
4499           ARM::VLD1d8QPseudoWB_fixed, ARM::VLD1d16QPseudoWB_fixed,
4500           ARM::VLD1d32QPseudoWB_fixed, ARM::VLD1d64QPseudoWB_fixed};
4501       SelectVLD(N, true, 2, DOpcodes, QOpcodes, nullptr);
4502       return;
4503     }
4504     break;
4505   }
4506 
4507   case ARMISD::VLD1x3_UPD: {
4508     if (Subtarget->hasNEON()) {
4509       static const uint16_t DOpcodes[] = {
4510           ARM::VLD1d8TPseudoWB_fixed, ARM::VLD1d16TPseudoWB_fixed,
4511           ARM::VLD1d32TPseudoWB_fixed, ARM::VLD1d64TPseudoWB_fixed};
4512       static const uint16_t QOpcodes0[] = {
4513           ARM::VLD1q8LowTPseudo_UPD, ARM::VLD1q16LowTPseudo_UPD,
4514           ARM::VLD1q32LowTPseudo_UPD, ARM::VLD1q64LowTPseudo_UPD};
4515       static const uint16_t QOpcodes1[] = {
4516           ARM::VLD1q8HighTPseudo_UPD, ARM::VLD1q16HighTPseudo_UPD,
4517           ARM::VLD1q32HighTPseudo_UPD, ARM::VLD1q64HighTPseudo_UPD};
4518       SelectVLD(N, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
4519       return;
4520     }
4521     break;
4522   }
4523 
4524   case ARMISD::VLD1x4_UPD: {
4525     if (Subtarget->hasNEON()) {
4526       static const uint16_t DOpcodes[] = {
4527           ARM::VLD1d8QPseudoWB_fixed, ARM::VLD1d16QPseudoWB_fixed,
4528           ARM::VLD1d32QPseudoWB_fixed, ARM::VLD1d64QPseudoWB_fixed};
4529       static const uint16_t QOpcodes0[] = {
4530           ARM::VLD1q8LowQPseudo_UPD, ARM::VLD1q16LowQPseudo_UPD,
4531           ARM::VLD1q32LowQPseudo_UPD, ARM::VLD1q64LowQPseudo_UPD};
4532       static const uint16_t QOpcodes1[] = {
4533           ARM::VLD1q8HighQPseudo_UPD, ARM::VLD1q16HighQPseudo_UPD,
4534           ARM::VLD1q32HighQPseudo_UPD, ARM::VLD1q64HighQPseudo_UPD};
4535       SelectVLD(N, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
4536       return;
4537     }
4538     break;
4539   }
4540 
4541   case ARMISD::VLD2LN_UPD: {
4542     static const uint16_t DOpcodes[] = { ARM::VLD2LNd8Pseudo_UPD,
4543                                          ARM::VLD2LNd16Pseudo_UPD,
4544                                          ARM::VLD2LNd32Pseudo_UPD };
4545     static const uint16_t QOpcodes[] = { ARM::VLD2LNq16Pseudo_UPD,
4546                                          ARM::VLD2LNq32Pseudo_UPD };
4547     SelectVLDSTLane(N, true, true, 2, DOpcodes, QOpcodes);
4548     return;
4549   }
4550 
4551   case ARMISD::VLD3LN_UPD: {
4552     static const uint16_t DOpcodes[] = { ARM::VLD3LNd8Pseudo_UPD,
4553                                          ARM::VLD3LNd16Pseudo_UPD,
4554                                          ARM::VLD3LNd32Pseudo_UPD };
4555     static const uint16_t QOpcodes[] = { ARM::VLD3LNq16Pseudo_UPD,
4556                                          ARM::VLD3LNq32Pseudo_UPD };
4557     SelectVLDSTLane(N, true, true, 3, DOpcodes, QOpcodes);
4558     return;
4559   }
4560 
4561   case ARMISD::VLD4LN_UPD: {
4562     static const uint16_t DOpcodes[] = { ARM::VLD4LNd8Pseudo_UPD,
4563                                          ARM::VLD4LNd16Pseudo_UPD,
4564                                          ARM::VLD4LNd32Pseudo_UPD };
4565     static const uint16_t QOpcodes[] = { ARM::VLD4LNq16Pseudo_UPD,
4566                                          ARM::VLD4LNq32Pseudo_UPD };
4567     SelectVLDSTLane(N, true, true, 4, DOpcodes, QOpcodes);
4568     return;
4569   }
4570 
4571   case ARMISD::VST1_UPD: {
4572     static const uint16_t DOpcodes[] = { ARM::VST1d8wb_fixed,
4573                                          ARM::VST1d16wb_fixed,
4574                                          ARM::VST1d32wb_fixed,
4575                                          ARM::VST1d64wb_fixed };
4576     static const uint16_t QOpcodes[] = { ARM::VST1q8wb_fixed,
4577                                          ARM::VST1q16wb_fixed,
4578                                          ARM::VST1q32wb_fixed,
4579                                          ARM::VST1q64wb_fixed };
4580     SelectVST(N, true, 1, DOpcodes, QOpcodes, nullptr);
4581     return;
4582   }
4583 
4584   case ARMISD::VST2_UPD: {
4585     if (Subtarget->hasNEON()) {
4586       static const uint16_t DOpcodes[] = {
4587           ARM::VST2d8wb_fixed, ARM::VST2d16wb_fixed, ARM::VST2d32wb_fixed,
4588           ARM::VST1q64wb_fixed};
4589       static const uint16_t QOpcodes[] = {ARM::VST2q8PseudoWB_fixed,
4590                                           ARM::VST2q16PseudoWB_fixed,
4591                                           ARM::VST2q32PseudoWB_fixed};
4592       SelectVST(N, true, 2, DOpcodes, QOpcodes, nullptr);
4593       return;
4594     }
4595     break;
4596   }
4597 
4598   case ARMISD::VST3_UPD: {
4599     static const uint16_t DOpcodes[] = { ARM::VST3d8Pseudo_UPD,
4600                                          ARM::VST3d16Pseudo_UPD,
4601                                          ARM::VST3d32Pseudo_UPD,
4602                                          ARM::VST1d64TPseudoWB_fixed};
4603     static const uint16_t QOpcodes0[] = { ARM::VST3q8Pseudo_UPD,
4604                                           ARM::VST3q16Pseudo_UPD,
4605                                           ARM::VST3q32Pseudo_UPD };
4606     static const uint16_t QOpcodes1[] = { ARM::VST3q8oddPseudo_UPD,
4607                                           ARM::VST3q16oddPseudo_UPD,
4608                                           ARM::VST3q32oddPseudo_UPD };
4609     SelectVST(N, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
4610     return;
4611   }
4612 
4613   case ARMISD::VST4_UPD: {
4614     if (Subtarget->hasNEON()) {
4615       static const uint16_t DOpcodes[] = {
4616           ARM::VST4d8Pseudo_UPD, ARM::VST4d16Pseudo_UPD, ARM::VST4d32Pseudo_UPD,
4617           ARM::VST1d64QPseudoWB_fixed};
4618       static const uint16_t QOpcodes0[] = {ARM::VST4q8Pseudo_UPD,
4619                                            ARM::VST4q16Pseudo_UPD,
4620                                            ARM::VST4q32Pseudo_UPD};
4621       static const uint16_t QOpcodes1[] = {ARM::VST4q8oddPseudo_UPD,
4622                                            ARM::VST4q16oddPseudo_UPD,
4623                                            ARM::VST4q32oddPseudo_UPD};
4624       SelectVST(N, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
4625       return;
4626     }
4627     break;
4628   }
4629 
4630   case ARMISD::VST1x2_UPD: {
4631     if (Subtarget->hasNEON()) {
4632       static const uint16_t DOpcodes[] = { ARM::VST1q8wb_fixed,
4633                                            ARM::VST1q16wb_fixed,
4634                                            ARM::VST1q32wb_fixed,
4635                                            ARM::VST1q64wb_fixed};
4636       static const uint16_t QOpcodes[] = { ARM::VST1d8QPseudoWB_fixed,
4637                                            ARM::VST1d16QPseudoWB_fixed,
4638                                            ARM::VST1d32QPseudoWB_fixed,
4639                                            ARM::VST1d64QPseudoWB_fixed };
4640       SelectVST(N, true, 2, DOpcodes, QOpcodes, nullptr);
4641       return;
4642     }
4643     break;
4644   }
4645 
4646   case ARMISD::VST1x3_UPD: {
4647     if (Subtarget->hasNEON()) {
4648       static const uint16_t DOpcodes[] = { ARM::VST1d8TPseudoWB_fixed,
4649                                            ARM::VST1d16TPseudoWB_fixed,
4650                                            ARM::VST1d32TPseudoWB_fixed,
4651                                            ARM::VST1d64TPseudoWB_fixed };
4652       static const uint16_t QOpcodes0[] = { ARM::VST1q8LowTPseudo_UPD,
4653                                             ARM::VST1q16LowTPseudo_UPD,
4654                                             ARM::VST1q32LowTPseudo_UPD,
4655                                             ARM::VST1q64LowTPseudo_UPD };
4656       static const uint16_t QOpcodes1[] = { ARM::VST1q8HighTPseudo_UPD,
4657                                             ARM::VST1q16HighTPseudo_UPD,
4658                                             ARM::VST1q32HighTPseudo_UPD,
4659                                             ARM::VST1q64HighTPseudo_UPD };
4660       SelectVST(N, true, 3, DOpcodes, QOpcodes0, QOpcodes1);
4661       return;
4662     }
4663     break;
4664   }
4665 
4666   case ARMISD::VST1x4_UPD: {
4667     if (Subtarget->hasNEON()) {
4668       static const uint16_t DOpcodes[] = { ARM::VST1d8QPseudoWB_fixed,
4669                                            ARM::VST1d16QPseudoWB_fixed,
4670                                            ARM::VST1d32QPseudoWB_fixed,
4671                                            ARM::VST1d64QPseudoWB_fixed };
4672       static const uint16_t QOpcodes0[] = { ARM::VST1q8LowQPseudo_UPD,
4673                                             ARM::VST1q16LowQPseudo_UPD,
4674                                             ARM::VST1q32LowQPseudo_UPD,
4675                                             ARM::VST1q64LowQPseudo_UPD };
4676       static const uint16_t QOpcodes1[] = { ARM::VST1q8HighQPseudo_UPD,
4677                                             ARM::VST1q16HighQPseudo_UPD,
4678                                             ARM::VST1q32HighQPseudo_UPD,
4679                                             ARM::VST1q64HighQPseudo_UPD };
4680       SelectVST(N, true, 4, DOpcodes, QOpcodes0, QOpcodes1);
4681       return;
4682     }
4683     break;
4684   }
4685   case ARMISD::VST2LN_UPD: {
4686     static const uint16_t DOpcodes[] = { ARM::VST2LNd8Pseudo_UPD,
4687                                          ARM::VST2LNd16Pseudo_UPD,
4688                                          ARM::VST2LNd32Pseudo_UPD };
4689     static const uint16_t QOpcodes[] = { ARM::VST2LNq16Pseudo_UPD,
4690                                          ARM::VST2LNq32Pseudo_UPD };
4691     SelectVLDSTLane(N, false, true, 2, DOpcodes, QOpcodes);
4692     return;
4693   }
4694 
4695   case ARMISD::VST3LN_UPD: {
4696     static const uint16_t DOpcodes[] = { ARM::VST3LNd8Pseudo_UPD,
4697                                          ARM::VST3LNd16Pseudo_UPD,
4698                                          ARM::VST3LNd32Pseudo_UPD };
4699     static const uint16_t QOpcodes[] = { ARM::VST3LNq16Pseudo_UPD,
4700                                          ARM::VST3LNq32Pseudo_UPD };
4701     SelectVLDSTLane(N, false, true, 3, DOpcodes, QOpcodes);
4702     return;
4703   }
4704 
4705   case ARMISD::VST4LN_UPD: {
4706     static const uint16_t DOpcodes[] = { ARM::VST4LNd8Pseudo_UPD,
4707                                          ARM::VST4LNd16Pseudo_UPD,
4708                                          ARM::VST4LNd32Pseudo_UPD };
4709     static const uint16_t QOpcodes[] = { ARM::VST4LNq16Pseudo_UPD,
4710                                          ARM::VST4LNq32Pseudo_UPD };
4711     SelectVLDSTLane(N, false, true, 4, DOpcodes, QOpcodes);
4712     return;
4713   }
4714 
4715   case ISD::INTRINSIC_VOID:
4716   case ISD::INTRINSIC_W_CHAIN: {
4717     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
4718     switch (IntNo) {
4719     default:
4720       break;
4721 
4722     case Intrinsic::arm_mrrc:
4723     case Intrinsic::arm_mrrc2: {
4724       SDLoc dl(N);
4725       SDValue Chain = N->getOperand(0);
4726       unsigned Opc;
4727 
4728       if (Subtarget->isThumb())
4729         Opc = (IntNo == Intrinsic::arm_mrrc ? ARM::t2MRRC : ARM::t2MRRC2);
4730       else
4731         Opc = (IntNo == Intrinsic::arm_mrrc ? ARM::MRRC : ARM::MRRC2);
4732 
4733       SmallVector<SDValue, 5> Ops;
4734       Ops.push_back(getI32Imm(cast<ConstantSDNode>(N->getOperand(2))->getZExtValue(), dl)); /* coproc */
4735       Ops.push_back(getI32Imm(cast<ConstantSDNode>(N->getOperand(3))->getZExtValue(), dl)); /* opc */
4736       Ops.push_back(getI32Imm(cast<ConstantSDNode>(N->getOperand(4))->getZExtValue(), dl)); /* CRm */
4737 
4738       // The mrrc2 instruction in ARM doesn't allow predicates, the top 4 bits of the encoded
4739       // instruction will always be '1111' but it is possible in assembly language to specify
4740       // AL as a predicate to mrrc2 but it doesn't make any difference to the encoded instruction.
4741       if (Opc != ARM::MRRC2) {
4742         Ops.push_back(getAL(CurDAG, dl));
4743         Ops.push_back(CurDAG->getRegister(0, MVT::i32));
4744       }
4745 
4746       Ops.push_back(Chain);
4747 
4748       // Writes to two registers.
4749       const EVT RetType[] = {MVT::i32, MVT::i32, MVT::Other};
4750 
4751       ReplaceNode(N, CurDAG->getMachineNode(Opc, dl, RetType, Ops));
4752       return;
4753     }
4754     case Intrinsic::arm_ldaexd:
4755     case Intrinsic::arm_ldrexd: {
4756       SDLoc dl(N);
4757       SDValue Chain = N->getOperand(0);
4758       SDValue MemAddr = N->getOperand(2);
4759       bool isThumb = Subtarget->isThumb() && Subtarget->hasV8MBaselineOps();
4760 
4761       bool IsAcquire = IntNo == Intrinsic::arm_ldaexd;
4762       unsigned NewOpc = isThumb ? (IsAcquire ? ARM::t2LDAEXD : ARM::t2LDREXD)
4763                                 : (IsAcquire ? ARM::LDAEXD : ARM::LDREXD);
4764 
4765       // arm_ldrexd returns a i64 value in {i32, i32}
4766       std::vector<EVT> ResTys;
4767       if (isThumb) {
4768         ResTys.push_back(MVT::i32);
4769         ResTys.push_back(MVT::i32);
4770       } else
4771         ResTys.push_back(MVT::Untyped);
4772       ResTys.push_back(MVT::Other);
4773 
4774       // Place arguments in the right order.
4775       SDValue Ops[] = {MemAddr, getAL(CurDAG, dl),
4776                        CurDAG->getRegister(0, MVT::i32), Chain};
4777       SDNode *Ld = CurDAG->getMachineNode(NewOpc, dl, ResTys, Ops);
4778       // Transfer memoperands.
4779       MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
4780       CurDAG->setNodeMemRefs(cast<MachineSDNode>(Ld), {MemOp});
4781 
4782       // Remap uses.
4783       SDValue OutChain = isThumb ? SDValue(Ld, 2) : SDValue(Ld, 1);
4784       if (!SDValue(N, 0).use_empty()) {
4785         SDValue Result;
4786         if (isThumb)
4787           Result = SDValue(Ld, 0);
4788         else {
4789           SDValue SubRegIdx =
4790             CurDAG->getTargetConstant(ARM::gsub_0, dl, MVT::i32);
4791           SDNode *ResNode = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
4792               dl, MVT::i32, SDValue(Ld, 0), SubRegIdx);
4793           Result = SDValue(ResNode,0);
4794         }
4795         ReplaceUses(SDValue(N, 0), Result);
4796       }
4797       if (!SDValue(N, 1).use_empty()) {
4798         SDValue Result;
4799         if (isThumb)
4800           Result = SDValue(Ld, 1);
4801         else {
4802           SDValue SubRegIdx =
4803             CurDAG->getTargetConstant(ARM::gsub_1, dl, MVT::i32);
4804           SDNode *ResNode = CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG,
4805               dl, MVT::i32, SDValue(Ld, 0), SubRegIdx);
4806           Result = SDValue(ResNode,0);
4807         }
4808         ReplaceUses(SDValue(N, 1), Result);
4809       }
4810       ReplaceUses(SDValue(N, 2), OutChain);
4811       CurDAG->RemoveDeadNode(N);
4812       return;
4813     }
4814     case Intrinsic::arm_stlexd:
4815     case Intrinsic::arm_strexd: {
4816       SDLoc dl(N);
4817       SDValue Chain = N->getOperand(0);
4818       SDValue Val0 = N->getOperand(2);
4819       SDValue Val1 = N->getOperand(3);
4820       SDValue MemAddr = N->getOperand(4);
4821 
4822       // Store exclusive double return a i32 value which is the return status
4823       // of the issued store.
4824       const EVT ResTys[] = {MVT::i32, MVT::Other};
4825 
4826       bool isThumb = Subtarget->isThumb() && Subtarget->hasThumb2();
4827       // Place arguments in the right order.
4828       SmallVector<SDValue, 7> Ops;
4829       if (isThumb) {
4830         Ops.push_back(Val0);
4831         Ops.push_back(Val1);
4832       } else
4833         // arm_strexd uses GPRPair.
4834         Ops.push_back(SDValue(createGPRPairNode(MVT::Untyped, Val0, Val1), 0));
4835       Ops.push_back(MemAddr);
4836       Ops.push_back(getAL(CurDAG, dl));
4837       Ops.push_back(CurDAG->getRegister(0, MVT::i32));
4838       Ops.push_back(Chain);
4839 
4840       bool IsRelease = IntNo == Intrinsic::arm_stlexd;
4841       unsigned NewOpc = isThumb ? (IsRelease ? ARM::t2STLEXD : ARM::t2STREXD)
4842                                 : (IsRelease ? ARM::STLEXD : ARM::STREXD);
4843 
4844       SDNode *St = CurDAG->getMachineNode(NewOpc, dl, ResTys, Ops);
4845       // Transfer memoperands.
4846       MachineMemOperand *MemOp = cast<MemIntrinsicSDNode>(N)->getMemOperand();
4847       CurDAG->setNodeMemRefs(cast<MachineSDNode>(St), {MemOp});
4848 
4849       ReplaceNode(N, St);
4850       return;
4851     }
4852 
4853     case Intrinsic::arm_neon_vld1: {
4854       static const uint16_t DOpcodes[] = { ARM::VLD1d8, ARM::VLD1d16,
4855                                            ARM::VLD1d32, ARM::VLD1d64 };
4856       static const uint16_t QOpcodes[] = { ARM::VLD1q8, ARM::VLD1q16,
4857                                            ARM::VLD1q32, ARM::VLD1q64};
4858       SelectVLD(N, false, 1, DOpcodes, QOpcodes, nullptr);
4859       return;
4860     }
4861 
4862     case Intrinsic::arm_neon_vld1x2: {
4863       static const uint16_t DOpcodes[] = { ARM::VLD1q8, ARM::VLD1q16,
4864                                            ARM::VLD1q32, ARM::VLD1q64 };
4865       static const uint16_t QOpcodes[] = { ARM::VLD1d8QPseudo,
4866                                            ARM::VLD1d16QPseudo,
4867                                            ARM::VLD1d32QPseudo,
4868                                            ARM::VLD1d64QPseudo };
4869       SelectVLD(N, false, 2, DOpcodes, QOpcodes, nullptr);
4870       return;
4871     }
4872 
4873     case Intrinsic::arm_neon_vld1x3: {
4874       static const uint16_t DOpcodes[] = { ARM::VLD1d8TPseudo,
4875                                            ARM::VLD1d16TPseudo,
4876                                            ARM::VLD1d32TPseudo,
4877                                            ARM::VLD1d64TPseudo };
4878       static const uint16_t QOpcodes0[] = { ARM::VLD1q8LowTPseudo_UPD,
4879                                             ARM::VLD1q16LowTPseudo_UPD,
4880                                             ARM::VLD1q32LowTPseudo_UPD,
4881                                             ARM::VLD1q64LowTPseudo_UPD };
4882       static const uint16_t QOpcodes1[] = { ARM::VLD1q8HighTPseudo,
4883                                             ARM::VLD1q16HighTPseudo,
4884                                             ARM::VLD1q32HighTPseudo,
4885                                             ARM::VLD1q64HighTPseudo };
4886       SelectVLD(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
4887       return;
4888     }
4889 
4890     case Intrinsic::arm_neon_vld1x4: {
4891       static const uint16_t DOpcodes[] = { ARM::VLD1d8QPseudo,
4892                                            ARM::VLD1d16QPseudo,
4893                                            ARM::VLD1d32QPseudo,
4894                                            ARM::VLD1d64QPseudo };
4895       static const uint16_t QOpcodes0[] = { ARM::VLD1q8LowQPseudo_UPD,
4896                                             ARM::VLD1q16LowQPseudo_UPD,
4897                                             ARM::VLD1q32LowQPseudo_UPD,
4898                                             ARM::VLD1q64LowQPseudo_UPD };
4899       static const uint16_t QOpcodes1[] = { ARM::VLD1q8HighQPseudo,
4900                                             ARM::VLD1q16HighQPseudo,
4901                                             ARM::VLD1q32HighQPseudo,
4902                                             ARM::VLD1q64HighQPseudo };
4903       SelectVLD(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
4904       return;
4905     }
4906 
4907     case Intrinsic::arm_neon_vld2: {
4908       static const uint16_t DOpcodes[] = { ARM::VLD2d8, ARM::VLD2d16,
4909                                            ARM::VLD2d32, ARM::VLD1q64 };
4910       static const uint16_t QOpcodes[] = { ARM::VLD2q8Pseudo, ARM::VLD2q16Pseudo,
4911                                            ARM::VLD2q32Pseudo };
4912       SelectVLD(N, false, 2, DOpcodes, QOpcodes, nullptr);
4913       return;
4914     }
4915 
4916     case Intrinsic::arm_neon_vld3: {
4917       static const uint16_t DOpcodes[] = { ARM::VLD3d8Pseudo,
4918                                            ARM::VLD3d16Pseudo,
4919                                            ARM::VLD3d32Pseudo,
4920                                            ARM::VLD1d64TPseudo };
4921       static const uint16_t QOpcodes0[] = { ARM::VLD3q8Pseudo_UPD,
4922                                             ARM::VLD3q16Pseudo_UPD,
4923                                             ARM::VLD3q32Pseudo_UPD };
4924       static const uint16_t QOpcodes1[] = { ARM::VLD3q8oddPseudo,
4925                                             ARM::VLD3q16oddPseudo,
4926                                             ARM::VLD3q32oddPseudo };
4927       SelectVLD(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
4928       return;
4929     }
4930 
4931     case Intrinsic::arm_neon_vld4: {
4932       static const uint16_t DOpcodes[] = { ARM::VLD4d8Pseudo,
4933                                            ARM::VLD4d16Pseudo,
4934                                            ARM::VLD4d32Pseudo,
4935                                            ARM::VLD1d64QPseudo };
4936       static const uint16_t QOpcodes0[] = { ARM::VLD4q8Pseudo_UPD,
4937                                             ARM::VLD4q16Pseudo_UPD,
4938                                             ARM::VLD4q32Pseudo_UPD };
4939       static const uint16_t QOpcodes1[] = { ARM::VLD4q8oddPseudo,
4940                                             ARM::VLD4q16oddPseudo,
4941                                             ARM::VLD4q32oddPseudo };
4942       SelectVLD(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
4943       return;
4944     }
4945 
4946     case Intrinsic::arm_neon_vld2dup: {
4947       static const uint16_t DOpcodes[] = { ARM::VLD2DUPd8, ARM::VLD2DUPd16,
4948                                            ARM::VLD2DUPd32, ARM::VLD1q64 };
4949       static const uint16_t QOpcodes0[] = { ARM::VLD2DUPq8EvenPseudo,
4950                                             ARM::VLD2DUPq16EvenPseudo,
4951                                             ARM::VLD2DUPq32EvenPseudo };
4952       static const uint16_t QOpcodes1[] = { ARM::VLD2DUPq8OddPseudo,
4953                                             ARM::VLD2DUPq16OddPseudo,
4954                                             ARM::VLD2DUPq32OddPseudo };
4955       SelectVLDDup(N, /* IsIntrinsic= */ true, false, 2,
4956                    DOpcodes, QOpcodes0, QOpcodes1);
4957       return;
4958     }
4959 
4960     case Intrinsic::arm_neon_vld3dup: {
4961       static const uint16_t DOpcodes[] = { ARM::VLD3DUPd8Pseudo,
4962                                            ARM::VLD3DUPd16Pseudo,
4963                                            ARM::VLD3DUPd32Pseudo,
4964                                            ARM::VLD1d64TPseudo };
4965       static const uint16_t QOpcodes0[] = { ARM::VLD3DUPq8EvenPseudo,
4966                                             ARM::VLD3DUPq16EvenPseudo,
4967                                             ARM::VLD3DUPq32EvenPseudo };
4968       static const uint16_t QOpcodes1[] = { ARM::VLD3DUPq8OddPseudo,
4969                                             ARM::VLD3DUPq16OddPseudo,
4970                                             ARM::VLD3DUPq32OddPseudo };
4971       SelectVLDDup(N, /* IsIntrinsic= */ true, false, 3,
4972                    DOpcodes, QOpcodes0, QOpcodes1);
4973       return;
4974     }
4975 
4976     case Intrinsic::arm_neon_vld4dup: {
4977       static const uint16_t DOpcodes[] = { ARM::VLD4DUPd8Pseudo,
4978                                            ARM::VLD4DUPd16Pseudo,
4979                                            ARM::VLD4DUPd32Pseudo,
4980                                            ARM::VLD1d64QPseudo };
4981       static const uint16_t QOpcodes0[] = { ARM::VLD4DUPq8EvenPseudo,
4982                                             ARM::VLD4DUPq16EvenPseudo,
4983                                             ARM::VLD4DUPq32EvenPseudo };
4984       static const uint16_t QOpcodes1[] = { ARM::VLD4DUPq8OddPseudo,
4985                                             ARM::VLD4DUPq16OddPseudo,
4986                                             ARM::VLD4DUPq32OddPseudo };
4987       SelectVLDDup(N, /* IsIntrinsic= */ true, false, 4,
4988                    DOpcodes, QOpcodes0, QOpcodes1);
4989       return;
4990     }
4991 
4992     case Intrinsic::arm_neon_vld2lane: {
4993       static const uint16_t DOpcodes[] = { ARM::VLD2LNd8Pseudo,
4994                                            ARM::VLD2LNd16Pseudo,
4995                                            ARM::VLD2LNd32Pseudo };
4996       static const uint16_t QOpcodes[] = { ARM::VLD2LNq16Pseudo,
4997                                            ARM::VLD2LNq32Pseudo };
4998       SelectVLDSTLane(N, true, false, 2, DOpcodes, QOpcodes);
4999       return;
5000     }
5001 
5002     case Intrinsic::arm_neon_vld3lane: {
5003       static const uint16_t DOpcodes[] = { ARM::VLD3LNd8Pseudo,
5004                                            ARM::VLD3LNd16Pseudo,
5005                                            ARM::VLD3LNd32Pseudo };
5006       static const uint16_t QOpcodes[] = { ARM::VLD3LNq16Pseudo,
5007                                            ARM::VLD3LNq32Pseudo };
5008       SelectVLDSTLane(N, true, false, 3, DOpcodes, QOpcodes);
5009       return;
5010     }
5011 
5012     case Intrinsic::arm_neon_vld4lane: {
5013       static const uint16_t DOpcodes[] = { ARM::VLD4LNd8Pseudo,
5014                                            ARM::VLD4LNd16Pseudo,
5015                                            ARM::VLD4LNd32Pseudo };
5016       static const uint16_t QOpcodes[] = { ARM::VLD4LNq16Pseudo,
5017                                            ARM::VLD4LNq32Pseudo };
5018       SelectVLDSTLane(N, true, false, 4, DOpcodes, QOpcodes);
5019       return;
5020     }
5021 
5022     case Intrinsic::arm_neon_vst1: {
5023       static const uint16_t DOpcodes[] = { ARM::VST1d8, ARM::VST1d16,
5024                                            ARM::VST1d32, ARM::VST1d64 };
5025       static const uint16_t QOpcodes[] = { ARM::VST1q8, ARM::VST1q16,
5026                                            ARM::VST1q32, ARM::VST1q64 };
5027       SelectVST(N, false, 1, DOpcodes, QOpcodes, nullptr);
5028       return;
5029     }
5030 
5031     case Intrinsic::arm_neon_vst1x2: {
5032       static const uint16_t DOpcodes[] = { ARM::VST1q8, ARM::VST1q16,
5033                                            ARM::VST1q32, ARM::VST1q64 };
5034       static const uint16_t QOpcodes[] = { ARM::VST1d8QPseudo,
5035                                            ARM::VST1d16QPseudo,
5036                                            ARM::VST1d32QPseudo,
5037                                            ARM::VST1d64QPseudo };
5038       SelectVST(N, false, 2, DOpcodes, QOpcodes, nullptr);
5039       return;
5040     }
5041 
5042     case Intrinsic::arm_neon_vst1x3: {
5043       static const uint16_t DOpcodes[] = { ARM::VST1d8TPseudo,
5044                                            ARM::VST1d16TPseudo,
5045                                            ARM::VST1d32TPseudo,
5046                                            ARM::VST1d64TPseudo };
5047       static const uint16_t QOpcodes0[] = { ARM::VST1q8LowTPseudo_UPD,
5048                                             ARM::VST1q16LowTPseudo_UPD,
5049                                             ARM::VST1q32LowTPseudo_UPD,
5050                                             ARM::VST1q64LowTPseudo_UPD };
5051       static const uint16_t QOpcodes1[] = { ARM::VST1q8HighTPseudo,
5052                                             ARM::VST1q16HighTPseudo,
5053                                             ARM::VST1q32HighTPseudo,
5054                                             ARM::VST1q64HighTPseudo };
5055       SelectVST(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
5056       return;
5057     }
5058 
5059     case Intrinsic::arm_neon_vst1x4: {
5060       static const uint16_t DOpcodes[] = { ARM::VST1d8QPseudo,
5061                                            ARM::VST1d16QPseudo,
5062                                            ARM::VST1d32QPseudo,
5063                                            ARM::VST1d64QPseudo };
5064       static const uint16_t QOpcodes0[] = { ARM::VST1q8LowQPseudo_UPD,
5065                                             ARM::VST1q16LowQPseudo_UPD,
5066                                             ARM::VST1q32LowQPseudo_UPD,
5067                                             ARM::VST1q64LowQPseudo_UPD };
5068       static const uint16_t QOpcodes1[] = { ARM::VST1q8HighQPseudo,
5069                                             ARM::VST1q16HighQPseudo,
5070                                             ARM::VST1q32HighQPseudo,
5071                                             ARM::VST1q64HighQPseudo };
5072       SelectVST(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
5073       return;
5074     }
5075 
5076     case Intrinsic::arm_neon_vst2: {
5077       static const uint16_t DOpcodes[] = { ARM::VST2d8, ARM::VST2d16,
5078                                            ARM::VST2d32, ARM::VST1q64 };
5079       static const uint16_t QOpcodes[] = { ARM::VST2q8Pseudo, ARM::VST2q16Pseudo,
5080                                            ARM::VST2q32Pseudo };
5081       SelectVST(N, false, 2, DOpcodes, QOpcodes, nullptr);
5082       return;
5083     }
5084 
5085     case Intrinsic::arm_neon_vst3: {
5086       static const uint16_t DOpcodes[] = { ARM::VST3d8Pseudo,
5087                                            ARM::VST3d16Pseudo,
5088                                            ARM::VST3d32Pseudo,
5089                                            ARM::VST1d64TPseudo };
5090       static const uint16_t QOpcodes0[] = { ARM::VST3q8Pseudo_UPD,
5091                                             ARM::VST3q16Pseudo_UPD,
5092                                             ARM::VST3q32Pseudo_UPD };
5093       static const uint16_t QOpcodes1[] = { ARM::VST3q8oddPseudo,
5094                                             ARM::VST3q16oddPseudo,
5095                                             ARM::VST3q32oddPseudo };
5096       SelectVST(N, false, 3, DOpcodes, QOpcodes0, QOpcodes1);
5097       return;
5098     }
5099 
5100     case Intrinsic::arm_neon_vst4: {
5101       static const uint16_t DOpcodes[] = { ARM::VST4d8Pseudo,
5102                                            ARM::VST4d16Pseudo,
5103                                            ARM::VST4d32Pseudo,
5104                                            ARM::VST1d64QPseudo };
5105       static const uint16_t QOpcodes0[] = { ARM::VST4q8Pseudo_UPD,
5106                                             ARM::VST4q16Pseudo_UPD,
5107                                             ARM::VST4q32Pseudo_UPD };
5108       static const uint16_t QOpcodes1[] = { ARM::VST4q8oddPseudo,
5109                                             ARM::VST4q16oddPseudo,
5110                                             ARM::VST4q32oddPseudo };
5111       SelectVST(N, false, 4, DOpcodes, QOpcodes0, QOpcodes1);
5112       return;
5113     }
5114 
5115     case Intrinsic::arm_neon_vst2lane: {
5116       static const uint16_t DOpcodes[] = { ARM::VST2LNd8Pseudo,
5117                                            ARM::VST2LNd16Pseudo,
5118                                            ARM::VST2LNd32Pseudo };
5119       static const uint16_t QOpcodes[] = { ARM::VST2LNq16Pseudo,
5120                                            ARM::VST2LNq32Pseudo };
5121       SelectVLDSTLane(N, false, false, 2, DOpcodes, QOpcodes);
5122       return;
5123     }
5124 
5125     case Intrinsic::arm_neon_vst3lane: {
5126       static const uint16_t DOpcodes[] = { ARM::VST3LNd8Pseudo,
5127                                            ARM::VST3LNd16Pseudo,
5128                                            ARM::VST3LNd32Pseudo };
5129       static const uint16_t QOpcodes[] = { ARM::VST3LNq16Pseudo,
5130                                            ARM::VST3LNq32Pseudo };
5131       SelectVLDSTLane(N, false, false, 3, DOpcodes, QOpcodes);
5132       return;
5133     }
5134 
5135     case Intrinsic::arm_neon_vst4lane: {
5136       static const uint16_t DOpcodes[] = { ARM::VST4LNd8Pseudo,
5137                                            ARM::VST4LNd16Pseudo,
5138                                            ARM::VST4LNd32Pseudo };
5139       static const uint16_t QOpcodes[] = { ARM::VST4LNq16Pseudo,
5140                                            ARM::VST4LNq32Pseudo };
5141       SelectVLDSTLane(N, false, false, 4, DOpcodes, QOpcodes);
5142       return;
5143     }
5144 
5145     case Intrinsic::arm_mve_vldr_gather_base_wb:
5146     case Intrinsic::arm_mve_vldr_gather_base_wb_predicated: {
5147       static const uint16_t Opcodes[] = {ARM::MVE_VLDRWU32_qi_pre,
5148                                          ARM::MVE_VLDRDU64_qi_pre};
5149       SelectMVE_WB(N, Opcodes,
5150                    IntNo == Intrinsic::arm_mve_vldr_gather_base_wb_predicated);
5151       return;
5152     }
5153 
5154     case Intrinsic::arm_mve_vld2q: {
5155       static const uint16_t Opcodes8[] = {ARM::MVE_VLD20_8, ARM::MVE_VLD21_8};
5156       static const uint16_t Opcodes16[] = {ARM::MVE_VLD20_16,
5157                                            ARM::MVE_VLD21_16};
5158       static const uint16_t Opcodes32[] = {ARM::MVE_VLD20_32,
5159                                            ARM::MVE_VLD21_32};
5160       static const uint16_t *const Opcodes[] = {Opcodes8, Opcodes16, Opcodes32};
5161       SelectMVE_VLD(N, 2, Opcodes, false);
5162       return;
5163     }
5164 
5165     case Intrinsic::arm_mve_vld4q: {
5166       static const uint16_t Opcodes8[] = {ARM::MVE_VLD40_8, ARM::MVE_VLD41_8,
5167                                           ARM::MVE_VLD42_8, ARM::MVE_VLD43_8};
5168       static const uint16_t Opcodes16[] = {ARM::MVE_VLD40_16, ARM::MVE_VLD41_16,
5169                                            ARM::MVE_VLD42_16,
5170                                            ARM::MVE_VLD43_16};
5171       static const uint16_t Opcodes32[] = {ARM::MVE_VLD40_32, ARM::MVE_VLD41_32,
5172                                            ARM::MVE_VLD42_32,
5173                                            ARM::MVE_VLD43_32};
5174       static const uint16_t *const Opcodes[] = {Opcodes8, Opcodes16, Opcodes32};
5175       SelectMVE_VLD(N, 4, Opcodes, false);
5176       return;
5177     }
5178     }
5179     break;
5180   }
5181 
5182   case ISD::INTRINSIC_WO_CHAIN: {
5183     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5184     switch (IntNo) {
5185     default:
5186       break;
5187 
5188     // Scalar f32 -> bf16
5189     case Intrinsic::arm_neon_vcvtbfp2bf: {
5190       SDLoc dl(N);
5191       const SDValue &Src = N->getOperand(1);
5192       llvm::EVT DestTy = N->getValueType(0);
5193       SDValue Pred = getAL(CurDAG, dl);
5194       SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
5195       SDValue Ops[] = { Src, Src, Pred, Reg0 };
5196       CurDAG->SelectNodeTo(N, ARM::BF16_VCVTB, DestTy, Ops);
5197       return;
5198     }
5199 
5200     // Vector v4f32 -> v4bf16
5201     case Intrinsic::arm_neon_vcvtfp2bf: {
5202       SDLoc dl(N);
5203       const SDValue &Src = N->getOperand(1);
5204       SDValue Pred = getAL(CurDAG, dl);
5205       SDValue Reg0 = CurDAG->getRegister(0, MVT::i32);
5206       SDValue Ops[] = { Src, Pred, Reg0 };
5207       CurDAG->SelectNodeTo(N, ARM::BF16_VCVT, MVT::v4bf16, Ops);
5208       return;
5209     }
5210 
5211     case Intrinsic::arm_mve_urshrl:
5212       SelectMVE_LongShift(N, ARM::MVE_URSHRL, true, false);
5213       return;
5214     case Intrinsic::arm_mve_uqshll:
5215       SelectMVE_LongShift(N, ARM::MVE_UQSHLL, true, false);
5216       return;
5217     case Intrinsic::arm_mve_srshrl:
5218       SelectMVE_LongShift(N, ARM::MVE_SRSHRL, true, false);
5219       return;
5220     case Intrinsic::arm_mve_sqshll:
5221       SelectMVE_LongShift(N, ARM::MVE_SQSHLL, true, false);
5222       return;
5223     case Intrinsic::arm_mve_uqrshll:
5224       SelectMVE_LongShift(N, ARM::MVE_UQRSHLL, false, true);
5225       return;
5226     case Intrinsic::arm_mve_sqrshrl:
5227       SelectMVE_LongShift(N, ARM::MVE_SQRSHRL, false, true);
5228       return;
5229 
5230     case Intrinsic::arm_mve_vadc:
5231     case Intrinsic::arm_mve_vadc_predicated:
5232       SelectMVE_VADCSBC(N, ARM::MVE_VADC, ARM::MVE_VADCI, true,
5233                         IntNo == Intrinsic::arm_mve_vadc_predicated);
5234       return;
5235     case Intrinsic::arm_mve_vsbc:
5236     case Intrinsic::arm_mve_vsbc_predicated:
5237       SelectMVE_VADCSBC(N, ARM::MVE_VSBC, ARM::MVE_VSBCI, true,
5238                         IntNo == Intrinsic::arm_mve_vsbc_predicated);
5239       return;
5240     case Intrinsic::arm_mve_vshlc:
5241     case Intrinsic::arm_mve_vshlc_predicated:
5242       SelectMVE_VSHLC(N, IntNo == Intrinsic::arm_mve_vshlc_predicated);
5243       return;
5244 
5245     case Intrinsic::arm_mve_vmlldava:
5246     case Intrinsic::arm_mve_vmlldava_predicated: {
5247       static const uint16_t OpcodesU[] = {
5248           ARM::MVE_VMLALDAVu16,   ARM::MVE_VMLALDAVu32,
5249           ARM::MVE_VMLALDAVau16,  ARM::MVE_VMLALDAVau32,
5250       };
5251       static const uint16_t OpcodesS[] = {
5252           ARM::MVE_VMLALDAVs16,   ARM::MVE_VMLALDAVs32,
5253           ARM::MVE_VMLALDAVas16,  ARM::MVE_VMLALDAVas32,
5254           ARM::MVE_VMLALDAVxs16,  ARM::MVE_VMLALDAVxs32,
5255           ARM::MVE_VMLALDAVaxs16, ARM::MVE_VMLALDAVaxs32,
5256           ARM::MVE_VMLSLDAVs16,   ARM::MVE_VMLSLDAVs32,
5257           ARM::MVE_VMLSLDAVas16,  ARM::MVE_VMLSLDAVas32,
5258           ARM::MVE_VMLSLDAVxs16,  ARM::MVE_VMLSLDAVxs32,
5259           ARM::MVE_VMLSLDAVaxs16, ARM::MVE_VMLSLDAVaxs32,
5260       };
5261       SelectMVE_VMLLDAV(N, IntNo == Intrinsic::arm_mve_vmlldava_predicated,
5262                         OpcodesS, OpcodesU);
5263       return;
5264     }
5265 
5266     case Intrinsic::arm_mve_vrmlldavha:
5267     case Intrinsic::arm_mve_vrmlldavha_predicated: {
5268       static const uint16_t OpcodesU[] = {
5269           ARM::MVE_VRMLALDAVHu32,  ARM::MVE_VRMLALDAVHau32,
5270       };
5271       static const uint16_t OpcodesS[] = {
5272           ARM::MVE_VRMLALDAVHs32,  ARM::MVE_VRMLALDAVHas32,
5273           ARM::MVE_VRMLALDAVHxs32, ARM::MVE_VRMLALDAVHaxs32,
5274           ARM::MVE_VRMLSLDAVHs32,  ARM::MVE_VRMLSLDAVHas32,
5275           ARM::MVE_VRMLSLDAVHxs32, ARM::MVE_VRMLSLDAVHaxs32,
5276       };
5277       SelectMVE_VRMLLDAVH(N, IntNo == Intrinsic::arm_mve_vrmlldavha_predicated,
5278                           OpcodesS, OpcodesU);
5279       return;
5280     }
5281 
5282     case Intrinsic::arm_mve_vidup:
5283     case Intrinsic::arm_mve_vidup_predicated: {
5284       static const uint16_t Opcodes[] = {
5285           ARM::MVE_VIDUPu8, ARM::MVE_VIDUPu16, ARM::MVE_VIDUPu32,
5286       };
5287       SelectMVE_VxDUP(N, Opcodes, false,
5288                       IntNo == Intrinsic::arm_mve_vidup_predicated);
5289       return;
5290     }
5291 
5292     case Intrinsic::arm_mve_vddup:
5293     case Intrinsic::arm_mve_vddup_predicated: {
5294       static const uint16_t Opcodes[] = {
5295           ARM::MVE_VDDUPu8, ARM::MVE_VDDUPu16, ARM::MVE_VDDUPu32,
5296       };
5297       SelectMVE_VxDUP(N, Opcodes, false,
5298                       IntNo == Intrinsic::arm_mve_vddup_predicated);
5299       return;
5300     }
5301 
5302     case Intrinsic::arm_mve_viwdup:
5303     case Intrinsic::arm_mve_viwdup_predicated: {
5304       static const uint16_t Opcodes[] = {
5305           ARM::MVE_VIWDUPu8, ARM::MVE_VIWDUPu16, ARM::MVE_VIWDUPu32,
5306       };
5307       SelectMVE_VxDUP(N, Opcodes, true,
5308                       IntNo == Intrinsic::arm_mve_viwdup_predicated);
5309       return;
5310     }
5311 
5312     case Intrinsic::arm_mve_vdwdup:
5313     case Intrinsic::arm_mve_vdwdup_predicated: {
5314       static const uint16_t Opcodes[] = {
5315           ARM::MVE_VDWDUPu8, ARM::MVE_VDWDUPu16, ARM::MVE_VDWDUPu32,
5316       };
5317       SelectMVE_VxDUP(N, Opcodes, true,
5318                       IntNo == Intrinsic::arm_mve_vdwdup_predicated);
5319       return;
5320     }
5321 
5322     case Intrinsic::arm_cde_cx1d:
5323     case Intrinsic::arm_cde_cx1da:
5324     case Intrinsic::arm_cde_cx2d:
5325     case Intrinsic::arm_cde_cx2da:
5326     case Intrinsic::arm_cde_cx3d:
5327     case Intrinsic::arm_cde_cx3da: {
5328       bool HasAccum = IntNo == Intrinsic::arm_cde_cx1da ||
5329                       IntNo == Intrinsic::arm_cde_cx2da ||
5330                       IntNo == Intrinsic::arm_cde_cx3da;
5331       size_t NumExtraOps;
5332       uint16_t Opcode;
5333       switch (IntNo) {
5334       case Intrinsic::arm_cde_cx1d:
5335       case Intrinsic::arm_cde_cx1da:
5336         NumExtraOps = 0;
5337         Opcode = HasAccum ? ARM::CDE_CX1DA : ARM::CDE_CX1D;
5338         break;
5339       case Intrinsic::arm_cde_cx2d:
5340       case Intrinsic::arm_cde_cx2da:
5341         NumExtraOps = 1;
5342         Opcode = HasAccum ? ARM::CDE_CX2DA : ARM::CDE_CX2D;
5343         break;
5344       case Intrinsic::arm_cde_cx3d:
5345       case Intrinsic::arm_cde_cx3da:
5346         NumExtraOps = 2;
5347         Opcode = HasAccum ? ARM::CDE_CX3DA : ARM::CDE_CX3D;
5348         break;
5349       default:
5350         llvm_unreachable("Unexpected opcode");
5351       }
5352       SelectCDE_CXxD(N, Opcode, NumExtraOps, HasAccum);
5353       return;
5354     }
5355     }
5356     break;
5357   }
5358 
5359   case ISD::ATOMIC_CMP_SWAP:
5360     SelectCMP_SWAP(N);
5361     return;
5362   }
5363 
5364   SelectCode(N);
5365 }
5366 
5367 // Inspect a register string of the form
5368 // cp<coprocessor>:<opc1>:c<CRn>:c<CRm>:<opc2> (32bit) or
5369 // cp<coprocessor>:<opc1>:c<CRm> (64bit) inspect the fields of the string
5370 // and obtain the integer operands from them, adding these operands to the
5371 // provided vector.
5372 static void getIntOperandsFromRegisterString(StringRef RegString,
5373                                              SelectionDAG *CurDAG,
5374                                              const SDLoc &DL,
5375                                              std::vector<SDValue> &Ops) {
5376   SmallVector<StringRef, 5> Fields;
5377   RegString.split(Fields, ':');
5378 
5379   if (Fields.size() > 1) {
5380     bool AllIntFields = true;
5381 
5382     for (StringRef Field : Fields) {
5383       // Need to trim out leading 'cp' characters and get the integer field.
5384       unsigned IntField;
5385       AllIntFields &= !Field.trim("CPcp").getAsInteger(10, IntField);
5386       Ops.push_back(CurDAG->getTargetConstant(IntField, DL, MVT::i32));
5387     }
5388 
5389     assert(AllIntFields &&
5390             "Unexpected non-integer value in special register string.");
5391     (void)AllIntFields;
5392   }
5393 }
5394 
5395 // Maps a Banked Register string to its mask value. The mask value returned is
5396 // for use in the MRSbanked / MSRbanked instruction nodes as the Banked Register
5397 // mask operand, which expresses which register is to be used, e.g. r8, and in
5398 // which mode it is to be used, e.g. usr. Returns -1 to signify that the string
5399 // was invalid.
5400 static inline int getBankedRegisterMask(StringRef RegString) {
5401   auto TheReg = ARMBankedReg::lookupBankedRegByName(RegString.lower());
5402   if (!TheReg)
5403      return -1;
5404   return TheReg->Encoding;
5405 }
5406 
5407 // The flags here are common to those allowed for apsr in the A class cores and
5408 // those allowed for the special registers in the M class cores. Returns a
5409 // value representing which flags were present, -1 if invalid.
5410 static inline int getMClassFlagsMask(StringRef Flags) {
5411   return StringSwitch<int>(Flags)
5412           .Case("", 0x2) // no flags means nzcvq for psr registers, and 0x2 is
5413                          // correct when flags are not permitted
5414           .Case("g", 0x1)
5415           .Case("nzcvq", 0x2)
5416           .Case("nzcvqg", 0x3)
5417           .Default(-1);
5418 }
5419 
5420 // Maps MClass special registers string to its value for use in the
5421 // t2MRS_M/t2MSR_M instruction nodes as the SYSm value operand.
5422 // Returns -1 to signify that the string was invalid.
5423 static int getMClassRegisterMask(StringRef Reg, const ARMSubtarget *Subtarget) {
5424   auto TheReg = ARMSysReg::lookupMClassSysRegByName(Reg);
5425   const FeatureBitset &FeatureBits = Subtarget->getFeatureBits();
5426   if (!TheReg || !TheReg->hasRequiredFeatures(FeatureBits))
5427     return -1;
5428   return (int)(TheReg->Encoding & 0xFFF); // SYSm value
5429 }
5430 
5431 static int getARClassRegisterMask(StringRef Reg, StringRef Flags) {
5432   // The mask operand contains the special register (R Bit) in bit 4, whether
5433   // the register is spsr (R bit is 1) or one of cpsr/apsr (R bit is 0), and
5434   // bits 3-0 contains the fields to be accessed in the special register, set by
5435   // the flags provided with the register.
5436   int Mask = 0;
5437   if (Reg == "apsr") {
5438     // The flags permitted for apsr are the same flags that are allowed in
5439     // M class registers. We get the flag value and then shift the flags into
5440     // the correct place to combine with the mask.
5441     Mask = getMClassFlagsMask(Flags);
5442     if (Mask == -1)
5443       return -1;
5444     return Mask << 2;
5445   }
5446 
5447   if (Reg != "cpsr" && Reg != "spsr") {
5448     return -1;
5449   }
5450 
5451   // This is the same as if the flags were "fc"
5452   if (Flags.empty() || Flags == "all")
5453     return Mask | 0x9;
5454 
5455   // Inspect the supplied flags string and set the bits in the mask for
5456   // the relevant and valid flags allowed for cpsr and spsr.
5457   for (char Flag : Flags) {
5458     int FlagVal;
5459     switch (Flag) {
5460       case 'c':
5461         FlagVal = 0x1;
5462         break;
5463       case 'x':
5464         FlagVal = 0x2;
5465         break;
5466       case 's':
5467         FlagVal = 0x4;
5468         break;
5469       case 'f':
5470         FlagVal = 0x8;
5471         break;
5472       default:
5473         FlagVal = 0;
5474     }
5475 
5476     // This avoids allowing strings where the same flag bit appears twice.
5477     if (!FlagVal || (Mask & FlagVal))
5478       return -1;
5479     Mask |= FlagVal;
5480   }
5481 
5482   // If the register is spsr then we need to set the R bit.
5483   if (Reg == "spsr")
5484     Mask |= 0x10;
5485 
5486   return Mask;
5487 }
5488 
5489 // Lower the read_register intrinsic to ARM specific DAG nodes
5490 // using the supplied metadata string to select the instruction node to use
5491 // and the registers/masks to construct as operands for the node.
5492 bool ARMDAGToDAGISel::tryReadRegister(SDNode *N){
5493   const auto *MD = cast<MDNodeSDNode>(N->getOperand(1));
5494   const auto *RegString = cast<MDString>(MD->getMD()->getOperand(0));
5495   bool IsThumb2 = Subtarget->isThumb2();
5496   SDLoc DL(N);
5497 
5498   std::vector<SDValue> Ops;
5499   getIntOperandsFromRegisterString(RegString->getString(), CurDAG, DL, Ops);
5500 
5501   if (!Ops.empty()) {
5502     // If the special register string was constructed of fields (as defined
5503     // in the ACLE) then need to lower to MRC node (32 bit) or
5504     // MRRC node(64 bit), we can make the distinction based on the number of
5505     // operands we have.
5506     unsigned Opcode;
5507     SmallVector<EVT, 3> ResTypes;
5508     if (Ops.size() == 5){
5509       Opcode = IsThumb2 ? ARM::t2MRC : ARM::MRC;
5510       ResTypes.append({ MVT::i32, MVT::Other });
5511     } else {
5512       assert(Ops.size() == 3 &&
5513               "Invalid number of fields in special register string.");
5514       Opcode = IsThumb2 ? ARM::t2MRRC : ARM::MRRC;
5515       ResTypes.append({ MVT::i32, MVT::i32, MVT::Other });
5516     }
5517 
5518     Ops.push_back(getAL(CurDAG, DL));
5519     Ops.push_back(CurDAG->getRegister(0, MVT::i32));
5520     Ops.push_back(N->getOperand(0));
5521     ReplaceNode(N, CurDAG->getMachineNode(Opcode, DL, ResTypes, Ops));
5522     return true;
5523   }
5524 
5525   std::string SpecialReg = RegString->getString().lower();
5526 
5527   int BankedReg = getBankedRegisterMask(SpecialReg);
5528   if (BankedReg != -1) {
5529     Ops = { CurDAG->getTargetConstant(BankedReg, DL, MVT::i32),
5530             getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5531             N->getOperand(0) };
5532     ReplaceNode(
5533         N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MRSbanked : ARM::MRSbanked,
5534                                   DL, MVT::i32, MVT::Other, Ops));
5535     return true;
5536   }
5537 
5538   // The VFP registers are read by creating SelectionDAG nodes with opcodes
5539   // corresponding to the register that is being read from. So we switch on the
5540   // string to find which opcode we need to use.
5541   unsigned Opcode = StringSwitch<unsigned>(SpecialReg)
5542                     .Case("fpscr", ARM::VMRS)
5543                     .Case("fpexc", ARM::VMRS_FPEXC)
5544                     .Case("fpsid", ARM::VMRS_FPSID)
5545                     .Case("mvfr0", ARM::VMRS_MVFR0)
5546                     .Case("mvfr1", ARM::VMRS_MVFR1)
5547                     .Case("mvfr2", ARM::VMRS_MVFR2)
5548                     .Case("fpinst", ARM::VMRS_FPINST)
5549                     .Case("fpinst2", ARM::VMRS_FPINST2)
5550                     .Default(0);
5551 
5552   // If an opcode was found then we can lower the read to a VFP instruction.
5553   if (Opcode) {
5554     if (!Subtarget->hasVFP2Base())
5555       return false;
5556     if (Opcode == ARM::VMRS_MVFR2 && !Subtarget->hasFPARMv8Base())
5557       return false;
5558 
5559     Ops = { getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5560             N->getOperand(0) };
5561     ReplaceNode(N,
5562                 CurDAG->getMachineNode(Opcode, DL, MVT::i32, MVT::Other, Ops));
5563     return true;
5564   }
5565 
5566   // If the target is M Class then need to validate that the register string
5567   // is an acceptable value, so check that a mask can be constructed from the
5568   // string.
5569   if (Subtarget->isMClass()) {
5570     int SYSmValue = getMClassRegisterMask(SpecialReg, Subtarget);
5571     if (SYSmValue == -1)
5572       return false;
5573 
5574     SDValue Ops[] = { CurDAG->getTargetConstant(SYSmValue, DL, MVT::i32),
5575                       getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5576                       N->getOperand(0) };
5577     ReplaceNode(
5578         N, CurDAG->getMachineNode(ARM::t2MRS_M, DL, MVT::i32, MVT::Other, Ops));
5579     return true;
5580   }
5581 
5582   // Here we know the target is not M Class so we need to check if it is one
5583   // of the remaining possible values which are apsr, cpsr or spsr.
5584   if (SpecialReg == "apsr" || SpecialReg == "cpsr") {
5585     Ops = { getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5586             N->getOperand(0) };
5587     ReplaceNode(N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MRS_AR : ARM::MRS,
5588                                           DL, MVT::i32, MVT::Other, Ops));
5589     return true;
5590   }
5591 
5592   if (SpecialReg == "spsr") {
5593     Ops = { getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5594             N->getOperand(0) };
5595     ReplaceNode(
5596         N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MRSsys_AR : ARM::MRSsys, DL,
5597                                   MVT::i32, MVT::Other, Ops));
5598     return true;
5599   }
5600 
5601   return false;
5602 }
5603 
5604 // Lower the write_register intrinsic to ARM specific DAG nodes
5605 // using the supplied metadata string to select the instruction node to use
5606 // and the registers/masks to use in the nodes
5607 bool ARMDAGToDAGISel::tryWriteRegister(SDNode *N){
5608   const auto *MD = cast<MDNodeSDNode>(N->getOperand(1));
5609   const auto *RegString = cast<MDString>(MD->getMD()->getOperand(0));
5610   bool IsThumb2 = Subtarget->isThumb2();
5611   SDLoc DL(N);
5612 
5613   std::vector<SDValue> Ops;
5614   getIntOperandsFromRegisterString(RegString->getString(), CurDAG, DL, Ops);
5615 
5616   if (!Ops.empty()) {
5617     // If the special register string was constructed of fields (as defined
5618     // in the ACLE) then need to lower to MCR node (32 bit) or
5619     // MCRR node(64 bit), we can make the distinction based on the number of
5620     // operands we have.
5621     unsigned Opcode;
5622     if (Ops.size() == 5) {
5623       Opcode = IsThumb2 ? ARM::t2MCR : ARM::MCR;
5624       Ops.insert(Ops.begin()+2, N->getOperand(2));
5625     } else {
5626       assert(Ops.size() == 3 &&
5627               "Invalid number of fields in special register string.");
5628       Opcode = IsThumb2 ? ARM::t2MCRR : ARM::MCRR;
5629       SDValue WriteValue[] = { N->getOperand(2), N->getOperand(3) };
5630       Ops.insert(Ops.begin()+2, WriteValue, WriteValue+2);
5631     }
5632 
5633     Ops.push_back(getAL(CurDAG, DL));
5634     Ops.push_back(CurDAG->getRegister(0, MVT::i32));
5635     Ops.push_back(N->getOperand(0));
5636 
5637     ReplaceNode(N, CurDAG->getMachineNode(Opcode, DL, MVT::Other, Ops));
5638     return true;
5639   }
5640 
5641   std::string SpecialReg = RegString->getString().lower();
5642   int BankedReg = getBankedRegisterMask(SpecialReg);
5643   if (BankedReg != -1) {
5644     Ops = { CurDAG->getTargetConstant(BankedReg, DL, MVT::i32), N->getOperand(2),
5645             getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5646             N->getOperand(0) };
5647     ReplaceNode(
5648         N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MSRbanked : ARM::MSRbanked,
5649                                   DL, MVT::Other, Ops));
5650     return true;
5651   }
5652 
5653   // The VFP registers are written to by creating SelectionDAG nodes with
5654   // opcodes corresponding to the register that is being written. So we switch
5655   // on the string to find which opcode we need to use.
5656   unsigned Opcode = StringSwitch<unsigned>(SpecialReg)
5657                     .Case("fpscr", ARM::VMSR)
5658                     .Case("fpexc", ARM::VMSR_FPEXC)
5659                     .Case("fpsid", ARM::VMSR_FPSID)
5660                     .Case("fpinst", ARM::VMSR_FPINST)
5661                     .Case("fpinst2", ARM::VMSR_FPINST2)
5662                     .Default(0);
5663 
5664   if (Opcode) {
5665     if (!Subtarget->hasVFP2Base())
5666       return false;
5667     Ops = { N->getOperand(2), getAL(CurDAG, DL),
5668             CurDAG->getRegister(0, MVT::i32), N->getOperand(0) };
5669     ReplaceNode(N, CurDAG->getMachineNode(Opcode, DL, MVT::Other, Ops));
5670     return true;
5671   }
5672 
5673   std::pair<StringRef, StringRef> Fields;
5674   Fields = StringRef(SpecialReg).rsplit('_');
5675   std::string Reg = Fields.first.str();
5676   StringRef Flags = Fields.second;
5677 
5678   // If the target was M Class then need to validate the special register value
5679   // and retrieve the mask for use in the instruction node.
5680   if (Subtarget->isMClass()) {
5681     int SYSmValue = getMClassRegisterMask(SpecialReg, Subtarget);
5682     if (SYSmValue == -1)
5683       return false;
5684 
5685     SDValue Ops[] = { CurDAG->getTargetConstant(SYSmValue, DL, MVT::i32),
5686                       N->getOperand(2), getAL(CurDAG, DL),
5687                       CurDAG->getRegister(0, MVT::i32), N->getOperand(0) };
5688     ReplaceNode(N, CurDAG->getMachineNode(ARM::t2MSR_M, DL, MVT::Other, Ops));
5689     return true;
5690   }
5691 
5692   // We then check to see if a valid mask can be constructed for one of the
5693   // register string values permitted for the A and R class cores. These values
5694   // are apsr, spsr and cpsr; these are also valid on older cores.
5695   int Mask = getARClassRegisterMask(Reg, Flags);
5696   if (Mask != -1) {
5697     Ops = { CurDAG->getTargetConstant(Mask, DL, MVT::i32), N->getOperand(2),
5698             getAL(CurDAG, DL), CurDAG->getRegister(0, MVT::i32),
5699             N->getOperand(0) };
5700     ReplaceNode(N, CurDAG->getMachineNode(IsThumb2 ? ARM::t2MSR_AR : ARM::MSR,
5701                                           DL, MVT::Other, Ops));
5702     return true;
5703   }
5704 
5705   return false;
5706 }
5707 
5708 bool ARMDAGToDAGISel::tryInlineAsm(SDNode *N){
5709   std::vector<SDValue> AsmNodeOperands;
5710   unsigned Flag, Kind;
5711   bool Changed = false;
5712   unsigned NumOps = N->getNumOperands();
5713 
5714   // Normally, i64 data is bounded to two arbitrary GRPs for "%r" constraint.
5715   // However, some instrstions (e.g. ldrexd/strexd in ARM mode) require
5716   // (even/even+1) GPRs and use %n and %Hn to refer to the individual regs
5717   // respectively. Since there is no constraint to explicitly specify a
5718   // reg pair, we use GPRPair reg class for "%r" for 64-bit data. For Thumb,
5719   // the 64-bit data may be referred by H, Q, R modifiers, so we still pack
5720   // them into a GPRPair.
5721 
5722   SDLoc dl(N);
5723   SDValue Glue = N->getGluedNode() ? N->getOperand(NumOps - 1) : SDValue();
5724 
5725   SmallVector<bool, 8> OpChanged;
5726   // Glue node will be appended late.
5727   for(unsigned i = 0, e = N->getGluedNode() ? NumOps - 1 : NumOps; i < e; ++i) {
5728     SDValue op = N->getOperand(i);
5729     AsmNodeOperands.push_back(op);
5730 
5731     if (i < InlineAsm::Op_FirstOperand)
5732       continue;
5733 
5734     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(i))) {
5735       Flag = C->getZExtValue();
5736       Kind = InlineAsm::getKind(Flag);
5737     }
5738     else
5739       continue;
5740 
5741     // Immediate operands to inline asm in the SelectionDAG are modeled with
5742     // two operands. The first is a constant of value InlineAsm::Kind_Imm, and
5743     // the second is a constant with the value of the immediate. If we get here
5744     // and we have a Kind_Imm, skip the next operand, and continue.
5745     if (Kind == InlineAsm::Kind_Imm) {
5746       SDValue op = N->getOperand(++i);
5747       AsmNodeOperands.push_back(op);
5748       continue;
5749     }
5750 
5751     unsigned NumRegs = InlineAsm::getNumOperandRegisters(Flag);
5752     if (NumRegs)
5753       OpChanged.push_back(false);
5754 
5755     unsigned DefIdx = 0;
5756     bool IsTiedToChangedOp = false;
5757     // If it's a use that is tied with a previous def, it has no
5758     // reg class constraint.
5759     if (Changed && InlineAsm::isUseOperandTiedToDef(Flag, DefIdx))
5760       IsTiedToChangedOp = OpChanged[DefIdx];
5761 
5762     // Memory operands to inline asm in the SelectionDAG are modeled with two
5763     // operands: a constant of value InlineAsm::Kind_Mem followed by the input
5764     // operand. If we get here and we have a Kind_Mem, skip the next operand (so
5765     // it doesn't get misinterpreted), and continue. We do this here because
5766     // it's important to update the OpChanged array correctly before moving on.
5767     if (Kind == InlineAsm::Kind_Mem) {
5768       SDValue op = N->getOperand(++i);
5769       AsmNodeOperands.push_back(op);
5770       continue;
5771     }
5772 
5773     if (Kind != InlineAsm::Kind_RegUse && Kind != InlineAsm::Kind_RegDef
5774         && Kind != InlineAsm::Kind_RegDefEarlyClobber)
5775       continue;
5776 
5777     unsigned RC;
5778     bool HasRC = InlineAsm::hasRegClassConstraint(Flag, RC);
5779     if ((!IsTiedToChangedOp && (!HasRC || RC != ARM::GPRRegClassID))
5780         || NumRegs != 2)
5781       continue;
5782 
5783     assert((i+2 < NumOps) && "Invalid number of operands in inline asm");
5784     SDValue V0 = N->getOperand(i+1);
5785     SDValue V1 = N->getOperand(i+2);
5786     Register Reg0 = cast<RegisterSDNode>(V0)->getReg();
5787     Register Reg1 = cast<RegisterSDNode>(V1)->getReg();
5788     SDValue PairedReg;
5789     MachineRegisterInfo &MRI = MF->getRegInfo();
5790 
5791     if (Kind == InlineAsm::Kind_RegDef ||
5792         Kind == InlineAsm::Kind_RegDefEarlyClobber) {
5793       // Replace the two GPRs with 1 GPRPair and copy values from GPRPair to
5794       // the original GPRs.
5795 
5796       Register GPVR = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
5797       PairedReg = CurDAG->getRegister(GPVR, MVT::Untyped);
5798       SDValue Chain = SDValue(N,0);
5799 
5800       SDNode *GU = N->getGluedUser();
5801       SDValue RegCopy = CurDAG->getCopyFromReg(Chain, dl, GPVR, MVT::Untyped,
5802                                                Chain.getValue(1));
5803 
5804       // Extract values from a GPRPair reg and copy to the original GPR reg.
5805       SDValue Sub0 = CurDAG->getTargetExtractSubreg(ARM::gsub_0, dl, MVT::i32,
5806                                                     RegCopy);
5807       SDValue Sub1 = CurDAG->getTargetExtractSubreg(ARM::gsub_1, dl, MVT::i32,
5808                                                     RegCopy);
5809       SDValue T0 = CurDAG->getCopyToReg(Sub0, dl, Reg0, Sub0,
5810                                         RegCopy.getValue(1));
5811       SDValue T1 = CurDAG->getCopyToReg(Sub1, dl, Reg1, Sub1, T0.getValue(1));
5812 
5813       // Update the original glue user.
5814       std::vector<SDValue> Ops(GU->op_begin(), GU->op_end()-1);
5815       Ops.push_back(T1.getValue(1));
5816       CurDAG->UpdateNodeOperands(GU, Ops);
5817     }
5818     else {
5819       // For Kind  == InlineAsm::Kind_RegUse, we first copy two GPRs into a
5820       // GPRPair and then pass the GPRPair to the inline asm.
5821       SDValue Chain = AsmNodeOperands[InlineAsm::Op_InputChain];
5822 
5823       // As REG_SEQ doesn't take RegisterSDNode, we copy them first.
5824       SDValue T0 = CurDAG->getCopyFromReg(Chain, dl, Reg0, MVT::i32,
5825                                           Chain.getValue(1));
5826       SDValue T1 = CurDAG->getCopyFromReg(Chain, dl, Reg1, MVT::i32,
5827                                           T0.getValue(1));
5828       SDValue Pair = SDValue(createGPRPairNode(MVT::Untyped, T0, T1), 0);
5829 
5830       // Copy REG_SEQ into a GPRPair-typed VR and replace the original two
5831       // i32 VRs of inline asm with it.
5832       Register GPVR = MRI.createVirtualRegister(&ARM::GPRPairRegClass);
5833       PairedReg = CurDAG->getRegister(GPVR, MVT::Untyped);
5834       Chain = CurDAG->getCopyToReg(T1, dl, GPVR, Pair, T1.getValue(1));
5835 
5836       AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
5837       Glue = Chain.getValue(1);
5838     }
5839 
5840     Changed = true;
5841 
5842     if(PairedReg.getNode()) {
5843       OpChanged[OpChanged.size() -1 ] = true;
5844       Flag = InlineAsm::getFlagWord(Kind, 1 /* RegNum*/);
5845       if (IsTiedToChangedOp)
5846         Flag = InlineAsm::getFlagWordForMatchingOp(Flag, DefIdx);
5847       else
5848         Flag = InlineAsm::getFlagWordForRegClass(Flag, ARM::GPRPairRegClassID);
5849       // Replace the current flag.
5850       AsmNodeOperands[AsmNodeOperands.size() -1] = CurDAG->getTargetConstant(
5851           Flag, dl, MVT::i32);
5852       // Add the new register node and skip the original two GPRs.
5853       AsmNodeOperands.push_back(PairedReg);
5854       // Skip the next two GPRs.
5855       i += 2;
5856     }
5857   }
5858 
5859   if (Glue.getNode())
5860     AsmNodeOperands.push_back(Glue);
5861   if (!Changed)
5862     return false;
5863 
5864   SDValue New = CurDAG->getNode(N->getOpcode(), SDLoc(N),
5865       CurDAG->getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
5866   New->setNodeId(-1);
5867   ReplaceNode(N, New.getNode());
5868   return true;
5869 }
5870 
5871 
5872 bool ARMDAGToDAGISel::
5873 SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
5874                              std::vector<SDValue> &OutOps) {
5875   switch(ConstraintID) {
5876   default:
5877     llvm_unreachable("Unexpected asm memory constraint");
5878   case InlineAsm::Constraint_m:
5879   case InlineAsm::Constraint_o:
5880   case InlineAsm::Constraint_Q:
5881   case InlineAsm::Constraint_Um:
5882   case InlineAsm::Constraint_Un:
5883   case InlineAsm::Constraint_Uq:
5884   case InlineAsm::Constraint_Us:
5885   case InlineAsm::Constraint_Ut:
5886   case InlineAsm::Constraint_Uv:
5887   case InlineAsm::Constraint_Uy:
5888     // Require the address to be in a register.  That is safe for all ARM
5889     // variants and it is hard to do anything much smarter without knowing
5890     // how the operand is used.
5891     OutOps.push_back(Op);
5892     return false;
5893   }
5894   return true;
5895 }
5896 
5897 /// createARMISelDag - This pass converts a legalized DAG into a
5898 /// ARM-specific DAG, ready for instruction scheduling.
5899 ///
5900 FunctionPass *llvm::createARMISelDag(ARMBaseTargetMachine &TM,
5901                                      CodeGenOpt::Level OptLevel) {
5902   return new ARMDAGToDAGISel(TM, OptLevel);
5903 }
5904