1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
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 the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "ARMISelLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSelectionDAGInfo.h"
23 #include "ARMSubtarget.h"
24 #include "MCTargetDesc/ARMAddressingModes.h"
25 #include "MCTargetDesc/ARMBaseInfo.h"
26 #include "Utils/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/CodeGen/CallingConvLower.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/IntrinsicLowering.h"
45 #include "llvm/CodeGen/MachineBasicBlock.h"
46 #include "llvm/CodeGen/MachineConstantPool.h"
47 #include "llvm/CodeGen/MachineFrameInfo.h"
48 #include "llvm/CodeGen/MachineFunction.h"
49 #include "llvm/CodeGen/MachineInstr.h"
50 #include "llvm/CodeGen/MachineInstrBuilder.h"
51 #include "llvm/CodeGen/MachineJumpTableInfo.h"
52 #include "llvm/CodeGen/MachineMemOperand.h"
53 #include "llvm/CodeGen/MachineOperand.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/RuntimeLibcalls.h"
56 #include "llvm/CodeGen/SelectionDAG.h"
57 #include "llvm/CodeGen/SelectionDAGNodes.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalValue.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/IRBuilder.h"
76 #include "llvm/IR/InlineAsm.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/Intrinsics.h"
81 #include "llvm/IR/IntrinsicsARM.h"
82 #include "llvm/IR/Module.h"
83 #include "llvm/IR/PatternMatch.h"
84 #include "llvm/IR/Type.h"
85 #include "llvm/IR/User.h"
86 #include "llvm/IR/Value.h"
87 #include "llvm/MC/MCInstrDesc.h"
88 #include "llvm/MC/MCInstrItineraries.h"
89 #include "llvm/MC/MCRegisterInfo.h"
90 #include "llvm/MC/MCSchedule.h"
91 #include "llvm/Support/AtomicOrdering.h"
92 #include "llvm/Support/BranchProbability.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CodeGen.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/ErrorHandling.h"
99 #include "llvm/Support/KnownBits.h"
100 #include "llvm/Support/MachineValueType.h"
101 #include "llvm/Support/MathExtras.h"
102 #include "llvm/Support/raw_ostream.h"
103 #include "llvm/Target/TargetMachine.h"
104 #include "llvm/Target/TargetOptions.h"
105 #include <algorithm>
106 #include <cassert>
107 #include <cstdint>
108 #include <cstdlib>
109 #include <iterator>
110 #include <limits>
111 #include <string>
112 #include <tuple>
113 #include <utility>
114 #include <vector>
115 
116 using namespace llvm;
117 using namespace llvm::PatternMatch;
118 
119 #define DEBUG_TYPE "arm-isel"
120 
121 STATISTIC(NumTailCalls, "Number of tail calls");
122 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
123 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
124 STATISTIC(NumConstpoolPromoted,
125   "Number of constants with their storage promoted into constant pools");
126 
127 static cl::opt<bool>
128 ARMInterworking("arm-interworking", cl::Hidden,
129   cl::desc("Enable / disable ARM interworking (for debugging only)"),
130   cl::init(true));
131 
132 static cl::opt<bool> EnableConstpoolPromotion(
133     "arm-promote-constant", cl::Hidden,
134     cl::desc("Enable / disable promotion of unnamed_addr constants into "
135              "constant pools"),
136     cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
137 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
138     "arm-promote-constant-max-size", cl::Hidden,
139     cl::desc("Maximum size of constant to promote into a constant pool"),
140     cl::init(64));
141 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
142     "arm-promote-constant-max-total", cl::Hidden,
143     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
144     cl::init(128));
145 
146 static cl::opt<unsigned>
147 MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
148   cl::desc("Maximum interleave factor for MVE VLDn to generate."),
149   cl::init(2));
150 
151 // The APCS parameter registers.
152 static const MCPhysReg GPRArgRegs[] = {
153   ARM::R0, ARM::R1, ARM::R2, ARM::R3
154 };
155 
156 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
157                                        MVT PromotedBitwiseVT) {
158   if (VT != PromotedLdStVT) {
159     setOperationAction(ISD::LOAD, VT, Promote);
160     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
161 
162     setOperationAction(ISD::STORE, VT, Promote);
163     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
164   }
165 
166   MVT ElemTy = VT.getVectorElementType();
167   if (ElemTy != MVT::f64)
168     setOperationAction(ISD::SETCC, VT, Custom);
169   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
170   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
171   if (ElemTy == MVT::i32) {
172     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
173     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
174     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
175     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
176   } else {
177     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
178     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
179     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
180     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
181   }
182   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
183   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
184   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
185   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
186   setOperationAction(ISD::SELECT,            VT, Expand);
187   setOperationAction(ISD::SELECT_CC,         VT, Expand);
188   setOperationAction(ISD::VSELECT,           VT, Expand);
189   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
190   if (VT.isInteger()) {
191     setOperationAction(ISD::SHL, VT, Custom);
192     setOperationAction(ISD::SRA, VT, Custom);
193     setOperationAction(ISD::SRL, VT, Custom);
194   }
195 
196   // Promote all bit-wise operations.
197   if (VT.isInteger() && VT != PromotedBitwiseVT) {
198     setOperationAction(ISD::AND, VT, Promote);
199     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
200     setOperationAction(ISD::OR,  VT, Promote);
201     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
202     setOperationAction(ISD::XOR, VT, Promote);
203     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
204   }
205 
206   // Neon does not support vector divide/remainder operations.
207   setOperationAction(ISD::SDIV, VT, Expand);
208   setOperationAction(ISD::UDIV, VT, Expand);
209   setOperationAction(ISD::FDIV, VT, Expand);
210   setOperationAction(ISD::SREM, VT, Expand);
211   setOperationAction(ISD::UREM, VT, Expand);
212   setOperationAction(ISD::FREM, VT, Expand);
213 
214   if (!VT.isFloatingPoint() &&
215       VT != MVT::v2i64 && VT != MVT::v1i64)
216     for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
217       setOperationAction(Opcode, VT, Legal);
218   if (!VT.isFloatingPoint())
219     for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
220       setOperationAction(Opcode, VT, Legal);
221 }
222 
223 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
224   addRegisterClass(VT, &ARM::DPRRegClass);
225   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
226 }
227 
228 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
229   addRegisterClass(VT, &ARM::DPairRegClass);
230   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
231 }
232 
233 void ARMTargetLowering::setAllExpand(MVT VT) {
234   for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
235     setOperationAction(Opc, VT, Expand);
236 
237   // We support these really simple operations even on types where all
238   // the actual arithmetic has to be broken down into simpler
239   // operations or turned into library calls.
240   setOperationAction(ISD::BITCAST, VT, Legal);
241   setOperationAction(ISD::LOAD, VT, Legal);
242   setOperationAction(ISD::STORE, VT, Legal);
243   setOperationAction(ISD::UNDEF, VT, Legal);
244 }
245 
246 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
247                                        LegalizeAction Action) {
248   setLoadExtAction(ISD::EXTLOAD,  From, To, Action);
249   setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
250   setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
251 }
252 
253 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
254   const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
255 
256   for (auto VT : IntTypes) {
257     addRegisterClass(VT, &ARM::MQPRRegClass);
258     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
259     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
260     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
261     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
262     setOperationAction(ISD::SHL, VT, Custom);
263     setOperationAction(ISD::SRA, VT, Custom);
264     setOperationAction(ISD::SRL, VT, Custom);
265     setOperationAction(ISD::SMIN, VT, Legal);
266     setOperationAction(ISD::SMAX, VT, Legal);
267     setOperationAction(ISD::UMIN, VT, Legal);
268     setOperationAction(ISD::UMAX, VT, Legal);
269     setOperationAction(ISD::ABS, VT, Legal);
270     setOperationAction(ISD::SETCC, VT, Custom);
271     setOperationAction(ISD::MLOAD, VT, Custom);
272     setOperationAction(ISD::MSTORE, VT, Legal);
273     setOperationAction(ISD::CTLZ, VT, Legal);
274     setOperationAction(ISD::CTTZ, VT, Custom);
275     setOperationAction(ISD::BITREVERSE, VT, Legal);
276     setOperationAction(ISD::BSWAP, VT, Legal);
277     setOperationAction(ISD::SADDSAT, VT, Legal);
278     setOperationAction(ISD::UADDSAT, VT, Legal);
279     setOperationAction(ISD::SSUBSAT, VT, Legal);
280     setOperationAction(ISD::USUBSAT, VT, Legal);
281 
282     // No native support for these.
283     setOperationAction(ISD::UDIV, VT, Expand);
284     setOperationAction(ISD::SDIV, VT, Expand);
285     setOperationAction(ISD::UREM, VT, Expand);
286     setOperationAction(ISD::SREM, VT, Expand);
287     setOperationAction(ISD::CTPOP, VT, Expand);
288 
289     // Vector reductions
290     setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
291     setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
292     setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
293     setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
294     setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
295 
296     if (!HasMVEFP) {
297       setOperationAction(ISD::SINT_TO_FP, VT, Expand);
298       setOperationAction(ISD::UINT_TO_FP, VT, Expand);
299       setOperationAction(ISD::FP_TO_SINT, VT, Expand);
300       setOperationAction(ISD::FP_TO_UINT, VT, Expand);
301     }
302 
303     // Pre and Post inc are supported on loads and stores
304     for (unsigned im = (unsigned)ISD::PRE_INC;
305          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
306       setIndexedLoadAction(im, VT, Legal);
307       setIndexedStoreAction(im, VT, Legal);
308       setIndexedMaskedLoadAction(im, VT, Legal);
309       setIndexedMaskedStoreAction(im, VT, Legal);
310     }
311   }
312 
313   const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
314   for (auto VT : FloatTypes) {
315     addRegisterClass(VT, &ARM::MQPRRegClass);
316     if (!HasMVEFP)
317       setAllExpand(VT);
318 
319     // These are legal or custom whether we have MVE.fp or not
320     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
321     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
322     setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
323     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
324     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
325     setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
326     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
327     setOperationAction(ISD::SETCC, VT, Custom);
328     setOperationAction(ISD::MLOAD, VT, Custom);
329     setOperationAction(ISD::MSTORE, VT, Legal);
330 
331     // Pre and Post inc are supported on loads and stores
332     for (unsigned im = (unsigned)ISD::PRE_INC;
333          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
334       setIndexedLoadAction(im, VT, Legal);
335       setIndexedStoreAction(im, VT, Legal);
336       setIndexedMaskedLoadAction(im, VT, Legal);
337       setIndexedMaskedStoreAction(im, VT, Legal);
338     }
339 
340     if (HasMVEFP) {
341       setOperationAction(ISD::FMINNUM, VT, Legal);
342       setOperationAction(ISD::FMAXNUM, VT, Legal);
343       setOperationAction(ISD::FROUND, VT, Legal);
344 
345       // No native support for these.
346       setOperationAction(ISD::FDIV, VT, Expand);
347       setOperationAction(ISD::FREM, VT, Expand);
348       setOperationAction(ISD::FSQRT, VT, Expand);
349       setOperationAction(ISD::FSIN, VT, Expand);
350       setOperationAction(ISD::FCOS, VT, Expand);
351       setOperationAction(ISD::FPOW, VT, Expand);
352       setOperationAction(ISD::FLOG, VT, Expand);
353       setOperationAction(ISD::FLOG2, VT, Expand);
354       setOperationAction(ISD::FLOG10, VT, Expand);
355       setOperationAction(ISD::FEXP, VT, Expand);
356       setOperationAction(ISD::FEXP2, VT, Expand);
357       setOperationAction(ISD::FNEARBYINT, VT, Expand);
358     }
359   }
360 
361   // We 'support' these types up to bitcast/load/store level, regardless of
362   // MVE integer-only / float support. Only doing FP data processing on the FP
363   // vector types is inhibited at integer-only level.
364   const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
365   for (auto VT : LongTypes) {
366     addRegisterClass(VT, &ARM::MQPRRegClass);
367     setAllExpand(VT);
368     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
369     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
370     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
371   }
372   // We can do bitwise operations on v2i64 vectors
373   setOperationAction(ISD::AND, MVT::v2i64, Legal);
374   setOperationAction(ISD::OR, MVT::v2i64, Legal);
375   setOperationAction(ISD::XOR, MVT::v2i64, Legal);
376 
377   // It is legal to extload from v4i8 to v4i16 or v4i32.
378   addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
379   addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
380   addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
381 
382   // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
383   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
384   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
385   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
386   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8,  Legal);
387   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal);
388 
389   // Some truncating stores are legal too.
390   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
391   setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
392   setTruncStoreAction(MVT::v8i16, MVT::v8i8,  Legal);
393 
394   // Pre and Post inc on these are legal, given the correct extends
395   for (unsigned im = (unsigned)ISD::PRE_INC;
396        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
397     for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
398       setIndexedLoadAction(im, VT, Legal);
399       setIndexedStoreAction(im, VT, Legal);
400       setIndexedMaskedLoadAction(im, VT, Legal);
401       setIndexedMaskedStoreAction(im, VT, Legal);
402     }
403   }
404 
405   // Predicate types
406   const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
407   for (auto VT : pTypes) {
408     addRegisterClass(VT, &ARM::VCCRRegClass);
409     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
410     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
411     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
412     setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
413     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
414     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
415     setOperationAction(ISD::SETCC, VT, Custom);
416     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
417     setOperationAction(ISD::LOAD, VT, Custom);
418     setOperationAction(ISD::STORE, VT, Custom);
419   }
420 }
421 
422 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
423                                      const ARMSubtarget &STI)
424     : TargetLowering(TM), Subtarget(&STI) {
425   RegInfo = Subtarget->getRegisterInfo();
426   Itins = Subtarget->getInstrItineraryData();
427 
428   setBooleanContents(ZeroOrOneBooleanContent);
429   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
430 
431   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
432       !Subtarget->isTargetWatchOS()) {
433     bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
434     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
435       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
436                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
437                                        : CallingConv::ARM_AAPCS);
438   }
439 
440   if (Subtarget->isTargetMachO()) {
441     // Uses VFP for Thumb libfuncs if available.
442     if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
443         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
444       static const struct {
445         const RTLIB::Libcall Op;
446         const char * const Name;
447         const ISD::CondCode Cond;
448       } LibraryCalls[] = {
449         // Single-precision floating-point arithmetic.
450         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
451         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
452         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
453         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
454 
455         // Double-precision floating-point arithmetic.
456         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
457         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
458         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
459         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
460 
461         // Single-precision comparisons.
462         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
463         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
464         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
465         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
466         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
467         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
468         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
469 
470         // Double-precision comparisons.
471         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
472         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
473         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
474         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
475         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
476         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
477         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
478 
479         // Floating-point to integer conversions.
480         // i64 conversions are done via library routines even when generating VFP
481         // instructions, so use the same ones.
482         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
483         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
484         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
485         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
486 
487         // Conversions between floating types.
488         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
489         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
490 
491         // Integer to floating-point conversions.
492         // i64 conversions are done via library routines even when generating VFP
493         // instructions, so use the same ones.
494         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
495         // e.g., __floatunsidf vs. __floatunssidfvfp.
496         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
497         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
498         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
499         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
500       };
501 
502       for (const auto &LC : LibraryCalls) {
503         setLibcallName(LC.Op, LC.Name);
504         if (LC.Cond != ISD::SETCC_INVALID)
505           setCmpLibcallCC(LC.Op, LC.Cond);
506       }
507     }
508   }
509 
510   // These libcalls are not available in 32-bit.
511   setLibcallName(RTLIB::SHL_I128, nullptr);
512   setLibcallName(RTLIB::SRL_I128, nullptr);
513   setLibcallName(RTLIB::SRA_I128, nullptr);
514 
515   // RTLIB
516   if (Subtarget->isAAPCS_ABI() &&
517       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
518        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
519     static const struct {
520       const RTLIB::Libcall Op;
521       const char * const Name;
522       const CallingConv::ID CC;
523       const ISD::CondCode Cond;
524     } LibraryCalls[] = {
525       // Double-precision floating-point arithmetic helper functions
526       // RTABI chapter 4.1.2, Table 2
527       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
528       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
529       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
530       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
531 
532       // Double-precision floating-point comparison helper functions
533       // RTABI chapter 4.1.2, Table 3
534       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
535       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
536       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
537       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
538       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
539       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
540       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
541 
542       // Single-precision floating-point arithmetic helper functions
543       // RTABI chapter 4.1.2, Table 4
544       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
545       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
546       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
547       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
548 
549       // Single-precision floating-point comparison helper functions
550       // RTABI chapter 4.1.2, Table 5
551       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
552       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
553       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
554       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
555       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
556       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
557       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
558 
559       // Floating-point to integer conversions.
560       // RTABI chapter 4.1.2, Table 6
561       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
562       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
563       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
564       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
565       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
566       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
567       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
568       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
569 
570       // Conversions between floating types.
571       // RTABI chapter 4.1.2, Table 7
572       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
573       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
574       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
575 
576       // Integer to floating-point conversions.
577       // RTABI chapter 4.1.2, Table 8
578       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
579       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
580       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
581       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
582       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
583       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
584       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
585       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
586 
587       // Long long helper functions
588       // RTABI chapter 4.2, Table 9
589       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
590       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
591       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
592       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
593 
594       // Integer division functions
595       // RTABI chapter 4.3.1
596       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
597       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
598       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
599       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
600       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
601       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
602       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
603       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
604     };
605 
606     for (const auto &LC : LibraryCalls) {
607       setLibcallName(LC.Op, LC.Name);
608       setLibcallCallingConv(LC.Op, LC.CC);
609       if (LC.Cond != ISD::SETCC_INVALID)
610         setCmpLibcallCC(LC.Op, LC.Cond);
611     }
612 
613     // EABI dependent RTLIB
614     if (TM.Options.EABIVersion == EABI::EABI4 ||
615         TM.Options.EABIVersion == EABI::EABI5) {
616       static const struct {
617         const RTLIB::Libcall Op;
618         const char *const Name;
619         const CallingConv::ID CC;
620         const ISD::CondCode Cond;
621       } MemOpsLibraryCalls[] = {
622         // Memory operations
623         // RTABI chapter 4.3.4
624         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
625         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
626         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
627       };
628 
629       for (const auto &LC : MemOpsLibraryCalls) {
630         setLibcallName(LC.Op, LC.Name);
631         setLibcallCallingConv(LC.Op, LC.CC);
632         if (LC.Cond != ISD::SETCC_INVALID)
633           setCmpLibcallCC(LC.Op, LC.Cond);
634       }
635     }
636   }
637 
638   if (Subtarget->isTargetWindows()) {
639     static const struct {
640       const RTLIB::Libcall Op;
641       const char * const Name;
642       const CallingConv::ID CC;
643     } LibraryCalls[] = {
644       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
645       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
646       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
647       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
648       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
649       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
650       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
651       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
652     };
653 
654     for (const auto &LC : LibraryCalls) {
655       setLibcallName(LC.Op, LC.Name);
656       setLibcallCallingConv(LC.Op, LC.CC);
657     }
658   }
659 
660   // Use divmod compiler-rt calls for iOS 5.0 and later.
661   if (Subtarget->isTargetMachO() &&
662       !(Subtarget->isTargetIOS() &&
663         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
664     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
665     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
666   }
667 
668   // The half <-> float conversion functions are always soft-float on
669   // non-watchos platforms, but are needed for some targets which use a
670   // hard-float calling convention by default.
671   if (!Subtarget->isTargetWatchABI()) {
672     if (Subtarget->isAAPCS_ABI()) {
673       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
674       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
675       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
676     } else {
677       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
678       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
679       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
680     }
681   }
682 
683   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
684   // a __gnu_ prefix (which is the default).
685   if (Subtarget->isTargetAEABI()) {
686     static const struct {
687       const RTLIB::Libcall Op;
688       const char * const Name;
689       const CallingConv::ID CC;
690     } LibraryCalls[] = {
691       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
692       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
693       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
694     };
695 
696     for (const auto &LC : LibraryCalls) {
697       setLibcallName(LC.Op, LC.Name);
698       setLibcallCallingConv(LC.Op, LC.CC);
699     }
700   }
701 
702   if (Subtarget->isThumb1Only())
703     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
704   else
705     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
706 
707   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
708       Subtarget->hasFPRegs()) {
709     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
710     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
711     if (!Subtarget->hasVFP2Base())
712       setAllExpand(MVT::f32);
713     if (!Subtarget->hasFP64())
714       setAllExpand(MVT::f64);
715   }
716 
717   if (Subtarget->hasFullFP16()) {
718     addRegisterClass(MVT::f16, &ARM::HPRRegClass);
719     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
720     setOperationAction(ISD::BITCAST, MVT::f16, Custom);
721 
722     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
723     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
724   }
725 
726   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
727     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
728       setTruncStoreAction(VT, InnerVT, Expand);
729       addAllExtLoads(VT, InnerVT, Expand);
730     }
731 
732     setOperationAction(ISD::MULHS, VT, Expand);
733     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
734     setOperationAction(ISD::MULHU, VT, Expand);
735     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
736 
737     setOperationAction(ISD::BSWAP, VT, Expand);
738   }
739 
740   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
741   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
742 
743   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
744   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
745 
746   if (Subtarget->hasMVEIntegerOps())
747     addMVEVectorTypes(Subtarget->hasMVEFloatOps());
748 
749   // Combine low-overhead loop intrinsics so that we can lower i1 types.
750   if (Subtarget->hasLOB()) {
751     setTargetDAGCombine(ISD::BRCOND);
752     setTargetDAGCombine(ISD::BR_CC);
753   }
754 
755   if (Subtarget->hasNEON()) {
756     addDRTypeForNEON(MVT::v2f32);
757     addDRTypeForNEON(MVT::v8i8);
758     addDRTypeForNEON(MVT::v4i16);
759     addDRTypeForNEON(MVT::v2i32);
760     addDRTypeForNEON(MVT::v1i64);
761 
762     addQRTypeForNEON(MVT::v4f32);
763     addQRTypeForNEON(MVT::v2f64);
764     addQRTypeForNEON(MVT::v16i8);
765     addQRTypeForNEON(MVT::v8i16);
766     addQRTypeForNEON(MVT::v4i32);
767     addQRTypeForNEON(MVT::v2i64);
768 
769     if (Subtarget->hasFullFP16()) {
770       addQRTypeForNEON(MVT::v8f16);
771       addDRTypeForNEON(MVT::v4f16);
772     }
773   }
774 
775   if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
776     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
777     // none of Neon, MVE or VFP supports any arithmetic operations on it.
778     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
779     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
780     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
781     // FIXME: Code duplication: FDIV and FREM are expanded always, see
782     // ARMTargetLowering::addTypeForNEON method for details.
783     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
784     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
785     // FIXME: Create unittest.
786     // In another words, find a way when "copysign" appears in DAG with vector
787     // operands.
788     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
789     // FIXME: Code duplication: SETCC has custom operation action, see
790     // ARMTargetLowering::addTypeForNEON method for details.
791     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
792     // FIXME: Create unittest for FNEG and for FABS.
793     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
794     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
795     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
796     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
797     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
798     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
799     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
800     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
801     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
802     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
803     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
804     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
805     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
806     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
807     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
808     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
809     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
810     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
811   }
812 
813   if (Subtarget->hasNEON()) {
814     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
815     // supported for v4f32.
816     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
817     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
818     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
819     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
820     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
821     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
822     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
823     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
824     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
825     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
826     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
827     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
828     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
829     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
830 
831     // Mark v2f32 intrinsics.
832     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
833     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
834     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
835     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
836     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
837     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
838     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
839     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
840     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
841     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
842     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
843     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
844     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
845     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
846 
847     // Neon does not support some operations on v1i64 and v2i64 types.
848     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
849     // Custom handling for some quad-vector types to detect VMULL.
850     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
851     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
852     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
853     // Custom handling for some vector types to avoid expensive expansions
854     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
855     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
856     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
857     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
858     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
859     // a destination type that is wider than the source, and nor does
860     // it have a FP_TO_[SU]INT instruction with a narrower destination than
861     // source.
862     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
863     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
864     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
865     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
866     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
867     setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
868     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
869     setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
870 
871     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
872     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
873 
874     // NEON does not have single instruction CTPOP for vectors with element
875     // types wider than 8-bits.  However, custom lowering can leverage the
876     // v8i8/v16i8 vcnt instruction.
877     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
878     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
879     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
880     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
881     setOperationAction(ISD::CTPOP,      MVT::v1i64, Custom);
882     setOperationAction(ISD::CTPOP,      MVT::v2i64, Custom);
883 
884     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
885     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
886 
887     // NEON does not have single instruction CTTZ for vectors.
888     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
889     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
890     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
891     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
892 
893     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
894     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
895     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
896     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
897 
898     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
899     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
900     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
901     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
902 
903     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
904     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
905     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
906     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
907 
908     // NEON only has FMA instructions as of VFP4.
909     if (!Subtarget->hasVFP4Base()) {
910       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
911       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
912     }
913 
914     setTargetDAGCombine(ISD::SHL);
915     setTargetDAGCombine(ISD::SRL);
916     setTargetDAGCombine(ISD::SRA);
917     setTargetDAGCombine(ISD::FP_TO_SINT);
918     setTargetDAGCombine(ISD::FP_TO_UINT);
919     setTargetDAGCombine(ISD::FDIV);
920     setTargetDAGCombine(ISD::LOAD);
921 
922     // It is legal to extload from v4i8 to v4i16 or v4i32.
923     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
924                    MVT::v2i32}) {
925       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
926         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
927         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
928         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
929       }
930     }
931   }
932 
933   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
934     setTargetDAGCombine(ISD::BUILD_VECTOR);
935     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
936     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
937     setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
938     setTargetDAGCombine(ISD::STORE);
939     setTargetDAGCombine(ISD::SIGN_EXTEND);
940     setTargetDAGCombine(ISD::ZERO_EXTEND);
941     setTargetDAGCombine(ISD::ANY_EXTEND);
942     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
943     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
944     setTargetDAGCombine(ISD::INTRINSIC_VOID);
945     setTargetDAGCombine(ISD::VECREDUCE_ADD);
946     setTargetDAGCombine(ISD::ADD);
947     setTargetDAGCombine(ISD::BITCAST);
948   }
949   if (Subtarget->hasMVEIntegerOps()) {
950     setTargetDAGCombine(ISD::SMIN);
951     setTargetDAGCombine(ISD::UMIN);
952     setTargetDAGCombine(ISD::SMAX);
953     setTargetDAGCombine(ISD::UMAX);
954   }
955 
956   if (!Subtarget->hasFP64()) {
957     // When targeting a floating-point unit with only single-precision
958     // operations, f64 is legal for the few double-precision instructions which
959     // are present However, no double-precision operations other than moves,
960     // loads and stores are provided by the hardware.
961     setOperationAction(ISD::FADD,       MVT::f64, Expand);
962     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
963     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
964     setOperationAction(ISD::FMA,        MVT::f64, Expand);
965     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
966     setOperationAction(ISD::FREM,       MVT::f64, Expand);
967     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
968     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
969     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
970     setOperationAction(ISD::FABS,       MVT::f64, Expand);
971     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
972     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
973     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
974     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
975     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
976     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
977     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
978     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
979     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
980     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
981     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
982     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
983     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
984     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
985     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
986     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
987     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
988     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
989     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
990     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
991     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
992     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
993     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
994     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
995     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
996     setOperationAction(ISD::STRICT_FP_ROUND,   MVT::f32, Custom);
997   }
998 
999   if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
1000     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
1001     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
1002     if (Subtarget->hasFullFP16()) {
1003       setOperationAction(ISD::FP_ROUND,  MVT::f16, Custom);
1004       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
1005     }
1006   }
1007 
1008   if (!Subtarget->hasFP16()) {
1009     setOperationAction(ISD::FP_EXTEND,  MVT::f32, Custom);
1010     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1011   }
1012 
1013   computeRegisterProperties(Subtarget->getRegisterInfo());
1014 
1015   // ARM does not have floating-point extending loads.
1016   for (MVT VT : MVT::fp_valuetypes()) {
1017     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1018     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1019   }
1020 
1021   // ... or truncating stores
1022   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1023   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1024   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1025 
1026   // ARM does not have i1 sign extending load.
1027   for (MVT VT : MVT::integer_valuetypes())
1028     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1029 
1030   // ARM supports all 4 flavors of integer indexed load / store.
1031   if (!Subtarget->isThumb1Only()) {
1032     for (unsigned im = (unsigned)ISD::PRE_INC;
1033          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1034       setIndexedLoadAction(im,  MVT::i1,  Legal);
1035       setIndexedLoadAction(im,  MVT::i8,  Legal);
1036       setIndexedLoadAction(im,  MVT::i16, Legal);
1037       setIndexedLoadAction(im,  MVT::i32, Legal);
1038       setIndexedStoreAction(im, MVT::i1,  Legal);
1039       setIndexedStoreAction(im, MVT::i8,  Legal);
1040       setIndexedStoreAction(im, MVT::i16, Legal);
1041       setIndexedStoreAction(im, MVT::i32, Legal);
1042     }
1043   } else {
1044     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1045     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
1046     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
1047   }
1048 
1049   setOperationAction(ISD::SADDO, MVT::i32, Custom);
1050   setOperationAction(ISD::UADDO, MVT::i32, Custom);
1051   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1052   setOperationAction(ISD::USUBO, MVT::i32, Custom);
1053 
1054   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1055   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1056   if (Subtarget->hasDSP()) {
1057     setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1058     setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1059     setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1060     setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1061   }
1062   if (Subtarget->hasBaseDSP()) {
1063     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1064     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1065   }
1066 
1067   // i64 operation support.
1068   setOperationAction(ISD::MUL,     MVT::i64, Expand);
1069   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
1070   if (Subtarget->isThumb1Only()) {
1071     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1072     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1073   }
1074   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1075       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1076     setOperationAction(ISD::MULHS, MVT::i32, Expand);
1077 
1078   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1079   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1080   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1081   setOperationAction(ISD::SRL,       MVT::i64, Custom);
1082   setOperationAction(ISD::SRA,       MVT::i64, Custom);
1083   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1084   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1085   setOperationAction(ISD::LOAD, MVT::i64, Custom);
1086   setOperationAction(ISD::STORE, MVT::i64, Custom);
1087 
1088   // MVE lowers 64 bit shifts to lsll and lsrl
1089   // assuming that ISD::SRL and SRA of i64 are already marked custom
1090   if (Subtarget->hasMVEIntegerOps())
1091     setOperationAction(ISD::SHL, MVT::i64, Custom);
1092 
1093   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1094   if (Subtarget->isThumb1Only()) {
1095     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1096     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1097     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1098   }
1099 
1100   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1101     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1102 
1103   // ARM does not have ROTL.
1104   setOperationAction(ISD::ROTL, MVT::i32, Expand);
1105   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1106     setOperationAction(ISD::ROTL, VT, Expand);
1107     setOperationAction(ISD::ROTR, VT, Expand);
1108   }
1109   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
1110   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1111   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1112     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1113     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1114   }
1115 
1116   // @llvm.readcyclecounter requires the Performance Monitors extension.
1117   // Default to the 0 expansion on unsupported platforms.
1118   // FIXME: Technically there are older ARM CPUs that have
1119   // implementation-specific ways of obtaining this information.
1120   if (Subtarget->hasPerfMon())
1121     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1122 
1123   // Only ARMv6 has BSWAP.
1124   if (!Subtarget->hasV6Ops())
1125     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1126 
1127   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1128                                         : Subtarget->hasDivideInARMMode();
1129   if (!hasDivide) {
1130     // These are expanded into libcalls if the cpu doesn't have HW divider.
1131     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
1132     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
1133   }
1134 
1135   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1136     setOperationAction(ISD::SDIV, MVT::i32, Custom);
1137     setOperationAction(ISD::UDIV, MVT::i32, Custom);
1138 
1139     setOperationAction(ISD::SDIV, MVT::i64, Custom);
1140     setOperationAction(ISD::UDIV, MVT::i64, Custom);
1141   }
1142 
1143   setOperationAction(ISD::SREM,  MVT::i32, Expand);
1144   setOperationAction(ISD::UREM,  MVT::i32, Expand);
1145 
1146   // Register based DivRem for AEABI (RTABI 4.2)
1147   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1148       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1149       Subtarget->isTargetWindows()) {
1150     setOperationAction(ISD::SREM, MVT::i64, Custom);
1151     setOperationAction(ISD::UREM, MVT::i64, Custom);
1152     HasStandaloneRem = false;
1153 
1154     if (Subtarget->isTargetWindows()) {
1155       const struct {
1156         const RTLIB::Libcall Op;
1157         const char * const Name;
1158         const CallingConv::ID CC;
1159       } LibraryCalls[] = {
1160         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1161         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1162         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1163         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1164 
1165         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1166         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1167         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1168         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1169       };
1170 
1171       for (const auto &LC : LibraryCalls) {
1172         setLibcallName(LC.Op, LC.Name);
1173         setLibcallCallingConv(LC.Op, LC.CC);
1174       }
1175     } else {
1176       const struct {
1177         const RTLIB::Libcall Op;
1178         const char * const Name;
1179         const CallingConv::ID CC;
1180       } LibraryCalls[] = {
1181         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1182         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1183         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1184         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1185 
1186         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1187         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1188         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1189         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1190       };
1191 
1192       for (const auto &LC : LibraryCalls) {
1193         setLibcallName(LC.Op, LC.Name);
1194         setLibcallCallingConv(LC.Op, LC.CC);
1195       }
1196     }
1197 
1198     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1199     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1200     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1201     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1202   } else {
1203     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1204     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1205   }
1206 
1207   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
1208     // MSVCRT doesn't have powi; fall back to pow
1209     setLibcallName(RTLIB::POWI_F32, nullptr);
1210     setLibcallName(RTLIB::POWI_F64, nullptr);
1211   }
1212 
1213   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
1214   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
1215   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1216   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1217 
1218   setOperationAction(ISD::TRAP, MVT::Other, Legal);
1219   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1220 
1221   // Use the default implementation.
1222   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
1223   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
1224   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
1225   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
1226   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
1227   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
1228 
1229   if (Subtarget->isTargetWindows())
1230     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1231   else
1232     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1233 
1234   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1235   // the default expansion.
1236   InsertFencesForAtomic = false;
1237   if (Subtarget->hasAnyDataBarrier() &&
1238       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1239     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1240     // to ldrex/strex loops already.
1241     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
1242     if (!Subtarget->isThumb() || !Subtarget->isMClass())
1243       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
1244 
1245     // On v8, we have particularly efficient implementations of atomic fences
1246     // if they can be combined with nearby atomic loads and stores.
1247     if (!Subtarget->hasAcquireRelease() ||
1248         getTargetMachine().getOptLevel() == 0) {
1249       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1250       InsertFencesForAtomic = true;
1251     }
1252   } else {
1253     // If there's anything we can use as a barrier, go through custom lowering
1254     // for ATOMIC_FENCE.
1255     // If target has DMB in thumb, Fences can be inserted.
1256     if (Subtarget->hasDataBarrier())
1257       InsertFencesForAtomic = true;
1258 
1259     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1260                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1261 
1262     // Set them all for expansion, which will force libcalls.
1263     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1264     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1265     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1266     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1267     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1268     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1269     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1270     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1271     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1272     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1273     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1274     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1275     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1276     // Unordered/Monotonic case.
1277     if (!InsertFencesForAtomic) {
1278       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1279       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1280     }
1281   }
1282 
1283   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1284 
1285   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1286   if (!Subtarget->hasV6Ops()) {
1287     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1288     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1289   }
1290   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1291 
1292   if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1293       !Subtarget->isThumb1Only()) {
1294     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1295     // iff target supports vfp2.
1296     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1297     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1298   }
1299 
1300   // We want to custom lower some of our intrinsics.
1301   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1302   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1303   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1304   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1305   if (Subtarget->useSjLjEH())
1306     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1307 
1308   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1309   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1310   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1311   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1312   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1313   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1314   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1315   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1316   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1317   if (Subtarget->hasFullFP16()) {
1318     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1319     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1320     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1321   }
1322 
1323   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1324 
1325   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1326   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1327   if (Subtarget->hasFullFP16())
1328       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1329   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1330   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1331   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1332 
1333   // We don't support sin/cos/fmod/copysign/pow
1334   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1335   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1336   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1337   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1338   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1339   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1340   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1341   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1342   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1343       !Subtarget->isThumb1Only()) {
1344     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1345     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1346   }
1347   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1348   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1349 
1350   if (!Subtarget->hasVFP4Base()) {
1351     setOperationAction(ISD::FMA, MVT::f64, Expand);
1352     setOperationAction(ISD::FMA, MVT::f32, Expand);
1353   }
1354 
1355   // Various VFP goodness
1356   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1357     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1358     if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1359       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1360       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1361     }
1362 
1363     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1364     if (!Subtarget->hasFP16()) {
1365       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1366       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1367     }
1368 
1369     // Strict floating-point comparisons need custom lowering.
1370     setOperationAction(ISD::STRICT_FSETCC,  MVT::f16, Custom);
1371     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
1372     setOperationAction(ISD::STRICT_FSETCC,  MVT::f32, Custom);
1373     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
1374     setOperationAction(ISD::STRICT_FSETCC,  MVT::f64, Custom);
1375     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
1376   }
1377 
1378   // Use __sincos_stret if available.
1379   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1380       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1381     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1382     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1383   }
1384 
1385   // FP-ARMv8 implements a lot of rounding-like FP operations.
1386   if (Subtarget->hasFPARMv8Base()) {
1387     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1388     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1389     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1390     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1391     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1392     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1393     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1394     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1395     if (Subtarget->hasNEON()) {
1396       setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1397       setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1398       setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1399       setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1400     }
1401 
1402     if (Subtarget->hasFP64()) {
1403       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1404       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1405       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1406       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1407       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1408       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1409       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1410       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1411     }
1412   }
1413 
1414   // FP16 often need to be promoted to call lib functions
1415   if (Subtarget->hasFullFP16()) {
1416     setOperationAction(ISD::FREM, MVT::f16, Promote);
1417     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1418     setOperationAction(ISD::FSIN, MVT::f16, Promote);
1419     setOperationAction(ISD::FCOS, MVT::f16, Promote);
1420     setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1421     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1422     setOperationAction(ISD::FPOW, MVT::f16, Promote);
1423     setOperationAction(ISD::FEXP, MVT::f16, Promote);
1424     setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1425     setOperationAction(ISD::FLOG, MVT::f16, Promote);
1426     setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1427     setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1428 
1429     setOperationAction(ISD::FROUND, MVT::f16, Legal);
1430   }
1431 
1432   if (Subtarget->hasNEON()) {
1433     // vmin and vmax aren't available in a scalar form, so we can use
1434     // a NEON instruction with an undef lane instead.  This has a performance
1435     // penalty on some cores, so we don't do this unless we have been
1436     // asked to by the core tuning model.
1437     if (Subtarget->useNEONForSinglePrecisionFP()) {
1438       setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1439       setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1440       setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1441       setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1442     }
1443     setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1444     setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1445     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1446     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1447 
1448     if (Subtarget->hasFullFP16()) {
1449       setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1450       setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1451       setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1452       setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1453 
1454       setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1455       setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1456       setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1457       setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1458     }
1459   }
1460 
1461   // We have target-specific dag combine patterns for the following nodes:
1462   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1463   setTargetDAGCombine(ISD::ADD);
1464   setTargetDAGCombine(ISD::SUB);
1465   setTargetDAGCombine(ISD::MUL);
1466   setTargetDAGCombine(ISD::AND);
1467   setTargetDAGCombine(ISD::OR);
1468   setTargetDAGCombine(ISD::XOR);
1469 
1470   if (Subtarget->hasMVEIntegerOps())
1471     setTargetDAGCombine(ISD::VSELECT);
1472 
1473   if (Subtarget->hasV6Ops())
1474     setTargetDAGCombine(ISD::SRL);
1475   if (Subtarget->isThumb1Only())
1476     setTargetDAGCombine(ISD::SHL);
1477 
1478   setStackPointerRegisterToSaveRestore(ARM::SP);
1479 
1480   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1481       !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1482     setSchedulingPreference(Sched::RegPressure);
1483   else
1484     setSchedulingPreference(Sched::Hybrid);
1485 
1486   //// temporary - rewrite interface to use type
1487   MaxStoresPerMemset = 8;
1488   MaxStoresPerMemsetOptSize = 4;
1489   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1490   MaxStoresPerMemcpyOptSize = 2;
1491   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1492   MaxStoresPerMemmoveOptSize = 2;
1493 
1494   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1495   // are at least 4 bytes aligned.
1496   setMinStackArgumentAlignment(Align(4));
1497 
1498   // Prefer likely predicted branches to selects on out-of-order cores.
1499   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1500 
1501   setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1502 
1503   setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1504 
1505   if (Subtarget->isThumb() || Subtarget->isThumb2())
1506     setTargetDAGCombine(ISD::ABS);
1507 }
1508 
1509 bool ARMTargetLowering::useSoftFloat() const {
1510   return Subtarget->useSoftFloat();
1511 }
1512 
1513 // FIXME: It might make sense to define the representative register class as the
1514 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1515 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1516 // SPR's representative would be DPR_VFP2. This should work well if register
1517 // pressure tracking were modified such that a register use would increment the
1518 // pressure of the register class's representative and all of it's super
1519 // classes' representatives transitively. We have not implemented this because
1520 // of the difficulty prior to coalescing of modeling operand register classes
1521 // due to the common occurrence of cross class copies and subregister insertions
1522 // and extractions.
1523 std::pair<const TargetRegisterClass *, uint8_t>
1524 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1525                                            MVT VT) const {
1526   const TargetRegisterClass *RRC = nullptr;
1527   uint8_t Cost = 1;
1528   switch (VT.SimpleTy) {
1529   default:
1530     return TargetLowering::findRepresentativeClass(TRI, VT);
1531   // Use DPR as representative register class for all floating point
1532   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1533   // the cost is 1 for both f32 and f64.
1534   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1535   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1536     RRC = &ARM::DPRRegClass;
1537     // When NEON is used for SP, only half of the register file is available
1538     // because operations that define both SP and DP results will be constrained
1539     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1540     // coalescing by double-counting the SP regs. See the FIXME above.
1541     if (Subtarget->useNEONForSinglePrecisionFP())
1542       Cost = 2;
1543     break;
1544   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1545   case MVT::v4f32: case MVT::v2f64:
1546     RRC = &ARM::DPRRegClass;
1547     Cost = 2;
1548     break;
1549   case MVT::v4i64:
1550     RRC = &ARM::DPRRegClass;
1551     Cost = 4;
1552     break;
1553   case MVT::v8i64:
1554     RRC = &ARM::DPRRegClass;
1555     Cost = 8;
1556     break;
1557   }
1558   return std::make_pair(RRC, Cost);
1559 }
1560 
1561 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1562   switch ((ARMISD::NodeType)Opcode) {
1563   case ARMISD::FIRST_NUMBER:  break;
1564   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1565   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1566   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1567   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1568   case ARMISD::CALL:          return "ARMISD::CALL";
1569   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1570   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1571   case ARMISD::tSECALL:       return "ARMISD::tSECALL";
1572   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1573   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1574   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1575   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1576   case ARMISD::SERET_FLAG:    return "ARMISD::SERET_FLAG";
1577   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1578   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1579   case ARMISD::CMP:           return "ARMISD::CMP";
1580   case ARMISD::CMN:           return "ARMISD::CMN";
1581   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1582   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1583   case ARMISD::CMPFPE:        return "ARMISD::CMPFPE";
1584   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1585   case ARMISD::CMPFPEw0:      return "ARMISD::CMPFPEw0";
1586   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1587   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1588 
1589   case ARMISD::CMOV:          return "ARMISD::CMOV";
1590   case ARMISD::SUBS:          return "ARMISD::SUBS";
1591 
1592   case ARMISD::SSAT:          return "ARMISD::SSAT";
1593   case ARMISD::USAT:          return "ARMISD::USAT";
1594 
1595   case ARMISD::ASRL:          return "ARMISD::ASRL";
1596   case ARMISD::LSRL:          return "ARMISD::LSRL";
1597   case ARMISD::LSLL:          return "ARMISD::LSLL";
1598 
1599   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1600   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1601   case ARMISD::RRX:           return "ARMISD::RRX";
1602 
1603   case ARMISD::ADDC:          return "ARMISD::ADDC";
1604   case ARMISD::ADDE:          return "ARMISD::ADDE";
1605   case ARMISD::SUBC:          return "ARMISD::SUBC";
1606   case ARMISD::SUBE:          return "ARMISD::SUBE";
1607   case ARMISD::LSLS:          return "ARMISD::LSLS";
1608 
1609   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1610   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1611   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1612   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1613   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
1614 
1615   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1616   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1617   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1618 
1619   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1620 
1621   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1622 
1623   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1624 
1625   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1626 
1627   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1628 
1629   case ARMISD::LDRD:          return "ARMISD::LDRD";
1630   case ARMISD::STRD:          return "ARMISD::STRD";
1631 
1632   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1633   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1634 
1635   case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1636   case ARMISD::VECTOR_REG_CAST: return "ARMISD::VECTOR_REG_CAST";
1637   case ARMISD::VCMP:          return "ARMISD::VCMP";
1638   case ARMISD::VCMPZ:         return "ARMISD::VCMPZ";
1639   case ARMISD::VTST:          return "ARMISD::VTST";
1640 
1641   case ARMISD::VSHLs:         return "ARMISD::VSHLs";
1642   case ARMISD::VSHLu:         return "ARMISD::VSHLu";
1643   case ARMISD::VSHLIMM:       return "ARMISD::VSHLIMM";
1644   case ARMISD::VSHRsIMM:      return "ARMISD::VSHRsIMM";
1645   case ARMISD::VSHRuIMM:      return "ARMISD::VSHRuIMM";
1646   case ARMISD::VRSHRsIMM:     return "ARMISD::VRSHRsIMM";
1647   case ARMISD::VRSHRuIMM:     return "ARMISD::VRSHRuIMM";
1648   case ARMISD::VRSHRNIMM:     return "ARMISD::VRSHRNIMM";
1649   case ARMISD::VQSHLsIMM:     return "ARMISD::VQSHLsIMM";
1650   case ARMISD::VQSHLuIMM:     return "ARMISD::VQSHLuIMM";
1651   case ARMISD::VQSHLsuIMM:    return "ARMISD::VQSHLsuIMM";
1652   case ARMISD::VQSHRNsIMM:    return "ARMISD::VQSHRNsIMM";
1653   case ARMISD::VQSHRNuIMM:    return "ARMISD::VQSHRNuIMM";
1654   case ARMISD::VQSHRNsuIMM:   return "ARMISD::VQSHRNsuIMM";
1655   case ARMISD::VQRSHRNsIMM:   return "ARMISD::VQRSHRNsIMM";
1656   case ARMISD::VQRSHRNuIMM:   return "ARMISD::VQRSHRNuIMM";
1657   case ARMISD::VQRSHRNsuIMM:  return "ARMISD::VQRSHRNsuIMM";
1658   case ARMISD::VSLIIMM:       return "ARMISD::VSLIIMM";
1659   case ARMISD::VSRIIMM:       return "ARMISD::VSRIIMM";
1660   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1661   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1662   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1663   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1664   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1665   case ARMISD::VDUP:          return "ARMISD::VDUP";
1666   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1667   case ARMISD::VEXT:          return "ARMISD::VEXT";
1668   case ARMISD::VREV64:        return "ARMISD::VREV64";
1669   case ARMISD::VREV32:        return "ARMISD::VREV32";
1670   case ARMISD::VREV16:        return "ARMISD::VREV16";
1671   case ARMISD::VZIP:          return "ARMISD::VZIP";
1672   case ARMISD::VUZP:          return "ARMISD::VUZP";
1673   case ARMISD::VTRN:          return "ARMISD::VTRN";
1674   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1675   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1676   case ARMISD::VMOVN:         return "ARMISD::VMOVN";
1677   case ARMISD::VQMOVNs:       return "ARMISD::VQMOVNs";
1678   case ARMISD::VQMOVNu:       return "ARMISD::VQMOVNu";
1679   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1680   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1681   case ARMISD::VADDVs:        return "ARMISD::VADDVs";
1682   case ARMISD::VADDVu:        return "ARMISD::VADDVu";
1683   case ARMISD::VADDLVs:       return "ARMISD::VADDLVs";
1684   case ARMISD::VADDLVu:       return "ARMISD::VADDLVu";
1685   case ARMISD::VADDLVAs:      return "ARMISD::VADDLVAs";
1686   case ARMISD::VADDLVAu:      return "ARMISD::VADDLVAu";
1687   case ARMISD::VADDLVps:      return "ARMISD::VADDLVps";
1688   case ARMISD::VADDLVpu:      return "ARMISD::VADDLVpu";
1689   case ARMISD::VADDLVAps:     return "ARMISD::VADDLVAps";
1690   case ARMISD::VADDLVApu:     return "ARMISD::VADDLVApu";
1691   case ARMISD::VMLAVs:        return "ARMISD::VMLAVs";
1692   case ARMISD::VMLAVu:        return "ARMISD::VMLAVu";
1693   case ARMISD::VMLALVs:       return "ARMISD::VMLALVs";
1694   case ARMISD::VMLALVu:       return "ARMISD::VMLALVu";
1695   case ARMISD::VMLALVAs:      return "ARMISD::VMLALVAs";
1696   case ARMISD::VMLALVAu:      return "ARMISD::VMLALVAu";
1697   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1698   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1699   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1700   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1701   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1702   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1703   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1704   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1705   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1706   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1707   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1708   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1709   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1710   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1711   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1712   case ARMISD::QADD16b:       return "ARMISD::QADD16b";
1713   case ARMISD::QSUB16b:       return "ARMISD::QSUB16b";
1714   case ARMISD::QADD8b:        return "ARMISD::QADD8b";
1715   case ARMISD::QSUB8b:        return "ARMISD::QSUB8b";
1716   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1717   case ARMISD::BFI:           return "ARMISD::BFI";
1718   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1719   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1720   case ARMISD::VBSL:          return "ARMISD::VBSL";
1721   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1722   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1723   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1724   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1725   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1726   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1727   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1728   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1729   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1730   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1731   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1732   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1733   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1734   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1735   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1736   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1737   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1738   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1739   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1740   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1741   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1742   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1743   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1744   case ARMISD::WLS:           return "ARMISD::WLS";
1745   case ARMISD::LE:            return "ARMISD::LE";
1746   case ARMISD::LOOP_DEC:      return "ARMISD::LOOP_DEC";
1747   case ARMISD::CSINV:         return "ARMISD::CSINV";
1748   case ARMISD::CSNEG:         return "ARMISD::CSNEG";
1749   case ARMISD::CSINC:         return "ARMISD::CSINC";
1750   }
1751   return nullptr;
1752 }
1753 
1754 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1755                                           EVT VT) const {
1756   if (!VT.isVector())
1757     return getPointerTy(DL);
1758 
1759   // MVE has a predicate register.
1760   if (Subtarget->hasMVEIntegerOps() &&
1761       (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1762     return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1763   return VT.changeVectorElementTypeToInteger();
1764 }
1765 
1766 /// getRegClassFor - Return the register class that should be used for the
1767 /// specified value type.
1768 const TargetRegisterClass *
1769 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1770   (void)isDivergent;
1771   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1772   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1773   // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1774   // MVE Q registers.
1775   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1776     if (VT == MVT::v4i64)
1777       return &ARM::QQPRRegClass;
1778     if (VT == MVT::v8i64)
1779       return &ARM::QQQQPRRegClass;
1780   }
1781   return TargetLowering::getRegClassFor(VT);
1782 }
1783 
1784 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1785 // source/dest is aligned and the copy size is large enough. We therefore want
1786 // to align such objects passed to memory intrinsics.
1787 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1788                                                unsigned &PrefAlign) const {
1789   if (!isa<MemIntrinsic>(CI))
1790     return false;
1791   MinSize = 8;
1792   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1793   // cycle faster than 4-byte aligned LDM.
1794   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1795   return true;
1796 }
1797 
1798 // Create a fast isel object.
1799 FastISel *
1800 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1801                                   const TargetLibraryInfo *libInfo) const {
1802   return ARM::createFastISel(funcInfo, libInfo);
1803 }
1804 
1805 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1806   unsigned NumVals = N->getNumValues();
1807   if (!NumVals)
1808     return Sched::RegPressure;
1809 
1810   for (unsigned i = 0; i != NumVals; ++i) {
1811     EVT VT = N->getValueType(i);
1812     if (VT == MVT::Glue || VT == MVT::Other)
1813       continue;
1814     if (VT.isFloatingPoint() || VT.isVector())
1815       return Sched::ILP;
1816   }
1817 
1818   if (!N->isMachineOpcode())
1819     return Sched::RegPressure;
1820 
1821   // Load are scheduled for latency even if there instruction itinerary
1822   // is not available.
1823   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1824   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1825 
1826   if (MCID.getNumDefs() == 0)
1827     return Sched::RegPressure;
1828   if (!Itins->isEmpty() &&
1829       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1830     return Sched::ILP;
1831 
1832   return Sched::RegPressure;
1833 }
1834 
1835 //===----------------------------------------------------------------------===//
1836 // Lowering Code
1837 //===----------------------------------------------------------------------===//
1838 
1839 static bool isSRL16(const SDValue &Op) {
1840   if (Op.getOpcode() != ISD::SRL)
1841     return false;
1842   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1843     return Const->getZExtValue() == 16;
1844   return false;
1845 }
1846 
1847 static bool isSRA16(const SDValue &Op) {
1848   if (Op.getOpcode() != ISD::SRA)
1849     return false;
1850   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1851     return Const->getZExtValue() == 16;
1852   return false;
1853 }
1854 
1855 static bool isSHL16(const SDValue &Op) {
1856   if (Op.getOpcode() != ISD::SHL)
1857     return false;
1858   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1859     return Const->getZExtValue() == 16;
1860   return false;
1861 }
1862 
1863 // Check for a signed 16-bit value. We special case SRA because it makes it
1864 // more simple when also looking for SRAs that aren't sign extending a
1865 // smaller value. Without the check, we'd need to take extra care with
1866 // checking order for some operations.
1867 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1868   if (isSRA16(Op))
1869     return isSHL16(Op.getOperand(0));
1870   return DAG.ComputeNumSignBits(Op) == 17;
1871 }
1872 
1873 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1874 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1875   switch (CC) {
1876   default: llvm_unreachable("Unknown condition code!");
1877   case ISD::SETNE:  return ARMCC::NE;
1878   case ISD::SETEQ:  return ARMCC::EQ;
1879   case ISD::SETGT:  return ARMCC::GT;
1880   case ISD::SETGE:  return ARMCC::GE;
1881   case ISD::SETLT:  return ARMCC::LT;
1882   case ISD::SETLE:  return ARMCC::LE;
1883   case ISD::SETUGT: return ARMCC::HI;
1884   case ISD::SETUGE: return ARMCC::HS;
1885   case ISD::SETULT: return ARMCC::LO;
1886   case ISD::SETULE: return ARMCC::LS;
1887   }
1888 }
1889 
1890 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1891 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1892                         ARMCC::CondCodes &CondCode2) {
1893   CondCode2 = ARMCC::AL;
1894   switch (CC) {
1895   default: llvm_unreachable("Unknown FP condition!");
1896   case ISD::SETEQ:
1897   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1898   case ISD::SETGT:
1899   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1900   case ISD::SETGE:
1901   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1902   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1903   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1904   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1905   case ISD::SETO:   CondCode = ARMCC::VC; break;
1906   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1907   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1908   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1909   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1910   case ISD::SETLT:
1911   case ISD::SETULT: CondCode = ARMCC::LT; break;
1912   case ISD::SETLE:
1913   case ISD::SETULE: CondCode = ARMCC::LE; break;
1914   case ISD::SETNE:
1915   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1916   }
1917 }
1918 
1919 //===----------------------------------------------------------------------===//
1920 //                      Calling Convention Implementation
1921 //===----------------------------------------------------------------------===//
1922 
1923 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1924 /// account presence of floating point hardware and calling convention
1925 /// limitations, such as support for variadic functions.
1926 CallingConv::ID
1927 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1928                                            bool isVarArg) const {
1929   switch (CC) {
1930   default:
1931     report_fatal_error("Unsupported calling convention");
1932   case CallingConv::ARM_AAPCS:
1933   case CallingConv::ARM_APCS:
1934   case CallingConv::GHC:
1935   case CallingConv::CFGuard_Check:
1936     return CC;
1937   case CallingConv::PreserveMost:
1938     return CallingConv::PreserveMost;
1939   case CallingConv::ARM_AAPCS_VFP:
1940   case CallingConv::Swift:
1941     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1942   case CallingConv::C:
1943     if (!Subtarget->isAAPCS_ABI())
1944       return CallingConv::ARM_APCS;
1945     else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1946              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1947              !isVarArg)
1948       return CallingConv::ARM_AAPCS_VFP;
1949     else
1950       return CallingConv::ARM_AAPCS;
1951   case CallingConv::Fast:
1952   case CallingConv::CXX_FAST_TLS:
1953     if (!Subtarget->isAAPCS_ABI()) {
1954       if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1955         return CallingConv::Fast;
1956       return CallingConv::ARM_APCS;
1957     } else if (Subtarget->hasVFP2Base() &&
1958                !Subtarget->isThumb1Only() && !isVarArg)
1959       return CallingConv::ARM_AAPCS_VFP;
1960     else
1961       return CallingConv::ARM_AAPCS;
1962   }
1963 }
1964 
1965 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1966                                                  bool isVarArg) const {
1967   return CCAssignFnForNode(CC, false, isVarArg);
1968 }
1969 
1970 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1971                                                    bool isVarArg) const {
1972   return CCAssignFnForNode(CC, true, isVarArg);
1973 }
1974 
1975 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1976 /// CallingConvention.
1977 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1978                                                  bool Return,
1979                                                  bool isVarArg) const {
1980   switch (getEffectiveCallingConv(CC, isVarArg)) {
1981   default:
1982     report_fatal_error("Unsupported calling convention");
1983   case CallingConv::ARM_APCS:
1984     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1985   case CallingConv::ARM_AAPCS:
1986     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1987   case CallingConv::ARM_AAPCS_VFP:
1988     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1989   case CallingConv::Fast:
1990     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1991   case CallingConv::GHC:
1992     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1993   case CallingConv::PreserveMost:
1994     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1995   case CallingConv::CFGuard_Check:
1996     return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
1997   }
1998 }
1999 
2000 /// LowerCallResult - Lower the result values of a call into the
2001 /// appropriate copies out of appropriate physical registers.
2002 SDValue ARMTargetLowering::LowerCallResult(
2003     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2004     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2005     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2006     SDValue ThisVal) const {
2007   // Assign locations to each value returned by this call.
2008   SmallVector<CCValAssign, 16> RVLocs;
2009   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2010                  *DAG.getContext());
2011   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
2012 
2013   // Copy all of the result registers out of their specified physreg.
2014   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2015     CCValAssign VA = RVLocs[i];
2016 
2017     // Pass 'this' value directly from the argument to return value, to avoid
2018     // reg unit interference
2019     if (i == 0 && isThisReturn) {
2020       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
2021              "unexpected return calling convention register assignment");
2022       InVals.push_back(ThisVal);
2023       continue;
2024     }
2025 
2026     SDValue Val;
2027     if (VA.needsCustom()) {
2028       // Handle f64 or half of a v2f64.
2029       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2030                                       InFlag);
2031       Chain = Lo.getValue(1);
2032       InFlag = Lo.getValue(2);
2033       VA = RVLocs[++i]; // skip ahead to next loc
2034       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2035                                       InFlag);
2036       Chain = Hi.getValue(1);
2037       InFlag = Hi.getValue(2);
2038       if (!Subtarget->isLittle())
2039         std::swap (Lo, Hi);
2040       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2041 
2042       if (VA.getLocVT() == MVT::v2f64) {
2043         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2044         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2045                           DAG.getConstant(0, dl, MVT::i32));
2046 
2047         VA = RVLocs[++i]; // skip ahead to next loc
2048         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2049         Chain = Lo.getValue(1);
2050         InFlag = Lo.getValue(2);
2051         VA = RVLocs[++i]; // skip ahead to next loc
2052         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2053         Chain = Hi.getValue(1);
2054         InFlag = Hi.getValue(2);
2055         if (!Subtarget->isLittle())
2056           std::swap (Lo, Hi);
2057         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2058         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2059                           DAG.getConstant(1, dl, MVT::i32));
2060       }
2061     } else {
2062       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2063                                InFlag);
2064       Chain = Val.getValue(1);
2065       InFlag = Val.getValue(2);
2066     }
2067 
2068     switch (VA.getLocInfo()) {
2069     default: llvm_unreachable("Unknown loc info!");
2070     case CCValAssign::Full: break;
2071     case CCValAssign::BCvt:
2072       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2073       break;
2074     }
2075 
2076     InVals.push_back(Val);
2077   }
2078 
2079   return Chain;
2080 }
2081 
2082 /// LowerMemOpCallTo - Store the argument to the stack.
2083 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
2084                                             SDValue Arg, const SDLoc &dl,
2085                                             SelectionDAG &DAG,
2086                                             const CCValAssign &VA,
2087                                             ISD::ArgFlagsTy Flags) const {
2088   unsigned LocMemOffset = VA.getLocMemOffset();
2089   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2090   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2091                        StackPtr, PtrOff);
2092   return DAG.getStore(
2093       Chain, dl, Arg, PtrOff,
2094       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2095 }
2096 
2097 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2098                                          SDValue Chain, SDValue &Arg,
2099                                          RegsToPassVector &RegsToPass,
2100                                          CCValAssign &VA, CCValAssign &NextVA,
2101                                          SDValue &StackPtr,
2102                                          SmallVectorImpl<SDValue> &MemOpChains,
2103                                          ISD::ArgFlagsTy Flags) const {
2104   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2105                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
2106   unsigned id = Subtarget->isLittle() ? 0 : 1;
2107   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2108 
2109   if (NextVA.isRegLoc())
2110     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2111   else {
2112     assert(NextVA.isMemLoc());
2113     if (!StackPtr.getNode())
2114       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2115                                     getPointerTy(DAG.getDataLayout()));
2116 
2117     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2118                                            dl, DAG, NextVA,
2119                                            Flags));
2120   }
2121 }
2122 
2123 /// LowerCall - Lowering a call into a callseq_start <-
2124 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2125 /// nodes.
2126 SDValue
2127 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2128                              SmallVectorImpl<SDValue> &InVals) const {
2129   SelectionDAG &DAG                     = CLI.DAG;
2130   SDLoc &dl                             = CLI.DL;
2131   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2132   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2133   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2134   SDValue Chain                         = CLI.Chain;
2135   SDValue Callee                        = CLI.Callee;
2136   bool &isTailCall                      = CLI.IsTailCall;
2137   CallingConv::ID CallConv              = CLI.CallConv;
2138   bool doesNotRet                       = CLI.DoesNotReturn;
2139   bool isVarArg                         = CLI.IsVarArg;
2140 
2141   MachineFunction &MF = DAG.getMachineFunction();
2142   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2143   MachineFunction::CallSiteInfo CSInfo;
2144   bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2145   bool isThisReturn = false;
2146   bool isCmseNSCall   = false;
2147   bool PreferIndirect = false;
2148 
2149   // Determine whether this is a non-secure function call.
2150   if (CLI.CB && CLI.CB->getAttributes().hasFnAttribute("cmse_nonsecure_call"))
2151     isCmseNSCall = true;
2152 
2153   // Disable tail calls if they're not supported.
2154   if (!Subtarget->supportsTailCall())
2155     isTailCall = false;
2156 
2157   // For both the non-secure calls and the returns from a CMSE entry function,
2158   // the function needs to do some extra work afte r the call, or before the
2159   // return, respectively, thus it cannot end with atail call
2160   if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2161     isTailCall = false;
2162 
2163   if (isa<GlobalAddressSDNode>(Callee)) {
2164     // If we're optimizing for minimum size and the function is called three or
2165     // more times in this block, we can improve codesize by calling indirectly
2166     // as BLXr has a 16-bit encoding.
2167     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2168     if (CLI.CB) {
2169       auto *BB = CLI.CB->getParent();
2170       PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2171                        count_if(GV->users(), [&BB](const User *U) {
2172                          return isa<Instruction>(U) &&
2173                                 cast<Instruction>(U)->getParent() == BB;
2174                        }) > 2;
2175     }
2176   }
2177   if (isTailCall) {
2178     // Check if it's really possible to do a tail call.
2179     isTailCall = IsEligibleForTailCallOptimization(
2180         Callee, CallConv, isVarArg, isStructRet,
2181         MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2182         PreferIndirect);
2183     if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2184       report_fatal_error("failed to perform tail call elimination on a call "
2185                          "site marked musttail");
2186     // We don't support GuaranteedTailCallOpt for ARM, only automatically
2187     // detected sibcalls.
2188     if (isTailCall)
2189       ++NumTailCalls;
2190   }
2191 
2192   // Analyze operands of the call, assigning locations to each operand.
2193   SmallVector<CCValAssign, 16> ArgLocs;
2194   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2195                  *DAG.getContext());
2196   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2197 
2198   // Get a count of how many bytes are to be pushed on the stack.
2199   unsigned NumBytes = CCInfo.getNextStackOffset();
2200 
2201   if (isTailCall) {
2202     // For tail calls, memory operands are available in our caller's stack.
2203     NumBytes = 0;
2204   } else {
2205     // Adjust the stack pointer for the new arguments...
2206     // These operations are automatically eliminated by the prolog/epilog pass
2207     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2208   }
2209 
2210   SDValue StackPtr =
2211       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2212 
2213   RegsToPassVector RegsToPass;
2214   SmallVector<SDValue, 8> MemOpChains;
2215 
2216   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2217   // of tail call optimization, arguments are handled later.
2218   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2219        i != e;
2220        ++i, ++realArgIdx) {
2221     CCValAssign &VA = ArgLocs[i];
2222     SDValue Arg = OutVals[realArgIdx];
2223     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2224     bool isByVal = Flags.isByVal();
2225 
2226     // Promote the value if needed.
2227     switch (VA.getLocInfo()) {
2228     default: llvm_unreachable("Unknown loc info!");
2229     case CCValAssign::Full: break;
2230     case CCValAssign::SExt:
2231       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2232       break;
2233     case CCValAssign::ZExt:
2234       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2235       break;
2236     case CCValAssign::AExt:
2237       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2238       break;
2239     case CCValAssign::BCvt:
2240       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2241       break;
2242     }
2243 
2244     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2245     if (VA.needsCustom()) {
2246       if (VA.getLocVT() == MVT::v2f64) {
2247         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2248                                   DAG.getConstant(0, dl, MVT::i32));
2249         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2250                                   DAG.getConstant(1, dl, MVT::i32));
2251 
2252         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2253                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2254 
2255         VA = ArgLocs[++i]; // skip ahead to next loc
2256         if (VA.isRegLoc()) {
2257           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2258                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2259         } else {
2260           assert(VA.isMemLoc());
2261 
2262           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2263                                                  dl, DAG, VA, Flags));
2264         }
2265       } else {
2266         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2267                          StackPtr, MemOpChains, Flags);
2268       }
2269     } else if (VA.isRegLoc()) {
2270       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2271           Outs[0].VT == MVT::i32) {
2272         assert(VA.getLocVT() == MVT::i32 &&
2273                "unexpected calling convention register assignment");
2274         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2275                "unexpected use of 'returned'");
2276         isThisReturn = true;
2277       }
2278       const TargetOptions &Options = DAG.getTarget().Options;
2279       if (Options.EmitCallSiteInfo)
2280         CSInfo.emplace_back(VA.getLocReg(), i);
2281       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2282     } else if (isByVal) {
2283       assert(VA.isMemLoc());
2284       unsigned offset = 0;
2285 
2286       // True if this byval aggregate will be split between registers
2287       // and memory.
2288       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2289       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2290 
2291       if (CurByValIdx < ByValArgsCount) {
2292 
2293         unsigned RegBegin, RegEnd;
2294         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2295 
2296         EVT PtrVT =
2297             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2298         unsigned int i, j;
2299         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2300           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2301           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2302           SDValue Load =
2303               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2304                           DAG.InferPtrAlign(AddArg));
2305           MemOpChains.push_back(Load.getValue(1));
2306           RegsToPass.push_back(std::make_pair(j, Load));
2307         }
2308 
2309         // If parameter size outsides register area, "offset" value
2310         // helps us to calculate stack slot for remained part properly.
2311         offset = RegEnd - RegBegin;
2312 
2313         CCInfo.nextInRegsParam();
2314       }
2315 
2316       if (Flags.getByValSize() > 4*offset) {
2317         auto PtrVT = getPointerTy(DAG.getDataLayout());
2318         unsigned LocMemOffset = VA.getLocMemOffset();
2319         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2320         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2321         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2322         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2323         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2324                                            MVT::i32);
2325         SDValue AlignNode =
2326             DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2327 
2328         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2329         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2330         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2331                                           Ops));
2332       }
2333     } else if (!isTailCall) {
2334       assert(VA.isMemLoc());
2335 
2336       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2337                                              dl, DAG, VA, Flags));
2338     }
2339   }
2340 
2341   if (!MemOpChains.empty())
2342     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2343 
2344   // Build a sequence of copy-to-reg nodes chained together with token chain
2345   // and flag operands which copy the outgoing args into the appropriate regs.
2346   SDValue InFlag;
2347   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2348     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2349                              RegsToPass[i].second, InFlag);
2350     InFlag = Chain.getValue(1);
2351   }
2352 
2353   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2354   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2355   // node so that legalize doesn't hack it.
2356   bool isDirect = false;
2357 
2358   const TargetMachine &TM = getTargetMachine();
2359   const Module *Mod = MF.getFunction().getParent();
2360   const GlobalValue *GV = nullptr;
2361   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2362     GV = G->getGlobal();
2363   bool isStub =
2364       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2365 
2366   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2367   bool isLocalARMFunc = false;
2368   auto PtrVt = getPointerTy(DAG.getDataLayout());
2369 
2370   if (Subtarget->genLongCalls()) {
2371     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2372            "long-calls codegen is not position independent!");
2373     // Handle a global address or an external symbol. If it's not one of
2374     // those, the target's already in a register, so we don't need to do
2375     // anything extra.
2376     if (isa<GlobalAddressSDNode>(Callee)) {
2377       // Create a constant pool entry for the callee address
2378       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2379       ARMConstantPoolValue *CPV =
2380         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2381 
2382       // Get the address of the callee into a register
2383       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2384       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2385       Callee = DAG.getLoad(
2386           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2387           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2388     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2389       const char *Sym = S->getSymbol();
2390 
2391       // Create a constant pool entry for the callee address
2392       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2393       ARMConstantPoolValue *CPV =
2394         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2395                                       ARMPCLabelIndex, 0);
2396       // Get the address of the callee into a register
2397       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2398       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2399       Callee = DAG.getLoad(
2400           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2401           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2402     }
2403   } else if (isa<GlobalAddressSDNode>(Callee)) {
2404     if (!PreferIndirect) {
2405       isDirect = true;
2406       bool isDef = GV->isStrongDefinitionForLinker();
2407 
2408       // ARM call to a local ARM function is predicable.
2409       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2410       // tBX takes a register source operand.
2411       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2412         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2413         Callee = DAG.getNode(
2414             ARMISD::WrapperPIC, dl, PtrVt,
2415             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2416         Callee = DAG.getLoad(
2417             PtrVt, dl, DAG.getEntryNode(), Callee,
2418             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2419             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2420                                      MachineMemOperand::MOInvariant);
2421       } else if (Subtarget->isTargetCOFF()) {
2422         assert(Subtarget->isTargetWindows() &&
2423                "Windows is the only supported COFF target");
2424         unsigned TargetFlags = ARMII::MO_NO_FLAG;
2425         if (GV->hasDLLImportStorageClass())
2426           TargetFlags = ARMII::MO_DLLIMPORT;
2427         else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
2428           TargetFlags = ARMII::MO_COFFSTUB;
2429         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2430                                             TargetFlags);
2431         if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2432           Callee =
2433               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2434                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2435                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2436       } else {
2437         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2438       }
2439     }
2440   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2441     isDirect = true;
2442     // tBX takes a register source operand.
2443     const char *Sym = S->getSymbol();
2444     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2445       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2446       ARMConstantPoolValue *CPV =
2447         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2448                                       ARMPCLabelIndex, 4);
2449       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2450       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2451       Callee = DAG.getLoad(
2452           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2453           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2454       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2455       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2456     } else {
2457       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2458     }
2459   }
2460 
2461   if (isCmseNSCall) {
2462     assert(!isARMFunc && !isDirect &&
2463            "Cannot handle call to ARM function or direct call");
2464     if (NumBytes > 0) {
2465       DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(),
2466                                      "call to non-secure function would "
2467                                      "require passing arguments on stack",
2468                                      dl.getDebugLoc());
2469       DAG.getContext()->diagnose(Diag);
2470     }
2471     if (isStructRet) {
2472       DiagnosticInfoUnsupported Diag(
2473           DAG.getMachineFunction().getFunction(),
2474           "call to non-secure function would return value through pointer",
2475           dl.getDebugLoc());
2476       DAG.getContext()->diagnose(Diag);
2477     }
2478   }
2479 
2480   // FIXME: handle tail calls differently.
2481   unsigned CallOpc;
2482   if (Subtarget->isThumb()) {
2483     if (isCmseNSCall)
2484       CallOpc = ARMISD::tSECALL;
2485     else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2486       CallOpc = ARMISD::CALL_NOLINK;
2487     else
2488       CallOpc = ARMISD::CALL;
2489   } else {
2490     if (!isDirect && !Subtarget->hasV5TOps())
2491       CallOpc = ARMISD::CALL_NOLINK;
2492     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2493              // Emit regular call when code size is the priority
2494              !Subtarget->hasMinSize())
2495       // "mov lr, pc; b _foo" to avoid confusing the RSP
2496       CallOpc = ARMISD::CALL_NOLINK;
2497     else
2498       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2499   }
2500 
2501   std::vector<SDValue> Ops;
2502   Ops.push_back(Chain);
2503   Ops.push_back(Callee);
2504 
2505   // Add argument registers to the end of the list so that they are known live
2506   // into the call.
2507   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2508     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2509                                   RegsToPass[i].second.getValueType()));
2510 
2511   // Add a register mask operand representing the call-preserved registers.
2512   if (!isTailCall) {
2513     const uint32_t *Mask;
2514     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2515     if (isThisReturn) {
2516       // For 'this' returns, use the R0-preserving mask if applicable
2517       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2518       if (!Mask) {
2519         // Set isThisReturn to false if the calling convention is not one that
2520         // allows 'returned' to be modeled in this way, so LowerCallResult does
2521         // not try to pass 'this' straight through
2522         isThisReturn = false;
2523         Mask = ARI->getCallPreservedMask(MF, CallConv);
2524       }
2525     } else
2526       Mask = ARI->getCallPreservedMask(MF, CallConv);
2527 
2528     assert(Mask && "Missing call preserved mask for calling convention");
2529     Ops.push_back(DAG.getRegisterMask(Mask));
2530   }
2531 
2532   if (InFlag.getNode())
2533     Ops.push_back(InFlag);
2534 
2535   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2536   if (isTailCall) {
2537     MF.getFrameInfo().setHasTailCall();
2538     SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2539     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2540     return Ret;
2541   }
2542 
2543   // Returns a chain and a flag for retval copy to use.
2544   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2545   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2546   InFlag = Chain.getValue(1);
2547   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2548 
2549   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2550                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2551   if (!Ins.empty())
2552     InFlag = Chain.getValue(1);
2553 
2554   // Handle result values, copying them out of physregs into vregs that we
2555   // return.
2556   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2557                          InVals, isThisReturn,
2558                          isThisReturn ? OutVals[0] : SDValue());
2559 }
2560 
2561 /// HandleByVal - Every parameter *after* a byval parameter is passed
2562 /// on the stack.  Remember the next parameter register to allocate,
2563 /// and then confiscate the rest of the parameter registers to insure
2564 /// this.
2565 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2566                                     Align Alignment) const {
2567   // Byval (as with any stack) slots are always at least 4 byte aligned.
2568   Alignment = std::max(Alignment, Align(4));
2569 
2570   unsigned Reg = State->AllocateReg(GPRArgRegs);
2571   if (!Reg)
2572     return;
2573 
2574   unsigned AlignInRegs = Alignment.value() / 4;
2575   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2576   for (unsigned i = 0; i < Waste; ++i)
2577     Reg = State->AllocateReg(GPRArgRegs);
2578 
2579   if (!Reg)
2580     return;
2581 
2582   unsigned Excess = 4 * (ARM::R4 - Reg);
2583 
2584   // Special case when NSAA != SP and parameter size greater than size of
2585   // all remained GPR regs. In that case we can't split parameter, we must
2586   // send it to stack. We also must set NCRN to R4, so waste all
2587   // remained registers.
2588   const unsigned NSAAOffset = State->getNextStackOffset();
2589   if (NSAAOffset != 0 && Size > Excess) {
2590     while (State->AllocateReg(GPRArgRegs))
2591       ;
2592     return;
2593   }
2594 
2595   // First register for byval parameter is the first register that wasn't
2596   // allocated before this method call, so it would be "reg".
2597   // If parameter is small enough to be saved in range [reg, r4), then
2598   // the end (first after last) register would be reg + param-size-in-regs,
2599   // else parameter would be splitted between registers and stack,
2600   // end register would be r4 in this case.
2601   unsigned ByValRegBegin = Reg;
2602   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2603   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2604   // Note, first register is allocated in the beginning of function already,
2605   // allocate remained amount of registers we need.
2606   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2607     State->AllocateReg(GPRArgRegs);
2608   // A byval parameter that is split between registers and memory needs its
2609   // size truncated here.
2610   // In the case where the entire structure fits in registers, we set the
2611   // size in memory to zero.
2612   Size = std::max<int>(Size - Excess, 0);
2613 }
2614 
2615 /// MatchingStackOffset - Return true if the given stack call argument is
2616 /// already available in the same position (relatively) of the caller's
2617 /// incoming argument stack.
2618 static
2619 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2620                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2621                          const TargetInstrInfo *TII) {
2622   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2623   int FI = std::numeric_limits<int>::max();
2624   if (Arg.getOpcode() == ISD::CopyFromReg) {
2625     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2626     if (!Register::isVirtualRegister(VR))
2627       return false;
2628     MachineInstr *Def = MRI->getVRegDef(VR);
2629     if (!Def)
2630       return false;
2631     if (!Flags.isByVal()) {
2632       if (!TII->isLoadFromStackSlot(*Def, FI))
2633         return false;
2634     } else {
2635       return false;
2636     }
2637   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2638     if (Flags.isByVal())
2639       // ByVal argument is passed in as a pointer but it's now being
2640       // dereferenced. e.g.
2641       // define @foo(%struct.X* %A) {
2642       //   tail call @bar(%struct.X* byval %A)
2643       // }
2644       return false;
2645     SDValue Ptr = Ld->getBasePtr();
2646     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2647     if (!FINode)
2648       return false;
2649     FI = FINode->getIndex();
2650   } else
2651     return false;
2652 
2653   assert(FI != std::numeric_limits<int>::max());
2654   if (!MFI.isFixedObjectIndex(FI))
2655     return false;
2656   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2657 }
2658 
2659 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2660 /// for tail call optimization. Targets which want to do tail call
2661 /// optimization should implement this function.
2662 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2663     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2664     bool isCalleeStructRet, bool isCallerStructRet,
2665     const SmallVectorImpl<ISD::OutputArg> &Outs,
2666     const SmallVectorImpl<SDValue> &OutVals,
2667     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2668     const bool isIndirect) const {
2669   MachineFunction &MF = DAG.getMachineFunction();
2670   const Function &CallerF = MF.getFunction();
2671   CallingConv::ID CallerCC = CallerF.getCallingConv();
2672 
2673   assert(Subtarget->supportsTailCall());
2674 
2675   // Indirect tail calls cannot be optimized for Thumb1 if the args
2676   // to the call take up r0-r3. The reason is that there are no legal registers
2677   // left to hold the pointer to the function to be called.
2678   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2679       (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2680     return false;
2681 
2682   // Look for obvious safe cases to perform tail call optimization that do not
2683   // require ABI changes. This is what gcc calls sibcall.
2684 
2685   // Exception-handling functions need a special set of instructions to indicate
2686   // a return to the hardware. Tail-calling another function would probably
2687   // break this.
2688   if (CallerF.hasFnAttribute("interrupt"))
2689     return false;
2690 
2691   // Also avoid sibcall optimization if either caller or callee uses struct
2692   // return semantics.
2693   if (isCalleeStructRet || isCallerStructRet)
2694     return false;
2695 
2696   // Externally-defined functions with weak linkage should not be
2697   // tail-called on ARM when the OS does not support dynamic
2698   // pre-emption of symbols, as the AAELF spec requires normal calls
2699   // to undefined weak functions to be replaced with a NOP or jump to the
2700   // next instruction. The behaviour of branch instructions in this
2701   // situation (as used for tail calls) is implementation-defined, so we
2702   // cannot rely on the linker replacing the tail call with a return.
2703   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2704     const GlobalValue *GV = G->getGlobal();
2705     const Triple &TT = getTargetMachine().getTargetTriple();
2706     if (GV->hasExternalWeakLinkage() &&
2707         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2708       return false;
2709   }
2710 
2711   // Check that the call results are passed in the same way.
2712   LLVMContext &C = *DAG.getContext();
2713   if (!CCState::resultsCompatible(
2714           getEffectiveCallingConv(CalleeCC, isVarArg),
2715           getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
2716           CCAssignFnForReturn(CalleeCC, isVarArg),
2717           CCAssignFnForReturn(CallerCC, CallerF.isVarArg())))
2718     return false;
2719   // The callee has to preserve all registers the caller needs to preserve.
2720   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2721   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2722   if (CalleeCC != CallerCC) {
2723     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2724     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2725       return false;
2726   }
2727 
2728   // If Caller's vararg or byval argument has been split between registers and
2729   // stack, do not perform tail call, since part of the argument is in caller's
2730   // local frame.
2731   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2732   if (AFI_Caller->getArgRegsSaveSize())
2733     return false;
2734 
2735   // If the callee takes no arguments then go on to check the results of the
2736   // call.
2737   if (!Outs.empty()) {
2738     // Check if stack adjustment is needed. For now, do not do this if any
2739     // argument is passed on the stack.
2740     SmallVector<CCValAssign, 16> ArgLocs;
2741     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2742     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2743     if (CCInfo.getNextStackOffset()) {
2744       // Check if the arguments are already laid out in the right way as
2745       // the caller's fixed stack objects.
2746       MachineFrameInfo &MFI = MF.getFrameInfo();
2747       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2748       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2749       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2750            i != e;
2751            ++i, ++realArgIdx) {
2752         CCValAssign &VA = ArgLocs[i];
2753         EVT RegVT = VA.getLocVT();
2754         SDValue Arg = OutVals[realArgIdx];
2755         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2756         if (VA.getLocInfo() == CCValAssign::Indirect)
2757           return false;
2758         if (VA.needsCustom()) {
2759           // f64 and vector types are split into multiple registers or
2760           // register/stack-slot combinations.  The types will not match
2761           // the registers; give up on memory f64 refs until we figure
2762           // out what to do about this.
2763           if (!VA.isRegLoc())
2764             return false;
2765           if (!ArgLocs[++i].isRegLoc())
2766             return false;
2767           if (RegVT == MVT::v2f64) {
2768             if (!ArgLocs[++i].isRegLoc())
2769               return false;
2770             if (!ArgLocs[++i].isRegLoc())
2771               return false;
2772           }
2773         } else if (!VA.isRegLoc()) {
2774           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2775                                    MFI, MRI, TII))
2776             return false;
2777         }
2778       }
2779     }
2780 
2781     const MachineRegisterInfo &MRI = MF.getRegInfo();
2782     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2783       return false;
2784   }
2785 
2786   return true;
2787 }
2788 
2789 bool
2790 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2791                                   MachineFunction &MF, bool isVarArg,
2792                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2793                                   LLVMContext &Context) const {
2794   SmallVector<CCValAssign, 16> RVLocs;
2795   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2796   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2797 }
2798 
2799 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2800                                     const SDLoc &DL, SelectionDAG &DAG) {
2801   const MachineFunction &MF = DAG.getMachineFunction();
2802   const Function &F = MF.getFunction();
2803 
2804   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2805 
2806   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2807   // version of the "preferred return address". These offsets affect the return
2808   // instruction if this is a return from PL1 without hypervisor extensions.
2809   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2810   //    SWI:     0      "subs pc, lr, #0"
2811   //    ABORT:   +4     "subs pc, lr, #4"
2812   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2813   // UNDEF varies depending on where the exception came from ARM or Thumb
2814   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2815 
2816   int64_t LROffset;
2817   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2818       IntKind == "ABORT")
2819     LROffset = 4;
2820   else if (IntKind == "SWI" || IntKind == "UNDEF")
2821     LROffset = 0;
2822   else
2823     report_fatal_error("Unsupported interrupt attribute. If present, value "
2824                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2825 
2826   RetOps.insert(RetOps.begin() + 1,
2827                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2828 
2829   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2830 }
2831 
2832 SDValue
2833 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2834                                bool isVarArg,
2835                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2836                                const SmallVectorImpl<SDValue> &OutVals,
2837                                const SDLoc &dl, SelectionDAG &DAG) const {
2838   // CCValAssign - represent the assignment of the return value to a location.
2839   SmallVector<CCValAssign, 16> RVLocs;
2840 
2841   // CCState - Info about the registers and stack slots.
2842   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2843                  *DAG.getContext());
2844 
2845   // Analyze outgoing return values.
2846   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2847 
2848   SDValue Flag;
2849   SmallVector<SDValue, 4> RetOps;
2850   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2851   bool isLittleEndian = Subtarget->isLittle();
2852 
2853   MachineFunction &MF = DAG.getMachineFunction();
2854   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2855   AFI->setReturnRegsCount(RVLocs.size());
2856 
2857  // Report error if cmse entry function returns structure through first ptr arg.
2858   if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
2859     // Note: using an empty SDLoc(), as the first line of the function is a
2860     // better place to report than the last line.
2861     DiagnosticInfoUnsupported Diag(
2862         DAG.getMachineFunction().getFunction(),
2863         "secure entry function would return value through pointer",
2864         SDLoc().getDebugLoc());
2865     DAG.getContext()->diagnose(Diag);
2866   }
2867 
2868   // Copy the result values into the output registers.
2869   for (unsigned i = 0, realRVLocIdx = 0;
2870        i != RVLocs.size();
2871        ++i, ++realRVLocIdx) {
2872     CCValAssign &VA = RVLocs[i];
2873     assert(VA.isRegLoc() && "Can only return in registers!");
2874 
2875     SDValue Arg = OutVals[realRVLocIdx];
2876     bool ReturnF16 = false;
2877 
2878     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2879       // Half-precision return values can be returned like this:
2880       //
2881       // t11 f16 = fadd ...
2882       // t12: i16 = bitcast t11
2883       //   t13: i32 = zero_extend t12
2884       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2885       //
2886       // to avoid code generation for bitcasts, we simply set Arg to the node
2887       // that produces the f16 value, t11 in this case.
2888       //
2889       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2890         SDValue ZE = Arg.getOperand(0);
2891         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2892           SDValue BC = ZE.getOperand(0);
2893           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2894             Arg = BC.getOperand(0);
2895             ReturnF16 = true;
2896           }
2897         }
2898       }
2899     }
2900 
2901     switch (VA.getLocInfo()) {
2902     default: llvm_unreachable("Unknown loc info!");
2903     case CCValAssign::Full: break;
2904     case CCValAssign::BCvt:
2905       if (!ReturnF16)
2906         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2907       break;
2908     }
2909 
2910     if (VA.needsCustom()) {
2911       if (VA.getLocVT() == MVT::v2f64) {
2912         // Extract the first half and return it in two registers.
2913         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2914                                    DAG.getConstant(0, dl, MVT::i32));
2915         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2916                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2917 
2918         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2919                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2920                                  Flag);
2921         Flag = Chain.getValue(1);
2922         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2923         VA = RVLocs[++i]; // skip ahead to next loc
2924         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2925                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2926                                  Flag);
2927         Flag = Chain.getValue(1);
2928         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2929         VA = RVLocs[++i]; // skip ahead to next loc
2930 
2931         // Extract the 2nd half and fall through to handle it as an f64 value.
2932         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2933                           DAG.getConstant(1, dl, MVT::i32));
2934       }
2935       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2936       // available.
2937       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2938                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2939       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2940                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2941                                Flag);
2942       Flag = Chain.getValue(1);
2943       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2944       VA = RVLocs[++i]; // skip ahead to next loc
2945       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2946                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2947                                Flag);
2948     } else
2949       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2950 
2951     // Guarantee that all emitted copies are
2952     // stuck together, avoiding something bad.
2953     Flag = Chain.getValue(1);
2954     RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2955                                      ReturnF16 ? MVT::f16 : VA.getLocVT()));
2956   }
2957   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2958   const MCPhysReg *I =
2959       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2960   if (I) {
2961     for (; *I; ++I) {
2962       if (ARM::GPRRegClass.contains(*I))
2963         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2964       else if (ARM::DPRRegClass.contains(*I))
2965         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2966       else
2967         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2968     }
2969   }
2970 
2971   // Update chain and glue.
2972   RetOps[0] = Chain;
2973   if (Flag.getNode())
2974     RetOps.push_back(Flag);
2975 
2976   // CPUs which aren't M-class use a special sequence to return from
2977   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2978   // though we use "subs pc, lr, #N").
2979   //
2980   // M-class CPUs actually use a normal return sequence with a special
2981   // (hardware-provided) value in LR, so the normal code path works.
2982   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2983       !Subtarget->isMClass()) {
2984     if (Subtarget->isThumb1Only())
2985       report_fatal_error("interrupt attribute is not supported in Thumb1");
2986     return LowerInterruptReturn(RetOps, dl, DAG);
2987   }
2988 
2989   ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG :
2990                                                             ARMISD::RET_FLAG;
2991   return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
2992 }
2993 
2994 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2995   if (N->getNumValues() != 1)
2996     return false;
2997   if (!N->hasNUsesOfValue(1, 0))
2998     return false;
2999 
3000   SDValue TCChain = Chain;
3001   SDNode *Copy = *N->use_begin();
3002   if (Copy->getOpcode() == ISD::CopyToReg) {
3003     // If the copy has a glue operand, we conservatively assume it isn't safe to
3004     // perform a tail call.
3005     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3006       return false;
3007     TCChain = Copy->getOperand(0);
3008   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3009     SDNode *VMov = Copy;
3010     // f64 returned in a pair of GPRs.
3011     SmallPtrSet<SDNode*, 2> Copies;
3012     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3013          UI != UE; ++UI) {
3014       if (UI->getOpcode() != ISD::CopyToReg)
3015         return false;
3016       Copies.insert(*UI);
3017     }
3018     if (Copies.size() > 2)
3019       return false;
3020 
3021     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3022          UI != UE; ++UI) {
3023       SDValue UseChain = UI->getOperand(0);
3024       if (Copies.count(UseChain.getNode()))
3025         // Second CopyToReg
3026         Copy = *UI;
3027       else {
3028         // We are at the top of this chain.
3029         // If the copy has a glue operand, we conservatively assume it
3030         // isn't safe to perform a tail call.
3031         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
3032           return false;
3033         // First CopyToReg
3034         TCChain = UseChain;
3035       }
3036     }
3037   } else if (Copy->getOpcode() == ISD::BITCAST) {
3038     // f32 returned in a single GPR.
3039     if (!Copy->hasOneUse())
3040       return false;
3041     Copy = *Copy->use_begin();
3042     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3043       return false;
3044     // If the copy has a glue operand, we conservatively assume it isn't safe to
3045     // perform a tail call.
3046     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3047       return false;
3048     TCChain = Copy->getOperand(0);
3049   } else {
3050     return false;
3051   }
3052 
3053   bool HasRet = false;
3054   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
3055        UI != UE; ++UI) {
3056     if (UI->getOpcode() != ARMISD::RET_FLAG &&
3057         UI->getOpcode() != ARMISD::INTRET_FLAG)
3058       return false;
3059     HasRet = true;
3060   }
3061 
3062   if (!HasRet)
3063     return false;
3064 
3065   Chain = TCChain;
3066   return true;
3067 }
3068 
3069 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3070   if (!Subtarget->supportsTailCall())
3071     return false;
3072 
3073   if (!CI->isTailCall())
3074     return false;
3075 
3076   return true;
3077 }
3078 
3079 // Trying to write a 64 bit value so need to split into two 32 bit values first,
3080 // and pass the lower and high parts through.
3081 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3082   SDLoc DL(Op);
3083   SDValue WriteValue = Op->getOperand(2);
3084 
3085   // This function is only supposed to be called for i64 type argument.
3086   assert(WriteValue.getValueType() == MVT::i64
3087           && "LowerWRITE_REGISTER called for non-i64 type argument.");
3088 
3089   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3090                            DAG.getConstant(0, DL, MVT::i32));
3091   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3092                            DAG.getConstant(1, DL, MVT::i32));
3093   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3094   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3095 }
3096 
3097 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3098 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3099 // one of the above mentioned nodes. It has to be wrapped because otherwise
3100 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3101 // be used to form addressing mode. These wrapped nodes will be selected
3102 // into MOVi.
3103 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3104                                              SelectionDAG &DAG) const {
3105   EVT PtrVT = Op.getValueType();
3106   // FIXME there is no actual debug info here
3107   SDLoc dl(Op);
3108   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3109   SDValue Res;
3110 
3111   // When generating execute-only code Constant Pools must be promoted to the
3112   // global data section. It's a bit ugly that we can't share them across basic
3113   // blocks, but this way we guarantee that execute-only behaves correct with
3114   // position-independent addressing modes.
3115   if (Subtarget->genExecuteOnly()) {
3116     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3117     auto T = const_cast<Type*>(CP->getType());
3118     auto C = const_cast<Constant*>(CP->getConstVal());
3119     auto M = const_cast<Module*>(DAG.getMachineFunction().
3120                                  getFunction().getParent());
3121     auto GV = new GlobalVariable(
3122                     *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3123                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3124                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3125                     Twine(AFI->createPICLabelUId())
3126                   );
3127     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3128                                             dl, PtrVT);
3129     return LowerGlobalAddress(GA, DAG);
3130   }
3131 
3132   if (CP->isMachineConstantPoolEntry())
3133     Res =
3134         DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
3135   else
3136     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign());
3137   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3138 }
3139 
3140 unsigned ARMTargetLowering::getJumpTableEncoding() const {
3141   return MachineJumpTableInfo::EK_Inline;
3142 }
3143 
3144 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3145                                              SelectionDAG &DAG) const {
3146   MachineFunction &MF = DAG.getMachineFunction();
3147   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3148   unsigned ARMPCLabelIndex = 0;
3149   SDLoc DL(Op);
3150   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3151   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3152   SDValue CPAddr;
3153   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3154   if (!IsPositionIndependent) {
3155     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3156   } else {
3157     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3158     ARMPCLabelIndex = AFI->createPICLabelUId();
3159     ARMConstantPoolValue *CPV =
3160       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3161                                       ARMCP::CPBlockAddress, PCAdj);
3162     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3163   }
3164   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3165   SDValue Result = DAG.getLoad(
3166       PtrVT, DL, DAG.getEntryNode(), CPAddr,
3167       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3168   if (!IsPositionIndependent)
3169     return Result;
3170   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3171   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3172 }
3173 
3174 /// Convert a TLS address reference into the correct sequence of loads
3175 /// and calls to compute the variable's address for Darwin, and return an
3176 /// SDValue containing the final node.
3177 
3178 /// Darwin only has one TLS scheme which must be capable of dealing with the
3179 /// fully general situation, in the worst case. This means:
3180 ///     + "extern __thread" declaration.
3181 ///     + Defined in a possibly unknown dynamic library.
3182 ///
3183 /// The general system is that each __thread variable has a [3 x i32] descriptor
3184 /// which contains information used by the runtime to calculate the address. The
3185 /// only part of this the compiler needs to know about is the first word, which
3186 /// contains a function pointer that must be called with the address of the
3187 /// entire descriptor in "r0".
3188 ///
3189 /// Since this descriptor may be in a different unit, in general access must
3190 /// proceed along the usual ARM rules. A common sequence to produce is:
3191 ///
3192 ///     movw rT1, :lower16:_var$non_lazy_ptr
3193 ///     movt rT1, :upper16:_var$non_lazy_ptr
3194 ///     ldr r0, [rT1]
3195 ///     ldr rT2, [r0]
3196 ///     blx rT2
3197 ///     [...address now in r0...]
3198 SDValue
3199 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3200                                                SelectionDAG &DAG) const {
3201   assert(Subtarget->isTargetDarwin() &&
3202          "This function expects a Darwin target");
3203   SDLoc DL(Op);
3204 
3205   // First step is to get the address of the actua global symbol. This is where
3206   // the TLS descriptor lives.
3207   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3208 
3209   // The first entry in the descriptor is a function pointer that we must call
3210   // to obtain the address of the variable.
3211   SDValue Chain = DAG.getEntryNode();
3212   SDValue FuncTLVGet = DAG.getLoad(
3213       MVT::i32, DL, Chain, DescAddr,
3214       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3215       /* Alignment = */ 4,
3216       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3217           MachineMemOperand::MOInvariant);
3218   Chain = FuncTLVGet.getValue(1);
3219 
3220   MachineFunction &F = DAG.getMachineFunction();
3221   MachineFrameInfo &MFI = F.getFrameInfo();
3222   MFI.setAdjustsStack(true);
3223 
3224   // TLS calls preserve all registers except those that absolutely must be
3225   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3226   // silly).
3227   auto TRI =
3228       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3229   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3230   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3231 
3232   // Finally, we can make the call. This is just a degenerate version of a
3233   // normal AArch64 call node: r0 takes the address of the descriptor, and
3234   // returns the address of the variable in this thread.
3235   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3236   Chain =
3237       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3238                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3239                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3240   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3241 }
3242 
3243 SDValue
3244 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3245                                                 SelectionDAG &DAG) const {
3246   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3247 
3248   SDValue Chain = DAG.getEntryNode();
3249   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3250   SDLoc DL(Op);
3251 
3252   // Load the current TEB (thread environment block)
3253   SDValue Ops[] = {Chain,
3254                    DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3255                    DAG.getTargetConstant(15, DL, MVT::i32),
3256                    DAG.getTargetConstant(0, DL, MVT::i32),
3257                    DAG.getTargetConstant(13, DL, MVT::i32),
3258                    DAG.getTargetConstant(0, DL, MVT::i32),
3259                    DAG.getTargetConstant(2, DL, MVT::i32)};
3260   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3261                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
3262 
3263   SDValue TEB = CurrentTEB.getValue(0);
3264   Chain = CurrentTEB.getValue(1);
3265 
3266   // Load the ThreadLocalStoragePointer from the TEB
3267   // A pointer to the TLS array is located at offset 0x2c from the TEB.
3268   SDValue TLSArray =
3269       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3270   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3271 
3272   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3273   // offset into the TLSArray.
3274 
3275   // Load the TLS index from the C runtime
3276   SDValue TLSIndex =
3277       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3278   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3279   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3280 
3281   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3282                               DAG.getConstant(2, DL, MVT::i32));
3283   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3284                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3285                             MachinePointerInfo());
3286 
3287   // Get the offset of the start of the .tls section (section base)
3288   const auto *GA = cast<GlobalAddressSDNode>(Op);
3289   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3290   SDValue Offset = DAG.getLoad(
3291       PtrVT, DL, Chain,
3292       DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3293                   DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3294       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3295 
3296   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3297 }
3298 
3299 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3300 SDValue
3301 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3302                                                  SelectionDAG &DAG) const {
3303   SDLoc dl(GA);
3304   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3305   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3306   MachineFunction &MF = DAG.getMachineFunction();
3307   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3308   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3309   ARMConstantPoolValue *CPV =
3310     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3311                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3312   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3313   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3314   Argument = DAG.getLoad(
3315       PtrVT, dl, DAG.getEntryNode(), Argument,
3316       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3317   SDValue Chain = Argument.getValue(1);
3318 
3319   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3320   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3321 
3322   // call __tls_get_addr.
3323   ArgListTy Args;
3324   ArgListEntry Entry;
3325   Entry.Node = Argument;
3326   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3327   Args.push_back(Entry);
3328 
3329   // FIXME: is there useful debug info available here?
3330   TargetLowering::CallLoweringInfo CLI(DAG);
3331   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3332       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3333       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3334 
3335   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3336   return CallResult.first;
3337 }
3338 
3339 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3340 // "local exec" model.
3341 SDValue
3342 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3343                                         SelectionDAG &DAG,
3344                                         TLSModel::Model model) const {
3345   const GlobalValue *GV = GA->getGlobal();
3346   SDLoc dl(GA);
3347   SDValue Offset;
3348   SDValue Chain = DAG.getEntryNode();
3349   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3350   // Get the Thread Pointer
3351   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3352 
3353   if (model == TLSModel::InitialExec) {
3354     MachineFunction &MF = DAG.getMachineFunction();
3355     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3356     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3357     // Initial exec model.
3358     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3359     ARMConstantPoolValue *CPV =
3360       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3361                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3362                                       true);
3363     Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3364     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3365     Offset = DAG.getLoad(
3366         PtrVT, dl, Chain, Offset,
3367         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3368     Chain = Offset.getValue(1);
3369 
3370     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3371     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3372 
3373     Offset = DAG.getLoad(
3374         PtrVT, dl, Chain, Offset,
3375         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3376   } else {
3377     // local exec model
3378     assert(model == TLSModel::LocalExec);
3379     ARMConstantPoolValue *CPV =
3380       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3381     Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3382     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3383     Offset = DAG.getLoad(
3384         PtrVT, dl, Chain, Offset,
3385         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3386   }
3387 
3388   // The address of the thread local variable is the add of the thread
3389   // pointer with the offset of the variable.
3390   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3391 }
3392 
3393 SDValue
3394 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3395   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3396   if (DAG.getTarget().useEmulatedTLS())
3397     return LowerToTLSEmulatedModel(GA, DAG);
3398 
3399   if (Subtarget->isTargetDarwin())
3400     return LowerGlobalTLSAddressDarwin(Op, DAG);
3401 
3402   if (Subtarget->isTargetWindows())
3403     return LowerGlobalTLSAddressWindows(Op, DAG);
3404 
3405   // TODO: implement the "local dynamic" model
3406   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3407   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3408 
3409   switch (model) {
3410     case TLSModel::GeneralDynamic:
3411     case TLSModel::LocalDynamic:
3412       return LowerToTLSGeneralDynamicModel(GA, DAG);
3413     case TLSModel::InitialExec:
3414     case TLSModel::LocalExec:
3415       return LowerToTLSExecModels(GA, DAG, model);
3416   }
3417   llvm_unreachable("bogus TLS model");
3418 }
3419 
3420 /// Return true if all users of V are within function F, looking through
3421 /// ConstantExprs.
3422 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3423   SmallVector<const User*,4> Worklist;
3424   for (auto *U : V->users())
3425     Worklist.push_back(U);
3426   while (!Worklist.empty()) {
3427     auto *U = Worklist.pop_back_val();
3428     if (isa<ConstantExpr>(U)) {
3429       for (auto *UU : U->users())
3430         Worklist.push_back(UU);
3431       continue;
3432     }
3433 
3434     auto *I = dyn_cast<Instruction>(U);
3435     if (!I || I->getParent()->getParent() != F)
3436       return false;
3437   }
3438   return true;
3439 }
3440 
3441 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3442                                      const GlobalValue *GV, SelectionDAG &DAG,
3443                                      EVT PtrVT, const SDLoc &dl) {
3444   // If we're creating a pool entry for a constant global with unnamed address,
3445   // and the global is small enough, we can emit it inline into the constant pool
3446   // to save ourselves an indirection.
3447   //
3448   // This is a win if the constant is only used in one function (so it doesn't
3449   // need to be duplicated) or duplicating the constant wouldn't increase code
3450   // size (implying the constant is no larger than 4 bytes).
3451   const Function &F = DAG.getMachineFunction().getFunction();
3452 
3453   // We rely on this decision to inline being idemopotent and unrelated to the
3454   // use-site. We know that if we inline a variable at one use site, we'll
3455   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3456   // doesn't know about this optimization, so bail out if it's enabled else
3457   // we could decide to inline here (and thus never emit the GV) but require
3458   // the GV from fast-isel generated code.
3459   if (!EnableConstpoolPromotion ||
3460       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3461       return SDValue();
3462 
3463   auto *GVar = dyn_cast<GlobalVariable>(GV);
3464   if (!GVar || !GVar->hasInitializer() ||
3465       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3466       !GVar->hasLocalLinkage())
3467     return SDValue();
3468 
3469   // If we inline a value that contains relocations, we move the relocations
3470   // from .data to .text. This is not allowed in position-independent code.
3471   auto *Init = GVar->getInitializer();
3472   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3473       Init->needsRelocation())
3474     return SDValue();
3475 
3476   // The constant islands pass can only really deal with alignment requests
3477   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3478   // any type wanting greater alignment requirements than 4 bytes. We also
3479   // can only promote constants that are multiples of 4 bytes in size or
3480   // are paddable to a multiple of 4. Currently we only try and pad constants
3481   // that are strings for simplicity.
3482   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3483   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3484   unsigned PrefAlign = DAG.getDataLayout().getPreferredAlignment(GVar);
3485   unsigned RequiredPadding = 4 - (Size % 4);
3486   bool PaddingPossible =
3487     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3488   if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3489       Size == 0)
3490     return SDValue();
3491 
3492   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3493   MachineFunction &MF = DAG.getMachineFunction();
3494   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3495 
3496   // We can't bloat the constant pool too much, else the ConstantIslands pass
3497   // may fail to converge. If we haven't promoted this global yet (it may have
3498   // multiple uses), and promoting it would increase the constant pool size (Sz
3499   // > 4), ensure we have space to do so up to MaxTotal.
3500   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3501     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3502         ConstpoolPromotionMaxTotal)
3503       return SDValue();
3504 
3505   // This is only valid if all users are in a single function; we can't clone
3506   // the constant in general. The LLVM IR unnamed_addr allows merging
3507   // constants, but not cloning them.
3508   //
3509   // We could potentially allow cloning if we could prove all uses of the
3510   // constant in the current function don't care about the address, like
3511   // printf format strings. But that isn't implemented for now.
3512   if (!allUsersAreInFunction(GVar, &F))
3513     return SDValue();
3514 
3515   // We're going to inline this global. Pad it out if needed.
3516   if (RequiredPadding != 4) {
3517     StringRef S = CDAInit->getAsString();
3518 
3519     SmallVector<uint8_t,16> V(S.size());
3520     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3521     while (RequiredPadding--)
3522       V.push_back(0);
3523     Init = ConstantDataArray::get(*DAG.getContext(), V);
3524   }
3525 
3526   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3527   SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3528   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3529     AFI->markGlobalAsPromotedToConstantPool(GVar);
3530     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3531                                       PaddedSize - 4);
3532   }
3533   ++NumConstpoolPromoted;
3534   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3535 }
3536 
3537 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3538   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3539     if (!(GV = GA->getBaseObject()))
3540       return false;
3541   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3542     return V->isConstant();
3543   return isa<Function>(GV);
3544 }
3545 
3546 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3547                                               SelectionDAG &DAG) const {
3548   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3549   default: llvm_unreachable("unknown object format");
3550   case Triple::COFF:
3551     return LowerGlobalAddressWindows(Op, DAG);
3552   case Triple::ELF:
3553     return LowerGlobalAddressELF(Op, DAG);
3554   case Triple::MachO:
3555     return LowerGlobalAddressDarwin(Op, DAG);
3556   }
3557 }
3558 
3559 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3560                                                  SelectionDAG &DAG) const {
3561   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3562   SDLoc dl(Op);
3563   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3564   const TargetMachine &TM = getTargetMachine();
3565   bool IsRO = isReadOnly(GV);
3566 
3567   // promoteToConstantPool only if not generating XO text section
3568   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3569     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3570       return V;
3571 
3572   if (isPositionIndependent()) {
3573     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3574     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3575                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3576     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3577     if (UseGOT_PREL)
3578       Result =
3579           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3580                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3581     return Result;
3582   } else if (Subtarget->isROPI() && IsRO) {
3583     // PC-relative.
3584     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3585     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3586     return Result;
3587   } else if (Subtarget->isRWPI() && !IsRO) {
3588     // SB-relative.
3589     SDValue RelAddr;
3590     if (Subtarget->useMovt()) {
3591       ++NumMovwMovt;
3592       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3593       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3594     } else { // use literal pool for address constant
3595       ARMConstantPoolValue *CPV =
3596         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3597       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3598       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3599       RelAddr = DAG.getLoad(
3600           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3601           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3602     }
3603     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3604     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3605     return Result;
3606   }
3607 
3608   // If we have T2 ops, we can materialize the address directly via movt/movw
3609   // pair. This is always cheaper.
3610   if (Subtarget->useMovt()) {
3611     ++NumMovwMovt;
3612     // FIXME: Once remat is capable of dealing with instructions with register
3613     // operands, expand this into two nodes.
3614     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3615                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3616   } else {
3617     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3618     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3619     return DAG.getLoad(
3620         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3621         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3622   }
3623 }
3624 
3625 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3626                                                     SelectionDAG &DAG) const {
3627   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3628          "ROPI/RWPI not currently supported for Darwin");
3629   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3630   SDLoc dl(Op);
3631   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3632 
3633   if (Subtarget->useMovt())
3634     ++NumMovwMovt;
3635 
3636   // FIXME: Once remat is capable of dealing with instructions with register
3637   // operands, expand this into multiple nodes
3638   unsigned Wrapper =
3639       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3640 
3641   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3642   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3643 
3644   if (Subtarget->isGVIndirectSymbol(GV))
3645     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3646                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3647   return Result;
3648 }
3649 
3650 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3651                                                      SelectionDAG &DAG) const {
3652   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3653   assert(Subtarget->useMovt() &&
3654          "Windows on ARM expects to use movw/movt");
3655   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3656          "ROPI/RWPI not currently supported for Windows");
3657 
3658   const TargetMachine &TM = getTargetMachine();
3659   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3660   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3661   if (GV->hasDLLImportStorageClass())
3662     TargetFlags = ARMII::MO_DLLIMPORT;
3663   else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3664     TargetFlags = ARMII::MO_COFFSTUB;
3665   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3666   SDValue Result;
3667   SDLoc DL(Op);
3668 
3669   ++NumMovwMovt;
3670 
3671   // FIXME: Once remat is capable of dealing with instructions with register
3672   // operands, expand this into two nodes.
3673   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3674                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3675                                                   TargetFlags));
3676   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3677     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3678                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3679   return Result;
3680 }
3681 
3682 SDValue
3683 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3684   SDLoc dl(Op);
3685   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3686   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3687                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3688                      Op.getOperand(1), Val);
3689 }
3690 
3691 SDValue
3692 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3693   SDLoc dl(Op);
3694   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3695                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3696 }
3697 
3698 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3699                                                       SelectionDAG &DAG) const {
3700   SDLoc dl(Op);
3701   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3702                      Op.getOperand(0));
3703 }
3704 
3705 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3706     SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3707   unsigned IntNo =
3708       cast<ConstantSDNode>(
3709           Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3710           ->getZExtValue();
3711   switch (IntNo) {
3712     default:
3713       return SDValue();  // Don't custom lower most intrinsics.
3714     case Intrinsic::arm_gnu_eabi_mcount: {
3715       MachineFunction &MF = DAG.getMachineFunction();
3716       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3717       SDLoc dl(Op);
3718       SDValue Chain = Op.getOperand(0);
3719       // call "\01__gnu_mcount_nc"
3720       const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3721       const uint32_t *Mask =
3722           ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3723       assert(Mask && "Missing call preserved mask for calling convention");
3724       // Mark LR an implicit live-in.
3725       unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3726       SDValue ReturnAddress =
3727           DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3728       constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3729       SDValue Callee =
3730           DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3731       SDValue RegisterMask = DAG.getRegisterMask(Mask);
3732       if (Subtarget->isThumb())
3733         return SDValue(
3734             DAG.getMachineNode(
3735                 ARM::tBL_PUSHLR, dl, ResultTys,
3736                 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3737                  DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3738             0);
3739       return SDValue(
3740           DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3741                              {ReturnAddress, Callee, RegisterMask, Chain}),
3742           0);
3743     }
3744   }
3745 }
3746 
3747 SDValue
3748 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3749                                           const ARMSubtarget *Subtarget) const {
3750   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3751   SDLoc dl(Op);
3752   switch (IntNo) {
3753   default: return SDValue();    // Don't custom lower most intrinsics.
3754   case Intrinsic::thread_pointer: {
3755     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3756     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3757   }
3758   case Intrinsic::arm_cls: {
3759     const SDValue &Operand = Op.getOperand(1);
3760     const EVT VTy = Op.getValueType();
3761     SDValue SRA =
3762         DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
3763     SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
3764     SDValue SHL =
3765         DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
3766     SDValue OR =
3767         DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
3768     SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
3769     return Result;
3770   }
3771   case Intrinsic::arm_cls64: {
3772     // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
3773     //          else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
3774     const SDValue &Operand = Op.getOperand(1);
3775     const EVT VTy = Op.getValueType();
3776 
3777     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3778                              DAG.getConstant(1, dl, VTy));
3779     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3780                              DAG.getConstant(0, dl, VTy));
3781     SDValue Constant0 = DAG.getConstant(0, dl, VTy);
3782     SDValue Constant1 = DAG.getConstant(1, dl, VTy);
3783     SDValue Constant31 = DAG.getConstant(31, dl, VTy);
3784     SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
3785     SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
3786     SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
3787     SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
3788     SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
3789     SDValue CheckLo =
3790         DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
3791     SDValue HiIsZero =
3792         DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
3793     SDValue AdjustedLo =
3794         DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
3795     SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
3796     SDValue Result =
3797         DAG.getSelect(dl, VTy, CheckLo,
3798                       DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
3799     return Result;
3800   }
3801   case Intrinsic::eh_sjlj_lsda: {
3802     MachineFunction &MF = DAG.getMachineFunction();
3803     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3804     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3805     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3806     SDValue CPAddr;
3807     bool IsPositionIndependent = isPositionIndependent();
3808     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3809     ARMConstantPoolValue *CPV =
3810       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3811                                       ARMCP::CPLSDA, PCAdj);
3812     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3813     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3814     SDValue Result = DAG.getLoad(
3815         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3816         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3817 
3818     if (IsPositionIndependent) {
3819       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3820       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3821     }
3822     return Result;
3823   }
3824   case Intrinsic::arm_neon_vabs:
3825     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3826                         Op.getOperand(1));
3827   case Intrinsic::arm_neon_vmulls:
3828   case Intrinsic::arm_neon_vmullu: {
3829     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3830       ? ARMISD::VMULLs : ARMISD::VMULLu;
3831     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3832                        Op.getOperand(1), Op.getOperand(2));
3833   }
3834   case Intrinsic::arm_neon_vminnm:
3835   case Intrinsic::arm_neon_vmaxnm: {
3836     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3837       ? ISD::FMINNUM : ISD::FMAXNUM;
3838     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3839                        Op.getOperand(1), Op.getOperand(2));
3840   }
3841   case Intrinsic::arm_neon_vminu:
3842   case Intrinsic::arm_neon_vmaxu: {
3843     if (Op.getValueType().isFloatingPoint())
3844       return SDValue();
3845     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3846       ? ISD::UMIN : ISD::UMAX;
3847     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3848                          Op.getOperand(1), Op.getOperand(2));
3849   }
3850   case Intrinsic::arm_neon_vmins:
3851   case Intrinsic::arm_neon_vmaxs: {
3852     // v{min,max}s is overloaded between signed integers and floats.
3853     if (!Op.getValueType().isFloatingPoint()) {
3854       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3855         ? ISD::SMIN : ISD::SMAX;
3856       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3857                          Op.getOperand(1), Op.getOperand(2));
3858     }
3859     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3860       ? ISD::FMINIMUM : ISD::FMAXIMUM;
3861     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3862                        Op.getOperand(1), Op.getOperand(2));
3863   }
3864   case Intrinsic::arm_neon_vtbl1:
3865     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3866                        Op.getOperand(1), Op.getOperand(2));
3867   case Intrinsic::arm_neon_vtbl2:
3868     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3869                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3870   case Intrinsic::arm_mve_pred_i2v:
3871   case Intrinsic::arm_mve_pred_v2i:
3872     return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
3873                        Op.getOperand(1));
3874   case Intrinsic::arm_mve_vreinterpretq:
3875     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
3876                        Op.getOperand(1));
3877   case Intrinsic::arm_mve_lsll:
3878     return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
3879                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3880   case Intrinsic::arm_mve_asrl:
3881     return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
3882                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3883   }
3884 }
3885 
3886 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3887                                  const ARMSubtarget *Subtarget) {
3888   SDLoc dl(Op);
3889   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3890   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3891   if (SSID == SyncScope::SingleThread)
3892     return Op;
3893 
3894   if (!Subtarget->hasDataBarrier()) {
3895     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3896     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3897     // here.
3898     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3899            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3900     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3901                        DAG.getConstant(0, dl, MVT::i32));
3902   }
3903 
3904   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3905   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3906   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3907   if (Subtarget->isMClass()) {
3908     // Only a full system barrier exists in the M-class architectures.
3909     Domain = ARM_MB::SY;
3910   } else if (Subtarget->preferISHSTBarriers() &&
3911              Ord == AtomicOrdering::Release) {
3912     // Swift happens to implement ISHST barriers in a way that's compatible with
3913     // Release semantics but weaker than ISH so we'd be fools not to use
3914     // it. Beware: other processors probably don't!
3915     Domain = ARM_MB::ISHST;
3916   }
3917 
3918   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3919                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3920                      DAG.getConstant(Domain, dl, MVT::i32));
3921 }
3922 
3923 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3924                              const ARMSubtarget *Subtarget) {
3925   // ARM pre v5TE and Thumb1 does not have preload instructions.
3926   if (!(Subtarget->isThumb2() ||
3927         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3928     // Just preserve the chain.
3929     return Op.getOperand(0);
3930 
3931   SDLoc dl(Op);
3932   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3933   if (!isRead &&
3934       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3935     // ARMv7 with MP extension has PLDW.
3936     return Op.getOperand(0);
3937 
3938   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3939   if (Subtarget->isThumb()) {
3940     // Invert the bits.
3941     isRead = ~isRead & 1;
3942     isData = ~isData & 1;
3943   }
3944 
3945   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3946                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3947                      DAG.getConstant(isData, dl, MVT::i32));
3948 }
3949 
3950 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3951   MachineFunction &MF = DAG.getMachineFunction();
3952   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3953 
3954   // vastart just stores the address of the VarArgsFrameIndex slot into the
3955   // memory location argument.
3956   SDLoc dl(Op);
3957   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3958   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3959   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3960   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3961                       MachinePointerInfo(SV));
3962 }
3963 
3964 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3965                                                 CCValAssign &NextVA,
3966                                                 SDValue &Root,
3967                                                 SelectionDAG &DAG,
3968                                                 const SDLoc &dl) const {
3969   MachineFunction &MF = DAG.getMachineFunction();
3970   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3971 
3972   const TargetRegisterClass *RC;
3973   if (AFI->isThumb1OnlyFunction())
3974     RC = &ARM::tGPRRegClass;
3975   else
3976     RC = &ARM::GPRRegClass;
3977 
3978   // Transform the arguments stored in physical registers into virtual ones.
3979   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3980   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3981 
3982   SDValue ArgValue2;
3983   if (NextVA.isMemLoc()) {
3984     MachineFrameInfo &MFI = MF.getFrameInfo();
3985     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3986 
3987     // Create load node to retrieve arguments from the stack.
3988     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3989     ArgValue2 = DAG.getLoad(
3990         MVT::i32, dl, Root, FIN,
3991         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3992   } else {
3993     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3994     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3995   }
3996   if (!Subtarget->isLittle())
3997     std::swap (ArgValue, ArgValue2);
3998   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3999 }
4000 
4001 // The remaining GPRs hold either the beginning of variable-argument
4002 // data, or the beginning of an aggregate passed by value (usually
4003 // byval).  Either way, we allocate stack slots adjacent to the data
4004 // provided by our caller, and store the unallocated registers there.
4005 // If this is a variadic function, the va_list pointer will begin with
4006 // these values; otherwise, this reassembles a (byval) structure that
4007 // was split between registers and memory.
4008 // Return: The frame index registers were stored into.
4009 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4010                                       const SDLoc &dl, SDValue &Chain,
4011                                       const Value *OrigArg,
4012                                       unsigned InRegsParamRecordIdx,
4013                                       int ArgOffset, unsigned ArgSize) const {
4014   // Currently, two use-cases possible:
4015   // Case #1. Non-var-args function, and we meet first byval parameter.
4016   //          Setup first unallocated register as first byval register;
4017   //          eat all remained registers
4018   //          (these two actions are performed by HandleByVal method).
4019   //          Then, here, we initialize stack frame with
4020   //          "store-reg" instructions.
4021   // Case #2. Var-args function, that doesn't contain byval parameters.
4022   //          The same: eat all remained unallocated registers,
4023   //          initialize stack frame.
4024 
4025   MachineFunction &MF = DAG.getMachineFunction();
4026   MachineFrameInfo &MFI = MF.getFrameInfo();
4027   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4028   unsigned RBegin, REnd;
4029   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4030     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4031   } else {
4032     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4033     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4034     REnd = ARM::R4;
4035   }
4036 
4037   if (REnd != RBegin)
4038     ArgOffset = -4 * (ARM::R4 - RBegin);
4039 
4040   auto PtrVT = getPointerTy(DAG.getDataLayout());
4041   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4042   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4043 
4044   SmallVector<SDValue, 4> MemOps;
4045   const TargetRegisterClass *RC =
4046       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4047 
4048   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4049     unsigned VReg = MF.addLiveIn(Reg, RC);
4050     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4051     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4052                                  MachinePointerInfo(OrigArg, 4 * i));
4053     MemOps.push_back(Store);
4054     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4055   }
4056 
4057   if (!MemOps.empty())
4058     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4059   return FrameIndex;
4060 }
4061 
4062 // Setup stack frame, the va_list pointer will start from.
4063 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4064                                              const SDLoc &dl, SDValue &Chain,
4065                                              unsigned ArgOffset,
4066                                              unsigned TotalArgRegsSaveSize,
4067                                              bool ForceMutable) const {
4068   MachineFunction &MF = DAG.getMachineFunction();
4069   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4070 
4071   // Try to store any remaining integer argument regs
4072   // to their spots on the stack so that they may be loaded by dereferencing
4073   // the result of va_next.
4074   // If there is no regs to be stored, just point address after last
4075   // argument passed via stack.
4076   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
4077                                   CCInfo.getInRegsParamsCount(),
4078                                   CCInfo.getNextStackOffset(),
4079                                   std::max(4U, TotalArgRegsSaveSize));
4080   AFI->setVarArgsFrameIndex(FrameIndex);
4081 }
4082 
4083 SDValue ARMTargetLowering::LowerFormalArguments(
4084     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4085     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4086     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4087   MachineFunction &MF = DAG.getMachineFunction();
4088   MachineFrameInfo &MFI = MF.getFrameInfo();
4089 
4090   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4091 
4092   // Assign locations to all of the incoming arguments.
4093   SmallVector<CCValAssign, 16> ArgLocs;
4094   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4095                  *DAG.getContext());
4096   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4097 
4098   SmallVector<SDValue, 16> ArgValues;
4099   SDValue ArgValue;
4100   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4101   unsigned CurArgIdx = 0;
4102 
4103   // Initially ArgRegsSaveSize is zero.
4104   // Then we increase this value each time we meet byval parameter.
4105   // We also increase this value in case of varargs function.
4106   AFI->setArgRegsSaveSize(0);
4107 
4108   // Calculate the amount of stack space that we need to allocate to store
4109   // byval and variadic arguments that are passed in registers.
4110   // We need to know this before we allocate the first byval or variadic
4111   // argument, as they will be allocated a stack slot below the CFA (Canonical
4112   // Frame Address, the stack pointer at entry to the function).
4113   unsigned ArgRegBegin = ARM::R4;
4114   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4115     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4116       break;
4117 
4118     CCValAssign &VA = ArgLocs[i];
4119     unsigned Index = VA.getValNo();
4120     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4121     if (!Flags.isByVal())
4122       continue;
4123 
4124     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4125     unsigned RBegin, REnd;
4126     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4127     ArgRegBegin = std::min(ArgRegBegin, RBegin);
4128 
4129     CCInfo.nextInRegsParam();
4130   }
4131   CCInfo.rewindByValRegsInfo();
4132 
4133   int lastInsIndex = -1;
4134   if (isVarArg && MFI.hasVAStart()) {
4135     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4136     if (RegIdx != array_lengthof(GPRArgRegs))
4137       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4138   }
4139 
4140   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4141   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4142   auto PtrVT = getPointerTy(DAG.getDataLayout());
4143 
4144   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4145     CCValAssign &VA = ArgLocs[i];
4146     if (Ins[VA.getValNo()].isOrigArg()) {
4147       std::advance(CurOrigArg,
4148                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4149       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4150     }
4151     // Arguments stored in registers.
4152     if (VA.isRegLoc()) {
4153       EVT RegVT = VA.getLocVT();
4154 
4155       if (VA.needsCustom()) {
4156         // f64 and vector types are split up into multiple registers or
4157         // combinations of registers and stack slots.
4158         if (VA.getLocVT() == MVT::v2f64) {
4159           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
4160                                                    Chain, DAG, dl);
4161           VA = ArgLocs[++i]; // skip ahead to next loc
4162           SDValue ArgValue2;
4163           if (VA.isMemLoc()) {
4164             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4165             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4166             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
4167                                     MachinePointerInfo::getFixedStack(
4168                                         DAG.getMachineFunction(), FI));
4169           } else {
4170             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
4171                                              Chain, DAG, dl);
4172           }
4173           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4174           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
4175                                  ArgValue, ArgValue1,
4176                                  DAG.getIntPtrConstant(0, dl));
4177           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
4178                                  ArgValue, ArgValue2,
4179                                  DAG.getIntPtrConstant(1, dl));
4180         } else
4181           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4182       } else {
4183         const TargetRegisterClass *RC;
4184 
4185 
4186         if (RegVT == MVT::f16)
4187           RC = &ARM::HPRRegClass;
4188         else if (RegVT == MVT::f32)
4189           RC = &ARM::SPRRegClass;
4190         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
4191           RC = &ARM::DPRRegClass;
4192         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
4193           RC = &ARM::QPRRegClass;
4194         else if (RegVT == MVT::i32)
4195           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4196                                            : &ARM::GPRRegClass;
4197         else
4198           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4199 
4200         // Transform the arguments in physical registers into virtual ones.
4201         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4202         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4203 
4204         // If this value is passed in r0 and has the returned attribute (e.g.
4205         // C++ 'structors), record this fact for later use.
4206         if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4207           AFI->setPreservesR0();
4208         }
4209       }
4210 
4211       // If this is an 8 or 16-bit value, it is really passed promoted
4212       // to 32 bits.  Insert an assert[sz]ext to capture this, then
4213       // truncate to the right size.
4214       switch (VA.getLocInfo()) {
4215       default: llvm_unreachable("Unknown loc info!");
4216       case CCValAssign::Full: break;
4217       case CCValAssign::BCvt:
4218         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4219         break;
4220       case CCValAssign::SExt:
4221         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4222                                DAG.getValueType(VA.getValVT()));
4223         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4224         break;
4225       case CCValAssign::ZExt:
4226         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4227                                DAG.getValueType(VA.getValVT()));
4228         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4229         break;
4230       }
4231 
4232       InVals.push_back(ArgValue);
4233     } else { // VA.isRegLoc()
4234       // sanity check
4235       assert(VA.isMemLoc());
4236       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4237 
4238       int index = VA.getValNo();
4239 
4240       // Some Ins[] entries become multiple ArgLoc[] entries.
4241       // Process them only once.
4242       if (index != lastInsIndex)
4243         {
4244           ISD::ArgFlagsTy Flags = Ins[index].Flags;
4245           // FIXME: For now, all byval parameter objects are marked mutable.
4246           // This can be changed with more analysis.
4247           // In case of tail call optimization mark all arguments mutable.
4248           // Since they could be overwritten by lowering of arguments in case of
4249           // a tail call.
4250           if (Flags.isByVal()) {
4251             assert(Ins[index].isOrigArg() &&
4252                    "Byval arguments cannot be implicit");
4253             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4254 
4255             int FrameIndex = StoreByValRegs(
4256                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4257                 VA.getLocMemOffset(), Flags.getByValSize());
4258             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4259             CCInfo.nextInRegsParam();
4260           } else {
4261             unsigned FIOffset = VA.getLocMemOffset();
4262             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4263                                            FIOffset, true);
4264 
4265             // Create load nodes to retrieve arguments from the stack.
4266             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4267             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4268                                          MachinePointerInfo::getFixedStack(
4269                                              DAG.getMachineFunction(), FI)));
4270           }
4271           lastInsIndex = index;
4272         }
4273     }
4274   }
4275 
4276   // varargs
4277   if (isVarArg && MFI.hasVAStart())
4278     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4279                          CCInfo.getNextStackOffset(),
4280                          TotalArgRegsSaveSize);
4281 
4282   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4283 
4284   return Chain;
4285 }
4286 
4287 /// isFloatingPointZero - Return true if this is +0.0.
4288 static bool isFloatingPointZero(SDValue Op) {
4289   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4290     return CFP->getValueAPF().isPosZero();
4291   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4292     // Maybe this has already been legalized into the constant pool?
4293     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4294       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4295       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4296         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4297           return CFP->getValueAPF().isPosZero();
4298     }
4299   } else if (Op->getOpcode() == ISD::BITCAST &&
4300              Op->getValueType(0) == MVT::f64) {
4301     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4302     // created by LowerConstantFP().
4303     SDValue BitcastOp = Op->getOperand(0);
4304     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4305         isNullConstant(BitcastOp->getOperand(0)))
4306       return true;
4307   }
4308   return false;
4309 }
4310 
4311 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4312 /// the given operands.
4313 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4314                                      SDValue &ARMcc, SelectionDAG &DAG,
4315                                      const SDLoc &dl) const {
4316   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4317     unsigned C = RHSC->getZExtValue();
4318     if (!isLegalICmpImmediate((int32_t)C)) {
4319       // Constant does not fit, try adjusting it by one.
4320       switch (CC) {
4321       default: break;
4322       case ISD::SETLT:
4323       case ISD::SETGE:
4324         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4325           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4326           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4327         }
4328         break;
4329       case ISD::SETULT:
4330       case ISD::SETUGE:
4331         if (C != 0 && isLegalICmpImmediate(C-1)) {
4332           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4333           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4334         }
4335         break;
4336       case ISD::SETLE:
4337       case ISD::SETGT:
4338         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4339           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4340           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4341         }
4342         break;
4343       case ISD::SETULE:
4344       case ISD::SETUGT:
4345         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4346           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4347           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4348         }
4349         break;
4350       }
4351     }
4352   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4353              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4354     // In ARM and Thumb-2, the compare instructions can shift their second
4355     // operand.
4356     CC = ISD::getSetCCSwappedOperands(CC);
4357     std::swap(LHS, RHS);
4358   }
4359 
4360   // Thumb1 has very limited immediate modes, so turning an "and" into a
4361   // shift can save multiple instructions.
4362   //
4363   // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4364   // into "((x << n) >> n)".  But that isn't necessarily profitable on its
4365   // own. If it's the operand to an unsigned comparison with an immediate,
4366   // we can eliminate one of the shifts: we transform
4367   // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4368   //
4369   // We avoid transforming cases which aren't profitable due to encoding
4370   // details:
4371   //
4372   // 1. C2 fits into the immediate field of a cmp, and the transformed version
4373   // would not; in that case, we're essentially trading one immediate load for
4374   // another.
4375   // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4376   // 3. C2 is zero; we have other code for this special case.
4377   //
4378   // FIXME: Figure out profitability for Thumb2; we usually can't save an
4379   // instruction, since the AND is always one instruction anyway, but we could
4380   // use narrow instructions in some cases.
4381   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4382       LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4383       LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4384       !isSignedIntSetCC(CC)) {
4385     unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4386     auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4387     uint64_t RHSV = RHSC->getZExtValue();
4388     if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4389       unsigned ShiftBits = countLeadingZeros(Mask);
4390       if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4391         SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4392         LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4393         RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4394       }
4395     }
4396   }
4397 
4398   // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4399   // single "lsls x, c+1".  The shift sets the "C" and "Z" flags the same
4400   // way a cmp would.
4401   // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4402   // some tweaks to the heuristics for the previous and->shift transform.
4403   // FIXME: Optimize cases where the LHS isn't a shift.
4404   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4405       isa<ConstantSDNode>(RHS) &&
4406       cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4407       CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4408       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4409     unsigned ShiftAmt =
4410       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4411     SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4412                                 DAG.getVTList(MVT::i32, MVT::i32),
4413                                 LHS.getOperand(0),
4414                                 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4415     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4416                                      Shift.getValue(1), SDValue());
4417     ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4418     return Chain.getValue(1);
4419   }
4420 
4421   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4422 
4423   // If the RHS is a constant zero then the V (overflow) flag will never be
4424   // set. This can allow us to simplify GE to PL or LT to MI, which can be
4425   // simpler for other passes (like the peephole optimiser) to deal with.
4426   if (isNullConstant(RHS)) {
4427     switch (CondCode) {
4428       default: break;
4429       case ARMCC::GE:
4430         CondCode = ARMCC::PL;
4431         break;
4432       case ARMCC::LT:
4433         CondCode = ARMCC::MI;
4434         break;
4435     }
4436   }
4437 
4438   ARMISD::NodeType CompareType;
4439   switch (CondCode) {
4440   default:
4441     CompareType = ARMISD::CMP;
4442     break;
4443   case ARMCC::EQ:
4444   case ARMCC::NE:
4445     // Uses only Z Flag
4446     CompareType = ARMISD::CMPZ;
4447     break;
4448   }
4449   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4450   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4451 }
4452 
4453 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4454 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4455                                      SelectionDAG &DAG, const SDLoc &dl,
4456                                      bool Signaling) const {
4457   assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4458   SDValue Cmp;
4459   if (!isFloatingPointZero(RHS))
4460     Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP,
4461                       dl, MVT::Glue, LHS, RHS);
4462   else
4463     Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0,
4464                       dl, MVT::Glue, LHS);
4465   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4466 }
4467 
4468 /// duplicateCmp - Glue values can have only one use, so this function
4469 /// duplicates a comparison node.
4470 SDValue
4471 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4472   unsigned Opc = Cmp.getOpcode();
4473   SDLoc DL(Cmp);
4474   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4475     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4476 
4477   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4478   Cmp = Cmp.getOperand(0);
4479   Opc = Cmp.getOpcode();
4480   if (Opc == ARMISD::CMPFP)
4481     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4482   else {
4483     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4484     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4485   }
4486   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4487 }
4488 
4489 // This function returns three things: the arithmetic computation itself
4490 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
4491 // comparison and the condition code define the case in which the arithmetic
4492 // computation *does not* overflow.
4493 std::pair<SDValue, SDValue>
4494 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4495                                  SDValue &ARMcc) const {
4496   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
4497 
4498   SDValue Value, OverflowCmp;
4499   SDValue LHS = Op.getOperand(0);
4500   SDValue RHS = Op.getOperand(1);
4501   SDLoc dl(Op);
4502 
4503   // FIXME: We are currently always generating CMPs because we don't support
4504   // generating CMN through the backend. This is not as good as the natural
4505   // CMP case because it causes a register dependency and cannot be folded
4506   // later.
4507 
4508   switch (Op.getOpcode()) {
4509   default:
4510     llvm_unreachable("Unknown overflow instruction!");
4511   case ISD::SADDO:
4512     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4513     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4514     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4515     break;
4516   case ISD::UADDO:
4517     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4518     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4519     // We do not use it in the USUBO case as Value may not be used.
4520     Value = DAG.getNode(ARMISD::ADDC, dl,
4521                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4522                 .getValue(0);
4523     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4524     break;
4525   case ISD::SSUBO:
4526     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4527     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4528     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4529     break;
4530   case ISD::USUBO:
4531     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4532     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4533     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4534     break;
4535   case ISD::UMULO:
4536     // We generate a UMUL_LOHI and then check if the high word is 0.
4537     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4538     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4539                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4540                         LHS, RHS);
4541     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4542                               DAG.getConstant(0, dl, MVT::i32));
4543     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4544     break;
4545   case ISD::SMULO:
4546     // We generate a SMUL_LOHI and then check if all the bits of the high word
4547     // are the same as the sign bit of the low word.
4548     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4549     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4550                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4551                         LHS, RHS);
4552     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4553                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4554                                           Value.getValue(0),
4555                                           DAG.getConstant(31, dl, MVT::i32)));
4556     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4557     break;
4558   } // switch (...)
4559 
4560   return std::make_pair(Value, OverflowCmp);
4561 }
4562 
4563 SDValue
4564 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4565   // Let legalize expand this if it isn't a legal type yet.
4566   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4567     return SDValue();
4568 
4569   SDValue Value, OverflowCmp;
4570   SDValue ARMcc;
4571   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4572   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4573   SDLoc dl(Op);
4574   // We use 0 and 1 as false and true values.
4575   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4576   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4577   EVT VT = Op.getValueType();
4578 
4579   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4580                                  ARMcc, CCR, OverflowCmp);
4581 
4582   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4583   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4584 }
4585 
4586 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4587                                               SelectionDAG &DAG) {
4588   SDLoc DL(BoolCarry);
4589   EVT CarryVT = BoolCarry.getValueType();
4590 
4591   // This converts the boolean value carry into the carry flag by doing
4592   // ARMISD::SUBC Carry, 1
4593   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4594                               DAG.getVTList(CarryVT, MVT::i32),
4595                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
4596   return Carry.getValue(1);
4597 }
4598 
4599 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4600                                               SelectionDAG &DAG) {
4601   SDLoc DL(Flags);
4602 
4603   // Now convert the carry flag into a boolean carry. We do this
4604   // using ARMISD:ADDE 0, 0, Carry
4605   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4606                      DAG.getConstant(0, DL, MVT::i32),
4607                      DAG.getConstant(0, DL, MVT::i32), Flags);
4608 }
4609 
4610 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4611                                              SelectionDAG &DAG) const {
4612   // Let legalize expand this if it isn't a legal type yet.
4613   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4614     return SDValue();
4615 
4616   SDValue LHS = Op.getOperand(0);
4617   SDValue RHS = Op.getOperand(1);
4618   SDLoc dl(Op);
4619 
4620   EVT VT = Op.getValueType();
4621   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4622   SDValue Value;
4623   SDValue Overflow;
4624   switch (Op.getOpcode()) {
4625   default:
4626     llvm_unreachable("Unknown overflow instruction!");
4627   case ISD::UADDO:
4628     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4629     // Convert the carry flag into a boolean value.
4630     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4631     break;
4632   case ISD::USUBO: {
4633     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4634     // Convert the carry flag into a boolean value.
4635     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4636     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4637     // value. So compute 1 - C.
4638     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4639                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4640     break;
4641   }
4642   }
4643 
4644   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4645 }
4646 
4647 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4648                                const ARMSubtarget *Subtarget) {
4649   EVT VT = Op.getValueType();
4650   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
4651     return SDValue();
4652   if (!VT.isSimple())
4653     return SDValue();
4654 
4655   unsigned NewOpcode;
4656   bool IsAdd = Op->getOpcode() == ISD::SADDSAT;
4657   switch (VT.getSimpleVT().SimpleTy) {
4658   default:
4659     return SDValue();
4660   case MVT::i8:
4661     NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b;
4662     break;
4663   case MVT::i16:
4664     NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b;
4665     break;
4666   }
4667 
4668   SDLoc dl(Op);
4669   SDValue Add =
4670       DAG.getNode(NewOpcode, dl, MVT::i32,
4671                   DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
4672                   DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
4673   return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
4674 }
4675 
4676 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4677   SDValue Cond = Op.getOperand(0);
4678   SDValue SelectTrue = Op.getOperand(1);
4679   SDValue SelectFalse = Op.getOperand(2);
4680   SDLoc dl(Op);
4681   unsigned Opc = Cond.getOpcode();
4682 
4683   if (Cond.getResNo() == 1 &&
4684       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4685        Opc == ISD::USUBO)) {
4686     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4687       return SDValue();
4688 
4689     SDValue Value, OverflowCmp;
4690     SDValue ARMcc;
4691     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4692     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4693     EVT VT = Op.getValueType();
4694 
4695     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4696                    OverflowCmp, DAG);
4697   }
4698 
4699   // Convert:
4700   //
4701   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4702   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4703   //
4704   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4705     const ConstantSDNode *CMOVTrue =
4706       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4707     const ConstantSDNode *CMOVFalse =
4708       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4709 
4710     if (CMOVTrue && CMOVFalse) {
4711       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4712       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4713 
4714       SDValue True;
4715       SDValue False;
4716       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4717         True = SelectTrue;
4718         False = SelectFalse;
4719       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4720         True = SelectFalse;
4721         False = SelectTrue;
4722       }
4723 
4724       if (True.getNode() && False.getNode()) {
4725         EVT VT = Op.getValueType();
4726         SDValue ARMcc = Cond.getOperand(2);
4727         SDValue CCR = Cond.getOperand(3);
4728         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4729         assert(True.getValueType() == VT);
4730         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4731       }
4732     }
4733   }
4734 
4735   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4736   // undefined bits before doing a full-word comparison with zero.
4737   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4738                      DAG.getConstant(1, dl, Cond.getValueType()));
4739 
4740   return DAG.getSelectCC(dl, Cond,
4741                          DAG.getConstant(0, dl, Cond.getValueType()),
4742                          SelectTrue, SelectFalse, ISD::SETNE);
4743 }
4744 
4745 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4746                                  bool &swpCmpOps, bool &swpVselOps) {
4747   // Start by selecting the GE condition code for opcodes that return true for
4748   // 'equality'
4749   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4750       CC == ISD::SETULE || CC == ISD::SETGE  || CC == ISD::SETLE)
4751     CondCode = ARMCC::GE;
4752 
4753   // and GT for opcodes that return false for 'equality'.
4754   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4755            CC == ISD::SETULT || CC == ISD::SETGT  || CC == ISD::SETLT)
4756     CondCode = ARMCC::GT;
4757 
4758   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4759   // to swap the compare operands.
4760   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4761       CC == ISD::SETULT || CC == ISD::SETLE  || CC == ISD::SETLT)
4762     swpCmpOps = true;
4763 
4764   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4765   // If we have an unordered opcode, we need to swap the operands to the VSEL
4766   // instruction (effectively negating the condition).
4767   //
4768   // This also has the effect of swapping which one of 'less' or 'greater'
4769   // returns true, so we also swap the compare operands. It also switches
4770   // whether we return true for 'equality', so we compensate by picking the
4771   // opposite condition code to our original choice.
4772   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4773       CC == ISD::SETUGT) {
4774     swpCmpOps = !swpCmpOps;
4775     swpVselOps = !swpVselOps;
4776     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4777   }
4778 
4779   // 'ordered' is 'anything but unordered', so use the VS condition code and
4780   // swap the VSEL operands.
4781   if (CC == ISD::SETO) {
4782     CondCode = ARMCC::VS;
4783     swpVselOps = true;
4784   }
4785 
4786   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4787   // code and swap the VSEL operands. Also do this if we don't care about the
4788   // unordered case.
4789   if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4790     CondCode = ARMCC::EQ;
4791     swpVselOps = true;
4792   }
4793 }
4794 
4795 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4796                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4797                                    SDValue Cmp, SelectionDAG &DAG) const {
4798   if (!Subtarget->hasFP64() && VT == MVT::f64) {
4799     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4800                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4801     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4802                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4803 
4804     SDValue TrueLow = TrueVal.getValue(0);
4805     SDValue TrueHigh = TrueVal.getValue(1);
4806     SDValue FalseLow = FalseVal.getValue(0);
4807     SDValue FalseHigh = FalseVal.getValue(1);
4808 
4809     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4810                               ARMcc, CCR, Cmp);
4811     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4812                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4813 
4814     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4815   } else {
4816     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4817                        Cmp);
4818   }
4819 }
4820 
4821 static bool isGTorGE(ISD::CondCode CC) {
4822   return CC == ISD::SETGT || CC == ISD::SETGE;
4823 }
4824 
4825 static bool isLTorLE(ISD::CondCode CC) {
4826   return CC == ISD::SETLT || CC == ISD::SETLE;
4827 }
4828 
4829 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4830 // All of these conditions (and their <= and >= counterparts) will do:
4831 //          x < k ? k : x
4832 //          x > k ? x : k
4833 //          k < x ? x : k
4834 //          k > x ? k : x
4835 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4836                             const SDValue TrueVal, const SDValue FalseVal,
4837                             const ISD::CondCode CC, const SDValue K) {
4838   return (isGTorGE(CC) &&
4839           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4840          (isLTorLE(CC) &&
4841           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4842 }
4843 
4844 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4845 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4846                             const SDValue TrueVal, const SDValue FalseVal,
4847                             const ISD::CondCode CC, const SDValue K) {
4848   return (isGTorGE(CC) &&
4849           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4850          (isLTorLE(CC) &&
4851           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4852 }
4853 
4854 // Check if two chained conditionals could be converted into SSAT or USAT.
4855 //
4856 // SSAT can replace a set of two conditional selectors that bound a number to an
4857 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4858 //
4859 //     x < -k ? -k : (x > k ? k : x)
4860 //     x < -k ? -k : (x < k ? x : k)
4861 //     x > -k ? (x > k ? k : x) : -k
4862 //     x < k ? (x < -k ? -k : x) : k
4863 //     etc.
4864 //
4865 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4866 // a power of 2.
4867 //
4868 // It returns true if the conversion can be done, false otherwise.
4869 // Additionally, the variable is returned in parameter V, the constant in K and
4870 // usat is set to true if the conditional represents an unsigned saturation
4871 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4872                                     uint64_t &K, bool &usat) {
4873   SDValue LHS1 = Op.getOperand(0);
4874   SDValue RHS1 = Op.getOperand(1);
4875   SDValue TrueVal1 = Op.getOperand(2);
4876   SDValue FalseVal1 = Op.getOperand(3);
4877   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4878 
4879   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4880   if (Op2.getOpcode() != ISD::SELECT_CC)
4881     return false;
4882 
4883   SDValue LHS2 = Op2.getOperand(0);
4884   SDValue RHS2 = Op2.getOperand(1);
4885   SDValue TrueVal2 = Op2.getOperand(2);
4886   SDValue FalseVal2 = Op2.getOperand(3);
4887   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4888 
4889   // Find out which are the constants and which are the variables
4890   // in each conditional
4891   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4892                                                         ? &RHS1
4893                                                         : nullptr;
4894   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4895                                                         ? &RHS2
4896                                                         : nullptr;
4897   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4898   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4899   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4900   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4901 
4902   // We must detect cases where the original operations worked with 16- or
4903   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4904   // must work with sign-extended values but the select operations return
4905   // the original non-extended value.
4906   SDValue V2TmpReg = V2Tmp;
4907   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4908     V2TmpReg = V2Tmp->getOperand(0);
4909 
4910   // Check that the registers and the constants have the correct values
4911   // in both conditionals
4912   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4913       V2TmpReg != V2)
4914     return false;
4915 
4916   // Figure out which conditional is saturating the lower/upper bound.
4917   const SDValue *LowerCheckOp =
4918       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4919           ? &Op
4920           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4921                 ? &Op2
4922                 : nullptr;
4923   const SDValue *UpperCheckOp =
4924       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4925           ? &Op
4926           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4927                 ? &Op2
4928                 : nullptr;
4929 
4930   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4931     return false;
4932 
4933   // Check that the constant in the lower-bound check is
4934   // the opposite of the constant in the upper-bound check
4935   // in 1's complement.
4936   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4937   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4938   int64_t PosVal = std::max(Val1, Val2);
4939   int64_t NegVal = std::min(Val1, Val2);
4940 
4941   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4942        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4943       isPowerOf2_64(PosVal + 1)) {
4944 
4945     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4946     if (Val1 == ~Val2)
4947       usat = false;
4948     else if (NegVal == 0)
4949       usat = true;
4950     else
4951       return false;
4952 
4953     V = V2;
4954     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4955 
4956     return true;
4957   }
4958 
4959   return false;
4960 }
4961 
4962 // Check if a condition of the type x < k ? k : x can be converted into a
4963 // bit operation instead of conditional moves.
4964 // Currently this is allowed given:
4965 // - The conditions and values match up
4966 // - k is 0 or -1 (all ones)
4967 // This function will not check the last condition, thats up to the caller
4968 // It returns true if the transformation can be made, and in such case
4969 // returns x in V, and k in SatK.
4970 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4971                                          SDValue &SatK)
4972 {
4973   SDValue LHS = Op.getOperand(0);
4974   SDValue RHS = Op.getOperand(1);
4975   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4976   SDValue TrueVal = Op.getOperand(2);
4977   SDValue FalseVal = Op.getOperand(3);
4978 
4979   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4980                                                ? &RHS
4981                                                : nullptr;
4982 
4983   // No constant operation in comparison, early out
4984   if (!K)
4985     return false;
4986 
4987   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4988   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4989   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4990 
4991   // If the constant on left and right side, or variable on left and right,
4992   // does not match, early out
4993   if (*K != KTmp || V != VTmp)
4994     return false;
4995 
4996   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4997     SatK = *K;
4998     return true;
4999   }
5000 
5001   return false;
5002 }
5003 
5004 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5005   if (VT == MVT::f32)
5006     return !Subtarget->hasVFP2Base();
5007   if (VT == MVT::f64)
5008     return !Subtarget->hasFP64();
5009   if (VT == MVT::f16)
5010     return !Subtarget->hasFullFP16();
5011   return false;
5012 }
5013 
5014 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5015   EVT VT = Op.getValueType();
5016   SDLoc dl(Op);
5017 
5018   // Try to convert two saturating conditional selects into a single SSAT
5019   SDValue SatValue;
5020   uint64_t SatConstant;
5021   bool SatUSat;
5022   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
5023       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
5024     if (SatUSat)
5025       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
5026                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
5027     else
5028       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
5029                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
5030   }
5031 
5032   // Try to convert expressions of the form x < k ? k : x (and similar forms)
5033   // into more efficient bit operations, which is possible when k is 0 or -1
5034   // On ARM and Thumb-2 which have flexible operand 2 this will result in
5035   // single instructions. On Thumb the shift and the bit operation will be two
5036   // instructions.
5037   // Only allow this transformation on full-width (32-bit) operations
5038   SDValue LowerSatConstant;
5039   if (VT == MVT::i32 &&
5040       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5041     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5042                                  DAG.getConstant(31, dl, VT));
5043     if (isNullConstant(LowerSatConstant)) {
5044       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5045                                       DAG.getAllOnesConstant(dl, VT));
5046       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5047     } else if (isAllOnesConstant(LowerSatConstant))
5048       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5049   }
5050 
5051   SDValue LHS = Op.getOperand(0);
5052   SDValue RHS = Op.getOperand(1);
5053   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5054   SDValue TrueVal = Op.getOperand(2);
5055   SDValue FalseVal = Op.getOperand(3);
5056   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5057   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5058 
5059   if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
5060       LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
5061     unsigned TVal = CTVal->getZExtValue();
5062     unsigned FVal = CFVal->getZExtValue();
5063     unsigned Opcode = 0;
5064 
5065     if (TVal == ~FVal) {
5066       Opcode = ARMISD::CSINV;
5067     } else if (TVal == ~FVal + 1) {
5068       Opcode = ARMISD::CSNEG;
5069     } else if (TVal + 1 == FVal) {
5070       Opcode = ARMISD::CSINC;
5071     } else if (TVal == FVal + 1) {
5072       Opcode = ARMISD::CSINC;
5073       std::swap(TrueVal, FalseVal);
5074       std::swap(TVal, FVal);
5075       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5076     }
5077 
5078     if (Opcode) {
5079       // If one of the constants is cheaper than another, materialise the
5080       // cheaper one and let the csel generate the other.
5081       if (Opcode != ARMISD::CSINC &&
5082           HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5083         std::swap(TrueVal, FalseVal);
5084         std::swap(TVal, FVal);
5085         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5086       }
5087 
5088       // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5089       // to get there. CSINC not is invertable like the other two (~(~a) == a,
5090       // -(-a) == a, but (a+1)+1 != a).
5091       if (FVal == 0 && Opcode != ARMISD::CSINC) {
5092         std::swap(TrueVal, FalseVal);
5093         std::swap(TVal, FVal);
5094         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5095       }
5096       if (TVal == 0)
5097         TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
5098 
5099       // Drops F's value because we can get it by inverting/negating TVal.
5100       FalseVal = TrueVal;
5101 
5102       SDValue ARMcc;
5103       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5104       EVT VT = TrueVal.getValueType();
5105       return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
5106     }
5107   }
5108 
5109   if (isUnsupportedFloatingType(LHS.getValueType())) {
5110     DAG.getTargetLoweringInfo().softenSetCCOperands(
5111         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5112 
5113     // If softenSetCCOperands only returned one value, we should compare it to
5114     // zero.
5115     if (!RHS.getNode()) {
5116       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5117       CC = ISD::SETNE;
5118     }
5119   }
5120 
5121   if (LHS.getValueType() == MVT::i32) {
5122     // Try to generate VSEL on ARMv8.
5123     // The VSEL instruction can't use all the usual ARM condition
5124     // codes: it only has two bits to select the condition code, so it's
5125     // constrained to use only GE, GT, VS and EQ.
5126     //
5127     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5128     // swap the operands of the previous compare instruction (effectively
5129     // inverting the compare condition, swapping 'less' and 'greater') and
5130     // sometimes need to swap the operands to the VSEL (which inverts the
5131     // condition in the sense of firing whenever the previous condition didn't)
5132     if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5133                                         TrueVal.getValueType() == MVT::f32 ||
5134                                         TrueVal.getValueType() == MVT::f64)) {
5135       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5136       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5137           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5138         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5139         std::swap(TrueVal, FalseVal);
5140       }
5141     }
5142 
5143     SDValue ARMcc;
5144     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5145     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5146     // Choose GE over PL, which vsel does now support
5147     if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
5148       ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5149     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5150   }
5151 
5152   ARMCC::CondCodes CondCode, CondCode2;
5153   FPCCToARMCC(CC, CondCode, CondCode2);
5154 
5155   // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5156   // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5157   // must use VSEL (limited condition codes), due to not having conditional f16
5158   // moves.
5159   if (Subtarget->hasFPARMv8Base() &&
5160       !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5161       (TrueVal.getValueType() == MVT::f16 ||
5162        TrueVal.getValueType() == MVT::f32 ||
5163        TrueVal.getValueType() == MVT::f64)) {
5164     bool swpCmpOps = false;
5165     bool swpVselOps = false;
5166     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5167 
5168     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5169         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5170       if (swpCmpOps)
5171         std::swap(LHS, RHS);
5172       if (swpVselOps)
5173         std::swap(TrueVal, FalseVal);
5174     }
5175   }
5176 
5177   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5178   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5179   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5180   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5181   if (CondCode2 != ARMCC::AL) {
5182     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5183     // FIXME: Needs another CMP because flag can have but one use.
5184     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5185     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5186   }
5187   return Result;
5188 }
5189 
5190 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
5191 /// to morph to an integer compare sequence.
5192 static bool canChangeToInt(SDValue Op, bool &SeenZero,
5193                            const ARMSubtarget *Subtarget) {
5194   SDNode *N = Op.getNode();
5195   if (!N->hasOneUse())
5196     // Otherwise it requires moving the value from fp to integer registers.
5197     return false;
5198   if (!N->getNumValues())
5199     return false;
5200   EVT VT = Op.getValueType();
5201   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5202     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5203     // vmrs are very slow, e.g. cortex-a8.
5204     return false;
5205 
5206   if (isFloatingPointZero(Op)) {
5207     SeenZero = true;
5208     return true;
5209   }
5210   return ISD::isNormalLoad(N);
5211 }
5212 
5213 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5214   if (isFloatingPointZero(Op))
5215     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5216 
5217   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5218     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5219                        Ld->getPointerInfo(), Ld->getAlignment(),
5220                        Ld->getMemOperand()->getFlags());
5221 
5222   llvm_unreachable("Unknown VFP cmp argument!");
5223 }
5224 
5225 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5226                            SDValue &RetVal1, SDValue &RetVal2) {
5227   SDLoc dl(Op);
5228 
5229   if (isFloatingPointZero(Op)) {
5230     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5231     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5232     return;
5233   }
5234 
5235   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5236     SDValue Ptr = Ld->getBasePtr();
5237     RetVal1 =
5238         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5239                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5240 
5241     EVT PtrType = Ptr.getValueType();
5242     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5243     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5244                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5245     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5246                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
5247                           Ld->getMemOperand()->getFlags());
5248     return;
5249   }
5250 
5251   llvm_unreachable("Unknown VFP cmp argument!");
5252 }
5253 
5254 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5255 /// f32 and even f64 comparisons to integer ones.
5256 SDValue
5257 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5258   SDValue Chain = Op.getOperand(0);
5259   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5260   SDValue LHS = Op.getOperand(2);
5261   SDValue RHS = Op.getOperand(3);
5262   SDValue Dest = Op.getOperand(4);
5263   SDLoc dl(Op);
5264 
5265   bool LHSSeenZero = false;
5266   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5267   bool RHSSeenZero = false;
5268   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5269   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5270     // If unsafe fp math optimization is enabled and there are no other uses of
5271     // the CMP operands, and the condition code is EQ or NE, we can optimize it
5272     // to an integer comparison.
5273     if (CC == ISD::SETOEQ)
5274       CC = ISD::SETEQ;
5275     else if (CC == ISD::SETUNE)
5276       CC = ISD::SETNE;
5277 
5278     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5279     SDValue ARMcc;
5280     if (LHS.getValueType() == MVT::f32) {
5281       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5282                         bitcastf32Toi32(LHS, DAG), Mask);
5283       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5284                         bitcastf32Toi32(RHS, DAG), Mask);
5285       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5286       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5287       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5288                          Chain, Dest, ARMcc, CCR, Cmp);
5289     }
5290 
5291     SDValue LHS1, LHS2;
5292     SDValue RHS1, RHS2;
5293     expandf64Toi32(LHS, DAG, LHS1, LHS2);
5294     expandf64Toi32(RHS, DAG, RHS1, RHS2);
5295     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5296     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5297     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5298     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5299     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5300     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5301     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5302   }
5303 
5304   return SDValue();
5305 }
5306 
5307 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5308   SDValue Chain = Op.getOperand(0);
5309   SDValue Cond = Op.getOperand(1);
5310   SDValue Dest = Op.getOperand(2);
5311   SDLoc dl(Op);
5312 
5313   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5314   // instruction.
5315   unsigned Opc = Cond.getOpcode();
5316   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5317                       !Subtarget->isThumb1Only();
5318   if (Cond.getResNo() == 1 &&
5319       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5320        Opc == ISD::USUBO || OptimizeMul)) {
5321     // Only lower legal XALUO ops.
5322     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5323       return SDValue();
5324 
5325     // The actual operation with overflow check.
5326     SDValue Value, OverflowCmp;
5327     SDValue ARMcc;
5328     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5329 
5330     // Reverse the condition code.
5331     ARMCC::CondCodes CondCode =
5332         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5333     CondCode = ARMCC::getOppositeCondition(CondCode);
5334     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5335     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5336 
5337     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5338                        OverflowCmp);
5339   }
5340 
5341   return SDValue();
5342 }
5343 
5344 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5345   SDValue Chain = Op.getOperand(0);
5346   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5347   SDValue LHS = Op.getOperand(2);
5348   SDValue RHS = Op.getOperand(3);
5349   SDValue Dest = Op.getOperand(4);
5350   SDLoc dl(Op);
5351 
5352   if (isUnsupportedFloatingType(LHS.getValueType())) {
5353     DAG.getTargetLoweringInfo().softenSetCCOperands(
5354         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5355 
5356     // If softenSetCCOperands only returned one value, we should compare it to
5357     // zero.
5358     if (!RHS.getNode()) {
5359       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5360       CC = ISD::SETNE;
5361     }
5362   }
5363 
5364   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5365   // instruction.
5366   unsigned Opc = LHS.getOpcode();
5367   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5368                       !Subtarget->isThumb1Only();
5369   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5370       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5371        Opc == ISD::USUBO || OptimizeMul) &&
5372       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5373     // Only lower legal XALUO ops.
5374     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5375       return SDValue();
5376 
5377     // The actual operation with overflow check.
5378     SDValue Value, OverflowCmp;
5379     SDValue ARMcc;
5380     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5381 
5382     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5383       // Reverse the condition code.
5384       ARMCC::CondCodes CondCode =
5385           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5386       CondCode = ARMCC::getOppositeCondition(CondCode);
5387       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5388     }
5389     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5390 
5391     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5392                        OverflowCmp);
5393   }
5394 
5395   if (LHS.getValueType() == MVT::i32) {
5396     SDValue ARMcc;
5397     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5398     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5399     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5400                        Chain, Dest, ARMcc, CCR, Cmp);
5401   }
5402 
5403   if (getTargetMachine().Options.UnsafeFPMath &&
5404       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5405        CC == ISD::SETNE || CC == ISD::SETUNE)) {
5406     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5407       return Result;
5408   }
5409 
5410   ARMCC::CondCodes CondCode, CondCode2;
5411   FPCCToARMCC(CC, CondCode, CondCode2);
5412 
5413   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5414   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5415   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5416   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5417   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5418   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5419   if (CondCode2 != ARMCC::AL) {
5420     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5421     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5422     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5423   }
5424   return Res;
5425 }
5426 
5427 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5428   SDValue Chain = Op.getOperand(0);
5429   SDValue Table = Op.getOperand(1);
5430   SDValue Index = Op.getOperand(2);
5431   SDLoc dl(Op);
5432 
5433   EVT PTy = getPointerTy(DAG.getDataLayout());
5434   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5435   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5436   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5437   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5438   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5439   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5440     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5441     // which does another jump to the destination. This also makes it easier
5442     // to translate it to TBB / TBH later (Thumb2 only).
5443     // FIXME: This might not work if the function is extremely large.
5444     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5445                        Addr, Op.getOperand(2), JTI);
5446   }
5447   if (isPositionIndependent() || Subtarget->isROPI()) {
5448     Addr =
5449         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5450                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5451     Chain = Addr.getValue(1);
5452     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5453     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5454   } else {
5455     Addr =
5456         DAG.getLoad(PTy, dl, Chain, Addr,
5457                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5458     Chain = Addr.getValue(1);
5459     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5460   }
5461 }
5462 
5463 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5464   EVT VT = Op.getValueType();
5465   SDLoc dl(Op);
5466 
5467   if (Op.getValueType().getVectorElementType() == MVT::i32) {
5468     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5469       return Op;
5470     return DAG.UnrollVectorOp(Op.getNode());
5471   }
5472 
5473   const bool HasFullFP16 =
5474     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5475 
5476   EVT NewTy;
5477   const EVT OpTy = Op.getOperand(0).getValueType();
5478   if (OpTy == MVT::v4f32)
5479     NewTy = MVT::v4i32;
5480   else if (OpTy == MVT::v4f16 && HasFullFP16)
5481     NewTy = MVT::v4i16;
5482   else if (OpTy == MVT::v8f16 && HasFullFP16)
5483     NewTy = MVT::v8i16;
5484   else
5485     llvm_unreachable("Invalid type for custom lowering!");
5486 
5487   if (VT != MVT::v4i16 && VT != MVT::v8i16)
5488     return DAG.UnrollVectorOp(Op.getNode());
5489 
5490   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5491   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5492 }
5493 
5494 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5495   EVT VT = Op.getValueType();
5496   if (VT.isVector())
5497     return LowerVectorFP_TO_INT(Op, DAG);
5498 
5499   bool IsStrict = Op->isStrictFPOpcode();
5500   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5501 
5502   if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5503     RTLIB::Libcall LC;
5504     if (Op.getOpcode() == ISD::FP_TO_SINT ||
5505         Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5506       LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5507                               Op.getValueType());
5508     else
5509       LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5510                               Op.getValueType());
5511     SDLoc Loc(Op);
5512     MakeLibCallOptions CallOptions;
5513     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5514     SDValue Result;
5515     std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5516                                           CallOptions, Loc, Chain);
5517     return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5518   }
5519 
5520   // FIXME: Remove this when we have strict fp instruction selection patterns
5521   if (IsStrict) {
5522     SDLoc Loc(Op);
5523     SDValue Result =
5524         DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5525                                                              : ISD::FP_TO_UINT,
5526                     Loc, Op.getValueType(), SrcVal);
5527     return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
5528   }
5529 
5530   return Op;
5531 }
5532 
5533 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5534   EVT VT = Op.getValueType();
5535   SDLoc dl(Op);
5536 
5537   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5538     if (VT.getVectorElementType() == MVT::f32)
5539       return Op;
5540     return DAG.UnrollVectorOp(Op.getNode());
5541   }
5542 
5543   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5544           Op.getOperand(0).getValueType() == MVT::v8i16) &&
5545          "Invalid type for custom lowering!");
5546 
5547   const bool HasFullFP16 =
5548     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5549 
5550   EVT DestVecType;
5551   if (VT == MVT::v4f32)
5552     DestVecType = MVT::v4i32;
5553   else if (VT == MVT::v4f16 && HasFullFP16)
5554     DestVecType = MVT::v4i16;
5555   else if (VT == MVT::v8f16 && HasFullFP16)
5556     DestVecType = MVT::v8i16;
5557   else
5558     return DAG.UnrollVectorOp(Op.getNode());
5559 
5560   unsigned CastOpc;
5561   unsigned Opc;
5562   switch (Op.getOpcode()) {
5563   default: llvm_unreachable("Invalid opcode!");
5564   case ISD::SINT_TO_FP:
5565     CastOpc = ISD::SIGN_EXTEND;
5566     Opc = ISD::SINT_TO_FP;
5567     break;
5568   case ISD::UINT_TO_FP:
5569     CastOpc = ISD::ZERO_EXTEND;
5570     Opc = ISD::UINT_TO_FP;
5571     break;
5572   }
5573 
5574   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5575   return DAG.getNode(Opc, dl, VT, Op);
5576 }
5577 
5578 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5579   EVT VT = Op.getValueType();
5580   if (VT.isVector())
5581     return LowerVectorINT_TO_FP(Op, DAG);
5582   if (isUnsupportedFloatingType(VT)) {
5583     RTLIB::Libcall LC;
5584     if (Op.getOpcode() == ISD::SINT_TO_FP)
5585       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5586                               Op.getValueType());
5587     else
5588       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5589                               Op.getValueType());
5590     MakeLibCallOptions CallOptions;
5591     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5592                        CallOptions, SDLoc(Op)).first;
5593   }
5594 
5595   return Op;
5596 }
5597 
5598 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5599   // Implement fcopysign with a fabs and a conditional fneg.
5600   SDValue Tmp0 = Op.getOperand(0);
5601   SDValue Tmp1 = Op.getOperand(1);
5602   SDLoc dl(Op);
5603   EVT VT = Op.getValueType();
5604   EVT SrcVT = Tmp1.getValueType();
5605   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5606     Tmp0.getOpcode() == ARMISD::VMOVDRR;
5607   bool UseNEON = !InGPR && Subtarget->hasNEON();
5608 
5609   if (UseNEON) {
5610     // Use VBSL to copy the sign bit.
5611     unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5612     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5613                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5614     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5615     if (VT == MVT::f64)
5616       Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5617                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5618                          DAG.getConstant(32, dl, MVT::i32));
5619     else /*if (VT == MVT::f32)*/
5620       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5621     if (SrcVT == MVT::f32) {
5622       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5623       if (VT == MVT::f64)
5624         Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5625                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5626                            DAG.getConstant(32, dl, MVT::i32));
5627     } else if (VT == MVT::f32)
5628       Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5629                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5630                          DAG.getConstant(32, dl, MVT::i32));
5631     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5632     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5633 
5634     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5635                                             dl, MVT::i32);
5636     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5637     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5638                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5639 
5640     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5641                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5642                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5643     if (VT == MVT::f32) {
5644       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5645       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5646                         DAG.getConstant(0, dl, MVT::i32));
5647     } else {
5648       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5649     }
5650 
5651     return Res;
5652   }
5653 
5654   // Bitcast operand 1 to i32.
5655   if (SrcVT == MVT::f64)
5656     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5657                        Tmp1).getValue(1);
5658   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5659 
5660   // Or in the signbit with integer operations.
5661   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5662   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5663   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5664   if (VT == MVT::f32) {
5665     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5666                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5667     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5668                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5669   }
5670 
5671   // f64: Or the high part with signbit and then combine two parts.
5672   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5673                      Tmp0);
5674   SDValue Lo = Tmp0.getValue(0);
5675   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5676   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5677   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5678 }
5679 
5680 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5681   MachineFunction &MF = DAG.getMachineFunction();
5682   MachineFrameInfo &MFI = MF.getFrameInfo();
5683   MFI.setReturnAddressIsTaken(true);
5684 
5685   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5686     return SDValue();
5687 
5688   EVT VT = Op.getValueType();
5689   SDLoc dl(Op);
5690   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5691   if (Depth) {
5692     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5693     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5694     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5695                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5696                        MachinePointerInfo());
5697   }
5698 
5699   // Return LR, which contains the return address. Mark it an implicit live-in.
5700   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5701   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5702 }
5703 
5704 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5705   const ARMBaseRegisterInfo &ARI =
5706     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5707   MachineFunction &MF = DAG.getMachineFunction();
5708   MachineFrameInfo &MFI = MF.getFrameInfo();
5709   MFI.setFrameAddressIsTaken(true);
5710 
5711   EVT VT = Op.getValueType();
5712   SDLoc dl(Op);  // FIXME probably not meaningful
5713   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5714   Register FrameReg = ARI.getFrameRegister(MF);
5715   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5716   while (Depth--)
5717     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5718                             MachinePointerInfo());
5719   return FrameAddr;
5720 }
5721 
5722 // FIXME? Maybe this could be a TableGen attribute on some registers and
5723 // this table could be generated automatically from RegInfo.
5724 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
5725                                               const MachineFunction &MF) const {
5726   Register Reg = StringSwitch<unsigned>(RegName)
5727                        .Case("sp", ARM::SP)
5728                        .Default(0);
5729   if (Reg)
5730     return Reg;
5731   report_fatal_error(Twine("Invalid register name \""
5732                               + StringRef(RegName)  + "\"."));
5733 }
5734 
5735 // Result is 64 bit value so split into two 32 bit values and return as a
5736 // pair of values.
5737 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5738                                 SelectionDAG &DAG) {
5739   SDLoc DL(N);
5740 
5741   // This function is only supposed to be called for i64 type destination.
5742   assert(N->getValueType(0) == MVT::i64
5743           && "ExpandREAD_REGISTER called for non-i64 type result.");
5744 
5745   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5746                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5747                              N->getOperand(0),
5748                              N->getOperand(1));
5749 
5750   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5751                     Read.getValue(1)));
5752   Results.push_back(Read.getOperand(0));
5753 }
5754 
5755 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5756 /// When \p DstVT, the destination type of \p BC, is on the vector
5757 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5758 /// it might be possible to combine them, such that everything stays on the
5759 /// vector register bank.
5760 /// \p return The node that would replace \p BT, if the combine
5761 /// is possible.
5762 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5763                                                 SelectionDAG &DAG) {
5764   SDValue Op = BC->getOperand(0);
5765   EVT DstVT = BC->getValueType(0);
5766 
5767   // The only vector instruction that can produce a scalar (remember,
5768   // since the bitcast was about to be turned into VMOVDRR, the source
5769   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5770   // Moreover, we can do this combine only if there is one use.
5771   // Finally, if the destination type is not a vector, there is not
5772   // much point on forcing everything on the vector bank.
5773   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5774       !Op.hasOneUse())
5775     return SDValue();
5776 
5777   // If the index is not constant, we will introduce an additional
5778   // multiply that will stick.
5779   // Give up in that case.
5780   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5781   if (!Index)
5782     return SDValue();
5783   unsigned DstNumElt = DstVT.getVectorNumElements();
5784 
5785   // Compute the new index.
5786   const APInt &APIntIndex = Index->getAPIntValue();
5787   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5788   NewIndex *= APIntIndex;
5789   // Check if the new constant index fits into i32.
5790   if (NewIndex.getBitWidth() > 32)
5791     return SDValue();
5792 
5793   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5794   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5795   SDLoc dl(Op);
5796   SDValue ExtractSrc = Op.getOperand(0);
5797   EVT VecVT = EVT::getVectorVT(
5798       *DAG.getContext(), DstVT.getScalarType(),
5799       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5800   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5801   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5802                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5803 }
5804 
5805 /// ExpandBITCAST - If the target supports VFP, this function is called to
5806 /// expand a bit convert where either the source or destination type is i64 to
5807 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5808 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5809 /// vectors), since the legalizer won't know what to do with that.
5810 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5811                              const ARMSubtarget *Subtarget) {
5812   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5813   SDLoc dl(N);
5814   SDValue Op = N->getOperand(0);
5815 
5816   // This function is only supposed to be called for i16 and i64 types, either
5817   // as the source or destination of the bit convert.
5818   EVT SrcVT = Op.getValueType();
5819   EVT DstVT = N->getValueType(0);
5820 
5821   if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5822     if (!Subtarget->hasFullFP16())
5823       return SDValue();
5824     // f16 bitcast i16 -> VMOVhr
5825     return DAG.getNode(ARMISD::VMOVhr, SDLoc(N), MVT::f16,
5826                        DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
5827   }
5828 
5829   if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5830     if (!Subtarget->hasFullFP16())
5831       return SDValue();
5832     // i16 bitcast f16 -> VMOVrh
5833     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16,
5834                        DAG.getNode(ARMISD::VMOVrh, SDLoc(N), MVT::i32, Op));
5835   }
5836 
5837   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5838     return SDValue();
5839 
5840   // Turn i64->f64 into VMOVDRR.
5841   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5842     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5843     // if we can combine the bitcast with its source.
5844     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5845       return Val;
5846 
5847     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5848                              DAG.getConstant(0, dl, MVT::i32));
5849     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5850                              DAG.getConstant(1, dl, MVT::i32));
5851     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5852                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5853   }
5854 
5855   // Turn f64->i64 into VMOVRRD.
5856   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5857     SDValue Cvt;
5858     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5859         SrcVT.getVectorNumElements() > 1)
5860       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5861                         DAG.getVTList(MVT::i32, MVT::i32),
5862                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5863     else
5864       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5865                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5866     // Merge the pieces into a single i64 value.
5867     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5868   }
5869 
5870   return SDValue();
5871 }
5872 
5873 /// getZeroVector - Returns a vector of specified type with all zero elements.
5874 /// Zero vectors are used to represent vector negation and in those cases
5875 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5876 /// not support i64 elements, so sometimes the zero vectors will need to be
5877 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5878 /// zero vector.
5879 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5880   assert(VT.isVector() && "Expected a vector type");
5881   // The canonical modified immediate encoding of a zero vector is....0!
5882   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5883   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5884   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5885   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5886 }
5887 
5888 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5889 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5890 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5891                                                 SelectionDAG &DAG) const {
5892   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5893   EVT VT = Op.getValueType();
5894   unsigned VTBits = VT.getSizeInBits();
5895   SDLoc dl(Op);
5896   SDValue ShOpLo = Op.getOperand(0);
5897   SDValue ShOpHi = Op.getOperand(1);
5898   SDValue ShAmt  = Op.getOperand(2);
5899   SDValue ARMcc;
5900   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5901   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5902 
5903   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5904 
5905   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5906                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5907   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5908   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5909                                    DAG.getConstant(VTBits, dl, MVT::i32));
5910   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5911   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5912   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5913   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5914                             ISD::SETGE, ARMcc, DAG, dl);
5915   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5916                            ARMcc, CCR, CmpLo);
5917 
5918   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5919   SDValue HiBigShift = Opc == ISD::SRA
5920                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5921                                          DAG.getConstant(VTBits - 1, dl, VT))
5922                            : DAG.getConstant(0, dl, VT);
5923   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5924                             ISD::SETGE, ARMcc, DAG, dl);
5925   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5926                            ARMcc, CCR, CmpHi);
5927 
5928   SDValue Ops[2] = { Lo, Hi };
5929   return DAG.getMergeValues(Ops, dl);
5930 }
5931 
5932 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5933 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5934 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5935                                                SelectionDAG &DAG) const {
5936   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5937   EVT VT = Op.getValueType();
5938   unsigned VTBits = VT.getSizeInBits();
5939   SDLoc dl(Op);
5940   SDValue ShOpLo = Op.getOperand(0);
5941   SDValue ShOpHi = Op.getOperand(1);
5942   SDValue ShAmt  = Op.getOperand(2);
5943   SDValue ARMcc;
5944   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5945 
5946   assert(Op.getOpcode() == ISD::SHL_PARTS);
5947   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5948                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5949   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5950   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5951   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5952 
5953   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5954                                    DAG.getConstant(VTBits, dl, MVT::i32));
5955   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5956   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5957                             ISD::SETGE, ARMcc, DAG, dl);
5958   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5959                            ARMcc, CCR, CmpHi);
5960 
5961   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5962                           ISD::SETGE, ARMcc, DAG, dl);
5963   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5964   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5965                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5966 
5967   SDValue Ops[2] = { Lo, Hi };
5968   return DAG.getMergeValues(Ops, dl);
5969 }
5970 
5971 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5972                                             SelectionDAG &DAG) const {
5973   // The rounding mode is in bits 23:22 of the FPSCR.
5974   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5975   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5976   // so that the shift + and get folded into a bitfield extract.
5977   SDLoc dl(Op);
5978   SDValue Chain = Op.getOperand(0);
5979   SDValue Ops[] = {Chain,
5980                    DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
5981 
5982   SDValue FPSCR =
5983       DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
5984   Chain = FPSCR.getValue(1);
5985   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5986                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5987   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5988                               DAG.getConstant(22, dl, MVT::i32));
5989   SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5990                             DAG.getConstant(3, dl, MVT::i32));
5991   return DAG.getMergeValues({And, Chain}, dl);
5992 }
5993 
5994 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5995                          const ARMSubtarget *ST) {
5996   SDLoc dl(N);
5997   EVT VT = N->getValueType(0);
5998   if (VT.isVector() && ST->hasNEON()) {
5999 
6000     // Compute the least significant set bit: LSB = X & -X
6001     SDValue X = N->getOperand(0);
6002     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6003     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6004 
6005     EVT ElemTy = VT.getVectorElementType();
6006 
6007     if (ElemTy == MVT::i8) {
6008       // Compute with: cttz(x) = ctpop(lsb - 1)
6009       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6010                                 DAG.getTargetConstant(1, dl, ElemTy));
6011       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6012       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6013     }
6014 
6015     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6016         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
6017       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6018       unsigned NumBits = ElemTy.getSizeInBits();
6019       SDValue WidthMinus1 =
6020           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6021                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6022       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6023       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6024     }
6025 
6026     // Compute with: cttz(x) = ctpop(lsb - 1)
6027 
6028     // Compute LSB - 1.
6029     SDValue Bits;
6030     if (ElemTy == MVT::i64) {
6031       // Load constant 0xffff'ffff'ffff'ffff to register.
6032       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6033                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6034       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6035     } else {
6036       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6037                                 DAG.getTargetConstant(1, dl, ElemTy));
6038       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6039     }
6040     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6041   }
6042 
6043   if (!ST->hasV6T2Ops())
6044     return SDValue();
6045 
6046   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6047   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6048 }
6049 
6050 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
6051                           const ARMSubtarget *ST) {
6052   EVT VT = N->getValueType(0);
6053   SDLoc DL(N);
6054 
6055   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6056   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6057           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6058          "Unexpected type for custom ctpop lowering");
6059 
6060   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6061   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6062   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6063   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6064 
6065   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6066   unsigned EltSize = 8;
6067   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6068   while (EltSize != VT.getScalarSizeInBits()) {
6069     SmallVector<SDValue, 8> Ops;
6070     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6071                                   TLI.getPointerTy(DAG.getDataLayout())));
6072     Ops.push_back(Res);
6073 
6074     EltSize *= 2;
6075     NumElts /= 2;
6076     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6077     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6078   }
6079 
6080   return Res;
6081 }
6082 
6083 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
6084 /// operand of a vector shift operation, where all the elements of the
6085 /// build_vector must have the same constant integer value.
6086 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6087   // Ignore bit_converts.
6088   while (Op.getOpcode() == ISD::BITCAST)
6089     Op = Op.getOperand(0);
6090   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6091   APInt SplatBits, SplatUndef;
6092   unsigned SplatBitSize;
6093   bool HasAnyUndefs;
6094   if (!BVN ||
6095       !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6096                             ElementBits) ||
6097       SplatBitSize > ElementBits)
6098     return false;
6099   Cnt = SplatBits.getSExtValue();
6100   return true;
6101 }
6102 
6103 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6104 /// operand of a vector shift left operation.  That value must be in the range:
6105 ///   0 <= Value < ElementBits for a left shift; or
6106 ///   0 <= Value <= ElementBits for a long left shift.
6107 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6108   assert(VT.isVector() && "vector shift count is not a vector type");
6109   int64_t ElementBits = VT.getScalarSizeInBits();
6110   if (!getVShiftImm(Op, ElementBits, Cnt))
6111     return false;
6112   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6113 }
6114 
6115 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6116 /// operand of a vector shift right operation.  For a shift opcode, the value
6117 /// is positive, but for an intrinsic the value count must be negative. The
6118 /// absolute value must be in the range:
6119 ///   1 <= |Value| <= ElementBits for a right shift; or
6120 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6121 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6122                          int64_t &Cnt) {
6123   assert(VT.isVector() && "vector shift count is not a vector type");
6124   int64_t ElementBits = VT.getScalarSizeInBits();
6125   if (!getVShiftImm(Op, ElementBits, Cnt))
6126     return false;
6127   if (!isIntrinsic)
6128     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6129   if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6130     Cnt = -Cnt;
6131     return true;
6132   }
6133   return false;
6134 }
6135 
6136 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6137                           const ARMSubtarget *ST) {
6138   EVT VT = N->getValueType(0);
6139   SDLoc dl(N);
6140   int64_t Cnt;
6141 
6142   if (!VT.isVector())
6143     return SDValue();
6144 
6145   // We essentially have two forms here. Shift by an immediate and shift by a
6146   // vector register (there are also shift by a gpr, but that is just handled
6147   // with a tablegen pattern). We cannot easily match shift by an immediate in
6148   // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6149   // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6150   // signed or unsigned, and a negative shift indicates a shift right).
6151   if (N->getOpcode() == ISD::SHL) {
6152     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6153       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6154                          DAG.getConstant(Cnt, dl, MVT::i32));
6155     return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6156                        N->getOperand(1));
6157   }
6158 
6159   assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6160          "unexpected vector shift opcode");
6161 
6162   if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6163     unsigned VShiftOpc =
6164         (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6165     return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6166                        DAG.getConstant(Cnt, dl, MVT::i32));
6167   }
6168 
6169   // Other right shifts we don't have operations for (we use a shift left by a
6170   // negative number).
6171   EVT ShiftVT = N->getOperand(1).getValueType();
6172   SDValue NegatedCount = DAG.getNode(
6173       ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6174   unsigned VShiftOpc =
6175       (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6176   return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6177 }
6178 
6179 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6180                                 const ARMSubtarget *ST) {
6181   EVT VT = N->getValueType(0);
6182   SDLoc dl(N);
6183 
6184   // We can get here for a node like i32 = ISD::SHL i32, i64
6185   if (VT != MVT::i64)
6186     return SDValue();
6187 
6188   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6189           N->getOpcode() == ISD::SHL) &&
6190          "Unknown shift to lower!");
6191 
6192   unsigned ShOpc = N->getOpcode();
6193   if (ST->hasMVEIntegerOps()) {
6194     SDValue ShAmt = N->getOperand(1);
6195     unsigned ShPartsOpc = ARMISD::LSLL;
6196     ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6197 
6198     // If the shift amount is greater than 32 or has a greater bitwidth than 64
6199     // then do the default optimisation
6200     if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6201         (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6202       return SDValue();
6203 
6204     // Extract the lower 32 bits of the shift amount if it's not an i32
6205     if (ShAmt->getValueType(0) != MVT::i32)
6206       ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6207 
6208     if (ShOpc == ISD::SRL) {
6209       if (!Con)
6210         // There is no t2LSRLr instruction so negate and perform an lsll if the
6211         // shift amount is in a register, emulating a right shift.
6212         ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6213                             DAG.getConstant(0, dl, MVT::i32), ShAmt);
6214       else
6215         // Else generate an lsrl on the immediate shift amount
6216         ShPartsOpc = ARMISD::LSRL;
6217     } else if (ShOpc == ISD::SRA)
6218       ShPartsOpc = ARMISD::ASRL;
6219 
6220     // Lower 32 bits of the destination/source
6221     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6222                              DAG.getConstant(0, dl, MVT::i32));
6223     // Upper 32 bits of the destination/source
6224     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6225                              DAG.getConstant(1, dl, MVT::i32));
6226 
6227     // Generate the shift operation as computed above
6228     Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6229                      ShAmt);
6230     // The upper 32 bits come from the second return value of lsll
6231     Hi = SDValue(Lo.getNode(), 1);
6232     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6233   }
6234 
6235   // We only lower SRA, SRL of 1 here, all others use generic lowering.
6236   if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6237     return SDValue();
6238 
6239   // If we are in thumb mode, we don't have RRX.
6240   if (ST->isThumb1Only())
6241     return SDValue();
6242 
6243   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
6244   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6245                            DAG.getConstant(0, dl, MVT::i32));
6246   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6247                            DAG.getConstant(1, dl, MVT::i32));
6248 
6249   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6250   // captures the result into a carry flag.
6251   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6252   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6253 
6254   // The low part is an ARMISD::RRX operand, which shifts the carry in.
6255   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6256 
6257   // Merge the pieces into a single i64 value.
6258  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6259 }
6260 
6261 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6262                            const ARMSubtarget *ST) {
6263   bool Invert = false;
6264   bool Swap = false;
6265   unsigned Opc = ARMCC::AL;
6266 
6267   SDValue Op0 = Op.getOperand(0);
6268   SDValue Op1 = Op.getOperand(1);
6269   SDValue CC = Op.getOperand(2);
6270   EVT VT = Op.getValueType();
6271   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6272   SDLoc dl(Op);
6273 
6274   EVT CmpVT;
6275   if (ST->hasNEON())
6276     CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6277   else {
6278     assert(ST->hasMVEIntegerOps() &&
6279            "No hardware support for integer vector comparison!");
6280 
6281     if (Op.getValueType().getVectorElementType() != MVT::i1)
6282       return SDValue();
6283 
6284     // Make sure we expand floating point setcc to scalar if we do not have
6285     // mve.fp, so that we can handle them from there.
6286     if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6287       return SDValue();
6288 
6289     CmpVT = VT;
6290   }
6291 
6292   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6293       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6294     // Special-case integer 64-bit equality comparisons. They aren't legal,
6295     // but they can be lowered with a few vector instructions.
6296     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6297     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6298     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6299     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6300     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6301                               DAG.getCondCode(ISD::SETEQ));
6302     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6303     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6304     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6305     if (SetCCOpcode == ISD::SETNE)
6306       Merged = DAG.getNOT(dl, Merged, CmpVT);
6307     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6308     return Merged;
6309   }
6310 
6311   if (CmpVT.getVectorElementType() == MVT::i64)
6312     // 64-bit comparisons are not legal in general.
6313     return SDValue();
6314 
6315   if (Op1.getValueType().isFloatingPoint()) {
6316     switch (SetCCOpcode) {
6317     default: llvm_unreachable("Illegal FP comparison");
6318     case ISD::SETUNE:
6319     case ISD::SETNE:
6320       if (ST->hasMVEFloatOps()) {
6321         Opc = ARMCC::NE; break;
6322       } else {
6323         Invert = true; LLVM_FALLTHROUGH;
6324       }
6325     case ISD::SETOEQ:
6326     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6327     case ISD::SETOLT:
6328     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6329     case ISD::SETOGT:
6330     case ISD::SETGT:  Opc = ARMCC::GT; break;
6331     case ISD::SETOLE:
6332     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6333     case ISD::SETOGE:
6334     case ISD::SETGE: Opc = ARMCC::GE; break;
6335     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6336     case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6337     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6338     case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6339     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6340     case ISD::SETONE: {
6341       // Expand this to (OLT | OGT).
6342       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6343                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6344       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6345                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6346       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6347       if (Invert)
6348         Result = DAG.getNOT(dl, Result, VT);
6349       return Result;
6350     }
6351     case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6352     case ISD::SETO: {
6353       // Expand this to (OLT | OGE).
6354       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6355                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6356       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6357                                    DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6358       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6359       if (Invert)
6360         Result = DAG.getNOT(dl, Result, VT);
6361       return Result;
6362     }
6363     }
6364   } else {
6365     // Integer comparisons.
6366     switch (SetCCOpcode) {
6367     default: llvm_unreachable("Illegal integer comparison");
6368     case ISD::SETNE:
6369       if (ST->hasMVEIntegerOps()) {
6370         Opc = ARMCC::NE; break;
6371       } else {
6372         Invert = true; LLVM_FALLTHROUGH;
6373       }
6374     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6375     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
6376     case ISD::SETGT:  Opc = ARMCC::GT; break;
6377     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6378     case ISD::SETGE:  Opc = ARMCC::GE; break;
6379     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6380     case ISD::SETUGT: Opc = ARMCC::HI; break;
6381     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6382     case ISD::SETUGE: Opc = ARMCC::HS; break;
6383     }
6384 
6385     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6386     if (ST->hasNEON() && Opc == ARMCC::EQ) {
6387       SDValue AndOp;
6388       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6389         AndOp = Op0;
6390       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6391         AndOp = Op1;
6392 
6393       // Ignore bitconvert.
6394       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6395         AndOp = AndOp.getOperand(0);
6396 
6397       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6398         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6399         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6400         SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6401         if (!Invert)
6402           Result = DAG.getNOT(dl, Result, VT);
6403         return Result;
6404       }
6405     }
6406   }
6407 
6408   if (Swap)
6409     std::swap(Op0, Op1);
6410 
6411   // If one of the operands is a constant vector zero, attempt to fold the
6412   // comparison to a specialized compare-against-zero form.
6413   SDValue SingleOp;
6414   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6415     SingleOp = Op0;
6416   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6417     if (Opc == ARMCC::GE)
6418       Opc = ARMCC::LE;
6419     else if (Opc == ARMCC::GT)
6420       Opc = ARMCC::LT;
6421     SingleOp = Op1;
6422   }
6423 
6424   SDValue Result;
6425   if (SingleOp.getNode()) {
6426     Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6427                          DAG.getConstant(Opc, dl, MVT::i32));
6428   } else {
6429     Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6430                          DAG.getConstant(Opc, dl, MVT::i32));
6431   }
6432 
6433   Result = DAG.getSExtOrTrunc(Result, dl, VT);
6434 
6435   if (Invert)
6436     Result = DAG.getNOT(dl, Result, VT);
6437 
6438   return Result;
6439 }
6440 
6441 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6442   SDValue LHS = Op.getOperand(0);
6443   SDValue RHS = Op.getOperand(1);
6444   SDValue Carry = Op.getOperand(2);
6445   SDValue Cond = Op.getOperand(3);
6446   SDLoc DL(Op);
6447 
6448   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6449 
6450   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6451   // have to invert the carry first.
6452   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6453                       DAG.getConstant(1, DL, MVT::i32), Carry);
6454   // This converts the boolean value carry into the carry flag.
6455   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6456 
6457   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6458   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6459 
6460   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6461   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6462   SDValue ARMcc = DAG.getConstant(
6463       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6464   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6465   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6466                                    Cmp.getValue(1), SDValue());
6467   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6468                      CCR, Chain.getValue(1));
6469 }
6470 
6471 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6472 /// valid vector constant for a NEON or MVE instruction with a "modified
6473 /// immediate" operand (e.g., VMOV).  If so, return the encoded value.
6474 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6475                                  unsigned SplatBitSize, SelectionDAG &DAG,
6476                                  const SDLoc &dl, EVT &VT, EVT VectorVT,
6477                                  VMOVModImmType type) {
6478   unsigned OpCmode, Imm;
6479   bool is128Bits = VectorVT.is128BitVector();
6480 
6481   // SplatBitSize is set to the smallest size that splats the vector, so a
6482   // zero vector will always have SplatBitSize == 8.  However, NEON modified
6483   // immediate instructions others than VMOV do not support the 8-bit encoding
6484   // of a zero vector, and the default encoding of zero is supposed to be the
6485   // 32-bit version.
6486   if (SplatBits == 0)
6487     SplatBitSize = 32;
6488 
6489   switch (SplatBitSize) {
6490   case 8:
6491     if (type != VMOVModImm)
6492       return SDValue();
6493     // Any 1-byte value is OK.  Op=0, Cmode=1110.
6494     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6495     OpCmode = 0xe;
6496     Imm = SplatBits;
6497     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6498     break;
6499 
6500   case 16:
6501     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6502     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6503     if ((SplatBits & ~0xff) == 0) {
6504       // Value = 0x00nn: Op=x, Cmode=100x.
6505       OpCmode = 0x8;
6506       Imm = SplatBits;
6507       break;
6508     }
6509     if ((SplatBits & ~0xff00) == 0) {
6510       // Value = 0xnn00: Op=x, Cmode=101x.
6511       OpCmode = 0xa;
6512       Imm = SplatBits >> 8;
6513       break;
6514     }
6515     return SDValue();
6516 
6517   case 32:
6518     // NEON's 32-bit VMOV supports splat values where:
6519     // * only one byte is nonzero, or
6520     // * the least significant byte is 0xff and the second byte is nonzero, or
6521     // * the least significant 2 bytes are 0xff and the third is nonzero.
6522     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6523     if ((SplatBits & ~0xff) == 0) {
6524       // Value = 0x000000nn: Op=x, Cmode=000x.
6525       OpCmode = 0;
6526       Imm = SplatBits;
6527       break;
6528     }
6529     if ((SplatBits & ~0xff00) == 0) {
6530       // Value = 0x0000nn00: Op=x, Cmode=001x.
6531       OpCmode = 0x2;
6532       Imm = SplatBits >> 8;
6533       break;
6534     }
6535     if ((SplatBits & ~0xff0000) == 0) {
6536       // Value = 0x00nn0000: Op=x, Cmode=010x.
6537       OpCmode = 0x4;
6538       Imm = SplatBits >> 16;
6539       break;
6540     }
6541     if ((SplatBits & ~0xff000000) == 0) {
6542       // Value = 0xnn000000: Op=x, Cmode=011x.
6543       OpCmode = 0x6;
6544       Imm = SplatBits >> 24;
6545       break;
6546     }
6547 
6548     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6549     if (type == OtherModImm) return SDValue();
6550 
6551     if ((SplatBits & ~0xffff) == 0 &&
6552         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6553       // Value = 0x0000nnff: Op=x, Cmode=1100.
6554       OpCmode = 0xc;
6555       Imm = SplatBits >> 8;
6556       break;
6557     }
6558 
6559     // cmode == 0b1101 is not supported for MVE VMVN
6560     if (type == MVEVMVNModImm)
6561       return SDValue();
6562 
6563     if ((SplatBits & ~0xffffff) == 0 &&
6564         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6565       // Value = 0x00nnffff: Op=x, Cmode=1101.
6566       OpCmode = 0xd;
6567       Imm = SplatBits >> 16;
6568       break;
6569     }
6570 
6571     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6572     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6573     // VMOV.I32.  A (very) minor optimization would be to replicate the value
6574     // and fall through here to test for a valid 64-bit splat.  But, then the
6575     // caller would also need to check and handle the change in size.
6576     return SDValue();
6577 
6578   case 64: {
6579     if (type != VMOVModImm)
6580       return SDValue();
6581     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6582     uint64_t BitMask = 0xff;
6583     uint64_t Val = 0;
6584     unsigned ImmMask = 1;
6585     Imm = 0;
6586     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6587       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6588         Val |= BitMask;
6589         Imm |= ImmMask;
6590       } else if ((SplatBits & BitMask) != 0) {
6591         return SDValue();
6592       }
6593       BitMask <<= 8;
6594       ImmMask <<= 1;
6595     }
6596 
6597     if (DAG.getDataLayout().isBigEndian()) {
6598       // Reverse the order of elements within the vector.
6599       unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8;
6600       unsigned Mask = (1 << BytesPerElem) - 1;
6601       unsigned NumElems = 8 / BytesPerElem;
6602       unsigned NewImm = 0;
6603       for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) {
6604         unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask);
6605         NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem;
6606       }
6607       Imm = NewImm;
6608     }
6609 
6610     // Op=1, Cmode=1110.
6611     OpCmode = 0x1e;
6612     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6613     break;
6614   }
6615 
6616   default:
6617     llvm_unreachable("unexpected size for isVMOVModifiedImm");
6618   }
6619 
6620   unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6621   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6622 }
6623 
6624 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6625                                            const ARMSubtarget *ST) const {
6626   EVT VT = Op.getValueType();
6627   bool IsDouble = (VT == MVT::f64);
6628   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6629   const APFloat &FPVal = CFP->getValueAPF();
6630 
6631   // Prevent floating-point constants from using literal loads
6632   // when execute-only is enabled.
6633   if (ST->genExecuteOnly()) {
6634     // If we can represent the constant as an immediate, don't lower it
6635     if (isFPImmLegal(FPVal, VT))
6636       return Op;
6637     // Otherwise, construct as integer, and move to float register
6638     APInt INTVal = FPVal.bitcastToAPInt();
6639     SDLoc DL(CFP);
6640     switch (VT.getSimpleVT().SimpleTy) {
6641       default:
6642         llvm_unreachable("Unknown floating point type!");
6643         break;
6644       case MVT::f64: {
6645         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6646         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6647         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6648       }
6649       case MVT::f32:
6650           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6651               DAG.getConstant(INTVal, DL, MVT::i32));
6652     }
6653   }
6654 
6655   if (!ST->hasVFP3Base())
6656     return SDValue();
6657 
6658   // Use the default (constant pool) lowering for double constants when we have
6659   // an SP-only FPU
6660   if (IsDouble && !Subtarget->hasFP64())
6661     return SDValue();
6662 
6663   // Try splatting with a VMOV.f32...
6664   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6665 
6666   if (ImmVal != -1) {
6667     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6668       // We have code in place to select a valid ConstantFP already, no need to
6669       // do any mangling.
6670       return Op;
6671     }
6672 
6673     // It's a float and we are trying to use NEON operations where
6674     // possible. Lower it to a splat followed by an extract.
6675     SDLoc DL(Op);
6676     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6677     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6678                                       NewVal);
6679     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6680                        DAG.getConstant(0, DL, MVT::i32));
6681   }
6682 
6683   // The rest of our options are NEON only, make sure that's allowed before
6684   // proceeding..
6685   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6686     return SDValue();
6687 
6688   EVT VMovVT;
6689   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6690 
6691   // It wouldn't really be worth bothering for doubles except for one very
6692   // important value, which does happen to match: 0.0. So make sure we don't do
6693   // anything stupid.
6694   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6695     return SDValue();
6696 
6697   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6698   SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6699                                      VMovVT, VT, VMOVModImm);
6700   if (NewVal != SDValue()) {
6701     SDLoc DL(Op);
6702     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6703                                       NewVal);
6704     if (IsDouble)
6705       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6706 
6707     // It's a float: cast and extract a vector element.
6708     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6709                                        VecConstant);
6710     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6711                        DAG.getConstant(0, DL, MVT::i32));
6712   }
6713 
6714   // Finally, try a VMVN.i32
6715   NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6716                              VT, VMVNModImm);
6717   if (NewVal != SDValue()) {
6718     SDLoc DL(Op);
6719     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6720 
6721     if (IsDouble)
6722       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6723 
6724     // It's a float: cast and extract a vector element.
6725     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6726                                        VecConstant);
6727     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6728                        DAG.getConstant(0, DL, MVT::i32));
6729   }
6730 
6731   return SDValue();
6732 }
6733 
6734 // check if an VEXT instruction can handle the shuffle mask when the
6735 // vector sources of the shuffle are the same.
6736 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6737   unsigned NumElts = VT.getVectorNumElements();
6738 
6739   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6740   if (M[0] < 0)
6741     return false;
6742 
6743   Imm = M[0];
6744 
6745   // If this is a VEXT shuffle, the immediate value is the index of the first
6746   // element.  The other shuffle indices must be the successive elements after
6747   // the first one.
6748   unsigned ExpectedElt = Imm;
6749   for (unsigned i = 1; i < NumElts; ++i) {
6750     // Increment the expected index.  If it wraps around, just follow it
6751     // back to index zero and keep going.
6752     ++ExpectedElt;
6753     if (ExpectedElt == NumElts)
6754       ExpectedElt = 0;
6755 
6756     if (M[i] < 0) continue; // ignore UNDEF indices
6757     if (ExpectedElt != static_cast<unsigned>(M[i]))
6758       return false;
6759   }
6760 
6761   return true;
6762 }
6763 
6764 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6765                        bool &ReverseVEXT, unsigned &Imm) {
6766   unsigned NumElts = VT.getVectorNumElements();
6767   ReverseVEXT = false;
6768 
6769   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6770   if (M[0] < 0)
6771     return false;
6772 
6773   Imm = M[0];
6774 
6775   // If this is a VEXT shuffle, the immediate value is the index of the first
6776   // element.  The other shuffle indices must be the successive elements after
6777   // the first one.
6778   unsigned ExpectedElt = Imm;
6779   for (unsigned i = 1; i < NumElts; ++i) {
6780     // Increment the expected index.  If it wraps around, it may still be
6781     // a VEXT but the source vectors must be swapped.
6782     ExpectedElt += 1;
6783     if (ExpectedElt == NumElts * 2) {
6784       ExpectedElt = 0;
6785       ReverseVEXT = true;
6786     }
6787 
6788     if (M[i] < 0) continue; // ignore UNDEF indices
6789     if (ExpectedElt != static_cast<unsigned>(M[i]))
6790       return false;
6791   }
6792 
6793   // Adjust the index value if the source operands will be swapped.
6794   if (ReverseVEXT)
6795     Imm -= NumElts;
6796 
6797   return true;
6798 }
6799 
6800 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6801 /// instruction with the specified blocksize.  (The order of the elements
6802 /// within each block of the vector is reversed.)
6803 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6804   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6805          "Only possible block sizes for VREV are: 16, 32, 64");
6806 
6807   unsigned EltSz = VT.getScalarSizeInBits();
6808   if (EltSz == 64)
6809     return false;
6810 
6811   unsigned NumElts = VT.getVectorNumElements();
6812   unsigned BlockElts = M[0] + 1;
6813   // If the first shuffle index is UNDEF, be optimistic.
6814   if (M[0] < 0)
6815     BlockElts = BlockSize / EltSz;
6816 
6817   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6818     return false;
6819 
6820   for (unsigned i = 0; i < NumElts; ++i) {
6821     if (M[i] < 0) continue; // ignore UNDEF indices
6822     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6823       return false;
6824   }
6825 
6826   return true;
6827 }
6828 
6829 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6830   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6831   // range, then 0 is placed into the resulting vector. So pretty much any mask
6832   // of 8 elements can work here.
6833   return VT == MVT::v8i8 && M.size() == 8;
6834 }
6835 
6836 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6837                                unsigned Index) {
6838   if (Mask.size() == Elements * 2)
6839     return Index / Elements;
6840   return Mask[Index] == 0 ? 0 : 1;
6841 }
6842 
6843 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6844 // checking that pairs of elements in the shuffle mask represent the same index
6845 // in each vector, incrementing the expected index by 2 at each step.
6846 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6847 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6848 //  v2={e,f,g,h}
6849 // WhichResult gives the offset for each element in the mask based on which
6850 // of the two results it belongs to.
6851 //
6852 // The transpose can be represented either as:
6853 // result1 = shufflevector v1, v2, result1_shuffle_mask
6854 // result2 = shufflevector v1, v2, result2_shuffle_mask
6855 // where v1/v2 and the shuffle masks have the same number of elements
6856 // (here WhichResult (see below) indicates which result is being checked)
6857 //
6858 // or as:
6859 // results = shufflevector v1, v2, shuffle_mask
6860 // where both results are returned in one vector and the shuffle mask has twice
6861 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6862 // want to check the low half and high half of the shuffle mask as if it were
6863 // the other case
6864 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6865   unsigned EltSz = VT.getScalarSizeInBits();
6866   if (EltSz == 64)
6867     return false;
6868 
6869   unsigned NumElts = VT.getVectorNumElements();
6870   if (M.size() != NumElts && M.size() != NumElts*2)
6871     return false;
6872 
6873   // If the mask is twice as long as the input vector then we need to check the
6874   // upper and lower parts of the mask with a matching value for WhichResult
6875   // FIXME: A mask with only even values will be rejected in case the first
6876   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6877   // M[0] is used to determine WhichResult
6878   for (unsigned i = 0; i < M.size(); i += NumElts) {
6879     WhichResult = SelectPairHalf(NumElts, M, i);
6880     for (unsigned j = 0; j < NumElts; j += 2) {
6881       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6882           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6883         return false;
6884     }
6885   }
6886 
6887   if (M.size() == NumElts*2)
6888     WhichResult = 0;
6889 
6890   return true;
6891 }
6892 
6893 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6894 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6895 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6896 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6897   unsigned EltSz = VT.getScalarSizeInBits();
6898   if (EltSz == 64)
6899     return false;
6900 
6901   unsigned NumElts = VT.getVectorNumElements();
6902   if (M.size() != NumElts && M.size() != NumElts*2)
6903     return false;
6904 
6905   for (unsigned i = 0; i < M.size(); i += NumElts) {
6906     WhichResult = SelectPairHalf(NumElts, M, i);
6907     for (unsigned j = 0; j < NumElts; j += 2) {
6908       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6909           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6910         return false;
6911     }
6912   }
6913 
6914   if (M.size() == NumElts*2)
6915     WhichResult = 0;
6916 
6917   return true;
6918 }
6919 
6920 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6921 // that the mask elements are either all even and in steps of size 2 or all odd
6922 // and in steps of size 2.
6923 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6924 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6925 //  v2={e,f,g,h}
6926 // Requires similar checks to that of isVTRNMask with
6927 // respect the how results are returned.
6928 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6929   unsigned EltSz = VT.getScalarSizeInBits();
6930   if (EltSz == 64)
6931     return false;
6932 
6933   unsigned NumElts = VT.getVectorNumElements();
6934   if (M.size() != NumElts && M.size() != NumElts*2)
6935     return false;
6936 
6937   for (unsigned i = 0; i < M.size(); i += NumElts) {
6938     WhichResult = SelectPairHalf(NumElts, M, i);
6939     for (unsigned j = 0; j < NumElts; ++j) {
6940       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6941         return false;
6942     }
6943   }
6944 
6945   if (M.size() == NumElts*2)
6946     WhichResult = 0;
6947 
6948   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6949   if (VT.is64BitVector() && EltSz == 32)
6950     return false;
6951 
6952   return true;
6953 }
6954 
6955 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6956 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6957 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6958 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6959   unsigned EltSz = VT.getScalarSizeInBits();
6960   if (EltSz == 64)
6961     return false;
6962 
6963   unsigned NumElts = VT.getVectorNumElements();
6964   if (M.size() != NumElts && M.size() != NumElts*2)
6965     return false;
6966 
6967   unsigned Half = NumElts / 2;
6968   for (unsigned i = 0; i < M.size(); i += NumElts) {
6969     WhichResult = SelectPairHalf(NumElts, M, i);
6970     for (unsigned j = 0; j < NumElts; j += Half) {
6971       unsigned Idx = WhichResult;
6972       for (unsigned k = 0; k < Half; ++k) {
6973         int MIdx = M[i + j + k];
6974         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6975           return false;
6976         Idx += 2;
6977       }
6978     }
6979   }
6980 
6981   if (M.size() == NumElts*2)
6982     WhichResult = 0;
6983 
6984   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6985   if (VT.is64BitVector() && EltSz == 32)
6986     return false;
6987 
6988   return true;
6989 }
6990 
6991 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6992 // that pairs of elements of the shufflemask represent the same index in each
6993 // vector incrementing sequentially through the vectors.
6994 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6995 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6996 //  v2={e,f,g,h}
6997 // Requires similar checks to that of isVTRNMask with respect the how results
6998 // are returned.
6999 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7000   unsigned EltSz = VT.getScalarSizeInBits();
7001   if (EltSz == 64)
7002     return false;
7003 
7004   unsigned NumElts = VT.getVectorNumElements();
7005   if (M.size() != NumElts && M.size() != NumElts*2)
7006     return false;
7007 
7008   for (unsigned i = 0; i < M.size(); i += NumElts) {
7009     WhichResult = SelectPairHalf(NumElts, M, i);
7010     unsigned Idx = WhichResult * NumElts / 2;
7011     for (unsigned j = 0; j < NumElts; j += 2) {
7012       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7013           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7014         return false;
7015       Idx += 1;
7016     }
7017   }
7018 
7019   if (M.size() == NumElts*2)
7020     WhichResult = 0;
7021 
7022   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7023   if (VT.is64BitVector() && EltSz == 32)
7024     return false;
7025 
7026   return true;
7027 }
7028 
7029 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7030 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7031 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7032 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7033   unsigned EltSz = VT.getScalarSizeInBits();
7034   if (EltSz == 64)
7035     return false;
7036 
7037   unsigned NumElts = VT.getVectorNumElements();
7038   if (M.size() != NumElts && M.size() != NumElts*2)
7039     return false;
7040 
7041   for (unsigned i = 0; i < M.size(); i += NumElts) {
7042     WhichResult = SelectPairHalf(NumElts, M, i);
7043     unsigned Idx = WhichResult * NumElts / 2;
7044     for (unsigned j = 0; j < NumElts; j += 2) {
7045       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7046           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7047         return false;
7048       Idx += 1;
7049     }
7050   }
7051 
7052   if (M.size() == NumElts*2)
7053     WhichResult = 0;
7054 
7055   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7056   if (VT.is64BitVector() && EltSz == 32)
7057     return false;
7058 
7059   return true;
7060 }
7061 
7062 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7063 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7064 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7065                                            unsigned &WhichResult,
7066                                            bool &isV_UNDEF) {
7067   isV_UNDEF = false;
7068   if (isVTRNMask(ShuffleMask, VT, WhichResult))
7069     return ARMISD::VTRN;
7070   if (isVUZPMask(ShuffleMask, VT, WhichResult))
7071     return ARMISD::VUZP;
7072   if (isVZIPMask(ShuffleMask, VT, WhichResult))
7073     return ARMISD::VZIP;
7074 
7075   isV_UNDEF = true;
7076   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7077     return ARMISD::VTRN;
7078   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7079     return ARMISD::VUZP;
7080   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7081     return ARMISD::VZIP;
7082 
7083   return 0;
7084 }
7085 
7086 /// \return true if this is a reverse operation on an vector.
7087 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7088   unsigned NumElts = VT.getVectorNumElements();
7089   // Make sure the mask has the right size.
7090   if (NumElts != M.size())
7091       return false;
7092 
7093   // Look for <15, ..., 3, -1, 1, 0>.
7094   for (unsigned i = 0; i != NumElts; ++i)
7095     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7096       return false;
7097 
7098   return true;
7099 }
7100 
7101 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) {
7102   unsigned NumElts = VT.getVectorNumElements();
7103   // Make sure the mask has the right size.
7104   if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7105       return false;
7106 
7107   // If Top
7108   //   Look for <0, N, 2, N+2, 4, N+4, ..>.
7109   //   This inserts Input2 into Input1
7110   // else if not Top
7111   //   Look for <0, N+1, 2, N+3, 4, N+5, ..>
7112   //   This inserts Input1 into Input2
7113   unsigned Offset = Top ? 0 : 1;
7114   for (unsigned i = 0; i < NumElts; i+=2) {
7115     if (M[i] >= 0 && M[i] != (int)i)
7116       return false;
7117     if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset))
7118       return false;
7119   }
7120 
7121   return true;
7122 }
7123 
7124 // If N is an integer constant that can be moved into a register in one
7125 // instruction, return an SDValue of such a constant (will become a MOV
7126 // instruction).  Otherwise return null.
7127 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7128                                      const ARMSubtarget *ST, const SDLoc &dl) {
7129   uint64_t Val;
7130   if (!isa<ConstantSDNode>(N))
7131     return SDValue();
7132   Val = cast<ConstantSDNode>(N)->getZExtValue();
7133 
7134   if (ST->isThumb1Only()) {
7135     if (Val <= 255 || ~Val <= 255)
7136       return DAG.getConstant(Val, dl, MVT::i32);
7137   } else {
7138     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7139       return DAG.getConstant(Val, dl, MVT::i32);
7140   }
7141   return SDValue();
7142 }
7143 
7144 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7145                                     const ARMSubtarget *ST) {
7146   SDLoc dl(Op);
7147   EVT VT = Op.getValueType();
7148 
7149   assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7150 
7151   unsigned NumElts = VT.getVectorNumElements();
7152   unsigned BoolMask;
7153   unsigned BitsPerBool;
7154   if (NumElts == 4) {
7155     BitsPerBool = 4;
7156     BoolMask = 0xf;
7157   } else if (NumElts == 8) {
7158     BitsPerBool = 2;
7159     BoolMask = 0x3;
7160   } else if (NumElts == 16) {
7161     BitsPerBool = 1;
7162     BoolMask = 0x1;
7163   } else
7164     return SDValue();
7165 
7166   // If this is a single value copied into all lanes (a splat), we can just sign
7167   // extend that single value
7168   SDValue FirstOp = Op.getOperand(0);
7169   if (!isa<ConstantSDNode>(FirstOp) &&
7170       std::all_of(std::next(Op->op_begin()), Op->op_end(),
7171                   [&FirstOp](SDUse &U) {
7172                     return U.get().isUndef() || U.get() == FirstOp;
7173                   })) {
7174     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7175                               DAG.getValueType(MVT::i1));
7176     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7177   }
7178 
7179   // First create base with bits set where known
7180   unsigned Bits32 = 0;
7181   for (unsigned i = 0; i < NumElts; ++i) {
7182     SDValue V = Op.getOperand(i);
7183     if (!isa<ConstantSDNode>(V) && !V.isUndef())
7184       continue;
7185     bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7186     if (BitSet)
7187       Bits32 |= BoolMask << (i * BitsPerBool);
7188   }
7189 
7190   // Add in unknown nodes
7191   SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7192                              DAG.getConstant(Bits32, dl, MVT::i32));
7193   for (unsigned i = 0; i < NumElts; ++i) {
7194     SDValue V = Op.getOperand(i);
7195     if (isa<ConstantSDNode>(V) || V.isUndef())
7196       continue;
7197     Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7198                        DAG.getConstant(i, dl, MVT::i32));
7199   }
7200 
7201   return Base;
7202 }
7203 
7204 // If this is a case we can't handle, return null and let the default
7205 // expansion code take care of it.
7206 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7207                                              const ARMSubtarget *ST) const {
7208   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7209   SDLoc dl(Op);
7210   EVT VT = Op.getValueType();
7211 
7212   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7213     return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7214 
7215   APInt SplatBits, SplatUndef;
7216   unsigned SplatBitSize;
7217   bool HasAnyUndefs;
7218   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7219     if (SplatUndef.isAllOnesValue())
7220       return DAG.getUNDEF(VT);
7221 
7222     if ((ST->hasNEON() && SplatBitSize <= 64) ||
7223         (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7224       // Check if an immediate VMOV works.
7225       EVT VmovVT;
7226       SDValue Val =
7227           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7228                             SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7229 
7230       if (Val.getNode()) {
7231         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7232         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7233       }
7234 
7235       // Try an immediate VMVN.
7236       uint64_t NegatedImm = (~SplatBits).getZExtValue();
7237       Val = isVMOVModifiedImm(
7238           NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7239           VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7240       if (Val.getNode()) {
7241         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7242         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7243       }
7244 
7245       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7246       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7247         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7248         if (ImmVal != -1) {
7249           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7250           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7251         }
7252       }
7253     }
7254   }
7255 
7256   // Scan through the operands to see if only one value is used.
7257   //
7258   // As an optimisation, even if more than one value is used it may be more
7259   // profitable to splat with one value then change some lanes.
7260   //
7261   // Heuristically we decide to do this if the vector has a "dominant" value,
7262   // defined as splatted to more than half of the lanes.
7263   unsigned NumElts = VT.getVectorNumElements();
7264   bool isOnlyLowElement = true;
7265   bool usesOnlyOneValue = true;
7266   bool hasDominantValue = false;
7267   bool isConstant = true;
7268 
7269   // Map of the number of times a particular SDValue appears in the
7270   // element list.
7271   DenseMap<SDValue, unsigned> ValueCounts;
7272   SDValue Value;
7273   for (unsigned i = 0; i < NumElts; ++i) {
7274     SDValue V = Op.getOperand(i);
7275     if (V.isUndef())
7276       continue;
7277     if (i > 0)
7278       isOnlyLowElement = false;
7279     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7280       isConstant = false;
7281 
7282     ValueCounts.insert(std::make_pair(V, 0));
7283     unsigned &Count = ValueCounts[V];
7284 
7285     // Is this value dominant? (takes up more than half of the lanes)
7286     if (++Count > (NumElts / 2)) {
7287       hasDominantValue = true;
7288       Value = V;
7289     }
7290   }
7291   if (ValueCounts.size() != 1)
7292     usesOnlyOneValue = false;
7293   if (!Value.getNode() && !ValueCounts.empty())
7294     Value = ValueCounts.begin()->first;
7295 
7296   if (ValueCounts.empty())
7297     return DAG.getUNDEF(VT);
7298 
7299   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7300   // Keep going if we are hitting this case.
7301   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7302     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7303 
7304   unsigned EltSize = VT.getScalarSizeInBits();
7305 
7306   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
7307   // i32 and try again.
7308   if (hasDominantValue && EltSize <= 32) {
7309     if (!isConstant) {
7310       SDValue N;
7311 
7312       // If we are VDUPing a value that comes directly from a vector, that will
7313       // cause an unnecessary move to and from a GPR, where instead we could
7314       // just use VDUPLANE. We can only do this if the lane being extracted
7315       // is at a constant index, as the VDUP from lane instructions only have
7316       // constant-index forms.
7317       ConstantSDNode *constIndex;
7318       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7319           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7320         // We need to create a new undef vector to use for the VDUPLANE if the
7321         // size of the vector from which we get the value is different than the
7322         // size of the vector that we need to create. We will insert the element
7323         // such that the register coalescer will remove unnecessary copies.
7324         if (VT != Value->getOperand(0).getValueType()) {
7325           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7326                              VT.getVectorNumElements();
7327           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7328                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7329                         Value, DAG.getConstant(index, dl, MVT::i32)),
7330                            DAG.getConstant(index, dl, MVT::i32));
7331         } else
7332           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7333                         Value->getOperand(0), Value->getOperand(1));
7334       } else
7335         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7336 
7337       if (!usesOnlyOneValue) {
7338         // The dominant value was splatted as 'N', but we now have to insert
7339         // all differing elements.
7340         for (unsigned I = 0; I < NumElts; ++I) {
7341           if (Op.getOperand(I) == Value)
7342             continue;
7343           SmallVector<SDValue, 3> Ops;
7344           Ops.push_back(N);
7345           Ops.push_back(Op.getOperand(I));
7346           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7347           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7348         }
7349       }
7350       return N;
7351     }
7352     if (VT.getVectorElementType().isFloatingPoint()) {
7353       SmallVector<SDValue, 8> Ops;
7354       MVT FVT = VT.getVectorElementType().getSimpleVT();
7355       assert(FVT == MVT::f32 || FVT == MVT::f16);
7356       MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7357       for (unsigned i = 0; i < NumElts; ++i)
7358         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7359                                   Op.getOperand(i)));
7360       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7361       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7362       Val = LowerBUILD_VECTOR(Val, DAG, ST);
7363       if (Val.getNode())
7364         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7365     }
7366     if (usesOnlyOneValue) {
7367       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7368       if (isConstant && Val.getNode())
7369         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7370     }
7371   }
7372 
7373   // If all elements are constants and the case above didn't get hit, fall back
7374   // to the default expansion, which will generate a load from the constant
7375   // pool.
7376   if (isConstant)
7377     return SDValue();
7378 
7379   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7380   if (NumElts >= 4) {
7381     SDValue shuffle = ReconstructShuffle(Op, DAG);
7382     if (shuffle != SDValue())
7383       return shuffle;
7384   }
7385 
7386   if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7387     // If we haven't found an efficient lowering, try splitting a 128-bit vector
7388     // into two 64-bit vectors; we might discover a better way to lower it.
7389     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7390     EVT ExtVT = VT.getVectorElementType();
7391     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7392     SDValue Lower =
7393         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7394     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7395       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7396     SDValue Upper = DAG.getBuildVector(
7397         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7398     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7399       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7400     if (Lower && Upper)
7401       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7402   }
7403 
7404   // Vectors with 32- or 64-bit elements can be built by directly assigning
7405   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
7406   // will be legalized.
7407   if (EltSize >= 32) {
7408     // Do the expansion with floating-point types, since that is what the VFP
7409     // registers are defined to use, and since i64 is not legal.
7410     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7411     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7412     SmallVector<SDValue, 8> Ops;
7413     for (unsigned i = 0; i < NumElts; ++i)
7414       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7415     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7416     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7417   }
7418 
7419   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7420   // know the default expansion would otherwise fall back on something even
7421   // worse. For a vector with one or two non-undef values, that's
7422   // scalar_to_vector for the elements followed by a shuffle (provided the
7423   // shuffle is valid for the target) and materialization element by element
7424   // on the stack followed by a load for everything else.
7425   if (!isConstant && !usesOnlyOneValue) {
7426     SDValue Vec = DAG.getUNDEF(VT);
7427     for (unsigned i = 0 ; i < NumElts; ++i) {
7428       SDValue V = Op.getOperand(i);
7429       if (V.isUndef())
7430         continue;
7431       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7432       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7433     }
7434     return Vec;
7435   }
7436 
7437   return SDValue();
7438 }
7439 
7440 // Gather data to see if the operation can be modelled as a
7441 // shuffle in combination with VEXTs.
7442 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7443                                               SelectionDAG &DAG) const {
7444   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7445   SDLoc dl(Op);
7446   EVT VT = Op.getValueType();
7447   unsigned NumElts = VT.getVectorNumElements();
7448 
7449   struct ShuffleSourceInfo {
7450     SDValue Vec;
7451     unsigned MinElt = std::numeric_limits<unsigned>::max();
7452     unsigned MaxElt = 0;
7453 
7454     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7455     // be compatible with the shuffle we intend to construct. As a result
7456     // ShuffleVec will be some sliding window into the original Vec.
7457     SDValue ShuffleVec;
7458 
7459     // Code should guarantee that element i in Vec starts at element "WindowBase
7460     // + i * WindowScale in ShuffleVec".
7461     int WindowBase = 0;
7462     int WindowScale = 1;
7463 
7464     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7465 
7466     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7467   };
7468 
7469   // First gather all vectors used as an immediate source for this BUILD_VECTOR
7470   // node.
7471   SmallVector<ShuffleSourceInfo, 2> Sources;
7472   for (unsigned i = 0; i < NumElts; ++i) {
7473     SDValue V = Op.getOperand(i);
7474     if (V.isUndef())
7475       continue;
7476     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7477       // A shuffle can only come from building a vector from various
7478       // elements of other vectors.
7479       return SDValue();
7480     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7481       // Furthermore, shuffles require a constant mask, whereas extractelts
7482       // accept variable indices.
7483       return SDValue();
7484     }
7485 
7486     // Add this element source to the list if it's not already there.
7487     SDValue SourceVec = V.getOperand(0);
7488     auto Source = llvm::find(Sources, SourceVec);
7489     if (Source == Sources.end())
7490       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7491 
7492     // Update the minimum and maximum lane number seen.
7493     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7494     Source->MinElt = std::min(Source->MinElt, EltNo);
7495     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7496   }
7497 
7498   // Currently only do something sane when at most two source vectors
7499   // are involved.
7500   if (Sources.size() > 2)
7501     return SDValue();
7502 
7503   // Find out the smallest element size among result and two sources, and use
7504   // it as element size to build the shuffle_vector.
7505   EVT SmallestEltTy = VT.getVectorElementType();
7506   for (auto &Source : Sources) {
7507     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7508     if (SrcEltTy.bitsLT(SmallestEltTy))
7509       SmallestEltTy = SrcEltTy;
7510   }
7511   unsigned ResMultiplier =
7512       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7513   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7514   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7515 
7516   // If the source vector is too wide or too narrow, we may nevertheless be able
7517   // to construct a compatible shuffle either by concatenating it with UNDEF or
7518   // extracting a suitable range of elements.
7519   for (auto &Src : Sources) {
7520     EVT SrcVT = Src.ShuffleVec.getValueType();
7521 
7522     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7523       continue;
7524 
7525     // This stage of the search produces a source with the same element type as
7526     // the original, but with a total width matching the BUILD_VECTOR output.
7527     EVT EltVT = SrcVT.getVectorElementType();
7528     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7529     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7530 
7531     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7532       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7533         return SDValue();
7534       // We can pad out the smaller vector for free, so if it's part of a
7535       // shuffle...
7536       Src.ShuffleVec =
7537           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7538                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7539       continue;
7540     }
7541 
7542     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7543       return SDValue();
7544 
7545     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7546       // Span too large for a VEXT to cope
7547       return SDValue();
7548     }
7549 
7550     if (Src.MinElt >= NumSrcElts) {
7551       // The extraction can just take the second half
7552       Src.ShuffleVec =
7553           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7554                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7555       Src.WindowBase = -NumSrcElts;
7556     } else if (Src.MaxElt < NumSrcElts) {
7557       // The extraction can just take the first half
7558       Src.ShuffleVec =
7559           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7560                       DAG.getConstant(0, dl, MVT::i32));
7561     } else {
7562       // An actual VEXT is needed
7563       SDValue VEXTSrc1 =
7564           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7565                       DAG.getConstant(0, dl, MVT::i32));
7566       SDValue VEXTSrc2 =
7567           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7568                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7569 
7570       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7571                                    VEXTSrc2,
7572                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
7573       Src.WindowBase = -Src.MinElt;
7574     }
7575   }
7576 
7577   // Another possible incompatibility occurs from the vector element types. We
7578   // can fix this by bitcasting the source vectors to the same type we intend
7579   // for the shuffle.
7580   for (auto &Src : Sources) {
7581     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7582     if (SrcEltTy == SmallestEltTy)
7583       continue;
7584     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7585     Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
7586     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7587     Src.WindowBase *= Src.WindowScale;
7588   }
7589 
7590   // Final sanity check before we try to actually produce a shuffle.
7591   LLVM_DEBUG(for (auto Src
7592                   : Sources)
7593                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7594 
7595   // The stars all align, our next step is to produce the mask for the shuffle.
7596   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7597   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7598   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7599     SDValue Entry = Op.getOperand(i);
7600     if (Entry.isUndef())
7601       continue;
7602 
7603     auto Src = llvm::find(Sources, Entry.getOperand(0));
7604     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7605 
7606     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7607     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7608     // segment.
7609     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7610     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7611                                VT.getScalarSizeInBits());
7612     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7613 
7614     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7615     // starting at the appropriate offset.
7616     int *LaneMask = &Mask[i * ResMultiplier];
7617 
7618     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7619     ExtractBase += NumElts * (Src - Sources.begin());
7620     for (int j = 0; j < LanesDefined; ++j)
7621       LaneMask[j] = ExtractBase + j;
7622   }
7623 
7624 
7625   // We can't handle more than two sources. This should have already
7626   // been checked before this point.
7627   assert(Sources.size() <= 2 && "Too many sources!");
7628 
7629   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7630   for (unsigned i = 0; i < Sources.size(); ++i)
7631     ShuffleOps[i] = Sources[i].ShuffleVec;
7632 
7633   SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7634                                             ShuffleOps[1], Mask, DAG);
7635   if (!Shuffle)
7636     return SDValue();
7637   return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
7638 }
7639 
7640 enum ShuffleOpCodes {
7641   OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7642   OP_VREV,
7643   OP_VDUP0,
7644   OP_VDUP1,
7645   OP_VDUP2,
7646   OP_VDUP3,
7647   OP_VEXT1,
7648   OP_VEXT2,
7649   OP_VEXT3,
7650   OP_VUZPL, // VUZP, left result
7651   OP_VUZPR, // VUZP, right result
7652   OP_VZIPL, // VZIP, left result
7653   OP_VZIPR, // VZIP, right result
7654   OP_VTRNL, // VTRN, left result
7655   OP_VTRNR  // VTRN, right result
7656 };
7657 
7658 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7659   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7660   switch (OpNum) {
7661   case OP_COPY:
7662   case OP_VREV:
7663   case OP_VDUP0:
7664   case OP_VDUP1:
7665   case OP_VDUP2:
7666   case OP_VDUP3:
7667     return true;
7668   }
7669   return false;
7670 }
7671 
7672 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7673 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7674 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7675 /// are assumed to be legal.
7676 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7677   if (VT.getVectorNumElements() == 4 &&
7678       (VT.is128BitVector() || VT.is64BitVector())) {
7679     unsigned PFIndexes[4];
7680     for (unsigned i = 0; i != 4; ++i) {
7681       if (M[i] < 0)
7682         PFIndexes[i] = 8;
7683       else
7684         PFIndexes[i] = M[i];
7685     }
7686 
7687     // Compute the index in the perfect shuffle table.
7688     unsigned PFTableIndex =
7689       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7690     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7691     unsigned Cost = (PFEntry >> 30);
7692 
7693     if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7694       return true;
7695   }
7696 
7697   bool ReverseVEXT, isV_UNDEF;
7698   unsigned Imm, WhichResult;
7699 
7700   unsigned EltSize = VT.getScalarSizeInBits();
7701   if (EltSize >= 32 ||
7702       ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7703       ShuffleVectorInst::isIdentityMask(M) ||
7704       isVREVMask(M, VT, 64) ||
7705       isVREVMask(M, VT, 32) ||
7706       isVREVMask(M, VT, 16))
7707     return true;
7708   else if (Subtarget->hasNEON() &&
7709            (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7710             isVTBLMask(M, VT) ||
7711             isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7712     return true;
7713   else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7714            isReverseMask(M, VT))
7715     return true;
7716   else if (Subtarget->hasMVEIntegerOps() &&
7717            (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1)))
7718     return true;
7719   else
7720     return false;
7721 }
7722 
7723 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7724 /// the specified operations to build the shuffle.
7725 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7726                                       SDValue RHS, SelectionDAG &DAG,
7727                                       const SDLoc &dl) {
7728   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7729   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7730   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7731 
7732   if (OpNum == OP_COPY) {
7733     if (LHSID == (1*9+2)*9+3) return LHS;
7734     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7735     return RHS;
7736   }
7737 
7738   SDValue OpLHS, OpRHS;
7739   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7740   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7741   EVT VT = OpLHS.getValueType();
7742 
7743   switch (OpNum) {
7744   default: llvm_unreachable("Unknown shuffle opcode!");
7745   case OP_VREV:
7746     // VREV divides the vector in half and swaps within the half.
7747     if (VT.getVectorElementType() == MVT::i32 ||
7748         VT.getVectorElementType() == MVT::f32)
7749       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7750     // vrev <4 x i16> -> VREV32
7751     if (VT.getVectorElementType() == MVT::i16)
7752       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7753     // vrev <4 x i8> -> VREV16
7754     assert(VT.getVectorElementType() == MVT::i8);
7755     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7756   case OP_VDUP0:
7757   case OP_VDUP1:
7758   case OP_VDUP2:
7759   case OP_VDUP3:
7760     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7761                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7762   case OP_VEXT1:
7763   case OP_VEXT2:
7764   case OP_VEXT3:
7765     return DAG.getNode(ARMISD::VEXT, dl, VT,
7766                        OpLHS, OpRHS,
7767                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7768   case OP_VUZPL:
7769   case OP_VUZPR:
7770     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7771                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7772   case OP_VZIPL:
7773   case OP_VZIPR:
7774     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7775                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7776   case OP_VTRNL:
7777   case OP_VTRNR:
7778     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7779                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7780   }
7781 }
7782 
7783 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7784                                        ArrayRef<int> ShuffleMask,
7785                                        SelectionDAG &DAG) {
7786   // Check to see if we can use the VTBL instruction.
7787   SDValue V1 = Op.getOperand(0);
7788   SDValue V2 = Op.getOperand(1);
7789   SDLoc DL(Op);
7790 
7791   SmallVector<SDValue, 8> VTBLMask;
7792   for (ArrayRef<int>::iterator
7793          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7794     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7795 
7796   if (V2.getNode()->isUndef())
7797     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7798                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7799 
7800   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7801                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7802 }
7803 
7804 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7805                                                       SelectionDAG &DAG) {
7806   SDLoc DL(Op);
7807   SDValue OpLHS = Op.getOperand(0);
7808   EVT VT = OpLHS.getValueType();
7809 
7810   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7811          "Expect an v8i16/v16i8 type");
7812   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7813   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7814   // extract the first 8 bytes into the top double word and the last 8 bytes
7815   // into the bottom double word. The v8i16 case is similar.
7816   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7817   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7818                      DAG.getConstant(ExtractNum, DL, MVT::i32));
7819 }
7820 
7821 static EVT getVectorTyFromPredicateVector(EVT VT) {
7822   switch (VT.getSimpleVT().SimpleTy) {
7823   case MVT::v4i1:
7824     return MVT::v4i32;
7825   case MVT::v8i1:
7826     return MVT::v8i16;
7827   case MVT::v16i1:
7828     return MVT::v16i8;
7829   default:
7830     llvm_unreachable("Unexpected vector predicate type");
7831   }
7832 }
7833 
7834 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7835                                     SelectionDAG &DAG) {
7836   // Converting from boolean predicates to integers involves creating a vector
7837   // of all ones or all zeroes and selecting the lanes based upon the real
7838   // predicate.
7839   SDValue AllOnes =
7840       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7841   AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7842 
7843   SDValue AllZeroes =
7844       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7845   AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7846 
7847   // Get full vector type from predicate type
7848   EVT NewVT = getVectorTyFromPredicateVector(VT);
7849 
7850   SDValue RecastV1;
7851   // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7852   // this to a v16i1. This cannot be done with an ordinary bitcast because the
7853   // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7854   // since we know in hardware the sizes are really the same.
7855   if (VT != MVT::v16i1)
7856     RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7857   else
7858     RecastV1 = Pred;
7859 
7860   // Select either all ones or zeroes depending upon the real predicate bits.
7861   SDValue PredAsVector =
7862       DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7863 
7864   // Recast our new predicate-as-integer v16i8 vector into something
7865   // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7866   return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7867 }
7868 
7869 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7870                                       const ARMSubtarget *ST) {
7871   EVT VT = Op.getValueType();
7872   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7873   ArrayRef<int> ShuffleMask = SVN->getMask();
7874 
7875   assert(ST->hasMVEIntegerOps() &&
7876          "No support for vector shuffle of boolean predicates");
7877 
7878   SDValue V1 = Op.getOperand(0);
7879   SDLoc dl(Op);
7880   if (isReverseMask(ShuffleMask, VT)) {
7881     SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7882     SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7883     SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7884                               DAG.getConstant(16, dl, MVT::i32));
7885     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7886   }
7887 
7888   // Until we can come up with optimised cases for every single vector
7889   // shuffle in existence we have chosen the least painful strategy. This is
7890   // to essentially promote the boolean predicate to a 8-bit integer, where
7891   // each predicate represents a byte. Then we fall back on a normal integer
7892   // vector shuffle and convert the result back into a predicate vector. In
7893   // many cases the generated code might be even better than scalar code
7894   // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7895   // fields in a register into 8 other arbitrary 2-bit fields!
7896   SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7897   EVT NewVT = PredAsVector.getValueType();
7898 
7899   // Do the shuffle!
7900   SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7901                                           DAG.getUNDEF(NewVT), ShuffleMask);
7902 
7903   // Now return the result of comparing the shuffled vector with zero,
7904   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7905   return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7906                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7907 }
7908 
7909 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
7910                                             ArrayRef<int> ShuffleMask,
7911                                             SelectionDAG &DAG) {
7912   // Attempt to lower the vector shuffle using as many whole register movs as
7913   // possible. This is useful for types smaller than 32bits, which would
7914   // often otherwise become a series for grp movs.
7915   SDLoc dl(Op);
7916   EVT VT = Op.getValueType();
7917   if (VT.getScalarSizeInBits() >= 32)
7918     return SDValue();
7919 
7920   assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
7921          "Unexpected vector type");
7922   int NumElts = VT.getVectorNumElements();
7923   int QuarterSize = NumElts / 4;
7924   // The four final parts of the vector, as i32's
7925   SDValue Parts[4];
7926 
7927   // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
7928   // <u,u,u,u>), returning the vmov lane index
7929   auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
7930     // Detect which mov lane this would be from the first non-undef element.
7931     int MovIdx = -1;
7932     for (int i = 0; i < Length; i++) {
7933       if (ShuffleMask[Start + i] >= 0) {
7934         if (ShuffleMask[Start + i] % Length != i)
7935           return -1;
7936         MovIdx = ShuffleMask[Start + i] / Length;
7937         break;
7938       }
7939     }
7940     // If all items are undef, leave this for other combines
7941     if (MovIdx == -1)
7942       return -1;
7943     // Check the remaining values are the correct part of the same mov
7944     for (int i = 1; i < Length; i++) {
7945       if (ShuffleMask[Start + i] >= 0 &&
7946           (ShuffleMask[Start + i] / Length != MovIdx ||
7947            ShuffleMask[Start + i] % Length != i))
7948         return -1;
7949     }
7950     return MovIdx;
7951   };
7952 
7953   for (int Part = 0; Part < 4; ++Part) {
7954     // Does this part look like a mov
7955     int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
7956     if (Elt != -1) {
7957       SDValue Input = Op->getOperand(0);
7958       if (Elt >= 4) {
7959         Input = Op->getOperand(1);
7960         Elt -= 4;
7961       }
7962       SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input);
7963       Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast,
7964                                 DAG.getConstant(Elt, dl, MVT::i32));
7965     }
7966   }
7967 
7968   // Nothing interesting found, just return
7969   if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
7970     return SDValue();
7971 
7972   // The other parts need to be built with the old shuffle vector, cast to a
7973   // v4i32 and extract_vector_elts
7974   if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
7975     SmallVector<int, 16> NewShuffleMask;
7976     for (int Part = 0; Part < 4; ++Part)
7977       for (int i = 0; i < QuarterSize; i++)
7978         NewShuffleMask.push_back(
7979             Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
7980     SDValue NewShuffle = DAG.getVectorShuffle(
7981         VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
7982     SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle);
7983 
7984     for (int Part = 0; Part < 4; ++Part)
7985       if (!Parts[Part])
7986         Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7987                                   BitCast, DAG.getConstant(Part, dl, MVT::i32));
7988   }
7989   // Build a vector out of the various parts and bitcast it back to the original
7990   // type.
7991   SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts);
7992   return DAG.getBitcast(VT, NewVec);
7993 }
7994 
7995 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7996                                    const ARMSubtarget *ST) {
7997   SDValue V1 = Op.getOperand(0);
7998   SDValue V2 = Op.getOperand(1);
7999   SDLoc dl(Op);
8000   EVT VT = Op.getValueType();
8001   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8002   unsigned EltSize = VT.getScalarSizeInBits();
8003 
8004   if (ST->hasMVEIntegerOps() && EltSize == 1)
8005     return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8006 
8007   // Convert shuffles that are directly supported on NEON to target-specific
8008   // DAG nodes, instead of keeping them as shuffles and matching them again
8009   // during code selection.  This is more efficient and avoids the possibility
8010   // of inconsistencies between legalization and selection.
8011   // FIXME: floating-point vectors should be canonicalized to integer vectors
8012   // of the same time so that they get CSEd properly.
8013   ArrayRef<int> ShuffleMask = SVN->getMask();
8014 
8015   if (EltSize <= 32) {
8016     if (SVN->isSplat()) {
8017       int Lane = SVN->getSplatIndex();
8018       // If this is undef splat, generate it via "just" vdup, if possible.
8019       if (Lane == -1) Lane = 0;
8020 
8021       // Test if V1 is a SCALAR_TO_VECTOR.
8022       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8023         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8024       }
8025       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8026       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8027       // reaches it).
8028       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8029           !isa<ConstantSDNode>(V1.getOperand(0))) {
8030         bool IsScalarToVector = true;
8031         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8032           if (!V1.getOperand(i).isUndef()) {
8033             IsScalarToVector = false;
8034             break;
8035           }
8036         if (IsScalarToVector)
8037           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8038       }
8039       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8040                          DAG.getConstant(Lane, dl, MVT::i32));
8041     }
8042 
8043     bool ReverseVEXT = false;
8044     unsigned Imm = 0;
8045     if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8046       if (ReverseVEXT)
8047         std::swap(V1, V2);
8048       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8049                          DAG.getConstant(Imm, dl, MVT::i32));
8050     }
8051 
8052     if (isVREVMask(ShuffleMask, VT, 64))
8053       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8054     if (isVREVMask(ShuffleMask, VT, 32))
8055       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8056     if (isVREVMask(ShuffleMask, VT, 16))
8057       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8058 
8059     if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8060       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8061                          DAG.getConstant(Imm, dl, MVT::i32));
8062     }
8063 
8064     // Check for Neon shuffles that modify both input vectors in place.
8065     // If both results are used, i.e., if there are two shuffles with the same
8066     // source operands and with masks corresponding to both results of one of
8067     // these operations, DAG memoization will ensure that a single node is
8068     // used for both shuffles.
8069     unsigned WhichResult = 0;
8070     bool isV_UNDEF = false;
8071     if (ST->hasNEON()) {
8072       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8073               ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8074         if (isV_UNDEF)
8075           V2 = V1;
8076         return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8077             .getValue(WhichResult);
8078       }
8079     }
8080     if (ST->hasMVEIntegerOps()) {
8081       if (isVMOVNMask(ShuffleMask, VT, 0))
8082         return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8083                            DAG.getConstant(0, dl, MVT::i32));
8084       if (isVMOVNMask(ShuffleMask, VT, 1))
8085         return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8086                            DAG.getConstant(1, dl, MVT::i32));
8087     }
8088 
8089     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8090     // shuffles that produce a result larger than their operands with:
8091     //   shuffle(concat(v1, undef), concat(v2, undef))
8092     // ->
8093     //   shuffle(concat(v1, v2), undef)
8094     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8095     //
8096     // This is useful in the general case, but there are special cases where
8097     // native shuffles produce larger results: the two-result ops.
8098     //
8099     // Look through the concat when lowering them:
8100     //   shuffle(concat(v1, v2), undef)
8101     // ->
8102     //   concat(VZIP(v1, v2):0, :1)
8103     //
8104     if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8105       SDValue SubV1 = V1->getOperand(0);
8106       SDValue SubV2 = V1->getOperand(1);
8107       EVT SubVT = SubV1.getValueType();
8108 
8109       // We expect these to have been canonicalized to -1.
8110       assert(llvm::all_of(ShuffleMask, [&](int i) {
8111         return i < (int)VT.getVectorNumElements();
8112       }) && "Unexpected shuffle index into UNDEF operand!");
8113 
8114       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8115               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8116         if (isV_UNDEF)
8117           SubV2 = SubV1;
8118         assert((WhichResult == 0) &&
8119                "In-place shuffle of concat can only have one result!");
8120         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8121                                   SubV1, SubV2);
8122         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8123                            Res.getValue(1));
8124       }
8125     }
8126   }
8127 
8128   // If the shuffle is not directly supported and it has 4 elements, use
8129   // the PerfectShuffle-generated table to synthesize it from other shuffles.
8130   unsigned NumElts = VT.getVectorNumElements();
8131   if (NumElts == 4) {
8132     unsigned PFIndexes[4];
8133     for (unsigned i = 0; i != 4; ++i) {
8134       if (ShuffleMask[i] < 0)
8135         PFIndexes[i] = 8;
8136       else
8137         PFIndexes[i] = ShuffleMask[i];
8138     }
8139 
8140     // Compute the index in the perfect shuffle table.
8141     unsigned PFTableIndex =
8142       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8143     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8144     unsigned Cost = (PFEntry >> 30);
8145 
8146     if (Cost <= 4) {
8147       if (ST->hasNEON())
8148         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8149       else if (isLegalMVEShuffleOp(PFEntry)) {
8150         unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8151         unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8152         unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8153         unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8154         if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8155           return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8156       }
8157     }
8158   }
8159 
8160   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8161   if (EltSize >= 32) {
8162     // Do the expansion with floating-point types, since that is what the VFP
8163     // registers are defined to use, and since i64 is not legal.
8164     EVT EltVT = EVT::getFloatingPointVT(EltSize);
8165     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8166     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8167     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8168     SmallVector<SDValue, 8> Ops;
8169     for (unsigned i = 0; i < NumElts; ++i) {
8170       if (ShuffleMask[i] < 0)
8171         Ops.push_back(DAG.getUNDEF(EltVT));
8172       else
8173         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8174                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
8175                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8176                                                   dl, MVT::i32)));
8177     }
8178     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8179     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8180   }
8181 
8182   if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
8183     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
8184 
8185   if (ST->hasNEON() && VT == MVT::v8i8)
8186     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8187       return NewOp;
8188 
8189   if (ST->hasMVEIntegerOps())
8190     if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8191       return NewOp;
8192 
8193   return SDValue();
8194 }
8195 
8196 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8197                                          const ARMSubtarget *ST) {
8198   EVT VecVT = Op.getOperand(0).getValueType();
8199   SDLoc dl(Op);
8200 
8201   assert(ST->hasMVEIntegerOps() &&
8202          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8203 
8204   SDValue Conv =
8205       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8206   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8207   unsigned LaneWidth =
8208       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8209   unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8210   SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8211                             Op.getOperand(1), DAG.getValueType(MVT::i1));
8212   SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8213                             DAG.getConstant(~Mask, dl, MVT::i32));
8214   return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8215 }
8216 
8217 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8218                                                   SelectionDAG &DAG) const {
8219   // INSERT_VECTOR_ELT is legal only for immediate indexes.
8220   SDValue Lane = Op.getOperand(2);
8221   if (!isa<ConstantSDNode>(Lane))
8222     return SDValue();
8223 
8224   SDValue Elt = Op.getOperand(1);
8225   EVT EltVT = Elt.getValueType();
8226 
8227   if (Subtarget->hasMVEIntegerOps() &&
8228       Op.getValueType().getScalarSizeInBits() == 1)
8229     return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8230 
8231   if (getTypeAction(*DAG.getContext(), EltVT) ==
8232       TargetLowering::TypePromoteFloat) {
8233     // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8234     // but the type system will try to do that if we don't intervene.
8235     // Reinterpret any such vector-element insertion as one with the
8236     // corresponding integer types.
8237 
8238     SDLoc dl(Op);
8239 
8240     EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8241     assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8242            TargetLowering::TypePromoteFloat);
8243 
8244     SDValue VecIn = Op.getOperand(0);
8245     EVT VecVT = VecIn.getValueType();
8246     EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8247                                   VecVT.getVectorNumElements());
8248 
8249     SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8250     SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8251     SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8252                                   IVecIn, IElt, Lane);
8253     return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8254   }
8255 
8256   return Op;
8257 }
8258 
8259 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8260                                           const ARMSubtarget *ST) {
8261   EVT VecVT = Op.getOperand(0).getValueType();
8262   SDLoc dl(Op);
8263 
8264   assert(ST->hasMVEIntegerOps() &&
8265          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8266 
8267   SDValue Conv =
8268       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8269   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8270   unsigned LaneWidth =
8271       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8272   SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8273                               DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8274   return Shift;
8275 }
8276 
8277 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8278                                        const ARMSubtarget *ST) {
8279   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8280   SDValue Lane = Op.getOperand(1);
8281   if (!isa<ConstantSDNode>(Lane))
8282     return SDValue();
8283 
8284   SDValue Vec = Op.getOperand(0);
8285   EVT VT = Vec.getValueType();
8286 
8287   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8288     return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8289 
8290   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8291     SDLoc dl(Op);
8292     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8293   }
8294 
8295   return Op;
8296 }
8297 
8298 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8299                                       const ARMSubtarget *ST) {
8300   SDValue V1 = Op.getOperand(0);
8301   SDValue V2 = Op.getOperand(1);
8302   SDLoc dl(Op);
8303   EVT VT = Op.getValueType();
8304   EVT Op1VT = V1.getValueType();
8305   EVT Op2VT = V2.getValueType();
8306   unsigned NumElts = VT.getVectorNumElements();
8307 
8308   assert(Op1VT == Op2VT && "Operand types don't match!");
8309   assert(VT.getScalarSizeInBits() == 1 &&
8310          "Unexpected custom CONCAT_VECTORS lowering");
8311   assert(ST->hasMVEIntegerOps() &&
8312          "CONCAT_VECTORS lowering only supported for MVE");
8313 
8314   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8315   SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8316 
8317   // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8318   // promoted to v8i16, etc.
8319 
8320   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8321 
8322   // Extract the vector elements from Op1 and Op2 one by one and truncate them
8323   // to be the right size for the destination. For example, if Op1 is v4i1 then
8324   // the promoted vector is v4i32. The result of concatentation gives a v8i1,
8325   // which when promoted is v8i16. That means each i32 element from Op1 needs
8326   // truncating to i16 and inserting in the result.
8327   EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8328   SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8329   auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8330     EVT NewVT = NewV.getValueType();
8331     EVT ConcatVT = ConVec.getValueType();
8332     for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8333       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8334                                 DAG.getIntPtrConstant(i, dl));
8335       ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8336                            DAG.getConstant(j, dl, MVT::i32));
8337     }
8338     return ConVec;
8339   };
8340   unsigned j = 0;
8341   ConVec = ExractInto(NewV1, ConVec, j);
8342   ConVec = ExractInto(NewV2, ConVec, j);
8343 
8344   // Now return the result of comparing the subvector with zero,
8345   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8346   return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8347                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8348 }
8349 
8350 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8351                                    const ARMSubtarget *ST) {
8352   EVT VT = Op->getValueType(0);
8353   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8354     return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8355 
8356   // The only time a CONCAT_VECTORS operation can have legal types is when
8357   // two 64-bit vectors are concatenated to a 128-bit vector.
8358   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8359          "unexpected CONCAT_VECTORS");
8360   SDLoc dl(Op);
8361   SDValue Val = DAG.getUNDEF(MVT::v2f64);
8362   SDValue Op0 = Op.getOperand(0);
8363   SDValue Op1 = Op.getOperand(1);
8364   if (!Op0.isUndef())
8365     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8366                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8367                       DAG.getIntPtrConstant(0, dl));
8368   if (!Op1.isUndef())
8369     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8370                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8371                       DAG.getIntPtrConstant(1, dl));
8372   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8373 }
8374 
8375 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8376                                       const ARMSubtarget *ST) {
8377   SDValue V1 = Op.getOperand(0);
8378   SDValue V2 = Op.getOperand(1);
8379   SDLoc dl(Op);
8380   EVT VT = Op.getValueType();
8381   EVT Op1VT = V1.getValueType();
8382   unsigned NumElts = VT.getVectorNumElements();
8383   unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8384 
8385   assert(VT.getScalarSizeInBits() == 1 &&
8386          "Unexpected custom EXTRACT_SUBVECTOR lowering");
8387   assert(ST->hasMVEIntegerOps() &&
8388          "EXTRACT_SUBVECTOR lowering only supported for MVE");
8389 
8390   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8391 
8392   // We now have Op1 promoted to a vector of integers, where v8i1 gets
8393   // promoted to v8i16, etc.
8394 
8395   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8396 
8397   EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8398   SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8399   for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8400     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8401                               DAG.getIntPtrConstant(i, dl));
8402     SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8403                          DAG.getConstant(j, dl, MVT::i32));
8404   }
8405 
8406   // Now return the result of comparing the subvector with zero,
8407   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8408   return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8409                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8410 }
8411 
8412 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8413 /// element has been zero/sign-extended, depending on the isSigned parameter,
8414 /// from an integer type half its size.
8415 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8416                                    bool isSigned) {
8417   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8418   EVT VT = N->getValueType(0);
8419   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8420     SDNode *BVN = N->getOperand(0).getNode();
8421     if (BVN->getValueType(0) != MVT::v4i32 ||
8422         BVN->getOpcode() != ISD::BUILD_VECTOR)
8423       return false;
8424     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8425     unsigned HiElt = 1 - LoElt;
8426     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8427     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8428     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8429     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8430     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8431       return false;
8432     if (isSigned) {
8433       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8434           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8435         return true;
8436     } else {
8437       if (Hi0->isNullValue() && Hi1->isNullValue())
8438         return true;
8439     }
8440     return false;
8441   }
8442 
8443   if (N->getOpcode() != ISD::BUILD_VECTOR)
8444     return false;
8445 
8446   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8447     SDNode *Elt = N->getOperand(i).getNode();
8448     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8449       unsigned EltSize = VT.getScalarSizeInBits();
8450       unsigned HalfSize = EltSize / 2;
8451       if (isSigned) {
8452         if (!isIntN(HalfSize, C->getSExtValue()))
8453           return false;
8454       } else {
8455         if (!isUIntN(HalfSize, C->getZExtValue()))
8456           return false;
8457       }
8458       continue;
8459     }
8460     return false;
8461   }
8462 
8463   return true;
8464 }
8465 
8466 /// isSignExtended - Check if a node is a vector value that is sign-extended
8467 /// or a constant BUILD_VECTOR with sign-extended elements.
8468 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8469   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8470     return true;
8471   if (isExtendedBUILD_VECTOR(N, DAG, true))
8472     return true;
8473   return false;
8474 }
8475 
8476 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8477 /// or a constant BUILD_VECTOR with zero-extended elements.
8478 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8479   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8480     return true;
8481   if (isExtendedBUILD_VECTOR(N, DAG, false))
8482     return true;
8483   return false;
8484 }
8485 
8486 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8487   if (OrigVT.getSizeInBits() >= 64)
8488     return OrigVT;
8489 
8490   assert(OrigVT.isSimple() && "Expecting a simple value type");
8491 
8492   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8493   switch (OrigSimpleTy) {
8494   default: llvm_unreachable("Unexpected Vector Type");
8495   case MVT::v2i8:
8496   case MVT::v2i16:
8497      return MVT::v2i32;
8498   case MVT::v4i8:
8499     return  MVT::v4i16;
8500   }
8501 }
8502 
8503 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8504 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8505 /// We insert the required extension here to get the vector to fill a D register.
8506 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8507                                             const EVT &OrigTy,
8508                                             const EVT &ExtTy,
8509                                             unsigned ExtOpcode) {
8510   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8511   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8512   // 64-bits we need to insert a new extension so that it will be 64-bits.
8513   assert(ExtTy.is128BitVector() && "Unexpected extension size");
8514   if (OrigTy.getSizeInBits() >= 64)
8515     return N;
8516 
8517   // Must extend size to at least 64 bits to be used as an operand for VMULL.
8518   EVT NewVT = getExtensionTo64Bits(OrigTy);
8519 
8520   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8521 }
8522 
8523 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8524 /// does not do any sign/zero extension. If the original vector is less
8525 /// than 64 bits, an appropriate extension will be added after the load to
8526 /// reach a total size of 64 bits. We have to add the extension separately
8527 /// because ARM does not have a sign/zero extending load for vectors.
8528 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8529   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8530 
8531   // The load already has the right type.
8532   if (ExtendedTy == LD->getMemoryVT())
8533     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8534                        LD->getBasePtr(), LD->getPointerInfo(),
8535                        LD->getAlignment(), LD->getMemOperand()->getFlags());
8536 
8537   // We need to create a zextload/sextload. We cannot just create a load
8538   // followed by a zext/zext node because LowerMUL is also run during normal
8539   // operation legalization where we can't create illegal types.
8540   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8541                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8542                         LD->getMemoryVT(), LD->getAlignment(),
8543                         LD->getMemOperand()->getFlags());
8544 }
8545 
8546 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8547 /// extending load, or BUILD_VECTOR with extended elements, return the
8548 /// unextended value. The unextended vector should be 64 bits so that it can
8549 /// be used as an operand to a VMULL instruction. If the original vector size
8550 /// before extension is less than 64 bits we add a an extension to resize
8551 /// the vector to 64 bits.
8552 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8553   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8554     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8555                                         N->getOperand(0)->getValueType(0),
8556                                         N->getValueType(0),
8557                                         N->getOpcode());
8558 
8559   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8560     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8561            "Expected extending load");
8562 
8563     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8564     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8565     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8566     SDValue extLoad =
8567         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8568     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8569 
8570     return newLoad;
8571   }
8572 
8573   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
8574   // have been legalized as a BITCAST from v4i32.
8575   if (N->getOpcode() == ISD::BITCAST) {
8576     SDNode *BVN = N->getOperand(0).getNode();
8577     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8578            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8579     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8580     return DAG.getBuildVector(
8581         MVT::v2i32, SDLoc(N),
8582         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8583   }
8584   // Construct a new BUILD_VECTOR with elements truncated to half the size.
8585   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8586   EVT VT = N->getValueType(0);
8587   unsigned EltSize = VT.getScalarSizeInBits() / 2;
8588   unsigned NumElts = VT.getVectorNumElements();
8589   MVT TruncVT = MVT::getIntegerVT(EltSize);
8590   SmallVector<SDValue, 8> Ops;
8591   SDLoc dl(N);
8592   for (unsigned i = 0; i != NumElts; ++i) {
8593     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8594     const APInt &CInt = C->getAPIntValue();
8595     // Element types smaller than 32 bits are not legal, so use i32 elements.
8596     // The values are implicitly truncated so sext vs. zext doesn't matter.
8597     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8598   }
8599   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8600 }
8601 
8602 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8603   unsigned Opcode = N->getOpcode();
8604   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8605     SDNode *N0 = N->getOperand(0).getNode();
8606     SDNode *N1 = N->getOperand(1).getNode();
8607     return N0->hasOneUse() && N1->hasOneUse() &&
8608       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8609   }
8610   return false;
8611 }
8612 
8613 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8614   unsigned Opcode = N->getOpcode();
8615   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8616     SDNode *N0 = N->getOperand(0).getNode();
8617     SDNode *N1 = N->getOperand(1).getNode();
8618     return N0->hasOneUse() && N1->hasOneUse() &&
8619       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8620   }
8621   return false;
8622 }
8623 
8624 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8625   // Multiplications are only custom-lowered for 128-bit vectors so that
8626   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
8627   EVT VT = Op.getValueType();
8628   assert(VT.is128BitVector() && VT.isInteger() &&
8629          "unexpected type for custom-lowering ISD::MUL");
8630   SDNode *N0 = Op.getOperand(0).getNode();
8631   SDNode *N1 = Op.getOperand(1).getNode();
8632   unsigned NewOpc = 0;
8633   bool isMLA = false;
8634   bool isN0SExt = isSignExtended(N0, DAG);
8635   bool isN1SExt = isSignExtended(N1, DAG);
8636   if (isN0SExt && isN1SExt)
8637     NewOpc = ARMISD::VMULLs;
8638   else {
8639     bool isN0ZExt = isZeroExtended(N0, DAG);
8640     bool isN1ZExt = isZeroExtended(N1, DAG);
8641     if (isN0ZExt && isN1ZExt)
8642       NewOpc = ARMISD::VMULLu;
8643     else if (isN1SExt || isN1ZExt) {
8644       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8645       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8646       if (isN1SExt && isAddSubSExt(N0, DAG)) {
8647         NewOpc = ARMISD::VMULLs;
8648         isMLA = true;
8649       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8650         NewOpc = ARMISD::VMULLu;
8651         isMLA = true;
8652       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8653         std::swap(N0, N1);
8654         NewOpc = ARMISD::VMULLu;
8655         isMLA = true;
8656       }
8657     }
8658 
8659     if (!NewOpc) {
8660       if (VT == MVT::v2i64)
8661         // Fall through to expand this.  It is not legal.
8662         return SDValue();
8663       else
8664         // Other vector multiplications are legal.
8665         return Op;
8666     }
8667   }
8668 
8669   // Legalize to a VMULL instruction.
8670   SDLoc DL(Op);
8671   SDValue Op0;
8672   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8673   if (!isMLA) {
8674     Op0 = SkipExtensionForVMULL(N0, DAG);
8675     assert(Op0.getValueType().is64BitVector() &&
8676            Op1.getValueType().is64BitVector() &&
8677            "unexpected types for extended operands to VMULL");
8678     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8679   }
8680 
8681   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8682   // isel lowering to take advantage of no-stall back to back vmul + vmla.
8683   //   vmull q0, d4, d6
8684   //   vmlal q0, d5, d6
8685   // is faster than
8686   //   vaddl q0, d4, d5
8687   //   vmovl q1, d6
8688   //   vmul  q0, q0, q1
8689   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8690   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8691   EVT Op1VT = Op1.getValueType();
8692   return DAG.getNode(N0->getOpcode(), DL, VT,
8693                      DAG.getNode(NewOpc, DL, VT,
8694                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8695                      DAG.getNode(NewOpc, DL, VT,
8696                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8697 }
8698 
8699 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8700                               SelectionDAG &DAG) {
8701   // TODO: Should this propagate fast-math-flags?
8702 
8703   // Convert to float
8704   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8705   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8706   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8707   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8708   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8709   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8710   // Get reciprocal estimate.
8711   // float4 recip = vrecpeq_f32(yf);
8712   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8713                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8714                    Y);
8715   // Because char has a smaller range than uchar, we can actually get away
8716   // without any newton steps.  This requires that we use a weird bias
8717   // of 0xb000, however (again, this has been exhaustively tested).
8718   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8719   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8720   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8721   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8722   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8723   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8724   // Convert back to short.
8725   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8726   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8727   return X;
8728 }
8729 
8730 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8731                                SelectionDAG &DAG) {
8732   // TODO: Should this propagate fast-math-flags?
8733 
8734   SDValue N2;
8735   // Convert to float.
8736   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8737   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8738   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8739   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8740   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8741   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8742 
8743   // Use reciprocal estimate and one refinement step.
8744   // float4 recip = vrecpeq_f32(yf);
8745   // recip *= vrecpsq_f32(yf, recip);
8746   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8747                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8748                    N1);
8749   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8750                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8751                    N1, N2);
8752   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8753   // Because short has a smaller range than ushort, we can actually get away
8754   // with only a single newton step.  This requires that we use a weird bias
8755   // of 89, however (again, this has been exhaustively tested).
8756   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8757   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8758   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8759   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8760   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8761   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8762   // Convert back to integer and return.
8763   // return vmovn_s32(vcvt_s32_f32(result));
8764   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8765   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8766   return N0;
8767 }
8768 
8769 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8770                          const ARMSubtarget *ST) {
8771   EVT VT = Op.getValueType();
8772   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8773          "unexpected type for custom-lowering ISD::SDIV");
8774 
8775   SDLoc dl(Op);
8776   SDValue N0 = Op.getOperand(0);
8777   SDValue N1 = Op.getOperand(1);
8778   SDValue N2, N3;
8779 
8780   if (VT == MVT::v8i8) {
8781     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8782     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8783 
8784     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8785                      DAG.getIntPtrConstant(4, dl));
8786     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8787                      DAG.getIntPtrConstant(4, dl));
8788     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8789                      DAG.getIntPtrConstant(0, dl));
8790     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8791                      DAG.getIntPtrConstant(0, dl));
8792 
8793     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8794     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8795 
8796     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8797     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8798 
8799     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8800     return N0;
8801   }
8802   return LowerSDIV_v4i16(N0, N1, dl, DAG);
8803 }
8804 
8805 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8806                          const ARMSubtarget *ST) {
8807   // TODO: Should this propagate fast-math-flags?
8808   EVT VT = Op.getValueType();
8809   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8810          "unexpected type for custom-lowering ISD::UDIV");
8811 
8812   SDLoc dl(Op);
8813   SDValue N0 = Op.getOperand(0);
8814   SDValue N1 = Op.getOperand(1);
8815   SDValue N2, N3;
8816 
8817   if (VT == MVT::v8i8) {
8818     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8819     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8820 
8821     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8822                      DAG.getIntPtrConstant(4, dl));
8823     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8824                      DAG.getIntPtrConstant(4, dl));
8825     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8826                      DAG.getIntPtrConstant(0, dl));
8827     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8828                      DAG.getIntPtrConstant(0, dl));
8829 
8830     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8831     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8832 
8833     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8834     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8835 
8836     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8837                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8838                                      MVT::i32),
8839                      N0);
8840     return N0;
8841   }
8842 
8843   // v4i16 sdiv ... Convert to float.
8844   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8845   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8846   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8847   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8848   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8849   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8850 
8851   // Use reciprocal estimate and two refinement steps.
8852   // float4 recip = vrecpeq_f32(yf);
8853   // recip *= vrecpsq_f32(yf, recip);
8854   // recip *= vrecpsq_f32(yf, recip);
8855   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8856                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8857                    BN1);
8858   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8859                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8860                    BN1, N2);
8861   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8862   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8863                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8864                    BN1, N2);
8865   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8866   // Simply multiplying by the reciprocal estimate can leave us a few ulps
8867   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8868   // and that it will never cause us to return an answer too large).
8869   // float4 result = as_float4(as_int4(xf*recip) + 2);
8870   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8871   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8872   N1 = DAG.getConstant(2, dl, MVT::v4i32);
8873   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8874   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8875   // Convert back to integer and return.
8876   // return vmovn_u32(vcvt_s32_f32(result));
8877   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8878   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8879   return N0;
8880 }
8881 
8882 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8883   SDNode *N = Op.getNode();
8884   EVT VT = N->getValueType(0);
8885   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8886 
8887   SDValue Carry = Op.getOperand(2);
8888 
8889   SDLoc DL(Op);
8890 
8891   SDValue Result;
8892   if (Op.getOpcode() == ISD::ADDCARRY) {
8893     // This converts the boolean value carry into the carry flag.
8894     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8895 
8896     // Do the addition proper using the carry flag we wanted.
8897     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8898                          Op.getOperand(1), Carry);
8899 
8900     // Now convert the carry flag into a boolean value.
8901     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8902   } else {
8903     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8904     // have to invert the carry first.
8905     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8906                         DAG.getConstant(1, DL, MVT::i32), Carry);
8907     // This converts the boolean value carry into the carry flag.
8908     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8909 
8910     // Do the subtraction proper using the carry flag we wanted.
8911     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8912                          Op.getOperand(1), Carry);
8913 
8914     // Now convert the carry flag into a boolean value.
8915     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8916     // But the carry returned by ARMISD::SUBE is not a borrow as expected
8917     // by ISD::SUBCARRY, so compute 1 - C.
8918     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8919                         DAG.getConstant(1, DL, MVT::i32), Carry);
8920   }
8921 
8922   // Return both values.
8923   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8924 }
8925 
8926 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8927   assert(Subtarget->isTargetDarwin());
8928 
8929   // For iOS, we want to call an alternative entry point: __sincos_stret,
8930   // return values are passed via sret.
8931   SDLoc dl(Op);
8932   SDValue Arg = Op.getOperand(0);
8933   EVT ArgVT = Arg.getValueType();
8934   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8935   auto PtrVT = getPointerTy(DAG.getDataLayout());
8936 
8937   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8938   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8939 
8940   // Pair of floats / doubles used to pass the result.
8941   Type *RetTy = StructType::get(ArgTy, ArgTy);
8942   auto &DL = DAG.getDataLayout();
8943 
8944   ArgListTy Args;
8945   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8946   SDValue SRet;
8947   if (ShouldUseSRet) {
8948     // Create stack object for sret.
8949     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8950     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8951     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8952     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8953 
8954     ArgListEntry Entry;
8955     Entry.Node = SRet;
8956     Entry.Ty = RetTy->getPointerTo();
8957     Entry.IsSExt = false;
8958     Entry.IsZExt = false;
8959     Entry.IsSRet = true;
8960     Args.push_back(Entry);
8961     RetTy = Type::getVoidTy(*DAG.getContext());
8962   }
8963 
8964   ArgListEntry Entry;
8965   Entry.Node = Arg;
8966   Entry.Ty = ArgTy;
8967   Entry.IsSExt = false;
8968   Entry.IsZExt = false;
8969   Args.push_back(Entry);
8970 
8971   RTLIB::Libcall LC =
8972       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8973   const char *LibcallName = getLibcallName(LC);
8974   CallingConv::ID CC = getLibcallCallingConv(LC);
8975   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8976 
8977   TargetLowering::CallLoweringInfo CLI(DAG);
8978   CLI.setDebugLoc(dl)
8979       .setChain(DAG.getEntryNode())
8980       .setCallee(CC, RetTy, Callee, std::move(Args))
8981       .setDiscardResult(ShouldUseSRet);
8982   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8983 
8984   if (!ShouldUseSRet)
8985     return CallResult.first;
8986 
8987   SDValue LoadSin =
8988       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8989 
8990   // Address of cos field.
8991   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8992                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8993   SDValue LoadCos =
8994       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8995 
8996   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8997   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8998                      LoadSin.getValue(0), LoadCos.getValue(0));
8999 }
9000 
9001 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9002                                                   bool Signed,
9003                                                   SDValue &Chain) const {
9004   EVT VT = Op.getValueType();
9005   assert((VT == MVT::i32 || VT == MVT::i64) &&
9006          "unexpected type for custom lowering DIV");
9007   SDLoc dl(Op);
9008 
9009   const auto &DL = DAG.getDataLayout();
9010   const auto &TLI = DAG.getTargetLoweringInfo();
9011 
9012   const char *Name = nullptr;
9013   if (Signed)
9014     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
9015   else
9016     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
9017 
9018   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
9019 
9020   ARMTargetLowering::ArgListTy Args;
9021 
9022   for (auto AI : {1, 0}) {
9023     ArgListEntry Arg;
9024     Arg.Node = Op.getOperand(AI);
9025     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
9026     Args.push_back(Arg);
9027   }
9028 
9029   CallLoweringInfo CLI(DAG);
9030   CLI.setDebugLoc(dl)
9031     .setChain(Chain)
9032     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
9033                ES, std::move(Args));
9034 
9035   return LowerCallTo(CLI).first;
9036 }
9037 
9038 // This is a code size optimisation: return the original SDIV node to
9039 // DAGCombiner when we don't want to expand SDIV into a sequence of
9040 // instructions, and an empty node otherwise which will cause the
9041 // SDIV to be expanded in DAGCombine.
9042 SDValue
9043 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9044                                  SelectionDAG &DAG,
9045                                  SmallVectorImpl<SDNode *> &Created) const {
9046   // TODO: Support SREM
9047   if (N->getOpcode() != ISD::SDIV)
9048     return SDValue();
9049 
9050   const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
9051   const bool MinSize = ST.hasMinSize();
9052   const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9053                                       : ST.hasDivideInARMMode();
9054 
9055   // Don't touch vector types; rewriting this may lead to scalarizing
9056   // the int divs.
9057   if (N->getOperand(0).getValueType().isVector())
9058     return SDValue();
9059 
9060   // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9061   // hwdiv support for this to be really profitable.
9062   if (!(MinSize && HasDivide))
9063     return SDValue();
9064 
9065   // ARM mode is a bit simpler than Thumb: we can handle large power
9066   // of 2 immediates with 1 mov instruction; no further checks required,
9067   // just return the sdiv node.
9068   if (!ST.isThumb())
9069     return SDValue(N, 0);
9070 
9071   // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9072   // and thus lose the code size benefits of a MOVS that requires only 2.
9073   // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9074   // but as it's doing exactly this, it's not worth the trouble to get TTI.
9075   if (Divisor.sgt(128))
9076     return SDValue();
9077 
9078   return SDValue(N, 0);
9079 }
9080 
9081 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9082                                             bool Signed) const {
9083   assert(Op.getValueType() == MVT::i32 &&
9084          "unexpected type for custom lowering DIV");
9085   SDLoc dl(Op);
9086 
9087   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9088                                DAG.getEntryNode(), Op.getOperand(1));
9089 
9090   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9091 }
9092 
9093 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9094   SDLoc DL(N);
9095   SDValue Op = N->getOperand(1);
9096   if (N->getValueType(0) == MVT::i32)
9097     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9098   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9099                            DAG.getConstant(0, DL, MVT::i32));
9100   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9101                            DAG.getConstant(1, DL, MVT::i32));
9102   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9103                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9104 }
9105 
9106 void ARMTargetLowering::ExpandDIV_Windows(
9107     SDValue Op, SelectionDAG &DAG, bool Signed,
9108     SmallVectorImpl<SDValue> &Results) const {
9109   const auto &DL = DAG.getDataLayout();
9110   const auto &TLI = DAG.getTargetLoweringInfo();
9111 
9112   assert(Op.getValueType() == MVT::i64 &&
9113          "unexpected type for custom lowering DIV");
9114   SDLoc dl(Op);
9115 
9116   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9117 
9118   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9119 
9120   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9121   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9122                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
9123   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9124 
9125   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9126 }
9127 
9128 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9129   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9130   EVT MemVT = LD->getMemoryVT();
9131   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9132          "Expected a predicate type!");
9133   assert(MemVT == Op.getValueType());
9134   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9135          "Expected a non-extending load");
9136   assert(LD->isUnindexed() && "Expected a unindexed load");
9137 
9138   // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
9139   // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9140   // need to make sure that 8/4 bits are actually loaded into the correct
9141   // place, which means loading the value and then shuffling the values into
9142   // the bottom bits of the predicate.
9143   // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9144   // for BE).
9145 
9146   SDLoc dl(Op);
9147   SDValue Load = DAG.getExtLoad(
9148       ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9149       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9150       LD->getMemOperand());
9151   SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load);
9152   if (MemVT != MVT::v16i1)
9153     Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9154                        DAG.getConstant(0, dl, MVT::i32));
9155   return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9156 }
9157 
9158 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9159                                   SelectionDAG &DAG) const {
9160   LoadSDNode *LD = cast<LoadSDNode>(N);
9161   EVT MemVT = LD->getMemoryVT();
9162   assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
9163 
9164   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9165       !Subtarget->isThumb1Only() && LD->isVolatile()) {
9166     SDLoc dl(N);
9167     SDValue Result = DAG.getMemIntrinsicNode(
9168         ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
9169         {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
9170     SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9171     SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9172     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
9173     Results.append({Pair, Result.getValue(2)});
9174   }
9175 }
9176 
9177 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
9178   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9179   EVT MemVT = ST->getMemoryVT();
9180   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9181          "Expected a predicate type!");
9182   assert(MemVT == ST->getValue().getValueType());
9183   assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9184   assert(ST->isUnindexed() && "Expected a unindexed store");
9185 
9186   // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
9187   // unset and a scalar store.
9188   SDLoc dl(Op);
9189   SDValue Build = ST->getValue();
9190   if (MemVT != MVT::v16i1) {
9191     SmallVector<SDValue, 16> Ops;
9192     for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++)
9193       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9194                                 DAG.getConstant(I, dl, MVT::i32)));
9195     for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9196       Ops.push_back(DAG.getUNDEF(MVT::i32));
9197     Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9198   }
9199   SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9200   return DAG.getTruncStore(
9201       ST->getChain(), dl, GRP, ST->getBasePtr(),
9202       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9203       ST->getMemOperand());
9204 }
9205 
9206 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG,
9207                           const ARMSubtarget *Subtarget) {
9208   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9209   EVT MemVT = ST->getMemoryVT();
9210   assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
9211 
9212   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9213       !Subtarget->isThumb1Only() && ST->isVolatile()) {
9214     SDNode *N = Op.getNode();
9215     SDLoc dl(N);
9216 
9217     SDValue Lo = DAG.getNode(
9218         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9219         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
9220                               MVT::i32));
9221     SDValue Hi = DAG.getNode(
9222         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9223         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
9224                               MVT::i32));
9225 
9226     return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
9227                                    {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9228                                    MemVT, ST->getMemOperand());
9229   } else if (Subtarget->hasMVEIntegerOps() &&
9230              ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9231                MemVT == MVT::v16i1))) {
9232     return LowerPredicateStore(Op, DAG);
9233   }
9234 
9235   return SDValue();
9236 }
9237 
9238 static bool isZeroVector(SDValue N) {
9239   return (ISD::isBuildVectorAllZeros(N.getNode()) ||
9240           (N->getOpcode() == ARMISD::VMOVIMM &&
9241            isNullConstant(N->getOperand(0))));
9242 }
9243 
9244 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
9245   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
9246   MVT VT = Op.getSimpleValueType();
9247   SDValue Mask = N->getMask();
9248   SDValue PassThru = N->getPassThru();
9249   SDLoc dl(Op);
9250 
9251   if (isZeroVector(PassThru))
9252     return Op;
9253 
9254   // MVE Masked loads use zero as the passthru value. Here we convert undef to
9255   // zero too, and other values are lowered to a select.
9256   SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
9257                                 DAG.getTargetConstant(0, dl, MVT::i32));
9258   SDValue NewLoad = DAG.getMaskedLoad(
9259       VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
9260       N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
9261       N->getExtensionType(), N->isExpandingLoad());
9262   SDValue Combo = NewLoad;
9263   bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9264                              PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9265                             isZeroVector(PassThru->getOperand(0));
9266   if (!PassThru.isUndef() && !PassThruIsCastZero)
9267     Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
9268   return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
9269 }
9270 
9271 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
9272   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
9273     // Acquire/Release load/store is not legal for targets without a dmb or
9274     // equivalent available.
9275     return SDValue();
9276 
9277   // Monotonic load/store is legal for all targets.
9278   return Op;
9279 }
9280 
9281 static void ReplaceREADCYCLECOUNTER(SDNode *N,
9282                                     SmallVectorImpl<SDValue> &Results,
9283                                     SelectionDAG &DAG,
9284                                     const ARMSubtarget *Subtarget) {
9285   SDLoc DL(N);
9286   // Under Power Management extensions, the cycle-count is:
9287   //    mrc p15, #0, <Rt>, c9, c13, #0
9288   SDValue Ops[] = { N->getOperand(0), // Chain
9289                     DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
9290                     DAG.getTargetConstant(15, DL, MVT::i32),
9291                     DAG.getTargetConstant(0, DL, MVT::i32),
9292                     DAG.getTargetConstant(9, DL, MVT::i32),
9293                     DAG.getTargetConstant(13, DL, MVT::i32),
9294                     DAG.getTargetConstant(0, DL, MVT::i32)
9295   };
9296 
9297   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
9298                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
9299   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
9300                                 DAG.getConstant(0, DL, MVT::i32)));
9301   Results.push_back(Cycles32.getValue(1));
9302 }
9303 
9304 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
9305   SDLoc dl(V.getNode());
9306   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
9307   SDValue VHi = DAG.getAnyExtOrTrunc(
9308       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
9309       dl, MVT::i32);
9310   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9311   if (isBigEndian)
9312     std::swap (VLo, VHi);
9313   SDValue RegClass =
9314       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
9315   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
9316   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
9317   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
9318   return SDValue(
9319       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
9320 }
9321 
9322 static void ReplaceCMP_SWAP_64Results(SDNode *N,
9323                                        SmallVectorImpl<SDValue> & Results,
9324                                        SelectionDAG &DAG) {
9325   assert(N->getValueType(0) == MVT::i64 &&
9326          "AtomicCmpSwap on types less than 64 should be legal");
9327   SDValue Ops[] = {N->getOperand(1),
9328                    createGPRPairNode(DAG, N->getOperand(2)),
9329                    createGPRPairNode(DAG, N->getOperand(3)),
9330                    N->getOperand(0)};
9331   SDNode *CmpSwap = DAG.getMachineNode(
9332       ARM::CMP_SWAP_64, SDLoc(N),
9333       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
9334 
9335   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
9336   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
9337 
9338   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9339 
9340   SDValue Lo =
9341       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
9342                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9343   SDValue Hi =
9344       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
9345                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9346   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
9347   Results.push_back(SDValue(CmpSwap, 2));
9348 }
9349 
9350 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
9351   SDLoc dl(Op);
9352   EVT VT = Op.getValueType();
9353   SDValue Chain = Op.getOperand(0);
9354   SDValue LHS = Op.getOperand(1);
9355   SDValue RHS = Op.getOperand(2);
9356   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
9357   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
9358 
9359   // If we don't have instructions of this float type then soften to a libcall
9360   // and use SETCC instead.
9361   if (isUnsupportedFloatingType(LHS.getValueType())) {
9362     DAG.getTargetLoweringInfo().softenSetCCOperands(
9363       DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling);
9364     if (!RHS.getNode()) {
9365       RHS = DAG.getConstant(0, dl, LHS.getValueType());
9366       CC = ISD::SETNE;
9367     }
9368     SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
9369                                  DAG.getCondCode(CC));
9370     return DAG.getMergeValues({Result, Chain}, dl);
9371   }
9372 
9373   ARMCC::CondCodes CondCode, CondCode2;
9374   FPCCToARMCC(CC, CondCode, CondCode2);
9375 
9376   // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit
9377   // in CMPFP and CMPFPE, but instead it should be made explicit by these
9378   // instructions using a chain instead of glue. This would also fix the problem
9379   // here (and also in LowerSELECT_CC) where we generate two comparisons when
9380   // CondCode2 != AL.
9381   SDValue True = DAG.getConstant(1, dl, VT);
9382   SDValue False =  DAG.getConstant(0, dl, VT);
9383   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
9384   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
9385   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9386   SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG);
9387   if (CondCode2 != ARMCC::AL) {
9388     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
9389     Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9390     Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG);
9391   }
9392   return DAG.getMergeValues({Result, Chain}, dl);
9393 }
9394 
9395 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9396   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
9397   switch (Op.getOpcode()) {
9398   default: llvm_unreachable("Don't know how to custom lower this!");
9399   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
9400   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9401   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
9402   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9403   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9404   case ISD::SELECT:        return LowerSELECT(Op, DAG);
9405   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
9406   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
9407   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
9408   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
9409   case ISD::VASTART:       return LowerVASTART(Op, DAG);
9410   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
9411   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
9412   case ISD::SINT_TO_FP:
9413   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
9414   case ISD::STRICT_FP_TO_SINT:
9415   case ISD::STRICT_FP_TO_UINT:
9416   case ISD::FP_TO_SINT:
9417   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
9418   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
9419   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
9420   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
9421   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
9422   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
9423   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
9424   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
9425   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
9426                                                                Subtarget);
9427   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
9428   case ISD::SHL:
9429   case ISD::SRL:
9430   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
9431   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
9432   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
9433   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
9434   case ISD::SRL_PARTS:
9435   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
9436   case ISD::CTTZ:
9437   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
9438   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
9439   case ISD::SETCC:         return LowerVSETCC(Op, DAG, Subtarget);
9440   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
9441   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
9442   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
9443   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
9444   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
9445   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9446   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
9447   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
9448   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
9449   case ISD::MUL:           return LowerMUL(Op, DAG);
9450   case ISD::SDIV:
9451     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9452       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
9453     return LowerSDIV(Op, DAG, Subtarget);
9454   case ISD::UDIV:
9455     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9456       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
9457     return LowerUDIV(Op, DAG, Subtarget);
9458   case ISD::ADDCARRY:
9459   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
9460   case ISD::SADDO:
9461   case ISD::SSUBO:
9462     return LowerSignedALUO(Op, DAG);
9463   case ISD::UADDO:
9464   case ISD::USUBO:
9465     return LowerUnsignedALUO(Op, DAG);
9466   case ISD::SADDSAT:
9467   case ISD::SSUBSAT:
9468     return LowerSADDSUBSAT(Op, DAG, Subtarget);
9469   case ISD::LOAD:
9470     return LowerPredicateLoad(Op, DAG);
9471   case ISD::STORE:
9472     return LowerSTORE(Op, DAG, Subtarget);
9473   case ISD::MLOAD:
9474     return LowerMLOAD(Op, DAG);
9475   case ISD::ATOMIC_LOAD:
9476   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
9477   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
9478   case ISD::SDIVREM:
9479   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
9480   case ISD::DYNAMIC_STACKALLOC:
9481     if (Subtarget->isTargetWindows())
9482       return LowerDYNAMIC_STACKALLOC(Op, DAG);
9483     llvm_unreachable("Don't know how to custom lower this!");
9484   case ISD::STRICT_FP_ROUND:
9485   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
9486   case ISD::STRICT_FP_EXTEND:
9487   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9488   case ISD::STRICT_FSETCC:
9489   case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
9490   case ARMISD::WIN__DBZCHK: return SDValue();
9491   }
9492 }
9493 
9494 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9495                                  SelectionDAG &DAG) {
9496   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9497   unsigned Opc = 0;
9498   if (IntNo == Intrinsic::arm_smlald)
9499     Opc = ARMISD::SMLALD;
9500   else if (IntNo == Intrinsic::arm_smlaldx)
9501     Opc = ARMISD::SMLALDX;
9502   else if (IntNo == Intrinsic::arm_smlsld)
9503     Opc = ARMISD::SMLSLD;
9504   else if (IntNo == Intrinsic::arm_smlsldx)
9505     Opc = ARMISD::SMLSLDX;
9506   else
9507     return;
9508 
9509   SDLoc dl(N);
9510   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9511                            N->getOperand(3),
9512                            DAG.getConstant(0, dl, MVT::i32));
9513   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9514                            N->getOperand(3),
9515                            DAG.getConstant(1, dl, MVT::i32));
9516 
9517   SDValue LongMul = DAG.getNode(Opc, dl,
9518                                 DAG.getVTList(MVT::i32, MVT::i32),
9519                                 N->getOperand(1), N->getOperand(2),
9520                                 Lo, Hi);
9521   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
9522                                 LongMul.getValue(0), LongMul.getValue(1)));
9523 }
9524 
9525 /// ReplaceNodeResults - Replace the results of node with an illegal result
9526 /// type with new values built out of custom code.
9527 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9528                                            SmallVectorImpl<SDValue> &Results,
9529                                            SelectionDAG &DAG) const {
9530   SDValue Res;
9531   switch (N->getOpcode()) {
9532   default:
9533     llvm_unreachable("Don't know how to custom expand this!");
9534   case ISD::READ_REGISTER:
9535     ExpandREAD_REGISTER(N, Results, DAG);
9536     break;
9537   case ISD::BITCAST:
9538     Res = ExpandBITCAST(N, DAG, Subtarget);
9539     break;
9540   case ISD::SRL:
9541   case ISD::SRA:
9542   case ISD::SHL:
9543     Res = Expand64BitShift(N, DAG, Subtarget);
9544     break;
9545   case ISD::SREM:
9546   case ISD::UREM:
9547     Res = LowerREM(N, DAG);
9548     break;
9549   case ISD::SDIVREM:
9550   case ISD::UDIVREM:
9551     Res = LowerDivRem(SDValue(N, 0), DAG);
9552     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9553     Results.push_back(Res.getValue(0));
9554     Results.push_back(Res.getValue(1));
9555     return;
9556   case ISD::SADDSAT:
9557   case ISD::SSUBSAT:
9558     Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
9559     break;
9560   case ISD::READCYCLECOUNTER:
9561     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9562     return;
9563   case ISD::UDIV:
9564   case ISD::SDIV:
9565     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9566     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9567                              Results);
9568   case ISD::ATOMIC_CMP_SWAP:
9569     ReplaceCMP_SWAP_64Results(N, Results, DAG);
9570     return;
9571   case ISD::INTRINSIC_WO_CHAIN:
9572     return ReplaceLongIntrinsic(N, Results, DAG);
9573   case ISD::ABS:
9574      lowerABS(N, Results, DAG);
9575      return ;
9576   case ISD::LOAD:
9577     LowerLOAD(N, Results, DAG);
9578     break;
9579   }
9580   if (Res.getNode())
9581     Results.push_back(Res);
9582 }
9583 
9584 //===----------------------------------------------------------------------===//
9585 //                           ARM Scheduler Hooks
9586 //===----------------------------------------------------------------------===//
9587 
9588 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9589 /// registers the function context.
9590 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9591                                                MachineBasicBlock *MBB,
9592                                                MachineBasicBlock *DispatchBB,
9593                                                int FI) const {
9594   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9595          "ROPI/RWPI not currently supported with SjLj");
9596   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9597   DebugLoc dl = MI.getDebugLoc();
9598   MachineFunction *MF = MBB->getParent();
9599   MachineRegisterInfo *MRI = &MF->getRegInfo();
9600   MachineConstantPool *MCP = MF->getConstantPool();
9601   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9602   const Function &F = MF->getFunction();
9603 
9604   bool isThumb = Subtarget->isThumb();
9605   bool isThumb2 = Subtarget->isThumb2();
9606 
9607   unsigned PCLabelId = AFI->createPICLabelUId();
9608   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9609   ARMConstantPoolValue *CPV =
9610     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9611   unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
9612 
9613   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9614                                            : &ARM::GPRRegClass;
9615 
9616   // Grab constant pool and fixed stack memory operands.
9617   MachineMemOperand *CPMMO =
9618       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9619                                MachineMemOperand::MOLoad, 4, Align(4));
9620 
9621   MachineMemOperand *FIMMOSt =
9622       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9623                                MachineMemOperand::MOStore, 4, Align(4));
9624 
9625   // Load the address of the dispatch MBB into the jump buffer.
9626   if (isThumb2) {
9627     // Incoming value: jbuf
9628     //   ldr.n  r5, LCPI1_1
9629     //   orr    r5, r5, #1
9630     //   add    r5, pc
9631     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
9632     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9633     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9634         .addConstantPoolIndex(CPI)
9635         .addMemOperand(CPMMO)
9636         .add(predOps(ARMCC::AL));
9637     // Set the low bit because of thumb mode.
9638     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9639     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9640         .addReg(NewVReg1, RegState::Kill)
9641         .addImm(0x01)
9642         .add(predOps(ARMCC::AL))
9643         .add(condCodeOp());
9644     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9645     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9646       .addReg(NewVReg2, RegState::Kill)
9647       .addImm(PCLabelId);
9648     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9649         .addReg(NewVReg3, RegState::Kill)
9650         .addFrameIndex(FI)
9651         .addImm(36) // &jbuf[1] :: pc
9652         .addMemOperand(FIMMOSt)
9653         .add(predOps(ARMCC::AL));
9654   } else if (isThumb) {
9655     // Incoming value: jbuf
9656     //   ldr.n  r1, LCPI1_4
9657     //   add    r1, pc
9658     //   mov    r2, #1
9659     //   orrs   r1, r2
9660     //   add    r2, $jbuf, #+4 ; &jbuf[1]
9661     //   str    r1, [r2]
9662     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9663     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9664         .addConstantPoolIndex(CPI)
9665         .addMemOperand(CPMMO)
9666         .add(predOps(ARMCC::AL));
9667     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9668     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9669       .addReg(NewVReg1, RegState::Kill)
9670       .addImm(PCLabelId);
9671     // Set the low bit because of thumb mode.
9672     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9673     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9674         .addReg(ARM::CPSR, RegState::Define)
9675         .addImm(1)
9676         .add(predOps(ARMCC::AL));
9677     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9678     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9679         .addReg(ARM::CPSR, RegState::Define)
9680         .addReg(NewVReg2, RegState::Kill)
9681         .addReg(NewVReg3, RegState::Kill)
9682         .add(predOps(ARMCC::AL));
9683     Register NewVReg5 = MRI->createVirtualRegister(TRC);
9684     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9685             .addFrameIndex(FI)
9686             .addImm(36); // &jbuf[1] :: pc
9687     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9688         .addReg(NewVReg4, RegState::Kill)
9689         .addReg(NewVReg5, RegState::Kill)
9690         .addImm(0)
9691         .addMemOperand(FIMMOSt)
9692         .add(predOps(ARMCC::AL));
9693   } else {
9694     // Incoming value: jbuf
9695     //   ldr  r1, LCPI1_1
9696     //   add  r1, pc, r1
9697     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
9698     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9699     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9700         .addConstantPoolIndex(CPI)
9701         .addImm(0)
9702         .addMemOperand(CPMMO)
9703         .add(predOps(ARMCC::AL));
9704     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9705     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9706         .addReg(NewVReg1, RegState::Kill)
9707         .addImm(PCLabelId)
9708         .add(predOps(ARMCC::AL));
9709     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9710         .addReg(NewVReg2, RegState::Kill)
9711         .addFrameIndex(FI)
9712         .addImm(36) // &jbuf[1] :: pc
9713         .addMemOperand(FIMMOSt)
9714         .add(predOps(ARMCC::AL));
9715   }
9716 }
9717 
9718 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9719                                               MachineBasicBlock *MBB) const {
9720   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9721   DebugLoc dl = MI.getDebugLoc();
9722   MachineFunction *MF = MBB->getParent();
9723   MachineRegisterInfo *MRI = &MF->getRegInfo();
9724   MachineFrameInfo &MFI = MF->getFrameInfo();
9725   int FI = MFI.getFunctionContextIndex();
9726 
9727   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9728                                                         : &ARM::GPRnopcRegClass;
9729 
9730   // Get a mapping of the call site numbers to all of the landing pads they're
9731   // associated with.
9732   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9733   unsigned MaxCSNum = 0;
9734   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9735        ++BB) {
9736     if (!BB->isEHPad()) continue;
9737 
9738     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9739     // pad.
9740     for (MachineBasicBlock::iterator
9741            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9742       if (!II->isEHLabel()) continue;
9743 
9744       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9745       if (!MF->hasCallSiteLandingPad(Sym)) continue;
9746 
9747       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9748       for (SmallVectorImpl<unsigned>::iterator
9749              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9750            CSI != CSE; ++CSI) {
9751         CallSiteNumToLPad[*CSI].push_back(&*BB);
9752         MaxCSNum = std::max(MaxCSNum, *CSI);
9753       }
9754       break;
9755     }
9756   }
9757 
9758   // Get an ordered list of the machine basic blocks for the jump table.
9759   std::vector<MachineBasicBlock*> LPadList;
9760   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9761   LPadList.reserve(CallSiteNumToLPad.size());
9762   for (unsigned I = 1; I <= MaxCSNum; ++I) {
9763     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9764     for (SmallVectorImpl<MachineBasicBlock*>::iterator
9765            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9766       LPadList.push_back(*II);
9767       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9768     }
9769   }
9770 
9771   assert(!LPadList.empty() &&
9772          "No landing pad destinations for the dispatch jump table!");
9773 
9774   // Create the jump table and associated information.
9775   MachineJumpTableInfo *JTI =
9776     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9777   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9778 
9779   // Create the MBBs for the dispatch code.
9780 
9781   // Shove the dispatch's address into the return slot in the function context.
9782   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9783   DispatchBB->setIsEHPad();
9784 
9785   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9786   unsigned trap_opcode;
9787   if (Subtarget->isThumb())
9788     trap_opcode = ARM::tTRAP;
9789   else
9790     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9791 
9792   BuildMI(TrapBB, dl, TII->get(trap_opcode));
9793   DispatchBB->addSuccessor(TrapBB);
9794 
9795   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9796   DispatchBB->addSuccessor(DispContBB);
9797 
9798   // Insert and MBBs.
9799   MF->insert(MF->end(), DispatchBB);
9800   MF->insert(MF->end(), DispContBB);
9801   MF->insert(MF->end(), TrapBB);
9802 
9803   // Insert code into the entry block that creates and registers the function
9804   // context.
9805   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9806 
9807   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9808       MachinePointerInfo::getFixedStack(*MF, FI),
9809       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4));
9810 
9811   MachineInstrBuilder MIB;
9812   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9813 
9814   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9815   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9816 
9817   // Add a register mask with no preserved registers.  This results in all
9818   // registers being marked as clobbered. This can't work if the dispatch block
9819   // is in a Thumb1 function and is linked with ARM code which uses the FP
9820   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9821   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9822 
9823   bool IsPositionIndependent = isPositionIndependent();
9824   unsigned NumLPads = LPadList.size();
9825   if (Subtarget->isThumb2()) {
9826     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9827     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9828         .addFrameIndex(FI)
9829         .addImm(4)
9830         .addMemOperand(FIMMOLd)
9831         .add(predOps(ARMCC::AL));
9832 
9833     if (NumLPads < 256) {
9834       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9835           .addReg(NewVReg1)
9836           .addImm(LPadList.size())
9837           .add(predOps(ARMCC::AL));
9838     } else {
9839       Register VReg1 = MRI->createVirtualRegister(TRC);
9840       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9841           .addImm(NumLPads & 0xFFFF)
9842           .add(predOps(ARMCC::AL));
9843 
9844       unsigned VReg2 = VReg1;
9845       if ((NumLPads & 0xFFFF0000) != 0) {
9846         VReg2 = MRI->createVirtualRegister(TRC);
9847         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9848             .addReg(VReg1)
9849             .addImm(NumLPads >> 16)
9850             .add(predOps(ARMCC::AL));
9851       }
9852 
9853       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9854           .addReg(NewVReg1)
9855           .addReg(VReg2)
9856           .add(predOps(ARMCC::AL));
9857     }
9858 
9859     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9860       .addMBB(TrapBB)
9861       .addImm(ARMCC::HI)
9862       .addReg(ARM::CPSR);
9863 
9864     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9865     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9866         .addJumpTableIndex(MJTI)
9867         .add(predOps(ARMCC::AL));
9868 
9869     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9870     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9871         .addReg(NewVReg3, RegState::Kill)
9872         .addReg(NewVReg1)
9873         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9874         .add(predOps(ARMCC::AL))
9875         .add(condCodeOp());
9876 
9877     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9878       .addReg(NewVReg4, RegState::Kill)
9879       .addReg(NewVReg1)
9880       .addJumpTableIndex(MJTI);
9881   } else if (Subtarget->isThumb()) {
9882     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9883     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9884         .addFrameIndex(FI)
9885         .addImm(1)
9886         .addMemOperand(FIMMOLd)
9887         .add(predOps(ARMCC::AL));
9888 
9889     if (NumLPads < 256) {
9890       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9891           .addReg(NewVReg1)
9892           .addImm(NumLPads)
9893           .add(predOps(ARMCC::AL));
9894     } else {
9895       MachineConstantPool *ConstantPool = MF->getConstantPool();
9896       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9897       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9898 
9899       // MachineConstantPool wants an explicit alignment.
9900       Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
9901       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
9902 
9903       Register VReg1 = MRI->createVirtualRegister(TRC);
9904       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9905           .addReg(VReg1, RegState::Define)
9906           .addConstantPoolIndex(Idx)
9907           .add(predOps(ARMCC::AL));
9908       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9909           .addReg(NewVReg1)
9910           .addReg(VReg1)
9911           .add(predOps(ARMCC::AL));
9912     }
9913 
9914     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9915       .addMBB(TrapBB)
9916       .addImm(ARMCC::HI)
9917       .addReg(ARM::CPSR);
9918 
9919     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9920     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9921         .addReg(ARM::CPSR, RegState::Define)
9922         .addReg(NewVReg1)
9923         .addImm(2)
9924         .add(predOps(ARMCC::AL));
9925 
9926     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9927     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9928         .addJumpTableIndex(MJTI)
9929         .add(predOps(ARMCC::AL));
9930 
9931     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9932     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9933         .addReg(ARM::CPSR, RegState::Define)
9934         .addReg(NewVReg2, RegState::Kill)
9935         .addReg(NewVReg3)
9936         .add(predOps(ARMCC::AL));
9937 
9938     MachineMemOperand *JTMMOLd =
9939         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
9940                                  MachineMemOperand::MOLoad, 4, Align(4));
9941 
9942     Register NewVReg5 = MRI->createVirtualRegister(TRC);
9943     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9944         .addReg(NewVReg4, RegState::Kill)
9945         .addImm(0)
9946         .addMemOperand(JTMMOLd)
9947         .add(predOps(ARMCC::AL));
9948 
9949     unsigned NewVReg6 = NewVReg5;
9950     if (IsPositionIndependent) {
9951       NewVReg6 = MRI->createVirtualRegister(TRC);
9952       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9953           .addReg(ARM::CPSR, RegState::Define)
9954           .addReg(NewVReg5, RegState::Kill)
9955           .addReg(NewVReg3)
9956           .add(predOps(ARMCC::AL));
9957     }
9958 
9959     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9960       .addReg(NewVReg6, RegState::Kill)
9961       .addJumpTableIndex(MJTI);
9962   } else {
9963     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9964     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9965         .addFrameIndex(FI)
9966         .addImm(4)
9967         .addMemOperand(FIMMOLd)
9968         .add(predOps(ARMCC::AL));
9969 
9970     if (NumLPads < 256) {
9971       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9972           .addReg(NewVReg1)
9973           .addImm(NumLPads)
9974           .add(predOps(ARMCC::AL));
9975     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9976       Register VReg1 = MRI->createVirtualRegister(TRC);
9977       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9978           .addImm(NumLPads & 0xFFFF)
9979           .add(predOps(ARMCC::AL));
9980 
9981       unsigned VReg2 = VReg1;
9982       if ((NumLPads & 0xFFFF0000) != 0) {
9983         VReg2 = MRI->createVirtualRegister(TRC);
9984         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9985             .addReg(VReg1)
9986             .addImm(NumLPads >> 16)
9987             .add(predOps(ARMCC::AL));
9988       }
9989 
9990       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9991           .addReg(NewVReg1)
9992           .addReg(VReg2)
9993           .add(predOps(ARMCC::AL));
9994     } else {
9995       MachineConstantPool *ConstantPool = MF->getConstantPool();
9996       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9997       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9998 
9999       // MachineConstantPool wants an explicit alignment.
10000       Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10001       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10002 
10003       Register VReg1 = MRI->createVirtualRegister(TRC);
10004       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
10005           .addReg(VReg1, RegState::Define)
10006           .addConstantPoolIndex(Idx)
10007           .addImm(0)
10008           .add(predOps(ARMCC::AL));
10009       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10010           .addReg(NewVReg1)
10011           .addReg(VReg1, RegState::Kill)
10012           .add(predOps(ARMCC::AL));
10013     }
10014 
10015     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
10016       .addMBB(TrapBB)
10017       .addImm(ARMCC::HI)
10018       .addReg(ARM::CPSR);
10019 
10020     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10021     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
10022         .addReg(NewVReg1)
10023         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10024         .add(predOps(ARMCC::AL))
10025         .add(condCodeOp());
10026     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10027     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
10028         .addJumpTableIndex(MJTI)
10029         .add(predOps(ARMCC::AL));
10030 
10031     MachineMemOperand *JTMMOLd =
10032         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10033                                  MachineMemOperand::MOLoad, 4, Align(4));
10034     Register NewVReg5 = MRI->createVirtualRegister(TRC);
10035     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
10036         .addReg(NewVReg3, RegState::Kill)
10037         .addReg(NewVReg4)
10038         .addImm(0)
10039         .addMemOperand(JTMMOLd)
10040         .add(predOps(ARMCC::AL));
10041 
10042     if (IsPositionIndependent) {
10043       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
10044         .addReg(NewVReg5, RegState::Kill)
10045         .addReg(NewVReg4)
10046         .addJumpTableIndex(MJTI);
10047     } else {
10048       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
10049         .addReg(NewVReg5, RegState::Kill)
10050         .addJumpTableIndex(MJTI);
10051     }
10052   }
10053 
10054   // Add the jump table entries as successors to the MBB.
10055   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
10056   for (std::vector<MachineBasicBlock*>::iterator
10057          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
10058     MachineBasicBlock *CurMBB = *I;
10059     if (SeenMBBs.insert(CurMBB).second)
10060       DispContBB->addSuccessor(CurMBB);
10061   }
10062 
10063   // N.B. the order the invoke BBs are processed in doesn't matter here.
10064   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
10065   SmallVector<MachineBasicBlock*, 64> MBBLPads;
10066   for (MachineBasicBlock *BB : InvokeBBs) {
10067 
10068     // Remove the landing pad successor from the invoke block and replace it
10069     // with the new dispatch block.
10070     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
10071                                                   BB->succ_end());
10072     while (!Successors.empty()) {
10073       MachineBasicBlock *SMBB = Successors.pop_back_val();
10074       if (SMBB->isEHPad()) {
10075         BB->removeSuccessor(SMBB);
10076         MBBLPads.push_back(SMBB);
10077       }
10078     }
10079 
10080     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
10081     BB->normalizeSuccProbs();
10082 
10083     // Find the invoke call and mark all of the callee-saved registers as
10084     // 'implicit defined' so that they're spilled. This prevents code from
10085     // moving instructions to before the EH block, where they will never be
10086     // executed.
10087     for (MachineBasicBlock::reverse_iterator
10088            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
10089       if (!II->isCall()) continue;
10090 
10091       DenseMap<unsigned, bool> DefRegs;
10092       for (MachineInstr::mop_iterator
10093              OI = II->operands_begin(), OE = II->operands_end();
10094            OI != OE; ++OI) {
10095         if (!OI->isReg()) continue;
10096         DefRegs[OI->getReg()] = true;
10097       }
10098 
10099       MachineInstrBuilder MIB(*MF, &*II);
10100 
10101       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
10102         unsigned Reg = SavedRegs[i];
10103         if (Subtarget->isThumb2() &&
10104             !ARM::tGPRRegClass.contains(Reg) &&
10105             !ARM::hGPRRegClass.contains(Reg))
10106           continue;
10107         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
10108           continue;
10109         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
10110           continue;
10111         if (!DefRegs[Reg])
10112           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
10113       }
10114 
10115       break;
10116     }
10117   }
10118 
10119   // Mark all former landing pads as non-landing pads. The dispatch is the only
10120   // landing pad now.
10121   for (SmallVectorImpl<MachineBasicBlock*>::iterator
10122          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
10123     (*I)->setIsEHPad(false);
10124 
10125   // The instruction is gone now.
10126   MI.eraseFromParent();
10127 }
10128 
10129 static
10130 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
10131   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
10132        E = MBB->succ_end(); I != E; ++I)
10133     if (*I != Succ)
10134       return *I;
10135   llvm_unreachable("Expecting a BB with two successors!");
10136 }
10137 
10138 /// Return the load opcode for a given load size. If load size >= 8,
10139 /// neon opcode will be returned.
10140 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
10141   if (LdSize >= 8)
10142     return LdSize == 16 ? ARM::VLD1q32wb_fixed
10143                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
10144   if (IsThumb1)
10145     return LdSize == 4 ? ARM::tLDRi
10146                        : LdSize == 2 ? ARM::tLDRHi
10147                                      : LdSize == 1 ? ARM::tLDRBi : 0;
10148   if (IsThumb2)
10149     return LdSize == 4 ? ARM::t2LDR_POST
10150                        : LdSize == 2 ? ARM::t2LDRH_POST
10151                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
10152   return LdSize == 4 ? ARM::LDR_POST_IMM
10153                      : LdSize == 2 ? ARM::LDRH_POST
10154                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
10155 }
10156 
10157 /// Return the store opcode for a given store size. If store size >= 8,
10158 /// neon opcode will be returned.
10159 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
10160   if (StSize >= 8)
10161     return StSize == 16 ? ARM::VST1q32wb_fixed
10162                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
10163   if (IsThumb1)
10164     return StSize == 4 ? ARM::tSTRi
10165                        : StSize == 2 ? ARM::tSTRHi
10166                                      : StSize == 1 ? ARM::tSTRBi : 0;
10167   if (IsThumb2)
10168     return StSize == 4 ? ARM::t2STR_POST
10169                        : StSize == 2 ? ARM::t2STRH_POST
10170                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
10171   return StSize == 4 ? ARM::STR_POST_IMM
10172                      : StSize == 2 ? ARM::STRH_POST
10173                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
10174 }
10175 
10176 /// Emit a post-increment load operation with given size. The instructions
10177 /// will be added to BB at Pos.
10178 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10179                        const TargetInstrInfo *TII, const DebugLoc &dl,
10180                        unsigned LdSize, unsigned Data, unsigned AddrIn,
10181                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10182   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
10183   assert(LdOpc != 0 && "Should have a load opcode");
10184   if (LdSize >= 8) {
10185     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10186         .addReg(AddrOut, RegState::Define)
10187         .addReg(AddrIn)
10188         .addImm(0)
10189         .add(predOps(ARMCC::AL));
10190   } else if (IsThumb1) {
10191     // load + update AddrIn
10192     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10193         .addReg(AddrIn)
10194         .addImm(0)
10195         .add(predOps(ARMCC::AL));
10196     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10197         .add(t1CondCodeOp())
10198         .addReg(AddrIn)
10199         .addImm(LdSize)
10200         .add(predOps(ARMCC::AL));
10201   } else if (IsThumb2) {
10202     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10203         .addReg(AddrOut, RegState::Define)
10204         .addReg(AddrIn)
10205         .addImm(LdSize)
10206         .add(predOps(ARMCC::AL));
10207   } else { // arm
10208     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10209         .addReg(AddrOut, RegState::Define)
10210         .addReg(AddrIn)
10211         .addReg(0)
10212         .addImm(LdSize)
10213         .add(predOps(ARMCC::AL));
10214   }
10215 }
10216 
10217 /// Emit a post-increment store operation with given size. The instructions
10218 /// will be added to BB at Pos.
10219 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10220                        const TargetInstrInfo *TII, const DebugLoc &dl,
10221                        unsigned StSize, unsigned Data, unsigned AddrIn,
10222                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10223   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
10224   assert(StOpc != 0 && "Should have a store opcode");
10225   if (StSize >= 8) {
10226     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10227         .addReg(AddrIn)
10228         .addImm(0)
10229         .addReg(Data)
10230         .add(predOps(ARMCC::AL));
10231   } else if (IsThumb1) {
10232     // store + update AddrIn
10233     BuildMI(*BB, Pos, dl, TII->get(StOpc))
10234         .addReg(Data)
10235         .addReg(AddrIn)
10236         .addImm(0)
10237         .add(predOps(ARMCC::AL));
10238     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10239         .add(t1CondCodeOp())
10240         .addReg(AddrIn)
10241         .addImm(StSize)
10242         .add(predOps(ARMCC::AL));
10243   } else if (IsThumb2) {
10244     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10245         .addReg(Data)
10246         .addReg(AddrIn)
10247         .addImm(StSize)
10248         .add(predOps(ARMCC::AL));
10249   } else { // arm
10250     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10251         .addReg(Data)
10252         .addReg(AddrIn)
10253         .addReg(0)
10254         .addImm(StSize)
10255         .add(predOps(ARMCC::AL));
10256   }
10257 }
10258 
10259 MachineBasicBlock *
10260 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
10261                                    MachineBasicBlock *BB) const {
10262   // This pseudo instruction has 3 operands: dst, src, size
10263   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
10264   // Otherwise, we will generate unrolled scalar copies.
10265   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10266   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10267   MachineFunction::iterator It = ++BB->getIterator();
10268 
10269   Register dest = MI.getOperand(0).getReg();
10270   Register src = MI.getOperand(1).getReg();
10271   unsigned SizeVal = MI.getOperand(2).getImm();
10272   unsigned Alignment = MI.getOperand(3).getImm();
10273   DebugLoc dl = MI.getDebugLoc();
10274 
10275   MachineFunction *MF = BB->getParent();
10276   MachineRegisterInfo &MRI = MF->getRegInfo();
10277   unsigned UnitSize = 0;
10278   const TargetRegisterClass *TRC = nullptr;
10279   const TargetRegisterClass *VecTRC = nullptr;
10280 
10281   bool IsThumb1 = Subtarget->isThumb1Only();
10282   bool IsThumb2 = Subtarget->isThumb2();
10283   bool IsThumb = Subtarget->isThumb();
10284 
10285   if (Alignment & 1) {
10286     UnitSize = 1;
10287   } else if (Alignment & 2) {
10288     UnitSize = 2;
10289   } else {
10290     // Check whether we can use NEON instructions.
10291     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
10292         Subtarget->hasNEON()) {
10293       if ((Alignment % 16 == 0) && SizeVal >= 16)
10294         UnitSize = 16;
10295       else if ((Alignment % 8 == 0) && SizeVal >= 8)
10296         UnitSize = 8;
10297     }
10298     // Can't use NEON instructions.
10299     if (UnitSize == 0)
10300       UnitSize = 4;
10301   }
10302 
10303   // Select the correct opcode and register class for unit size load/store
10304   bool IsNeon = UnitSize >= 8;
10305   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
10306   if (IsNeon)
10307     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
10308                             : UnitSize == 8 ? &ARM::DPRRegClass
10309                                             : nullptr;
10310 
10311   unsigned BytesLeft = SizeVal % UnitSize;
10312   unsigned LoopSize = SizeVal - BytesLeft;
10313 
10314   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
10315     // Use LDR and STR to copy.
10316     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
10317     // [destOut] = STR_POST(scratch, destIn, UnitSize)
10318     unsigned srcIn = src;
10319     unsigned destIn = dest;
10320     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
10321       Register srcOut = MRI.createVirtualRegister(TRC);
10322       Register destOut = MRI.createVirtualRegister(TRC);
10323       Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10324       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
10325                  IsThumb1, IsThumb2);
10326       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
10327                  IsThumb1, IsThumb2);
10328       srcIn = srcOut;
10329       destIn = destOut;
10330     }
10331 
10332     // Handle the leftover bytes with LDRB and STRB.
10333     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
10334     // [destOut] = STRB_POST(scratch, destIn, 1)
10335     for (unsigned i = 0; i < BytesLeft; i++) {
10336       Register srcOut = MRI.createVirtualRegister(TRC);
10337       Register destOut = MRI.createVirtualRegister(TRC);
10338       Register scratch = MRI.createVirtualRegister(TRC);
10339       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
10340                  IsThumb1, IsThumb2);
10341       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
10342                  IsThumb1, IsThumb2);
10343       srcIn = srcOut;
10344       destIn = destOut;
10345     }
10346     MI.eraseFromParent(); // The instruction is gone now.
10347     return BB;
10348   }
10349 
10350   // Expand the pseudo op to a loop.
10351   // thisMBB:
10352   //   ...
10353   //   movw varEnd, # --> with thumb2
10354   //   movt varEnd, #
10355   //   ldrcp varEnd, idx --> without thumb2
10356   //   fallthrough --> loopMBB
10357   // loopMBB:
10358   //   PHI varPhi, varEnd, varLoop
10359   //   PHI srcPhi, src, srcLoop
10360   //   PHI destPhi, dst, destLoop
10361   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10362   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
10363   //   subs varLoop, varPhi, #UnitSize
10364   //   bne loopMBB
10365   //   fallthrough --> exitMBB
10366   // exitMBB:
10367   //   epilogue to handle left-over bytes
10368   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10369   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10370   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10371   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10372   MF->insert(It, loopMBB);
10373   MF->insert(It, exitMBB);
10374 
10375   // Transfer the remainder of BB and its successor edges to exitMBB.
10376   exitMBB->splice(exitMBB->begin(), BB,
10377                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10378   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10379 
10380   // Load an immediate to varEnd.
10381   Register varEnd = MRI.createVirtualRegister(TRC);
10382   if (Subtarget->useMovt()) {
10383     unsigned Vtmp = varEnd;
10384     if ((LoopSize & 0xFFFF0000) != 0)
10385       Vtmp = MRI.createVirtualRegister(TRC);
10386     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
10387         .addImm(LoopSize & 0xFFFF)
10388         .add(predOps(ARMCC::AL));
10389 
10390     if ((LoopSize & 0xFFFF0000) != 0)
10391       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
10392           .addReg(Vtmp)
10393           .addImm(LoopSize >> 16)
10394           .add(predOps(ARMCC::AL));
10395   } else {
10396     MachineConstantPool *ConstantPool = MF->getConstantPool();
10397     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10398     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
10399 
10400     // MachineConstantPool wants an explicit alignment.
10401     Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10402     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10403     MachineMemOperand *CPMMO =
10404         MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10405                                  MachineMemOperand::MOLoad, 4, Align(4));
10406 
10407     if (IsThumb)
10408       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
10409           .addReg(varEnd, RegState::Define)
10410           .addConstantPoolIndex(Idx)
10411           .add(predOps(ARMCC::AL))
10412           .addMemOperand(CPMMO);
10413     else
10414       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
10415           .addReg(varEnd, RegState::Define)
10416           .addConstantPoolIndex(Idx)
10417           .addImm(0)
10418           .add(predOps(ARMCC::AL))
10419           .addMemOperand(CPMMO);
10420   }
10421   BB->addSuccessor(loopMBB);
10422 
10423   // Generate the loop body:
10424   //   varPhi = PHI(varLoop, varEnd)
10425   //   srcPhi = PHI(srcLoop, src)
10426   //   destPhi = PHI(destLoop, dst)
10427   MachineBasicBlock *entryBB = BB;
10428   BB = loopMBB;
10429   Register varLoop = MRI.createVirtualRegister(TRC);
10430   Register varPhi = MRI.createVirtualRegister(TRC);
10431   Register srcLoop = MRI.createVirtualRegister(TRC);
10432   Register srcPhi = MRI.createVirtualRegister(TRC);
10433   Register destLoop = MRI.createVirtualRegister(TRC);
10434   Register destPhi = MRI.createVirtualRegister(TRC);
10435 
10436   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
10437     .addReg(varLoop).addMBB(loopMBB)
10438     .addReg(varEnd).addMBB(entryBB);
10439   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
10440     .addReg(srcLoop).addMBB(loopMBB)
10441     .addReg(src).addMBB(entryBB);
10442   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
10443     .addReg(destLoop).addMBB(loopMBB)
10444     .addReg(dest).addMBB(entryBB);
10445 
10446   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10447   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
10448   Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10449   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
10450              IsThumb1, IsThumb2);
10451   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
10452              IsThumb1, IsThumb2);
10453 
10454   // Decrement loop variable by UnitSize.
10455   if (IsThumb1) {
10456     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
10457         .add(t1CondCodeOp())
10458         .addReg(varPhi)
10459         .addImm(UnitSize)
10460         .add(predOps(ARMCC::AL));
10461   } else {
10462     MachineInstrBuilder MIB =
10463         BuildMI(*BB, BB->end(), dl,
10464                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
10465     MIB.addReg(varPhi)
10466         .addImm(UnitSize)
10467         .add(predOps(ARMCC::AL))
10468         .add(condCodeOp());
10469     MIB->getOperand(5).setReg(ARM::CPSR);
10470     MIB->getOperand(5).setIsDef(true);
10471   }
10472   BuildMI(*BB, BB->end(), dl,
10473           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
10474       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
10475 
10476   // loopMBB can loop back to loopMBB or fall through to exitMBB.
10477   BB->addSuccessor(loopMBB);
10478   BB->addSuccessor(exitMBB);
10479 
10480   // Add epilogue to handle BytesLeft.
10481   BB = exitMBB;
10482   auto StartOfExit = exitMBB->begin();
10483 
10484   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10485   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10486   unsigned srcIn = srcLoop;
10487   unsigned destIn = destLoop;
10488   for (unsigned i = 0; i < BytesLeft; i++) {
10489     Register srcOut = MRI.createVirtualRegister(TRC);
10490     Register destOut = MRI.createVirtualRegister(TRC);
10491     Register scratch = MRI.createVirtualRegister(TRC);
10492     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
10493                IsThumb1, IsThumb2);
10494     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10495                IsThumb1, IsThumb2);
10496     srcIn = srcOut;
10497     destIn = destOut;
10498   }
10499 
10500   MI.eraseFromParent(); // The instruction is gone now.
10501   return BB;
10502 }
10503 
10504 MachineBasicBlock *
10505 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10506                                        MachineBasicBlock *MBB) const {
10507   const TargetMachine &TM = getTargetMachine();
10508   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10509   DebugLoc DL = MI.getDebugLoc();
10510 
10511   assert(Subtarget->isTargetWindows() &&
10512          "__chkstk is only supported on Windows");
10513   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10514 
10515   // __chkstk takes the number of words to allocate on the stack in R4, and
10516   // returns the stack adjustment in number of bytes in R4.  This will not
10517   // clober any other registers (other than the obvious lr).
10518   //
10519   // Although, technically, IP should be considered a register which may be
10520   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
10521   // thumb-2 environment, so there is no interworking required.  As a result, we
10522   // do not expect a veneer to be emitted by the linker, clobbering IP.
10523   //
10524   // Each module receives its own copy of __chkstk, so no import thunk is
10525   // required, again, ensuring that IP is not clobbered.
10526   //
10527   // Finally, although some linkers may theoretically provide a trampoline for
10528   // out of range calls (which is quite common due to a 32M range limitation of
10529   // branches for Thumb), we can generate the long-call version via
10530   // -mcmodel=large, alleviating the need for the trampoline which may clobber
10531   // IP.
10532 
10533   switch (TM.getCodeModel()) {
10534   case CodeModel::Tiny:
10535     llvm_unreachable("Tiny code model not available on ARM.");
10536   case CodeModel::Small:
10537   case CodeModel::Medium:
10538   case CodeModel::Kernel:
10539     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10540         .add(predOps(ARMCC::AL))
10541         .addExternalSymbol("__chkstk")
10542         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10543         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10544         .addReg(ARM::R12,
10545                 RegState::Implicit | RegState::Define | RegState::Dead)
10546         .addReg(ARM::CPSR,
10547                 RegState::Implicit | RegState::Define | RegState::Dead);
10548     break;
10549   case CodeModel::Large: {
10550     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10551     Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10552 
10553     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10554       .addExternalSymbol("__chkstk");
10555     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10556         .add(predOps(ARMCC::AL))
10557         .addReg(Reg, RegState::Kill)
10558         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10559         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10560         .addReg(ARM::R12,
10561                 RegState::Implicit | RegState::Define | RegState::Dead)
10562         .addReg(ARM::CPSR,
10563                 RegState::Implicit | RegState::Define | RegState::Dead);
10564     break;
10565   }
10566   }
10567 
10568   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10569       .addReg(ARM::SP, RegState::Kill)
10570       .addReg(ARM::R4, RegState::Kill)
10571       .setMIFlags(MachineInstr::FrameSetup)
10572       .add(predOps(ARMCC::AL))
10573       .add(condCodeOp());
10574 
10575   MI.eraseFromParent();
10576   return MBB;
10577 }
10578 
10579 MachineBasicBlock *
10580 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10581                                        MachineBasicBlock *MBB) const {
10582   DebugLoc DL = MI.getDebugLoc();
10583   MachineFunction *MF = MBB->getParent();
10584   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10585 
10586   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10587   MF->insert(++MBB->getIterator(), ContBB);
10588   ContBB->splice(ContBB->begin(), MBB,
10589                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10590   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10591   MBB->addSuccessor(ContBB);
10592 
10593   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10594   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10595   MF->push_back(TrapBB);
10596   MBB->addSuccessor(TrapBB);
10597 
10598   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10599       .addReg(MI.getOperand(0).getReg())
10600       .addImm(0)
10601       .add(predOps(ARMCC::AL));
10602   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10603       .addMBB(TrapBB)
10604       .addImm(ARMCC::EQ)
10605       .addReg(ARM::CPSR);
10606 
10607   MI.eraseFromParent();
10608   return ContBB;
10609 }
10610 
10611 // The CPSR operand of SelectItr might be missing a kill marker
10612 // because there were multiple uses of CPSR, and ISel didn't know
10613 // which to mark. Figure out whether SelectItr should have had a
10614 // kill marker, and set it if it should. Returns the correct kill
10615 // marker value.
10616 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10617                                    MachineBasicBlock* BB,
10618                                    const TargetRegisterInfo* TRI) {
10619   // Scan forward through BB for a use/def of CPSR.
10620   MachineBasicBlock::iterator miI(std::next(SelectItr));
10621   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10622     const MachineInstr& mi = *miI;
10623     if (mi.readsRegister(ARM::CPSR))
10624       return false;
10625     if (mi.definesRegister(ARM::CPSR))
10626       break; // Should have kill-flag - update below.
10627   }
10628 
10629   // If we hit the end of the block, check whether CPSR is live into a
10630   // successor.
10631   if (miI == BB->end()) {
10632     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10633                                           sEnd = BB->succ_end();
10634          sItr != sEnd; ++sItr) {
10635       MachineBasicBlock* succ = *sItr;
10636       if (succ->isLiveIn(ARM::CPSR))
10637         return false;
10638     }
10639   }
10640 
10641   // We found a def, or hit the end of the basic block and CPSR wasn't live
10642   // out. SelectMI should have a kill flag on CPSR.
10643   SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10644   return true;
10645 }
10646 
10647 MachineBasicBlock *
10648 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10649                                                MachineBasicBlock *BB) const {
10650   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10651   DebugLoc dl = MI.getDebugLoc();
10652   bool isThumb2 = Subtarget->isThumb2();
10653   switch (MI.getOpcode()) {
10654   default: {
10655     MI.print(errs());
10656     llvm_unreachable("Unexpected instr type to insert");
10657   }
10658 
10659   // Thumb1 post-indexed loads are really just single-register LDMs.
10660   case ARM::tLDR_postidx: {
10661     MachineOperand Def(MI.getOperand(1));
10662     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10663         .add(Def)  // Rn_wb
10664         .add(MI.getOperand(2))  // Rn
10665         .add(MI.getOperand(3))  // PredImm
10666         .add(MI.getOperand(4))  // PredReg
10667         .add(MI.getOperand(0))  // Rt
10668         .cloneMemRefs(MI);
10669     MI.eraseFromParent();
10670     return BB;
10671   }
10672 
10673   // The Thumb2 pre-indexed stores have the same MI operands, they just
10674   // define them differently in the .td files from the isel patterns, so
10675   // they need pseudos.
10676   case ARM::t2STR_preidx:
10677     MI.setDesc(TII->get(ARM::t2STR_PRE));
10678     return BB;
10679   case ARM::t2STRB_preidx:
10680     MI.setDesc(TII->get(ARM::t2STRB_PRE));
10681     return BB;
10682   case ARM::t2STRH_preidx:
10683     MI.setDesc(TII->get(ARM::t2STRH_PRE));
10684     return BB;
10685 
10686   case ARM::STRi_preidx:
10687   case ARM::STRBi_preidx: {
10688     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10689                                                          : ARM::STRB_PRE_IMM;
10690     // Decode the offset.
10691     unsigned Offset = MI.getOperand(4).getImm();
10692     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10693     Offset = ARM_AM::getAM2Offset(Offset);
10694     if (isSub)
10695       Offset = -Offset;
10696 
10697     MachineMemOperand *MMO = *MI.memoperands_begin();
10698     BuildMI(*BB, MI, dl, TII->get(NewOpc))
10699         .add(MI.getOperand(0)) // Rn_wb
10700         .add(MI.getOperand(1)) // Rt
10701         .add(MI.getOperand(2)) // Rn
10702         .addImm(Offset)        // offset (skip GPR==zero_reg)
10703         .add(MI.getOperand(5)) // pred
10704         .add(MI.getOperand(6))
10705         .addMemOperand(MMO);
10706     MI.eraseFromParent();
10707     return BB;
10708   }
10709   case ARM::STRr_preidx:
10710   case ARM::STRBr_preidx:
10711   case ARM::STRH_preidx: {
10712     unsigned NewOpc;
10713     switch (MI.getOpcode()) {
10714     default: llvm_unreachable("unexpected opcode!");
10715     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10716     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10717     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10718     }
10719     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10720     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10721       MIB.add(MI.getOperand(i));
10722     MI.eraseFromParent();
10723     return BB;
10724   }
10725 
10726   case ARM::tMOVCCr_pseudo: {
10727     // To "insert" a SELECT_CC instruction, we actually have to insert the
10728     // diamond control-flow pattern.  The incoming instruction knows the
10729     // destination vreg to set, the condition code register to branch on, the
10730     // true/false values to select between, and a branch opcode to use.
10731     const BasicBlock *LLVM_BB = BB->getBasicBlock();
10732     MachineFunction::iterator It = ++BB->getIterator();
10733 
10734     //  thisMBB:
10735     //  ...
10736     //   TrueVal = ...
10737     //   cmpTY ccX, r1, r2
10738     //   bCC copy1MBB
10739     //   fallthrough --> copy0MBB
10740     MachineBasicBlock *thisMBB  = BB;
10741     MachineFunction *F = BB->getParent();
10742     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10743     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
10744     F->insert(It, copy0MBB);
10745     F->insert(It, sinkMBB);
10746 
10747     // Check whether CPSR is live past the tMOVCCr_pseudo.
10748     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10749     if (!MI.killsRegister(ARM::CPSR) &&
10750         !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10751       copy0MBB->addLiveIn(ARM::CPSR);
10752       sinkMBB->addLiveIn(ARM::CPSR);
10753     }
10754 
10755     // Transfer the remainder of BB and its successor edges to sinkMBB.
10756     sinkMBB->splice(sinkMBB->begin(), BB,
10757                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10758     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10759 
10760     BB->addSuccessor(copy0MBB);
10761     BB->addSuccessor(sinkMBB);
10762 
10763     BuildMI(BB, dl, TII->get(ARM::tBcc))
10764         .addMBB(sinkMBB)
10765         .addImm(MI.getOperand(3).getImm())
10766         .addReg(MI.getOperand(4).getReg());
10767 
10768     //  copy0MBB:
10769     //   %FalseValue = ...
10770     //   # fallthrough to sinkMBB
10771     BB = copy0MBB;
10772 
10773     // Update machine-CFG edges
10774     BB->addSuccessor(sinkMBB);
10775 
10776     //  sinkMBB:
10777     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10778     //  ...
10779     BB = sinkMBB;
10780     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10781         .addReg(MI.getOperand(1).getReg())
10782         .addMBB(copy0MBB)
10783         .addReg(MI.getOperand(2).getReg())
10784         .addMBB(thisMBB);
10785 
10786     MI.eraseFromParent(); // The pseudo instruction is gone now.
10787     return BB;
10788   }
10789 
10790   case ARM::BCCi64:
10791   case ARM::BCCZi64: {
10792     // If there is an unconditional branch to the other successor, remove it.
10793     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10794 
10795     // Compare both parts that make up the double comparison separately for
10796     // equality.
10797     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10798 
10799     Register LHS1 = MI.getOperand(1).getReg();
10800     Register LHS2 = MI.getOperand(2).getReg();
10801     if (RHSisZero) {
10802       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10803           .addReg(LHS1)
10804           .addImm(0)
10805           .add(predOps(ARMCC::AL));
10806       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10807         .addReg(LHS2).addImm(0)
10808         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10809     } else {
10810       Register RHS1 = MI.getOperand(3).getReg();
10811       Register RHS2 = MI.getOperand(4).getReg();
10812       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10813           .addReg(LHS1)
10814           .addReg(RHS1)
10815           .add(predOps(ARMCC::AL));
10816       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10817         .addReg(LHS2).addReg(RHS2)
10818         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10819     }
10820 
10821     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10822     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10823     if (MI.getOperand(0).getImm() == ARMCC::NE)
10824       std::swap(destMBB, exitMBB);
10825 
10826     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10827       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10828     if (isThumb2)
10829       BuildMI(BB, dl, TII->get(ARM::t2B))
10830           .addMBB(exitMBB)
10831           .add(predOps(ARMCC::AL));
10832     else
10833       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10834 
10835     MI.eraseFromParent(); // The pseudo instruction is gone now.
10836     return BB;
10837   }
10838 
10839   case ARM::Int_eh_sjlj_setjmp:
10840   case ARM::Int_eh_sjlj_setjmp_nofp:
10841   case ARM::tInt_eh_sjlj_setjmp:
10842   case ARM::t2Int_eh_sjlj_setjmp:
10843   case ARM::t2Int_eh_sjlj_setjmp_nofp:
10844     return BB;
10845 
10846   case ARM::Int_eh_sjlj_setup_dispatch:
10847     EmitSjLjDispatchBlock(MI, BB);
10848     return BB;
10849 
10850   case ARM::ABS:
10851   case ARM::t2ABS: {
10852     // To insert an ABS instruction, we have to insert the
10853     // diamond control-flow pattern.  The incoming instruction knows the
10854     // source vreg to test against 0, the destination vreg to set,
10855     // the condition code register to branch on, the
10856     // true/false values to select between, and a branch opcode to use.
10857     // It transforms
10858     //     V1 = ABS V0
10859     // into
10860     //     V2 = MOVS V0
10861     //     BCC                      (branch to SinkBB if V0 >= 0)
10862     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
10863     //     SinkBB: V1 = PHI(V2, V3)
10864     const BasicBlock *LLVM_BB = BB->getBasicBlock();
10865     MachineFunction::iterator BBI = ++BB->getIterator();
10866     MachineFunction *Fn = BB->getParent();
10867     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10868     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
10869     Fn->insert(BBI, RSBBB);
10870     Fn->insert(BBI, SinkBB);
10871 
10872     Register ABSSrcReg = MI.getOperand(1).getReg();
10873     Register ABSDstReg = MI.getOperand(0).getReg();
10874     bool ABSSrcKIll = MI.getOperand(1).isKill();
10875     bool isThumb2 = Subtarget->isThumb2();
10876     MachineRegisterInfo &MRI = Fn->getRegInfo();
10877     // In Thumb mode S must not be specified if source register is the SP or
10878     // PC and if destination register is the SP, so restrict register class
10879     Register NewRsbDstReg = MRI.createVirtualRegister(
10880         isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10881 
10882     // Transfer the remainder of BB and its successor edges to sinkMBB.
10883     SinkBB->splice(SinkBB->begin(), BB,
10884                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
10885     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10886 
10887     BB->addSuccessor(RSBBB);
10888     BB->addSuccessor(SinkBB);
10889 
10890     // fall through to SinkMBB
10891     RSBBB->addSuccessor(SinkBB);
10892 
10893     // insert a cmp at the end of BB
10894     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10895         .addReg(ABSSrcReg)
10896         .addImm(0)
10897         .add(predOps(ARMCC::AL));
10898 
10899     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10900     BuildMI(BB, dl,
10901       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10902       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10903 
10904     // insert rsbri in RSBBB
10905     // Note: BCC and rsbri will be converted into predicated rsbmi
10906     // by if-conversion pass
10907     BuildMI(*RSBBB, RSBBB->begin(), dl,
10908             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10909         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10910         .addImm(0)
10911         .add(predOps(ARMCC::AL))
10912         .add(condCodeOp());
10913 
10914     // insert PHI in SinkBB,
10915     // reuse ABSDstReg to not change uses of ABS instruction
10916     BuildMI(*SinkBB, SinkBB->begin(), dl,
10917       TII->get(ARM::PHI), ABSDstReg)
10918       .addReg(NewRsbDstReg).addMBB(RSBBB)
10919       .addReg(ABSSrcReg).addMBB(BB);
10920 
10921     // remove ABS instruction
10922     MI.eraseFromParent();
10923 
10924     // return last added BB
10925     return SinkBB;
10926   }
10927   case ARM::COPY_STRUCT_BYVAL_I32:
10928     ++NumLoopByVals;
10929     return EmitStructByval(MI, BB);
10930   case ARM::WIN__CHKSTK:
10931     return EmitLowered__chkstk(MI, BB);
10932   case ARM::WIN__DBZCHK:
10933     return EmitLowered__dbzchk(MI, BB);
10934   }
10935 }
10936 
10937 /// Attaches vregs to MEMCPY that it will use as scratch registers
10938 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10939 /// instead of as a custom inserter because we need the use list from the SDNode.
10940 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10941                                     MachineInstr &MI, const SDNode *Node) {
10942   bool isThumb1 = Subtarget->isThumb1Only();
10943 
10944   DebugLoc DL = MI.getDebugLoc();
10945   MachineFunction *MF = MI.getParent()->getParent();
10946   MachineRegisterInfo &MRI = MF->getRegInfo();
10947   MachineInstrBuilder MIB(*MF, MI);
10948 
10949   // If the new dst/src is unused mark it as dead.
10950   if (!Node->hasAnyUseOfValue(0)) {
10951     MI.getOperand(0).setIsDead(true);
10952   }
10953   if (!Node->hasAnyUseOfValue(1)) {
10954     MI.getOperand(1).setIsDead(true);
10955   }
10956 
10957   // The MEMCPY both defines and kills the scratch registers.
10958   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10959     Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10960                                                          : &ARM::GPRRegClass);
10961     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10962   }
10963 }
10964 
10965 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10966                                                       SDNode *Node) const {
10967   if (MI.getOpcode() == ARM::MEMCPY) {
10968     attachMEMCPYScratchRegs(Subtarget, MI, Node);
10969     return;
10970   }
10971 
10972   const MCInstrDesc *MCID = &MI.getDesc();
10973   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10974   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10975   // operand is still set to noreg. If needed, set the optional operand's
10976   // register to CPSR, and remove the redundant implicit def.
10977   //
10978   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10979 
10980   // Rename pseudo opcodes.
10981   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10982   unsigned ccOutIdx;
10983   if (NewOpc) {
10984     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10985     MCID = &TII->get(NewOpc);
10986 
10987     assert(MCID->getNumOperands() ==
10988            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10989         && "converted opcode should be the same except for cc_out"
10990            " (and, on Thumb1, pred)");
10991 
10992     MI.setDesc(*MCID);
10993 
10994     // Add the optional cc_out operand
10995     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10996 
10997     // On Thumb1, move all input operands to the end, then add the predicate
10998     if (Subtarget->isThumb1Only()) {
10999       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
11000         MI.addOperand(MI.getOperand(1));
11001         MI.RemoveOperand(1);
11002       }
11003 
11004       // Restore the ties
11005       for (unsigned i = MI.getNumOperands(); i--;) {
11006         const MachineOperand& op = MI.getOperand(i);
11007         if (op.isReg() && op.isUse()) {
11008           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
11009           if (DefIdx != -1)
11010             MI.tieOperands(DefIdx, i);
11011         }
11012       }
11013 
11014       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
11015       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
11016       ccOutIdx = 1;
11017     } else
11018       ccOutIdx = MCID->getNumOperands() - 1;
11019   } else
11020     ccOutIdx = MCID->getNumOperands() - 1;
11021 
11022   // Any ARM instruction that sets the 's' bit should specify an optional
11023   // "cc_out" operand in the last operand position.
11024   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
11025     assert(!NewOpc && "Optional cc_out operand required");
11026     return;
11027   }
11028   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
11029   // since we already have an optional CPSR def.
11030   bool definesCPSR = false;
11031   bool deadCPSR = false;
11032   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
11033        ++i) {
11034     const MachineOperand &MO = MI.getOperand(i);
11035     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
11036       definesCPSR = true;
11037       if (MO.isDead())
11038         deadCPSR = true;
11039       MI.RemoveOperand(i);
11040       break;
11041     }
11042   }
11043   if (!definesCPSR) {
11044     assert(!NewOpc && "Optional cc_out operand required");
11045     return;
11046   }
11047   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
11048   if (deadCPSR) {
11049     assert(!MI.getOperand(ccOutIdx).getReg() &&
11050            "expect uninitialized optional cc_out operand");
11051     // Thumb1 instructions must have the S bit even if the CPSR is dead.
11052     if (!Subtarget->isThumb1Only())
11053       return;
11054   }
11055 
11056   // If this instruction was defined with an optional CPSR def and its dag node
11057   // had a live implicit CPSR def, then activate the optional CPSR def.
11058   MachineOperand &MO = MI.getOperand(ccOutIdx);
11059   MO.setReg(ARM::CPSR);
11060   MO.setIsDef(true);
11061 }
11062 
11063 //===----------------------------------------------------------------------===//
11064 //                           ARM Optimization Hooks
11065 //===----------------------------------------------------------------------===//
11066 
11067 // Helper function that checks if N is a null or all ones constant.
11068 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
11069   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
11070 }
11071 
11072 // Return true if N is conditionally 0 or all ones.
11073 // Detects these expressions where cc is an i1 value:
11074 //
11075 //   (select cc 0, y)   [AllOnes=0]
11076 //   (select cc y, 0)   [AllOnes=0]
11077 //   (zext cc)          [AllOnes=0]
11078 //   (sext cc)          [AllOnes=0/1]
11079 //   (select cc -1, y)  [AllOnes=1]
11080 //   (select cc y, -1)  [AllOnes=1]
11081 //
11082 // Invert is set when N is the null/all ones constant when CC is false.
11083 // OtherOp is set to the alternative value of N.
11084 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
11085                                        SDValue &CC, bool &Invert,
11086                                        SDValue &OtherOp,
11087                                        SelectionDAG &DAG) {
11088   switch (N->getOpcode()) {
11089   default: return false;
11090   case ISD::SELECT: {
11091     CC = N->getOperand(0);
11092     SDValue N1 = N->getOperand(1);
11093     SDValue N2 = N->getOperand(2);
11094     if (isZeroOrAllOnes(N1, AllOnes)) {
11095       Invert = false;
11096       OtherOp = N2;
11097       return true;
11098     }
11099     if (isZeroOrAllOnes(N2, AllOnes)) {
11100       Invert = true;
11101       OtherOp = N1;
11102       return true;
11103     }
11104     return false;
11105   }
11106   case ISD::ZERO_EXTEND:
11107     // (zext cc) can never be the all ones value.
11108     if (AllOnes)
11109       return false;
11110     LLVM_FALLTHROUGH;
11111   case ISD::SIGN_EXTEND: {
11112     SDLoc dl(N);
11113     EVT VT = N->getValueType(0);
11114     CC = N->getOperand(0);
11115     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
11116       return false;
11117     Invert = !AllOnes;
11118     if (AllOnes)
11119       // When looking for an AllOnes constant, N is an sext, and the 'other'
11120       // value is 0.
11121       OtherOp = DAG.getConstant(0, dl, VT);
11122     else if (N->getOpcode() == ISD::ZERO_EXTEND)
11123       // When looking for a 0 constant, N can be zext or sext.
11124       OtherOp = DAG.getConstant(1, dl, VT);
11125     else
11126       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
11127                                 VT);
11128     return true;
11129   }
11130   }
11131 }
11132 
11133 // Combine a constant select operand into its use:
11134 //
11135 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
11136 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
11137 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
11138 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
11139 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
11140 //
11141 // The transform is rejected if the select doesn't have a constant operand that
11142 // is null, or all ones when AllOnes is set.
11143 //
11144 // Also recognize sext/zext from i1:
11145 //
11146 //   (add (zext cc), x) -> (select cc (add x, 1), x)
11147 //   (add (sext cc), x) -> (select cc (add x, -1), x)
11148 //
11149 // These transformations eventually create predicated instructions.
11150 //
11151 // @param N       The node to transform.
11152 // @param Slct    The N operand that is a select.
11153 // @param OtherOp The other N operand (x above).
11154 // @param DCI     Context.
11155 // @param AllOnes Require the select constant to be all ones instead of null.
11156 // @returns The new node, or SDValue() on failure.
11157 static
11158 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
11159                             TargetLowering::DAGCombinerInfo &DCI,
11160                             bool AllOnes = false) {
11161   SelectionDAG &DAG = DCI.DAG;
11162   EVT VT = N->getValueType(0);
11163   SDValue NonConstantVal;
11164   SDValue CCOp;
11165   bool SwapSelectOps;
11166   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
11167                                   NonConstantVal, DAG))
11168     return SDValue();
11169 
11170   // Slct is now know to be the desired identity constant when CC is true.
11171   SDValue TrueVal = OtherOp;
11172   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11173                                  OtherOp, NonConstantVal);
11174   // Unless SwapSelectOps says CC should be false.
11175   if (SwapSelectOps)
11176     std::swap(TrueVal, FalseVal);
11177 
11178   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
11179                      CCOp, TrueVal, FalseVal);
11180 }
11181 
11182 // Attempt combineSelectAndUse on each operand of a commutative operator N.
11183 static
11184 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
11185                                        TargetLowering::DAGCombinerInfo &DCI) {
11186   SDValue N0 = N->getOperand(0);
11187   SDValue N1 = N->getOperand(1);
11188   if (N0.getNode()->hasOneUse())
11189     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
11190       return Result;
11191   if (N1.getNode()->hasOneUse())
11192     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
11193       return Result;
11194   return SDValue();
11195 }
11196 
11197 static bool IsVUZPShuffleNode(SDNode *N) {
11198   // VUZP shuffle node.
11199   if (N->getOpcode() == ARMISD::VUZP)
11200     return true;
11201 
11202   // "VUZP" on i32 is an alias for VTRN.
11203   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
11204     return true;
11205 
11206   return false;
11207 }
11208 
11209 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
11210                                  TargetLowering::DAGCombinerInfo &DCI,
11211                                  const ARMSubtarget *Subtarget) {
11212   // Look for ADD(VUZP.0, VUZP.1).
11213   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
11214       N0 == N1)
11215    return SDValue();
11216 
11217   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
11218   if (!N->getValueType(0).is64BitVector())
11219     return SDValue();
11220 
11221   // Generate vpadd.
11222   SelectionDAG &DAG = DCI.DAG;
11223   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11224   SDLoc dl(N);
11225   SDNode *Unzip = N0.getNode();
11226   EVT VT = N->getValueType(0);
11227 
11228   SmallVector<SDValue, 8> Ops;
11229   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
11230                                 TLI.getPointerTy(DAG.getDataLayout())));
11231   Ops.push_back(Unzip->getOperand(0));
11232   Ops.push_back(Unzip->getOperand(1));
11233 
11234   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11235 }
11236 
11237 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11238                                       TargetLowering::DAGCombinerInfo &DCI,
11239                                       const ARMSubtarget *Subtarget) {
11240   // Check for two extended operands.
11241   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
11242         N1.getOpcode() == ISD::SIGN_EXTEND) &&
11243       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
11244         N1.getOpcode() == ISD::ZERO_EXTEND))
11245     return SDValue();
11246 
11247   SDValue N00 = N0.getOperand(0);
11248   SDValue N10 = N1.getOperand(0);
11249 
11250   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
11251   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
11252       N00 == N10)
11253     return SDValue();
11254 
11255   // We only recognize Q register paddl here; this can't be reached until
11256   // after type legalization.
11257   if (!N00.getValueType().is64BitVector() ||
11258       !N0.getValueType().is128BitVector())
11259     return SDValue();
11260 
11261   // Generate vpaddl.
11262   SelectionDAG &DAG = DCI.DAG;
11263   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11264   SDLoc dl(N);
11265   EVT VT = N->getValueType(0);
11266 
11267   SmallVector<SDValue, 8> Ops;
11268   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
11269   unsigned Opcode;
11270   if (N0.getOpcode() == ISD::SIGN_EXTEND)
11271     Opcode = Intrinsic::arm_neon_vpaddls;
11272   else
11273     Opcode = Intrinsic::arm_neon_vpaddlu;
11274   Ops.push_back(DAG.getConstant(Opcode, dl,
11275                                 TLI.getPointerTy(DAG.getDataLayout())));
11276   EVT ElemTy = N00.getValueType().getVectorElementType();
11277   unsigned NumElts = VT.getVectorNumElements();
11278   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
11279   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
11280                                N00.getOperand(0), N00.getOperand(1));
11281   Ops.push_back(Concat);
11282 
11283   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11284 }
11285 
11286 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
11287 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
11288 // much easier to match.
11289 static SDValue
11290 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11291                                TargetLowering::DAGCombinerInfo &DCI,
11292                                const ARMSubtarget *Subtarget) {
11293   // Only perform optimization if after legalize, and if NEON is available. We
11294   // also expected both operands to be BUILD_VECTORs.
11295   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
11296       || N0.getOpcode() != ISD::BUILD_VECTOR
11297       || N1.getOpcode() != ISD::BUILD_VECTOR)
11298     return SDValue();
11299 
11300   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
11301   EVT VT = N->getValueType(0);
11302   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
11303     return SDValue();
11304 
11305   // Check that the vector operands are of the right form.
11306   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
11307   // operands, where N is the size of the formed vector.
11308   // Each EXTRACT_VECTOR should have the same input vector and odd or even
11309   // index such that we have a pair wise add pattern.
11310 
11311   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
11312   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11313     return SDValue();
11314   SDValue Vec = N0->getOperand(0)->getOperand(0);
11315   SDNode *V = Vec.getNode();
11316   unsigned nextIndex = 0;
11317 
11318   // For each operands to the ADD which are BUILD_VECTORs,
11319   // check to see if each of their operands are an EXTRACT_VECTOR with
11320   // the same vector and appropriate index.
11321   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
11322     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
11323         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11324 
11325       SDValue ExtVec0 = N0->getOperand(i);
11326       SDValue ExtVec1 = N1->getOperand(i);
11327 
11328       // First operand is the vector, verify its the same.
11329       if (V != ExtVec0->getOperand(0).getNode() ||
11330           V != ExtVec1->getOperand(0).getNode())
11331         return SDValue();
11332 
11333       // Second is the constant, verify its correct.
11334       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
11335       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
11336 
11337       // For the constant, we want to see all the even or all the odd.
11338       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
11339           || C1->getZExtValue() != nextIndex+1)
11340         return SDValue();
11341 
11342       // Increment index.
11343       nextIndex+=2;
11344     } else
11345       return SDValue();
11346   }
11347 
11348   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
11349   // we're using the entire input vector, otherwise there's a size/legality
11350   // mismatch somewhere.
11351   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
11352       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
11353     return SDValue();
11354 
11355   // Create VPADDL node.
11356   SelectionDAG &DAG = DCI.DAG;
11357   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11358 
11359   SDLoc dl(N);
11360 
11361   // Build operand list.
11362   SmallVector<SDValue, 8> Ops;
11363   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
11364                                 TLI.getPointerTy(DAG.getDataLayout())));
11365 
11366   // Input is the vector.
11367   Ops.push_back(Vec);
11368 
11369   // Get widened type and narrowed type.
11370   MVT widenType;
11371   unsigned numElem = VT.getVectorNumElements();
11372 
11373   EVT inputLaneType = Vec.getValueType().getVectorElementType();
11374   switch (inputLaneType.getSimpleVT().SimpleTy) {
11375     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
11376     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
11377     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
11378     default:
11379       llvm_unreachable("Invalid vector element type for padd optimization.");
11380   }
11381 
11382   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
11383   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
11384   return DAG.getNode(ExtOp, dl, VT, tmp);
11385 }
11386 
11387 static SDValue findMUL_LOHI(SDValue V) {
11388   if (V->getOpcode() == ISD::UMUL_LOHI ||
11389       V->getOpcode() == ISD::SMUL_LOHI)
11390     return V;
11391   return SDValue();
11392 }
11393 
11394 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
11395                                         TargetLowering::DAGCombinerInfo &DCI,
11396                                         const ARMSubtarget *Subtarget) {
11397   if (!Subtarget->hasBaseDSP())
11398     return SDValue();
11399 
11400   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
11401   // accumulates the product into a 64-bit value. The 16-bit values will
11402   // be sign extended somehow or SRA'd into 32-bit values
11403   // (addc (adde (mul 16bit, 16bit), lo), hi)
11404   SDValue Mul = AddcNode->getOperand(0);
11405   SDValue Lo = AddcNode->getOperand(1);
11406   if (Mul.getOpcode() != ISD::MUL) {
11407     Lo = AddcNode->getOperand(0);
11408     Mul = AddcNode->getOperand(1);
11409     if (Mul.getOpcode() != ISD::MUL)
11410       return SDValue();
11411   }
11412 
11413   SDValue SRA = AddeNode->getOperand(0);
11414   SDValue Hi = AddeNode->getOperand(1);
11415   if (SRA.getOpcode() != ISD::SRA) {
11416     SRA = AddeNode->getOperand(1);
11417     Hi = AddeNode->getOperand(0);
11418     if (SRA.getOpcode() != ISD::SRA)
11419       return SDValue();
11420   }
11421   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
11422     if (Const->getZExtValue() != 31)
11423       return SDValue();
11424   } else
11425     return SDValue();
11426 
11427   if (SRA.getOperand(0) != Mul)
11428     return SDValue();
11429 
11430   SelectionDAG &DAG = DCI.DAG;
11431   SDLoc dl(AddcNode);
11432   unsigned Opcode = 0;
11433   SDValue Op0;
11434   SDValue Op1;
11435 
11436   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
11437     Opcode = ARMISD::SMLALBB;
11438     Op0 = Mul.getOperand(0);
11439     Op1 = Mul.getOperand(1);
11440   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
11441     Opcode = ARMISD::SMLALBT;
11442     Op0 = Mul.getOperand(0);
11443     Op1 = Mul.getOperand(1).getOperand(0);
11444   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
11445     Opcode = ARMISD::SMLALTB;
11446     Op0 = Mul.getOperand(0).getOperand(0);
11447     Op1 = Mul.getOperand(1);
11448   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
11449     Opcode = ARMISD::SMLALTT;
11450     Op0 = Mul->getOperand(0).getOperand(0);
11451     Op1 = Mul->getOperand(1).getOperand(0);
11452   }
11453 
11454   if (!Op0 || !Op1)
11455     return SDValue();
11456 
11457   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
11458                               Op0, Op1, Lo, Hi);
11459   // Replace the ADDs' nodes uses by the MLA node's values.
11460   SDValue HiMLALResult(SMLAL.getNode(), 1);
11461   SDValue LoMLALResult(SMLAL.getNode(), 0);
11462 
11463   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
11464   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
11465 
11466   // Return original node to notify the driver to stop replacing.
11467   SDValue resNode(AddcNode, 0);
11468   return resNode;
11469 }
11470 
11471 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
11472                                      TargetLowering::DAGCombinerInfo &DCI,
11473                                      const ARMSubtarget *Subtarget) {
11474   // Look for multiply add opportunities.
11475   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
11476   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
11477   // a glue link from the first add to the second add.
11478   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
11479   // a S/UMLAL instruction.
11480   //                  UMUL_LOHI
11481   //                 / :lo    \ :hi
11482   //                V          \          [no multiline comment]
11483   //    loAdd ->  ADDC         |
11484   //                 \ :carry /
11485   //                  V      V
11486   //                    ADDE   <- hiAdd
11487   //
11488   // In the special case where only the higher part of a signed result is used
11489   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
11490   // a constant with the exact value of 0x80000000, we recognize we are dealing
11491   // with a "rounded multiply and add" (or subtract) and transform it into
11492   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11493 
11494   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11495           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11496          "Expect an ADDE or SUBE");
11497 
11498   assert(AddeSubeNode->getNumOperands() == 3 &&
11499          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11500          "ADDE node has the wrong inputs");
11501 
11502   // Check that we are chained to the right ADDC or SUBC node.
11503   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11504   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11505        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11506       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11507        AddcSubcNode->getOpcode() != ARMISD::SUBC))
11508     return SDValue();
11509 
11510   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11511   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11512 
11513   // Check if the two operands are from the same mul_lohi node.
11514   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11515     return SDValue();
11516 
11517   assert(AddcSubcNode->getNumValues() == 2 &&
11518          AddcSubcNode->getValueType(0) == MVT::i32 &&
11519          "Expect ADDC with two result values. First: i32");
11520 
11521   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11522   // maybe a SMLAL which multiplies two 16-bit values.
11523   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11524       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11525       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11526       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11527       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11528     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11529 
11530   // Check for the triangle shape.
11531   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11532   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11533 
11534   // Make sure that the ADDE/SUBE operands are not coming from the same node.
11535   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11536     return SDValue();
11537 
11538   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11539   bool IsLeftOperandMUL = false;
11540   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11541   if (MULOp == SDValue())
11542     MULOp = findMUL_LOHI(AddeSubeOp1);
11543   else
11544     IsLeftOperandMUL = true;
11545   if (MULOp == SDValue())
11546     return SDValue();
11547 
11548   // Figure out the right opcode.
11549   unsigned Opc = MULOp->getOpcode();
11550   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11551 
11552   // Figure out the high and low input values to the MLAL node.
11553   SDValue *HiAddSub = nullptr;
11554   SDValue *LoMul = nullptr;
11555   SDValue *LowAddSub = nullptr;
11556 
11557   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11558   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11559     return SDValue();
11560 
11561   if (IsLeftOperandMUL)
11562     HiAddSub = &AddeSubeOp1;
11563   else
11564     HiAddSub = &AddeSubeOp0;
11565 
11566   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11567   // whose low result is fed to the ADDC/SUBC we are checking.
11568 
11569   if (AddcSubcOp0 == MULOp.getValue(0)) {
11570     LoMul = &AddcSubcOp0;
11571     LowAddSub = &AddcSubcOp1;
11572   }
11573   if (AddcSubcOp1 == MULOp.getValue(0)) {
11574     LoMul = &AddcSubcOp1;
11575     LowAddSub = &AddcSubcOp0;
11576   }
11577 
11578   if (!LoMul)
11579     return SDValue();
11580 
11581   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11582   // the replacement below will create a cycle.
11583   if (AddcSubcNode == HiAddSub->getNode() ||
11584       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11585     return SDValue();
11586 
11587   // Create the merged node.
11588   SelectionDAG &DAG = DCI.DAG;
11589 
11590   // Start building operand list.
11591   SmallVector<SDValue, 8> Ops;
11592   Ops.push_back(LoMul->getOperand(0));
11593   Ops.push_back(LoMul->getOperand(1));
11594 
11595   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
11596   // the case, we must be doing signed multiplication and only use the higher
11597   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11598   // addition or subtraction with the value of 0x800000.
11599   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11600       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11601       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11602       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11603           0x80000000) {
11604     Ops.push_back(*HiAddSub);
11605     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11606       FinalOpc = ARMISD::SMMLSR;
11607     } else {
11608       FinalOpc = ARMISD::SMMLAR;
11609     }
11610     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11611     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11612 
11613     return SDValue(AddeSubeNode, 0);
11614   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11615     // SMMLS is generated during instruction selection and the rest of this
11616     // function can not handle the case where AddcSubcNode is a SUBC.
11617     return SDValue();
11618 
11619   // Finish building the operand list for {U/S}MLAL
11620   Ops.push_back(*LowAddSub);
11621   Ops.push_back(*HiAddSub);
11622 
11623   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11624                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
11625 
11626   // Replace the ADDs' nodes uses by the MLA node's values.
11627   SDValue HiMLALResult(MLALNode.getNode(), 1);
11628   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11629 
11630   SDValue LoMLALResult(MLALNode.getNode(), 0);
11631   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11632 
11633   // Return original node to notify the driver to stop replacing.
11634   return SDValue(AddeSubeNode, 0);
11635 }
11636 
11637 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11638                                       TargetLowering::DAGCombinerInfo &DCI,
11639                                       const ARMSubtarget *Subtarget) {
11640   // UMAAL is similar to UMLAL except that it adds two unsigned values.
11641   // While trying to combine for the other MLAL nodes, first search for the
11642   // chance to use UMAAL. Check if Addc uses a node which has already
11643   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11644   // as the addend, and it's handled in PerformUMLALCombine.
11645 
11646   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11647     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11648 
11649   // Check that we have a glued ADDC node.
11650   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11651   if (AddcNode->getOpcode() != ARMISD::ADDC)
11652     return SDValue();
11653 
11654   // Find the converted UMAAL or quit if it doesn't exist.
11655   SDNode *UmlalNode = nullptr;
11656   SDValue AddHi;
11657   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11658     UmlalNode = AddcNode->getOperand(0).getNode();
11659     AddHi = AddcNode->getOperand(1);
11660   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11661     UmlalNode = AddcNode->getOperand(1).getNode();
11662     AddHi = AddcNode->getOperand(0);
11663   } else {
11664     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11665   }
11666 
11667   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11668   // the ADDC as well as Zero.
11669   if (!isNullConstant(UmlalNode->getOperand(3)))
11670     return SDValue();
11671 
11672   if ((isNullConstant(AddeNode->getOperand(0)) &&
11673        AddeNode->getOperand(1).getNode() == UmlalNode) ||
11674       (AddeNode->getOperand(0).getNode() == UmlalNode &&
11675        isNullConstant(AddeNode->getOperand(1)))) {
11676     SelectionDAG &DAG = DCI.DAG;
11677     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11678                       UmlalNode->getOperand(2), AddHi };
11679     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11680                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
11681 
11682     // Replace the ADDs' nodes uses by the UMAAL node's values.
11683     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11684     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11685 
11686     // Return original node to notify the driver to stop replacing.
11687     return SDValue(AddeNode, 0);
11688   }
11689   return SDValue();
11690 }
11691 
11692 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11693                                    const ARMSubtarget *Subtarget) {
11694   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11695     return SDValue();
11696 
11697   // Check that we have a pair of ADDC and ADDE as operands.
11698   // Both addends of the ADDE must be zero.
11699   SDNode* AddcNode = N->getOperand(2).getNode();
11700   SDNode* AddeNode = N->getOperand(3).getNode();
11701   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11702       (AddeNode->getOpcode() == ARMISD::ADDE) &&
11703       isNullConstant(AddeNode->getOperand(0)) &&
11704       isNullConstant(AddeNode->getOperand(1)) &&
11705       (AddeNode->getOperand(2).getNode() == AddcNode))
11706     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11707                        DAG.getVTList(MVT::i32, MVT::i32),
11708                        {N->getOperand(0), N->getOperand(1),
11709                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
11710   else
11711     return SDValue();
11712 }
11713 
11714 static SDValue PerformAddcSubcCombine(SDNode *N,
11715                                       TargetLowering::DAGCombinerInfo &DCI,
11716                                       const ARMSubtarget *Subtarget) {
11717   SelectionDAG &DAG(DCI.DAG);
11718 
11719   if (N->getOpcode() == ARMISD::SUBC) {
11720     // (SUBC (ADDE 0, 0, C), 1) -> C
11721     SDValue LHS = N->getOperand(0);
11722     SDValue RHS = N->getOperand(1);
11723     if (LHS->getOpcode() == ARMISD::ADDE &&
11724         isNullConstant(LHS->getOperand(0)) &&
11725         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11726       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11727     }
11728   }
11729 
11730   if (Subtarget->isThumb1Only()) {
11731     SDValue RHS = N->getOperand(1);
11732     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11733       int32_t imm = C->getSExtValue();
11734       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11735         SDLoc DL(N);
11736         RHS = DAG.getConstant(-imm, DL, MVT::i32);
11737         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11738                                                            : ARMISD::ADDC;
11739         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11740       }
11741     }
11742   }
11743 
11744   return SDValue();
11745 }
11746 
11747 static SDValue PerformAddeSubeCombine(SDNode *N,
11748                                       TargetLowering::DAGCombinerInfo &DCI,
11749                                       const ARMSubtarget *Subtarget) {
11750   if (Subtarget->isThumb1Only()) {
11751     SelectionDAG &DAG = DCI.DAG;
11752     SDValue RHS = N->getOperand(1);
11753     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11754       int64_t imm = C->getSExtValue();
11755       if (imm < 0) {
11756         SDLoc DL(N);
11757 
11758         // The with-carry-in form matches bitwise not instead of the negation.
11759         // Effectively, the inverse interpretation of the carry flag already
11760         // accounts for part of the negation.
11761         RHS = DAG.getConstant(~imm, DL, MVT::i32);
11762 
11763         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11764                                                            : ARMISD::ADDE;
11765         return DAG.getNode(Opcode, DL, N->getVTList(),
11766                            N->getOperand(0), RHS, N->getOperand(2));
11767       }
11768     }
11769   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11770     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11771   }
11772   return SDValue();
11773 }
11774 
11775 static SDValue PerformVSELECTCombine(SDNode *N,
11776                                      TargetLowering::DAGCombinerInfo &DCI,
11777                                      const ARMSubtarget *Subtarget) {
11778   // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
11779   //
11780   // We need to re-implement this optimization here as the implementation in the
11781   // Target-Independent DAGCombiner does not handle the kind of constant we make
11782   // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
11783   // good reason, allowing truncation there would break other targets).
11784   //
11785   // Currently, this is only done for MVE, as it's the only target that benefits
11786   // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
11787   if (!Subtarget->hasMVEIntegerOps())
11788     return SDValue();
11789 
11790   if (N->getOperand(0).getOpcode() != ISD::XOR)
11791     return SDValue();
11792   SDValue XOR = N->getOperand(0);
11793 
11794   // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
11795   // It is important to check with truncation allowed as the BUILD_VECTORs we
11796   // generate in those situations will truncate their operands.
11797   ConstantSDNode *Const =
11798       isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
11799                           /*AllowTruncation*/ true);
11800   if (!Const || !Const->isOne())
11801     return SDValue();
11802 
11803   // Rewrite into vselect(cond, rhs, lhs).
11804   SDValue Cond = XOR->getOperand(0);
11805   SDValue LHS = N->getOperand(1);
11806   SDValue RHS = N->getOperand(2);
11807   EVT Type = N->getValueType(0);
11808   return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
11809 }
11810 
11811 static SDValue PerformABSCombine(SDNode *N,
11812                                   TargetLowering::DAGCombinerInfo &DCI,
11813                                   const ARMSubtarget *Subtarget) {
11814   SDValue res;
11815   SelectionDAG &DAG = DCI.DAG;
11816   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11817 
11818   if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11819     return SDValue();
11820 
11821   if (!TLI.expandABS(N, res, DAG))
11822       return SDValue();
11823 
11824   return res;
11825 }
11826 
11827 /// PerformADDECombine - Target-specific dag combine transform from
11828 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11829 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11830 static SDValue PerformADDECombine(SDNode *N,
11831                                   TargetLowering::DAGCombinerInfo &DCI,
11832                                   const ARMSubtarget *Subtarget) {
11833   // Only ARM and Thumb2 support UMLAL/SMLAL.
11834   if (Subtarget->isThumb1Only())
11835     return PerformAddeSubeCombine(N, DCI, Subtarget);
11836 
11837   // Only perform the checks after legalize when the pattern is available.
11838   if (DCI.isBeforeLegalize()) return SDValue();
11839 
11840   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11841 }
11842 
11843 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11844 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
11845 /// called with the default operands, and if that fails, with commuted
11846 /// operands.
11847 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11848                                           TargetLowering::DAGCombinerInfo &DCI,
11849                                           const ARMSubtarget *Subtarget){
11850   // Attempt to create vpadd for this add.
11851   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11852     return Result;
11853 
11854   // Attempt to create vpaddl for this add.
11855   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11856     return Result;
11857   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11858                                                       Subtarget))
11859     return Result;
11860 
11861   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11862   if (N0.getNode()->hasOneUse())
11863     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11864       return Result;
11865   return SDValue();
11866 }
11867 
11868 static SDValue PerformADDVecReduce(SDNode *N,
11869                                    TargetLowering::DAGCombinerInfo &DCI,
11870                                    const ARMSubtarget *Subtarget) {
11871   if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64)
11872     return SDValue();
11873 
11874   SDValue N0 = N->getOperand(0);
11875   SDValue N1 = N->getOperand(1);
11876 
11877   // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
11878   // will look like:
11879   //   t1: i32,i32 = ARMISD::VADDLVs x
11880   //   t2: i64 = build_pair t1, t1:1
11881   //   t3: i64 = add t2, y
11882   // We also need to check for sext / zext and commutitive adds.
11883   auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
11884                            SDValue NB) {
11885     if (NB->getOpcode() != ISD::BUILD_PAIR)
11886       return SDValue();
11887     SDValue VecRed = NB->getOperand(0);
11888     if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 ||
11889         NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
11890       return SDValue();
11891 
11892     SDLoc dl(N);
11893     SmallVector<SDValue, 4> Ops;
11894     Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
11895                                   DCI.DAG.getConstant(0, dl, MVT::i32)));
11896     Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
11897                                   DCI.DAG.getConstant(1, dl, MVT::i32)));
11898     for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++)
11899       Ops.push_back(VecRed->getOperand(i));
11900     SDValue Red = DCI.DAG.getNode(OpcodeA, dl,
11901                                   DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops);
11902     return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
11903                            SDValue(Red.getNode(), 1));
11904   };
11905 
11906   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
11907     return M;
11908   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
11909     return M;
11910   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
11911     return M;
11912   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
11913     return M;
11914   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
11915     return M;
11916   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
11917     return M;
11918   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
11919     return M;
11920   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
11921     return M;
11922   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
11923     return M;
11924   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
11925     return M;
11926   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
11927     return M;
11928   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
11929     return M;
11930   return SDValue();
11931 }
11932 
11933 bool
11934 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11935                                                  CombineLevel Level) const {
11936   if (Level == BeforeLegalizeTypes)
11937     return true;
11938 
11939   if (N->getOpcode() != ISD::SHL)
11940     return true;
11941 
11942   if (Subtarget->isThumb1Only()) {
11943     // Avoid making expensive immediates by commuting shifts. (This logic
11944     // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11945     // for free.)
11946     if (N->getOpcode() != ISD::SHL)
11947       return true;
11948     SDValue N1 = N->getOperand(0);
11949     if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11950         N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11951       return true;
11952     if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11953       if (Const->getAPIntValue().ult(256))
11954         return false;
11955       if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11956           Const->getAPIntValue().sgt(-256))
11957         return false;
11958     }
11959     return true;
11960   }
11961 
11962   // Turn off commute-with-shift transform after legalization, so it doesn't
11963   // conflict with PerformSHLSimplify.  (We could try to detect when
11964   // PerformSHLSimplify would trigger more precisely, but it isn't
11965   // really necessary.)
11966   return false;
11967 }
11968 
11969 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11970     const SDNode *N, CombineLevel Level) const {
11971   if (!Subtarget->isThumb1Only())
11972     return true;
11973 
11974   if (Level == BeforeLegalizeTypes)
11975     return true;
11976 
11977   return false;
11978 }
11979 
11980 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11981   if (!Subtarget->hasNEON()) {
11982     if (Subtarget->isThumb1Only())
11983       return VT.getScalarSizeInBits() <= 32;
11984     return true;
11985   }
11986   return VT.isScalarInteger();
11987 }
11988 
11989 static SDValue PerformSHLSimplify(SDNode *N,
11990                                 TargetLowering::DAGCombinerInfo &DCI,
11991                                 const ARMSubtarget *ST) {
11992   // Allow the generic combiner to identify potential bswaps.
11993   if (DCI.isBeforeLegalize())
11994     return SDValue();
11995 
11996   // DAG combiner will fold:
11997   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11998   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11999   // Other code patterns that can be also be modified have the following form:
12000   // b + ((a << 1) | 510)
12001   // b + ((a << 1) & 510)
12002   // b + ((a << 1) ^ 510)
12003   // b + ((a << 1) + 510)
12004 
12005   // Many instructions can  perform the shift for free, but it requires both
12006   // the operands to be registers. If c1 << c2 is too large, a mov immediate
12007   // instruction will needed. So, unfold back to the original pattern if:
12008   // - if c1 and c2 are small enough that they don't require mov imms.
12009   // - the user(s) of the node can perform an shl
12010 
12011   // No shifted operands for 16-bit instructions.
12012   if (ST->isThumb() && ST->isThumb1Only())
12013     return SDValue();
12014 
12015   // Check that all the users could perform the shl themselves.
12016   for (auto U : N->uses()) {
12017     switch(U->getOpcode()) {
12018     default:
12019       return SDValue();
12020     case ISD::SUB:
12021     case ISD::ADD:
12022     case ISD::AND:
12023     case ISD::OR:
12024     case ISD::XOR:
12025     case ISD::SETCC:
12026     case ARMISD::CMP:
12027       // Check that the user isn't already using a constant because there
12028       // aren't any instructions that support an immediate operand and a
12029       // shifted operand.
12030       if (isa<ConstantSDNode>(U->getOperand(0)) ||
12031           isa<ConstantSDNode>(U->getOperand(1)))
12032         return SDValue();
12033 
12034       // Check that it's not already using a shift.
12035       if (U->getOperand(0).getOpcode() == ISD::SHL ||
12036           U->getOperand(1).getOpcode() == ISD::SHL)
12037         return SDValue();
12038       break;
12039     }
12040   }
12041 
12042   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
12043       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
12044     return SDValue();
12045 
12046   if (N->getOperand(0).getOpcode() != ISD::SHL)
12047     return SDValue();
12048 
12049   SDValue SHL = N->getOperand(0);
12050 
12051   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
12052   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
12053   if (!C1ShlC2 || !C2)
12054     return SDValue();
12055 
12056   APInt C2Int = C2->getAPIntValue();
12057   APInt C1Int = C1ShlC2->getAPIntValue();
12058 
12059   // Check that performing a lshr will not lose any information.
12060   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
12061                                      C2Int.getBitWidth() - C2->getZExtValue());
12062   if ((C1Int & Mask) != C1Int)
12063     return SDValue();
12064 
12065   // Shift the first constant.
12066   C1Int.lshrInPlace(C2Int);
12067 
12068   // The immediates are encoded as an 8-bit value that can be rotated.
12069   auto LargeImm = [](const APInt &Imm) {
12070     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
12071     return Imm.getBitWidth() - Zeros > 8;
12072   };
12073 
12074   if (LargeImm(C1Int) || LargeImm(C2Int))
12075     return SDValue();
12076 
12077   SelectionDAG &DAG = DCI.DAG;
12078   SDLoc dl(N);
12079   SDValue X = SHL.getOperand(0);
12080   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
12081                               DAG.getConstant(C1Int, dl, MVT::i32));
12082   // Shift left to compensate for the lshr of C1Int.
12083   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
12084 
12085   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
12086              SHL.dump(); N->dump());
12087   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
12088   return Res;
12089 }
12090 
12091 
12092 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
12093 ///
12094 static SDValue PerformADDCombine(SDNode *N,
12095                                  TargetLowering::DAGCombinerInfo &DCI,
12096                                  const ARMSubtarget *Subtarget) {
12097   SDValue N0 = N->getOperand(0);
12098   SDValue N1 = N->getOperand(1);
12099 
12100   // Only works one way, because it needs an immediate operand.
12101   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12102     return Result;
12103 
12104   if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget))
12105     return Result;
12106 
12107   // First try with the default operand order.
12108   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
12109     return Result;
12110 
12111   // If that didn't work, try again with the operands commuted.
12112   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
12113 }
12114 
12115 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
12116 ///
12117 static SDValue PerformSUBCombine(SDNode *N,
12118                                  TargetLowering::DAGCombinerInfo &DCI,
12119                                  const ARMSubtarget *Subtarget) {
12120   SDValue N0 = N->getOperand(0);
12121   SDValue N1 = N->getOperand(1);
12122 
12123   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12124   if (N1.getNode()->hasOneUse())
12125     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
12126       return Result;
12127 
12128   if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
12129     return SDValue();
12130 
12131   // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
12132   // so that we can readily pattern match more mve instructions which can use
12133   // a scalar operand.
12134   SDValue VDup = N->getOperand(1);
12135   if (VDup->getOpcode() != ARMISD::VDUP)
12136     return SDValue();
12137 
12138   SDValue VMov = N->getOperand(0);
12139   if (VMov->getOpcode() == ISD::BITCAST)
12140     VMov = VMov->getOperand(0);
12141 
12142   if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
12143     return SDValue();
12144 
12145   SDLoc dl(N);
12146   SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
12147                                    DCI.DAG.getConstant(0, dl, MVT::i32),
12148                                    VDup->getOperand(0));
12149   return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
12150 }
12151 
12152 /// PerformVMULCombine
12153 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
12154 /// special multiplier accumulator forwarding.
12155 ///   vmul d3, d0, d2
12156 ///   vmla d3, d1, d2
12157 /// is faster than
12158 ///   vadd d3, d0, d1
12159 ///   vmul d3, d3, d2
12160 //  However, for (A + B) * (A + B),
12161 //    vadd d2, d0, d1
12162 //    vmul d3, d0, d2
12163 //    vmla d3, d1, d2
12164 //  is slower than
12165 //    vadd d2, d0, d1
12166 //    vmul d3, d2, d2
12167 static SDValue PerformVMULCombine(SDNode *N,
12168                                   TargetLowering::DAGCombinerInfo &DCI,
12169                                   const ARMSubtarget *Subtarget) {
12170   if (!Subtarget->hasVMLxForwarding())
12171     return SDValue();
12172 
12173   SelectionDAG &DAG = DCI.DAG;
12174   SDValue N0 = N->getOperand(0);
12175   SDValue N1 = N->getOperand(1);
12176   unsigned Opcode = N0.getOpcode();
12177   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12178       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
12179     Opcode = N1.getOpcode();
12180     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12181         Opcode != ISD::FADD && Opcode != ISD::FSUB)
12182       return SDValue();
12183     std::swap(N0, N1);
12184   }
12185 
12186   if (N0 == N1)
12187     return SDValue();
12188 
12189   EVT VT = N->getValueType(0);
12190   SDLoc DL(N);
12191   SDValue N00 = N0->getOperand(0);
12192   SDValue N01 = N0->getOperand(1);
12193   return DAG.getNode(Opcode, DL, VT,
12194                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
12195                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
12196 }
12197 
12198 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
12199                                       const ARMSubtarget *Subtarget) {
12200   EVT VT = N->getValueType(0);
12201   if (VT != MVT::v2i64)
12202     return SDValue();
12203 
12204   SDValue N0 = N->getOperand(0);
12205   SDValue N1 = N->getOperand(1);
12206 
12207   auto IsSignExt = [&](SDValue Op) {
12208     if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
12209       return SDValue();
12210     EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
12211     if (VT.getScalarSizeInBits() == 32)
12212       return Op->getOperand(0);
12213     return SDValue();
12214   };
12215   auto IsZeroExt = [&](SDValue Op) {
12216     // Zero extends are a little more awkward. At the point we are matching
12217     // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
12218     // That might be before of after a bitcast depending on how the and is
12219     // placed. Because this has to look through bitcasts, it is currently only
12220     // supported on LE.
12221     if (!Subtarget->isLittle())
12222       return SDValue();
12223 
12224     SDValue And = Op;
12225     if (And->getOpcode() == ISD::BITCAST)
12226       And = And->getOperand(0);
12227     if (And->getOpcode() != ISD::AND)
12228       return SDValue();
12229     SDValue Mask = And->getOperand(1);
12230     if (Mask->getOpcode() == ISD::BITCAST)
12231       Mask = Mask->getOperand(0);
12232 
12233     if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
12234         Mask.getValueType() != MVT::v4i32)
12235       return SDValue();
12236     if (isAllOnesConstant(Mask->getOperand(0)) &&
12237         isNullConstant(Mask->getOperand(1)) &&
12238         isAllOnesConstant(Mask->getOperand(2)) &&
12239         isNullConstant(Mask->getOperand(3)))
12240       return And->getOperand(0);
12241     return SDValue();
12242   };
12243 
12244   SDLoc dl(N);
12245   if (SDValue Op0 = IsSignExt(N0)) {
12246     if (SDValue Op1 = IsSignExt(N1)) {
12247       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12248       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12249       return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
12250     }
12251   }
12252   if (SDValue Op0 = IsZeroExt(N0)) {
12253     if (SDValue Op1 = IsZeroExt(N1)) {
12254       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12255       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12256       return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
12257     }
12258   }
12259 
12260   return SDValue();
12261 }
12262 
12263 static SDValue PerformMULCombine(SDNode *N,
12264                                  TargetLowering::DAGCombinerInfo &DCI,
12265                                  const ARMSubtarget *Subtarget) {
12266   SelectionDAG &DAG = DCI.DAG;
12267 
12268   EVT VT = N->getValueType(0);
12269   if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
12270     return PerformMVEVMULLCombine(N, DAG, Subtarget);
12271 
12272   if (Subtarget->isThumb1Only())
12273     return SDValue();
12274 
12275   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12276     return SDValue();
12277 
12278   if (VT.is64BitVector() || VT.is128BitVector())
12279     return PerformVMULCombine(N, DCI, Subtarget);
12280   if (VT != MVT::i32)
12281     return SDValue();
12282 
12283   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12284   if (!C)
12285     return SDValue();
12286 
12287   int64_t MulAmt = C->getSExtValue();
12288   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
12289 
12290   ShiftAmt = ShiftAmt & (32 - 1);
12291   SDValue V = N->getOperand(0);
12292   SDLoc DL(N);
12293 
12294   SDValue Res;
12295   MulAmt >>= ShiftAmt;
12296 
12297   if (MulAmt >= 0) {
12298     if (isPowerOf2_32(MulAmt - 1)) {
12299       // (mul x, 2^N + 1) => (add (shl x, N), x)
12300       Res = DAG.getNode(ISD::ADD, DL, VT,
12301                         V,
12302                         DAG.getNode(ISD::SHL, DL, VT,
12303                                     V,
12304                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
12305                                                     MVT::i32)));
12306     } else if (isPowerOf2_32(MulAmt + 1)) {
12307       // (mul x, 2^N - 1) => (sub (shl x, N), x)
12308       Res = DAG.getNode(ISD::SUB, DL, VT,
12309                         DAG.getNode(ISD::SHL, DL, VT,
12310                                     V,
12311                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
12312                                                     MVT::i32)),
12313                         V);
12314     } else
12315       return SDValue();
12316   } else {
12317     uint64_t MulAmtAbs = -MulAmt;
12318     if (isPowerOf2_32(MulAmtAbs + 1)) {
12319       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
12320       Res = DAG.getNode(ISD::SUB, DL, VT,
12321                         V,
12322                         DAG.getNode(ISD::SHL, DL, VT,
12323                                     V,
12324                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
12325                                                     MVT::i32)));
12326     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
12327       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
12328       Res = DAG.getNode(ISD::ADD, DL, VT,
12329                         V,
12330                         DAG.getNode(ISD::SHL, DL, VT,
12331                                     V,
12332                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
12333                                                     MVT::i32)));
12334       Res = DAG.getNode(ISD::SUB, DL, VT,
12335                         DAG.getConstant(0, DL, MVT::i32), Res);
12336     } else
12337       return SDValue();
12338   }
12339 
12340   if (ShiftAmt != 0)
12341     Res = DAG.getNode(ISD::SHL, DL, VT,
12342                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
12343 
12344   // Do not add new nodes to DAG combiner worklist.
12345   DCI.CombineTo(N, Res, false);
12346   return SDValue();
12347 }
12348 
12349 static SDValue CombineANDShift(SDNode *N,
12350                                TargetLowering::DAGCombinerInfo &DCI,
12351                                const ARMSubtarget *Subtarget) {
12352   // Allow DAGCombine to pattern-match before we touch the canonical form.
12353   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12354     return SDValue();
12355 
12356   if (N->getValueType(0) != MVT::i32)
12357     return SDValue();
12358 
12359   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12360   if (!N1C)
12361     return SDValue();
12362 
12363   uint32_t C1 = (uint32_t)N1C->getZExtValue();
12364   // Don't transform uxtb/uxth.
12365   if (C1 == 255 || C1 == 65535)
12366     return SDValue();
12367 
12368   SDNode *N0 = N->getOperand(0).getNode();
12369   if (!N0->hasOneUse())
12370     return SDValue();
12371 
12372   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
12373     return SDValue();
12374 
12375   bool LeftShift = N0->getOpcode() == ISD::SHL;
12376 
12377   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12378   if (!N01C)
12379     return SDValue();
12380 
12381   uint32_t C2 = (uint32_t)N01C->getZExtValue();
12382   if (!C2 || C2 >= 32)
12383     return SDValue();
12384 
12385   // Clear irrelevant bits in the mask.
12386   if (LeftShift)
12387     C1 &= (-1U << C2);
12388   else
12389     C1 &= (-1U >> C2);
12390 
12391   SelectionDAG &DAG = DCI.DAG;
12392   SDLoc DL(N);
12393 
12394   // We have a pattern of the form "(and (shl x, c2) c1)" or
12395   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
12396   // transform to a pair of shifts, to save materializing c1.
12397 
12398   // First pattern: right shift, then mask off leading bits.
12399   // FIXME: Use demanded bits?
12400   if (!LeftShift && isMask_32(C1)) {
12401     uint32_t C3 = countLeadingZeros(C1);
12402     if (C2 < C3) {
12403       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12404                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12405       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12406                          DAG.getConstant(C3, DL, MVT::i32));
12407     }
12408   }
12409 
12410   // First pattern, reversed: left shift, then mask off trailing bits.
12411   if (LeftShift && isMask_32(~C1)) {
12412     uint32_t C3 = countTrailingZeros(C1);
12413     if (C2 < C3) {
12414       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12415                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12416       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12417                          DAG.getConstant(C3, DL, MVT::i32));
12418     }
12419   }
12420 
12421   // Second pattern: left shift, then mask off leading bits.
12422   // FIXME: Use demanded bits?
12423   if (LeftShift && isShiftedMask_32(C1)) {
12424     uint32_t Trailing = countTrailingZeros(C1);
12425     uint32_t C3 = countLeadingZeros(C1);
12426     if (Trailing == C2 && C2 + C3 < 32) {
12427       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12428                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12429       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12430                         DAG.getConstant(C3, DL, MVT::i32));
12431     }
12432   }
12433 
12434   // Second pattern, reversed: right shift, then mask off trailing bits.
12435   // FIXME: Handle other patterns of known/demanded bits.
12436   if (!LeftShift && isShiftedMask_32(C1)) {
12437     uint32_t Leading = countLeadingZeros(C1);
12438     uint32_t C3 = countTrailingZeros(C1);
12439     if (Leading == C2 && C2 + C3 < 32) {
12440       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12441                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12442       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12443                          DAG.getConstant(C3, DL, MVT::i32));
12444     }
12445   }
12446 
12447   // FIXME: Transform "(and (shl x, c2) c1)" ->
12448   // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
12449   // c1.
12450   return SDValue();
12451 }
12452 
12453 static SDValue PerformANDCombine(SDNode *N,
12454                                  TargetLowering::DAGCombinerInfo &DCI,
12455                                  const ARMSubtarget *Subtarget) {
12456   // Attempt to use immediate-form VBIC
12457   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12458   SDLoc dl(N);
12459   EVT VT = N->getValueType(0);
12460   SelectionDAG &DAG = DCI.DAG;
12461 
12462   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v4i1 ||
12463       VT == MVT::v8i1 || VT == MVT::v16i1)
12464     return SDValue();
12465 
12466   APInt SplatBits, SplatUndef;
12467   unsigned SplatBitSize;
12468   bool HasAnyUndefs;
12469   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
12470       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12471     if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
12472         SplatBitSize == 64) {
12473       EVT VbicVT;
12474       SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
12475                                       SplatUndef.getZExtValue(), SplatBitSize,
12476                                       DAG, dl, VbicVT, VT, OtherModImm);
12477       if (Val.getNode()) {
12478         SDValue Input =
12479           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
12480         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
12481         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
12482       }
12483     }
12484   }
12485 
12486   if (!Subtarget->isThumb1Only()) {
12487     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
12488     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
12489       return Result;
12490 
12491     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12492       return Result;
12493   }
12494 
12495   if (Subtarget->isThumb1Only())
12496     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
12497       return Result;
12498 
12499   return SDValue();
12500 }
12501 
12502 // Try combining OR nodes to SMULWB, SMULWT.
12503 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
12504                                          TargetLowering::DAGCombinerInfo &DCI,
12505                                          const ARMSubtarget *Subtarget) {
12506   if (!Subtarget->hasV6Ops() ||
12507       (Subtarget->isThumb() &&
12508        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
12509     return SDValue();
12510 
12511   SDValue SRL = OR->getOperand(0);
12512   SDValue SHL = OR->getOperand(1);
12513 
12514   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
12515     SRL = OR->getOperand(1);
12516     SHL = OR->getOperand(0);
12517   }
12518   if (!isSRL16(SRL) || !isSHL16(SHL))
12519     return SDValue();
12520 
12521   // The first operands to the shifts need to be the two results from the
12522   // same smul_lohi node.
12523   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
12524        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
12525     return SDValue();
12526 
12527   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
12528   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
12529       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
12530     return SDValue();
12531 
12532   // Now we have:
12533   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
12534   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
12535   // For SMUWB the 16-bit value will signed extended somehow.
12536   // For SMULWT only the SRA is required.
12537   // Check both sides of SMUL_LOHI
12538   SDValue OpS16 = SMULLOHI->getOperand(0);
12539   SDValue OpS32 = SMULLOHI->getOperand(1);
12540 
12541   SelectionDAG &DAG = DCI.DAG;
12542   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
12543     OpS16 = OpS32;
12544     OpS32 = SMULLOHI->getOperand(0);
12545   }
12546 
12547   SDLoc dl(OR);
12548   unsigned Opcode = 0;
12549   if (isS16(OpS16, DAG))
12550     Opcode = ARMISD::SMULWB;
12551   else if (isSRA16(OpS16)) {
12552     Opcode = ARMISD::SMULWT;
12553     OpS16 = OpS16->getOperand(0);
12554   }
12555   else
12556     return SDValue();
12557 
12558   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
12559   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
12560   return SDValue(OR, 0);
12561 }
12562 
12563 static SDValue PerformORCombineToBFI(SDNode *N,
12564                                      TargetLowering::DAGCombinerInfo &DCI,
12565                                      const ARMSubtarget *Subtarget) {
12566   // BFI is only available on V6T2+
12567   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
12568     return SDValue();
12569 
12570   EVT VT = N->getValueType(0);
12571   SDValue N0 = N->getOperand(0);
12572   SDValue N1 = N->getOperand(1);
12573   SelectionDAG &DAG = DCI.DAG;
12574   SDLoc DL(N);
12575   // 1) or (and A, mask), val => ARMbfi A, val, mask
12576   //      iff (val & mask) == val
12577   //
12578   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12579   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
12580   //          && mask == ~mask2
12581   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
12582   //          && ~mask == mask2
12583   //  (i.e., copy a bitfield value into another bitfield of the same width)
12584 
12585   if (VT != MVT::i32)
12586     return SDValue();
12587 
12588   SDValue N00 = N0.getOperand(0);
12589 
12590   // The value and the mask need to be constants so we can verify this is
12591   // actually a bitfield set. If the mask is 0xffff, we can do better
12592   // via a movt instruction, so don't use BFI in that case.
12593   SDValue MaskOp = N0.getOperand(1);
12594   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
12595   if (!MaskC)
12596     return SDValue();
12597   unsigned Mask = MaskC->getZExtValue();
12598   if (Mask == 0xffff)
12599     return SDValue();
12600   SDValue Res;
12601   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
12602   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12603   if (N1C) {
12604     unsigned Val = N1C->getZExtValue();
12605     if ((Val & ~Mask) != Val)
12606       return SDValue();
12607 
12608     if (ARM::isBitFieldInvertedMask(Mask)) {
12609       Val >>= countTrailingZeros(~Mask);
12610 
12611       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
12612                         DAG.getConstant(Val, DL, MVT::i32),
12613                         DAG.getConstant(Mask, DL, MVT::i32));
12614 
12615       DCI.CombineTo(N, Res, false);
12616       // Return value from the original node to inform the combiner than N is
12617       // now dead.
12618       return SDValue(N, 0);
12619     }
12620   } else if (N1.getOpcode() == ISD::AND) {
12621     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12622     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12623     if (!N11C)
12624       return SDValue();
12625     unsigned Mask2 = N11C->getZExtValue();
12626 
12627     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
12628     // as is to match.
12629     if (ARM::isBitFieldInvertedMask(Mask) &&
12630         (Mask == ~Mask2)) {
12631       // The pack halfword instruction works better for masks that fit it,
12632       // so use that when it's available.
12633       if (Subtarget->hasDSP() &&
12634           (Mask == 0xffff || Mask == 0xffff0000))
12635         return SDValue();
12636       // 2a
12637       unsigned amt = countTrailingZeros(Mask2);
12638       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
12639                         DAG.getConstant(amt, DL, MVT::i32));
12640       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
12641                         DAG.getConstant(Mask, DL, MVT::i32));
12642       DCI.CombineTo(N, Res, false);
12643       // Return value from the original node to inform the combiner than N is
12644       // now dead.
12645       return SDValue(N, 0);
12646     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
12647                (~Mask == Mask2)) {
12648       // The pack halfword instruction works better for masks that fit it,
12649       // so use that when it's available.
12650       if (Subtarget->hasDSP() &&
12651           (Mask2 == 0xffff || Mask2 == 0xffff0000))
12652         return SDValue();
12653       // 2b
12654       unsigned lsb = countTrailingZeros(Mask);
12655       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
12656                         DAG.getConstant(lsb, DL, MVT::i32));
12657       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
12658                         DAG.getConstant(Mask2, DL, MVT::i32));
12659       DCI.CombineTo(N, Res, false);
12660       // Return value from the original node to inform the combiner than N is
12661       // now dead.
12662       return SDValue(N, 0);
12663     }
12664   }
12665 
12666   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
12667       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
12668       ARM::isBitFieldInvertedMask(~Mask)) {
12669     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
12670     // where lsb(mask) == #shamt and masked bits of B are known zero.
12671     SDValue ShAmt = N00.getOperand(1);
12672     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
12673     unsigned LSB = countTrailingZeros(Mask);
12674     if (ShAmtC != LSB)
12675       return SDValue();
12676 
12677     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
12678                       DAG.getConstant(~Mask, DL, MVT::i32));
12679 
12680     DCI.CombineTo(N, Res, false);
12681     // Return value from the original node to inform the combiner than N is
12682     // now dead.
12683     return SDValue(N, 0);
12684   }
12685 
12686   return SDValue();
12687 }
12688 
12689 static bool isValidMVECond(unsigned CC, bool IsFloat) {
12690   switch (CC) {
12691   case ARMCC::EQ:
12692   case ARMCC::NE:
12693   case ARMCC::LE:
12694   case ARMCC::GT:
12695   case ARMCC::GE:
12696   case ARMCC::LT:
12697     return true;
12698   case ARMCC::HS:
12699   case ARMCC::HI:
12700     return !IsFloat;
12701   default:
12702     return false;
12703   };
12704 }
12705 
12706 static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
12707   if (N->getOpcode() == ARMISD::VCMP)
12708     return (ARMCC::CondCodes)N->getConstantOperandVal(2);
12709   else if (N->getOpcode() == ARMISD::VCMPZ)
12710     return (ARMCC::CondCodes)N->getConstantOperandVal(1);
12711   else
12712     llvm_unreachable("Not a VCMP/VCMPZ!");
12713 }
12714 
12715 static bool CanInvertMVEVCMP(SDValue N) {
12716   ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N));
12717   return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
12718 }
12719 
12720 static SDValue PerformORCombine_i1(SDNode *N,
12721                                    TargetLowering::DAGCombinerInfo &DCI,
12722                                    const ARMSubtarget *Subtarget) {
12723   // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
12724   // together with predicates
12725   EVT VT = N->getValueType(0);
12726   SDLoc DL(N);
12727   SDValue N0 = N->getOperand(0);
12728   SDValue N1 = N->getOperand(1);
12729 
12730   auto IsFreelyInvertable = [&](SDValue V) {
12731     if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
12732       return CanInvertMVEVCMP(V);
12733     return false;
12734   };
12735 
12736   // At least one operand must be freely invertable.
12737   if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
12738     return SDValue();
12739 
12740   SDValue NewN0 = DCI.DAG.getLogicalNOT(DL, N0, VT);
12741   SDValue NewN1 = DCI.DAG.getLogicalNOT(DL, N1, VT);
12742   SDValue And = DCI.DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
12743   return DCI.DAG.getLogicalNOT(DL, And, VT);
12744 }
12745 
12746 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
12747 static SDValue PerformORCombine(SDNode *N,
12748                                 TargetLowering::DAGCombinerInfo &DCI,
12749                                 const ARMSubtarget *Subtarget) {
12750   // Attempt to use immediate-form VORR
12751   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12752   SDLoc dl(N);
12753   EVT VT = N->getValueType(0);
12754   SelectionDAG &DAG = DCI.DAG;
12755 
12756   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12757     return SDValue();
12758 
12759   if (Subtarget->hasMVEIntegerOps() &&
12760       (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
12761     return PerformORCombine_i1(N, DCI, Subtarget);
12762 
12763   APInt SplatBits, SplatUndef;
12764   unsigned SplatBitSize;
12765   bool HasAnyUndefs;
12766   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
12767       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12768     if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
12769         SplatBitSize == 64) {
12770       EVT VorrVT;
12771       SDValue Val =
12772           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
12773                             SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
12774       if (Val.getNode()) {
12775         SDValue Input =
12776           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
12777         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
12778         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
12779       }
12780     }
12781   }
12782 
12783   if (!Subtarget->isThumb1Only()) {
12784     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12785     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12786       return Result;
12787     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
12788       return Result;
12789   }
12790 
12791   SDValue N0 = N->getOperand(0);
12792   SDValue N1 = N->getOperand(1);
12793 
12794   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
12795   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
12796       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12797 
12798     // The code below optimizes (or (and X, Y), Z).
12799     // The AND operand needs to have a single user to make these optimizations
12800     // profitable.
12801     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
12802       return SDValue();
12803 
12804     APInt SplatUndef;
12805     unsigned SplatBitSize;
12806     bool HasAnyUndefs;
12807 
12808     APInt SplatBits0, SplatBits1;
12809     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
12810     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
12811     // Ensure that the second operand of both ands are constants
12812     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
12813                                       HasAnyUndefs) && !HasAnyUndefs) {
12814         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
12815                                           HasAnyUndefs) && !HasAnyUndefs) {
12816             // Ensure that the bit width of the constants are the same and that
12817             // the splat arguments are logical inverses as per the pattern we
12818             // are trying to simplify.
12819             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
12820                 SplatBits0 == ~SplatBits1) {
12821                 // Canonicalize the vector type to make instruction selection
12822                 // simpler.
12823                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
12824                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
12825                                              N0->getOperand(1),
12826                                              N0->getOperand(0),
12827                                              N1->getOperand(0));
12828                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12829             }
12830         }
12831     }
12832   }
12833 
12834   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
12835   // reasonable.
12836   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
12837     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
12838       return Res;
12839   }
12840 
12841   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12842     return Result;
12843 
12844   return SDValue();
12845 }
12846 
12847 static SDValue PerformXORCombine(SDNode *N,
12848                                  TargetLowering::DAGCombinerInfo &DCI,
12849                                  const ARMSubtarget *Subtarget) {
12850   EVT VT = N->getValueType(0);
12851   SelectionDAG &DAG = DCI.DAG;
12852 
12853   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12854     return SDValue();
12855 
12856   if (!Subtarget->isThumb1Only()) {
12857     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12858     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12859       return Result;
12860 
12861     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12862       return Result;
12863   }
12864 
12865   if (Subtarget->hasMVEIntegerOps()) {
12866     // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
12867     SDValue N0 = N->getOperand(0);
12868     SDValue N1 = N->getOperand(1);
12869     const TargetLowering *TLI = Subtarget->getTargetLowering();
12870     if (TLI->isConstTrueVal(N1.getNode()) &&
12871         (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
12872       if (CanInvertMVEVCMP(N0)) {
12873         SDLoc DL(N0);
12874         ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0));
12875 
12876         SmallVector<SDValue, 4> Ops;
12877         Ops.push_back(N0->getOperand(0));
12878         if (N0->getOpcode() == ARMISD::VCMP)
12879           Ops.push_back(N0->getOperand(1));
12880         Ops.push_back(DCI.DAG.getConstant(CC, DL, MVT::i32));
12881         return DCI.DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
12882       }
12883     }
12884   }
12885 
12886   return SDValue();
12887 }
12888 
12889 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12890 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12891 // their position in "to" (Rd).
12892 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12893   assert(N->getOpcode() == ARMISD::BFI);
12894 
12895   SDValue From = N->getOperand(1);
12896   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12897   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12898 
12899   // If the Base came from a SHR #C, we can deduce that it is really testing bit
12900   // #C in the base of the SHR.
12901   if (From->getOpcode() == ISD::SRL &&
12902       isa<ConstantSDNode>(From->getOperand(1))) {
12903     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12904     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12905     FromMask <<= Shift.getLimitedValue(31);
12906     From = From->getOperand(0);
12907   }
12908 
12909   return From;
12910 }
12911 
12912 // If A and B contain one contiguous set of bits, does A | B == A . B?
12913 //
12914 // Neither A nor B must be zero.
12915 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12916   unsigned LastActiveBitInA =  A.countTrailingZeros();
12917   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12918   return LastActiveBitInA - 1 == FirstActiveBitInB;
12919 }
12920 
12921 static SDValue FindBFIToCombineWith(SDNode *N) {
12922   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12923   // if one exists.
12924   APInt ToMask, FromMask;
12925   SDValue From = ParseBFI(N, ToMask, FromMask);
12926   SDValue To = N->getOperand(0);
12927 
12928   // Now check for a compatible BFI to merge with. We can pass through BFIs that
12929   // aren't compatible, but not if they set the same bit in their destination as
12930   // we do (or that of any BFI we're going to combine with).
12931   SDValue V = To;
12932   APInt CombinedToMask = ToMask;
12933   while (V.getOpcode() == ARMISD::BFI) {
12934     APInt NewToMask, NewFromMask;
12935     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12936     if (NewFrom != From) {
12937       // This BFI has a different base. Keep going.
12938       CombinedToMask |= NewToMask;
12939       V = V.getOperand(0);
12940       continue;
12941     }
12942 
12943     // Do the written bits conflict with any we've seen so far?
12944     if ((NewToMask & CombinedToMask).getBoolValue())
12945       // Conflicting bits - bail out because going further is unsafe.
12946       return SDValue();
12947 
12948     // Are the new bits contiguous when combined with the old bits?
12949     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12950         BitsProperlyConcatenate(FromMask, NewFromMask))
12951       return V;
12952     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12953         BitsProperlyConcatenate(NewFromMask, FromMask))
12954       return V;
12955 
12956     // We've seen a write to some bits, so track it.
12957     CombinedToMask |= NewToMask;
12958     // Keep going...
12959     V = V.getOperand(0);
12960   }
12961 
12962   return SDValue();
12963 }
12964 
12965 static SDValue PerformBFICombine(SDNode *N,
12966                                  TargetLowering::DAGCombinerInfo &DCI) {
12967   SDValue N1 = N->getOperand(1);
12968   if (N1.getOpcode() == ISD::AND) {
12969     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12970     // the bits being cleared by the AND are not demanded by the BFI.
12971     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12972     if (!N11C)
12973       return SDValue();
12974     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12975     unsigned LSB = countTrailingZeros(~InvMask);
12976     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12977     assert(Width <
12978                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12979            "undefined behavior");
12980     unsigned Mask = (1u << Width) - 1;
12981     unsigned Mask2 = N11C->getZExtValue();
12982     if ((Mask & (~Mask2)) == 0)
12983       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12984                              N->getOperand(0), N1.getOperand(0),
12985                              N->getOperand(2));
12986   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12987     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12988     // Keep track of any consecutive bits set that all come from the same base
12989     // value. We can combine these together into a single BFI.
12990     SDValue CombineBFI = FindBFIToCombineWith(N);
12991     if (CombineBFI == SDValue())
12992       return SDValue();
12993 
12994     // We've found a BFI.
12995     APInt ToMask1, FromMask1;
12996     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12997 
12998     APInt ToMask2, FromMask2;
12999     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
13000     assert(From1 == From2);
13001     (void)From2;
13002 
13003     // First, unlink CombineBFI.
13004     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
13005     // Then create a new BFI, combining the two together.
13006     APInt NewFromMask = FromMask1 | FromMask2;
13007     APInt NewToMask = ToMask1 | ToMask2;
13008 
13009     EVT VT = N->getValueType(0);
13010     SDLoc dl(N);
13011 
13012     if (NewFromMask[0] == 0)
13013       From1 = DCI.DAG.getNode(
13014         ISD::SRL, dl, VT, From1,
13015         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
13016     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
13017                            DCI.DAG.getConstant(~NewToMask, dl, VT));
13018   }
13019   return SDValue();
13020 }
13021 
13022 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
13023 /// ARMISD::VMOVRRD.
13024 static SDValue PerformVMOVRRDCombine(SDNode *N,
13025                                      TargetLowering::DAGCombinerInfo &DCI,
13026                                      const ARMSubtarget *Subtarget) {
13027   // vmovrrd(vmovdrr x, y) -> x,y
13028   SDValue InDouble = N->getOperand(0);
13029   if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
13030     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
13031 
13032   // vmovrrd(load f64) -> (load i32), (load i32)
13033   SDNode *InNode = InDouble.getNode();
13034   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
13035       InNode->getValueType(0) == MVT::f64 &&
13036       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
13037       !cast<LoadSDNode>(InNode)->isVolatile()) {
13038     // TODO: Should this be done for non-FrameIndex operands?
13039     LoadSDNode *LD = cast<LoadSDNode>(InNode);
13040 
13041     SelectionDAG &DAG = DCI.DAG;
13042     SDLoc DL(LD);
13043     SDValue BasePtr = LD->getBasePtr();
13044     SDValue NewLD1 =
13045         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
13046                     LD->getAlignment(), LD->getMemOperand()->getFlags());
13047 
13048     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13049                                     DAG.getConstant(4, DL, MVT::i32));
13050 
13051     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
13052                                  LD->getPointerInfo().getWithOffset(4),
13053                                  std::min(4U, LD->getAlignment()),
13054                                  LD->getMemOperand()->getFlags());
13055 
13056     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
13057     if (DCI.DAG.getDataLayout().isBigEndian())
13058       std::swap (NewLD1, NewLD2);
13059     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
13060     return Result;
13061   }
13062 
13063   return SDValue();
13064 }
13065 
13066 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
13067 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
13068 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
13069   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
13070   SDValue Op0 = N->getOperand(0);
13071   SDValue Op1 = N->getOperand(1);
13072   if (Op0.getOpcode() == ISD::BITCAST)
13073     Op0 = Op0.getOperand(0);
13074   if (Op1.getOpcode() == ISD::BITCAST)
13075     Op1 = Op1.getOperand(0);
13076   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
13077       Op0.getNode() == Op1.getNode() &&
13078       Op0.getResNo() == 0 && Op1.getResNo() == 1)
13079     return DAG.getNode(ISD::BITCAST, SDLoc(N),
13080                        N->getValueType(0), Op0.getOperand(0));
13081   return SDValue();
13082 }
13083 
13084 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13085   SDValue Op0 = N->getOperand(0);
13086 
13087   // VMOVhr (VMOVrh (X)) -> X
13088   if (Op0->getOpcode() == ARMISD::VMOVrh)
13089     return Op0->getOperand(0);
13090 
13091   // FullFP16: half values are passed in S-registers, and we don't
13092   // need any of the bitcast and moves:
13093   //
13094   //     t2: f32,ch = CopyFromReg t0, Register:f32 %0
13095   //   t5: i32 = bitcast t2
13096   // t18: f16 = ARMISD::VMOVhr t5
13097   if (Op0->getOpcode() == ISD::BITCAST) {
13098     SDValue Copy = Op0->getOperand(0);
13099     if (Copy.getValueType() == MVT::f32 &&
13100         Copy->getOpcode() == ISD::CopyFromReg) {
13101       SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)};
13102       SDValue NewCopy =
13103           DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), MVT::f16, Ops);
13104       return NewCopy;
13105     }
13106   }
13107 
13108   // fold (VMOVhr (load x)) -> (load (f16*)x)
13109   if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
13110     if (LN0->hasOneUse() && LN0->isUnindexed() &&
13111         LN0->getMemoryVT() == MVT::i16) {
13112       SDValue Load = DCI.DAG.getLoad(MVT::f16, SDLoc(N), LN0->getChain(),
13113                                      LN0->getBasePtr(), LN0->getMemOperand());
13114       DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13115       DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
13116       return Load;
13117     }
13118   }
13119 
13120   // Only the bottom 16 bits of the source register are used.
13121   APInt DemandedMask = APInt::getLowBitsSet(32, 16);
13122   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
13123   if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
13124     return SDValue(N, 0);
13125 
13126   return SDValue();
13127 }
13128 
13129 static SDValue PerformVMOVrhCombine(SDNode *N,
13130                                     TargetLowering::DAGCombinerInfo &DCI) {
13131   SDValue N0 = N->getOperand(0);
13132   EVT VT = N->getValueType(0);
13133 
13134   // fold (VMOVrh (load x)) -> (zextload (i16*)x)
13135   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
13136     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
13137 
13138     SDValue Load =
13139         DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
13140                            LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
13141     DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13142     DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
13143     return Load;
13144   }
13145 
13146   // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
13147   if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
13148       isa<ConstantSDNode>(N0->getOperand(1)))
13149     return DCI.DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
13150                            N0->getOperand(1));
13151 
13152   return SDValue();
13153 }
13154 
13155 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
13156 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
13157 /// i64 vector to have f64 elements, since the value can then be loaded
13158 /// directly into a VFP register.
13159 static bool hasNormalLoadOperand(SDNode *N) {
13160   unsigned NumElts = N->getValueType(0).getVectorNumElements();
13161   for (unsigned i = 0; i < NumElts; ++i) {
13162     SDNode *Elt = N->getOperand(i).getNode();
13163     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
13164       return true;
13165   }
13166   return false;
13167 }
13168 
13169 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
13170 /// ISD::BUILD_VECTOR.
13171 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
13172                                           TargetLowering::DAGCombinerInfo &DCI,
13173                                           const ARMSubtarget *Subtarget) {
13174   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
13175   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
13176   // into a pair of GPRs, which is fine when the value is used as a scalar,
13177   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
13178   SelectionDAG &DAG = DCI.DAG;
13179   if (N->getNumOperands() == 2)
13180     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
13181       return RV;
13182 
13183   // Load i64 elements as f64 values so that type legalization does not split
13184   // them up into i32 values.
13185   EVT VT = N->getValueType(0);
13186   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
13187     return SDValue();
13188   SDLoc dl(N);
13189   SmallVector<SDValue, 8> Ops;
13190   unsigned NumElts = VT.getVectorNumElements();
13191   for (unsigned i = 0; i < NumElts; ++i) {
13192     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
13193     Ops.push_back(V);
13194     // Make the DAGCombiner fold the bitcast.
13195     DCI.AddToWorklist(V.getNode());
13196   }
13197   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
13198   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
13199   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
13200 }
13201 
13202 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
13203 static SDValue
13204 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13205   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
13206   // At that time, we may have inserted bitcasts from integer to float.
13207   // If these bitcasts have survived DAGCombine, change the lowering of this
13208   // BUILD_VECTOR in something more vector friendly, i.e., that does not
13209   // force to use floating point types.
13210 
13211   // Make sure we can change the type of the vector.
13212   // This is possible iff:
13213   // 1. The vector is only used in a bitcast to a integer type. I.e.,
13214   //    1.1. Vector is used only once.
13215   //    1.2. Use is a bit convert to an integer type.
13216   // 2. The size of its operands are 32-bits (64-bits are not legal).
13217   EVT VT = N->getValueType(0);
13218   EVT EltVT = VT.getVectorElementType();
13219 
13220   // Check 1.1. and 2.
13221   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
13222     return SDValue();
13223 
13224   // By construction, the input type must be float.
13225   assert(EltVT == MVT::f32 && "Unexpected type!");
13226 
13227   // Check 1.2.
13228   SDNode *Use = *N->use_begin();
13229   if (Use->getOpcode() != ISD::BITCAST ||
13230       Use->getValueType(0).isFloatingPoint())
13231     return SDValue();
13232 
13233   // Check profitability.
13234   // Model is, if more than half of the relevant operands are bitcast from
13235   // i32, turn the build_vector into a sequence of insert_vector_elt.
13236   // Relevant operands are everything that is not statically
13237   // (i.e., at compile time) bitcasted.
13238   unsigned NumOfBitCastedElts = 0;
13239   unsigned NumElts = VT.getVectorNumElements();
13240   unsigned NumOfRelevantElts = NumElts;
13241   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
13242     SDValue Elt = N->getOperand(Idx);
13243     if (Elt->getOpcode() == ISD::BITCAST) {
13244       // Assume only bit cast to i32 will go away.
13245       if (Elt->getOperand(0).getValueType() == MVT::i32)
13246         ++NumOfBitCastedElts;
13247     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
13248       // Constants are statically casted, thus do not count them as
13249       // relevant operands.
13250       --NumOfRelevantElts;
13251   }
13252 
13253   // Check if more than half of the elements require a non-free bitcast.
13254   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
13255     return SDValue();
13256 
13257   SelectionDAG &DAG = DCI.DAG;
13258   // Create the new vector type.
13259   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
13260   // Check if the type is legal.
13261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13262   if (!TLI.isTypeLegal(VecVT))
13263     return SDValue();
13264 
13265   // Combine:
13266   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
13267   // => BITCAST INSERT_VECTOR_ELT
13268   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
13269   //                      (BITCAST EN), N.
13270   SDValue Vec = DAG.getUNDEF(VecVT);
13271   SDLoc dl(N);
13272   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
13273     SDValue V = N->getOperand(Idx);
13274     if (V.isUndef())
13275       continue;
13276     if (V.getOpcode() == ISD::BITCAST &&
13277         V->getOperand(0).getValueType() == MVT::i32)
13278       // Fold obvious case.
13279       V = V.getOperand(0);
13280     else {
13281       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
13282       // Make the DAGCombiner fold the bitcasts.
13283       DCI.AddToWorklist(V.getNode());
13284     }
13285     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
13286     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
13287   }
13288   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
13289   // Make the DAGCombiner fold the bitcasts.
13290   DCI.AddToWorklist(Vec.getNode());
13291   return Vec;
13292 }
13293 
13294 static SDValue
13295 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13296   EVT VT = N->getValueType(0);
13297   SDValue Op = N->getOperand(0);
13298   SDLoc dl(N);
13299 
13300   // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
13301   if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
13302     // If the valuetypes are the same, we can remove the cast entirely.
13303     if (Op->getOperand(0).getValueType() == VT)
13304       return Op->getOperand(0);
13305     return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
13306   }
13307 
13308   return SDValue();
13309 }
13310 
13311 static SDValue
13312 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13313                               const ARMSubtarget *ST) {
13314   EVT VT = N->getValueType(0);
13315   SDValue Op = N->getOperand(0);
13316   SDLoc dl(N);
13317 
13318   // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
13319   if (ST->isLittle())
13320     return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op);
13321 
13322   // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
13323   if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
13324     // If the valuetypes are the same, we can remove the cast entirely.
13325     if (Op->getOperand(0).getValueType() == VT)
13326       return Op->getOperand(0);
13327     return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
13328   }
13329 
13330   return SDValue();
13331 }
13332 
13333 static SDValue PerformVCMPCombine(SDNode *N,
13334                                   TargetLowering::DAGCombinerInfo &DCI,
13335                                   const ARMSubtarget *Subtarget) {
13336   if (!Subtarget->hasMVEIntegerOps())
13337     return SDValue();
13338 
13339   EVT VT = N->getValueType(0);
13340   SDValue Op0 = N->getOperand(0);
13341   SDValue Op1 = N->getOperand(1);
13342   ARMCC::CondCodes Cond =
13343       (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13344   SDLoc dl(N);
13345 
13346   // vcmp X, 0, cc -> vcmpz X, cc
13347   if (isZeroVector(Op1))
13348     return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0,
13349                            N->getOperand(2));
13350 
13351   unsigned SwappedCond = getSwappedCondition(Cond);
13352   if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
13353     // vcmp 0, X, cc -> vcmpz X, reversed(cc)
13354     if (isZeroVector(Op0))
13355       return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
13356                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13357     // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
13358     if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
13359       return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
13360                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13361   }
13362 
13363   return SDValue();
13364 }
13365 
13366 /// PerformInsertEltCombine - Target-specific dag combine xforms for
13367 /// ISD::INSERT_VECTOR_ELT.
13368 static SDValue PerformInsertEltCombine(SDNode *N,
13369                                        TargetLowering::DAGCombinerInfo &DCI) {
13370   // Bitcast an i64 load inserted into a vector to f64.
13371   // Otherwise, the i64 value will be legalized to a pair of i32 values.
13372   EVT VT = N->getValueType(0);
13373   SDNode *Elt = N->getOperand(1).getNode();
13374   if (VT.getVectorElementType() != MVT::i64 ||
13375       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
13376     return SDValue();
13377 
13378   SelectionDAG &DAG = DCI.DAG;
13379   SDLoc dl(N);
13380   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13381                                  VT.getVectorNumElements());
13382   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
13383   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
13384   // Make the DAGCombiner fold the bitcasts.
13385   DCI.AddToWorklist(Vec.getNode());
13386   DCI.AddToWorklist(V.getNode());
13387   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
13388                                Vec, V, N->getOperand(2));
13389   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
13390 }
13391 
13392 static SDValue PerformExtractEltCombine(SDNode *N,
13393                                         TargetLowering::DAGCombinerInfo &DCI) {
13394   SDValue Op0 = N->getOperand(0);
13395   EVT VT = N->getValueType(0);
13396   SDLoc dl(N);
13397 
13398   // extract (vdup x) -> x
13399   if (Op0->getOpcode() == ARMISD::VDUP) {
13400     SDValue X = Op0->getOperand(0);
13401     if (VT == MVT::f16 && X.getValueType() == MVT::i32)
13402       return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
13403     if (VT == MVT::i32 && X.getValueType() == MVT::f16)
13404       return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
13405 
13406     while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
13407       X = X->getOperand(0);
13408     if (X.getValueType() == VT)
13409       return X;
13410   }
13411 
13412   return SDValue();
13413 }
13414 
13415 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
13416 /// ISD::VECTOR_SHUFFLE.
13417 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
13418   // The LLVM shufflevector instruction does not require the shuffle mask
13419   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
13420   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
13421   // operands do not match the mask length, they are extended by concatenating
13422   // them with undef vectors.  That is probably the right thing for other
13423   // targets, but for NEON it is better to concatenate two double-register
13424   // size vector operands into a single quad-register size vector.  Do that
13425   // transformation here:
13426   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
13427   //   shuffle(concat(v1, v2), undef)
13428   SDValue Op0 = N->getOperand(0);
13429   SDValue Op1 = N->getOperand(1);
13430   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
13431       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
13432       Op0.getNumOperands() != 2 ||
13433       Op1.getNumOperands() != 2)
13434     return SDValue();
13435   SDValue Concat0Op1 = Op0.getOperand(1);
13436   SDValue Concat1Op1 = Op1.getOperand(1);
13437   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
13438     return SDValue();
13439   // Skip the transformation if any of the types are illegal.
13440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13441   EVT VT = N->getValueType(0);
13442   if (!TLI.isTypeLegal(VT) ||
13443       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
13444       !TLI.isTypeLegal(Concat1Op1.getValueType()))
13445     return SDValue();
13446 
13447   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13448                                   Op0.getOperand(0), Op1.getOperand(0));
13449   // Translate the shuffle mask.
13450   SmallVector<int, 16> NewMask;
13451   unsigned NumElts = VT.getVectorNumElements();
13452   unsigned HalfElts = NumElts/2;
13453   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13454   for (unsigned n = 0; n < NumElts; ++n) {
13455     int MaskElt = SVN->getMaskElt(n);
13456     int NewElt = -1;
13457     if (MaskElt < (int)HalfElts)
13458       NewElt = MaskElt;
13459     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
13460       NewElt = HalfElts + MaskElt - NumElts;
13461     NewMask.push_back(NewElt);
13462   }
13463   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
13464                               DAG.getUNDEF(VT), NewMask);
13465 }
13466 
13467 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
13468 /// NEON load/store intrinsics, and generic vector load/stores, to merge
13469 /// base address updates.
13470 /// For generic load/stores, the memory type is assumed to be a vector.
13471 /// The caller is assumed to have checked legality.
13472 static SDValue CombineBaseUpdate(SDNode *N,
13473                                  TargetLowering::DAGCombinerInfo &DCI) {
13474   SelectionDAG &DAG = DCI.DAG;
13475   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
13476                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
13477   const bool isStore = N->getOpcode() == ISD::STORE;
13478   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
13479   SDValue Addr = N->getOperand(AddrOpIdx);
13480   MemSDNode *MemN = cast<MemSDNode>(N);
13481   SDLoc dl(N);
13482 
13483   // Search for a use of the address operand that is an increment.
13484   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
13485          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
13486     SDNode *User = *UI;
13487     if (User->getOpcode() != ISD::ADD ||
13488         UI.getUse().getResNo() != Addr.getResNo())
13489       continue;
13490 
13491     // Check that the add is independent of the load/store.  Otherwise, folding
13492     // it would create a cycle. We can avoid searching through Addr as it's a
13493     // predecessor to both.
13494     SmallPtrSet<const SDNode *, 32> Visited;
13495     SmallVector<const SDNode *, 16> Worklist;
13496     Visited.insert(Addr.getNode());
13497     Worklist.push_back(N);
13498     Worklist.push_back(User);
13499     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
13500         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13501       continue;
13502 
13503     // Find the new opcode for the updating load/store.
13504     bool isLoadOp = true;
13505     bool isLaneOp = false;
13506     unsigned NewOpc = 0;
13507     unsigned NumVecs = 0;
13508     if (isIntrinsic) {
13509       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
13510       switch (IntNo) {
13511       default: llvm_unreachable("unexpected intrinsic for Neon base update");
13512       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
13513         NumVecs = 1; break;
13514       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
13515         NumVecs = 2; break;
13516       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
13517         NumVecs = 3; break;
13518       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
13519         NumVecs = 4; break;
13520       case Intrinsic::arm_neon_vld2dup:
13521       case Intrinsic::arm_neon_vld3dup:
13522       case Intrinsic::arm_neon_vld4dup:
13523         // TODO: Support updating VLDxDUP nodes. For now, we just skip
13524         // combining base updates for such intrinsics.
13525         continue;
13526       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
13527         NumVecs = 2; isLaneOp = true; break;
13528       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
13529         NumVecs = 3; isLaneOp = true; break;
13530       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
13531         NumVecs = 4; isLaneOp = true; break;
13532       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
13533         NumVecs = 1; isLoadOp = false; break;
13534       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
13535         NumVecs = 2; isLoadOp = false; break;
13536       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
13537         NumVecs = 3; isLoadOp = false; break;
13538       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
13539         NumVecs = 4; isLoadOp = false; break;
13540       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
13541         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
13542       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
13543         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
13544       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
13545         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
13546       }
13547     } else {
13548       isLaneOp = true;
13549       switch (N->getOpcode()) {
13550       default: llvm_unreachable("unexpected opcode for Neon base update");
13551       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
13552       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
13553       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
13554       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
13555       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
13556         NumVecs = 1; isLaneOp = false; break;
13557       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
13558         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
13559       }
13560     }
13561 
13562     // Find the size of memory referenced by the load/store.
13563     EVT VecTy;
13564     if (isLoadOp) {
13565       VecTy = N->getValueType(0);
13566     } else if (isIntrinsic) {
13567       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
13568     } else {
13569       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
13570       VecTy = N->getOperand(1).getValueType();
13571     }
13572 
13573     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
13574     if (isLaneOp)
13575       NumBytes /= VecTy.getVectorNumElements();
13576 
13577     // If the increment is a constant, it must match the memory ref size.
13578     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13579     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
13580     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
13581       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
13582       // separate instructions that make it harder to use a non-constant update.
13583       continue;
13584     }
13585 
13586     // OK, we found an ADD we can fold into the base update.
13587     // Now, create a _UPD node, taking care of not breaking alignment.
13588 
13589     EVT AlignedVecTy = VecTy;
13590     unsigned Alignment = MemN->getAlignment();
13591 
13592     // If this is a less-than-standard-aligned load/store, change the type to
13593     // match the standard alignment.
13594     // The alignment is overlooked when selecting _UPD variants; and it's
13595     // easier to introduce bitcasts here than fix that.
13596     // There are 3 ways to get to this base-update combine:
13597     // - intrinsics: they are assumed to be properly aligned (to the standard
13598     //   alignment of the memory type), so we don't need to do anything.
13599     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
13600     //   intrinsics, so, likewise, there's nothing to do.
13601     // - generic load/store instructions: the alignment is specified as an
13602     //   explicit operand, rather than implicitly as the standard alignment
13603     //   of the memory type (like the intrisics).  We need to change the
13604     //   memory type to match the explicit alignment.  That way, we don't
13605     //   generate non-standard-aligned ARMISD::VLDx nodes.
13606     if (isa<LSBaseSDNode>(N)) {
13607       if (Alignment == 0)
13608         Alignment = 1;
13609       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
13610         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
13611         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
13612         assert(!isLaneOp && "Unexpected generic load/store lane.");
13613         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
13614         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
13615       }
13616       // Don't set an explicit alignment on regular load/stores that we want
13617       // to transform to VLD/VST 1_UPD nodes.
13618       // This matches the behavior of regular load/stores, which only get an
13619       // explicit alignment if the MMO alignment is larger than the standard
13620       // alignment of the memory type.
13621       // Intrinsics, however, always get an explicit alignment, set to the
13622       // alignment of the MMO.
13623       Alignment = 1;
13624     }
13625 
13626     // Create the new updating load/store node.
13627     // First, create an SDVTList for the new updating node's results.
13628     EVT Tys[6];
13629     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
13630     unsigned n;
13631     for (n = 0; n < NumResultVecs; ++n)
13632       Tys[n] = AlignedVecTy;
13633     Tys[n++] = MVT::i32;
13634     Tys[n] = MVT::Other;
13635     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
13636 
13637     // Then, gather the new node's operands.
13638     SmallVector<SDValue, 8> Ops;
13639     Ops.push_back(N->getOperand(0)); // incoming chain
13640     Ops.push_back(N->getOperand(AddrOpIdx));
13641     Ops.push_back(Inc);
13642 
13643     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
13644       // Try to match the intrinsic's signature
13645       Ops.push_back(StN->getValue());
13646     } else {
13647       // Loads (and of course intrinsics) match the intrinsics' signature,
13648       // so just add all but the alignment operand.
13649       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
13650         Ops.push_back(N->getOperand(i));
13651     }
13652 
13653     // For all node types, the alignment operand is always the last one.
13654     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
13655 
13656     // If this is a non-standard-aligned STORE, the penultimate operand is the
13657     // stored value.  Bitcast it to the aligned type.
13658     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
13659       SDValue &StVal = Ops[Ops.size()-2];
13660       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
13661     }
13662 
13663     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
13664     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
13665                                            MemN->getMemOperand());
13666 
13667     // Update the uses.
13668     SmallVector<SDValue, 5> NewResults;
13669     for (unsigned i = 0; i < NumResultVecs; ++i)
13670       NewResults.push_back(SDValue(UpdN.getNode(), i));
13671 
13672     // If this is an non-standard-aligned LOAD, the first result is the loaded
13673     // value.  Bitcast it to the expected result type.
13674     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
13675       SDValue &LdVal = NewResults[0];
13676       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
13677     }
13678 
13679     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
13680     DCI.CombineTo(N, NewResults);
13681     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13682 
13683     break;
13684   }
13685   return SDValue();
13686 }
13687 
13688 static SDValue PerformVLDCombine(SDNode *N,
13689                                  TargetLowering::DAGCombinerInfo &DCI) {
13690   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13691     return SDValue();
13692 
13693   return CombineBaseUpdate(N, DCI);
13694 }
13695 
13696 static SDValue PerformMVEVLDCombine(SDNode *N,
13697                                     TargetLowering::DAGCombinerInfo &DCI) {
13698   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13699     return SDValue();
13700 
13701   SelectionDAG &DAG = DCI.DAG;
13702   SDValue Addr = N->getOperand(2);
13703   MemSDNode *MemN = cast<MemSDNode>(N);
13704   SDLoc dl(N);
13705 
13706   // For the stores, where there are multiple intrinsics we only actually want
13707   // to post-inc the last of the them.
13708   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
13709   if (IntNo == Intrinsic::arm_mve_vst2q &&
13710       cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1)
13711     return SDValue();
13712   if (IntNo == Intrinsic::arm_mve_vst4q &&
13713       cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3)
13714     return SDValue();
13715 
13716   // Search for a use of the address operand that is an increment.
13717   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
13718                             UE = Addr.getNode()->use_end();
13719        UI != UE; ++UI) {
13720     SDNode *User = *UI;
13721     if (User->getOpcode() != ISD::ADD ||
13722         UI.getUse().getResNo() != Addr.getResNo())
13723       continue;
13724 
13725     // Check that the add is independent of the load/store.  Otherwise, folding
13726     // it would create a cycle. We can avoid searching through Addr as it's a
13727     // predecessor to both.
13728     SmallPtrSet<const SDNode *, 32> Visited;
13729     SmallVector<const SDNode *, 16> Worklist;
13730     Visited.insert(Addr.getNode());
13731     Worklist.push_back(N);
13732     Worklist.push_back(User);
13733     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
13734         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13735       continue;
13736 
13737     // Find the new opcode for the updating load/store.
13738     bool isLoadOp = true;
13739     unsigned NewOpc = 0;
13740     unsigned NumVecs = 0;
13741     switch (IntNo) {
13742     default:
13743       llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
13744     case Intrinsic::arm_mve_vld2q:
13745       NewOpc = ARMISD::VLD2_UPD;
13746       NumVecs = 2;
13747       break;
13748     case Intrinsic::arm_mve_vld4q:
13749       NewOpc = ARMISD::VLD4_UPD;
13750       NumVecs = 4;
13751       break;
13752     case Intrinsic::arm_mve_vst2q:
13753       NewOpc = ARMISD::VST2_UPD;
13754       NumVecs = 2;
13755       isLoadOp = false;
13756       break;
13757     case Intrinsic::arm_mve_vst4q:
13758       NewOpc = ARMISD::VST4_UPD;
13759       NumVecs = 4;
13760       isLoadOp = false;
13761       break;
13762     }
13763 
13764     // Find the size of memory referenced by the load/store.
13765     EVT VecTy;
13766     if (isLoadOp) {
13767       VecTy = N->getValueType(0);
13768     } else {
13769       VecTy = N->getOperand(3).getValueType();
13770     }
13771 
13772     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
13773 
13774     // If the increment is a constant, it must match the memory ref size.
13775     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13776     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
13777     if (!CInc || CInc->getZExtValue() != NumBytes)
13778       continue;
13779 
13780     // Create the new updating load/store node.
13781     // First, create an SDVTList for the new updating node's results.
13782     EVT Tys[6];
13783     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
13784     unsigned n;
13785     for (n = 0; n < NumResultVecs; ++n)
13786       Tys[n] = VecTy;
13787     Tys[n++] = MVT::i32;
13788     Tys[n] = MVT::Other;
13789     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
13790 
13791     // Then, gather the new node's operands.
13792     SmallVector<SDValue, 8> Ops;
13793     Ops.push_back(N->getOperand(0)); // incoming chain
13794     Ops.push_back(N->getOperand(2)); // ptr
13795     Ops.push_back(Inc);
13796 
13797     for (unsigned i = 3; i < N->getNumOperands(); ++i)
13798       Ops.push_back(N->getOperand(i));
13799 
13800     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
13801                                            MemN->getMemOperand());
13802 
13803     // Update the uses.
13804     SmallVector<SDValue, 5> NewResults;
13805     for (unsigned i = 0; i < NumResultVecs; ++i)
13806       NewResults.push_back(SDValue(UpdN.getNode(), i));
13807 
13808     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
13809     DCI.CombineTo(N, NewResults);
13810     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13811 
13812     break;
13813   }
13814 
13815   return SDValue();
13816 }
13817 
13818 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
13819 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
13820 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
13821 /// return true.
13822 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13823   SelectionDAG &DAG = DCI.DAG;
13824   EVT VT = N->getValueType(0);
13825   // vldN-dup instructions only support 64-bit vectors for N > 1.
13826   if (!VT.is64BitVector())
13827     return false;
13828 
13829   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
13830   SDNode *VLD = N->getOperand(0).getNode();
13831   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
13832     return false;
13833   unsigned NumVecs = 0;
13834   unsigned NewOpc = 0;
13835   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
13836   if (IntNo == Intrinsic::arm_neon_vld2lane) {
13837     NumVecs = 2;
13838     NewOpc = ARMISD::VLD2DUP;
13839   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
13840     NumVecs = 3;
13841     NewOpc = ARMISD::VLD3DUP;
13842   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
13843     NumVecs = 4;
13844     NewOpc = ARMISD::VLD4DUP;
13845   } else {
13846     return false;
13847   }
13848 
13849   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
13850   // numbers match the load.
13851   unsigned VLDLaneNo =
13852     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
13853   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13854        UI != UE; ++UI) {
13855     // Ignore uses of the chain result.
13856     if (UI.getUse().getResNo() == NumVecs)
13857       continue;
13858     SDNode *User = *UI;
13859     if (User->getOpcode() != ARMISD::VDUPLANE ||
13860         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
13861       return false;
13862   }
13863 
13864   // Create the vldN-dup node.
13865   EVT Tys[5];
13866   unsigned n;
13867   for (n = 0; n < NumVecs; ++n)
13868     Tys[n] = VT;
13869   Tys[n] = MVT::Other;
13870   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
13871   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
13872   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
13873   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
13874                                            Ops, VLDMemInt->getMemoryVT(),
13875                                            VLDMemInt->getMemOperand());
13876 
13877   // Update the uses.
13878   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13879        UI != UE; ++UI) {
13880     unsigned ResNo = UI.getUse().getResNo();
13881     // Ignore uses of the chain result.
13882     if (ResNo == NumVecs)
13883       continue;
13884     SDNode *User = *UI;
13885     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
13886   }
13887 
13888   // Now the vldN-lane intrinsic is dead except for its chain result.
13889   // Update uses of the chain.
13890   std::vector<SDValue> VLDDupResults;
13891   for (unsigned n = 0; n < NumVecs; ++n)
13892     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
13893   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
13894   DCI.CombineTo(VLD, VLDDupResults);
13895 
13896   return true;
13897 }
13898 
13899 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
13900 /// ARMISD::VDUPLANE.
13901 static SDValue PerformVDUPLANECombine(SDNode *N,
13902                                       TargetLowering::DAGCombinerInfo &DCI,
13903                                       const ARMSubtarget *Subtarget) {
13904   SDValue Op = N->getOperand(0);
13905   EVT VT = N->getValueType(0);
13906 
13907   // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
13908   if (Subtarget->hasMVEIntegerOps()) {
13909     EVT ExtractVT = VT.getVectorElementType();
13910     // We need to ensure we are creating a legal type.
13911     if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
13912       ExtractVT = MVT::i32;
13913     SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
13914                               N->getOperand(0), N->getOperand(1));
13915     return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
13916   }
13917 
13918   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
13919   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
13920   if (CombineVLDDUP(N, DCI))
13921     return SDValue(N, 0);
13922 
13923   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
13924   // redundant.  Ignore bit_converts for now; element sizes are checked below.
13925   while (Op.getOpcode() == ISD::BITCAST)
13926     Op = Op.getOperand(0);
13927   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
13928     return SDValue();
13929 
13930   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
13931   unsigned EltSize = Op.getScalarValueSizeInBits();
13932   // The canonical VMOV for a zero vector uses a 32-bit element size.
13933   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13934   unsigned EltBits;
13935   if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
13936     EltSize = 8;
13937   if (EltSize > VT.getScalarSizeInBits())
13938     return SDValue();
13939 
13940   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
13941 }
13942 
13943 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
13944 static SDValue PerformVDUPCombine(SDNode *N,
13945                                   TargetLowering::DAGCombinerInfo &DCI,
13946                                   const ARMSubtarget *Subtarget) {
13947   SelectionDAG &DAG = DCI.DAG;
13948   SDValue Op = N->getOperand(0);
13949   SDLoc dl(N);
13950 
13951   if (Subtarget->hasMVEIntegerOps()) {
13952     // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
13953     // need to come from a GPR.
13954     if (Op.getValueType() == MVT::f32)
13955       return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
13956                              DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
13957     else if (Op.getValueType() == MVT::f16)
13958       return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
13959                              DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
13960   }
13961 
13962   if (!Subtarget->hasNEON())
13963     return SDValue();
13964 
13965   // Match VDUP(LOAD) -> VLD1DUP.
13966   // We match this pattern here rather than waiting for isel because the
13967   // transform is only legal for unindexed loads.
13968   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
13969   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
13970       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
13971     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
13972                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
13973     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
13974     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
13975                                              Ops, LD->getMemoryVT(),
13976                                              LD->getMemOperand());
13977     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
13978     return VLDDup;
13979   }
13980 
13981   return SDValue();
13982 }
13983 
13984 static SDValue PerformLOADCombine(SDNode *N,
13985                                   TargetLowering::DAGCombinerInfo &DCI) {
13986   EVT VT = N->getValueType(0);
13987 
13988   // If this is a legal vector load, try to combine it into a VLD1_UPD.
13989   if (ISD::isNormalLoad(N) && VT.isVector() &&
13990       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13991     return CombineBaseUpdate(N, DCI);
13992 
13993   return SDValue();
13994 }
13995 
13996 // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
13997 // pack all of the elements in one place.  Next, store to memory in fewer
13998 // chunks.
13999 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
14000                                              SelectionDAG &DAG) {
14001   SDValue StVal = St->getValue();
14002   EVT VT = StVal.getValueType();
14003   if (!St->isTruncatingStore() || !VT.isVector())
14004     return SDValue();
14005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14006   EVT StVT = St->getMemoryVT();
14007   unsigned NumElems = VT.getVectorNumElements();
14008   assert(StVT != VT && "Cannot truncate to the same type");
14009   unsigned FromEltSz = VT.getScalarSizeInBits();
14010   unsigned ToEltSz = StVT.getScalarSizeInBits();
14011 
14012   // From, To sizes and ElemCount must be pow of two
14013   if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
14014     return SDValue();
14015 
14016   // We are going to use the original vector elt for storing.
14017   // Accumulated smaller vector elements must be a multiple of the store size.
14018   if (0 != (NumElems * FromEltSz) % ToEltSz)
14019     return SDValue();
14020 
14021   unsigned SizeRatio = FromEltSz / ToEltSz;
14022   assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
14023 
14024   // Create a type on which we perform the shuffle.
14025   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
14026                                    NumElems * SizeRatio);
14027   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14028 
14029   SDLoc DL(St);
14030   SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
14031   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14032   for (unsigned i = 0; i < NumElems; ++i)
14033     ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
14034                                                       : i * SizeRatio;
14035 
14036   // Can't shuffle using an illegal type.
14037   if (!TLI.isTypeLegal(WideVecVT))
14038     return SDValue();
14039 
14040   SDValue Shuff = DAG.getVectorShuffle(
14041       WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
14042   // At this point all of the data is stored at the bottom of the
14043   // register. We now need to save it to mem.
14044 
14045   // Find the largest store unit
14046   MVT StoreType = MVT::i8;
14047   for (MVT Tp : MVT::integer_valuetypes()) {
14048     if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
14049       StoreType = Tp;
14050   }
14051   // Didn't find a legal store type.
14052   if (!TLI.isTypeLegal(StoreType))
14053     return SDValue();
14054 
14055   // Bitcast the original vector into a vector of store-size units
14056   EVT StoreVecVT =
14057       EVT::getVectorVT(*DAG.getContext(), StoreType,
14058                        VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
14059   assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14060   SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
14061   SmallVector<SDValue, 8> Chains;
14062   SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
14063                                       TLI.getPointerTy(DAG.getDataLayout()));
14064   SDValue BasePtr = St->getBasePtr();
14065 
14066   // Perform one or more big stores into memory.
14067   unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
14068   for (unsigned I = 0; I < E; I++) {
14069     SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
14070                                  ShuffWide, DAG.getIntPtrConstant(I, DL));
14071     SDValue Ch =
14072         DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
14073                      St->getAlignment(), St->getMemOperand()->getFlags());
14074     BasePtr =
14075         DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
14076     Chains.push_back(Ch);
14077   }
14078   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
14079 }
14080 
14081 // Try taking a single vector store from an truncate (which would otherwise turn
14082 // into an expensive buildvector) and splitting it into a series of narrowing
14083 // stores.
14084 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
14085                                                  SelectionDAG &DAG) {
14086   if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
14087     return SDValue();
14088   SDValue Trunc = St->getValue();
14089   if (Trunc->getOpcode() != ISD::TRUNCATE)
14090     return SDValue();
14091   EVT FromVT = Trunc->getOperand(0).getValueType();
14092   EVT ToVT = Trunc.getValueType();
14093   if (!ToVT.isVector())
14094     return SDValue();
14095   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
14096   EVT ToEltVT = ToVT.getVectorElementType();
14097   EVT FromEltVT = FromVT.getVectorElementType();
14098 
14099   unsigned NumElements = 0;
14100   if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8))
14101     NumElements = 4;
14102   if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8)
14103     NumElements = 8;
14104   if (NumElements == 0 || FromVT.getVectorNumElements() == NumElements ||
14105       FromVT.getVectorNumElements() % NumElements != 0)
14106     return SDValue();
14107 
14108   // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so
14109   // use the VMOVN over splitting the store. We are looking for patterns of:
14110   // !rev: 0 N 1 N+1 2 N+2 ...
14111   //  rev: N 0 N+1 1 N+2 2 ...
14112   auto isVMOVNOriginalMask = [&](ArrayRef<int> M, bool rev) {
14113     unsigned NumElts = ToVT.getVectorNumElements();
14114     if (NumElts != M.size() || (ToVT != MVT::v8i16 && ToVT != MVT::v16i8))
14115       return false;
14116 
14117     unsigned Off0 = rev ? NumElts : 0;
14118     unsigned Off1 = rev ? 0 : NumElts;
14119 
14120     for (unsigned i = 0; i < NumElts; i += 2) {
14121       if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
14122         return false;
14123       if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
14124         return false;
14125     }
14126 
14127     return true;
14128   };
14129 
14130   if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc->getOperand(0)))
14131     if (isVMOVNOriginalMask(Shuffle->getMask(), false) ||
14132         isVMOVNOriginalMask(Shuffle->getMask(), true))
14133       return SDValue();
14134 
14135   SDLoc DL(St);
14136   // Details about the old store
14137   SDValue Ch = St->getChain();
14138   SDValue BasePtr = St->getBasePtr();
14139   Align Alignment = St->getOriginalAlign();
14140   MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
14141   AAMDNodes AAInfo = St->getAAInfo();
14142 
14143   EVT NewFromVT = EVT::getVectorVT(*DAG.getContext(), FromEltVT, NumElements);
14144   EVT NewToVT = EVT::getVectorVT(*DAG.getContext(), ToEltVT, NumElements);
14145 
14146   SmallVector<SDValue, 4> Stores;
14147   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
14148     unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
14149     SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
14150 
14151     SDValue Extract =
14152         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
14153                     DAG.getConstant(i * NumElements, DL, MVT::i32));
14154     SDValue Store = DAG.getTruncStore(
14155         Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
14156         NewToVT, Alignment.value(), MMOFlags, AAInfo);
14157     Stores.push_back(Store);
14158   }
14159   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
14160 }
14161 
14162 /// PerformSTORECombine - Target-specific dag combine xforms for
14163 /// ISD::STORE.
14164 static SDValue PerformSTORECombine(SDNode *N,
14165                                    TargetLowering::DAGCombinerInfo &DCI,
14166                                    const ARMSubtarget *Subtarget) {
14167   StoreSDNode *St = cast<StoreSDNode>(N);
14168   if (St->isVolatile())
14169     return SDValue();
14170   SDValue StVal = St->getValue();
14171   EVT VT = StVal.getValueType();
14172 
14173   if (Subtarget->hasNEON())
14174     if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
14175       return Store;
14176 
14177   if (Subtarget->hasMVEIntegerOps())
14178     if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
14179       return NewToken;
14180 
14181   if (!ISD::isNormalStore(St))
14182     return SDValue();
14183 
14184   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
14185   // ARM stores of arguments in the same cache line.
14186   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
14187       StVal.getNode()->hasOneUse()) {
14188     SelectionDAG  &DAG = DCI.DAG;
14189     bool isBigEndian = DAG.getDataLayout().isBigEndian();
14190     SDLoc DL(St);
14191     SDValue BasePtr = St->getBasePtr();
14192     SDValue NewST1 = DAG.getStore(
14193         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
14194         BasePtr, St->getPointerInfo(), St->getAlignment(),
14195         St->getMemOperand()->getFlags());
14196 
14197     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
14198                                     DAG.getConstant(4, DL, MVT::i32));
14199     return DAG.getStore(NewST1.getValue(0), DL,
14200                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
14201                         OffsetPtr, St->getPointerInfo(),
14202                         std::min(4U, St->getAlignment() / 2),
14203                         St->getMemOperand()->getFlags());
14204   }
14205 
14206   if (StVal.getValueType() == MVT::i64 &&
14207       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14208 
14209     // Bitcast an i64 store extracted from a vector to f64.
14210     // Otherwise, the i64 value will be legalized to a pair of i32 values.
14211     SelectionDAG &DAG = DCI.DAG;
14212     SDLoc dl(StVal);
14213     SDValue IntVec = StVal.getOperand(0);
14214     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
14215                                    IntVec.getValueType().getVectorNumElements());
14216     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
14217     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
14218                                  Vec, StVal.getOperand(1));
14219     dl = SDLoc(N);
14220     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
14221     // Make the DAGCombiner fold the bitcasts.
14222     DCI.AddToWorklist(Vec.getNode());
14223     DCI.AddToWorklist(ExtElt.getNode());
14224     DCI.AddToWorklist(V.getNode());
14225     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
14226                         St->getPointerInfo(), St->getAlignment(),
14227                         St->getMemOperand()->getFlags(), St->getAAInfo());
14228   }
14229 
14230   // If this is a legal vector store, try to combine it into a VST1_UPD.
14231   if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
14232       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
14233     return CombineBaseUpdate(N, DCI);
14234 
14235   return SDValue();
14236 }
14237 
14238 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
14239 /// can replace combinations of VMUL and VCVT (floating-point to integer)
14240 /// when the VMUL has a constant operand that is a power of 2.
14241 ///
14242 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14243 ///  vmul.f32        d16, d17, d16
14244 ///  vcvt.s32.f32    d16, d16
14245 /// becomes:
14246 ///  vcvt.s32.f32    d16, d16, #3
14247 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
14248                                   const ARMSubtarget *Subtarget) {
14249   if (!Subtarget->hasNEON())
14250     return SDValue();
14251 
14252   SDValue Op = N->getOperand(0);
14253   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
14254       Op.getOpcode() != ISD::FMUL)
14255     return SDValue();
14256 
14257   SDValue ConstVec = Op->getOperand(1);
14258   if (!isa<BuildVectorSDNode>(ConstVec))
14259     return SDValue();
14260 
14261   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
14262   uint32_t FloatBits = FloatTy.getSizeInBits();
14263   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
14264   uint32_t IntBits = IntTy.getSizeInBits();
14265   unsigned NumLanes = Op.getValueType().getVectorNumElements();
14266   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14267     // These instructions only exist converting from f32 to i32. We can handle
14268     // smaller integers by generating an extra truncate, but larger ones would
14269     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14270     // these intructions only support v2i32/v4i32 types.
14271     return SDValue();
14272   }
14273 
14274   BitVector UndefElements;
14275   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14276   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14277   if (C == -1 || C == 0 || C > 32)
14278     return SDValue();
14279 
14280   SDLoc dl(N);
14281   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
14282   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
14283     Intrinsic::arm_neon_vcvtfp2fxu;
14284   SDValue FixConv = DAG.getNode(
14285       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14286       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
14287       DAG.getConstant(C, dl, MVT::i32));
14288 
14289   if (IntBits < FloatBits)
14290     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
14291 
14292   return FixConv;
14293 }
14294 
14295 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
14296 /// can replace combinations of VCVT (integer to floating-point) and VDIV
14297 /// when the VDIV has a constant operand that is a power of 2.
14298 ///
14299 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14300 ///  vcvt.f32.s32    d16, d16
14301 ///  vdiv.f32        d16, d17, d16
14302 /// becomes:
14303 ///  vcvt.f32.s32    d16, d16, #3
14304 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
14305                                   const ARMSubtarget *Subtarget) {
14306   if (!Subtarget->hasNEON())
14307     return SDValue();
14308 
14309   SDValue Op = N->getOperand(0);
14310   unsigned OpOpcode = Op.getNode()->getOpcode();
14311   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
14312       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
14313     return SDValue();
14314 
14315   SDValue ConstVec = N->getOperand(1);
14316   if (!isa<BuildVectorSDNode>(ConstVec))
14317     return SDValue();
14318 
14319   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
14320   uint32_t FloatBits = FloatTy.getSizeInBits();
14321   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
14322   uint32_t IntBits = IntTy.getSizeInBits();
14323   unsigned NumLanes = Op.getValueType().getVectorNumElements();
14324   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14325     // These instructions only exist converting from i32 to f32. We can handle
14326     // smaller integers by generating an extra extend, but larger ones would
14327     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14328     // these intructions only support v2i32/v4i32 types.
14329     return SDValue();
14330   }
14331 
14332   BitVector UndefElements;
14333   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14334   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14335   if (C == -1 || C == 0 || C > 32)
14336     return SDValue();
14337 
14338   SDLoc dl(N);
14339   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
14340   SDValue ConvInput = Op.getOperand(0);
14341   if (IntBits < FloatBits)
14342     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
14343                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14344                             ConvInput);
14345 
14346   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
14347     Intrinsic::arm_neon_vcvtfxu2fp;
14348   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
14349                      Op.getValueType(),
14350                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
14351                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
14352 }
14353 
14354 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
14355                                            const ARMSubtarget *ST) {
14356   if (!ST->hasMVEIntegerOps())
14357     return SDValue();
14358 
14359   assert(N->getOpcode() == ISD::VECREDUCE_ADD);
14360   EVT ResVT = N->getValueType(0);
14361   SDValue N0 = N->getOperand(0);
14362   SDLoc dl(N);
14363 
14364   // We are looking for something that will have illegal types if left alone,
14365   // but that we can convert to a single instruction undef MVE. For example
14366   // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
14367   // or
14368   // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
14369 
14370   // Cases:
14371   //   VADDV u/s 8/16/32
14372   //   VMLAV u/s 8/16/32
14373   //   VADDLV u/s 32
14374   //   VMLALV u/s 16/32
14375 
14376   auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
14377     if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
14378       return SDValue();
14379     SDValue A = N0->getOperand(0);
14380     if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14381       return A;
14382     return SDValue();
14383   };
14384   auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
14385                      SDValue &A, SDValue &B) {
14386     if (ResVT != RetTy || N0->getOpcode() != ISD::MUL)
14387       return false;
14388     SDValue ExtA = N0->getOperand(0);
14389     SDValue ExtB = N0->getOperand(1);
14390     if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode)
14391       return false;
14392     A = ExtA->getOperand(0);
14393     B = ExtB->getOperand(0);
14394     if (A.getValueType() == B.getValueType() &&
14395         llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14396       return true;
14397     return false;
14398   };
14399   auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
14400     SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
14401     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
14402                        SDValue(Node.getNode(), 1));
14403   };
14404 
14405   if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
14406     return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
14407   if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
14408     return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
14409   if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
14410     return Create64bitNode(ARMISD::VADDLVs, {A});
14411   if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
14412     return Create64bitNode(ARMISD::VADDLVu, {A});
14413 
14414   SDValue A, B;
14415   if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
14416     return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
14417   if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
14418     return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
14419   if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B))
14420     return Create64bitNode(ARMISD::VMLALVs, {A, B});
14421   if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B))
14422     return Create64bitNode(ARMISD::VMLALVu, {A, B});
14423   return SDValue();
14424 }
14425 
14426 static SDValue PerformVMOVNCombine(SDNode *N,
14427                                    TargetLowering::DAGCombinerInfo &DCI) {
14428   SDValue Op0 = N->getOperand(0);
14429   SDValue Op1 = N->getOperand(1);
14430   unsigned IsTop = N->getConstantOperandVal(2);
14431 
14432   // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
14433   // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
14434   if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
14435        Op1->getOpcode() == ARMISD::VQMOVNu) &&
14436       Op1->getConstantOperandVal(2) == 0)
14437     return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
14438                            Op0, Op1->getOperand(1), N->getOperand(2));
14439 
14440   // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
14441   // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
14442   // into the top or bottom lanes.
14443   unsigned NumElts = N->getValueType(0).getVectorNumElements();
14444   APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
14445   APInt Op0DemandedElts =
14446       IsTop ? Op1DemandedElts
14447             : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
14448 
14449   APInt KnownUndef, KnownZero;
14450   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
14451   if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
14452                                      KnownZero, DCI))
14453     return SDValue(N, 0);
14454   if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, KnownUndef,
14455                                      KnownZero, DCI))
14456     return SDValue(N, 0);
14457 
14458   return SDValue();
14459 }
14460 
14461 static SDValue PerformVQMOVNCombine(SDNode *N,
14462                                     TargetLowering::DAGCombinerInfo &DCI) {
14463   SDValue Op0 = N->getOperand(0);
14464   unsigned IsTop = N->getConstantOperandVal(2);
14465 
14466   unsigned NumElts = N->getValueType(0).getVectorNumElements();
14467   APInt Op0DemandedElts =
14468       APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
14469                                      : APInt::getHighBitsSet(2, 1));
14470 
14471   APInt KnownUndef, KnownZero;
14472   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
14473   if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
14474                                      KnownZero, DCI))
14475     return SDValue(N, 0);
14476   return SDValue();
14477 }
14478 
14479 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
14480   SDLoc DL(N);
14481   SDValue Op0 = N->getOperand(0);
14482   SDValue Op1 = N->getOperand(1);
14483 
14484   // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
14485   // uses of the intrinsics.
14486   if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
14487     int ShiftAmt = C->getSExtValue();
14488     if (ShiftAmt == 0) {
14489       SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
14490       DAG.ReplaceAllUsesWith(N, Merge.getNode());
14491       return SDValue();
14492     }
14493 
14494     if (ShiftAmt >= -32 && ShiftAmt < 0) {
14495       unsigned NewOpcode =
14496           N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
14497       SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
14498                                      DAG.getConstant(-ShiftAmt, DL, MVT::i32));
14499       DAG.ReplaceAllUsesWith(N, NewShift.getNode());
14500       return NewShift;
14501     }
14502   }
14503 
14504   return SDValue();
14505 }
14506 
14507 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
14508 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
14509                                                    DAGCombinerInfo &DCI) const {
14510   SelectionDAG &DAG = DCI.DAG;
14511   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14512   switch (IntNo) {
14513   default:
14514     // Don't do anything for most intrinsics.
14515     break;
14516 
14517   // Vector shifts: check for immediate versions and lower them.
14518   // Note: This is done during DAG combining instead of DAG legalizing because
14519   // the build_vectors for 64-bit vector element shift counts are generally
14520   // not legal, and it is hard to see their values after they get legalized to
14521   // loads from a constant pool.
14522   case Intrinsic::arm_neon_vshifts:
14523   case Intrinsic::arm_neon_vshiftu:
14524   case Intrinsic::arm_neon_vrshifts:
14525   case Intrinsic::arm_neon_vrshiftu:
14526   case Intrinsic::arm_neon_vrshiftn:
14527   case Intrinsic::arm_neon_vqshifts:
14528   case Intrinsic::arm_neon_vqshiftu:
14529   case Intrinsic::arm_neon_vqshiftsu:
14530   case Intrinsic::arm_neon_vqshiftns:
14531   case Intrinsic::arm_neon_vqshiftnu:
14532   case Intrinsic::arm_neon_vqshiftnsu:
14533   case Intrinsic::arm_neon_vqrshiftns:
14534   case Intrinsic::arm_neon_vqrshiftnu:
14535   case Intrinsic::arm_neon_vqrshiftnsu: {
14536     EVT VT = N->getOperand(1).getValueType();
14537     int64_t Cnt;
14538     unsigned VShiftOpc = 0;
14539 
14540     switch (IntNo) {
14541     case Intrinsic::arm_neon_vshifts:
14542     case Intrinsic::arm_neon_vshiftu:
14543       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
14544         VShiftOpc = ARMISD::VSHLIMM;
14545         break;
14546       }
14547       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
14548         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
14549                                                           : ARMISD::VSHRuIMM);
14550         break;
14551       }
14552       return SDValue();
14553 
14554     case Intrinsic::arm_neon_vrshifts:
14555     case Intrinsic::arm_neon_vrshiftu:
14556       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
14557         break;
14558       return SDValue();
14559 
14560     case Intrinsic::arm_neon_vqshifts:
14561     case Intrinsic::arm_neon_vqshiftu:
14562       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
14563         break;
14564       return SDValue();
14565 
14566     case Intrinsic::arm_neon_vqshiftsu:
14567       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
14568         break;
14569       llvm_unreachable("invalid shift count for vqshlu intrinsic");
14570 
14571     case Intrinsic::arm_neon_vrshiftn:
14572     case Intrinsic::arm_neon_vqshiftns:
14573     case Intrinsic::arm_neon_vqshiftnu:
14574     case Intrinsic::arm_neon_vqshiftnsu:
14575     case Intrinsic::arm_neon_vqrshiftns:
14576     case Intrinsic::arm_neon_vqrshiftnu:
14577     case Intrinsic::arm_neon_vqrshiftnsu:
14578       // Narrowing shifts require an immediate right shift.
14579       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
14580         break;
14581       llvm_unreachable("invalid shift count for narrowing vector shift "
14582                        "intrinsic");
14583 
14584     default:
14585       llvm_unreachable("unhandled vector shift");
14586     }
14587 
14588     switch (IntNo) {
14589     case Intrinsic::arm_neon_vshifts:
14590     case Intrinsic::arm_neon_vshiftu:
14591       // Opcode already set above.
14592       break;
14593     case Intrinsic::arm_neon_vrshifts:
14594       VShiftOpc = ARMISD::VRSHRsIMM;
14595       break;
14596     case Intrinsic::arm_neon_vrshiftu:
14597       VShiftOpc = ARMISD::VRSHRuIMM;
14598       break;
14599     case Intrinsic::arm_neon_vrshiftn:
14600       VShiftOpc = ARMISD::VRSHRNIMM;
14601       break;
14602     case Intrinsic::arm_neon_vqshifts:
14603       VShiftOpc = ARMISD::VQSHLsIMM;
14604       break;
14605     case Intrinsic::arm_neon_vqshiftu:
14606       VShiftOpc = ARMISD::VQSHLuIMM;
14607       break;
14608     case Intrinsic::arm_neon_vqshiftsu:
14609       VShiftOpc = ARMISD::VQSHLsuIMM;
14610       break;
14611     case Intrinsic::arm_neon_vqshiftns:
14612       VShiftOpc = ARMISD::VQSHRNsIMM;
14613       break;
14614     case Intrinsic::arm_neon_vqshiftnu:
14615       VShiftOpc = ARMISD::VQSHRNuIMM;
14616       break;
14617     case Intrinsic::arm_neon_vqshiftnsu:
14618       VShiftOpc = ARMISD::VQSHRNsuIMM;
14619       break;
14620     case Intrinsic::arm_neon_vqrshiftns:
14621       VShiftOpc = ARMISD::VQRSHRNsIMM;
14622       break;
14623     case Intrinsic::arm_neon_vqrshiftnu:
14624       VShiftOpc = ARMISD::VQRSHRNuIMM;
14625       break;
14626     case Intrinsic::arm_neon_vqrshiftnsu:
14627       VShiftOpc = ARMISD::VQRSHRNsuIMM;
14628       break;
14629     }
14630 
14631     SDLoc dl(N);
14632     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
14633                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
14634   }
14635 
14636   case Intrinsic::arm_neon_vshiftins: {
14637     EVT VT = N->getOperand(1).getValueType();
14638     int64_t Cnt;
14639     unsigned VShiftOpc = 0;
14640 
14641     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
14642       VShiftOpc = ARMISD::VSLIIMM;
14643     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
14644       VShiftOpc = ARMISD::VSRIIMM;
14645     else {
14646       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
14647     }
14648 
14649     SDLoc dl(N);
14650     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
14651                        N->getOperand(1), N->getOperand(2),
14652                        DAG.getConstant(Cnt, dl, MVT::i32));
14653   }
14654 
14655   case Intrinsic::arm_neon_vqrshifts:
14656   case Intrinsic::arm_neon_vqrshiftu:
14657     // No immediate versions of these to check for.
14658     break;
14659 
14660   case Intrinsic::arm_mve_vqdmlah:
14661   case Intrinsic::arm_mve_vqdmlash:
14662   case Intrinsic::arm_mve_vqrdmlah:
14663   case Intrinsic::arm_mve_vqrdmlash:
14664   case Intrinsic::arm_mve_vmla_n_predicated:
14665   case Intrinsic::arm_mve_vmlas_n_predicated:
14666   case Intrinsic::arm_mve_vqdmlah_predicated:
14667   case Intrinsic::arm_mve_vqdmlash_predicated:
14668   case Intrinsic::arm_mve_vqrdmlah_predicated:
14669   case Intrinsic::arm_mve_vqrdmlash_predicated: {
14670     // These intrinsics all take an i32 scalar operand which is narrowed to the
14671     // size of a single lane of the vector type they return. So we don't need
14672     // any bits of that operand above that point, which allows us to eliminate
14673     // uxth/sxth.
14674     unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
14675     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
14676     if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
14677       return SDValue();
14678     break;
14679   }
14680 
14681   case Intrinsic::arm_mve_minv:
14682   case Intrinsic::arm_mve_maxv:
14683   case Intrinsic::arm_mve_minav:
14684   case Intrinsic::arm_mve_maxav:
14685   case Intrinsic::arm_mve_minv_predicated:
14686   case Intrinsic::arm_mve_maxv_predicated:
14687   case Intrinsic::arm_mve_minav_predicated:
14688   case Intrinsic::arm_mve_maxav_predicated: {
14689     // These intrinsics all take an i32 scalar operand which is narrowed to the
14690     // size of a single lane of the vector type they take as the other input.
14691     unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
14692     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
14693     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14694       return SDValue();
14695     break;
14696   }
14697 
14698   case Intrinsic::arm_mve_addv: {
14699     // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
14700     // which allow PerformADDVecReduce to turn it into VADDLV when possible.
14701     bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14702     unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
14703     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
14704   }
14705 
14706   case Intrinsic::arm_mve_addlv:
14707   case Intrinsic::arm_mve_addlv_predicated: {
14708     // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
14709     // which recombines the two outputs into an i64
14710     bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14711     unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
14712                     (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
14713                     (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
14714 
14715     SmallVector<SDValue, 4> Ops;
14716     for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
14717       if (i != 2)                      // skip the unsigned flag
14718         Ops.push_back(N->getOperand(i));
14719 
14720     SDLoc dl(N);
14721     SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
14722     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
14723                        val.getValue(1));
14724   }
14725   }
14726 
14727   return SDValue();
14728 }
14729 
14730 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
14731 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
14732 /// combining instead of DAG legalizing because the build_vectors for 64-bit
14733 /// vector element shift counts are generally not legal, and it is hard to see
14734 /// their values after they get legalized to loads from a constant pool.
14735 static SDValue PerformShiftCombine(SDNode *N,
14736                                    TargetLowering::DAGCombinerInfo &DCI,
14737                                    const ARMSubtarget *ST) {
14738   SelectionDAG &DAG = DCI.DAG;
14739   EVT VT = N->getValueType(0);
14740   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
14741     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
14742     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
14743     SDValue N1 = N->getOperand(1);
14744     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
14745       SDValue N0 = N->getOperand(0);
14746       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
14747           DAG.MaskedValueIsZero(N0.getOperand(0),
14748                                 APInt::getHighBitsSet(32, 16)))
14749         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
14750     }
14751   }
14752 
14753   if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
14754       N->getOperand(0)->getOpcode() == ISD::AND &&
14755       N->getOperand(0)->hasOneUse()) {
14756     if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14757       return SDValue();
14758     // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
14759     // usually show up because instcombine prefers to canonicalize it to
14760     // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
14761     // out of GEP lowering in some cases.
14762     SDValue N0 = N->getOperand(0);
14763     ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
14764     if (!ShiftAmtNode)
14765       return SDValue();
14766     uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
14767     ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14768     if (!AndMaskNode)
14769       return SDValue();
14770     uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
14771     // Don't transform uxtb/uxth.
14772     if (AndMask == 255 || AndMask == 65535)
14773       return SDValue();
14774     if (isMask_32(AndMask)) {
14775       uint32_t MaskedBits = countLeadingZeros(AndMask);
14776       if (MaskedBits > ShiftAmt) {
14777         SDLoc DL(N);
14778         SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14779                                   DAG.getConstant(MaskedBits, DL, MVT::i32));
14780         return DAG.getNode(
14781             ISD::SRL, DL, MVT::i32, SHL,
14782             DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
14783       }
14784     }
14785   }
14786 
14787   // Nothing to be done for scalar shifts.
14788   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14789   if (!VT.isVector() || !TLI.isTypeLegal(VT))
14790     return SDValue();
14791   if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
14792     return SDValue();
14793 
14794   int64_t Cnt;
14795 
14796   switch (N->getOpcode()) {
14797   default: llvm_unreachable("unexpected shift opcode");
14798 
14799   case ISD::SHL:
14800     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
14801       SDLoc dl(N);
14802       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
14803                          DAG.getConstant(Cnt, dl, MVT::i32));
14804     }
14805     break;
14806 
14807   case ISD::SRA:
14808   case ISD::SRL:
14809     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
14810       unsigned VShiftOpc =
14811           (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
14812       SDLoc dl(N);
14813       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
14814                          DAG.getConstant(Cnt, dl, MVT::i32));
14815     }
14816   }
14817   return SDValue();
14818 }
14819 
14820 // Look for a sign/zero extend of a larger than legal load. This can be split
14821 // into two extending loads, which are simpler to deal with than an arbitrary
14822 // sign extend.
14823 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
14824   SDValue N0 = N->getOperand(0);
14825   if (N0.getOpcode() != ISD::LOAD)
14826     return SDValue();
14827   LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
14828   if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
14829       LD->getExtensionType() != ISD::NON_EXTLOAD)
14830     return SDValue();
14831   EVT FromVT = LD->getValueType(0);
14832   EVT ToVT = N->getValueType(0);
14833   if (!ToVT.isVector())
14834     return SDValue();
14835   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
14836   EVT ToEltVT = ToVT.getVectorElementType();
14837   EVT FromEltVT = FromVT.getVectorElementType();
14838 
14839   unsigned NumElements = 0;
14840   if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
14841     NumElements = 4;
14842   if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
14843     NumElements = 8;
14844   if (NumElements == 0 ||
14845       FromVT.getVectorNumElements() == NumElements ||
14846       FromVT.getVectorNumElements() % NumElements != 0 ||
14847       !isPowerOf2_32(NumElements))
14848     return SDValue();
14849 
14850   SDLoc DL(LD);
14851   // Details about the old load
14852   SDValue Ch = LD->getChain();
14853   SDValue BasePtr = LD->getBasePtr();
14854   Align Alignment = LD->getOriginalAlign();
14855   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
14856   AAMDNodes AAInfo = LD->getAAInfo();
14857 
14858   ISD::LoadExtType NewExtType =
14859       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
14860   SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
14861   EVT NewFromVT = FromVT.getHalfNumVectorElementsVT(*DAG.getContext());
14862   EVT NewToVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
14863   unsigned NewOffset = NewFromVT.getSizeInBits() / 8;
14864   SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
14865 
14866   // Split the load in half, each side of which is extended separately. This
14867   // is good enough, as legalisation will take it from there. They are either
14868   // already legal or they will be split further into something that is
14869   // legal.
14870   SDValue NewLoad1 = DAG.getLoad(
14871       ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, BasePtr, Offset,
14872       LD->getPointerInfo(), NewFromVT, Alignment.value(), MMOFlags, AAInfo);
14873   SDValue NewLoad2 =
14874       DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
14875                   LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
14876                   Alignment.value(), MMOFlags, AAInfo);
14877 
14878   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14879                                  SDValue(NewLoad1.getNode(), 1),
14880                                  SDValue(NewLoad2.getNode(), 1));
14881   DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
14882   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, NewLoad1, NewLoad2);
14883 }
14884 
14885 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
14886 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
14887 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
14888                                     const ARMSubtarget *ST) {
14889   SDValue N0 = N->getOperand(0);
14890 
14891   // Check for sign- and zero-extensions of vector extract operations of 8- and
14892   // 16-bit vector elements. NEON and MVE support these directly. They are
14893   // handled during DAG combining because type legalization will promote them
14894   // to 32-bit types and it is messy to recognize the operations after that.
14895   if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
14896       N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14897     SDValue Vec = N0.getOperand(0);
14898     SDValue Lane = N0.getOperand(1);
14899     EVT VT = N->getValueType(0);
14900     EVT EltVT = N0.getValueType();
14901     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14902 
14903     if (VT == MVT::i32 &&
14904         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
14905         TLI.isTypeLegal(Vec.getValueType()) &&
14906         isa<ConstantSDNode>(Lane)) {
14907 
14908       unsigned Opc = 0;
14909       switch (N->getOpcode()) {
14910       default: llvm_unreachable("unexpected opcode");
14911       case ISD::SIGN_EXTEND:
14912         Opc = ARMISD::VGETLANEs;
14913         break;
14914       case ISD::ZERO_EXTEND:
14915       case ISD::ANY_EXTEND:
14916         Opc = ARMISD::VGETLANEu;
14917         break;
14918       }
14919       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
14920     }
14921   }
14922 
14923   if (ST->hasMVEIntegerOps())
14924     if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
14925       return NewLoad;
14926 
14927   return SDValue();
14928 }
14929 
14930 /// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
14931 /// saturates.
14932 static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG,
14933                                     const ARMSubtarget *ST) {
14934   EVT VT = N->getValueType(0);
14935   SDValue N0 = N->getOperand(0);
14936   if (!ST->hasMVEIntegerOps())
14937     return SDValue();
14938 
14939   if (VT != MVT::v4i32 && VT != MVT::v8i16)
14940     return SDValue();
14941 
14942   auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
14943     // Check one is a smin and the other is a smax
14944     if (Min->getOpcode() != ISD::SMIN)
14945       std::swap(Min, Max);
14946     if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
14947       return false;
14948 
14949     APInt SaturateC;
14950     if (VT == MVT::v4i32)
14951       SaturateC = APInt(32, (1 << 15) - 1, true);
14952     else //if (VT == MVT::v8i16)
14953       SaturateC = APInt(16, (1 << 7) - 1, true);
14954 
14955     APInt MinC, MaxC;
14956     if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
14957         MinC != SaturateC)
14958       return false;
14959     if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) ||
14960         MaxC != ~SaturateC)
14961       return false;
14962     return true;
14963   };
14964 
14965   if (IsSignedSaturate(N, N0.getNode())) {
14966     SDLoc DL(N);
14967     MVT ExtVT, HalfVT;
14968     if (VT == MVT::v4i32) {
14969       HalfVT = MVT::v8i16;
14970       ExtVT = MVT::v4i16;
14971     } else { // if (VT == MVT::v8i16)
14972       HalfVT = MVT::v16i8;
14973       ExtVT = MVT::v8i8;
14974     }
14975 
14976     // Create a VQMOVNB with undef top lanes, then signed extended into the top
14977     // half. That extend will hopefully be removed if only the bottom bits are
14978     // demanded (though a truncating store, for example).
14979     SDValue VQMOVN =
14980         DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
14981                     N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
14982     SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
14983     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
14984                        DAG.getValueType(ExtVT));
14985   }
14986 
14987   auto IsUnsignedSaturate = [&](SDNode *Min) {
14988     // For unsigned, we just need to check for <= 0xffff
14989     if (Min->getOpcode() != ISD::UMIN)
14990       return false;
14991 
14992     APInt SaturateC;
14993     if (VT == MVT::v4i32)
14994       SaturateC = APInt(32, (1 << 16) - 1, true);
14995     else //if (VT == MVT::v8i16)
14996       SaturateC = APInt(16, (1 << 8) - 1, true);
14997 
14998     APInt MinC;
14999     if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
15000         MinC != SaturateC)
15001       return false;
15002     return true;
15003   };
15004 
15005   if (IsUnsignedSaturate(N)) {
15006     SDLoc DL(N);
15007     MVT HalfVT;
15008     unsigned ExtConst;
15009     if (VT == MVT::v4i32) {
15010       HalfVT = MVT::v8i16;
15011       ExtConst = 0x0000FFFF;
15012     } else { //if (VT == MVT::v8i16)
15013       HalfVT = MVT::v16i8;
15014       ExtConst = 0x00FF;
15015     }
15016 
15017     // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
15018     // an AND. That extend will hopefully be removed if only the bottom bits are
15019     // demanded (though a truncating store, for example).
15020     SDValue VQMOVN =
15021         DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
15022                     DAG.getConstant(0, DL, MVT::i32));
15023     SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
15024     return DAG.getNode(ISD::AND, DL, VT, Bitcast,
15025                        DAG.getConstant(ExtConst, DL, VT));
15026   }
15027 
15028   return SDValue();
15029 }
15030 
15031 static const APInt *isPowerOf2Constant(SDValue V) {
15032   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
15033   if (!C)
15034     return nullptr;
15035   const APInt *CV = &C->getAPIntValue();
15036   return CV->isPowerOf2() ? CV : nullptr;
15037 }
15038 
15039 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
15040   // If we have a CMOV, OR and AND combination such as:
15041   //   if (x & CN)
15042   //     y |= CM;
15043   //
15044   // And:
15045   //   * CN is a single bit;
15046   //   * All bits covered by CM are known zero in y
15047   //
15048   // Then we can convert this into a sequence of BFI instructions. This will
15049   // always be a win if CM is a single bit, will always be no worse than the
15050   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
15051   // three bits (due to the extra IT instruction).
15052 
15053   SDValue Op0 = CMOV->getOperand(0);
15054   SDValue Op1 = CMOV->getOperand(1);
15055   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
15056   auto CC = CCNode->getAPIntValue().getLimitedValue();
15057   SDValue CmpZ = CMOV->getOperand(4);
15058 
15059   // The compare must be against zero.
15060   if (!isNullConstant(CmpZ->getOperand(1)))
15061     return SDValue();
15062 
15063   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
15064   SDValue And = CmpZ->getOperand(0);
15065   if (And->getOpcode() != ISD::AND)
15066     return SDValue();
15067   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
15068   if (!AndC)
15069     return SDValue();
15070   SDValue X = And->getOperand(0);
15071 
15072   if (CC == ARMCC::EQ) {
15073     // We're performing an "equal to zero" compare. Swap the operands so we
15074     // canonicalize on a "not equal to zero" compare.
15075     std::swap(Op0, Op1);
15076   } else {
15077     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
15078   }
15079 
15080   if (Op1->getOpcode() != ISD::OR)
15081     return SDValue();
15082 
15083   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
15084   if (!OrC)
15085     return SDValue();
15086   SDValue Y = Op1->getOperand(0);
15087 
15088   if (Op0 != Y)
15089     return SDValue();
15090 
15091   // Now, is it profitable to continue?
15092   APInt OrCI = OrC->getAPIntValue();
15093   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
15094   if (OrCI.countPopulation() > Heuristic)
15095     return SDValue();
15096 
15097   // Lastly, can we determine that the bits defined by OrCI
15098   // are zero in Y?
15099   KnownBits Known = DAG.computeKnownBits(Y);
15100   if ((OrCI & Known.Zero) != OrCI)
15101     return SDValue();
15102 
15103   // OK, we can do the combine.
15104   SDValue V = Y;
15105   SDLoc dl(X);
15106   EVT VT = X.getValueType();
15107   unsigned BitInX = AndC->logBase2();
15108 
15109   if (BitInX != 0) {
15110     // We must shift X first.
15111     X = DAG.getNode(ISD::SRL, dl, VT, X,
15112                     DAG.getConstant(BitInX, dl, VT));
15113   }
15114 
15115   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
15116        BitInY < NumActiveBits; ++BitInY) {
15117     if (OrCI[BitInY] == 0)
15118       continue;
15119     APInt Mask(VT.getSizeInBits(), 0);
15120     Mask.setBit(BitInY);
15121     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
15122                     // Confusingly, the operand is an *inverted* mask.
15123                     DAG.getConstant(~Mask, dl, VT));
15124   }
15125 
15126   return V;
15127 }
15128 
15129 // Given N, the value controlling the conditional branch, search for the loop
15130 // intrinsic, returning it, along with how the value is used. We need to handle
15131 // patterns such as the following:
15132 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
15133 // (brcond (setcc (loop.decrement), 0, eq), exit)
15134 // (brcond (setcc (loop.decrement), 0, ne), header)
15135 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
15136                                    bool &Negate) {
15137   switch (N->getOpcode()) {
15138   default:
15139     break;
15140   case ISD::XOR: {
15141     if (!isa<ConstantSDNode>(N.getOperand(1)))
15142       return SDValue();
15143     if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
15144       return SDValue();
15145     Negate = !Negate;
15146     return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
15147   }
15148   case ISD::SETCC: {
15149     auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
15150     if (!Const)
15151       return SDValue();
15152     if (Const->isNullValue())
15153       Imm = 0;
15154     else if (Const->isOne())
15155       Imm = 1;
15156     else
15157       return SDValue();
15158     CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
15159     return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
15160   }
15161   case ISD::INTRINSIC_W_CHAIN: {
15162     unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
15163     if (IntOp != Intrinsic::test_set_loop_iterations &&
15164         IntOp != Intrinsic::loop_decrement_reg)
15165       return SDValue();
15166     return N;
15167   }
15168   }
15169   return SDValue();
15170 }
15171 
15172 static SDValue PerformHWLoopCombine(SDNode *N,
15173                                     TargetLowering::DAGCombinerInfo &DCI,
15174                                     const ARMSubtarget *ST) {
15175 
15176   // The hwloop intrinsics that we're interested are used for control-flow,
15177   // either for entering or exiting the loop:
15178   // - test.set.loop.iterations will test whether its operand is zero. If it
15179   //   is zero, the proceeding branch should not enter the loop.
15180   // - loop.decrement.reg also tests whether its operand is zero. If it is
15181   //   zero, the proceeding branch should not branch back to the beginning of
15182   //   the loop.
15183   // So here, we need to check that how the brcond is using the result of each
15184   // of the intrinsics to ensure that we're branching to the right place at the
15185   // right time.
15186 
15187   ISD::CondCode CC;
15188   SDValue Cond;
15189   int Imm = 1;
15190   bool Negate = false;
15191   SDValue Chain = N->getOperand(0);
15192   SDValue Dest;
15193 
15194   if (N->getOpcode() == ISD::BRCOND) {
15195     CC = ISD::SETEQ;
15196     Cond = N->getOperand(1);
15197     Dest = N->getOperand(2);
15198   } else {
15199     assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
15200     CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15201     Cond = N->getOperand(2);
15202     Dest = N->getOperand(4);
15203     if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
15204       if (!Const->isOne() && !Const->isNullValue())
15205         return SDValue();
15206       Imm = Const->getZExtValue();
15207     } else
15208       return SDValue();
15209   }
15210 
15211   SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
15212   if (!Int)
15213     return SDValue();
15214 
15215   if (Negate)
15216     CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
15217 
15218   auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
15219     return (CC == ISD::SETEQ && Imm == 0) ||
15220            (CC == ISD::SETNE && Imm == 1) ||
15221            (CC == ISD::SETLT && Imm == 1) ||
15222            (CC == ISD::SETULT && Imm == 1);
15223   };
15224 
15225   auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
15226     return (CC == ISD::SETEQ && Imm == 1) ||
15227            (CC == ISD::SETNE && Imm == 0) ||
15228            (CC == ISD::SETGT && Imm == 0) ||
15229            (CC == ISD::SETUGT && Imm == 0) ||
15230            (CC == ISD::SETGE && Imm == 1) ||
15231            (CC == ISD::SETUGE && Imm == 1);
15232   };
15233 
15234   assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
15235          "unsupported condition");
15236 
15237   SDLoc dl(Int);
15238   SelectionDAG &DAG = DCI.DAG;
15239   SDValue Elements = Int.getOperand(2);
15240   unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
15241   assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
15242           && "expected single br user");
15243   SDNode *Br = *N->use_begin();
15244   SDValue OtherTarget = Br->getOperand(1);
15245 
15246   // Update the unconditional branch to branch to the given Dest.
15247   auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
15248     SDValue NewBrOps[] = { Br->getOperand(0), Dest };
15249     SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
15250     DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
15251   };
15252 
15253   if (IntOp == Intrinsic::test_set_loop_iterations) {
15254     SDValue Res;
15255     // We expect this 'instruction' to branch when the counter is zero.
15256     if (IsTrueIfZero(CC, Imm)) {
15257       SDValue Ops[] = { Chain, Elements, Dest };
15258       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
15259     } else {
15260       // The logic is the reverse of what we need for WLS, so find the other
15261       // basic block target: the target of the proceeding br.
15262       UpdateUncondBr(Br, Dest, DAG);
15263 
15264       SDValue Ops[] = { Chain, Elements, OtherTarget };
15265       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
15266     }
15267     DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
15268     return Res;
15269   } else {
15270     SDValue Size = DAG.getTargetConstant(
15271       cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
15272     SDValue Args[] = { Int.getOperand(0), Elements, Size, };
15273     SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
15274                                   DAG.getVTList(MVT::i32, MVT::Other), Args);
15275     DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
15276 
15277     // We expect this instruction to branch when the count is not zero.
15278     SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
15279 
15280     // Update the unconditional branch to target the loop preheader if we've
15281     // found the condition has been reversed.
15282     if (Target == OtherTarget)
15283       UpdateUncondBr(Br, Dest, DAG);
15284 
15285     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15286                         SDValue(LoopDec.getNode(), 1), Chain);
15287 
15288     SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
15289     return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
15290   }
15291   return SDValue();
15292 }
15293 
15294 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
15295 SDValue
15296 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
15297   SDValue Cmp = N->getOperand(4);
15298   if (Cmp.getOpcode() != ARMISD::CMPZ)
15299     // Only looking at NE cases.
15300     return SDValue();
15301 
15302   EVT VT = N->getValueType(0);
15303   SDLoc dl(N);
15304   SDValue LHS = Cmp.getOperand(0);
15305   SDValue RHS = Cmp.getOperand(1);
15306   SDValue Chain = N->getOperand(0);
15307   SDValue BB = N->getOperand(1);
15308   SDValue ARMcc = N->getOperand(2);
15309   ARMCC::CondCodes CC =
15310     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
15311 
15312   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
15313   // -> (brcond Chain BB CC CPSR Cmp)
15314   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
15315       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
15316       LHS->getOperand(0)->hasOneUse()) {
15317     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
15318     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
15319     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
15320     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
15321     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
15322         (LHS01C && LHS01C->getZExtValue() == 1) &&
15323         (LHS1C && LHS1C->getZExtValue() == 1) &&
15324         (RHSC && RHSC->getZExtValue() == 0)) {
15325       return DAG.getNode(
15326           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
15327           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
15328     }
15329   }
15330 
15331   return SDValue();
15332 }
15333 
15334 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
15335 SDValue
15336 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
15337   SDValue Cmp = N->getOperand(4);
15338   if (Cmp.getOpcode() != ARMISD::CMPZ)
15339     // Only looking at EQ and NE cases.
15340     return SDValue();
15341 
15342   EVT VT = N->getValueType(0);
15343   SDLoc dl(N);
15344   SDValue LHS = Cmp.getOperand(0);
15345   SDValue RHS = Cmp.getOperand(1);
15346   SDValue FalseVal = N->getOperand(0);
15347   SDValue TrueVal = N->getOperand(1);
15348   SDValue ARMcc = N->getOperand(2);
15349   ARMCC::CondCodes CC =
15350     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
15351 
15352   // BFI is only available on V6T2+.
15353   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
15354     SDValue R = PerformCMOVToBFICombine(N, DAG);
15355     if (R)
15356       return R;
15357   }
15358 
15359   // Simplify
15360   //   mov     r1, r0
15361   //   cmp     r1, x
15362   //   mov     r0, y
15363   //   moveq   r0, x
15364   // to
15365   //   cmp     r0, x
15366   //   movne   r0, y
15367   //
15368   //   mov     r1, r0
15369   //   cmp     r1, x
15370   //   mov     r0, x
15371   //   movne   r0, y
15372   // to
15373   //   cmp     r0, x
15374   //   movne   r0, y
15375   /// FIXME: Turn this into a target neutral optimization?
15376   SDValue Res;
15377   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
15378     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
15379                       N->getOperand(3), Cmp);
15380   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
15381     SDValue ARMcc;
15382     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
15383     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
15384                       N->getOperand(3), NewCmp);
15385   }
15386 
15387   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
15388   // -> (cmov F T CC CPSR Cmp)
15389   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
15390     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
15391     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
15392     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
15393     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
15394         (LHS1C && LHS1C->getZExtValue() == 1) &&
15395         (RHSC && RHSC->getZExtValue() == 0)) {
15396       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
15397                          LHS->getOperand(2), LHS->getOperand(3),
15398                          LHS->getOperand(4));
15399     }
15400   }
15401 
15402   if (!VT.isInteger())
15403       return SDValue();
15404 
15405   // Materialize a boolean comparison for integers so we can avoid branching.
15406   if (isNullConstant(FalseVal)) {
15407     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
15408       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
15409         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
15410         // right 5 bits will make that 32 be 1, otherwise it will be 0.
15411         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
15412         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
15413         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
15414                           DAG.getConstant(5, dl, MVT::i32));
15415       } else {
15416         // CMOV 0, 1, ==, (CMPZ x, y) ->
15417         //     (ADDCARRY (SUB x, y), t:0, t:1)
15418         // where t = (SUBCARRY 0, (SUB x, y), 0)
15419         //
15420         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
15421         // x != y. In other words, a carry C == 1 when x == y, C == 0
15422         // otherwise.
15423         // The final ADDCARRY computes
15424         //     x - y + (0 - (x - y)) + C == C
15425         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
15426         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15427         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
15428         // ISD::SUBCARRY returns a borrow but we want the carry here
15429         // actually.
15430         SDValue Carry =
15431             DAG.getNode(ISD::SUB, dl, MVT::i32,
15432                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
15433         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
15434       }
15435     } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
15436                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
15437       // This seems pointless but will allow us to combine it further below.
15438       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
15439       SDValue Sub =
15440           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
15441       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
15442                                           Sub.getValue(1), SDValue());
15443       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
15444                         N->getOperand(3), CPSRGlue.getValue(1));
15445       FalseVal = Sub;
15446     }
15447   } else if (isNullConstant(TrueVal)) {
15448     if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
15449         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
15450       // This seems pointless but will allow us to combine it further below
15451       // Note that we change == for != as this is the dual for the case above.
15452       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
15453       SDValue Sub =
15454           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
15455       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
15456                                           Sub.getValue(1), SDValue());
15457       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
15458                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
15459                         N->getOperand(3), CPSRGlue.getValue(1));
15460       FalseVal = Sub;
15461     }
15462   }
15463 
15464   // On Thumb1, the DAG above may be further combined if z is a power of 2
15465   // (z == 2 ^ K).
15466   // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
15467   // t1 = (USUBO (SUB x, y), 1)
15468   // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
15469   // Result = if K != 0 then (SHL t2:0, K) else t2:0
15470   //
15471   // This also handles the special case of comparing against zero; it's
15472   // essentially, the same pattern, except there's no SUBS:
15473   // CMOV x, z, !=, (CMPZ x, 0) ->
15474   // t1 = (USUBO x, 1)
15475   // t2 = (SUBCARRY x, t1:0, t1:1)
15476   // Result = if K != 0 then (SHL t2:0, K) else t2:0
15477   const APInt *TrueConst;
15478   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
15479       ((FalseVal.getOpcode() == ARMISD::SUBS &&
15480         FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
15481        (FalseVal == LHS && isNullConstant(RHS))) &&
15482       (TrueConst = isPowerOf2Constant(TrueVal))) {
15483     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15484     unsigned ShiftAmount = TrueConst->logBase2();
15485     if (ShiftAmount)
15486       TrueVal = DAG.getConstant(1, dl, VT);
15487     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
15488     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
15489 
15490     if (ShiftAmount)
15491       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
15492                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
15493   }
15494 
15495   if (Res.getNode()) {
15496     KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
15497     // Capture demanded bits information that would be otherwise lost.
15498     if (Known.Zero == 0xfffffffe)
15499       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
15500                         DAG.getValueType(MVT::i1));
15501     else if (Known.Zero == 0xffffff00)
15502       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
15503                         DAG.getValueType(MVT::i8));
15504     else if (Known.Zero == 0xffff0000)
15505       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
15506                         DAG.getValueType(MVT::i16));
15507   }
15508 
15509   return Res;
15510 }
15511 
15512 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
15513                                     const ARMSubtarget *ST) {
15514   SDValue Src = N->getOperand(0);
15515   EVT DstVT = N->getValueType(0);
15516 
15517   // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
15518   if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
15519     EVT SrcVT = Src.getValueType();
15520     if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
15521       return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
15522   }
15523 
15524   // We may have a bitcast of something that has already had this bitcast
15525   // combine performed on it, so skip past any VECTOR_REG_CASTs.
15526   while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST)
15527     Src = Src.getOperand(0);
15528 
15529   // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
15530   // would be generated is at least the width of the element type.
15531   EVT SrcVT = Src.getValueType();
15532   if ((Src.getOpcode() == ARMISD::VMOVIMM ||
15533        Src.getOpcode() == ARMISD::VMVNIMM ||
15534        Src.getOpcode() == ARMISD::VMOVFPIMM) &&
15535       SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
15536       DAG.getDataLayout().isBigEndian())
15537     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
15538 
15539   return SDValue();
15540 }
15541 
15542 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
15543                                              DAGCombinerInfo &DCI) const {
15544   switch (N->getOpcode()) {
15545   default: break;
15546   case ISD::VSELECT:    return PerformVSELECTCombine(N, DCI, Subtarget);
15547   case ISD::ABS:        return PerformABSCombine(N, DCI, Subtarget);
15548   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
15549   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
15550   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
15551   case ISD::SUB:        return PerformSUBCombine(N, DCI, Subtarget);
15552   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
15553   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
15554   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
15555   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
15556   case ISD::BRCOND:
15557   case ISD::BR_CC:      return PerformHWLoopCombine(N, DCI, Subtarget);
15558   case ARMISD::ADDC:
15559   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
15560   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
15561   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
15562   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
15563   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
15564   case ARMISD::VMOVhr:  return PerformVMOVhrCombine(N, DCI);
15565   case ARMISD::VMOVrh:  return PerformVMOVrhCombine(N, DCI);
15566   case ISD::STORE:      return PerformSTORECombine(N, DCI, Subtarget);
15567   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
15568   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
15569   case ISD::EXTRACT_VECTOR_ELT: return PerformExtractEltCombine(N, DCI);
15570   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
15571   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
15572   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
15573   case ISD::FP_TO_SINT:
15574   case ISD::FP_TO_UINT:
15575     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
15576   case ISD::FDIV:
15577     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
15578   case ISD::INTRINSIC_WO_CHAIN:
15579     return PerformIntrinsicCombine(N, DCI);
15580   case ISD::SHL:
15581   case ISD::SRA:
15582   case ISD::SRL:
15583     return PerformShiftCombine(N, DCI, Subtarget);
15584   case ISD::SIGN_EXTEND:
15585   case ISD::ZERO_EXTEND:
15586   case ISD::ANY_EXTEND:
15587     return PerformExtendCombine(N, DCI.DAG, Subtarget);
15588   case ISD::SMIN:
15589   case ISD::UMIN:
15590   case ISD::SMAX:
15591   case ISD::UMAX:
15592     return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
15593   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
15594   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
15595   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
15596   case ARMISD::VLD1DUP:
15597   case ARMISD::VLD2DUP:
15598   case ARMISD::VLD3DUP:
15599   case ARMISD::VLD4DUP:
15600     return PerformVLDCombine(N, DCI);
15601   case ARMISD::BUILD_VECTOR:
15602     return PerformARMBUILD_VECTORCombine(N, DCI);
15603   case ISD::BITCAST:
15604     return PerformBITCASTCombine(N, DCI.DAG, Subtarget);
15605   case ARMISD::PREDICATE_CAST:
15606     return PerformPREDICATE_CASTCombine(N, DCI);
15607   case ARMISD::VECTOR_REG_CAST:
15608     return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget);
15609   case ARMISD::VCMP:
15610     return PerformVCMPCombine(N, DCI, Subtarget);
15611   case ISD::VECREDUCE_ADD:
15612     return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
15613   case ARMISD::VMOVN:
15614     return PerformVMOVNCombine(N, DCI);
15615   case ARMISD::VQMOVNs:
15616   case ARMISD::VQMOVNu:
15617     return PerformVQMOVNCombine(N, DCI);
15618   case ARMISD::ASRL:
15619   case ARMISD::LSRL:
15620   case ARMISD::LSLL:
15621     return PerformLongShiftCombine(N, DCI.DAG);
15622   case ARMISD::SMULWB: {
15623     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15624     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
15625     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
15626       return SDValue();
15627     break;
15628   }
15629   case ARMISD::SMULWT: {
15630     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15631     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
15632     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
15633       return SDValue();
15634     break;
15635   }
15636   case ARMISD::SMLALBB:
15637   case ARMISD::QADD16b:
15638   case ARMISD::QSUB16b: {
15639     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15640     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
15641     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
15642         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
15643       return SDValue();
15644     break;
15645   }
15646   case ARMISD::SMLALBT: {
15647     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
15648     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
15649     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
15650     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
15651     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
15652         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
15653       return SDValue();
15654     break;
15655   }
15656   case ARMISD::SMLALTB: {
15657     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
15658     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
15659     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
15660     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
15661     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
15662         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
15663       return SDValue();
15664     break;
15665   }
15666   case ARMISD::SMLALTT: {
15667     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15668     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
15669     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
15670         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
15671       return SDValue();
15672     break;
15673   }
15674   case ARMISD::QADD8b:
15675   case ARMISD::QSUB8b: {
15676     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15677     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
15678     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
15679         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
15680       return SDValue();
15681     break;
15682   }
15683   case ISD::INTRINSIC_VOID:
15684   case ISD::INTRINSIC_W_CHAIN:
15685     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15686     case Intrinsic::arm_neon_vld1:
15687     case Intrinsic::arm_neon_vld1x2:
15688     case Intrinsic::arm_neon_vld1x3:
15689     case Intrinsic::arm_neon_vld1x4:
15690     case Intrinsic::arm_neon_vld2:
15691     case Intrinsic::arm_neon_vld3:
15692     case Intrinsic::arm_neon_vld4:
15693     case Intrinsic::arm_neon_vld2lane:
15694     case Intrinsic::arm_neon_vld3lane:
15695     case Intrinsic::arm_neon_vld4lane:
15696     case Intrinsic::arm_neon_vld2dup:
15697     case Intrinsic::arm_neon_vld3dup:
15698     case Intrinsic::arm_neon_vld4dup:
15699     case Intrinsic::arm_neon_vst1:
15700     case Intrinsic::arm_neon_vst1x2:
15701     case Intrinsic::arm_neon_vst1x3:
15702     case Intrinsic::arm_neon_vst1x4:
15703     case Intrinsic::arm_neon_vst2:
15704     case Intrinsic::arm_neon_vst3:
15705     case Intrinsic::arm_neon_vst4:
15706     case Intrinsic::arm_neon_vst2lane:
15707     case Intrinsic::arm_neon_vst3lane:
15708     case Intrinsic::arm_neon_vst4lane:
15709       return PerformVLDCombine(N, DCI);
15710     case Intrinsic::arm_mve_vld2q:
15711     case Intrinsic::arm_mve_vld4q:
15712     case Intrinsic::arm_mve_vst2q:
15713     case Intrinsic::arm_mve_vst4q:
15714       return PerformMVEVLDCombine(N, DCI);
15715     default: break;
15716     }
15717     break;
15718   }
15719   return SDValue();
15720 }
15721 
15722 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
15723                                                           EVT VT) const {
15724   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
15725 }
15726 
15727 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
15728                                                        unsigned Alignment,
15729                                                        MachineMemOperand::Flags,
15730                                                        bool *Fast) const {
15731   // Depends what it gets converted into if the type is weird.
15732   if (!VT.isSimple())
15733     return false;
15734 
15735   // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
15736   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
15737   auto Ty = VT.getSimpleVT().SimpleTy;
15738 
15739   if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
15740     // Unaligned access can use (for example) LRDB, LRDH, LDR
15741     if (AllowsUnaligned) {
15742       if (Fast)
15743         *Fast = Subtarget->hasV7Ops();
15744       return true;
15745     }
15746   }
15747 
15748   if (Ty == MVT::f64 || Ty == MVT::v2f64) {
15749     // For any little-endian targets with neon, we can support unaligned ld/st
15750     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
15751     // A big-endian target may also explicitly support unaligned accesses
15752     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
15753       if (Fast)
15754         *Fast = true;
15755       return true;
15756     }
15757   }
15758 
15759   if (!Subtarget->hasMVEIntegerOps())
15760     return false;
15761 
15762   // These are for predicates
15763   if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
15764     if (Fast)
15765       *Fast = true;
15766     return true;
15767   }
15768 
15769   // These are for truncated stores/narrowing loads. They are fine so long as
15770   // the alignment is at least the size of the item being loaded
15771   if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
15772       Alignment >= VT.getScalarSizeInBits() / 8) {
15773     if (Fast)
15774       *Fast = true;
15775     return true;
15776   }
15777 
15778   // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
15779   // VSTRW.U32 all store the vector register in exactly the same format, and
15780   // differ only in the range of their immediate offset field and the required
15781   // alignment. So there is always a store that can be used, regardless of
15782   // actual type.
15783   //
15784   // For big endian, that is not the case. But can still emit a (VSTRB.U8;
15785   // VREV64.8) pair and get the same effect. This will likely be better than
15786   // aligning the vector through the stack.
15787   if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
15788       Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
15789       Ty == MVT::v2f64) {
15790     if (Fast)
15791       *Fast = true;
15792     return true;
15793   }
15794 
15795   return false;
15796 }
15797 
15798 
15799 EVT ARMTargetLowering::getOptimalMemOpType(
15800     const MemOp &Op, const AttributeList &FuncAttributes) const {
15801   // See if we can use NEON instructions for this...
15802   if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
15803       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15804     bool Fast;
15805     if (Op.size() >= 16 &&
15806         (Op.isAligned(Align(16)) ||
15807          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
15808                                          MachineMemOperand::MONone, &Fast) &&
15809           Fast))) {
15810       return MVT::v2f64;
15811     } else if (Op.size() >= 8 &&
15812                (Op.isAligned(Align(8)) ||
15813                 (allowsMisalignedMemoryAccesses(
15814                      MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
15815                  Fast))) {
15816       return MVT::f64;
15817     }
15818   }
15819 
15820   // Let the target-independent logic figure it out.
15821   return MVT::Other;
15822 }
15823 
15824 // 64-bit integers are split into their high and low parts and held in two
15825 // different registers, so the trunc is free since the low register can just
15826 // be used.
15827 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
15828   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
15829     return false;
15830   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
15831   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
15832   return (SrcBits == 64 && DestBits == 32);
15833 }
15834 
15835 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
15836   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
15837       !DstVT.isInteger())
15838     return false;
15839   unsigned SrcBits = SrcVT.getSizeInBits();
15840   unsigned DestBits = DstVT.getSizeInBits();
15841   return (SrcBits == 64 && DestBits == 32);
15842 }
15843 
15844 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15845   if (Val.getOpcode() != ISD::LOAD)
15846     return false;
15847 
15848   EVT VT1 = Val.getValueType();
15849   if (!VT1.isSimple() || !VT1.isInteger() ||
15850       !VT2.isSimple() || !VT2.isInteger())
15851     return false;
15852 
15853   switch (VT1.getSimpleVT().SimpleTy) {
15854   default: break;
15855   case MVT::i1:
15856   case MVT::i8:
15857   case MVT::i16:
15858     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
15859     return true;
15860   }
15861 
15862   return false;
15863 }
15864 
15865 bool ARMTargetLowering::isFNegFree(EVT VT) const {
15866   if (!VT.isSimple())
15867     return false;
15868 
15869   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
15870   // negate values directly (fneg is free). So, we don't want to let the DAG
15871   // combiner rewrite fneg into xors and some other instructions.  For f16 and
15872   // FullFP16 argument passing, some bitcast nodes may be introduced,
15873   // triggering this DAG combine rewrite, so we are avoiding that with this.
15874   switch (VT.getSimpleVT().SimpleTy) {
15875   default: break;
15876   case MVT::f16:
15877     return Subtarget->hasFullFP16();
15878   }
15879 
15880   return false;
15881 }
15882 
15883 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
15884 /// of the vector elements.
15885 static bool areExtractExts(Value *Ext1, Value *Ext2) {
15886   auto areExtDoubled = [](Instruction *Ext) {
15887     return Ext->getType()->getScalarSizeInBits() ==
15888            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
15889   };
15890 
15891   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
15892       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
15893       !areExtDoubled(cast<Instruction>(Ext1)) ||
15894       !areExtDoubled(cast<Instruction>(Ext2)))
15895     return false;
15896 
15897   return true;
15898 }
15899 
15900 /// Check if sinking \p I's operands to I's basic block is profitable, because
15901 /// the operands can be folded into a target instruction, e.g.
15902 /// sext/zext can be folded into vsubl.
15903 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
15904                                            SmallVectorImpl<Use *> &Ops) const {
15905   if (!I->getType()->isVectorTy())
15906     return false;
15907 
15908   if (Subtarget->hasNEON()) {
15909     switch (I->getOpcode()) {
15910     case Instruction::Sub:
15911     case Instruction::Add: {
15912       if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
15913         return false;
15914       Ops.push_back(&I->getOperandUse(0));
15915       Ops.push_back(&I->getOperandUse(1));
15916       return true;
15917     }
15918     default:
15919       return false;
15920     }
15921   }
15922 
15923   if (!Subtarget->hasMVEIntegerOps())
15924     return false;
15925 
15926   auto IsFMSMul = [&](Instruction *I) {
15927     if (!I->hasOneUse())
15928       return false;
15929     auto *Sub = cast<Instruction>(*I->users().begin());
15930     return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I;
15931   };
15932   auto IsFMS = [&](Instruction *I) {
15933     if (match(I->getOperand(0), m_FNeg(m_Value())) ||
15934         match(I->getOperand(1), m_FNeg(m_Value())))
15935       return true;
15936     return false;
15937   };
15938 
15939   auto IsSinker = [&](Instruction *I, int Operand) {
15940     switch (I->getOpcode()) {
15941     case Instruction::Add:
15942     case Instruction::Mul:
15943     case Instruction::FAdd:
15944     case Instruction::ICmp:
15945     case Instruction::FCmp:
15946       return true;
15947     case Instruction::FMul:
15948       return !IsFMSMul(I);
15949     case Instruction::Sub:
15950     case Instruction::FSub:
15951     case Instruction::Shl:
15952     case Instruction::LShr:
15953     case Instruction::AShr:
15954       return Operand == 1;
15955     case Instruction::Call:
15956       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
15957         switch (II->getIntrinsicID()) {
15958         case Intrinsic::fma:
15959           return !IsFMS(I);
15960         default:
15961           return false;
15962         }
15963       }
15964       return false;
15965     default:
15966       return false;
15967     }
15968   };
15969 
15970   for (auto OpIdx : enumerate(I->operands())) {
15971     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
15972     // Make sure we are not already sinking this operand
15973     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
15974       continue;
15975 
15976     Instruction *Shuffle = Op;
15977     if (Shuffle->getOpcode() == Instruction::BitCast)
15978       Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0));
15979     // We are looking for a splat that can be sunk.
15980     if (!Shuffle ||
15981         !match(Shuffle, m_Shuffle(
15982                             m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
15983                             m_Undef(), m_ZeroMask())))
15984       continue;
15985     if (!IsSinker(I, OpIdx.index()))
15986       continue;
15987 
15988     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
15989     // and vector registers
15990     for (Use &U : Op->uses()) {
15991       Instruction *Insn = cast<Instruction>(U.getUser());
15992       if (!IsSinker(Insn, U.getOperandNo()))
15993         return false;
15994     }
15995 
15996     Ops.push_back(&Shuffle->getOperandUse(0));
15997     if (Shuffle != Op)
15998       Ops.push_back(&Op->getOperandUse(0));
15999     Ops.push_back(&OpIdx.value());
16000   }
16001   return true;
16002 }
16003 
16004 Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const {
16005   if (!Subtarget->hasMVEIntegerOps())
16006     return nullptr;
16007   Type *SVIType = SVI->getType();
16008   Type *ScalarType = SVIType->getScalarType();
16009 
16010   if (ScalarType->isFloatTy())
16011     return Type::getInt32Ty(SVIType->getContext());
16012   if (ScalarType->isHalfTy())
16013     return Type::getInt16Ty(SVIType->getContext());
16014   return nullptr;
16015 }
16016 
16017 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
16018   EVT VT = ExtVal.getValueType();
16019 
16020   if (!isTypeLegal(VT))
16021     return false;
16022 
16023   if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
16024     if (Ld->isExpandingLoad())
16025       return false;
16026   }
16027 
16028   if (Subtarget->hasMVEIntegerOps())
16029     return true;
16030 
16031   // Don't create a loadext if we can fold the extension into a wide/long
16032   // instruction.
16033   // If there's more than one user instruction, the loadext is desirable no
16034   // matter what.  There can be two uses by the same instruction.
16035   if (ExtVal->use_empty() ||
16036       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
16037     return true;
16038 
16039   SDNode *U = *ExtVal->use_begin();
16040   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
16041        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
16042     return false;
16043 
16044   return true;
16045 }
16046 
16047 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16048   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16049     return false;
16050 
16051   if (!isTypeLegal(EVT::getEVT(Ty1)))
16052     return false;
16053 
16054   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16055 
16056   // Assuming the caller doesn't have a zeroext or signext return parameter,
16057   // truncation all the way down to i1 is valid.
16058   return true;
16059 }
16060 
16061 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
16062                                                 const AddrMode &AM, Type *Ty,
16063                                                 unsigned AS) const {
16064   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
16065     if (Subtarget->hasFPAO())
16066       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
16067     return 0;
16068   }
16069   return -1;
16070 }
16071 
16072 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
16073 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
16074 /// expanded to FMAs when this method returns true, otherwise fmuladd is
16075 /// expanded to fmul + fadd.
16076 ///
16077 /// ARM supports both fused and unfused multiply-add operations; we already
16078 /// lower a pair of fmul and fadd to the latter so it's not clear that there
16079 /// would be a gain or that the gain would be worthwhile enough to risk
16080 /// correctness bugs.
16081 ///
16082 /// For MVE, we set this to true as it helps simplify the need for some
16083 /// patterns (and we don't have the non-fused floating point instruction).
16084 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16085                                                    EVT VT) const {
16086   if (!VT.isSimple())
16087     return false;
16088 
16089   switch (VT.getSimpleVT().SimpleTy) {
16090   case MVT::v4f32:
16091   case MVT::v8f16:
16092     return Subtarget->hasMVEFloatOps();
16093   case MVT::f16:
16094     return Subtarget->useFPVFMx16();
16095   case MVT::f32:
16096     return Subtarget->useFPVFMx();
16097   case MVT::f64:
16098     return Subtarget->useFPVFMx64();
16099   default:
16100     break;
16101   }
16102 
16103   return false;
16104 }
16105 
16106 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
16107   if (V < 0)
16108     return false;
16109 
16110   unsigned Scale = 1;
16111   switch (VT.getSimpleVT().SimpleTy) {
16112   case MVT::i1:
16113   case MVT::i8:
16114     // Scale == 1;
16115     break;
16116   case MVT::i16:
16117     // Scale == 2;
16118     Scale = 2;
16119     break;
16120   default:
16121     // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
16122     // Scale == 4;
16123     Scale = 4;
16124     break;
16125   }
16126 
16127   if ((V & (Scale - 1)) != 0)
16128     return false;
16129   return isUInt<5>(V / Scale);
16130 }
16131 
16132 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
16133                                       const ARMSubtarget *Subtarget) {
16134   if (!VT.isInteger() && !VT.isFloatingPoint())
16135     return false;
16136   if (VT.isVector() && Subtarget->hasNEON())
16137     return false;
16138   if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
16139       !Subtarget->hasMVEFloatOps())
16140     return false;
16141 
16142   bool IsNeg = false;
16143   if (V < 0) {
16144     IsNeg = true;
16145     V = -V;
16146   }
16147 
16148   unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
16149 
16150   // MVE: size * imm7
16151   if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
16152     switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
16153     case MVT::i32:
16154     case MVT::f32:
16155       return isShiftedUInt<7,2>(V);
16156     case MVT::i16:
16157     case MVT::f16:
16158       return isShiftedUInt<7,1>(V);
16159     case MVT::i8:
16160       return isUInt<7>(V);
16161     default:
16162       return false;
16163     }
16164   }
16165 
16166   // half VLDR: 2 * imm8
16167   if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
16168     return isShiftedUInt<8, 1>(V);
16169   // VLDR and LDRD: 4 * imm8
16170   if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
16171     return isShiftedUInt<8, 2>(V);
16172 
16173   if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
16174     // + imm12 or - imm8
16175     if (IsNeg)
16176       return isUInt<8>(V);
16177     return isUInt<12>(V);
16178   }
16179 
16180   return false;
16181 }
16182 
16183 /// isLegalAddressImmediate - Return true if the integer value can be used
16184 /// as the offset of the target addressing mode for load / store of the
16185 /// given type.
16186 static bool isLegalAddressImmediate(int64_t V, EVT VT,
16187                                     const ARMSubtarget *Subtarget) {
16188   if (V == 0)
16189     return true;
16190 
16191   if (!VT.isSimple())
16192     return false;
16193 
16194   if (Subtarget->isThumb1Only())
16195     return isLegalT1AddressImmediate(V, VT);
16196   else if (Subtarget->isThumb2())
16197     return isLegalT2AddressImmediate(V, VT, Subtarget);
16198 
16199   // ARM mode.
16200   if (V < 0)
16201     V = - V;
16202   switch (VT.getSimpleVT().SimpleTy) {
16203   default: return false;
16204   case MVT::i1:
16205   case MVT::i8:
16206   case MVT::i32:
16207     // +- imm12
16208     return isUInt<12>(V);
16209   case MVT::i16:
16210     // +- imm8
16211     return isUInt<8>(V);
16212   case MVT::f32:
16213   case MVT::f64:
16214     if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
16215       return false;
16216     return isShiftedUInt<8, 2>(V);
16217   }
16218 }
16219 
16220 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
16221                                                       EVT VT) const {
16222   int Scale = AM.Scale;
16223   if (Scale < 0)
16224     return false;
16225 
16226   switch (VT.getSimpleVT().SimpleTy) {
16227   default: return false;
16228   case MVT::i1:
16229   case MVT::i8:
16230   case MVT::i16:
16231   case MVT::i32:
16232     if (Scale == 1)
16233       return true;
16234     // r + r << imm
16235     Scale = Scale & ~1;
16236     return Scale == 2 || Scale == 4 || Scale == 8;
16237   case MVT::i64:
16238     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
16239     // version in Thumb mode.
16240     // r + r
16241     if (Scale == 1)
16242       return true;
16243     // r * 2 (this can be lowered to r + r).
16244     if (!AM.HasBaseReg && Scale == 2)
16245       return true;
16246     return false;
16247   case MVT::isVoid:
16248     // Note, we allow "void" uses (basically, uses that aren't loads or
16249     // stores), because arm allows folding a scale into many arithmetic
16250     // operations.  This should be made more precise and revisited later.
16251 
16252     // Allow r << imm, but the imm has to be a multiple of two.
16253     if (Scale & 1) return false;
16254     return isPowerOf2_32(Scale);
16255   }
16256 }
16257 
16258 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
16259                                                       EVT VT) const {
16260   const int Scale = AM.Scale;
16261 
16262   // Negative scales are not supported in Thumb1.
16263   if (Scale < 0)
16264     return false;
16265 
16266   // Thumb1 addressing modes do not support register scaling excepting the
16267   // following cases:
16268   // 1. Scale == 1 means no scaling.
16269   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
16270   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
16271 }
16272 
16273 /// isLegalAddressingMode - Return true if the addressing mode represented
16274 /// by AM is legal for this target, for a load/store of the specified type.
16275 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16276                                               const AddrMode &AM, Type *Ty,
16277                                               unsigned AS, Instruction *I) const {
16278   EVT VT = getValueType(DL, Ty, true);
16279   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
16280     return false;
16281 
16282   // Can never fold addr of global into load/store.
16283   if (AM.BaseGV)
16284     return false;
16285 
16286   switch (AM.Scale) {
16287   case 0:  // no scale reg, must be "r+i" or "r", or "i".
16288     break;
16289   default:
16290     // ARM doesn't support any R+R*scale+imm addr modes.
16291     if (AM.BaseOffs)
16292       return false;
16293 
16294     if (!VT.isSimple())
16295       return false;
16296 
16297     if (Subtarget->isThumb1Only())
16298       return isLegalT1ScaledAddressingMode(AM, VT);
16299 
16300     if (Subtarget->isThumb2())
16301       return isLegalT2ScaledAddressingMode(AM, VT);
16302 
16303     int Scale = AM.Scale;
16304     switch (VT.getSimpleVT().SimpleTy) {
16305     default: return false;
16306     case MVT::i1:
16307     case MVT::i8:
16308     case MVT::i32:
16309       if (Scale < 0) Scale = -Scale;
16310       if (Scale == 1)
16311         return true;
16312       // r + r << imm
16313       return isPowerOf2_32(Scale & ~1);
16314     case MVT::i16:
16315     case MVT::i64:
16316       // r +/- r
16317       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
16318         return true;
16319       // r * 2 (this can be lowered to r + r).
16320       if (!AM.HasBaseReg && Scale == 2)
16321         return true;
16322       return false;
16323 
16324     case MVT::isVoid:
16325       // Note, we allow "void" uses (basically, uses that aren't loads or
16326       // stores), because arm allows folding a scale into many arithmetic
16327       // operations.  This should be made more precise and revisited later.
16328 
16329       // Allow r << imm, but the imm has to be a multiple of two.
16330       if (Scale & 1) return false;
16331       return isPowerOf2_32(Scale);
16332     }
16333   }
16334   return true;
16335 }
16336 
16337 /// isLegalICmpImmediate - Return true if the specified immediate is legal
16338 /// icmp immediate, that is the target has icmp instructions which can compare
16339 /// a register against the immediate without having to materialize the
16340 /// immediate into a register.
16341 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16342   // Thumb2 and ARM modes can use cmn for negative immediates.
16343   if (!Subtarget->isThumb())
16344     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
16345            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
16346   if (Subtarget->isThumb2())
16347     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
16348            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
16349   // Thumb1 doesn't have cmn, and only 8-bit immediates.
16350   return Imm >= 0 && Imm <= 255;
16351 }
16352 
16353 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
16354 /// *or sub* immediate, that is the target has add or sub instructions which can
16355 /// add a register with the immediate without having to materialize the
16356 /// immediate into a register.
16357 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16358   // Same encoding for add/sub, just flip the sign.
16359   int64_t AbsImm = std::abs(Imm);
16360   if (!Subtarget->isThumb())
16361     return ARM_AM::getSOImmVal(AbsImm) != -1;
16362   if (Subtarget->isThumb2())
16363     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
16364   // Thumb1 only has 8-bit unsigned immediate.
16365   return AbsImm >= 0 && AbsImm <= 255;
16366 }
16367 
16368 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
16369                                       bool isSEXTLoad, SDValue &Base,
16370                                       SDValue &Offset, bool &isInc,
16371                                       SelectionDAG &DAG) {
16372   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
16373     return false;
16374 
16375   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
16376     // AddressingMode 3
16377     Base = Ptr->getOperand(0);
16378     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
16379       int RHSC = (int)RHS->getZExtValue();
16380       if (RHSC < 0 && RHSC > -256) {
16381         assert(Ptr->getOpcode() == ISD::ADD);
16382         isInc = false;
16383         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16384         return true;
16385       }
16386     }
16387     isInc = (Ptr->getOpcode() == ISD::ADD);
16388     Offset = Ptr->getOperand(1);
16389     return true;
16390   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
16391     // AddressingMode 2
16392     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
16393       int RHSC = (int)RHS->getZExtValue();
16394       if (RHSC < 0 && RHSC > -0x1000) {
16395         assert(Ptr->getOpcode() == ISD::ADD);
16396         isInc = false;
16397         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16398         Base = Ptr->getOperand(0);
16399         return true;
16400       }
16401     }
16402 
16403     if (Ptr->getOpcode() == ISD::ADD) {
16404       isInc = true;
16405       ARM_AM::ShiftOpc ShOpcVal=
16406         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
16407       if (ShOpcVal != ARM_AM::no_shift) {
16408         Base = Ptr->getOperand(1);
16409         Offset = Ptr->getOperand(0);
16410       } else {
16411         Base = Ptr->getOperand(0);
16412         Offset = Ptr->getOperand(1);
16413       }
16414       return true;
16415     }
16416 
16417     isInc = (Ptr->getOpcode() == ISD::ADD);
16418     Base = Ptr->getOperand(0);
16419     Offset = Ptr->getOperand(1);
16420     return true;
16421   }
16422 
16423   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
16424   return false;
16425 }
16426 
16427 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
16428                                      bool isSEXTLoad, SDValue &Base,
16429                                      SDValue &Offset, bool &isInc,
16430                                      SelectionDAG &DAG) {
16431   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
16432     return false;
16433 
16434   Base = Ptr->getOperand(0);
16435   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
16436     int RHSC = (int)RHS->getZExtValue();
16437     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
16438       assert(Ptr->getOpcode() == ISD::ADD);
16439       isInc = false;
16440       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16441       return true;
16442     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
16443       isInc = Ptr->getOpcode() == ISD::ADD;
16444       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
16445       return true;
16446     }
16447   }
16448 
16449   return false;
16450 }
16451 
16452 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align,
16453                                       bool isSEXTLoad, bool IsMasked, bool isLE,
16454                                       SDValue &Base, SDValue &Offset,
16455                                       bool &isInc, SelectionDAG &DAG) {
16456   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
16457     return false;
16458   if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
16459     return false;
16460 
16461   // We allow LE non-masked loads to change the type (for example use a vldrb.8
16462   // as opposed to a vldrw.32). This can allow extra addressing modes or
16463   // alignments for what is otherwise an equivalent instruction.
16464   bool CanChangeType = isLE && !IsMasked;
16465 
16466   ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
16467   int RHSC = (int)RHS->getZExtValue();
16468 
16469   auto IsInRange = [&](int RHSC, int Limit, int Scale) {
16470     if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
16471       assert(Ptr->getOpcode() == ISD::ADD);
16472       isInc = false;
16473       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16474       return true;
16475     } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
16476       isInc = Ptr->getOpcode() == ISD::ADD;
16477       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
16478       return true;
16479     }
16480     return false;
16481   };
16482 
16483   // Try to find a matching instruction based on s/zext, Alignment, Offset and
16484   // (in BE/masked) type.
16485   Base = Ptr->getOperand(0);
16486   if (VT == MVT::v4i16) {
16487     if (Align >= 2 && IsInRange(RHSC, 0x80, 2))
16488       return true;
16489   } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
16490     if (IsInRange(RHSC, 0x80, 1))
16491       return true;
16492   } else if (Align >= 4 &&
16493              (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
16494              IsInRange(RHSC, 0x80, 4))
16495     return true;
16496   else if (Align >= 2 &&
16497            (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
16498            IsInRange(RHSC, 0x80, 2))
16499     return true;
16500   else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
16501     return true;
16502   return false;
16503 }
16504 
16505 /// getPreIndexedAddressParts - returns true by value, base pointer and
16506 /// offset pointer and addressing mode by reference if the node's address
16507 /// can be legally represented as pre-indexed load / store address.
16508 bool
16509 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
16510                                              SDValue &Offset,
16511                                              ISD::MemIndexedMode &AM,
16512                                              SelectionDAG &DAG) const {
16513   if (Subtarget->isThumb1Only())
16514     return false;
16515 
16516   EVT VT;
16517   SDValue Ptr;
16518   unsigned Align;
16519   bool isSEXTLoad = false;
16520   bool IsMasked = false;
16521   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
16522     Ptr = LD->getBasePtr();
16523     VT = LD->getMemoryVT();
16524     Align = LD->getAlignment();
16525     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
16526   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
16527     Ptr = ST->getBasePtr();
16528     VT = ST->getMemoryVT();
16529     Align = ST->getAlignment();
16530   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
16531     Ptr = LD->getBasePtr();
16532     VT = LD->getMemoryVT();
16533     Align = LD->getAlignment();
16534     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
16535     IsMasked = true;
16536   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
16537     Ptr = ST->getBasePtr();
16538     VT = ST->getMemoryVT();
16539     Align = ST->getAlignment();
16540     IsMasked = true;
16541   } else
16542     return false;
16543 
16544   bool isInc;
16545   bool isLegal = false;
16546   if (VT.isVector())
16547     isLegal = Subtarget->hasMVEIntegerOps() &&
16548               getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad,
16549                                         IsMasked, Subtarget->isLittle(), Base,
16550                                         Offset, isInc, DAG);
16551   else {
16552     if (Subtarget->isThumb2())
16553       isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
16554                                          Offset, isInc, DAG);
16555     else
16556       isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
16557                                           Offset, isInc, DAG);
16558   }
16559   if (!isLegal)
16560     return false;
16561 
16562   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
16563   return true;
16564 }
16565 
16566 /// getPostIndexedAddressParts - returns true by value, base pointer and
16567 /// offset pointer and addressing mode by reference if this node can be
16568 /// combined with a load / store to form a post-indexed load / store.
16569 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
16570                                                    SDValue &Base,
16571                                                    SDValue &Offset,
16572                                                    ISD::MemIndexedMode &AM,
16573                                                    SelectionDAG &DAG) const {
16574   EVT VT;
16575   SDValue Ptr;
16576   unsigned Align;
16577   bool isSEXTLoad = false, isNonExt;
16578   bool IsMasked = false;
16579   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
16580     VT = LD->getMemoryVT();
16581     Ptr = LD->getBasePtr();
16582     Align = LD->getAlignment();
16583     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
16584     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
16585   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
16586     VT = ST->getMemoryVT();
16587     Ptr = ST->getBasePtr();
16588     Align = ST->getAlignment();
16589     isNonExt = !ST->isTruncatingStore();
16590   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
16591     VT = LD->getMemoryVT();
16592     Ptr = LD->getBasePtr();
16593     Align = LD->getAlignment();
16594     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
16595     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
16596     IsMasked = true;
16597   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
16598     VT = ST->getMemoryVT();
16599     Ptr = ST->getBasePtr();
16600     Align = ST->getAlignment();
16601     isNonExt = !ST->isTruncatingStore();
16602     IsMasked = true;
16603   } else
16604     return false;
16605 
16606   if (Subtarget->isThumb1Only()) {
16607     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
16608     // must be non-extending/truncating, i32, with an offset of 4.
16609     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
16610     if (Op->getOpcode() != ISD::ADD || !isNonExt)
16611       return false;
16612     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
16613     if (!RHS || RHS->getZExtValue() != 4)
16614       return false;
16615 
16616     Offset = Op->getOperand(1);
16617     Base = Op->getOperand(0);
16618     AM = ISD::POST_INC;
16619     return true;
16620   }
16621 
16622   bool isInc;
16623   bool isLegal = false;
16624   if (VT.isVector())
16625     isLegal = Subtarget->hasMVEIntegerOps() &&
16626               getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad, IsMasked,
16627                                         Subtarget->isLittle(), Base, Offset,
16628                                         isInc, DAG);
16629   else {
16630     if (Subtarget->isThumb2())
16631       isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
16632                                          isInc, DAG);
16633     else
16634       isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
16635                                           isInc, DAG);
16636   }
16637   if (!isLegal)
16638     return false;
16639 
16640   if (Ptr != Base) {
16641     // Swap base ptr and offset to catch more post-index load / store when
16642     // it's legal. In Thumb2 mode, offset must be an immediate.
16643     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
16644         !Subtarget->isThumb2())
16645       std::swap(Base, Offset);
16646 
16647     // Post-indexed load / store update the base pointer.
16648     if (Ptr != Base)
16649       return false;
16650   }
16651 
16652   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
16653   return true;
16654 }
16655 
16656 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
16657                                                       KnownBits &Known,
16658                                                       const APInt &DemandedElts,
16659                                                       const SelectionDAG &DAG,
16660                                                       unsigned Depth) const {
16661   unsigned BitWidth = Known.getBitWidth();
16662   Known.resetAll();
16663   switch (Op.getOpcode()) {
16664   default: break;
16665   case ARMISD::ADDC:
16666   case ARMISD::ADDE:
16667   case ARMISD::SUBC:
16668   case ARMISD::SUBE:
16669     // Special cases when we convert a carry to a boolean.
16670     if (Op.getResNo() == 0) {
16671       SDValue LHS = Op.getOperand(0);
16672       SDValue RHS = Op.getOperand(1);
16673       // (ADDE 0, 0, C) will give us a single bit.
16674       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
16675           isNullConstant(RHS)) {
16676         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16677         return;
16678       }
16679     }
16680     break;
16681   case ARMISD::CMOV: {
16682     // Bits are known zero/one if known on the LHS and RHS.
16683     Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
16684     if (Known.isUnknown())
16685       return;
16686 
16687     KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
16688     Known.Zero &= KnownRHS.Zero;
16689     Known.One  &= KnownRHS.One;
16690     return;
16691   }
16692   case ISD::INTRINSIC_W_CHAIN: {
16693     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
16694     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
16695     switch (IntID) {
16696     default: return;
16697     case Intrinsic::arm_ldaex:
16698     case Intrinsic::arm_ldrex: {
16699       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
16700       unsigned MemBits = VT.getScalarSizeInBits();
16701       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
16702       return;
16703     }
16704     }
16705   }
16706   case ARMISD::BFI: {
16707     // Conservatively, we can recurse down the first operand
16708     // and just mask out all affected bits.
16709     Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
16710 
16711     // The operand to BFI is already a mask suitable for removing the bits it
16712     // sets.
16713     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
16714     const APInt &Mask = CI->getAPIntValue();
16715     Known.Zero &= Mask;
16716     Known.One &= Mask;
16717     return;
16718   }
16719   case ARMISD::VGETLANEs:
16720   case ARMISD::VGETLANEu: {
16721     const SDValue &SrcSV = Op.getOperand(0);
16722     EVT VecVT = SrcSV.getValueType();
16723     assert(VecVT.isVector() && "VGETLANE expected a vector type");
16724     const unsigned NumSrcElts = VecVT.getVectorNumElements();
16725     ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
16726     assert(Pos->getAPIntValue().ult(NumSrcElts) &&
16727            "VGETLANE index out of bounds");
16728     unsigned Idx = Pos->getZExtValue();
16729     APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
16730     Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
16731 
16732     EVT VT = Op.getValueType();
16733     const unsigned DstSz = VT.getScalarSizeInBits();
16734     const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
16735     (void)SrcSz;
16736     assert(SrcSz == Known.getBitWidth());
16737     assert(DstSz > SrcSz);
16738     if (Op.getOpcode() == ARMISD::VGETLANEs)
16739       Known = Known.sext(DstSz);
16740     else {
16741       Known = Known.zext(DstSz);
16742     }
16743     assert(DstSz == Known.getBitWidth());
16744     break;
16745   }
16746   case ARMISD::VMOVrh: {
16747     KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
16748     assert(KnownOp.getBitWidth() == 16);
16749     Known = KnownOp.zext(32);
16750     break;
16751   }
16752   }
16753 }
16754 
16755 bool
16756 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
16757                                                 const APInt &DemandedAPInt,
16758                                                 TargetLoweringOpt &TLO) const {
16759   // Delay optimization, so we don't have to deal with illegal types, or block
16760   // optimizations.
16761   if (!TLO.LegalOps)
16762     return false;
16763 
16764   // Only optimize AND for now.
16765   if (Op.getOpcode() != ISD::AND)
16766     return false;
16767 
16768   EVT VT = Op.getValueType();
16769 
16770   // Ignore vectors.
16771   if (VT.isVector())
16772     return false;
16773 
16774   assert(VT == MVT::i32 && "Unexpected integer type");
16775 
16776   // Make sure the RHS really is a constant.
16777   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
16778   if (!C)
16779     return false;
16780 
16781   unsigned Mask = C->getZExtValue();
16782 
16783   unsigned Demanded = DemandedAPInt.getZExtValue();
16784   unsigned ShrunkMask = Mask & Demanded;
16785   unsigned ExpandedMask = Mask | ~Demanded;
16786 
16787   // If the mask is all zeros, let the target-independent code replace the
16788   // result with zero.
16789   if (ShrunkMask == 0)
16790     return false;
16791 
16792   // If the mask is all ones, erase the AND. (Currently, the target-independent
16793   // code won't do this, so we have to do it explicitly to avoid an infinite
16794   // loop in obscure cases.)
16795   if (ExpandedMask == ~0U)
16796     return TLO.CombineTo(Op, Op.getOperand(0));
16797 
16798   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
16799     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
16800   };
16801   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
16802     if (NewMask == Mask)
16803       return true;
16804     SDLoc DL(Op);
16805     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
16806     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
16807     return TLO.CombineTo(Op, NewOp);
16808   };
16809 
16810   // Prefer uxtb mask.
16811   if (IsLegalMask(0xFF))
16812     return UseMask(0xFF);
16813 
16814   // Prefer uxth mask.
16815   if (IsLegalMask(0xFFFF))
16816     return UseMask(0xFFFF);
16817 
16818   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
16819   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
16820   if (ShrunkMask < 256)
16821     return UseMask(ShrunkMask);
16822 
16823   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
16824   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
16825   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
16826     return UseMask(ExpandedMask);
16827 
16828   // Potential improvements:
16829   //
16830   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
16831   // We could try to prefer Thumb1 immediates which can be lowered to a
16832   // two-instruction sequence.
16833   // We could try to recognize more legal ARM/Thumb2 immediates here.
16834 
16835   return false;
16836 }
16837 
16838 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
16839     SDValue Op, const APInt &OriginalDemandedBits,
16840     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
16841     unsigned Depth) const {
16842   unsigned Opc = Op.getOpcode();
16843 
16844   switch (Opc) {
16845   case ARMISD::ASRL:
16846   case ARMISD::LSRL: {
16847     // If this is result 0 and the other result is unused, see if the demand
16848     // bits allow us to shrink this long shift into a standard small shift in
16849     // the opposite direction.
16850     if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
16851         isa<ConstantSDNode>(Op->getOperand(2))) {
16852       unsigned ShAmt = Op->getConstantOperandVal(2);
16853       if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(
16854                             APInt::getAllOnesValue(32) << (32 - ShAmt)))
16855         return TLO.CombineTo(
16856             Op, TLO.DAG.getNode(
16857                     ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
16858                     TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
16859     }
16860     break;
16861   }
16862   }
16863 
16864   return TargetLowering::SimplifyDemandedBitsForTargetNode(
16865       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
16866 }
16867 
16868 //===----------------------------------------------------------------------===//
16869 //                           ARM Inline Assembly Support
16870 //===----------------------------------------------------------------------===//
16871 
16872 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
16873   // Looking for "rev" which is V6+.
16874   if (!Subtarget->hasV6Ops())
16875     return false;
16876 
16877   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
16878   std::string AsmStr = IA->getAsmString();
16879   SmallVector<StringRef, 4> AsmPieces;
16880   SplitString(AsmStr, AsmPieces, ";\n");
16881 
16882   switch (AsmPieces.size()) {
16883   default: return false;
16884   case 1:
16885     AsmStr = std::string(AsmPieces[0]);
16886     AsmPieces.clear();
16887     SplitString(AsmStr, AsmPieces, " \t,");
16888 
16889     // rev $0, $1
16890     if (AsmPieces.size() == 3 &&
16891         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
16892         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
16893       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16894       if (Ty && Ty->getBitWidth() == 32)
16895         return IntrinsicLowering::LowerToByteSwap(CI);
16896     }
16897     break;
16898   }
16899 
16900   return false;
16901 }
16902 
16903 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
16904   // At this point, we have to lower this constraint to something else, so we
16905   // lower it to an "r" or "w". However, by doing this we will force the result
16906   // to be in register, while the X constraint is much more permissive.
16907   //
16908   // Although we are correct (we are free to emit anything, without
16909   // constraints), we might break use cases that would expect us to be more
16910   // efficient and emit something else.
16911   if (!Subtarget->hasVFP2Base())
16912     return "r";
16913   if (ConstraintVT.isFloatingPoint())
16914     return "w";
16915   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
16916      (ConstraintVT.getSizeInBits() == 64 ||
16917       ConstraintVT.getSizeInBits() == 128))
16918     return "w";
16919 
16920   return "r";
16921 }
16922 
16923 /// getConstraintType - Given a constraint letter, return the type of
16924 /// constraint it is for this target.
16925 ARMTargetLowering::ConstraintType
16926 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
16927   unsigned S = Constraint.size();
16928   if (S == 1) {
16929     switch (Constraint[0]) {
16930     default:  break;
16931     case 'l': return C_RegisterClass;
16932     case 'w': return C_RegisterClass;
16933     case 'h': return C_RegisterClass;
16934     case 'x': return C_RegisterClass;
16935     case 't': return C_RegisterClass;
16936     case 'j': return C_Immediate; // Constant for movw.
16937     // An address with a single base register. Due to the way we
16938     // currently handle addresses it is the same as an 'r' memory constraint.
16939     case 'Q': return C_Memory;
16940     }
16941   } else if (S == 2) {
16942     switch (Constraint[0]) {
16943     default: break;
16944     case 'T': return C_RegisterClass;
16945     // All 'U+' constraints are addresses.
16946     case 'U': return C_Memory;
16947     }
16948   }
16949   return TargetLowering::getConstraintType(Constraint);
16950 }
16951 
16952 /// Examine constraint type and operand type and determine a weight value.
16953 /// This object must already have been set up with the operand type
16954 /// and the current alternative constraint selected.
16955 TargetLowering::ConstraintWeight
16956 ARMTargetLowering::getSingleConstraintMatchWeight(
16957     AsmOperandInfo &info, const char *constraint) const {
16958   ConstraintWeight weight = CW_Invalid;
16959   Value *CallOperandVal = info.CallOperandVal;
16960     // If we don't have a value, we can't do a match,
16961     // but allow it at the lowest weight.
16962   if (!CallOperandVal)
16963     return CW_Default;
16964   Type *type = CallOperandVal->getType();
16965   // Look at the constraint type.
16966   switch (*constraint) {
16967   default:
16968     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16969     break;
16970   case 'l':
16971     if (type->isIntegerTy()) {
16972       if (Subtarget->isThumb())
16973         weight = CW_SpecificReg;
16974       else
16975         weight = CW_Register;
16976     }
16977     break;
16978   case 'w':
16979     if (type->isFloatingPointTy())
16980       weight = CW_Register;
16981     break;
16982   }
16983   return weight;
16984 }
16985 
16986 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
16987 
16988 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
16989     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
16990   switch (Constraint.size()) {
16991   case 1:
16992     // GCC ARM Constraint Letters
16993     switch (Constraint[0]) {
16994     case 'l': // Low regs or general regs.
16995       if (Subtarget->isThumb())
16996         return RCPair(0U, &ARM::tGPRRegClass);
16997       return RCPair(0U, &ARM::GPRRegClass);
16998     case 'h': // High regs or no regs.
16999       if (Subtarget->isThumb())
17000         return RCPair(0U, &ARM::hGPRRegClass);
17001       break;
17002     case 'r':
17003       if (Subtarget->isThumb1Only())
17004         return RCPair(0U, &ARM::tGPRRegClass);
17005       return RCPair(0U, &ARM::GPRRegClass);
17006     case 'w':
17007       if (VT == MVT::Other)
17008         break;
17009       if (VT == MVT::f32)
17010         return RCPair(0U, &ARM::SPRRegClass);
17011       if (VT.getSizeInBits() == 64)
17012         return RCPair(0U, &ARM::DPRRegClass);
17013       if (VT.getSizeInBits() == 128)
17014         return RCPair(0U, &ARM::QPRRegClass);
17015       break;
17016     case 'x':
17017       if (VT == MVT::Other)
17018         break;
17019       if (VT == MVT::f32)
17020         return RCPair(0U, &ARM::SPR_8RegClass);
17021       if (VT.getSizeInBits() == 64)
17022         return RCPair(0U, &ARM::DPR_8RegClass);
17023       if (VT.getSizeInBits() == 128)
17024         return RCPair(0U, &ARM::QPR_8RegClass);
17025       break;
17026     case 't':
17027       if (VT == MVT::Other)
17028         break;
17029       if (VT == MVT::f32 || VT == MVT::i32)
17030         return RCPair(0U, &ARM::SPRRegClass);
17031       if (VT.getSizeInBits() == 64)
17032         return RCPair(0U, &ARM::DPR_VFP2RegClass);
17033       if (VT.getSizeInBits() == 128)
17034         return RCPair(0U, &ARM::QPR_VFP2RegClass);
17035       break;
17036     }
17037     break;
17038 
17039   case 2:
17040     if (Constraint[0] == 'T') {
17041       switch (Constraint[1]) {
17042       default:
17043         break;
17044       case 'e':
17045         return RCPair(0U, &ARM::tGPREvenRegClass);
17046       case 'o':
17047         return RCPair(0U, &ARM::tGPROddRegClass);
17048       }
17049     }
17050     break;
17051 
17052   default:
17053     break;
17054   }
17055 
17056   if (StringRef("{cc}").equals_lower(Constraint))
17057     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
17058 
17059   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
17060 }
17061 
17062 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17063 /// vector.  If it is invalid, don't add anything to Ops.
17064 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17065                                                      std::string &Constraint,
17066                                                      std::vector<SDValue>&Ops,
17067                                                      SelectionDAG &DAG) const {
17068   SDValue Result;
17069 
17070   // Currently only support length 1 constraints.
17071   if (Constraint.length() != 1) return;
17072 
17073   char ConstraintLetter = Constraint[0];
17074   switch (ConstraintLetter) {
17075   default: break;
17076   case 'j':
17077   case 'I': case 'J': case 'K': case 'L':
17078   case 'M': case 'N': case 'O':
17079     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
17080     if (!C)
17081       return;
17082 
17083     int64_t CVal64 = C->getSExtValue();
17084     int CVal = (int) CVal64;
17085     // None of these constraints allow values larger than 32 bits.  Check
17086     // that the value fits in an int.
17087     if (CVal != CVal64)
17088       return;
17089 
17090     switch (ConstraintLetter) {
17091       case 'j':
17092         // Constant suitable for movw, must be between 0 and
17093         // 65535.
17094         if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
17095           if (CVal >= 0 && CVal <= 65535)
17096             break;
17097         return;
17098       case 'I':
17099         if (Subtarget->isThumb1Only()) {
17100           // This must be a constant between 0 and 255, for ADD
17101           // immediates.
17102           if (CVal >= 0 && CVal <= 255)
17103             break;
17104         } else if (Subtarget->isThumb2()) {
17105           // A constant that can be used as an immediate value in a
17106           // data-processing instruction.
17107           if (ARM_AM::getT2SOImmVal(CVal) != -1)
17108             break;
17109         } else {
17110           // A constant that can be used as an immediate value in a
17111           // data-processing instruction.
17112           if (ARM_AM::getSOImmVal(CVal) != -1)
17113             break;
17114         }
17115         return;
17116 
17117       case 'J':
17118         if (Subtarget->isThumb1Only()) {
17119           // This must be a constant between -255 and -1, for negated ADD
17120           // immediates. This can be used in GCC with an "n" modifier that
17121           // prints the negated value, for use with SUB instructions. It is
17122           // not useful otherwise but is implemented for compatibility.
17123           if (CVal >= -255 && CVal <= -1)
17124             break;
17125         } else {
17126           // This must be a constant between -4095 and 4095. It is not clear
17127           // what this constraint is intended for. Implemented for
17128           // compatibility with GCC.
17129           if (CVal >= -4095 && CVal <= 4095)
17130             break;
17131         }
17132         return;
17133 
17134       case 'K':
17135         if (Subtarget->isThumb1Only()) {
17136           // A 32-bit value where only one byte has a nonzero value. Exclude
17137           // zero to match GCC. This constraint is used by GCC internally for
17138           // constants that can be loaded with a move/shift combination.
17139           // It is not useful otherwise but is implemented for compatibility.
17140           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
17141             break;
17142         } else if (Subtarget->isThumb2()) {
17143           // A constant whose bitwise inverse can be used as an immediate
17144           // value in a data-processing instruction. This can be used in GCC
17145           // with a "B" modifier that prints the inverted value, for use with
17146           // BIC and MVN instructions. It is not useful otherwise but is
17147           // implemented for compatibility.
17148           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
17149             break;
17150         } else {
17151           // A constant whose bitwise inverse can be used as an immediate
17152           // value in a data-processing instruction. This can be used in GCC
17153           // with a "B" modifier that prints the inverted value, for use with
17154           // BIC and MVN instructions. It is not useful otherwise but is
17155           // implemented for compatibility.
17156           if (ARM_AM::getSOImmVal(~CVal) != -1)
17157             break;
17158         }
17159         return;
17160 
17161       case 'L':
17162         if (Subtarget->isThumb1Only()) {
17163           // This must be a constant between -7 and 7,
17164           // for 3-operand ADD/SUB immediate instructions.
17165           if (CVal >= -7 && CVal < 7)
17166             break;
17167         } else if (Subtarget->isThumb2()) {
17168           // A constant whose negation can be used as an immediate value in a
17169           // data-processing instruction. This can be used in GCC with an "n"
17170           // modifier that prints the negated value, for use with SUB
17171           // instructions. It is not useful otherwise but is implemented for
17172           // compatibility.
17173           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
17174             break;
17175         } else {
17176           // A constant whose negation can be used as an immediate value in a
17177           // data-processing instruction. This can be used in GCC with an "n"
17178           // modifier that prints the negated value, for use with SUB
17179           // instructions. It is not useful otherwise but is implemented for
17180           // compatibility.
17181           if (ARM_AM::getSOImmVal(-CVal) != -1)
17182             break;
17183         }
17184         return;
17185 
17186       case 'M':
17187         if (Subtarget->isThumb1Only()) {
17188           // This must be a multiple of 4 between 0 and 1020, for
17189           // ADD sp + immediate.
17190           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
17191             break;
17192         } else {
17193           // A power of two or a constant between 0 and 32.  This is used in
17194           // GCC for the shift amount on shifted register operands, but it is
17195           // useful in general for any shift amounts.
17196           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
17197             break;
17198         }
17199         return;
17200 
17201       case 'N':
17202         if (Subtarget->isThumb1Only()) {
17203           // This must be a constant between 0 and 31, for shift amounts.
17204           if (CVal >= 0 && CVal <= 31)
17205             break;
17206         }
17207         return;
17208 
17209       case 'O':
17210         if (Subtarget->isThumb1Only()) {
17211           // This must be a multiple of 4 between -508 and 508, for
17212           // ADD/SUB sp = sp + immediate.
17213           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
17214             break;
17215         }
17216         return;
17217     }
17218     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
17219     break;
17220   }
17221 
17222   if (Result.getNode()) {
17223     Ops.push_back(Result);
17224     return;
17225   }
17226   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17227 }
17228 
17229 static RTLIB::Libcall getDivRemLibcall(
17230     const SDNode *N, MVT::SimpleValueType SVT) {
17231   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
17232           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
17233          "Unhandled Opcode in getDivRemLibcall");
17234   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
17235                   N->getOpcode() == ISD::SREM;
17236   RTLIB::Libcall LC;
17237   switch (SVT) {
17238   default: llvm_unreachable("Unexpected request for libcall!");
17239   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
17240   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
17241   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
17242   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
17243   }
17244   return LC;
17245 }
17246 
17247 static TargetLowering::ArgListTy getDivRemArgList(
17248     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
17249   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
17250           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
17251          "Unhandled Opcode in getDivRemArgList");
17252   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
17253                   N->getOpcode() == ISD::SREM;
17254   TargetLowering::ArgListTy Args;
17255   TargetLowering::ArgListEntry Entry;
17256   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
17257     EVT ArgVT = N->getOperand(i).getValueType();
17258     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
17259     Entry.Node = N->getOperand(i);
17260     Entry.Ty = ArgTy;
17261     Entry.IsSExt = isSigned;
17262     Entry.IsZExt = !isSigned;
17263     Args.push_back(Entry);
17264   }
17265   if (Subtarget->isTargetWindows() && Args.size() >= 2)
17266     std::swap(Args[0], Args[1]);
17267   return Args;
17268 }
17269 
17270 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
17271   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
17272           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
17273           Subtarget->isTargetWindows()) &&
17274          "Register-based DivRem lowering only");
17275   unsigned Opcode = Op->getOpcode();
17276   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
17277          "Invalid opcode for Div/Rem lowering");
17278   bool isSigned = (Opcode == ISD::SDIVREM);
17279   EVT VT = Op->getValueType(0);
17280   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
17281   SDLoc dl(Op);
17282 
17283   // If the target has hardware divide, use divide + multiply + subtract:
17284   //     div = a / b
17285   //     rem = a - b * div
17286   //     return {div, rem}
17287   // This should be lowered into UDIV/SDIV + MLS later on.
17288   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
17289                                         : Subtarget->hasDivideInARMMode();
17290   if (hasDivide && Op->getValueType(0).isSimple() &&
17291       Op->getSimpleValueType(0) == MVT::i32) {
17292     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
17293     const SDValue Dividend = Op->getOperand(0);
17294     const SDValue Divisor = Op->getOperand(1);
17295     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
17296     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
17297     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
17298 
17299     SDValue Values[2] = {Div, Rem};
17300     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
17301   }
17302 
17303   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
17304                                        VT.getSimpleVT().SimpleTy);
17305   SDValue InChain = DAG.getEntryNode();
17306 
17307   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
17308                                                     DAG.getContext(),
17309                                                     Subtarget);
17310 
17311   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17312                                          getPointerTy(DAG.getDataLayout()));
17313 
17314   Type *RetTy = StructType::get(Ty, Ty);
17315 
17316   if (Subtarget->isTargetWindows())
17317     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
17318 
17319   TargetLowering::CallLoweringInfo CLI(DAG);
17320   CLI.setDebugLoc(dl).setChain(InChain)
17321     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
17322     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17323 
17324   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17325   return CallInfo.first;
17326 }
17327 
17328 // Lowers REM using divmod helpers
17329 // see RTABI section 4.2/4.3
17330 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
17331   // Build return types (div and rem)
17332   std::vector<Type*> RetTyParams;
17333   Type *RetTyElement;
17334 
17335   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
17336   default: llvm_unreachable("Unexpected request for libcall!");
17337   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
17338   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
17339   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
17340   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
17341   }
17342 
17343   RetTyParams.push_back(RetTyElement);
17344   RetTyParams.push_back(RetTyElement);
17345   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
17346   Type *RetTy = StructType::get(*DAG.getContext(), ret);
17347 
17348   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
17349                                                              SimpleTy);
17350   SDValue InChain = DAG.getEntryNode();
17351   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
17352                                                     Subtarget);
17353   bool isSigned = N->getOpcode() == ISD::SREM;
17354   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17355                                          getPointerTy(DAG.getDataLayout()));
17356 
17357   if (Subtarget->isTargetWindows())
17358     InChain = WinDBZCheckDenominator(DAG, N, InChain);
17359 
17360   // Lower call
17361   CallLoweringInfo CLI(DAG);
17362   CLI.setChain(InChain)
17363      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
17364      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
17365   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
17366 
17367   // Return second (rem) result operand (first contains div)
17368   SDNode *ResNode = CallResult.first.getNode();
17369   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
17370   return ResNode->getOperand(1);
17371 }
17372 
17373 SDValue
17374 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
17375   assert(Subtarget->isTargetWindows() && "unsupported target platform");
17376   SDLoc DL(Op);
17377 
17378   // Get the inputs.
17379   SDValue Chain = Op.getOperand(0);
17380   SDValue Size  = Op.getOperand(1);
17381 
17382   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
17383           "no-stack-arg-probe")) {
17384     unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
17385     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
17386     Chain = SP.getValue(1);
17387     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
17388     if (Align)
17389       SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
17390                        DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
17391     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
17392     SDValue Ops[2] = { SP, Chain };
17393     return DAG.getMergeValues(Ops, DL);
17394   }
17395 
17396   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
17397                               DAG.getConstant(2, DL, MVT::i32));
17398 
17399   SDValue Flag;
17400   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
17401   Flag = Chain.getValue(1);
17402 
17403   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
17404   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
17405 
17406   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
17407   Chain = NewSP.getValue(1);
17408 
17409   SDValue Ops[2] = { NewSP, Chain };
17410   return DAG.getMergeValues(Ops, DL);
17411 }
17412 
17413 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
17414   bool IsStrict = Op->isStrictFPOpcode();
17415   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
17416   const unsigned DstSz = Op.getValueType().getSizeInBits();
17417   const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
17418   assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
17419          "Unexpected type for custom-lowering FP_EXTEND");
17420 
17421   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
17422          "With both FP DP and 16, any FP conversion is legal!");
17423 
17424   assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
17425          "With FP16, 16 to 32 conversion is legal!");
17426 
17427   // Converting from 32 -> 64 is valid if we have FP64.
17428   if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
17429     // FIXME: Remove this when we have strict fp instruction selection patterns
17430     if (IsStrict) {
17431       SDLoc Loc(Op);
17432       SDValue Result = DAG.getNode(ISD::FP_EXTEND,
17433                                    Loc, Op.getValueType(), SrcVal);
17434       return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
17435     }
17436     return Op;
17437   }
17438 
17439   // Either we are converting from 16 -> 64, without FP16 and/or
17440   // FP.double-precision or without Armv8-fp. So we must do it in two
17441   // steps.
17442   // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
17443   // without FP16. So we must do a function call.
17444   SDLoc Loc(Op);
17445   RTLIB::Libcall LC;
17446   MakeLibCallOptions CallOptions;
17447   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
17448   for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
17449     bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
17450     MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
17451     MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
17452     if (Supported) {
17453       if (IsStrict) {
17454         SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
17455                              {DstVT, MVT::Other}, {Chain, SrcVal});
17456         Chain = SrcVal.getValue(1);
17457       } else {
17458         SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
17459       }
17460     } else {
17461       LC = RTLIB::getFPEXT(SrcVT, DstVT);
17462       assert(LC != RTLIB::UNKNOWN_LIBCALL &&
17463              "Unexpected type for custom-lowering FP_EXTEND");
17464       std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
17465                                             Loc, Chain);
17466     }
17467   }
17468 
17469   return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
17470 }
17471 
17472 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
17473   bool IsStrict = Op->isStrictFPOpcode();
17474 
17475   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
17476   EVT SrcVT = SrcVal.getValueType();
17477   EVT DstVT = Op.getValueType();
17478   const unsigned DstSz = Op.getValueType().getSizeInBits();
17479   const unsigned SrcSz = SrcVT.getSizeInBits();
17480   (void)DstSz;
17481   assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
17482          "Unexpected type for custom-lowering FP_ROUND");
17483 
17484   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
17485          "With both FP DP and 16, any FP conversion is legal!");
17486 
17487   SDLoc Loc(Op);
17488 
17489   // Instruction from 32 -> 16 if hasFP16 is valid
17490   if (SrcSz == 32 && Subtarget->hasFP16())
17491     return Op;
17492 
17493   // Lib call from 32 -> 16 / 64 -> [32, 16]
17494   RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
17495   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
17496          "Unexpected type for custom-lowering FP_ROUND");
17497   MakeLibCallOptions CallOptions;
17498   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
17499   SDValue Result;
17500   std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
17501                                         Loc, Chain);
17502   return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
17503 }
17504 
17505 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
17506                                  SelectionDAG &DAG) const {
17507   assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
17508   MVT HalfT = MVT::i32;
17509   SDLoc dl(N);
17510   SDValue Hi, Lo, Tmp;
17511 
17512   if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
17513       !isOperationLegalOrCustom(ISD::UADDO, HalfT))
17514     return ;
17515 
17516   unsigned OpTypeBits = HalfT.getScalarSizeInBits();
17517   SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
17518 
17519   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
17520                    DAG.getConstant(0, dl, HalfT));
17521   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
17522                    DAG.getConstant(1, dl, HalfT));
17523 
17524   Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
17525                     DAG.getConstant(OpTypeBits - 1, dl,
17526                     getShiftAmountTy(HalfT, DAG.getDataLayout())));
17527   Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
17528   Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
17529                    SDValue(Lo.getNode(), 1));
17530   Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
17531   Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
17532 
17533   Results.push_back(Lo);
17534   Results.push_back(Hi);
17535 }
17536 
17537 bool
17538 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
17539   // The ARM target isn't yet aware of offsets.
17540   return false;
17541 }
17542 
17543 bool ARM::isBitFieldInvertedMask(unsigned v) {
17544   if (v == 0xffffffff)
17545     return false;
17546 
17547   // there can be 1's on either or both "outsides", all the "inside"
17548   // bits must be 0's
17549   return isShiftedMask_32(~v);
17550 }
17551 
17552 /// isFPImmLegal - Returns true if the target can instruction select the
17553 /// specified FP immediate natively. If false, the legalizer will
17554 /// materialize the FP immediate as a load from a constant pool.
17555 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
17556                                      bool ForCodeSize) const {
17557   if (!Subtarget->hasVFP3Base())
17558     return false;
17559   if (VT == MVT::f16 && Subtarget->hasFullFP16())
17560     return ARM_AM::getFP16Imm(Imm) != -1;
17561   if (VT == MVT::f32)
17562     return ARM_AM::getFP32Imm(Imm) != -1;
17563   if (VT == MVT::f64 && Subtarget->hasFP64())
17564     return ARM_AM::getFP64Imm(Imm) != -1;
17565   return false;
17566 }
17567 
17568 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
17569 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
17570 /// specified in the intrinsic calls.
17571 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
17572                                            const CallInst &I,
17573                                            MachineFunction &MF,
17574                                            unsigned Intrinsic) const {
17575   switch (Intrinsic) {
17576   case Intrinsic::arm_neon_vld1:
17577   case Intrinsic::arm_neon_vld2:
17578   case Intrinsic::arm_neon_vld3:
17579   case Intrinsic::arm_neon_vld4:
17580   case Intrinsic::arm_neon_vld2lane:
17581   case Intrinsic::arm_neon_vld3lane:
17582   case Intrinsic::arm_neon_vld4lane:
17583   case Intrinsic::arm_neon_vld2dup:
17584   case Intrinsic::arm_neon_vld3dup:
17585   case Intrinsic::arm_neon_vld4dup: {
17586     Info.opc = ISD::INTRINSIC_W_CHAIN;
17587     // Conservatively set memVT to the entire set of vectors loaded.
17588     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17589     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
17590     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
17591     Info.ptrVal = I.getArgOperand(0);
17592     Info.offset = 0;
17593     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
17594     Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
17595     // volatile loads with NEON intrinsics not supported
17596     Info.flags = MachineMemOperand::MOLoad;
17597     return true;
17598   }
17599   case Intrinsic::arm_neon_vld1x2:
17600   case Intrinsic::arm_neon_vld1x3:
17601   case Intrinsic::arm_neon_vld1x4: {
17602     Info.opc = ISD::INTRINSIC_W_CHAIN;
17603     // Conservatively set memVT to the entire set of vectors loaded.
17604     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17605     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
17606     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
17607     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
17608     Info.offset = 0;
17609     Info.align.reset();
17610     // volatile loads with NEON intrinsics not supported
17611     Info.flags = MachineMemOperand::MOLoad;
17612     return true;
17613   }
17614   case Intrinsic::arm_neon_vst1:
17615   case Intrinsic::arm_neon_vst2:
17616   case Intrinsic::arm_neon_vst3:
17617   case Intrinsic::arm_neon_vst4:
17618   case Intrinsic::arm_neon_vst2lane:
17619   case Intrinsic::arm_neon_vst3lane:
17620   case Intrinsic::arm_neon_vst4lane: {
17621     Info.opc = ISD::INTRINSIC_VOID;
17622     // Conservatively set memVT to the entire set of vectors stored.
17623     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17624     unsigned NumElts = 0;
17625     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
17626       Type *ArgTy = I.getArgOperand(ArgI)->getType();
17627       if (!ArgTy->isVectorTy())
17628         break;
17629       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
17630     }
17631     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
17632     Info.ptrVal = I.getArgOperand(0);
17633     Info.offset = 0;
17634     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
17635     Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
17636     // volatile stores with NEON intrinsics not supported
17637     Info.flags = MachineMemOperand::MOStore;
17638     return true;
17639   }
17640   case Intrinsic::arm_neon_vst1x2:
17641   case Intrinsic::arm_neon_vst1x3:
17642   case Intrinsic::arm_neon_vst1x4: {
17643     Info.opc = ISD::INTRINSIC_VOID;
17644     // Conservatively set memVT to the entire set of vectors stored.
17645     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17646     unsigned NumElts = 0;
17647     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
17648       Type *ArgTy = I.getArgOperand(ArgI)->getType();
17649       if (!ArgTy->isVectorTy())
17650         break;
17651       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
17652     }
17653     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
17654     Info.ptrVal = I.getArgOperand(0);
17655     Info.offset = 0;
17656     Info.align.reset();
17657     // volatile stores with NEON intrinsics not supported
17658     Info.flags = MachineMemOperand::MOStore;
17659     return true;
17660   }
17661   case Intrinsic::arm_mve_vld2q:
17662   case Intrinsic::arm_mve_vld4q: {
17663     Info.opc = ISD::INTRINSIC_W_CHAIN;
17664     // Conservatively set memVT to the entire set of vectors loaded.
17665     Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
17666     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
17667     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
17668     Info.ptrVal = I.getArgOperand(0);
17669     Info.offset = 0;
17670     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
17671     // volatile loads with MVE intrinsics not supported
17672     Info.flags = MachineMemOperand::MOLoad;
17673     return true;
17674   }
17675   case Intrinsic::arm_mve_vst2q:
17676   case Intrinsic::arm_mve_vst4q: {
17677     Info.opc = ISD::INTRINSIC_VOID;
17678     // Conservatively set memVT to the entire set of vectors stored.
17679     Type *VecTy = I.getArgOperand(1)->getType();
17680     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
17681     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
17682     Info.ptrVal = I.getArgOperand(0);
17683     Info.offset = 0;
17684     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
17685     // volatile stores with MVE intrinsics not supported
17686     Info.flags = MachineMemOperand::MOStore;
17687     return true;
17688   }
17689   case Intrinsic::arm_ldaex:
17690   case Intrinsic::arm_ldrex: {
17691     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17692     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
17693     Info.opc = ISD::INTRINSIC_W_CHAIN;
17694     Info.memVT = MVT::getVT(PtrTy->getElementType());
17695     Info.ptrVal = I.getArgOperand(0);
17696     Info.offset = 0;
17697     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
17698     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
17699     return true;
17700   }
17701   case Intrinsic::arm_stlex:
17702   case Intrinsic::arm_strex: {
17703     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17704     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
17705     Info.opc = ISD::INTRINSIC_W_CHAIN;
17706     Info.memVT = MVT::getVT(PtrTy->getElementType());
17707     Info.ptrVal = I.getArgOperand(1);
17708     Info.offset = 0;
17709     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
17710     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
17711     return true;
17712   }
17713   case Intrinsic::arm_stlexd:
17714   case Intrinsic::arm_strexd:
17715     Info.opc = ISD::INTRINSIC_W_CHAIN;
17716     Info.memVT = MVT::i64;
17717     Info.ptrVal = I.getArgOperand(2);
17718     Info.offset = 0;
17719     Info.align = Align(8);
17720     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
17721     return true;
17722 
17723   case Intrinsic::arm_ldaexd:
17724   case Intrinsic::arm_ldrexd:
17725     Info.opc = ISD::INTRINSIC_W_CHAIN;
17726     Info.memVT = MVT::i64;
17727     Info.ptrVal = I.getArgOperand(0);
17728     Info.offset = 0;
17729     Info.align = Align(8);
17730     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
17731     return true;
17732 
17733   default:
17734     break;
17735   }
17736 
17737   return false;
17738 }
17739 
17740 /// Returns true if it is beneficial to convert a load of a constant
17741 /// to just the constant itself.
17742 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
17743                                                           Type *Ty) const {
17744   assert(Ty->isIntegerTy());
17745 
17746   unsigned Bits = Ty->getPrimitiveSizeInBits();
17747   if (Bits == 0 || Bits > 32)
17748     return false;
17749   return true;
17750 }
17751 
17752 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
17753                                                 unsigned Index) const {
17754   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
17755     return false;
17756 
17757   return (Index == 0 || Index == ResVT.getVectorNumElements());
17758 }
17759 
17760 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
17761                                         ARM_MB::MemBOpt Domain) const {
17762   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17763 
17764   // First, if the target has no DMB, see what fallback we can use.
17765   if (!Subtarget->hasDataBarrier()) {
17766     // Some ARMv6 cpus can support data barriers with an mcr instruction.
17767     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
17768     // here.
17769     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
17770       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
17771       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
17772                         Builder.getInt32(0), Builder.getInt32(7),
17773                         Builder.getInt32(10), Builder.getInt32(5)};
17774       return Builder.CreateCall(MCR, args);
17775     } else {
17776       // Instead of using barriers, atomic accesses on these subtargets use
17777       // libcalls.
17778       llvm_unreachable("makeDMB on a target so old that it has no barriers");
17779     }
17780   } else {
17781     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
17782     // Only a full system barrier exists in the M-class architectures.
17783     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
17784     Constant *CDomain = Builder.getInt32(Domain);
17785     return Builder.CreateCall(DMB, CDomain);
17786   }
17787 }
17788 
17789 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
17790 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
17791                                                  Instruction *Inst,
17792                                                  AtomicOrdering Ord) const {
17793   switch (Ord) {
17794   case AtomicOrdering::NotAtomic:
17795   case AtomicOrdering::Unordered:
17796     llvm_unreachable("Invalid fence: unordered/non-atomic");
17797   case AtomicOrdering::Monotonic:
17798   case AtomicOrdering::Acquire:
17799     return nullptr; // Nothing to do
17800   case AtomicOrdering::SequentiallyConsistent:
17801     if (!Inst->hasAtomicStore())
17802       return nullptr; // Nothing to do
17803     LLVM_FALLTHROUGH;
17804   case AtomicOrdering::Release:
17805   case AtomicOrdering::AcquireRelease:
17806     if (Subtarget->preferISHSTBarriers())
17807       return makeDMB(Builder, ARM_MB::ISHST);
17808     // FIXME: add a comment with a link to documentation justifying this.
17809     else
17810       return makeDMB(Builder, ARM_MB::ISH);
17811   }
17812   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
17813 }
17814 
17815 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
17816                                                   Instruction *Inst,
17817                                                   AtomicOrdering Ord) const {
17818   switch (Ord) {
17819   case AtomicOrdering::NotAtomic:
17820   case AtomicOrdering::Unordered:
17821     llvm_unreachable("Invalid fence: unordered/not-atomic");
17822   case AtomicOrdering::Monotonic:
17823   case AtomicOrdering::Release:
17824     return nullptr; // Nothing to do
17825   case AtomicOrdering::Acquire:
17826   case AtomicOrdering::AcquireRelease:
17827   case AtomicOrdering::SequentiallyConsistent:
17828     return makeDMB(Builder, ARM_MB::ISH);
17829   }
17830   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
17831 }
17832 
17833 // Loads and stores less than 64-bits are already atomic; ones above that
17834 // are doomed anyway, so defer to the default libcall and blame the OS when
17835 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
17836 // anything for those.
17837 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17838   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
17839   return (Size == 64) && !Subtarget->isMClass();
17840 }
17841 
17842 // Loads and stores less than 64-bits are already atomic; ones above that
17843 // are doomed anyway, so defer to the default libcall and blame the OS when
17844 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
17845 // anything for those.
17846 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
17847 // guarantee, see DDI0406C ARM architecture reference manual,
17848 // sections A8.8.72-74 LDRD)
17849 TargetLowering::AtomicExpansionKind
17850 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17851   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
17852   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
17853                                                   : AtomicExpansionKind::None;
17854 }
17855 
17856 // For the real atomic operations, we have ldrex/strex up to 32 bits,
17857 // and up to 64 bits on the non-M profiles
17858 TargetLowering::AtomicExpansionKind
17859 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17860   if (AI->isFloatingPointOperation())
17861     return AtomicExpansionKind::CmpXChg;
17862 
17863   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
17864   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
17865   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
17866              ? AtomicExpansionKind::LLSC
17867              : AtomicExpansionKind::None;
17868 }
17869 
17870 TargetLowering::AtomicExpansionKind
17871 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
17872   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
17873   // implement cmpxchg without spilling. If the address being exchanged is also
17874   // on the stack and close enough to the spill slot, this can lead to a
17875   // situation where the monitor always gets cleared and the atomic operation
17876   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
17877   bool HasAtomicCmpXchg =
17878       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
17879   if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
17880     return AtomicExpansionKind::LLSC;
17881   return AtomicExpansionKind::None;
17882 }
17883 
17884 bool ARMTargetLowering::shouldInsertFencesForAtomic(
17885     const Instruction *I) const {
17886   return InsertFencesForAtomic;
17887 }
17888 
17889 // This has so far only been implemented for MachO.
17890 bool ARMTargetLowering::useLoadStackGuardNode() const {
17891   return Subtarget->isTargetMachO();
17892 }
17893 
17894 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
17895   if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
17896     return TargetLowering::insertSSPDeclarations(M);
17897 
17898   // MSVC CRT has a global variable holding security cookie.
17899   M.getOrInsertGlobal("__security_cookie",
17900                       Type::getInt8PtrTy(M.getContext()));
17901 
17902   // MSVC CRT has a function to validate security cookie.
17903   FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
17904       "__security_check_cookie", Type::getVoidTy(M.getContext()),
17905       Type::getInt8PtrTy(M.getContext()));
17906   if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
17907     F->addAttribute(1, Attribute::AttrKind::InReg);
17908 }
17909 
17910 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
17911   // MSVC CRT has a global variable holding security cookie.
17912   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
17913     return M.getGlobalVariable("__security_cookie");
17914   return TargetLowering::getSDagStackGuard(M);
17915 }
17916 
17917 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
17918   // MSVC CRT has a function to validate security cookie.
17919   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
17920     return M.getFunction("__security_check_cookie");
17921   return TargetLowering::getSSPStackGuardCheck(M);
17922 }
17923 
17924 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
17925                                                   unsigned &Cost) const {
17926   // If we do not have NEON, vector types are not natively supported.
17927   if (!Subtarget->hasNEON())
17928     return false;
17929 
17930   // Floating point values and vector values map to the same register file.
17931   // Therefore, although we could do a store extract of a vector type, this is
17932   // better to leave at float as we have more freedom in the addressing mode for
17933   // those.
17934   if (VectorTy->isFPOrFPVectorTy())
17935     return false;
17936 
17937   // If the index is unknown at compile time, this is very expensive to lower
17938   // and it is not possible to combine the store with the extract.
17939   if (!isa<ConstantInt>(Idx))
17940     return false;
17941 
17942   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
17943   unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize();
17944   // We can do a store + vector extract on any vector that fits perfectly in a D
17945   // or Q register.
17946   if (BitWidth == 64 || BitWidth == 128) {
17947     Cost = 0;
17948     return true;
17949   }
17950   return false;
17951 }
17952 
17953 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
17954   return Subtarget->hasV6T2Ops();
17955 }
17956 
17957 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
17958   return Subtarget->hasV6T2Ops();
17959 }
17960 
17961 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
17962   return !Subtarget->hasMinSize() || Subtarget->isTargetWindows();
17963 }
17964 
17965 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
17966                                          AtomicOrdering Ord) const {
17967   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17968   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
17969   bool IsAcquire = isAcquireOrStronger(Ord);
17970 
17971   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
17972   // intrinsic must return {i32, i32} and we have to recombine them into a
17973   // single i64 here.
17974   if (ValTy->getPrimitiveSizeInBits() == 64) {
17975     Intrinsic::ID Int =
17976         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
17977     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
17978 
17979     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
17980     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
17981 
17982     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17983     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17984     if (!Subtarget->isLittle())
17985       std::swap (Lo, Hi);
17986     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
17987     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
17988     return Builder.CreateOr(
17989         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
17990   }
17991 
17992   Type *Tys[] = { Addr->getType() };
17993   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
17994   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
17995 
17996   return Builder.CreateTruncOrBitCast(
17997       Builder.CreateCall(Ldrex, Addr),
17998       cast<PointerType>(Addr->getType())->getElementType());
17999 }
18000 
18001 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
18002     IRBuilder<> &Builder) const {
18003   if (!Subtarget->hasV7Ops())
18004     return;
18005   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18006   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
18007 }
18008 
18009 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
18010                                                Value *Addr,
18011                                                AtomicOrdering Ord) const {
18012   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18013   bool IsRelease = isReleaseOrStronger(Ord);
18014 
18015   // Since the intrinsics must have legal type, the i64 intrinsics take two
18016   // parameters: "i32, i32". We must marshal Val into the appropriate form
18017   // before the call.
18018   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
18019     Intrinsic::ID Int =
18020         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
18021     Function *Strex = Intrinsic::getDeclaration(M, Int);
18022     Type *Int32Ty = Type::getInt32Ty(M->getContext());
18023 
18024     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
18025     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
18026     if (!Subtarget->isLittle())
18027       std::swap(Lo, Hi);
18028     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
18029     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
18030   }
18031 
18032   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
18033   Type *Tys[] = { Addr->getType() };
18034   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
18035 
18036   return Builder.CreateCall(
18037       Strex, {Builder.CreateZExtOrBitCast(
18038                   Val, Strex->getFunctionType()->getParamType(0)),
18039               Addr});
18040 }
18041 
18042 
18043 bool ARMTargetLowering::alignLoopsWithOptSize() const {
18044   return Subtarget->isMClass();
18045 }
18046 
18047 /// A helper function for determining the number of interleaved accesses we
18048 /// will generate when lowering accesses of the given type.
18049 unsigned
18050 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
18051                                              const DataLayout &DL) const {
18052   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
18053 }
18054 
18055 bool ARMTargetLowering::isLegalInterleavedAccessType(
18056     unsigned Factor, FixedVectorType *VecTy, const DataLayout &DL) const {
18057 
18058   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
18059   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
18060 
18061   if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
18062     return false;
18063 
18064   // Ensure the vector doesn't have f16 elements. Even though we could do an
18065   // i16 vldN, we can't hold the f16 vectors and will end up converting via
18066   // f32.
18067   if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
18068     return false;
18069   if (Subtarget->hasMVEIntegerOps() && Factor == 3)
18070     return false;
18071 
18072   // Ensure the number of vector elements is greater than 1.
18073   if (VecTy->getNumElements() < 2)
18074     return false;
18075 
18076   // Ensure the element type is legal.
18077   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
18078     return false;
18079 
18080   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
18081   // 128 will be split into multiple interleaved accesses.
18082   if (Subtarget->hasNEON() && VecSize == 64)
18083     return true;
18084   return VecSize % 128 == 0;
18085 }
18086 
18087 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
18088   if (Subtarget->hasNEON())
18089     return 4;
18090   if (Subtarget->hasMVEIntegerOps())
18091     return MVEMaxSupportedInterleaveFactor;
18092   return TargetLoweringBase::getMaxSupportedInterleaveFactor();
18093 }
18094 
18095 /// Lower an interleaved load into a vldN intrinsic.
18096 ///
18097 /// E.g. Lower an interleaved load (Factor = 2):
18098 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
18099 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
18100 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
18101 ///
18102 ///      Into:
18103 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
18104 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
18105 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
18106 bool ARMTargetLowering::lowerInterleavedLoad(
18107     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
18108     ArrayRef<unsigned> Indices, unsigned Factor) const {
18109   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
18110          "Invalid interleave factor");
18111   assert(!Shuffles.empty() && "Empty shufflevector input");
18112   assert(Shuffles.size() == Indices.size() &&
18113          "Unmatched number of shufflevectors and indices");
18114 
18115   auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType());
18116   Type *EltTy = VecTy->getElementType();
18117 
18118   const DataLayout &DL = LI->getModule()->getDataLayout();
18119 
18120   // Skip if we do not have NEON and skip illegal vector types. We can
18121   // "legalize" wide vector types into multiple interleaved accesses as long as
18122   // the vector types are divisible by 128.
18123   if (!isLegalInterleavedAccessType(Factor, VecTy, DL))
18124     return false;
18125 
18126   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
18127 
18128   // A pointer vector can not be the return type of the ldN intrinsics. Need to
18129   // load integer vectors first and then convert to pointer vectors.
18130   if (EltTy->isPointerTy())
18131     VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy);
18132 
18133   IRBuilder<> Builder(LI);
18134 
18135   // The base address of the load.
18136   Value *BaseAddr = LI->getPointerOperand();
18137 
18138   if (NumLoads > 1) {
18139     // If we're going to generate more than one load, reset the sub-vector type
18140     // to something legal.
18141     VecTy = FixedVectorType::get(VecTy->getElementType(),
18142                                  VecTy->getNumElements() / NumLoads);
18143 
18144     // We will compute the pointer operand of each load from the original base
18145     // address using GEPs. Cast the base address to a pointer to the scalar
18146     // element type.
18147     BaseAddr = Builder.CreateBitCast(
18148         BaseAddr,
18149         VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
18150   }
18151 
18152   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
18153 
18154   auto createLoadIntrinsic = [&](Value *BaseAddr) {
18155     if (Subtarget->hasNEON()) {
18156       Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
18157       Type *Tys[] = {VecTy, Int8Ptr};
18158       static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
18159                                                 Intrinsic::arm_neon_vld3,
18160                                                 Intrinsic::arm_neon_vld4};
18161       Function *VldnFunc =
18162           Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
18163 
18164       SmallVector<Value *, 2> Ops;
18165       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
18166       Ops.push_back(Builder.getInt32(LI->getAlignment()));
18167 
18168       return Builder.CreateCall(VldnFunc, Ops, "vldN");
18169     } else {
18170       assert((Factor == 2 || Factor == 4) &&
18171              "expected interleave factor of 2 or 4 for MVE");
18172       Intrinsic::ID LoadInts =
18173           Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
18174       Type *VecEltTy =
18175           VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace());
18176       Type *Tys[] = {VecTy, VecEltTy};
18177       Function *VldnFunc =
18178           Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys);
18179 
18180       SmallVector<Value *, 2> Ops;
18181       Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy));
18182       return Builder.CreateCall(VldnFunc, Ops, "vldN");
18183     }
18184   };
18185 
18186   // Holds sub-vectors extracted from the load intrinsic return values. The
18187   // sub-vectors are associated with the shufflevector instructions they will
18188   // replace.
18189   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
18190 
18191   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
18192     // If we're generating more than one load, compute the base address of
18193     // subsequent loads as an offset from the previous.
18194     if (LoadCount > 0)
18195       BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
18196                                             VecTy->getNumElements() * Factor);
18197 
18198     CallInst *VldN = createLoadIntrinsic(BaseAddr);
18199 
18200     // Replace uses of each shufflevector with the corresponding vector loaded
18201     // by ldN.
18202     for (unsigned i = 0; i < Shuffles.size(); i++) {
18203       ShuffleVectorInst *SV = Shuffles[i];
18204       unsigned Index = Indices[i];
18205 
18206       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
18207 
18208       // Convert the integer vector to pointer vector if the element is pointer.
18209       if (EltTy->isPointerTy())
18210         SubVec = Builder.CreateIntToPtr(
18211             SubVec,
18212             FixedVectorType::get(SV->getType()->getElementType(), VecTy));
18213 
18214       SubVecs[SV].push_back(SubVec);
18215     }
18216   }
18217 
18218   // Replace uses of the shufflevector instructions with the sub-vectors
18219   // returned by the load intrinsic. If a shufflevector instruction is
18220   // associated with more than one sub-vector, those sub-vectors will be
18221   // concatenated into a single wide vector.
18222   for (ShuffleVectorInst *SVI : Shuffles) {
18223     auto &SubVec = SubVecs[SVI];
18224     auto *WideVec =
18225         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
18226     SVI->replaceAllUsesWith(WideVec);
18227   }
18228 
18229   return true;
18230 }
18231 
18232 /// Lower an interleaved store into a vstN intrinsic.
18233 ///
18234 /// E.g. Lower an interleaved store (Factor = 3):
18235 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
18236 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
18237 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
18238 ///
18239 ///      Into:
18240 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
18241 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
18242 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
18243 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
18244 ///
18245 /// Note that the new shufflevectors will be removed and we'll only generate one
18246 /// vst3 instruction in CodeGen.
18247 ///
18248 /// Example for a more general valid mask (Factor 3). Lower:
18249 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
18250 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
18251 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
18252 ///
18253 ///      Into:
18254 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
18255 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
18256 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
18257 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
18258 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
18259                                               ShuffleVectorInst *SVI,
18260                                               unsigned Factor) const {
18261   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
18262          "Invalid interleave factor");
18263 
18264   auto *VecTy = cast<FixedVectorType>(SVI->getType());
18265   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
18266 
18267   unsigned LaneLen = VecTy->getNumElements() / Factor;
18268   Type *EltTy = VecTy->getElementType();
18269   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
18270 
18271   const DataLayout &DL = SI->getModule()->getDataLayout();
18272 
18273   // Skip if we do not have NEON and skip illegal vector types. We can
18274   // "legalize" wide vector types into multiple interleaved accesses as long as
18275   // the vector types are divisible by 128.
18276   if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL))
18277     return false;
18278 
18279   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
18280 
18281   Value *Op0 = SVI->getOperand(0);
18282   Value *Op1 = SVI->getOperand(1);
18283   IRBuilder<> Builder(SI);
18284 
18285   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
18286   // vectors to integer vectors.
18287   if (EltTy->isPointerTy()) {
18288     Type *IntTy = DL.getIntPtrType(EltTy);
18289 
18290     // Convert to the corresponding integer vector.
18291     auto *IntVecTy =
18292         FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType()));
18293     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
18294     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
18295 
18296     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
18297   }
18298 
18299   // The base address of the store.
18300   Value *BaseAddr = SI->getPointerOperand();
18301 
18302   if (NumStores > 1) {
18303     // If we're going to generate more than one store, reset the lane length
18304     // and sub-vector type to something legal.
18305     LaneLen /= NumStores;
18306     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
18307 
18308     // We will compute the pointer operand of each store from the original base
18309     // address using GEPs. Cast the base address to a pointer to the scalar
18310     // element type.
18311     BaseAddr = Builder.CreateBitCast(
18312         BaseAddr,
18313         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
18314   }
18315 
18316   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
18317 
18318   auto Mask = SVI->getShuffleMask();
18319 
18320   auto createStoreIntrinsic = [&](Value *BaseAddr,
18321                                   SmallVectorImpl<Value *> &Shuffles) {
18322     if (Subtarget->hasNEON()) {
18323       static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
18324                                                  Intrinsic::arm_neon_vst3,
18325                                                  Intrinsic::arm_neon_vst4};
18326       Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
18327       Type *Tys[] = {Int8Ptr, SubVecTy};
18328 
18329       Function *VstNFunc = Intrinsic::getDeclaration(
18330           SI->getModule(), StoreInts[Factor - 2], Tys);
18331 
18332       SmallVector<Value *, 6> Ops;
18333       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
18334       for (auto S : Shuffles)
18335         Ops.push_back(S);
18336       Ops.push_back(Builder.getInt32(SI->getAlignment()));
18337       Builder.CreateCall(VstNFunc, Ops);
18338     } else {
18339       assert((Factor == 2 || Factor == 4) &&
18340              "expected interleave factor of 2 or 4 for MVE");
18341       Intrinsic::ID StoreInts =
18342           Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
18343       Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo(
18344           SI->getPointerAddressSpace());
18345       Type *Tys[] = {EltPtrTy, SubVecTy};
18346       Function *VstNFunc =
18347           Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys);
18348 
18349       SmallVector<Value *, 6> Ops;
18350       Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy));
18351       for (auto S : Shuffles)
18352         Ops.push_back(S);
18353       for (unsigned F = 0; F < Factor; F++) {
18354         Ops.push_back(Builder.getInt32(F));
18355         Builder.CreateCall(VstNFunc, Ops);
18356         Ops.pop_back();
18357       }
18358     }
18359   };
18360 
18361   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
18362     // If we generating more than one store, we compute the base address of
18363     // subsequent stores as an offset from the previous.
18364     if (StoreCount > 0)
18365       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
18366                                             BaseAddr, LaneLen * Factor);
18367 
18368     SmallVector<Value *, 4> Shuffles;
18369 
18370     // Split the shufflevector operands into sub vectors for the new vstN call.
18371     for (unsigned i = 0; i < Factor; i++) {
18372       unsigned IdxI = StoreCount * LaneLen * Factor + i;
18373       if (Mask[IdxI] >= 0) {
18374         Shuffles.push_back(Builder.CreateShuffleVector(
18375             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
18376       } else {
18377         unsigned StartMask = 0;
18378         for (unsigned j = 1; j < LaneLen; j++) {
18379           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
18380           if (Mask[IdxJ * Factor + IdxI] >= 0) {
18381             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
18382             break;
18383           }
18384         }
18385         // Note: If all elements in a chunk are undefs, StartMask=0!
18386         // Note: Filling undef gaps with random elements is ok, since
18387         // those elements were being written anyway (with undefs).
18388         // In the case of all undefs we're defaulting to using elems from 0
18389         // Note: StartMask cannot be negative, it's checked in
18390         // isReInterleaveMask
18391         Shuffles.push_back(Builder.CreateShuffleVector(
18392             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
18393       }
18394     }
18395 
18396     createStoreIntrinsic(BaseAddr, Shuffles);
18397   }
18398   return true;
18399 }
18400 
18401 enum HABaseType {
18402   HA_UNKNOWN = 0,
18403   HA_FLOAT,
18404   HA_DOUBLE,
18405   HA_VECT64,
18406   HA_VECT128
18407 };
18408 
18409 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
18410                                    uint64_t &Members) {
18411   if (auto *ST = dyn_cast<StructType>(Ty)) {
18412     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
18413       uint64_t SubMembers = 0;
18414       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
18415         return false;
18416       Members += SubMembers;
18417     }
18418   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
18419     uint64_t SubMembers = 0;
18420     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
18421       return false;
18422     Members += SubMembers * AT->getNumElements();
18423   } else if (Ty->isFloatTy()) {
18424     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
18425       return false;
18426     Members = 1;
18427     Base = HA_FLOAT;
18428   } else if (Ty->isDoubleTy()) {
18429     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
18430       return false;
18431     Members = 1;
18432     Base = HA_DOUBLE;
18433   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
18434     Members = 1;
18435     switch (Base) {
18436     case HA_FLOAT:
18437     case HA_DOUBLE:
18438       return false;
18439     case HA_VECT64:
18440       return VT->getPrimitiveSizeInBits().getFixedSize() == 64;
18441     case HA_VECT128:
18442       return VT->getPrimitiveSizeInBits().getFixedSize() == 128;
18443     case HA_UNKNOWN:
18444       switch (VT->getPrimitiveSizeInBits().getFixedSize()) {
18445       case 64:
18446         Base = HA_VECT64;
18447         return true;
18448       case 128:
18449         Base = HA_VECT128;
18450         return true;
18451       default:
18452         return false;
18453       }
18454     }
18455   }
18456 
18457   return (Members > 0 && Members <= 4);
18458 }
18459 
18460 /// Return the correct alignment for the current calling convention.
18461 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
18462                                                        DataLayout DL) const {
18463   const Align ABITypeAlign(DL.getABITypeAlignment(ArgTy));
18464   if (!ArgTy->isVectorTy())
18465     return ABITypeAlign;
18466 
18467   // Avoid over-aligning vector parameters. It would require realigning the
18468   // stack and waste space for no real benefit.
18469   return std::min(ABITypeAlign, DL.getStackAlignment());
18470 }
18471 
18472 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
18473 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
18474 /// passing according to AAPCS rules.
18475 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
18476     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
18477   if (getEffectiveCallingConv(CallConv, isVarArg) !=
18478       CallingConv::ARM_AAPCS_VFP)
18479     return false;
18480 
18481   HABaseType Base = HA_UNKNOWN;
18482   uint64_t Members = 0;
18483   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
18484   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
18485 
18486   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
18487   return IsHA || IsIntArray;
18488 }
18489 
18490 Register ARMTargetLowering::getExceptionPointerRegister(
18491     const Constant *PersonalityFn) const {
18492   // Platforms which do not use SjLj EH may return values in these registers
18493   // via the personality function.
18494   return Subtarget->useSjLjEH() ? Register() : ARM::R0;
18495 }
18496 
18497 Register ARMTargetLowering::getExceptionSelectorRegister(
18498     const Constant *PersonalityFn) const {
18499   // Platforms which do not use SjLj EH may return values in these registers
18500   // via the personality function.
18501   return Subtarget->useSjLjEH() ? Register() : ARM::R1;
18502 }
18503 
18504 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
18505   // Update IsSplitCSR in ARMFunctionInfo.
18506   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
18507   AFI->setIsSplitCSR(true);
18508 }
18509 
18510 void ARMTargetLowering::insertCopiesSplitCSR(
18511     MachineBasicBlock *Entry,
18512     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
18513   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
18514   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
18515   if (!IStart)
18516     return;
18517 
18518   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18519   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
18520   MachineBasicBlock::iterator MBBI = Entry->begin();
18521   for (const MCPhysReg *I = IStart; *I; ++I) {
18522     const TargetRegisterClass *RC = nullptr;
18523     if (ARM::GPRRegClass.contains(*I))
18524       RC = &ARM::GPRRegClass;
18525     else if (ARM::DPRRegClass.contains(*I))
18526       RC = &ARM::DPRRegClass;
18527     else
18528       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
18529 
18530     Register NewVR = MRI->createVirtualRegister(RC);
18531     // Create copy from CSR to a virtual register.
18532     // FIXME: this currently does not emit CFI pseudo-instructions, it works
18533     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
18534     // nounwind. If we want to generalize this later, we may need to emit
18535     // CFI pseudo-instructions.
18536     assert(Entry->getParent()->getFunction().hasFnAttribute(
18537                Attribute::NoUnwind) &&
18538            "Function should be nounwind in insertCopiesSplitCSR!");
18539     Entry->addLiveIn(*I);
18540     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
18541         .addReg(*I);
18542 
18543     // Insert the copy-back instructions right before the terminator.
18544     for (auto *Exit : Exits)
18545       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
18546               TII->get(TargetOpcode::COPY), *I)
18547           .addReg(NewVR);
18548   }
18549 }
18550 
18551 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
18552   MF.getFrameInfo().computeMaxCallFrameSize(MF);
18553   TargetLoweringBase::finalizeLowering(MF);
18554 }
18555