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 
950   if (!Subtarget->hasFP64()) {
951     // When targeting a floating-point unit with only single-precision
952     // operations, f64 is legal for the few double-precision instructions which
953     // are present However, no double-precision operations other than moves,
954     // loads and stores are provided by the hardware.
955     setOperationAction(ISD::FADD,       MVT::f64, Expand);
956     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
957     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
958     setOperationAction(ISD::FMA,        MVT::f64, Expand);
959     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
960     setOperationAction(ISD::FREM,       MVT::f64, Expand);
961     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
962     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
963     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
964     setOperationAction(ISD::FABS,       MVT::f64, Expand);
965     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
966     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
967     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
968     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
969     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
970     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
971     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
972     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
973     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
974     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
975     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
976     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
977     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
978     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
979     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
980     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
981     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
982     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
983     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
984     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
985     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
986     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
987     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
988     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
989     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
990     setOperationAction(ISD::STRICT_FP_ROUND,   MVT::f32, Custom);
991   }
992 
993   if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
994     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
995     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
996     if (Subtarget->hasFullFP16()) {
997       setOperationAction(ISD::FP_ROUND,  MVT::f16, Custom);
998       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
999     }
1000   }
1001 
1002   if (!Subtarget->hasFP16()) {
1003     setOperationAction(ISD::FP_EXTEND,  MVT::f32, Custom);
1004     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1005   }
1006 
1007   computeRegisterProperties(Subtarget->getRegisterInfo());
1008 
1009   // ARM does not have floating-point extending loads.
1010   for (MVT VT : MVT::fp_valuetypes()) {
1011     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1012     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1013   }
1014 
1015   // ... or truncating stores
1016   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1017   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1018   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1019 
1020   // ARM does not have i1 sign extending load.
1021   for (MVT VT : MVT::integer_valuetypes())
1022     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1023 
1024   // ARM supports all 4 flavors of integer indexed load / store.
1025   if (!Subtarget->isThumb1Only()) {
1026     for (unsigned im = (unsigned)ISD::PRE_INC;
1027          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1028       setIndexedLoadAction(im,  MVT::i1,  Legal);
1029       setIndexedLoadAction(im,  MVT::i8,  Legal);
1030       setIndexedLoadAction(im,  MVT::i16, Legal);
1031       setIndexedLoadAction(im,  MVT::i32, Legal);
1032       setIndexedStoreAction(im, MVT::i1,  Legal);
1033       setIndexedStoreAction(im, MVT::i8,  Legal);
1034       setIndexedStoreAction(im, MVT::i16, Legal);
1035       setIndexedStoreAction(im, MVT::i32, Legal);
1036     }
1037   } else {
1038     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1039     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
1040     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
1041   }
1042 
1043   setOperationAction(ISD::SADDO, MVT::i32, Custom);
1044   setOperationAction(ISD::UADDO, MVT::i32, Custom);
1045   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1046   setOperationAction(ISD::USUBO, MVT::i32, Custom);
1047 
1048   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1049   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1050   if (Subtarget->hasDSP()) {
1051     setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1052     setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1053     setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1054     setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1055   }
1056   if (Subtarget->hasBaseDSP()) {
1057     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1058     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1059   }
1060 
1061   // i64 operation support.
1062   setOperationAction(ISD::MUL,     MVT::i64, Expand);
1063   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
1064   if (Subtarget->isThumb1Only()) {
1065     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1066     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1067   }
1068   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1069       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1070     setOperationAction(ISD::MULHS, MVT::i32, Expand);
1071 
1072   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1073   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1074   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1075   setOperationAction(ISD::SRL,       MVT::i64, Custom);
1076   setOperationAction(ISD::SRA,       MVT::i64, Custom);
1077   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1078   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1079   setOperationAction(ISD::LOAD, MVT::i64, Custom);
1080   setOperationAction(ISD::STORE, MVT::i64, Custom);
1081 
1082   // MVE lowers 64 bit shifts to lsll and lsrl
1083   // assuming that ISD::SRL and SRA of i64 are already marked custom
1084   if (Subtarget->hasMVEIntegerOps())
1085     setOperationAction(ISD::SHL, MVT::i64, Custom);
1086 
1087   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1088   if (Subtarget->isThumb1Only()) {
1089     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1090     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1091     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1092   }
1093 
1094   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1095     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1096 
1097   // ARM does not have ROTL.
1098   setOperationAction(ISD::ROTL, MVT::i32, Expand);
1099   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1100     setOperationAction(ISD::ROTL, VT, Expand);
1101     setOperationAction(ISD::ROTR, VT, Expand);
1102   }
1103   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
1104   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1105   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1106     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1107     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1108   }
1109 
1110   // @llvm.readcyclecounter requires the Performance Monitors extension.
1111   // Default to the 0 expansion on unsupported platforms.
1112   // FIXME: Technically there are older ARM CPUs that have
1113   // implementation-specific ways of obtaining this information.
1114   if (Subtarget->hasPerfMon())
1115     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1116 
1117   // Only ARMv6 has BSWAP.
1118   if (!Subtarget->hasV6Ops())
1119     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1120 
1121   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1122                                         : Subtarget->hasDivideInARMMode();
1123   if (!hasDivide) {
1124     // These are expanded into libcalls if the cpu doesn't have HW divider.
1125     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
1126     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
1127   }
1128 
1129   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1130     setOperationAction(ISD::SDIV, MVT::i32, Custom);
1131     setOperationAction(ISD::UDIV, MVT::i32, Custom);
1132 
1133     setOperationAction(ISD::SDIV, MVT::i64, Custom);
1134     setOperationAction(ISD::UDIV, MVT::i64, Custom);
1135   }
1136 
1137   setOperationAction(ISD::SREM,  MVT::i32, Expand);
1138   setOperationAction(ISD::UREM,  MVT::i32, Expand);
1139 
1140   // Register based DivRem for AEABI (RTABI 4.2)
1141   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1142       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1143       Subtarget->isTargetWindows()) {
1144     setOperationAction(ISD::SREM, MVT::i64, Custom);
1145     setOperationAction(ISD::UREM, MVT::i64, Custom);
1146     HasStandaloneRem = false;
1147 
1148     if (Subtarget->isTargetWindows()) {
1149       const struct {
1150         const RTLIB::Libcall Op;
1151         const char * const Name;
1152         const CallingConv::ID CC;
1153       } LibraryCalls[] = {
1154         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1155         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1156         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1157         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1158 
1159         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1160         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1161         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1162         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1163       };
1164 
1165       for (const auto &LC : LibraryCalls) {
1166         setLibcallName(LC.Op, LC.Name);
1167         setLibcallCallingConv(LC.Op, LC.CC);
1168       }
1169     } else {
1170       const struct {
1171         const RTLIB::Libcall Op;
1172         const char * const Name;
1173         const CallingConv::ID CC;
1174       } LibraryCalls[] = {
1175         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1176         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1177         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1178         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1179 
1180         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1181         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1182         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1183         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1184       };
1185 
1186       for (const auto &LC : LibraryCalls) {
1187         setLibcallName(LC.Op, LC.Name);
1188         setLibcallCallingConv(LC.Op, LC.CC);
1189       }
1190     }
1191 
1192     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1193     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1194     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1195     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1196   } else {
1197     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1198     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1199   }
1200 
1201   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
1202     // MSVCRT doesn't have powi; fall back to pow
1203     setLibcallName(RTLIB::POWI_F32, nullptr);
1204     setLibcallName(RTLIB::POWI_F64, nullptr);
1205   }
1206 
1207   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
1208   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
1209   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1210   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1211 
1212   setOperationAction(ISD::TRAP, MVT::Other, Legal);
1213   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1214 
1215   // Use the default implementation.
1216   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
1217   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
1218   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
1219   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
1220   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
1221   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
1222 
1223   if (Subtarget->isTargetWindows())
1224     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1225   else
1226     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1227 
1228   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1229   // the default expansion.
1230   InsertFencesForAtomic = false;
1231   if (Subtarget->hasAnyDataBarrier() &&
1232       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1233     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1234     // to ldrex/strex loops already.
1235     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
1236     if (!Subtarget->isThumb() || !Subtarget->isMClass())
1237       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
1238 
1239     // On v8, we have particularly efficient implementations of atomic fences
1240     // if they can be combined with nearby atomic loads and stores.
1241     if (!Subtarget->hasAcquireRelease() ||
1242         getTargetMachine().getOptLevel() == 0) {
1243       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1244       InsertFencesForAtomic = true;
1245     }
1246   } else {
1247     // If there's anything we can use as a barrier, go through custom lowering
1248     // for ATOMIC_FENCE.
1249     // If target has DMB in thumb, Fences can be inserted.
1250     if (Subtarget->hasDataBarrier())
1251       InsertFencesForAtomic = true;
1252 
1253     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1254                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1255 
1256     // Set them all for expansion, which will force libcalls.
1257     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1258     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1259     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1260     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1261     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1262     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1263     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1264     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1265     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1266     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1267     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1268     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1269     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1270     // Unordered/Monotonic case.
1271     if (!InsertFencesForAtomic) {
1272       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1273       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1274     }
1275   }
1276 
1277   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1278 
1279   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1280   if (!Subtarget->hasV6Ops()) {
1281     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1282     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1283   }
1284   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1285 
1286   if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1287       !Subtarget->isThumb1Only()) {
1288     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1289     // iff target supports vfp2.
1290     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1291     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1292   }
1293 
1294   // We want to custom lower some of our intrinsics.
1295   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1296   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1297   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1298   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1299   if (Subtarget->useSjLjEH())
1300     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1301 
1302   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1303   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1304   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1305   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1306   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1307   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1308   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1309   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1310   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1311   if (Subtarget->hasFullFP16()) {
1312     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1313     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1314     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1315   }
1316 
1317   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1318 
1319   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1320   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1321   if (Subtarget->hasFullFP16())
1322       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1323   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1324   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1325   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1326 
1327   // We don't support sin/cos/fmod/copysign/pow
1328   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1329   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1330   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1331   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1332   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1333   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1334   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1335   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1336   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1337       !Subtarget->isThumb1Only()) {
1338     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1339     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1340   }
1341   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1342   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1343 
1344   if (!Subtarget->hasVFP4Base()) {
1345     setOperationAction(ISD::FMA, MVT::f64, Expand);
1346     setOperationAction(ISD::FMA, MVT::f32, Expand);
1347   }
1348 
1349   // Various VFP goodness
1350   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1351     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1352     if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1353       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1354       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1355     }
1356 
1357     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1358     if (!Subtarget->hasFP16()) {
1359       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1360       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1361     }
1362 
1363     // Strict floating-point comparisons need custom lowering.
1364     setOperationAction(ISD::STRICT_FSETCC,  MVT::f16, Custom);
1365     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
1366     setOperationAction(ISD::STRICT_FSETCC,  MVT::f32, Custom);
1367     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
1368     setOperationAction(ISD::STRICT_FSETCC,  MVT::f64, Custom);
1369     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
1370   }
1371 
1372   // Use __sincos_stret if available.
1373   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1374       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1375     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1376     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1377   }
1378 
1379   // FP-ARMv8 implements a lot of rounding-like FP operations.
1380   if (Subtarget->hasFPARMv8Base()) {
1381     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1382     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1383     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1384     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1385     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1386     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1387     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1388     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1389     if (Subtarget->hasNEON()) {
1390       setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1391       setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1392       setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1393       setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1394     }
1395 
1396     if (Subtarget->hasFP64()) {
1397       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1398       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1399       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1400       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1401       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1402       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1403       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1404       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1405     }
1406   }
1407 
1408   // FP16 often need to be promoted to call lib functions
1409   if (Subtarget->hasFullFP16()) {
1410     setOperationAction(ISD::FREM, MVT::f16, Promote);
1411     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1412     setOperationAction(ISD::FSIN, MVT::f16, Promote);
1413     setOperationAction(ISD::FCOS, MVT::f16, Promote);
1414     setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1415     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1416     setOperationAction(ISD::FPOW, MVT::f16, Promote);
1417     setOperationAction(ISD::FEXP, MVT::f16, Promote);
1418     setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1419     setOperationAction(ISD::FLOG, MVT::f16, Promote);
1420     setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1421     setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1422 
1423     setOperationAction(ISD::FROUND, MVT::f16, Legal);
1424   }
1425 
1426   if (Subtarget->hasNEON()) {
1427     // vmin and vmax aren't available in a scalar form, so we can use
1428     // a NEON instruction with an undef lane instead.  This has a performance
1429     // penalty on some cores, so we don't do this unless we have been
1430     // asked to by the core tuning model.
1431     if (Subtarget->useNEONForSinglePrecisionFP()) {
1432       setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1433       setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1434       setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1435       setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1436     }
1437     setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1438     setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1439     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1440     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1441 
1442     if (Subtarget->hasFullFP16()) {
1443       setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1444       setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1445       setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1446       setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1447 
1448       setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1449       setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1450       setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1451       setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1452     }
1453   }
1454 
1455   // We have target-specific dag combine patterns for the following nodes:
1456   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1457   setTargetDAGCombine(ISD::ADD);
1458   setTargetDAGCombine(ISD::SUB);
1459   setTargetDAGCombine(ISD::MUL);
1460   setTargetDAGCombine(ISD::AND);
1461   setTargetDAGCombine(ISD::OR);
1462   setTargetDAGCombine(ISD::XOR);
1463 
1464   if (Subtarget->hasMVEIntegerOps())
1465     setTargetDAGCombine(ISD::VSELECT);
1466 
1467   if (Subtarget->hasV6Ops())
1468     setTargetDAGCombine(ISD::SRL);
1469   if (Subtarget->isThumb1Only())
1470     setTargetDAGCombine(ISD::SHL);
1471 
1472   setStackPointerRegisterToSaveRestore(ARM::SP);
1473 
1474   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1475       !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1476     setSchedulingPreference(Sched::RegPressure);
1477   else
1478     setSchedulingPreference(Sched::Hybrid);
1479 
1480   //// temporary - rewrite interface to use type
1481   MaxStoresPerMemset = 8;
1482   MaxStoresPerMemsetOptSize = 4;
1483   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1484   MaxStoresPerMemcpyOptSize = 2;
1485   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1486   MaxStoresPerMemmoveOptSize = 2;
1487 
1488   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1489   // are at least 4 bytes aligned.
1490   setMinStackArgumentAlignment(Align(4));
1491 
1492   // Prefer likely predicted branches to selects on out-of-order cores.
1493   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1494 
1495   setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1496 
1497   setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1498 
1499   if (Subtarget->isThumb() || Subtarget->isThumb2())
1500     setTargetDAGCombine(ISD::ABS);
1501 }
1502 
1503 bool ARMTargetLowering::useSoftFloat() const {
1504   return Subtarget->useSoftFloat();
1505 }
1506 
1507 // FIXME: It might make sense to define the representative register class as the
1508 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1509 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1510 // SPR's representative would be DPR_VFP2. This should work well if register
1511 // pressure tracking were modified such that a register use would increment the
1512 // pressure of the register class's representative and all of it's super
1513 // classes' representatives transitively. We have not implemented this because
1514 // of the difficulty prior to coalescing of modeling operand register classes
1515 // due to the common occurrence of cross class copies and subregister insertions
1516 // and extractions.
1517 std::pair<const TargetRegisterClass *, uint8_t>
1518 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1519                                            MVT VT) const {
1520   const TargetRegisterClass *RRC = nullptr;
1521   uint8_t Cost = 1;
1522   switch (VT.SimpleTy) {
1523   default:
1524     return TargetLowering::findRepresentativeClass(TRI, VT);
1525   // Use DPR as representative register class for all floating point
1526   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1527   // the cost is 1 for both f32 and f64.
1528   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1529   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1530     RRC = &ARM::DPRRegClass;
1531     // When NEON is used for SP, only half of the register file is available
1532     // because operations that define both SP and DP results will be constrained
1533     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1534     // coalescing by double-counting the SP regs. See the FIXME above.
1535     if (Subtarget->useNEONForSinglePrecisionFP())
1536       Cost = 2;
1537     break;
1538   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1539   case MVT::v4f32: case MVT::v2f64:
1540     RRC = &ARM::DPRRegClass;
1541     Cost = 2;
1542     break;
1543   case MVT::v4i64:
1544     RRC = &ARM::DPRRegClass;
1545     Cost = 4;
1546     break;
1547   case MVT::v8i64:
1548     RRC = &ARM::DPRRegClass;
1549     Cost = 8;
1550     break;
1551   }
1552   return std::make_pair(RRC, Cost);
1553 }
1554 
1555 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1556   switch ((ARMISD::NodeType)Opcode) {
1557   case ARMISD::FIRST_NUMBER:  break;
1558   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1559   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1560   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1561   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1562   case ARMISD::CALL:          return "ARMISD::CALL";
1563   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1564   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1565   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1566   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1567   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1568   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1569   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1570   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1571   case ARMISD::CMP:           return "ARMISD::CMP";
1572   case ARMISD::CMN:           return "ARMISD::CMN";
1573   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1574   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1575   case ARMISD::CMPFPE:        return "ARMISD::CMPFPE";
1576   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1577   case ARMISD::CMPFPEw0:      return "ARMISD::CMPFPEw0";
1578   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1579   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1580 
1581   case ARMISD::CMOV:          return "ARMISD::CMOV";
1582   case ARMISD::SUBS:          return "ARMISD::SUBS";
1583 
1584   case ARMISD::SSAT:          return "ARMISD::SSAT";
1585   case ARMISD::USAT:          return "ARMISD::USAT";
1586 
1587   case ARMISD::ASRL:          return "ARMISD::ASRL";
1588   case ARMISD::LSRL:          return "ARMISD::LSRL";
1589   case ARMISD::LSLL:          return "ARMISD::LSLL";
1590 
1591   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1592   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1593   case ARMISD::RRX:           return "ARMISD::RRX";
1594 
1595   case ARMISD::ADDC:          return "ARMISD::ADDC";
1596   case ARMISD::ADDE:          return "ARMISD::ADDE";
1597   case ARMISD::SUBC:          return "ARMISD::SUBC";
1598   case ARMISD::SUBE:          return "ARMISD::SUBE";
1599   case ARMISD::LSLS:          return "ARMISD::LSLS";
1600 
1601   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1602   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1603   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1604   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1605   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
1606 
1607   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1608   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1609   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1610 
1611   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1612 
1613   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1614 
1615   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1616 
1617   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1618 
1619   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1620 
1621   case ARMISD::LDRD:          return "ARMISD::LDRD";
1622   case ARMISD::STRD:          return "ARMISD::STRD";
1623 
1624   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1625   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1626 
1627   case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1628   case ARMISD::VECTOR_REG_CAST: return "ARMISD::VECTOR_REG_CAST";
1629   case ARMISD::VCMP:          return "ARMISD::VCMP";
1630   case ARMISD::VCMPZ:         return "ARMISD::VCMPZ";
1631   case ARMISD::VTST:          return "ARMISD::VTST";
1632 
1633   case ARMISD::VSHLs:         return "ARMISD::VSHLs";
1634   case ARMISD::VSHLu:         return "ARMISD::VSHLu";
1635   case ARMISD::VSHLIMM:       return "ARMISD::VSHLIMM";
1636   case ARMISD::VSHRsIMM:      return "ARMISD::VSHRsIMM";
1637   case ARMISD::VSHRuIMM:      return "ARMISD::VSHRuIMM";
1638   case ARMISD::VRSHRsIMM:     return "ARMISD::VRSHRsIMM";
1639   case ARMISD::VRSHRuIMM:     return "ARMISD::VRSHRuIMM";
1640   case ARMISD::VRSHRNIMM:     return "ARMISD::VRSHRNIMM";
1641   case ARMISD::VQSHLsIMM:     return "ARMISD::VQSHLsIMM";
1642   case ARMISD::VQSHLuIMM:     return "ARMISD::VQSHLuIMM";
1643   case ARMISD::VQSHLsuIMM:    return "ARMISD::VQSHLsuIMM";
1644   case ARMISD::VQSHRNsIMM:    return "ARMISD::VQSHRNsIMM";
1645   case ARMISD::VQSHRNuIMM:    return "ARMISD::VQSHRNuIMM";
1646   case ARMISD::VQSHRNsuIMM:   return "ARMISD::VQSHRNsuIMM";
1647   case ARMISD::VQRSHRNsIMM:   return "ARMISD::VQRSHRNsIMM";
1648   case ARMISD::VQRSHRNuIMM:   return "ARMISD::VQRSHRNuIMM";
1649   case ARMISD::VQRSHRNsuIMM:  return "ARMISD::VQRSHRNsuIMM";
1650   case ARMISD::VSLIIMM:       return "ARMISD::VSLIIMM";
1651   case ARMISD::VSRIIMM:       return "ARMISD::VSRIIMM";
1652   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1653   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1654   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1655   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1656   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1657   case ARMISD::VDUP:          return "ARMISD::VDUP";
1658   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1659   case ARMISD::VEXT:          return "ARMISD::VEXT";
1660   case ARMISD::VREV64:        return "ARMISD::VREV64";
1661   case ARMISD::VREV32:        return "ARMISD::VREV32";
1662   case ARMISD::VREV16:        return "ARMISD::VREV16";
1663   case ARMISD::VZIP:          return "ARMISD::VZIP";
1664   case ARMISD::VUZP:          return "ARMISD::VUZP";
1665   case ARMISD::VTRN:          return "ARMISD::VTRN";
1666   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1667   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1668   case ARMISD::VMOVN:         return "ARMISD::VMOVN";
1669   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1670   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1671   case ARMISD::VADDVs:        return "ARMISD::VADDVs";
1672   case ARMISD::VADDVu:        return "ARMISD::VADDVu";
1673   case ARMISD::VADDLVs:       return "ARMISD::VADDLVs";
1674   case ARMISD::VADDLVu:       return "ARMISD::VADDLVu";
1675   case ARMISD::VADDLVAs:      return "ARMISD::VADDLVAs";
1676   case ARMISD::VADDLVAu:      return "ARMISD::VADDLVAu";
1677   case ARMISD::VADDLVps:      return "ARMISD::VADDLVps";
1678   case ARMISD::VADDLVpu:      return "ARMISD::VADDLVpu";
1679   case ARMISD::VADDLVAps:     return "ARMISD::VADDLVAps";
1680   case ARMISD::VADDLVApu:     return "ARMISD::VADDLVApu";
1681   case ARMISD::VMLAVs:        return "ARMISD::VMLAVs";
1682   case ARMISD::VMLAVu:        return "ARMISD::VMLAVu";
1683   case ARMISD::VMLALVs:       return "ARMISD::VMLALVs";
1684   case ARMISD::VMLALVu:       return "ARMISD::VMLALVu";
1685   case ARMISD::VMLALVAs:      return "ARMISD::VMLALVAs";
1686   case ARMISD::VMLALVAu:      return "ARMISD::VMLALVAu";
1687   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1688   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1689   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1690   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1691   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1692   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1693   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1694   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1695   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1696   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1697   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1698   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1699   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1700   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1701   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1702   case ARMISD::QADD16b:       return "ARMISD::QADD16b";
1703   case ARMISD::QSUB16b:       return "ARMISD::QSUB16b";
1704   case ARMISD::QADD8b:        return "ARMISD::QADD8b";
1705   case ARMISD::QSUB8b:        return "ARMISD::QSUB8b";
1706   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1707   case ARMISD::BFI:           return "ARMISD::BFI";
1708   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1709   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1710   case ARMISD::VBSL:          return "ARMISD::VBSL";
1711   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1712   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1713   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1714   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1715   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1716   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1717   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1718   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1719   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1720   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1721   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1722   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1723   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1724   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1725   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1726   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1727   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1728   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1729   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1730   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1731   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1732   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1733   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1734   case ARMISD::WLS:           return "ARMISD::WLS";
1735   case ARMISD::LE:            return "ARMISD::LE";
1736   case ARMISD::LOOP_DEC:      return "ARMISD::LOOP_DEC";
1737   case ARMISD::CSINV:         return "ARMISD::CSINV";
1738   case ARMISD::CSNEG:         return "ARMISD::CSNEG";
1739   case ARMISD::CSINC:         return "ARMISD::CSINC";
1740   }
1741   return nullptr;
1742 }
1743 
1744 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1745                                           EVT VT) const {
1746   if (!VT.isVector())
1747     return getPointerTy(DL);
1748 
1749   // MVE has a predicate register.
1750   if (Subtarget->hasMVEIntegerOps() &&
1751       (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1752     return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1753   return VT.changeVectorElementTypeToInteger();
1754 }
1755 
1756 /// getRegClassFor - Return the register class that should be used for the
1757 /// specified value type.
1758 const TargetRegisterClass *
1759 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1760   (void)isDivergent;
1761   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1762   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1763   // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1764   // MVE Q registers.
1765   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1766     if (VT == MVT::v4i64)
1767       return &ARM::QQPRRegClass;
1768     if (VT == MVT::v8i64)
1769       return &ARM::QQQQPRRegClass;
1770   }
1771   return TargetLowering::getRegClassFor(VT);
1772 }
1773 
1774 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1775 // source/dest is aligned and the copy size is large enough. We therefore want
1776 // to align such objects passed to memory intrinsics.
1777 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1778                                                unsigned &PrefAlign) const {
1779   if (!isa<MemIntrinsic>(CI))
1780     return false;
1781   MinSize = 8;
1782   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1783   // cycle faster than 4-byte aligned LDM.
1784   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1785   return true;
1786 }
1787 
1788 // Create a fast isel object.
1789 FastISel *
1790 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1791                                   const TargetLibraryInfo *libInfo) const {
1792   return ARM::createFastISel(funcInfo, libInfo);
1793 }
1794 
1795 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1796   unsigned NumVals = N->getNumValues();
1797   if (!NumVals)
1798     return Sched::RegPressure;
1799 
1800   for (unsigned i = 0; i != NumVals; ++i) {
1801     EVT VT = N->getValueType(i);
1802     if (VT == MVT::Glue || VT == MVT::Other)
1803       continue;
1804     if (VT.isFloatingPoint() || VT.isVector())
1805       return Sched::ILP;
1806   }
1807 
1808   if (!N->isMachineOpcode())
1809     return Sched::RegPressure;
1810 
1811   // Load are scheduled for latency even if there instruction itinerary
1812   // is not available.
1813   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1814   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1815 
1816   if (MCID.getNumDefs() == 0)
1817     return Sched::RegPressure;
1818   if (!Itins->isEmpty() &&
1819       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1820     return Sched::ILP;
1821 
1822   return Sched::RegPressure;
1823 }
1824 
1825 //===----------------------------------------------------------------------===//
1826 // Lowering Code
1827 //===----------------------------------------------------------------------===//
1828 
1829 static bool isSRL16(const SDValue &Op) {
1830   if (Op.getOpcode() != ISD::SRL)
1831     return false;
1832   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1833     return Const->getZExtValue() == 16;
1834   return false;
1835 }
1836 
1837 static bool isSRA16(const SDValue &Op) {
1838   if (Op.getOpcode() != ISD::SRA)
1839     return false;
1840   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1841     return Const->getZExtValue() == 16;
1842   return false;
1843 }
1844 
1845 static bool isSHL16(const SDValue &Op) {
1846   if (Op.getOpcode() != ISD::SHL)
1847     return false;
1848   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1849     return Const->getZExtValue() == 16;
1850   return false;
1851 }
1852 
1853 // Check for a signed 16-bit value. We special case SRA because it makes it
1854 // more simple when also looking for SRAs that aren't sign extending a
1855 // smaller value. Without the check, we'd need to take extra care with
1856 // checking order for some operations.
1857 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1858   if (isSRA16(Op))
1859     return isSHL16(Op.getOperand(0));
1860   return DAG.ComputeNumSignBits(Op) == 17;
1861 }
1862 
1863 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1864 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1865   switch (CC) {
1866   default: llvm_unreachable("Unknown condition code!");
1867   case ISD::SETNE:  return ARMCC::NE;
1868   case ISD::SETEQ:  return ARMCC::EQ;
1869   case ISD::SETGT:  return ARMCC::GT;
1870   case ISD::SETGE:  return ARMCC::GE;
1871   case ISD::SETLT:  return ARMCC::LT;
1872   case ISD::SETLE:  return ARMCC::LE;
1873   case ISD::SETUGT: return ARMCC::HI;
1874   case ISD::SETUGE: return ARMCC::HS;
1875   case ISD::SETULT: return ARMCC::LO;
1876   case ISD::SETULE: return ARMCC::LS;
1877   }
1878 }
1879 
1880 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1881 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1882                         ARMCC::CondCodes &CondCode2) {
1883   CondCode2 = ARMCC::AL;
1884   switch (CC) {
1885   default: llvm_unreachable("Unknown FP condition!");
1886   case ISD::SETEQ:
1887   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1888   case ISD::SETGT:
1889   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1890   case ISD::SETGE:
1891   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1892   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1893   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1894   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1895   case ISD::SETO:   CondCode = ARMCC::VC; break;
1896   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1897   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1898   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1899   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1900   case ISD::SETLT:
1901   case ISD::SETULT: CondCode = ARMCC::LT; break;
1902   case ISD::SETLE:
1903   case ISD::SETULE: CondCode = ARMCC::LE; break;
1904   case ISD::SETNE:
1905   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1906   }
1907 }
1908 
1909 //===----------------------------------------------------------------------===//
1910 //                      Calling Convention Implementation
1911 //===----------------------------------------------------------------------===//
1912 
1913 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1914 /// account presence of floating point hardware and calling convention
1915 /// limitations, such as support for variadic functions.
1916 CallingConv::ID
1917 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1918                                            bool isVarArg) const {
1919   switch (CC) {
1920   default:
1921     report_fatal_error("Unsupported calling convention");
1922   case CallingConv::ARM_AAPCS:
1923   case CallingConv::ARM_APCS:
1924   case CallingConv::GHC:
1925   case CallingConv::CFGuard_Check:
1926     return CC;
1927   case CallingConv::PreserveMost:
1928     return CallingConv::PreserveMost;
1929   case CallingConv::ARM_AAPCS_VFP:
1930   case CallingConv::Swift:
1931     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1932   case CallingConv::C:
1933     if (!Subtarget->isAAPCS_ABI())
1934       return CallingConv::ARM_APCS;
1935     else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1936              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1937              !isVarArg)
1938       return CallingConv::ARM_AAPCS_VFP;
1939     else
1940       return CallingConv::ARM_AAPCS;
1941   case CallingConv::Fast:
1942   case CallingConv::CXX_FAST_TLS:
1943     if (!Subtarget->isAAPCS_ABI()) {
1944       if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1945         return CallingConv::Fast;
1946       return CallingConv::ARM_APCS;
1947     } else if (Subtarget->hasVFP2Base() &&
1948                !Subtarget->isThumb1Only() && !isVarArg)
1949       return CallingConv::ARM_AAPCS_VFP;
1950     else
1951       return CallingConv::ARM_AAPCS;
1952   }
1953 }
1954 
1955 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1956                                                  bool isVarArg) const {
1957   return CCAssignFnForNode(CC, false, isVarArg);
1958 }
1959 
1960 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1961                                                    bool isVarArg) const {
1962   return CCAssignFnForNode(CC, true, isVarArg);
1963 }
1964 
1965 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1966 /// CallingConvention.
1967 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1968                                                  bool Return,
1969                                                  bool isVarArg) const {
1970   switch (getEffectiveCallingConv(CC, isVarArg)) {
1971   default:
1972     report_fatal_error("Unsupported calling convention");
1973   case CallingConv::ARM_APCS:
1974     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1975   case CallingConv::ARM_AAPCS:
1976     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1977   case CallingConv::ARM_AAPCS_VFP:
1978     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1979   case CallingConv::Fast:
1980     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1981   case CallingConv::GHC:
1982     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1983   case CallingConv::PreserveMost:
1984     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1985   case CallingConv::CFGuard_Check:
1986     return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
1987   }
1988 }
1989 
1990 /// LowerCallResult - Lower the result values of a call into the
1991 /// appropriate copies out of appropriate physical registers.
1992 SDValue ARMTargetLowering::LowerCallResult(
1993     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1994     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1995     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1996     SDValue ThisVal) const {
1997   // Assign locations to each value returned by this call.
1998   SmallVector<CCValAssign, 16> RVLocs;
1999   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2000                  *DAG.getContext());
2001   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
2002 
2003   // Copy all of the result registers out of their specified physreg.
2004   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2005     CCValAssign VA = RVLocs[i];
2006 
2007     // Pass 'this' value directly from the argument to return value, to avoid
2008     // reg unit interference
2009     if (i == 0 && isThisReturn) {
2010       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
2011              "unexpected return calling convention register assignment");
2012       InVals.push_back(ThisVal);
2013       continue;
2014     }
2015 
2016     SDValue Val;
2017     if (VA.needsCustom()) {
2018       // Handle f64 or half of a v2f64.
2019       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2020                                       InFlag);
2021       Chain = Lo.getValue(1);
2022       InFlag = Lo.getValue(2);
2023       VA = RVLocs[++i]; // skip ahead to next loc
2024       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2025                                       InFlag);
2026       Chain = Hi.getValue(1);
2027       InFlag = Hi.getValue(2);
2028       if (!Subtarget->isLittle())
2029         std::swap (Lo, Hi);
2030       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2031 
2032       if (VA.getLocVT() == MVT::v2f64) {
2033         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2034         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2035                           DAG.getConstant(0, dl, MVT::i32));
2036 
2037         VA = RVLocs[++i]; // skip ahead to next loc
2038         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2039         Chain = Lo.getValue(1);
2040         InFlag = Lo.getValue(2);
2041         VA = RVLocs[++i]; // skip ahead to next loc
2042         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2043         Chain = Hi.getValue(1);
2044         InFlag = Hi.getValue(2);
2045         if (!Subtarget->isLittle())
2046           std::swap (Lo, Hi);
2047         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2048         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2049                           DAG.getConstant(1, dl, MVT::i32));
2050       }
2051     } else {
2052       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2053                                InFlag);
2054       Chain = Val.getValue(1);
2055       InFlag = Val.getValue(2);
2056     }
2057 
2058     switch (VA.getLocInfo()) {
2059     default: llvm_unreachable("Unknown loc info!");
2060     case CCValAssign::Full: break;
2061     case CCValAssign::BCvt:
2062       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2063       break;
2064     }
2065 
2066     InVals.push_back(Val);
2067   }
2068 
2069   return Chain;
2070 }
2071 
2072 /// LowerMemOpCallTo - Store the argument to the stack.
2073 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
2074                                             SDValue Arg, const SDLoc &dl,
2075                                             SelectionDAG &DAG,
2076                                             const CCValAssign &VA,
2077                                             ISD::ArgFlagsTy Flags) const {
2078   unsigned LocMemOffset = VA.getLocMemOffset();
2079   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2080   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2081                        StackPtr, PtrOff);
2082   return DAG.getStore(
2083       Chain, dl, Arg, PtrOff,
2084       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2085 }
2086 
2087 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2088                                          SDValue Chain, SDValue &Arg,
2089                                          RegsToPassVector &RegsToPass,
2090                                          CCValAssign &VA, CCValAssign &NextVA,
2091                                          SDValue &StackPtr,
2092                                          SmallVectorImpl<SDValue> &MemOpChains,
2093                                          ISD::ArgFlagsTy Flags) const {
2094   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2095                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
2096   unsigned id = Subtarget->isLittle() ? 0 : 1;
2097   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2098 
2099   if (NextVA.isRegLoc())
2100     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2101   else {
2102     assert(NextVA.isMemLoc());
2103     if (!StackPtr.getNode())
2104       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2105                                     getPointerTy(DAG.getDataLayout()));
2106 
2107     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2108                                            dl, DAG, NextVA,
2109                                            Flags));
2110   }
2111 }
2112 
2113 /// LowerCall - Lowering a call into a callseq_start <-
2114 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2115 /// nodes.
2116 SDValue
2117 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2118                              SmallVectorImpl<SDValue> &InVals) const {
2119   SelectionDAG &DAG                     = CLI.DAG;
2120   SDLoc &dl                             = CLI.DL;
2121   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2122   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2123   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2124   SDValue Chain                         = CLI.Chain;
2125   SDValue Callee                        = CLI.Callee;
2126   bool &isTailCall                      = CLI.IsTailCall;
2127   CallingConv::ID CallConv              = CLI.CallConv;
2128   bool doesNotRet                       = CLI.DoesNotReturn;
2129   bool isVarArg                         = CLI.IsVarArg;
2130 
2131   MachineFunction &MF = DAG.getMachineFunction();
2132   MachineFunction::CallSiteInfo CSInfo;
2133   bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2134   bool isThisReturn = false;
2135   bool PreferIndirect = false;
2136 
2137   // Disable tail calls if they're not supported.
2138   if (!Subtarget->supportsTailCall())
2139     isTailCall = false;
2140 
2141   if (isa<GlobalAddressSDNode>(Callee)) {
2142     // If we're optimizing for minimum size and the function is called three or
2143     // more times in this block, we can improve codesize by calling indirectly
2144     // as BLXr has a 16-bit encoding.
2145     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2146     if (CLI.CB) {
2147       auto *BB = CLI.CB->getParent();
2148       PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2149                        count_if(GV->users(), [&BB](const User *U) {
2150                          return isa<Instruction>(U) &&
2151                                 cast<Instruction>(U)->getParent() == BB;
2152                        }) > 2;
2153     }
2154   }
2155   if (isTailCall) {
2156     // Check if it's really possible to do a tail call.
2157     isTailCall = IsEligibleForTailCallOptimization(
2158         Callee, CallConv, isVarArg, isStructRet,
2159         MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2160         PreferIndirect);
2161     if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2162       report_fatal_error("failed to perform tail call elimination on a call "
2163                          "site marked musttail");
2164     // We don't support GuaranteedTailCallOpt for ARM, only automatically
2165     // detected sibcalls.
2166     if (isTailCall)
2167       ++NumTailCalls;
2168   }
2169 
2170   // Analyze operands of the call, assigning locations to each operand.
2171   SmallVector<CCValAssign, 16> ArgLocs;
2172   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2173                  *DAG.getContext());
2174   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2175 
2176   // Get a count of how many bytes are to be pushed on the stack.
2177   unsigned NumBytes = CCInfo.getNextStackOffset();
2178 
2179   if (isTailCall) {
2180     // For tail calls, memory operands are available in our caller's stack.
2181     NumBytes = 0;
2182   } else {
2183     // Adjust the stack pointer for the new arguments...
2184     // These operations are automatically eliminated by the prolog/epilog pass
2185     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2186   }
2187 
2188   SDValue StackPtr =
2189       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2190 
2191   RegsToPassVector RegsToPass;
2192   SmallVector<SDValue, 8> MemOpChains;
2193 
2194   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2195   // of tail call optimization, arguments are handled later.
2196   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2197        i != e;
2198        ++i, ++realArgIdx) {
2199     CCValAssign &VA = ArgLocs[i];
2200     SDValue Arg = OutVals[realArgIdx];
2201     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2202     bool isByVal = Flags.isByVal();
2203 
2204     // Promote the value if needed.
2205     switch (VA.getLocInfo()) {
2206     default: llvm_unreachable("Unknown loc info!");
2207     case CCValAssign::Full: break;
2208     case CCValAssign::SExt:
2209       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2210       break;
2211     case CCValAssign::ZExt:
2212       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2213       break;
2214     case CCValAssign::AExt:
2215       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2216       break;
2217     case CCValAssign::BCvt:
2218       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2219       break;
2220     }
2221 
2222     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2223     if (VA.needsCustom()) {
2224       if (VA.getLocVT() == MVT::v2f64) {
2225         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2226                                   DAG.getConstant(0, dl, MVT::i32));
2227         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2228                                   DAG.getConstant(1, dl, MVT::i32));
2229 
2230         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2231                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2232 
2233         VA = ArgLocs[++i]; // skip ahead to next loc
2234         if (VA.isRegLoc()) {
2235           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2236                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2237         } else {
2238           assert(VA.isMemLoc());
2239 
2240           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2241                                                  dl, DAG, VA, Flags));
2242         }
2243       } else {
2244         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2245                          StackPtr, MemOpChains, Flags);
2246       }
2247     } else if (VA.isRegLoc()) {
2248       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2249           Outs[0].VT == MVT::i32) {
2250         assert(VA.getLocVT() == MVT::i32 &&
2251                "unexpected calling convention register assignment");
2252         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2253                "unexpected use of 'returned'");
2254         isThisReturn = true;
2255       }
2256       const TargetOptions &Options = DAG.getTarget().Options;
2257       if (Options.EmitCallSiteInfo)
2258         CSInfo.emplace_back(VA.getLocReg(), i);
2259       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2260     } else if (isByVal) {
2261       assert(VA.isMemLoc());
2262       unsigned offset = 0;
2263 
2264       // True if this byval aggregate will be split between registers
2265       // and memory.
2266       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2267       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2268 
2269       if (CurByValIdx < ByValArgsCount) {
2270 
2271         unsigned RegBegin, RegEnd;
2272         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2273 
2274         EVT PtrVT =
2275             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2276         unsigned int i, j;
2277         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2278           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2279           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2280           SDValue Load =
2281               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2282                           DAG.InferPtrAlign(AddArg));
2283           MemOpChains.push_back(Load.getValue(1));
2284           RegsToPass.push_back(std::make_pair(j, Load));
2285         }
2286 
2287         // If parameter size outsides register area, "offset" value
2288         // helps us to calculate stack slot for remained part properly.
2289         offset = RegEnd - RegBegin;
2290 
2291         CCInfo.nextInRegsParam();
2292       }
2293 
2294       if (Flags.getByValSize() > 4*offset) {
2295         auto PtrVT = getPointerTy(DAG.getDataLayout());
2296         unsigned LocMemOffset = VA.getLocMemOffset();
2297         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2298         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2299         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2300         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2301         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2302                                            MVT::i32);
2303         SDValue AlignNode =
2304             DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2305 
2306         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2307         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2308         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2309                                           Ops));
2310       }
2311     } else if (!isTailCall) {
2312       assert(VA.isMemLoc());
2313 
2314       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2315                                              dl, DAG, VA, Flags));
2316     }
2317   }
2318 
2319   if (!MemOpChains.empty())
2320     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2321 
2322   // Build a sequence of copy-to-reg nodes chained together with token chain
2323   // and flag operands which copy the outgoing args into the appropriate regs.
2324   SDValue InFlag;
2325   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2326     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2327                              RegsToPass[i].second, InFlag);
2328     InFlag = Chain.getValue(1);
2329   }
2330 
2331   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2332   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2333   // node so that legalize doesn't hack it.
2334   bool isDirect = false;
2335 
2336   const TargetMachine &TM = getTargetMachine();
2337   const Module *Mod = MF.getFunction().getParent();
2338   const GlobalValue *GV = nullptr;
2339   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2340     GV = G->getGlobal();
2341   bool isStub =
2342       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2343 
2344   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2345   bool isLocalARMFunc = false;
2346   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2347   auto PtrVt = getPointerTy(DAG.getDataLayout());
2348 
2349   if (Subtarget->genLongCalls()) {
2350     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2351            "long-calls codegen is not position independent!");
2352     // Handle a global address or an external symbol. If it's not one of
2353     // those, the target's already in a register, so we don't need to do
2354     // anything extra.
2355     if (isa<GlobalAddressSDNode>(Callee)) {
2356       // Create a constant pool entry for the callee address
2357       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2358       ARMConstantPoolValue *CPV =
2359         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2360 
2361       // Get the address of the callee into a register
2362       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2363       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2364       Callee = DAG.getLoad(
2365           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2366           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2367     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2368       const char *Sym = S->getSymbol();
2369 
2370       // Create a constant pool entry for the callee address
2371       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2372       ARMConstantPoolValue *CPV =
2373         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2374                                       ARMPCLabelIndex, 0);
2375       // Get the address of the callee into a register
2376       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2377       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2378       Callee = DAG.getLoad(
2379           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2380           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2381     }
2382   } else if (isa<GlobalAddressSDNode>(Callee)) {
2383     if (!PreferIndirect) {
2384       isDirect = true;
2385       bool isDef = GV->isStrongDefinitionForLinker();
2386 
2387       // ARM call to a local ARM function is predicable.
2388       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2389       // tBX takes a register source operand.
2390       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2391         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2392         Callee = DAG.getNode(
2393             ARMISD::WrapperPIC, dl, PtrVt,
2394             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2395         Callee = DAG.getLoad(
2396             PtrVt, dl, DAG.getEntryNode(), Callee,
2397             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2398             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2399                                      MachineMemOperand::MOInvariant);
2400       } else if (Subtarget->isTargetCOFF()) {
2401         assert(Subtarget->isTargetWindows() &&
2402                "Windows is the only supported COFF target");
2403         unsigned TargetFlags = ARMII::MO_NO_FLAG;
2404         if (GV->hasDLLImportStorageClass())
2405           TargetFlags = ARMII::MO_DLLIMPORT;
2406         else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
2407           TargetFlags = ARMII::MO_COFFSTUB;
2408         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2409                                             TargetFlags);
2410         if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2411           Callee =
2412               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2413                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2414                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2415       } else {
2416         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2417       }
2418     }
2419   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2420     isDirect = true;
2421     // tBX takes a register source operand.
2422     const char *Sym = S->getSymbol();
2423     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2424       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2425       ARMConstantPoolValue *CPV =
2426         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2427                                       ARMPCLabelIndex, 4);
2428       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2429       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2430       Callee = DAG.getLoad(
2431           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2432           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2433       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2434       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2435     } else {
2436       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2437     }
2438   }
2439 
2440   // FIXME: handle tail calls differently.
2441   unsigned CallOpc;
2442   if (Subtarget->isThumb()) {
2443     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2444       CallOpc = ARMISD::CALL_NOLINK;
2445     else
2446       CallOpc = ARMISD::CALL;
2447   } else {
2448     if (!isDirect && !Subtarget->hasV5TOps())
2449       CallOpc = ARMISD::CALL_NOLINK;
2450     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2451              // Emit regular call when code size is the priority
2452              !Subtarget->hasMinSize())
2453       // "mov lr, pc; b _foo" to avoid confusing the RSP
2454       CallOpc = ARMISD::CALL_NOLINK;
2455     else
2456       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2457   }
2458 
2459   std::vector<SDValue> Ops;
2460   Ops.push_back(Chain);
2461   Ops.push_back(Callee);
2462 
2463   // Add argument registers to the end of the list so that they are known live
2464   // into the call.
2465   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2466     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2467                                   RegsToPass[i].second.getValueType()));
2468 
2469   // Add a register mask operand representing the call-preserved registers.
2470   if (!isTailCall) {
2471     const uint32_t *Mask;
2472     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2473     if (isThisReturn) {
2474       // For 'this' returns, use the R0-preserving mask if applicable
2475       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2476       if (!Mask) {
2477         // Set isThisReturn to false if the calling convention is not one that
2478         // allows 'returned' to be modeled in this way, so LowerCallResult does
2479         // not try to pass 'this' straight through
2480         isThisReturn = false;
2481         Mask = ARI->getCallPreservedMask(MF, CallConv);
2482       }
2483     } else
2484       Mask = ARI->getCallPreservedMask(MF, CallConv);
2485 
2486     assert(Mask && "Missing call preserved mask for calling convention");
2487     Ops.push_back(DAG.getRegisterMask(Mask));
2488   }
2489 
2490   if (InFlag.getNode())
2491     Ops.push_back(InFlag);
2492 
2493   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2494   if (isTailCall) {
2495     MF.getFrameInfo().setHasTailCall();
2496     SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2497     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2498     return Ret;
2499   }
2500 
2501   // Returns a chain and a flag for retval copy to use.
2502   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2503   InFlag = Chain.getValue(1);
2504   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2505 
2506   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2507                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2508   if (!Ins.empty())
2509     InFlag = Chain.getValue(1);
2510 
2511   // Handle result values, copying them out of physregs into vregs that we
2512   // return.
2513   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2514                          InVals, isThisReturn,
2515                          isThisReturn ? OutVals[0] : SDValue());
2516 }
2517 
2518 /// HandleByVal - Every parameter *after* a byval parameter is passed
2519 /// on the stack.  Remember the next parameter register to allocate,
2520 /// and then confiscate the rest of the parameter registers to insure
2521 /// this.
2522 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2523                                     unsigned Align) const {
2524   // Byval (as with any stack) slots are always at least 4 byte aligned.
2525   Align = std::max(Align, 4U);
2526 
2527   unsigned Reg = State->AllocateReg(GPRArgRegs);
2528   if (!Reg)
2529     return;
2530 
2531   unsigned AlignInRegs = Align / 4;
2532   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2533   for (unsigned i = 0; i < Waste; ++i)
2534     Reg = State->AllocateReg(GPRArgRegs);
2535 
2536   if (!Reg)
2537     return;
2538 
2539   unsigned Excess = 4 * (ARM::R4 - Reg);
2540 
2541   // Special case when NSAA != SP and parameter size greater than size of
2542   // all remained GPR regs. In that case we can't split parameter, we must
2543   // send it to stack. We also must set NCRN to R4, so waste all
2544   // remained registers.
2545   const unsigned NSAAOffset = State->getNextStackOffset();
2546   if (NSAAOffset != 0 && Size > Excess) {
2547     while (State->AllocateReg(GPRArgRegs))
2548       ;
2549     return;
2550   }
2551 
2552   // First register for byval parameter is the first register that wasn't
2553   // allocated before this method call, so it would be "reg".
2554   // If parameter is small enough to be saved in range [reg, r4), then
2555   // the end (first after last) register would be reg + param-size-in-regs,
2556   // else parameter would be splitted between registers and stack,
2557   // end register would be r4 in this case.
2558   unsigned ByValRegBegin = Reg;
2559   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2560   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2561   // Note, first register is allocated in the beginning of function already,
2562   // allocate remained amount of registers we need.
2563   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2564     State->AllocateReg(GPRArgRegs);
2565   // A byval parameter that is split between registers and memory needs its
2566   // size truncated here.
2567   // In the case where the entire structure fits in registers, we set the
2568   // size in memory to zero.
2569   Size = std::max<int>(Size - Excess, 0);
2570 }
2571 
2572 /// MatchingStackOffset - Return true if the given stack call argument is
2573 /// already available in the same position (relatively) of the caller's
2574 /// incoming argument stack.
2575 static
2576 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2577                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2578                          const TargetInstrInfo *TII) {
2579   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2580   int FI = std::numeric_limits<int>::max();
2581   if (Arg.getOpcode() == ISD::CopyFromReg) {
2582     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2583     if (!Register::isVirtualRegister(VR))
2584       return false;
2585     MachineInstr *Def = MRI->getVRegDef(VR);
2586     if (!Def)
2587       return false;
2588     if (!Flags.isByVal()) {
2589       if (!TII->isLoadFromStackSlot(*Def, FI))
2590         return false;
2591     } else {
2592       return false;
2593     }
2594   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2595     if (Flags.isByVal())
2596       // ByVal argument is passed in as a pointer but it's now being
2597       // dereferenced. e.g.
2598       // define @foo(%struct.X* %A) {
2599       //   tail call @bar(%struct.X* byval %A)
2600       // }
2601       return false;
2602     SDValue Ptr = Ld->getBasePtr();
2603     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2604     if (!FINode)
2605       return false;
2606     FI = FINode->getIndex();
2607   } else
2608     return false;
2609 
2610   assert(FI != std::numeric_limits<int>::max());
2611   if (!MFI.isFixedObjectIndex(FI))
2612     return false;
2613   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2614 }
2615 
2616 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2617 /// for tail call optimization. Targets which want to do tail call
2618 /// optimization should implement this function.
2619 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2620     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2621     bool isCalleeStructRet, bool isCallerStructRet,
2622     const SmallVectorImpl<ISD::OutputArg> &Outs,
2623     const SmallVectorImpl<SDValue> &OutVals,
2624     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2625     const bool isIndirect) const {
2626   MachineFunction &MF = DAG.getMachineFunction();
2627   const Function &CallerF = MF.getFunction();
2628   CallingConv::ID CallerCC = CallerF.getCallingConv();
2629 
2630   assert(Subtarget->supportsTailCall());
2631 
2632   // Indirect tail calls cannot be optimized for Thumb1 if the args
2633   // to the call take up r0-r3. The reason is that there are no legal registers
2634   // left to hold the pointer to the function to be called.
2635   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2636       (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2637     return false;
2638 
2639   // Look for obvious safe cases to perform tail call optimization that do not
2640   // require ABI changes. This is what gcc calls sibcall.
2641 
2642   // Exception-handling functions need a special set of instructions to indicate
2643   // a return to the hardware. Tail-calling another function would probably
2644   // break this.
2645   if (CallerF.hasFnAttribute("interrupt"))
2646     return false;
2647 
2648   // Also avoid sibcall optimization if either caller or callee uses struct
2649   // return semantics.
2650   if (isCalleeStructRet || isCallerStructRet)
2651     return false;
2652 
2653   // Externally-defined functions with weak linkage should not be
2654   // tail-called on ARM when the OS does not support dynamic
2655   // pre-emption of symbols, as the AAELF spec requires normal calls
2656   // to undefined weak functions to be replaced with a NOP or jump to the
2657   // next instruction. The behaviour of branch instructions in this
2658   // situation (as used for tail calls) is implementation-defined, so we
2659   // cannot rely on the linker replacing the tail call with a return.
2660   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2661     const GlobalValue *GV = G->getGlobal();
2662     const Triple &TT = getTargetMachine().getTargetTriple();
2663     if (GV->hasExternalWeakLinkage() &&
2664         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2665       return false;
2666   }
2667 
2668   // Check that the call results are passed in the same way.
2669   LLVMContext &C = *DAG.getContext();
2670   if (!CCState::resultsCompatible(
2671           getEffectiveCallingConv(CalleeCC, isVarArg),
2672           getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
2673           CCAssignFnForReturn(CalleeCC, isVarArg),
2674           CCAssignFnForReturn(CallerCC, CallerF.isVarArg())))
2675     return false;
2676   // The callee has to preserve all registers the caller needs to preserve.
2677   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2678   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2679   if (CalleeCC != CallerCC) {
2680     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2681     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2682       return false;
2683   }
2684 
2685   // If Caller's vararg or byval argument has been split between registers and
2686   // stack, do not perform tail call, since part of the argument is in caller's
2687   // local frame.
2688   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2689   if (AFI_Caller->getArgRegsSaveSize())
2690     return false;
2691 
2692   // If the callee takes no arguments then go on to check the results of the
2693   // call.
2694   if (!Outs.empty()) {
2695     // Check if stack adjustment is needed. For now, do not do this if any
2696     // argument is passed on the stack.
2697     SmallVector<CCValAssign, 16> ArgLocs;
2698     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2699     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2700     if (CCInfo.getNextStackOffset()) {
2701       // Check if the arguments are already laid out in the right way as
2702       // the caller's fixed stack objects.
2703       MachineFrameInfo &MFI = MF.getFrameInfo();
2704       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2705       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2706       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2707            i != e;
2708            ++i, ++realArgIdx) {
2709         CCValAssign &VA = ArgLocs[i];
2710         EVT RegVT = VA.getLocVT();
2711         SDValue Arg = OutVals[realArgIdx];
2712         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2713         if (VA.getLocInfo() == CCValAssign::Indirect)
2714           return false;
2715         if (VA.needsCustom()) {
2716           // f64 and vector types are split into multiple registers or
2717           // register/stack-slot combinations.  The types will not match
2718           // the registers; give up on memory f64 refs until we figure
2719           // out what to do about this.
2720           if (!VA.isRegLoc())
2721             return false;
2722           if (!ArgLocs[++i].isRegLoc())
2723             return false;
2724           if (RegVT == MVT::v2f64) {
2725             if (!ArgLocs[++i].isRegLoc())
2726               return false;
2727             if (!ArgLocs[++i].isRegLoc())
2728               return false;
2729           }
2730         } else if (!VA.isRegLoc()) {
2731           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2732                                    MFI, MRI, TII))
2733             return false;
2734         }
2735       }
2736     }
2737 
2738     const MachineRegisterInfo &MRI = MF.getRegInfo();
2739     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2740       return false;
2741   }
2742 
2743   return true;
2744 }
2745 
2746 bool
2747 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2748                                   MachineFunction &MF, bool isVarArg,
2749                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2750                                   LLVMContext &Context) const {
2751   SmallVector<CCValAssign, 16> RVLocs;
2752   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2753   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2754 }
2755 
2756 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2757                                     const SDLoc &DL, SelectionDAG &DAG) {
2758   const MachineFunction &MF = DAG.getMachineFunction();
2759   const Function &F = MF.getFunction();
2760 
2761   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2762 
2763   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2764   // version of the "preferred return address". These offsets affect the return
2765   // instruction if this is a return from PL1 without hypervisor extensions.
2766   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2767   //    SWI:     0      "subs pc, lr, #0"
2768   //    ABORT:   +4     "subs pc, lr, #4"
2769   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2770   // UNDEF varies depending on where the exception came from ARM or Thumb
2771   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2772 
2773   int64_t LROffset;
2774   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2775       IntKind == "ABORT")
2776     LROffset = 4;
2777   else if (IntKind == "SWI" || IntKind == "UNDEF")
2778     LROffset = 0;
2779   else
2780     report_fatal_error("Unsupported interrupt attribute. If present, value "
2781                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2782 
2783   RetOps.insert(RetOps.begin() + 1,
2784                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2785 
2786   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2787 }
2788 
2789 SDValue
2790 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2791                                bool isVarArg,
2792                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2793                                const SmallVectorImpl<SDValue> &OutVals,
2794                                const SDLoc &dl, SelectionDAG &DAG) const {
2795   // CCValAssign - represent the assignment of the return value to a location.
2796   SmallVector<CCValAssign, 16> RVLocs;
2797 
2798   // CCState - Info about the registers and stack slots.
2799   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2800                  *DAG.getContext());
2801 
2802   // Analyze outgoing return values.
2803   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2804 
2805   SDValue Flag;
2806   SmallVector<SDValue, 4> RetOps;
2807   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2808   bool isLittleEndian = Subtarget->isLittle();
2809 
2810   MachineFunction &MF = DAG.getMachineFunction();
2811   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2812   AFI->setReturnRegsCount(RVLocs.size());
2813 
2814   // Copy the result values into the output registers.
2815   for (unsigned i = 0, realRVLocIdx = 0;
2816        i != RVLocs.size();
2817        ++i, ++realRVLocIdx) {
2818     CCValAssign &VA = RVLocs[i];
2819     assert(VA.isRegLoc() && "Can only return in registers!");
2820 
2821     SDValue Arg = OutVals[realRVLocIdx];
2822     bool ReturnF16 = false;
2823 
2824     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2825       // Half-precision return values can be returned like this:
2826       //
2827       // t11 f16 = fadd ...
2828       // t12: i16 = bitcast t11
2829       //   t13: i32 = zero_extend t12
2830       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2831       //
2832       // to avoid code generation for bitcasts, we simply set Arg to the node
2833       // that produces the f16 value, t11 in this case.
2834       //
2835       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2836         SDValue ZE = Arg.getOperand(0);
2837         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2838           SDValue BC = ZE.getOperand(0);
2839           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2840             Arg = BC.getOperand(0);
2841             ReturnF16 = true;
2842           }
2843         }
2844       }
2845     }
2846 
2847     switch (VA.getLocInfo()) {
2848     default: llvm_unreachable("Unknown loc info!");
2849     case CCValAssign::Full: break;
2850     case CCValAssign::BCvt:
2851       if (!ReturnF16)
2852         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2853       break;
2854     }
2855 
2856     if (VA.needsCustom()) {
2857       if (VA.getLocVT() == MVT::v2f64) {
2858         // Extract the first half and return it in two registers.
2859         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2860                                    DAG.getConstant(0, dl, MVT::i32));
2861         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2862                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2863 
2864         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2865                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2866                                  Flag);
2867         Flag = Chain.getValue(1);
2868         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2869         VA = RVLocs[++i]; // skip ahead to next loc
2870         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2871                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2872                                  Flag);
2873         Flag = Chain.getValue(1);
2874         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2875         VA = RVLocs[++i]; // skip ahead to next loc
2876 
2877         // Extract the 2nd half and fall through to handle it as an f64 value.
2878         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2879                           DAG.getConstant(1, dl, MVT::i32));
2880       }
2881       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2882       // available.
2883       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2884                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2885       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2886                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2887                                Flag);
2888       Flag = Chain.getValue(1);
2889       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2890       VA = RVLocs[++i]; // skip ahead to next loc
2891       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2892                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2893                                Flag);
2894     } else
2895       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2896 
2897     // Guarantee that all emitted copies are
2898     // stuck together, avoiding something bad.
2899     Flag = Chain.getValue(1);
2900     RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2901                                      ReturnF16 ? MVT::f16 : VA.getLocVT()));
2902   }
2903   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2904   const MCPhysReg *I =
2905       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2906   if (I) {
2907     for (; *I; ++I) {
2908       if (ARM::GPRRegClass.contains(*I))
2909         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2910       else if (ARM::DPRRegClass.contains(*I))
2911         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2912       else
2913         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2914     }
2915   }
2916 
2917   // Update chain and glue.
2918   RetOps[0] = Chain;
2919   if (Flag.getNode())
2920     RetOps.push_back(Flag);
2921 
2922   // CPUs which aren't M-class use a special sequence to return from
2923   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2924   // though we use "subs pc, lr, #N").
2925   //
2926   // M-class CPUs actually use a normal return sequence with a special
2927   // (hardware-provided) value in LR, so the normal code path works.
2928   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2929       !Subtarget->isMClass()) {
2930     if (Subtarget->isThumb1Only())
2931       report_fatal_error("interrupt attribute is not supported in Thumb1");
2932     return LowerInterruptReturn(RetOps, dl, DAG);
2933   }
2934 
2935   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2936 }
2937 
2938 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2939   if (N->getNumValues() != 1)
2940     return false;
2941   if (!N->hasNUsesOfValue(1, 0))
2942     return false;
2943 
2944   SDValue TCChain = Chain;
2945   SDNode *Copy = *N->use_begin();
2946   if (Copy->getOpcode() == ISD::CopyToReg) {
2947     // If the copy has a glue operand, we conservatively assume it isn't safe to
2948     // perform a tail call.
2949     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2950       return false;
2951     TCChain = Copy->getOperand(0);
2952   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2953     SDNode *VMov = Copy;
2954     // f64 returned in a pair of GPRs.
2955     SmallPtrSet<SDNode*, 2> Copies;
2956     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2957          UI != UE; ++UI) {
2958       if (UI->getOpcode() != ISD::CopyToReg)
2959         return false;
2960       Copies.insert(*UI);
2961     }
2962     if (Copies.size() > 2)
2963       return false;
2964 
2965     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2966          UI != UE; ++UI) {
2967       SDValue UseChain = UI->getOperand(0);
2968       if (Copies.count(UseChain.getNode()))
2969         // Second CopyToReg
2970         Copy = *UI;
2971       else {
2972         // We are at the top of this chain.
2973         // If the copy has a glue operand, we conservatively assume it
2974         // isn't safe to perform a tail call.
2975         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2976           return false;
2977         // First CopyToReg
2978         TCChain = UseChain;
2979       }
2980     }
2981   } else if (Copy->getOpcode() == ISD::BITCAST) {
2982     // f32 returned in a single GPR.
2983     if (!Copy->hasOneUse())
2984       return false;
2985     Copy = *Copy->use_begin();
2986     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2987       return false;
2988     // If the copy has a glue operand, we conservatively assume it isn't safe to
2989     // perform a tail call.
2990     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2991       return false;
2992     TCChain = Copy->getOperand(0);
2993   } else {
2994     return false;
2995   }
2996 
2997   bool HasRet = false;
2998   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2999        UI != UE; ++UI) {
3000     if (UI->getOpcode() != ARMISD::RET_FLAG &&
3001         UI->getOpcode() != ARMISD::INTRET_FLAG)
3002       return false;
3003     HasRet = true;
3004   }
3005 
3006   if (!HasRet)
3007     return false;
3008 
3009   Chain = TCChain;
3010   return true;
3011 }
3012 
3013 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3014   if (!Subtarget->supportsTailCall())
3015     return false;
3016 
3017   if (!CI->isTailCall())
3018     return false;
3019 
3020   return true;
3021 }
3022 
3023 // Trying to write a 64 bit value so need to split into two 32 bit values first,
3024 // and pass the lower and high parts through.
3025 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3026   SDLoc DL(Op);
3027   SDValue WriteValue = Op->getOperand(2);
3028 
3029   // This function is only supposed to be called for i64 type argument.
3030   assert(WriteValue.getValueType() == MVT::i64
3031           && "LowerWRITE_REGISTER called for non-i64 type argument.");
3032 
3033   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3034                            DAG.getConstant(0, DL, MVT::i32));
3035   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3036                            DAG.getConstant(1, DL, MVT::i32));
3037   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3038   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3039 }
3040 
3041 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3042 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3043 // one of the above mentioned nodes. It has to be wrapped because otherwise
3044 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3045 // be used to form addressing mode. These wrapped nodes will be selected
3046 // into MOVi.
3047 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3048                                              SelectionDAG &DAG) const {
3049   EVT PtrVT = Op.getValueType();
3050   // FIXME there is no actual debug info here
3051   SDLoc dl(Op);
3052   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3053   SDValue Res;
3054 
3055   // When generating execute-only code Constant Pools must be promoted to the
3056   // global data section. It's a bit ugly that we can't share them across basic
3057   // blocks, but this way we guarantee that execute-only behaves correct with
3058   // position-independent addressing modes.
3059   if (Subtarget->genExecuteOnly()) {
3060     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3061     auto T = const_cast<Type*>(CP->getType());
3062     auto C = const_cast<Constant*>(CP->getConstVal());
3063     auto M = const_cast<Module*>(DAG.getMachineFunction().
3064                                  getFunction().getParent());
3065     auto GV = new GlobalVariable(
3066                     *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3067                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3068                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3069                     Twine(AFI->createPICLabelUId())
3070                   );
3071     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3072                                             dl, PtrVT);
3073     return LowerGlobalAddress(GA, DAG);
3074   }
3075 
3076   if (CP->isMachineConstantPoolEntry())
3077     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
3078                                     CP->getAlignment());
3079   else
3080     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
3081                                     CP->getAlignment());
3082   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3083 }
3084 
3085 unsigned ARMTargetLowering::getJumpTableEncoding() const {
3086   return MachineJumpTableInfo::EK_Inline;
3087 }
3088 
3089 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3090                                              SelectionDAG &DAG) const {
3091   MachineFunction &MF = DAG.getMachineFunction();
3092   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3093   unsigned ARMPCLabelIndex = 0;
3094   SDLoc DL(Op);
3095   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3096   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3097   SDValue CPAddr;
3098   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3099   if (!IsPositionIndependent) {
3100     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
3101   } else {
3102     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3103     ARMPCLabelIndex = AFI->createPICLabelUId();
3104     ARMConstantPoolValue *CPV =
3105       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3106                                       ARMCP::CPBlockAddress, PCAdj);
3107     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3108   }
3109   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3110   SDValue Result = DAG.getLoad(
3111       PtrVT, DL, DAG.getEntryNode(), CPAddr,
3112       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3113   if (!IsPositionIndependent)
3114     return Result;
3115   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3116   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3117 }
3118 
3119 /// Convert a TLS address reference into the correct sequence of loads
3120 /// and calls to compute the variable's address for Darwin, and return an
3121 /// SDValue containing the final node.
3122 
3123 /// Darwin only has one TLS scheme which must be capable of dealing with the
3124 /// fully general situation, in the worst case. This means:
3125 ///     + "extern __thread" declaration.
3126 ///     + Defined in a possibly unknown dynamic library.
3127 ///
3128 /// The general system is that each __thread variable has a [3 x i32] descriptor
3129 /// which contains information used by the runtime to calculate the address. The
3130 /// only part of this the compiler needs to know about is the first word, which
3131 /// contains a function pointer that must be called with the address of the
3132 /// entire descriptor in "r0".
3133 ///
3134 /// Since this descriptor may be in a different unit, in general access must
3135 /// proceed along the usual ARM rules. A common sequence to produce is:
3136 ///
3137 ///     movw rT1, :lower16:_var$non_lazy_ptr
3138 ///     movt rT1, :upper16:_var$non_lazy_ptr
3139 ///     ldr r0, [rT1]
3140 ///     ldr rT2, [r0]
3141 ///     blx rT2
3142 ///     [...address now in r0...]
3143 SDValue
3144 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3145                                                SelectionDAG &DAG) const {
3146   assert(Subtarget->isTargetDarwin() &&
3147          "This function expects a Darwin target");
3148   SDLoc DL(Op);
3149 
3150   // First step is to get the address of the actua global symbol. This is where
3151   // the TLS descriptor lives.
3152   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3153 
3154   // The first entry in the descriptor is a function pointer that we must call
3155   // to obtain the address of the variable.
3156   SDValue Chain = DAG.getEntryNode();
3157   SDValue FuncTLVGet = DAG.getLoad(
3158       MVT::i32, DL, Chain, DescAddr,
3159       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3160       /* Alignment = */ 4,
3161       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3162           MachineMemOperand::MOInvariant);
3163   Chain = FuncTLVGet.getValue(1);
3164 
3165   MachineFunction &F = DAG.getMachineFunction();
3166   MachineFrameInfo &MFI = F.getFrameInfo();
3167   MFI.setAdjustsStack(true);
3168 
3169   // TLS calls preserve all registers except those that absolutely must be
3170   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3171   // silly).
3172   auto TRI =
3173       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3174   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3175   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3176 
3177   // Finally, we can make the call. This is just a degenerate version of a
3178   // normal AArch64 call node: r0 takes the address of the descriptor, and
3179   // returns the address of the variable in this thread.
3180   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3181   Chain =
3182       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3183                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3184                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3185   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3186 }
3187 
3188 SDValue
3189 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3190                                                 SelectionDAG &DAG) const {
3191   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3192 
3193   SDValue Chain = DAG.getEntryNode();
3194   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3195   SDLoc DL(Op);
3196 
3197   // Load the current TEB (thread environment block)
3198   SDValue Ops[] = {Chain,
3199                    DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3200                    DAG.getTargetConstant(15, DL, MVT::i32),
3201                    DAG.getTargetConstant(0, DL, MVT::i32),
3202                    DAG.getTargetConstant(13, DL, MVT::i32),
3203                    DAG.getTargetConstant(0, DL, MVT::i32),
3204                    DAG.getTargetConstant(2, DL, MVT::i32)};
3205   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3206                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
3207 
3208   SDValue TEB = CurrentTEB.getValue(0);
3209   Chain = CurrentTEB.getValue(1);
3210 
3211   // Load the ThreadLocalStoragePointer from the TEB
3212   // A pointer to the TLS array is located at offset 0x2c from the TEB.
3213   SDValue TLSArray =
3214       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3215   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3216 
3217   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3218   // offset into the TLSArray.
3219 
3220   // Load the TLS index from the C runtime
3221   SDValue TLSIndex =
3222       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3223   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3224   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3225 
3226   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3227                               DAG.getConstant(2, DL, MVT::i32));
3228   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3229                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3230                             MachinePointerInfo());
3231 
3232   // Get the offset of the start of the .tls section (section base)
3233   const auto *GA = cast<GlobalAddressSDNode>(Op);
3234   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3235   SDValue Offset = DAG.getLoad(
3236       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3237                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3238       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3239 
3240   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3241 }
3242 
3243 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3244 SDValue
3245 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3246                                                  SelectionDAG &DAG) const {
3247   SDLoc dl(GA);
3248   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3249   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3250   MachineFunction &MF = DAG.getMachineFunction();
3251   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3252   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3253   ARMConstantPoolValue *CPV =
3254     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3255                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3256   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3257   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3258   Argument = DAG.getLoad(
3259       PtrVT, dl, DAG.getEntryNode(), Argument,
3260       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3261   SDValue Chain = Argument.getValue(1);
3262 
3263   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3264   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3265 
3266   // call __tls_get_addr.
3267   ArgListTy Args;
3268   ArgListEntry Entry;
3269   Entry.Node = Argument;
3270   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3271   Args.push_back(Entry);
3272 
3273   // FIXME: is there useful debug info available here?
3274   TargetLowering::CallLoweringInfo CLI(DAG);
3275   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3276       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3277       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3278 
3279   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3280   return CallResult.first;
3281 }
3282 
3283 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3284 // "local exec" model.
3285 SDValue
3286 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3287                                         SelectionDAG &DAG,
3288                                         TLSModel::Model model) const {
3289   const GlobalValue *GV = GA->getGlobal();
3290   SDLoc dl(GA);
3291   SDValue Offset;
3292   SDValue Chain = DAG.getEntryNode();
3293   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3294   // Get the Thread Pointer
3295   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3296 
3297   if (model == TLSModel::InitialExec) {
3298     MachineFunction &MF = DAG.getMachineFunction();
3299     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3300     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3301     // Initial exec model.
3302     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3303     ARMConstantPoolValue *CPV =
3304       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3305                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3306                                       true);
3307     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3308     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3309     Offset = DAG.getLoad(
3310         PtrVT, dl, Chain, Offset,
3311         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3312     Chain = Offset.getValue(1);
3313 
3314     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3315     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3316 
3317     Offset = DAG.getLoad(
3318         PtrVT, dl, Chain, Offset,
3319         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3320   } else {
3321     // local exec model
3322     assert(model == TLSModel::LocalExec);
3323     ARMConstantPoolValue *CPV =
3324       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3325     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3326     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3327     Offset = DAG.getLoad(
3328         PtrVT, dl, Chain, Offset,
3329         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3330   }
3331 
3332   // The address of the thread local variable is the add of the thread
3333   // pointer with the offset of the variable.
3334   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3335 }
3336 
3337 SDValue
3338 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3339   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3340   if (DAG.getTarget().useEmulatedTLS())
3341     return LowerToTLSEmulatedModel(GA, DAG);
3342 
3343   if (Subtarget->isTargetDarwin())
3344     return LowerGlobalTLSAddressDarwin(Op, DAG);
3345 
3346   if (Subtarget->isTargetWindows())
3347     return LowerGlobalTLSAddressWindows(Op, DAG);
3348 
3349   // TODO: implement the "local dynamic" model
3350   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3351   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3352 
3353   switch (model) {
3354     case TLSModel::GeneralDynamic:
3355     case TLSModel::LocalDynamic:
3356       return LowerToTLSGeneralDynamicModel(GA, DAG);
3357     case TLSModel::InitialExec:
3358     case TLSModel::LocalExec:
3359       return LowerToTLSExecModels(GA, DAG, model);
3360   }
3361   llvm_unreachable("bogus TLS model");
3362 }
3363 
3364 /// Return true if all users of V are within function F, looking through
3365 /// ConstantExprs.
3366 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3367   SmallVector<const User*,4> Worklist;
3368   for (auto *U : V->users())
3369     Worklist.push_back(U);
3370   while (!Worklist.empty()) {
3371     auto *U = Worklist.pop_back_val();
3372     if (isa<ConstantExpr>(U)) {
3373       for (auto *UU : U->users())
3374         Worklist.push_back(UU);
3375       continue;
3376     }
3377 
3378     auto *I = dyn_cast<Instruction>(U);
3379     if (!I || I->getParent()->getParent() != F)
3380       return false;
3381   }
3382   return true;
3383 }
3384 
3385 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3386                                      const GlobalValue *GV, SelectionDAG &DAG,
3387                                      EVT PtrVT, const SDLoc &dl) {
3388   // If we're creating a pool entry for a constant global with unnamed address,
3389   // and the global is small enough, we can emit it inline into the constant pool
3390   // to save ourselves an indirection.
3391   //
3392   // This is a win if the constant is only used in one function (so it doesn't
3393   // need to be duplicated) or duplicating the constant wouldn't increase code
3394   // size (implying the constant is no larger than 4 bytes).
3395   const Function &F = DAG.getMachineFunction().getFunction();
3396 
3397   // We rely on this decision to inline being idemopotent and unrelated to the
3398   // use-site. We know that if we inline a variable at one use site, we'll
3399   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3400   // doesn't know about this optimization, so bail out if it's enabled else
3401   // we could decide to inline here (and thus never emit the GV) but require
3402   // the GV from fast-isel generated code.
3403   if (!EnableConstpoolPromotion ||
3404       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3405       return SDValue();
3406 
3407   auto *GVar = dyn_cast<GlobalVariable>(GV);
3408   if (!GVar || !GVar->hasInitializer() ||
3409       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3410       !GVar->hasLocalLinkage())
3411     return SDValue();
3412 
3413   // If we inline a value that contains relocations, we move the relocations
3414   // from .data to .text. This is not allowed in position-independent code.
3415   auto *Init = GVar->getInitializer();
3416   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3417       Init->needsRelocation())
3418     return SDValue();
3419 
3420   // The constant islands pass can only really deal with alignment requests
3421   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3422   // any type wanting greater alignment requirements than 4 bytes. We also
3423   // can only promote constants that are multiples of 4 bytes in size or
3424   // are paddable to a multiple of 4. Currently we only try and pad constants
3425   // that are strings for simplicity.
3426   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3427   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3428   unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3429   unsigned RequiredPadding = 4 - (Size % 4);
3430   bool PaddingPossible =
3431     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3432   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3433       Size == 0)
3434     return SDValue();
3435 
3436   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3437   MachineFunction &MF = DAG.getMachineFunction();
3438   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3439 
3440   // We can't bloat the constant pool too much, else the ConstantIslands pass
3441   // may fail to converge. If we haven't promoted this global yet (it may have
3442   // multiple uses), and promoting it would increase the constant pool size (Sz
3443   // > 4), ensure we have space to do so up to MaxTotal.
3444   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3445     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3446         ConstpoolPromotionMaxTotal)
3447       return SDValue();
3448 
3449   // This is only valid if all users are in a single function; we can't clone
3450   // the constant in general. The LLVM IR unnamed_addr allows merging
3451   // constants, but not cloning them.
3452   //
3453   // We could potentially allow cloning if we could prove all uses of the
3454   // constant in the current function don't care about the address, like
3455   // printf format strings. But that isn't implemented for now.
3456   if (!allUsersAreInFunction(GVar, &F))
3457     return SDValue();
3458 
3459   // We're going to inline this global. Pad it out if needed.
3460   if (RequiredPadding != 4) {
3461     StringRef S = CDAInit->getAsString();
3462 
3463     SmallVector<uint8_t,16> V(S.size());
3464     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3465     while (RequiredPadding--)
3466       V.push_back(0);
3467     Init = ConstantDataArray::get(*DAG.getContext(), V);
3468   }
3469 
3470   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3471   SDValue CPAddr =
3472     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3473   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3474     AFI->markGlobalAsPromotedToConstantPool(GVar);
3475     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3476                                       PaddedSize - 4);
3477   }
3478   ++NumConstpoolPromoted;
3479   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3480 }
3481 
3482 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3483   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3484     if (!(GV = GA->getBaseObject()))
3485       return false;
3486   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3487     return V->isConstant();
3488   return isa<Function>(GV);
3489 }
3490 
3491 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3492                                               SelectionDAG &DAG) const {
3493   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3494   default: llvm_unreachable("unknown object format");
3495   case Triple::COFF:
3496     return LowerGlobalAddressWindows(Op, DAG);
3497   case Triple::ELF:
3498     return LowerGlobalAddressELF(Op, DAG);
3499   case Triple::MachO:
3500     return LowerGlobalAddressDarwin(Op, DAG);
3501   }
3502 }
3503 
3504 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3505                                                  SelectionDAG &DAG) const {
3506   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3507   SDLoc dl(Op);
3508   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3509   const TargetMachine &TM = getTargetMachine();
3510   bool IsRO = isReadOnly(GV);
3511 
3512   // promoteToConstantPool only if not generating XO text section
3513   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3514     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3515       return V;
3516 
3517   if (isPositionIndependent()) {
3518     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3519     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3520                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3521     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3522     if (UseGOT_PREL)
3523       Result =
3524           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3525                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3526     return Result;
3527   } else if (Subtarget->isROPI() && IsRO) {
3528     // PC-relative.
3529     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3530     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3531     return Result;
3532   } else if (Subtarget->isRWPI() && !IsRO) {
3533     // SB-relative.
3534     SDValue RelAddr;
3535     if (Subtarget->useMovt()) {
3536       ++NumMovwMovt;
3537       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3538       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3539     } else { // use literal pool for address constant
3540       ARMConstantPoolValue *CPV =
3541         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3542       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3543       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3544       RelAddr = DAG.getLoad(
3545           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3546           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3547     }
3548     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3549     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3550     return Result;
3551   }
3552 
3553   // If we have T2 ops, we can materialize the address directly via movt/movw
3554   // pair. This is always cheaper.
3555   if (Subtarget->useMovt()) {
3556     ++NumMovwMovt;
3557     // FIXME: Once remat is capable of dealing with instructions with register
3558     // operands, expand this into two nodes.
3559     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3560                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3561   } else {
3562     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3563     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3564     return DAG.getLoad(
3565         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3566         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3567   }
3568 }
3569 
3570 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3571                                                     SelectionDAG &DAG) const {
3572   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3573          "ROPI/RWPI not currently supported for Darwin");
3574   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3575   SDLoc dl(Op);
3576   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3577 
3578   if (Subtarget->useMovt())
3579     ++NumMovwMovt;
3580 
3581   // FIXME: Once remat is capable of dealing with instructions with register
3582   // operands, expand this into multiple nodes
3583   unsigned Wrapper =
3584       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3585 
3586   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3587   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3588 
3589   if (Subtarget->isGVIndirectSymbol(GV))
3590     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3591                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3592   return Result;
3593 }
3594 
3595 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3596                                                      SelectionDAG &DAG) const {
3597   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3598   assert(Subtarget->useMovt() &&
3599          "Windows on ARM expects to use movw/movt");
3600   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3601          "ROPI/RWPI not currently supported for Windows");
3602 
3603   const TargetMachine &TM = getTargetMachine();
3604   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3605   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3606   if (GV->hasDLLImportStorageClass())
3607     TargetFlags = ARMII::MO_DLLIMPORT;
3608   else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3609     TargetFlags = ARMII::MO_COFFSTUB;
3610   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3611   SDValue Result;
3612   SDLoc DL(Op);
3613 
3614   ++NumMovwMovt;
3615 
3616   // FIXME: Once remat is capable of dealing with instructions with register
3617   // operands, expand this into two nodes.
3618   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3619                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3620                                                   TargetFlags));
3621   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3622     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3623                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3624   return Result;
3625 }
3626 
3627 SDValue
3628 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3629   SDLoc dl(Op);
3630   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3631   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3632                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3633                      Op.getOperand(1), Val);
3634 }
3635 
3636 SDValue
3637 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3638   SDLoc dl(Op);
3639   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3640                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3641 }
3642 
3643 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3644                                                       SelectionDAG &DAG) const {
3645   SDLoc dl(Op);
3646   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3647                      Op.getOperand(0));
3648 }
3649 
3650 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3651     SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3652   unsigned IntNo =
3653       cast<ConstantSDNode>(
3654           Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3655           ->getZExtValue();
3656   switch (IntNo) {
3657     default:
3658       return SDValue();  // Don't custom lower most intrinsics.
3659     case Intrinsic::arm_gnu_eabi_mcount: {
3660       MachineFunction &MF = DAG.getMachineFunction();
3661       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3662       SDLoc dl(Op);
3663       SDValue Chain = Op.getOperand(0);
3664       // call "\01__gnu_mcount_nc"
3665       const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3666       const uint32_t *Mask =
3667           ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3668       assert(Mask && "Missing call preserved mask for calling convention");
3669       // Mark LR an implicit live-in.
3670       unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3671       SDValue ReturnAddress =
3672           DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3673       constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3674       SDValue Callee =
3675           DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3676       SDValue RegisterMask = DAG.getRegisterMask(Mask);
3677       if (Subtarget->isThumb())
3678         return SDValue(
3679             DAG.getMachineNode(
3680                 ARM::tBL_PUSHLR, dl, ResultTys,
3681                 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3682                  DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3683             0);
3684       return SDValue(
3685           DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3686                              {ReturnAddress, Callee, RegisterMask, Chain}),
3687           0);
3688     }
3689   }
3690 }
3691 
3692 SDValue
3693 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3694                                           const ARMSubtarget *Subtarget) const {
3695   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3696   SDLoc dl(Op);
3697   switch (IntNo) {
3698   default: return SDValue();    // Don't custom lower most intrinsics.
3699   case Intrinsic::thread_pointer: {
3700     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3701     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3702   }
3703   case Intrinsic::arm_cls: {
3704     const SDValue &Operand = Op.getOperand(1);
3705     const EVT VTy = Op.getValueType();
3706     SDValue SRA =
3707         DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
3708     SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
3709     SDValue SHL =
3710         DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
3711     SDValue OR =
3712         DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
3713     SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
3714     return Result;
3715   }
3716   case Intrinsic::arm_cls64: {
3717     // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
3718     //          else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
3719     const SDValue &Operand = Op.getOperand(1);
3720     const EVT VTy = Op.getValueType();
3721 
3722     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3723                              DAG.getConstant(1, dl, VTy));
3724     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3725                              DAG.getConstant(0, dl, VTy));
3726     SDValue Constant0 = DAG.getConstant(0, dl, VTy);
3727     SDValue Constant1 = DAG.getConstant(1, dl, VTy);
3728     SDValue Constant31 = DAG.getConstant(31, dl, VTy);
3729     SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
3730     SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
3731     SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
3732     SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
3733     SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
3734     SDValue CheckLo =
3735         DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
3736     SDValue HiIsZero =
3737         DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
3738     SDValue AdjustedLo =
3739         DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
3740     SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
3741     SDValue Result =
3742         DAG.getSelect(dl, VTy, CheckLo,
3743                       DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
3744     return Result;
3745   }
3746   case Intrinsic::eh_sjlj_lsda: {
3747     MachineFunction &MF = DAG.getMachineFunction();
3748     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3749     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3750     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3751     SDValue CPAddr;
3752     bool IsPositionIndependent = isPositionIndependent();
3753     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3754     ARMConstantPoolValue *CPV =
3755       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3756                                       ARMCP::CPLSDA, PCAdj);
3757     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3758     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3759     SDValue Result = DAG.getLoad(
3760         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3761         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3762 
3763     if (IsPositionIndependent) {
3764       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3765       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3766     }
3767     return Result;
3768   }
3769   case Intrinsic::arm_neon_vabs:
3770     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3771                         Op.getOperand(1));
3772   case Intrinsic::arm_neon_vmulls:
3773   case Intrinsic::arm_neon_vmullu: {
3774     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3775       ? ARMISD::VMULLs : ARMISD::VMULLu;
3776     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3777                        Op.getOperand(1), Op.getOperand(2));
3778   }
3779   case Intrinsic::arm_neon_vminnm:
3780   case Intrinsic::arm_neon_vmaxnm: {
3781     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3782       ? ISD::FMINNUM : ISD::FMAXNUM;
3783     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3784                        Op.getOperand(1), Op.getOperand(2));
3785   }
3786   case Intrinsic::arm_neon_vminu:
3787   case Intrinsic::arm_neon_vmaxu: {
3788     if (Op.getValueType().isFloatingPoint())
3789       return SDValue();
3790     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3791       ? ISD::UMIN : ISD::UMAX;
3792     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3793                          Op.getOperand(1), Op.getOperand(2));
3794   }
3795   case Intrinsic::arm_neon_vmins:
3796   case Intrinsic::arm_neon_vmaxs: {
3797     // v{min,max}s is overloaded between signed integers and floats.
3798     if (!Op.getValueType().isFloatingPoint()) {
3799       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3800         ? ISD::SMIN : ISD::SMAX;
3801       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3802                          Op.getOperand(1), Op.getOperand(2));
3803     }
3804     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3805       ? ISD::FMINIMUM : ISD::FMAXIMUM;
3806     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3807                        Op.getOperand(1), Op.getOperand(2));
3808   }
3809   case Intrinsic::arm_neon_vtbl1:
3810     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3811                        Op.getOperand(1), Op.getOperand(2));
3812   case Intrinsic::arm_neon_vtbl2:
3813     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3814                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3815   case Intrinsic::arm_mve_pred_i2v:
3816   case Intrinsic::arm_mve_pred_v2i:
3817     return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
3818                        Op.getOperand(1));
3819   case Intrinsic::arm_mve_vreinterpretq:
3820     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
3821                        Op.getOperand(1));
3822   case Intrinsic::arm_mve_lsll:
3823     return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
3824                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3825   case Intrinsic::arm_mve_asrl:
3826     return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
3827                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3828   }
3829 }
3830 
3831 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3832                                  const ARMSubtarget *Subtarget) {
3833   SDLoc dl(Op);
3834   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3835   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3836   if (SSID == SyncScope::SingleThread)
3837     return Op;
3838 
3839   if (!Subtarget->hasDataBarrier()) {
3840     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3841     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3842     // here.
3843     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3844            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3845     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3846                        DAG.getConstant(0, dl, MVT::i32));
3847   }
3848 
3849   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3850   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3851   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3852   if (Subtarget->isMClass()) {
3853     // Only a full system barrier exists in the M-class architectures.
3854     Domain = ARM_MB::SY;
3855   } else if (Subtarget->preferISHSTBarriers() &&
3856              Ord == AtomicOrdering::Release) {
3857     // Swift happens to implement ISHST barriers in a way that's compatible with
3858     // Release semantics but weaker than ISH so we'd be fools not to use
3859     // it. Beware: other processors probably don't!
3860     Domain = ARM_MB::ISHST;
3861   }
3862 
3863   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3864                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3865                      DAG.getConstant(Domain, dl, MVT::i32));
3866 }
3867 
3868 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3869                              const ARMSubtarget *Subtarget) {
3870   // ARM pre v5TE and Thumb1 does not have preload instructions.
3871   if (!(Subtarget->isThumb2() ||
3872         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3873     // Just preserve the chain.
3874     return Op.getOperand(0);
3875 
3876   SDLoc dl(Op);
3877   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3878   if (!isRead &&
3879       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3880     // ARMv7 with MP extension has PLDW.
3881     return Op.getOperand(0);
3882 
3883   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3884   if (Subtarget->isThumb()) {
3885     // Invert the bits.
3886     isRead = ~isRead & 1;
3887     isData = ~isData & 1;
3888   }
3889 
3890   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3891                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3892                      DAG.getConstant(isData, dl, MVT::i32));
3893 }
3894 
3895 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3896   MachineFunction &MF = DAG.getMachineFunction();
3897   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3898 
3899   // vastart just stores the address of the VarArgsFrameIndex slot into the
3900   // memory location argument.
3901   SDLoc dl(Op);
3902   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3903   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3904   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3905   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3906                       MachinePointerInfo(SV));
3907 }
3908 
3909 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3910                                                 CCValAssign &NextVA,
3911                                                 SDValue &Root,
3912                                                 SelectionDAG &DAG,
3913                                                 const SDLoc &dl) const {
3914   MachineFunction &MF = DAG.getMachineFunction();
3915   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3916 
3917   const TargetRegisterClass *RC;
3918   if (AFI->isThumb1OnlyFunction())
3919     RC = &ARM::tGPRRegClass;
3920   else
3921     RC = &ARM::GPRRegClass;
3922 
3923   // Transform the arguments stored in physical registers into virtual ones.
3924   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3925   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3926 
3927   SDValue ArgValue2;
3928   if (NextVA.isMemLoc()) {
3929     MachineFrameInfo &MFI = MF.getFrameInfo();
3930     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3931 
3932     // Create load node to retrieve arguments from the stack.
3933     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3934     ArgValue2 = DAG.getLoad(
3935         MVT::i32, dl, Root, FIN,
3936         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3937   } else {
3938     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3939     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3940   }
3941   if (!Subtarget->isLittle())
3942     std::swap (ArgValue, ArgValue2);
3943   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3944 }
3945 
3946 // The remaining GPRs hold either the beginning of variable-argument
3947 // data, or the beginning of an aggregate passed by value (usually
3948 // byval).  Either way, we allocate stack slots adjacent to the data
3949 // provided by our caller, and store the unallocated registers there.
3950 // If this is a variadic function, the va_list pointer will begin with
3951 // these values; otherwise, this reassembles a (byval) structure that
3952 // was split between registers and memory.
3953 // Return: The frame index registers were stored into.
3954 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3955                                       const SDLoc &dl, SDValue &Chain,
3956                                       const Value *OrigArg,
3957                                       unsigned InRegsParamRecordIdx,
3958                                       int ArgOffset, unsigned ArgSize) const {
3959   // Currently, two use-cases possible:
3960   // Case #1. Non-var-args function, and we meet first byval parameter.
3961   //          Setup first unallocated register as first byval register;
3962   //          eat all remained registers
3963   //          (these two actions are performed by HandleByVal method).
3964   //          Then, here, we initialize stack frame with
3965   //          "store-reg" instructions.
3966   // Case #2. Var-args function, that doesn't contain byval parameters.
3967   //          The same: eat all remained unallocated registers,
3968   //          initialize stack frame.
3969 
3970   MachineFunction &MF = DAG.getMachineFunction();
3971   MachineFrameInfo &MFI = MF.getFrameInfo();
3972   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3973   unsigned RBegin, REnd;
3974   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3975     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3976   } else {
3977     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3978     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3979     REnd = ARM::R4;
3980   }
3981 
3982   if (REnd != RBegin)
3983     ArgOffset = -4 * (ARM::R4 - RBegin);
3984 
3985   auto PtrVT = getPointerTy(DAG.getDataLayout());
3986   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3987   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3988 
3989   SmallVector<SDValue, 4> MemOps;
3990   const TargetRegisterClass *RC =
3991       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3992 
3993   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3994     unsigned VReg = MF.addLiveIn(Reg, RC);
3995     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3996     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3997                                  MachinePointerInfo(OrigArg, 4 * i));
3998     MemOps.push_back(Store);
3999     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4000   }
4001 
4002   if (!MemOps.empty())
4003     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4004   return FrameIndex;
4005 }
4006 
4007 // Setup stack frame, the va_list pointer will start from.
4008 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4009                                              const SDLoc &dl, SDValue &Chain,
4010                                              unsigned ArgOffset,
4011                                              unsigned TotalArgRegsSaveSize,
4012                                              bool ForceMutable) const {
4013   MachineFunction &MF = DAG.getMachineFunction();
4014   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4015 
4016   // Try to store any remaining integer argument regs
4017   // to their spots on the stack so that they may be loaded by dereferencing
4018   // the result of va_next.
4019   // If there is no regs to be stored, just point address after last
4020   // argument passed via stack.
4021   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
4022                                   CCInfo.getInRegsParamsCount(),
4023                                   CCInfo.getNextStackOffset(),
4024                                   std::max(4U, TotalArgRegsSaveSize));
4025   AFI->setVarArgsFrameIndex(FrameIndex);
4026 }
4027 
4028 SDValue ARMTargetLowering::LowerFormalArguments(
4029     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4030     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4031     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4032   MachineFunction &MF = DAG.getMachineFunction();
4033   MachineFrameInfo &MFI = MF.getFrameInfo();
4034 
4035   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4036 
4037   // Assign locations to all of the incoming arguments.
4038   SmallVector<CCValAssign, 16> ArgLocs;
4039   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4040                  *DAG.getContext());
4041   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4042 
4043   SmallVector<SDValue, 16> ArgValues;
4044   SDValue ArgValue;
4045   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4046   unsigned CurArgIdx = 0;
4047 
4048   // Initially ArgRegsSaveSize is zero.
4049   // Then we increase this value each time we meet byval parameter.
4050   // We also increase this value in case of varargs function.
4051   AFI->setArgRegsSaveSize(0);
4052 
4053   // Calculate the amount of stack space that we need to allocate to store
4054   // byval and variadic arguments that are passed in registers.
4055   // We need to know this before we allocate the first byval or variadic
4056   // argument, as they will be allocated a stack slot below the CFA (Canonical
4057   // Frame Address, the stack pointer at entry to the function).
4058   unsigned ArgRegBegin = ARM::R4;
4059   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4060     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4061       break;
4062 
4063     CCValAssign &VA = ArgLocs[i];
4064     unsigned Index = VA.getValNo();
4065     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4066     if (!Flags.isByVal())
4067       continue;
4068 
4069     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4070     unsigned RBegin, REnd;
4071     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4072     ArgRegBegin = std::min(ArgRegBegin, RBegin);
4073 
4074     CCInfo.nextInRegsParam();
4075   }
4076   CCInfo.rewindByValRegsInfo();
4077 
4078   int lastInsIndex = -1;
4079   if (isVarArg && MFI.hasVAStart()) {
4080     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4081     if (RegIdx != array_lengthof(GPRArgRegs))
4082       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4083   }
4084 
4085   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4086   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4087   auto PtrVT = getPointerTy(DAG.getDataLayout());
4088 
4089   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4090     CCValAssign &VA = ArgLocs[i];
4091     if (Ins[VA.getValNo()].isOrigArg()) {
4092       std::advance(CurOrigArg,
4093                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4094       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4095     }
4096     // Arguments stored in registers.
4097     if (VA.isRegLoc()) {
4098       EVT RegVT = VA.getLocVT();
4099 
4100       if (VA.needsCustom()) {
4101         // f64 and vector types are split up into multiple registers or
4102         // combinations of registers and stack slots.
4103         if (VA.getLocVT() == MVT::v2f64) {
4104           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
4105                                                    Chain, DAG, dl);
4106           VA = ArgLocs[++i]; // skip ahead to next loc
4107           SDValue ArgValue2;
4108           if (VA.isMemLoc()) {
4109             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4110             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4111             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
4112                                     MachinePointerInfo::getFixedStack(
4113                                         DAG.getMachineFunction(), FI));
4114           } else {
4115             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
4116                                              Chain, DAG, dl);
4117           }
4118           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4119           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
4120                                  ArgValue, ArgValue1,
4121                                  DAG.getIntPtrConstant(0, dl));
4122           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
4123                                  ArgValue, ArgValue2,
4124                                  DAG.getIntPtrConstant(1, dl));
4125         } else
4126           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4127       } else {
4128         const TargetRegisterClass *RC;
4129 
4130 
4131         if (RegVT == MVT::f16)
4132           RC = &ARM::HPRRegClass;
4133         else if (RegVT == MVT::f32)
4134           RC = &ARM::SPRRegClass;
4135         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
4136           RC = &ARM::DPRRegClass;
4137         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
4138           RC = &ARM::QPRRegClass;
4139         else if (RegVT == MVT::i32)
4140           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4141                                            : &ARM::GPRRegClass;
4142         else
4143           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4144 
4145         // Transform the arguments in physical registers into virtual ones.
4146         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4147         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4148 
4149         // If this value is passed in r0 and has the returned attribute (e.g.
4150         // C++ 'structors), record this fact for later use.
4151         if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4152           AFI->setPreservesR0();
4153         }
4154       }
4155 
4156       // If this is an 8 or 16-bit value, it is really passed promoted
4157       // to 32 bits.  Insert an assert[sz]ext to capture this, then
4158       // truncate to the right size.
4159       switch (VA.getLocInfo()) {
4160       default: llvm_unreachable("Unknown loc info!");
4161       case CCValAssign::Full: break;
4162       case CCValAssign::BCvt:
4163         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4164         break;
4165       case CCValAssign::SExt:
4166         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4167                                DAG.getValueType(VA.getValVT()));
4168         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4169         break;
4170       case CCValAssign::ZExt:
4171         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4172                                DAG.getValueType(VA.getValVT()));
4173         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4174         break;
4175       }
4176 
4177       InVals.push_back(ArgValue);
4178     } else { // VA.isRegLoc()
4179       // sanity check
4180       assert(VA.isMemLoc());
4181       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4182 
4183       int index = VA.getValNo();
4184 
4185       // Some Ins[] entries become multiple ArgLoc[] entries.
4186       // Process them only once.
4187       if (index != lastInsIndex)
4188         {
4189           ISD::ArgFlagsTy Flags = Ins[index].Flags;
4190           // FIXME: For now, all byval parameter objects are marked mutable.
4191           // This can be changed with more analysis.
4192           // In case of tail call optimization mark all arguments mutable.
4193           // Since they could be overwritten by lowering of arguments in case of
4194           // a tail call.
4195           if (Flags.isByVal()) {
4196             assert(Ins[index].isOrigArg() &&
4197                    "Byval arguments cannot be implicit");
4198             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4199 
4200             int FrameIndex = StoreByValRegs(
4201                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4202                 VA.getLocMemOffset(), Flags.getByValSize());
4203             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4204             CCInfo.nextInRegsParam();
4205           } else {
4206             unsigned FIOffset = VA.getLocMemOffset();
4207             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4208                                            FIOffset, true);
4209 
4210             // Create load nodes to retrieve arguments from the stack.
4211             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4212             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4213                                          MachinePointerInfo::getFixedStack(
4214                                              DAG.getMachineFunction(), FI)));
4215           }
4216           lastInsIndex = index;
4217         }
4218     }
4219   }
4220 
4221   // varargs
4222   if (isVarArg && MFI.hasVAStart())
4223     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4224                          CCInfo.getNextStackOffset(),
4225                          TotalArgRegsSaveSize);
4226 
4227   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4228 
4229   return Chain;
4230 }
4231 
4232 /// isFloatingPointZero - Return true if this is +0.0.
4233 static bool isFloatingPointZero(SDValue Op) {
4234   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4235     return CFP->getValueAPF().isPosZero();
4236   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4237     // Maybe this has already been legalized into the constant pool?
4238     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4239       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4240       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4241         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4242           return CFP->getValueAPF().isPosZero();
4243     }
4244   } else if (Op->getOpcode() == ISD::BITCAST &&
4245              Op->getValueType(0) == MVT::f64) {
4246     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4247     // created by LowerConstantFP().
4248     SDValue BitcastOp = Op->getOperand(0);
4249     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4250         isNullConstant(BitcastOp->getOperand(0)))
4251       return true;
4252   }
4253   return false;
4254 }
4255 
4256 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4257 /// the given operands.
4258 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4259                                      SDValue &ARMcc, SelectionDAG &DAG,
4260                                      const SDLoc &dl) const {
4261   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4262     unsigned C = RHSC->getZExtValue();
4263     if (!isLegalICmpImmediate((int32_t)C)) {
4264       // Constant does not fit, try adjusting it by one.
4265       switch (CC) {
4266       default: break;
4267       case ISD::SETLT:
4268       case ISD::SETGE:
4269         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4270           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4271           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4272         }
4273         break;
4274       case ISD::SETULT:
4275       case ISD::SETUGE:
4276         if (C != 0 && isLegalICmpImmediate(C-1)) {
4277           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4278           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4279         }
4280         break;
4281       case ISD::SETLE:
4282       case ISD::SETGT:
4283         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4284           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4285           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4286         }
4287         break;
4288       case ISD::SETULE:
4289       case ISD::SETUGT:
4290         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4291           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4292           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4293         }
4294         break;
4295       }
4296     }
4297   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4298              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4299     // In ARM and Thumb-2, the compare instructions can shift their second
4300     // operand.
4301     CC = ISD::getSetCCSwappedOperands(CC);
4302     std::swap(LHS, RHS);
4303   }
4304 
4305   // Thumb1 has very limited immediate modes, so turning an "and" into a
4306   // shift can save multiple instructions.
4307   //
4308   // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4309   // into "((x << n) >> n)".  But that isn't necessarily profitable on its
4310   // own. If it's the operand to an unsigned comparison with an immediate,
4311   // we can eliminate one of the shifts: we transform
4312   // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4313   //
4314   // We avoid transforming cases which aren't profitable due to encoding
4315   // details:
4316   //
4317   // 1. C2 fits into the immediate field of a cmp, and the transformed version
4318   // would not; in that case, we're essentially trading one immediate load for
4319   // another.
4320   // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4321   // 3. C2 is zero; we have other code for this special case.
4322   //
4323   // FIXME: Figure out profitability for Thumb2; we usually can't save an
4324   // instruction, since the AND is always one instruction anyway, but we could
4325   // use narrow instructions in some cases.
4326   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4327       LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4328       LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4329       !isSignedIntSetCC(CC)) {
4330     unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4331     auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4332     uint64_t RHSV = RHSC->getZExtValue();
4333     if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4334       unsigned ShiftBits = countLeadingZeros(Mask);
4335       if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4336         SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4337         LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4338         RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4339       }
4340     }
4341   }
4342 
4343   // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4344   // single "lsls x, c+1".  The shift sets the "C" and "Z" flags the same
4345   // way a cmp would.
4346   // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4347   // some tweaks to the heuristics for the previous and->shift transform.
4348   // FIXME: Optimize cases where the LHS isn't a shift.
4349   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4350       isa<ConstantSDNode>(RHS) &&
4351       cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4352       CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4353       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4354     unsigned ShiftAmt =
4355       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4356     SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4357                                 DAG.getVTList(MVT::i32, MVT::i32),
4358                                 LHS.getOperand(0),
4359                                 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4360     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4361                                      Shift.getValue(1), SDValue());
4362     ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4363     return Chain.getValue(1);
4364   }
4365 
4366   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4367 
4368   // If the RHS is a constant zero then the V (overflow) flag will never be
4369   // set. This can allow us to simplify GE to PL or LT to MI, which can be
4370   // simpler for other passes (like the peephole optimiser) to deal with.
4371   if (isNullConstant(RHS)) {
4372     switch (CondCode) {
4373       default: break;
4374       case ARMCC::GE:
4375         CondCode = ARMCC::PL;
4376         break;
4377       case ARMCC::LT:
4378         CondCode = ARMCC::MI;
4379         break;
4380     }
4381   }
4382 
4383   ARMISD::NodeType CompareType;
4384   switch (CondCode) {
4385   default:
4386     CompareType = ARMISD::CMP;
4387     break;
4388   case ARMCC::EQ:
4389   case ARMCC::NE:
4390     // Uses only Z Flag
4391     CompareType = ARMISD::CMPZ;
4392     break;
4393   }
4394   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4395   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4396 }
4397 
4398 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4399 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4400                                      SelectionDAG &DAG, const SDLoc &dl,
4401                                      bool Signaling) const {
4402   assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4403   SDValue Cmp;
4404   if (!isFloatingPointZero(RHS))
4405     Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP,
4406                       dl, MVT::Glue, LHS, RHS);
4407   else
4408     Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0,
4409                       dl, MVT::Glue, LHS);
4410   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4411 }
4412 
4413 /// duplicateCmp - Glue values can have only one use, so this function
4414 /// duplicates a comparison node.
4415 SDValue
4416 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4417   unsigned Opc = Cmp.getOpcode();
4418   SDLoc DL(Cmp);
4419   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4420     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4421 
4422   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4423   Cmp = Cmp.getOperand(0);
4424   Opc = Cmp.getOpcode();
4425   if (Opc == ARMISD::CMPFP)
4426     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4427   else {
4428     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4429     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4430   }
4431   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4432 }
4433 
4434 // This function returns three things: the arithmetic computation itself
4435 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
4436 // comparison and the condition code define the case in which the arithmetic
4437 // computation *does not* overflow.
4438 std::pair<SDValue, SDValue>
4439 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4440                                  SDValue &ARMcc) const {
4441   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
4442 
4443   SDValue Value, OverflowCmp;
4444   SDValue LHS = Op.getOperand(0);
4445   SDValue RHS = Op.getOperand(1);
4446   SDLoc dl(Op);
4447 
4448   // FIXME: We are currently always generating CMPs because we don't support
4449   // generating CMN through the backend. This is not as good as the natural
4450   // CMP case because it causes a register dependency and cannot be folded
4451   // later.
4452 
4453   switch (Op.getOpcode()) {
4454   default:
4455     llvm_unreachable("Unknown overflow instruction!");
4456   case ISD::SADDO:
4457     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4458     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4459     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4460     break;
4461   case ISD::UADDO:
4462     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4463     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4464     // We do not use it in the USUBO case as Value may not be used.
4465     Value = DAG.getNode(ARMISD::ADDC, dl,
4466                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4467                 .getValue(0);
4468     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4469     break;
4470   case ISD::SSUBO:
4471     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4472     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4473     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4474     break;
4475   case ISD::USUBO:
4476     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4477     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4478     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4479     break;
4480   case ISD::UMULO:
4481     // We generate a UMUL_LOHI and then check if the high word is 0.
4482     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4483     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4484                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4485                         LHS, RHS);
4486     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4487                               DAG.getConstant(0, dl, MVT::i32));
4488     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4489     break;
4490   case ISD::SMULO:
4491     // We generate a SMUL_LOHI and then check if all the bits of the high word
4492     // are the same as the sign bit of the low word.
4493     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4494     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4495                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4496                         LHS, RHS);
4497     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4498                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4499                                           Value.getValue(0),
4500                                           DAG.getConstant(31, dl, MVT::i32)));
4501     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4502     break;
4503   } // switch (...)
4504 
4505   return std::make_pair(Value, OverflowCmp);
4506 }
4507 
4508 SDValue
4509 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4510   // Let legalize expand this if it isn't a legal type yet.
4511   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4512     return SDValue();
4513 
4514   SDValue Value, OverflowCmp;
4515   SDValue ARMcc;
4516   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4517   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4518   SDLoc dl(Op);
4519   // We use 0 and 1 as false and true values.
4520   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4521   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4522   EVT VT = Op.getValueType();
4523 
4524   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4525                                  ARMcc, CCR, OverflowCmp);
4526 
4527   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4528   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4529 }
4530 
4531 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4532                                               SelectionDAG &DAG) {
4533   SDLoc DL(BoolCarry);
4534   EVT CarryVT = BoolCarry.getValueType();
4535 
4536   // This converts the boolean value carry into the carry flag by doing
4537   // ARMISD::SUBC Carry, 1
4538   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4539                               DAG.getVTList(CarryVT, MVT::i32),
4540                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
4541   return Carry.getValue(1);
4542 }
4543 
4544 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4545                                               SelectionDAG &DAG) {
4546   SDLoc DL(Flags);
4547 
4548   // Now convert the carry flag into a boolean carry. We do this
4549   // using ARMISD:ADDE 0, 0, Carry
4550   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4551                      DAG.getConstant(0, DL, MVT::i32),
4552                      DAG.getConstant(0, DL, MVT::i32), Flags);
4553 }
4554 
4555 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4556                                              SelectionDAG &DAG) const {
4557   // Let legalize expand this if it isn't a legal type yet.
4558   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4559     return SDValue();
4560 
4561   SDValue LHS = Op.getOperand(0);
4562   SDValue RHS = Op.getOperand(1);
4563   SDLoc dl(Op);
4564 
4565   EVT VT = Op.getValueType();
4566   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4567   SDValue Value;
4568   SDValue Overflow;
4569   switch (Op.getOpcode()) {
4570   default:
4571     llvm_unreachable("Unknown overflow instruction!");
4572   case ISD::UADDO:
4573     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4574     // Convert the carry flag into a boolean value.
4575     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4576     break;
4577   case ISD::USUBO: {
4578     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4579     // Convert the carry flag into a boolean value.
4580     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4581     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4582     // value. So compute 1 - C.
4583     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4584                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4585     break;
4586   }
4587   }
4588 
4589   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4590 }
4591 
4592 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4593                                const ARMSubtarget *Subtarget) {
4594   EVT VT = Op.getValueType();
4595   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
4596     return SDValue();
4597   if (!VT.isSimple())
4598     return SDValue();
4599 
4600   unsigned NewOpcode;
4601   bool IsAdd = Op->getOpcode() == ISD::SADDSAT;
4602   switch (VT.getSimpleVT().SimpleTy) {
4603   default:
4604     return SDValue();
4605   case MVT::i8:
4606     NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b;
4607     break;
4608   case MVT::i16:
4609     NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b;
4610     break;
4611   }
4612 
4613   SDLoc dl(Op);
4614   SDValue Add =
4615       DAG.getNode(NewOpcode, dl, MVT::i32,
4616                   DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
4617                   DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
4618   return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
4619 }
4620 
4621 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4622   SDValue Cond = Op.getOperand(0);
4623   SDValue SelectTrue = Op.getOperand(1);
4624   SDValue SelectFalse = Op.getOperand(2);
4625   SDLoc dl(Op);
4626   unsigned Opc = Cond.getOpcode();
4627 
4628   if (Cond.getResNo() == 1 &&
4629       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4630        Opc == ISD::USUBO)) {
4631     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4632       return SDValue();
4633 
4634     SDValue Value, OverflowCmp;
4635     SDValue ARMcc;
4636     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4637     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4638     EVT VT = Op.getValueType();
4639 
4640     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4641                    OverflowCmp, DAG);
4642   }
4643 
4644   // Convert:
4645   //
4646   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4647   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4648   //
4649   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4650     const ConstantSDNode *CMOVTrue =
4651       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4652     const ConstantSDNode *CMOVFalse =
4653       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4654 
4655     if (CMOVTrue && CMOVFalse) {
4656       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4657       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4658 
4659       SDValue True;
4660       SDValue False;
4661       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4662         True = SelectTrue;
4663         False = SelectFalse;
4664       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4665         True = SelectFalse;
4666         False = SelectTrue;
4667       }
4668 
4669       if (True.getNode() && False.getNode()) {
4670         EVT VT = Op.getValueType();
4671         SDValue ARMcc = Cond.getOperand(2);
4672         SDValue CCR = Cond.getOperand(3);
4673         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4674         assert(True.getValueType() == VT);
4675         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4676       }
4677     }
4678   }
4679 
4680   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4681   // undefined bits before doing a full-word comparison with zero.
4682   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4683                      DAG.getConstant(1, dl, Cond.getValueType()));
4684 
4685   return DAG.getSelectCC(dl, Cond,
4686                          DAG.getConstant(0, dl, Cond.getValueType()),
4687                          SelectTrue, SelectFalse, ISD::SETNE);
4688 }
4689 
4690 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4691                                  bool &swpCmpOps, bool &swpVselOps) {
4692   // Start by selecting the GE condition code for opcodes that return true for
4693   // 'equality'
4694   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4695       CC == ISD::SETULE || CC == ISD::SETGE  || CC == ISD::SETLE)
4696     CondCode = ARMCC::GE;
4697 
4698   // and GT for opcodes that return false for 'equality'.
4699   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4700            CC == ISD::SETULT || CC == ISD::SETGT  || CC == ISD::SETLT)
4701     CondCode = ARMCC::GT;
4702 
4703   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4704   // to swap the compare operands.
4705   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4706       CC == ISD::SETULT || CC == ISD::SETLE  || CC == ISD::SETLT)
4707     swpCmpOps = true;
4708 
4709   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4710   // If we have an unordered opcode, we need to swap the operands to the VSEL
4711   // instruction (effectively negating the condition).
4712   //
4713   // This also has the effect of swapping which one of 'less' or 'greater'
4714   // returns true, so we also swap the compare operands. It also switches
4715   // whether we return true for 'equality', so we compensate by picking the
4716   // opposite condition code to our original choice.
4717   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4718       CC == ISD::SETUGT) {
4719     swpCmpOps = !swpCmpOps;
4720     swpVselOps = !swpVselOps;
4721     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4722   }
4723 
4724   // 'ordered' is 'anything but unordered', so use the VS condition code and
4725   // swap the VSEL operands.
4726   if (CC == ISD::SETO) {
4727     CondCode = ARMCC::VS;
4728     swpVselOps = true;
4729   }
4730 
4731   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4732   // code and swap the VSEL operands. Also do this if we don't care about the
4733   // unordered case.
4734   if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4735     CondCode = ARMCC::EQ;
4736     swpVselOps = true;
4737   }
4738 }
4739 
4740 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4741                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4742                                    SDValue Cmp, SelectionDAG &DAG) const {
4743   if (!Subtarget->hasFP64() && VT == MVT::f64) {
4744     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4745                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4746     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4747                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4748 
4749     SDValue TrueLow = TrueVal.getValue(0);
4750     SDValue TrueHigh = TrueVal.getValue(1);
4751     SDValue FalseLow = FalseVal.getValue(0);
4752     SDValue FalseHigh = FalseVal.getValue(1);
4753 
4754     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4755                               ARMcc, CCR, Cmp);
4756     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4757                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4758 
4759     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4760   } else {
4761     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4762                        Cmp);
4763   }
4764 }
4765 
4766 static bool isGTorGE(ISD::CondCode CC) {
4767   return CC == ISD::SETGT || CC == ISD::SETGE;
4768 }
4769 
4770 static bool isLTorLE(ISD::CondCode CC) {
4771   return CC == ISD::SETLT || CC == ISD::SETLE;
4772 }
4773 
4774 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4775 // All of these conditions (and their <= and >= counterparts) will do:
4776 //          x < k ? k : x
4777 //          x > k ? x : k
4778 //          k < x ? x : k
4779 //          k > x ? k : x
4780 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4781                             const SDValue TrueVal, const SDValue FalseVal,
4782                             const ISD::CondCode CC, const SDValue K) {
4783   return (isGTorGE(CC) &&
4784           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4785          (isLTorLE(CC) &&
4786           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4787 }
4788 
4789 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4790 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4791                             const SDValue TrueVal, const SDValue FalseVal,
4792                             const ISD::CondCode CC, const SDValue K) {
4793   return (isGTorGE(CC) &&
4794           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4795          (isLTorLE(CC) &&
4796           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4797 }
4798 
4799 // Check if two chained conditionals could be converted into SSAT or USAT.
4800 //
4801 // SSAT can replace a set of two conditional selectors that bound a number to an
4802 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4803 //
4804 //     x < -k ? -k : (x > k ? k : x)
4805 //     x < -k ? -k : (x < k ? x : k)
4806 //     x > -k ? (x > k ? k : x) : -k
4807 //     x < k ? (x < -k ? -k : x) : k
4808 //     etc.
4809 //
4810 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4811 // a power of 2.
4812 //
4813 // It returns true if the conversion can be done, false otherwise.
4814 // Additionally, the variable is returned in parameter V, the constant in K and
4815 // usat is set to true if the conditional represents an unsigned saturation
4816 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4817                                     uint64_t &K, bool &usat) {
4818   SDValue LHS1 = Op.getOperand(0);
4819   SDValue RHS1 = Op.getOperand(1);
4820   SDValue TrueVal1 = Op.getOperand(2);
4821   SDValue FalseVal1 = Op.getOperand(3);
4822   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4823 
4824   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4825   if (Op2.getOpcode() != ISD::SELECT_CC)
4826     return false;
4827 
4828   SDValue LHS2 = Op2.getOperand(0);
4829   SDValue RHS2 = Op2.getOperand(1);
4830   SDValue TrueVal2 = Op2.getOperand(2);
4831   SDValue FalseVal2 = Op2.getOperand(3);
4832   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4833 
4834   // Find out which are the constants and which are the variables
4835   // in each conditional
4836   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4837                                                         ? &RHS1
4838                                                         : nullptr;
4839   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4840                                                         ? &RHS2
4841                                                         : nullptr;
4842   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4843   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4844   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4845   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4846 
4847   // We must detect cases where the original operations worked with 16- or
4848   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4849   // must work with sign-extended values but the select operations return
4850   // the original non-extended value.
4851   SDValue V2TmpReg = V2Tmp;
4852   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4853     V2TmpReg = V2Tmp->getOperand(0);
4854 
4855   // Check that the registers and the constants have the correct values
4856   // in both conditionals
4857   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4858       V2TmpReg != V2)
4859     return false;
4860 
4861   // Figure out which conditional is saturating the lower/upper bound.
4862   const SDValue *LowerCheckOp =
4863       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4864           ? &Op
4865           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4866                 ? &Op2
4867                 : nullptr;
4868   const SDValue *UpperCheckOp =
4869       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4870           ? &Op
4871           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4872                 ? &Op2
4873                 : nullptr;
4874 
4875   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4876     return false;
4877 
4878   // Check that the constant in the lower-bound check is
4879   // the opposite of the constant in the upper-bound check
4880   // in 1's complement.
4881   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4882   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4883   int64_t PosVal = std::max(Val1, Val2);
4884   int64_t NegVal = std::min(Val1, Val2);
4885 
4886   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4887        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4888       isPowerOf2_64(PosVal + 1)) {
4889 
4890     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4891     if (Val1 == ~Val2)
4892       usat = false;
4893     else if (NegVal == 0)
4894       usat = true;
4895     else
4896       return false;
4897 
4898     V = V2;
4899     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4900 
4901     return true;
4902   }
4903 
4904   return false;
4905 }
4906 
4907 // Check if a condition of the type x < k ? k : x can be converted into a
4908 // bit operation instead of conditional moves.
4909 // Currently this is allowed given:
4910 // - The conditions and values match up
4911 // - k is 0 or -1 (all ones)
4912 // This function will not check the last condition, thats up to the caller
4913 // It returns true if the transformation can be made, and in such case
4914 // returns x in V, and k in SatK.
4915 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4916                                          SDValue &SatK)
4917 {
4918   SDValue LHS = Op.getOperand(0);
4919   SDValue RHS = Op.getOperand(1);
4920   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4921   SDValue TrueVal = Op.getOperand(2);
4922   SDValue FalseVal = Op.getOperand(3);
4923 
4924   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4925                                                ? &RHS
4926                                                : nullptr;
4927 
4928   // No constant operation in comparison, early out
4929   if (!K)
4930     return false;
4931 
4932   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4933   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4934   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4935 
4936   // If the constant on left and right side, or variable on left and right,
4937   // does not match, early out
4938   if (*K != KTmp || V != VTmp)
4939     return false;
4940 
4941   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4942     SatK = *K;
4943     return true;
4944   }
4945 
4946   return false;
4947 }
4948 
4949 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4950   if (VT == MVT::f32)
4951     return !Subtarget->hasVFP2Base();
4952   if (VT == MVT::f64)
4953     return !Subtarget->hasFP64();
4954   if (VT == MVT::f16)
4955     return !Subtarget->hasFullFP16();
4956   return false;
4957 }
4958 
4959 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4960   EVT VT = Op.getValueType();
4961   SDLoc dl(Op);
4962 
4963   // Try to convert two saturating conditional selects into a single SSAT
4964   SDValue SatValue;
4965   uint64_t SatConstant;
4966   bool SatUSat;
4967   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4968       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4969     if (SatUSat)
4970       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4971                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4972     else
4973       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4974                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4975   }
4976 
4977   // Try to convert expressions of the form x < k ? k : x (and similar forms)
4978   // into more efficient bit operations, which is possible when k is 0 or -1
4979   // On ARM and Thumb-2 which have flexible operand 2 this will result in
4980   // single instructions. On Thumb the shift and the bit operation will be two
4981   // instructions.
4982   // Only allow this transformation on full-width (32-bit) operations
4983   SDValue LowerSatConstant;
4984   if (VT == MVT::i32 &&
4985       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4986     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4987                                  DAG.getConstant(31, dl, VT));
4988     if (isNullConstant(LowerSatConstant)) {
4989       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4990                                       DAG.getAllOnesConstant(dl, VT));
4991       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4992     } else if (isAllOnesConstant(LowerSatConstant))
4993       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4994   }
4995 
4996   SDValue LHS = Op.getOperand(0);
4997   SDValue RHS = Op.getOperand(1);
4998   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4999   SDValue TrueVal = Op.getOperand(2);
5000   SDValue FalseVal = Op.getOperand(3);
5001   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5002   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5003 
5004   if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
5005       LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
5006     unsigned TVal = CTVal->getZExtValue();
5007     unsigned FVal = CFVal->getZExtValue();
5008     unsigned Opcode = 0;
5009 
5010     if (TVal == ~FVal) {
5011       Opcode = ARMISD::CSINV;
5012     } else if (TVal == ~FVal + 1) {
5013       Opcode = ARMISD::CSNEG;
5014     } else if (TVal + 1 == FVal) {
5015       Opcode = ARMISD::CSINC;
5016     } else if (TVal == FVal + 1) {
5017       Opcode = ARMISD::CSINC;
5018       std::swap(TrueVal, FalseVal);
5019       std::swap(TVal, FVal);
5020       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5021     }
5022 
5023     if (Opcode) {
5024       // If one of the constants is cheaper than another, materialise the
5025       // cheaper one and let the csel generate the other.
5026       if (Opcode != ARMISD::CSINC &&
5027           HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5028         std::swap(TrueVal, FalseVal);
5029         std::swap(TVal, FVal);
5030         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5031       }
5032 
5033       // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5034       // to get there. CSINC not is invertable like the other two (~(~a) == a,
5035       // -(-a) == a, but (a+1)+1 != a).
5036       if (FVal == 0 && Opcode != ARMISD::CSINC) {
5037         std::swap(TrueVal, FalseVal);
5038         std::swap(TVal, FVal);
5039         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5040       }
5041       if (TVal == 0)
5042         TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
5043 
5044       // Drops F's value because we can get it by inverting/negating TVal.
5045       FalseVal = TrueVal;
5046 
5047       SDValue ARMcc;
5048       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5049       EVT VT = TrueVal.getValueType();
5050       return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
5051     }
5052   }
5053 
5054   if (isUnsupportedFloatingType(LHS.getValueType())) {
5055     DAG.getTargetLoweringInfo().softenSetCCOperands(
5056         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5057 
5058     // If softenSetCCOperands only returned one value, we should compare it to
5059     // zero.
5060     if (!RHS.getNode()) {
5061       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5062       CC = ISD::SETNE;
5063     }
5064   }
5065 
5066   if (LHS.getValueType() == MVT::i32) {
5067     // Try to generate VSEL on ARMv8.
5068     // The VSEL instruction can't use all the usual ARM condition
5069     // codes: it only has two bits to select the condition code, so it's
5070     // constrained to use only GE, GT, VS and EQ.
5071     //
5072     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5073     // swap the operands of the previous compare instruction (effectively
5074     // inverting the compare condition, swapping 'less' and 'greater') and
5075     // sometimes need to swap the operands to the VSEL (which inverts the
5076     // condition in the sense of firing whenever the previous condition didn't)
5077     if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5078                                         TrueVal.getValueType() == MVT::f32 ||
5079                                         TrueVal.getValueType() == MVT::f64)) {
5080       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5081       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5082           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5083         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5084         std::swap(TrueVal, FalseVal);
5085       }
5086     }
5087 
5088     SDValue ARMcc;
5089     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5090     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5091     // Choose GE over PL, which vsel does now support
5092     if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
5093       ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5094     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5095   }
5096 
5097   ARMCC::CondCodes CondCode, CondCode2;
5098   FPCCToARMCC(CC, CondCode, CondCode2);
5099 
5100   // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5101   // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5102   // must use VSEL (limited condition codes), due to not having conditional f16
5103   // moves.
5104   if (Subtarget->hasFPARMv8Base() &&
5105       !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5106       (TrueVal.getValueType() == MVT::f16 ||
5107        TrueVal.getValueType() == MVT::f32 ||
5108        TrueVal.getValueType() == MVT::f64)) {
5109     bool swpCmpOps = false;
5110     bool swpVselOps = false;
5111     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5112 
5113     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5114         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5115       if (swpCmpOps)
5116         std::swap(LHS, RHS);
5117       if (swpVselOps)
5118         std::swap(TrueVal, FalseVal);
5119     }
5120   }
5121 
5122   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5123   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5124   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5125   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5126   if (CondCode2 != ARMCC::AL) {
5127     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5128     // FIXME: Needs another CMP because flag can have but one use.
5129     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5130     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5131   }
5132   return Result;
5133 }
5134 
5135 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
5136 /// to morph to an integer compare sequence.
5137 static bool canChangeToInt(SDValue Op, bool &SeenZero,
5138                            const ARMSubtarget *Subtarget) {
5139   SDNode *N = Op.getNode();
5140   if (!N->hasOneUse())
5141     // Otherwise it requires moving the value from fp to integer registers.
5142     return false;
5143   if (!N->getNumValues())
5144     return false;
5145   EVT VT = Op.getValueType();
5146   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5147     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5148     // vmrs are very slow, e.g. cortex-a8.
5149     return false;
5150 
5151   if (isFloatingPointZero(Op)) {
5152     SeenZero = true;
5153     return true;
5154   }
5155   return ISD::isNormalLoad(N);
5156 }
5157 
5158 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5159   if (isFloatingPointZero(Op))
5160     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5161 
5162   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5163     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5164                        Ld->getPointerInfo(), Ld->getAlignment(),
5165                        Ld->getMemOperand()->getFlags());
5166 
5167   llvm_unreachable("Unknown VFP cmp argument!");
5168 }
5169 
5170 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5171                            SDValue &RetVal1, SDValue &RetVal2) {
5172   SDLoc dl(Op);
5173 
5174   if (isFloatingPointZero(Op)) {
5175     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5176     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5177     return;
5178   }
5179 
5180   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5181     SDValue Ptr = Ld->getBasePtr();
5182     RetVal1 =
5183         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5184                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5185 
5186     EVT PtrType = Ptr.getValueType();
5187     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5188     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5189                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5190     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5191                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
5192                           Ld->getMemOperand()->getFlags());
5193     return;
5194   }
5195 
5196   llvm_unreachable("Unknown VFP cmp argument!");
5197 }
5198 
5199 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5200 /// f32 and even f64 comparisons to integer ones.
5201 SDValue
5202 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5203   SDValue Chain = Op.getOperand(0);
5204   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5205   SDValue LHS = Op.getOperand(2);
5206   SDValue RHS = Op.getOperand(3);
5207   SDValue Dest = Op.getOperand(4);
5208   SDLoc dl(Op);
5209 
5210   bool LHSSeenZero = false;
5211   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5212   bool RHSSeenZero = false;
5213   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5214   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5215     // If unsafe fp math optimization is enabled and there are no other uses of
5216     // the CMP operands, and the condition code is EQ or NE, we can optimize it
5217     // to an integer comparison.
5218     if (CC == ISD::SETOEQ)
5219       CC = ISD::SETEQ;
5220     else if (CC == ISD::SETUNE)
5221       CC = ISD::SETNE;
5222 
5223     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5224     SDValue ARMcc;
5225     if (LHS.getValueType() == MVT::f32) {
5226       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5227                         bitcastf32Toi32(LHS, DAG), Mask);
5228       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5229                         bitcastf32Toi32(RHS, DAG), Mask);
5230       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5231       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5232       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5233                          Chain, Dest, ARMcc, CCR, Cmp);
5234     }
5235 
5236     SDValue LHS1, LHS2;
5237     SDValue RHS1, RHS2;
5238     expandf64Toi32(LHS, DAG, LHS1, LHS2);
5239     expandf64Toi32(RHS, DAG, RHS1, RHS2);
5240     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5241     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5242     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5243     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5244     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5245     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5246     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5247   }
5248 
5249   return SDValue();
5250 }
5251 
5252 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5253   SDValue Chain = Op.getOperand(0);
5254   SDValue Cond = Op.getOperand(1);
5255   SDValue Dest = Op.getOperand(2);
5256   SDLoc dl(Op);
5257 
5258   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5259   // instruction.
5260   unsigned Opc = Cond.getOpcode();
5261   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5262                       !Subtarget->isThumb1Only();
5263   if (Cond.getResNo() == 1 &&
5264       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5265        Opc == ISD::USUBO || OptimizeMul)) {
5266     // Only lower legal XALUO ops.
5267     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5268       return SDValue();
5269 
5270     // The actual operation with overflow check.
5271     SDValue Value, OverflowCmp;
5272     SDValue ARMcc;
5273     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5274 
5275     // Reverse the condition code.
5276     ARMCC::CondCodes CondCode =
5277         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5278     CondCode = ARMCC::getOppositeCondition(CondCode);
5279     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5280     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5281 
5282     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5283                        OverflowCmp);
5284   }
5285 
5286   return SDValue();
5287 }
5288 
5289 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5290   SDValue Chain = Op.getOperand(0);
5291   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5292   SDValue LHS = Op.getOperand(2);
5293   SDValue RHS = Op.getOperand(3);
5294   SDValue Dest = Op.getOperand(4);
5295   SDLoc dl(Op);
5296 
5297   if (isUnsupportedFloatingType(LHS.getValueType())) {
5298     DAG.getTargetLoweringInfo().softenSetCCOperands(
5299         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5300 
5301     // If softenSetCCOperands only returned one value, we should compare it to
5302     // zero.
5303     if (!RHS.getNode()) {
5304       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5305       CC = ISD::SETNE;
5306     }
5307   }
5308 
5309   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5310   // instruction.
5311   unsigned Opc = LHS.getOpcode();
5312   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5313                       !Subtarget->isThumb1Only();
5314   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5315       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5316        Opc == ISD::USUBO || OptimizeMul) &&
5317       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5318     // Only lower legal XALUO ops.
5319     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5320       return SDValue();
5321 
5322     // The actual operation with overflow check.
5323     SDValue Value, OverflowCmp;
5324     SDValue ARMcc;
5325     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5326 
5327     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5328       // Reverse the condition code.
5329       ARMCC::CondCodes CondCode =
5330           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5331       CondCode = ARMCC::getOppositeCondition(CondCode);
5332       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5333     }
5334     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5335 
5336     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5337                        OverflowCmp);
5338   }
5339 
5340   if (LHS.getValueType() == MVT::i32) {
5341     SDValue ARMcc;
5342     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5343     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5344     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5345                        Chain, Dest, ARMcc, CCR, Cmp);
5346   }
5347 
5348   if (getTargetMachine().Options.UnsafeFPMath &&
5349       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5350        CC == ISD::SETNE || CC == ISD::SETUNE)) {
5351     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5352       return Result;
5353   }
5354 
5355   ARMCC::CondCodes CondCode, CondCode2;
5356   FPCCToARMCC(CC, CondCode, CondCode2);
5357 
5358   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5359   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5360   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5361   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5362   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5363   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5364   if (CondCode2 != ARMCC::AL) {
5365     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5366     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5367     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5368   }
5369   return Res;
5370 }
5371 
5372 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5373   SDValue Chain = Op.getOperand(0);
5374   SDValue Table = Op.getOperand(1);
5375   SDValue Index = Op.getOperand(2);
5376   SDLoc dl(Op);
5377 
5378   EVT PTy = getPointerTy(DAG.getDataLayout());
5379   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5380   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5381   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5382   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5383   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5384   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5385     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5386     // which does another jump to the destination. This also makes it easier
5387     // to translate it to TBB / TBH later (Thumb2 only).
5388     // FIXME: This might not work if the function is extremely large.
5389     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5390                        Addr, Op.getOperand(2), JTI);
5391   }
5392   if (isPositionIndependent() || Subtarget->isROPI()) {
5393     Addr =
5394         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5395                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5396     Chain = Addr.getValue(1);
5397     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5398     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5399   } else {
5400     Addr =
5401         DAG.getLoad(PTy, dl, Chain, Addr,
5402                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5403     Chain = Addr.getValue(1);
5404     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5405   }
5406 }
5407 
5408 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5409   EVT VT = Op.getValueType();
5410   SDLoc dl(Op);
5411 
5412   if (Op.getValueType().getVectorElementType() == MVT::i32) {
5413     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5414       return Op;
5415     return DAG.UnrollVectorOp(Op.getNode());
5416   }
5417 
5418   const bool HasFullFP16 =
5419     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5420 
5421   EVT NewTy;
5422   const EVT OpTy = Op.getOperand(0).getValueType();
5423   if (OpTy == MVT::v4f32)
5424     NewTy = MVT::v4i32;
5425   else if (OpTy == MVT::v4f16 && HasFullFP16)
5426     NewTy = MVT::v4i16;
5427   else if (OpTy == MVT::v8f16 && HasFullFP16)
5428     NewTy = MVT::v8i16;
5429   else
5430     llvm_unreachable("Invalid type for custom lowering!");
5431 
5432   if (VT != MVT::v4i16 && VT != MVT::v8i16)
5433     return DAG.UnrollVectorOp(Op.getNode());
5434 
5435   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5436   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5437 }
5438 
5439 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5440   EVT VT = Op.getValueType();
5441   if (VT.isVector())
5442     return LowerVectorFP_TO_INT(Op, DAG);
5443 
5444   bool IsStrict = Op->isStrictFPOpcode();
5445   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5446 
5447   if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5448     RTLIB::Libcall LC;
5449     if (Op.getOpcode() == ISD::FP_TO_SINT ||
5450         Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5451       LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5452                               Op.getValueType());
5453     else
5454       LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5455                               Op.getValueType());
5456     SDLoc Loc(Op);
5457     MakeLibCallOptions CallOptions;
5458     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5459     SDValue Result;
5460     std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5461                                           CallOptions, Loc, Chain);
5462     return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5463   }
5464 
5465   // FIXME: Remove this when we have strict fp instruction selection patterns
5466   if (IsStrict) {
5467     SDLoc Loc(Op);
5468     SDValue Result =
5469         DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5470                                                              : ISD::FP_TO_UINT,
5471                     Loc, Op.getValueType(), SrcVal);
5472     return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
5473   }
5474 
5475   return Op;
5476 }
5477 
5478 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5479   EVT VT = Op.getValueType();
5480   SDLoc dl(Op);
5481 
5482   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5483     if (VT.getVectorElementType() == MVT::f32)
5484       return Op;
5485     return DAG.UnrollVectorOp(Op.getNode());
5486   }
5487 
5488   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5489           Op.getOperand(0).getValueType() == MVT::v8i16) &&
5490          "Invalid type for custom lowering!");
5491 
5492   const bool HasFullFP16 =
5493     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5494 
5495   EVT DestVecType;
5496   if (VT == MVT::v4f32)
5497     DestVecType = MVT::v4i32;
5498   else if (VT == MVT::v4f16 && HasFullFP16)
5499     DestVecType = MVT::v4i16;
5500   else if (VT == MVT::v8f16 && HasFullFP16)
5501     DestVecType = MVT::v8i16;
5502   else
5503     return DAG.UnrollVectorOp(Op.getNode());
5504 
5505   unsigned CastOpc;
5506   unsigned Opc;
5507   switch (Op.getOpcode()) {
5508   default: llvm_unreachable("Invalid opcode!");
5509   case ISD::SINT_TO_FP:
5510     CastOpc = ISD::SIGN_EXTEND;
5511     Opc = ISD::SINT_TO_FP;
5512     break;
5513   case ISD::UINT_TO_FP:
5514     CastOpc = ISD::ZERO_EXTEND;
5515     Opc = ISD::UINT_TO_FP;
5516     break;
5517   }
5518 
5519   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5520   return DAG.getNode(Opc, dl, VT, Op);
5521 }
5522 
5523 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5524   EVT VT = Op.getValueType();
5525   if (VT.isVector())
5526     return LowerVectorINT_TO_FP(Op, DAG);
5527   if (isUnsupportedFloatingType(VT)) {
5528     RTLIB::Libcall LC;
5529     if (Op.getOpcode() == ISD::SINT_TO_FP)
5530       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5531                               Op.getValueType());
5532     else
5533       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5534                               Op.getValueType());
5535     MakeLibCallOptions CallOptions;
5536     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5537                        CallOptions, SDLoc(Op)).first;
5538   }
5539 
5540   return Op;
5541 }
5542 
5543 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5544   // Implement fcopysign with a fabs and a conditional fneg.
5545   SDValue Tmp0 = Op.getOperand(0);
5546   SDValue Tmp1 = Op.getOperand(1);
5547   SDLoc dl(Op);
5548   EVT VT = Op.getValueType();
5549   EVT SrcVT = Tmp1.getValueType();
5550   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5551     Tmp0.getOpcode() == ARMISD::VMOVDRR;
5552   bool UseNEON = !InGPR && Subtarget->hasNEON();
5553 
5554   if (UseNEON) {
5555     // Use VBSL to copy the sign bit.
5556     unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5557     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5558                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5559     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5560     if (VT == MVT::f64)
5561       Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5562                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5563                          DAG.getConstant(32, dl, MVT::i32));
5564     else /*if (VT == MVT::f32)*/
5565       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5566     if (SrcVT == MVT::f32) {
5567       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5568       if (VT == MVT::f64)
5569         Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5570                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5571                            DAG.getConstant(32, dl, MVT::i32));
5572     } else if (VT == MVT::f32)
5573       Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5574                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5575                          DAG.getConstant(32, dl, MVT::i32));
5576     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5577     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5578 
5579     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5580                                             dl, MVT::i32);
5581     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5582     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5583                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5584 
5585     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5586                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5587                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5588     if (VT == MVT::f32) {
5589       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5590       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5591                         DAG.getConstant(0, dl, MVT::i32));
5592     } else {
5593       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5594     }
5595 
5596     return Res;
5597   }
5598 
5599   // Bitcast operand 1 to i32.
5600   if (SrcVT == MVT::f64)
5601     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5602                        Tmp1).getValue(1);
5603   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5604 
5605   // Or in the signbit with integer operations.
5606   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5607   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5608   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5609   if (VT == MVT::f32) {
5610     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5611                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5612     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5613                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5614   }
5615 
5616   // f64: Or the high part with signbit and then combine two parts.
5617   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5618                      Tmp0);
5619   SDValue Lo = Tmp0.getValue(0);
5620   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5621   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5622   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5623 }
5624 
5625 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5626   MachineFunction &MF = DAG.getMachineFunction();
5627   MachineFrameInfo &MFI = MF.getFrameInfo();
5628   MFI.setReturnAddressIsTaken(true);
5629 
5630   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5631     return SDValue();
5632 
5633   EVT VT = Op.getValueType();
5634   SDLoc dl(Op);
5635   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5636   if (Depth) {
5637     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5638     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5639     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5640                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5641                        MachinePointerInfo());
5642   }
5643 
5644   // Return LR, which contains the return address. Mark it an implicit live-in.
5645   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5646   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5647 }
5648 
5649 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5650   const ARMBaseRegisterInfo &ARI =
5651     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5652   MachineFunction &MF = DAG.getMachineFunction();
5653   MachineFrameInfo &MFI = MF.getFrameInfo();
5654   MFI.setFrameAddressIsTaken(true);
5655 
5656   EVT VT = Op.getValueType();
5657   SDLoc dl(Op);  // FIXME probably not meaningful
5658   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5659   Register FrameReg = ARI.getFrameRegister(MF);
5660   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5661   while (Depth--)
5662     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5663                             MachinePointerInfo());
5664   return FrameAddr;
5665 }
5666 
5667 // FIXME? Maybe this could be a TableGen attribute on some registers and
5668 // this table could be generated automatically from RegInfo.
5669 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
5670                                               const MachineFunction &MF) const {
5671   Register Reg = StringSwitch<unsigned>(RegName)
5672                        .Case("sp", ARM::SP)
5673                        .Default(0);
5674   if (Reg)
5675     return Reg;
5676   report_fatal_error(Twine("Invalid register name \""
5677                               + StringRef(RegName)  + "\"."));
5678 }
5679 
5680 // Result is 64 bit value so split into two 32 bit values and return as a
5681 // pair of values.
5682 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5683                                 SelectionDAG &DAG) {
5684   SDLoc DL(N);
5685 
5686   // This function is only supposed to be called for i64 type destination.
5687   assert(N->getValueType(0) == MVT::i64
5688           && "ExpandREAD_REGISTER called for non-i64 type result.");
5689 
5690   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5691                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5692                              N->getOperand(0),
5693                              N->getOperand(1));
5694 
5695   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5696                     Read.getValue(1)));
5697   Results.push_back(Read.getOperand(0));
5698 }
5699 
5700 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5701 /// When \p DstVT, the destination type of \p BC, is on the vector
5702 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5703 /// it might be possible to combine them, such that everything stays on the
5704 /// vector register bank.
5705 /// \p return The node that would replace \p BT, if the combine
5706 /// is possible.
5707 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5708                                                 SelectionDAG &DAG) {
5709   SDValue Op = BC->getOperand(0);
5710   EVT DstVT = BC->getValueType(0);
5711 
5712   // The only vector instruction that can produce a scalar (remember,
5713   // since the bitcast was about to be turned into VMOVDRR, the source
5714   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5715   // Moreover, we can do this combine only if there is one use.
5716   // Finally, if the destination type is not a vector, there is not
5717   // much point on forcing everything on the vector bank.
5718   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5719       !Op.hasOneUse())
5720     return SDValue();
5721 
5722   // If the index is not constant, we will introduce an additional
5723   // multiply that will stick.
5724   // Give up in that case.
5725   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5726   if (!Index)
5727     return SDValue();
5728   unsigned DstNumElt = DstVT.getVectorNumElements();
5729 
5730   // Compute the new index.
5731   const APInt &APIntIndex = Index->getAPIntValue();
5732   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5733   NewIndex *= APIntIndex;
5734   // Check if the new constant index fits into i32.
5735   if (NewIndex.getBitWidth() > 32)
5736     return SDValue();
5737 
5738   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5739   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5740   SDLoc dl(Op);
5741   SDValue ExtractSrc = Op.getOperand(0);
5742   EVT VecVT = EVT::getVectorVT(
5743       *DAG.getContext(), DstVT.getScalarType(),
5744       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5745   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5746   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5747                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5748 }
5749 
5750 /// ExpandBITCAST - If the target supports VFP, this function is called to
5751 /// expand a bit convert where either the source or destination type is i64 to
5752 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5753 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5754 /// vectors), since the legalizer won't know what to do with that.
5755 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5756                              const ARMSubtarget *Subtarget) {
5757   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5758   SDLoc dl(N);
5759   SDValue Op = N->getOperand(0);
5760 
5761   // This function is only supposed to be called for i16 and i64 types, either
5762   // as the source or destination of the bit convert.
5763   EVT SrcVT = Op.getValueType();
5764   EVT DstVT = N->getValueType(0);
5765 
5766   if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5767     if (!Subtarget->hasFullFP16())
5768       return SDValue();
5769     // f16 bitcast i16 -> VMOVhr
5770     return DAG.getNode(ARMISD::VMOVhr, SDLoc(N), MVT::f16,
5771                        DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
5772   }
5773 
5774   if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5775     if (!Subtarget->hasFullFP16())
5776       return SDValue();
5777     // i16 bitcast f16 -> VMOVrh
5778     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16,
5779                        DAG.getNode(ARMISD::VMOVrh, SDLoc(N), MVT::i32, Op));
5780   }
5781 
5782   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5783     return SDValue();
5784 
5785   // Turn i64->f64 into VMOVDRR.
5786   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5787     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5788     // if we can combine the bitcast with its source.
5789     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5790       return Val;
5791 
5792     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5793                              DAG.getConstant(0, dl, MVT::i32));
5794     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5795                              DAG.getConstant(1, dl, MVT::i32));
5796     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5797                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5798   }
5799 
5800   // Turn f64->i64 into VMOVRRD.
5801   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5802     SDValue Cvt;
5803     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5804         SrcVT.getVectorNumElements() > 1)
5805       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5806                         DAG.getVTList(MVT::i32, MVT::i32),
5807                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5808     else
5809       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5810                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5811     // Merge the pieces into a single i64 value.
5812     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5813   }
5814 
5815   return SDValue();
5816 }
5817 
5818 /// getZeroVector - Returns a vector of specified type with all zero elements.
5819 /// Zero vectors are used to represent vector negation and in those cases
5820 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5821 /// not support i64 elements, so sometimes the zero vectors will need to be
5822 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5823 /// zero vector.
5824 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5825   assert(VT.isVector() && "Expected a vector type");
5826   // The canonical modified immediate encoding of a zero vector is....0!
5827   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5828   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5829   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5830   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5831 }
5832 
5833 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5834 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5835 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5836                                                 SelectionDAG &DAG) const {
5837   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5838   EVT VT = Op.getValueType();
5839   unsigned VTBits = VT.getSizeInBits();
5840   SDLoc dl(Op);
5841   SDValue ShOpLo = Op.getOperand(0);
5842   SDValue ShOpHi = Op.getOperand(1);
5843   SDValue ShAmt  = Op.getOperand(2);
5844   SDValue ARMcc;
5845   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5846   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5847 
5848   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5849 
5850   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5851                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5852   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5853   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5854                                    DAG.getConstant(VTBits, dl, MVT::i32));
5855   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5856   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5857   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5858   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5859                             ISD::SETGE, ARMcc, DAG, dl);
5860   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5861                            ARMcc, CCR, CmpLo);
5862 
5863   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5864   SDValue HiBigShift = Opc == ISD::SRA
5865                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5866                                          DAG.getConstant(VTBits - 1, dl, VT))
5867                            : DAG.getConstant(0, dl, VT);
5868   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5869                             ISD::SETGE, ARMcc, DAG, dl);
5870   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5871                            ARMcc, CCR, CmpHi);
5872 
5873   SDValue Ops[2] = { Lo, Hi };
5874   return DAG.getMergeValues(Ops, dl);
5875 }
5876 
5877 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5878 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5879 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5880                                                SelectionDAG &DAG) const {
5881   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5882   EVT VT = Op.getValueType();
5883   unsigned VTBits = VT.getSizeInBits();
5884   SDLoc dl(Op);
5885   SDValue ShOpLo = Op.getOperand(0);
5886   SDValue ShOpHi = Op.getOperand(1);
5887   SDValue ShAmt  = Op.getOperand(2);
5888   SDValue ARMcc;
5889   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5890 
5891   assert(Op.getOpcode() == ISD::SHL_PARTS);
5892   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5893                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5894   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5895   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5896   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5897 
5898   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5899                                    DAG.getConstant(VTBits, dl, MVT::i32));
5900   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5901   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5902                             ISD::SETGE, ARMcc, DAG, dl);
5903   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5904                            ARMcc, CCR, CmpHi);
5905 
5906   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5907                           ISD::SETGE, ARMcc, DAG, dl);
5908   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5909   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5910                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5911 
5912   SDValue Ops[2] = { Lo, Hi };
5913   return DAG.getMergeValues(Ops, dl);
5914 }
5915 
5916 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5917                                             SelectionDAG &DAG) const {
5918   // The rounding mode is in bits 23:22 of the FPSCR.
5919   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5920   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5921   // so that the shift + and get folded into a bitfield extract.
5922   SDLoc dl(Op);
5923   SDValue Chain = Op.getOperand(0);
5924   SDValue Ops[] = {Chain,
5925                    DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
5926 
5927   SDValue FPSCR =
5928       DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
5929   Chain = FPSCR.getValue(1);
5930   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5931                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5932   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5933                               DAG.getConstant(22, dl, MVT::i32));
5934   SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5935                             DAG.getConstant(3, dl, MVT::i32));
5936   return DAG.getMergeValues({And, Chain}, dl);
5937 }
5938 
5939 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5940                          const ARMSubtarget *ST) {
5941   SDLoc dl(N);
5942   EVT VT = N->getValueType(0);
5943   if (VT.isVector() && ST->hasNEON()) {
5944 
5945     // Compute the least significant set bit: LSB = X & -X
5946     SDValue X = N->getOperand(0);
5947     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5948     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5949 
5950     EVT ElemTy = VT.getVectorElementType();
5951 
5952     if (ElemTy == MVT::i8) {
5953       // Compute with: cttz(x) = ctpop(lsb - 1)
5954       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5955                                 DAG.getTargetConstant(1, dl, ElemTy));
5956       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5957       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5958     }
5959 
5960     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5961         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5962       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5963       unsigned NumBits = ElemTy.getSizeInBits();
5964       SDValue WidthMinus1 =
5965           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5966                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5967       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5968       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5969     }
5970 
5971     // Compute with: cttz(x) = ctpop(lsb - 1)
5972 
5973     // Compute LSB - 1.
5974     SDValue Bits;
5975     if (ElemTy == MVT::i64) {
5976       // Load constant 0xffff'ffff'ffff'ffff to register.
5977       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5978                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5979       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5980     } else {
5981       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5982                                 DAG.getTargetConstant(1, dl, ElemTy));
5983       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5984     }
5985     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5986   }
5987 
5988   if (!ST->hasV6T2Ops())
5989     return SDValue();
5990 
5991   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5992   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5993 }
5994 
5995 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5996                           const ARMSubtarget *ST) {
5997   EVT VT = N->getValueType(0);
5998   SDLoc DL(N);
5999 
6000   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6001   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6002           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6003          "Unexpected type for custom ctpop lowering");
6004 
6005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6006   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6007   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6008   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6009 
6010   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6011   unsigned EltSize = 8;
6012   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6013   while (EltSize != VT.getScalarSizeInBits()) {
6014     SmallVector<SDValue, 8> Ops;
6015     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6016                                   TLI.getPointerTy(DAG.getDataLayout())));
6017     Ops.push_back(Res);
6018 
6019     EltSize *= 2;
6020     NumElts /= 2;
6021     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6022     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6023   }
6024 
6025   return Res;
6026 }
6027 
6028 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
6029 /// operand of a vector shift operation, where all the elements of the
6030 /// build_vector must have the same constant integer value.
6031 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6032   // Ignore bit_converts.
6033   while (Op.getOpcode() == ISD::BITCAST)
6034     Op = Op.getOperand(0);
6035   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6036   APInt SplatBits, SplatUndef;
6037   unsigned SplatBitSize;
6038   bool HasAnyUndefs;
6039   if (!BVN ||
6040       !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6041                             ElementBits) ||
6042       SplatBitSize > ElementBits)
6043     return false;
6044   Cnt = SplatBits.getSExtValue();
6045   return true;
6046 }
6047 
6048 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6049 /// operand of a vector shift left operation.  That value must be in the range:
6050 ///   0 <= Value < ElementBits for a left shift; or
6051 ///   0 <= Value <= ElementBits for a long left shift.
6052 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6053   assert(VT.isVector() && "vector shift count is not a vector type");
6054   int64_t ElementBits = VT.getScalarSizeInBits();
6055   if (!getVShiftImm(Op, ElementBits, Cnt))
6056     return false;
6057   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6058 }
6059 
6060 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6061 /// operand of a vector shift right operation.  For a shift opcode, the value
6062 /// is positive, but for an intrinsic the value count must be negative. The
6063 /// absolute value must be in the range:
6064 ///   1 <= |Value| <= ElementBits for a right shift; or
6065 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6066 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6067                          int64_t &Cnt) {
6068   assert(VT.isVector() && "vector shift count is not a vector type");
6069   int64_t ElementBits = VT.getScalarSizeInBits();
6070   if (!getVShiftImm(Op, ElementBits, Cnt))
6071     return false;
6072   if (!isIntrinsic)
6073     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6074   if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6075     Cnt = -Cnt;
6076     return true;
6077   }
6078   return false;
6079 }
6080 
6081 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6082                           const ARMSubtarget *ST) {
6083   EVT VT = N->getValueType(0);
6084   SDLoc dl(N);
6085   int64_t Cnt;
6086 
6087   if (!VT.isVector())
6088     return SDValue();
6089 
6090   // We essentially have two forms here. Shift by an immediate and shift by a
6091   // vector register (there are also shift by a gpr, but that is just handled
6092   // with a tablegen pattern). We cannot easily match shift by an immediate in
6093   // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6094   // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6095   // signed or unsigned, and a negative shift indicates a shift right).
6096   if (N->getOpcode() == ISD::SHL) {
6097     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6098       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6099                          DAG.getConstant(Cnt, dl, MVT::i32));
6100     return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6101                        N->getOperand(1));
6102   }
6103 
6104   assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6105          "unexpected vector shift opcode");
6106 
6107   if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6108     unsigned VShiftOpc =
6109         (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6110     return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6111                        DAG.getConstant(Cnt, dl, MVT::i32));
6112   }
6113 
6114   // Other right shifts we don't have operations for (we use a shift left by a
6115   // negative number).
6116   EVT ShiftVT = N->getOperand(1).getValueType();
6117   SDValue NegatedCount = DAG.getNode(
6118       ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6119   unsigned VShiftOpc =
6120       (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6121   return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6122 }
6123 
6124 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6125                                 const ARMSubtarget *ST) {
6126   EVT VT = N->getValueType(0);
6127   SDLoc dl(N);
6128 
6129   // We can get here for a node like i32 = ISD::SHL i32, i64
6130   if (VT != MVT::i64)
6131     return SDValue();
6132 
6133   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6134           N->getOpcode() == ISD::SHL) &&
6135          "Unknown shift to lower!");
6136 
6137   unsigned ShOpc = N->getOpcode();
6138   if (ST->hasMVEIntegerOps()) {
6139     SDValue ShAmt = N->getOperand(1);
6140     unsigned ShPartsOpc = ARMISD::LSLL;
6141     ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6142 
6143     // If the shift amount is greater than 32 or has a greater bitwidth than 64
6144     // then do the default optimisation
6145     if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6146         (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6147       return SDValue();
6148 
6149     // Extract the lower 32 bits of the shift amount if it's not an i32
6150     if (ShAmt->getValueType(0) != MVT::i32)
6151       ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6152 
6153     if (ShOpc == ISD::SRL) {
6154       if (!Con)
6155         // There is no t2LSRLr instruction so negate and perform an lsll if the
6156         // shift amount is in a register, emulating a right shift.
6157         ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6158                             DAG.getConstant(0, dl, MVT::i32), ShAmt);
6159       else
6160         // Else generate an lsrl on the immediate shift amount
6161         ShPartsOpc = ARMISD::LSRL;
6162     } else if (ShOpc == ISD::SRA)
6163       ShPartsOpc = ARMISD::ASRL;
6164 
6165     // Lower 32 bits of the destination/source
6166     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6167                              DAG.getConstant(0, dl, MVT::i32));
6168     // Upper 32 bits of the destination/source
6169     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6170                              DAG.getConstant(1, dl, MVT::i32));
6171 
6172     // Generate the shift operation as computed above
6173     Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6174                      ShAmt);
6175     // The upper 32 bits come from the second return value of lsll
6176     Hi = SDValue(Lo.getNode(), 1);
6177     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6178   }
6179 
6180   // We only lower SRA, SRL of 1 here, all others use generic lowering.
6181   if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6182     return SDValue();
6183 
6184   // If we are in thumb mode, we don't have RRX.
6185   if (ST->isThumb1Only())
6186     return SDValue();
6187 
6188   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
6189   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6190                            DAG.getConstant(0, dl, MVT::i32));
6191   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6192                            DAG.getConstant(1, dl, MVT::i32));
6193 
6194   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6195   // captures the result into a carry flag.
6196   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6197   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6198 
6199   // The low part is an ARMISD::RRX operand, which shifts the carry in.
6200   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6201 
6202   // Merge the pieces into a single i64 value.
6203  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6204 }
6205 
6206 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6207                            const ARMSubtarget *ST) {
6208   bool Invert = false;
6209   bool Swap = false;
6210   unsigned Opc = ARMCC::AL;
6211 
6212   SDValue Op0 = Op.getOperand(0);
6213   SDValue Op1 = Op.getOperand(1);
6214   SDValue CC = Op.getOperand(2);
6215   EVT VT = Op.getValueType();
6216   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6217   SDLoc dl(Op);
6218 
6219   EVT CmpVT;
6220   if (ST->hasNEON())
6221     CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6222   else {
6223     assert(ST->hasMVEIntegerOps() &&
6224            "No hardware support for integer vector comparison!");
6225 
6226     if (Op.getValueType().getVectorElementType() != MVT::i1)
6227       return SDValue();
6228 
6229     // Make sure we expand floating point setcc to scalar if we do not have
6230     // mve.fp, so that we can handle them from there.
6231     if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6232       return SDValue();
6233 
6234     CmpVT = VT;
6235   }
6236 
6237   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6238       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6239     // Special-case integer 64-bit equality comparisons. They aren't legal,
6240     // but they can be lowered with a few vector instructions.
6241     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6242     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6243     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6244     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6245     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6246                               DAG.getCondCode(ISD::SETEQ));
6247     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6248     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6249     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6250     if (SetCCOpcode == ISD::SETNE)
6251       Merged = DAG.getNOT(dl, Merged, CmpVT);
6252     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6253     return Merged;
6254   }
6255 
6256   if (CmpVT.getVectorElementType() == MVT::i64)
6257     // 64-bit comparisons are not legal in general.
6258     return SDValue();
6259 
6260   if (Op1.getValueType().isFloatingPoint()) {
6261     switch (SetCCOpcode) {
6262     default: llvm_unreachable("Illegal FP comparison");
6263     case ISD::SETUNE:
6264     case ISD::SETNE:
6265       if (ST->hasMVEFloatOps()) {
6266         Opc = ARMCC::NE; break;
6267       } else {
6268         Invert = true; LLVM_FALLTHROUGH;
6269       }
6270     case ISD::SETOEQ:
6271     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6272     case ISD::SETOLT:
6273     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6274     case ISD::SETOGT:
6275     case ISD::SETGT:  Opc = ARMCC::GT; break;
6276     case ISD::SETOLE:
6277     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6278     case ISD::SETOGE:
6279     case ISD::SETGE: Opc = ARMCC::GE; break;
6280     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6281     case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6282     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6283     case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6284     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6285     case ISD::SETONE: {
6286       // Expand this to (OLT | OGT).
6287       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6288                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6289       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6290                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6291       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6292       if (Invert)
6293         Result = DAG.getNOT(dl, Result, VT);
6294       return Result;
6295     }
6296     case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6297     case ISD::SETO: {
6298       // Expand this to (OLT | OGE).
6299       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6300                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6301       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6302                                    DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6303       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6304       if (Invert)
6305         Result = DAG.getNOT(dl, Result, VT);
6306       return Result;
6307     }
6308     }
6309   } else {
6310     // Integer comparisons.
6311     switch (SetCCOpcode) {
6312     default: llvm_unreachable("Illegal integer comparison");
6313     case ISD::SETNE:
6314       if (ST->hasMVEIntegerOps()) {
6315         Opc = ARMCC::NE; break;
6316       } else {
6317         Invert = true; LLVM_FALLTHROUGH;
6318       }
6319     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6320     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
6321     case ISD::SETGT:  Opc = ARMCC::GT; break;
6322     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6323     case ISD::SETGE:  Opc = ARMCC::GE; break;
6324     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6325     case ISD::SETUGT: Opc = ARMCC::HI; break;
6326     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6327     case ISD::SETUGE: Opc = ARMCC::HS; break;
6328     }
6329 
6330     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6331     if (ST->hasNEON() && Opc == ARMCC::EQ) {
6332       SDValue AndOp;
6333       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6334         AndOp = Op0;
6335       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6336         AndOp = Op1;
6337 
6338       // Ignore bitconvert.
6339       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6340         AndOp = AndOp.getOperand(0);
6341 
6342       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6343         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6344         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6345         SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6346         if (!Invert)
6347           Result = DAG.getNOT(dl, Result, VT);
6348         return Result;
6349       }
6350     }
6351   }
6352 
6353   if (Swap)
6354     std::swap(Op0, Op1);
6355 
6356   // If one of the operands is a constant vector zero, attempt to fold the
6357   // comparison to a specialized compare-against-zero form.
6358   SDValue SingleOp;
6359   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6360     SingleOp = Op0;
6361   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6362     if (Opc == ARMCC::GE)
6363       Opc = ARMCC::LE;
6364     else if (Opc == ARMCC::GT)
6365       Opc = ARMCC::LT;
6366     SingleOp = Op1;
6367   }
6368 
6369   SDValue Result;
6370   if (SingleOp.getNode()) {
6371     Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6372                          DAG.getConstant(Opc, dl, MVT::i32));
6373   } else {
6374     Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6375                          DAG.getConstant(Opc, dl, MVT::i32));
6376   }
6377 
6378   Result = DAG.getSExtOrTrunc(Result, dl, VT);
6379 
6380   if (Invert)
6381     Result = DAG.getNOT(dl, Result, VT);
6382 
6383   return Result;
6384 }
6385 
6386 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6387   SDValue LHS = Op.getOperand(0);
6388   SDValue RHS = Op.getOperand(1);
6389   SDValue Carry = Op.getOperand(2);
6390   SDValue Cond = Op.getOperand(3);
6391   SDLoc DL(Op);
6392 
6393   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6394 
6395   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6396   // have to invert the carry first.
6397   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6398                       DAG.getConstant(1, DL, MVT::i32), Carry);
6399   // This converts the boolean value carry into the carry flag.
6400   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6401 
6402   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6403   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6404 
6405   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6406   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6407   SDValue ARMcc = DAG.getConstant(
6408       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6409   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6410   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6411                                    Cmp.getValue(1), SDValue());
6412   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6413                      CCR, Chain.getValue(1));
6414 }
6415 
6416 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6417 /// valid vector constant for a NEON or MVE instruction with a "modified
6418 /// immediate" operand (e.g., VMOV).  If so, return the encoded value.
6419 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6420                                  unsigned SplatBitSize, SelectionDAG &DAG,
6421                                  const SDLoc &dl, EVT &VT, EVT VectorVT,
6422                                  VMOVModImmType type) {
6423   unsigned OpCmode, Imm;
6424   bool is128Bits = VectorVT.is128BitVector();
6425 
6426   // SplatBitSize is set to the smallest size that splats the vector, so a
6427   // zero vector will always have SplatBitSize == 8.  However, NEON modified
6428   // immediate instructions others than VMOV do not support the 8-bit encoding
6429   // of a zero vector, and the default encoding of zero is supposed to be the
6430   // 32-bit version.
6431   if (SplatBits == 0)
6432     SplatBitSize = 32;
6433 
6434   switch (SplatBitSize) {
6435   case 8:
6436     if (type != VMOVModImm)
6437       return SDValue();
6438     // Any 1-byte value is OK.  Op=0, Cmode=1110.
6439     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6440     OpCmode = 0xe;
6441     Imm = SplatBits;
6442     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6443     break;
6444 
6445   case 16:
6446     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6447     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6448     if ((SplatBits & ~0xff) == 0) {
6449       // Value = 0x00nn: Op=x, Cmode=100x.
6450       OpCmode = 0x8;
6451       Imm = SplatBits;
6452       break;
6453     }
6454     if ((SplatBits & ~0xff00) == 0) {
6455       // Value = 0xnn00: Op=x, Cmode=101x.
6456       OpCmode = 0xa;
6457       Imm = SplatBits >> 8;
6458       break;
6459     }
6460     return SDValue();
6461 
6462   case 32:
6463     // NEON's 32-bit VMOV supports splat values where:
6464     // * only one byte is nonzero, or
6465     // * the least significant byte is 0xff and the second byte is nonzero, or
6466     // * the least significant 2 bytes are 0xff and the third is nonzero.
6467     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6468     if ((SplatBits & ~0xff) == 0) {
6469       // Value = 0x000000nn: Op=x, Cmode=000x.
6470       OpCmode = 0;
6471       Imm = SplatBits;
6472       break;
6473     }
6474     if ((SplatBits & ~0xff00) == 0) {
6475       // Value = 0x0000nn00: Op=x, Cmode=001x.
6476       OpCmode = 0x2;
6477       Imm = SplatBits >> 8;
6478       break;
6479     }
6480     if ((SplatBits & ~0xff0000) == 0) {
6481       // Value = 0x00nn0000: Op=x, Cmode=010x.
6482       OpCmode = 0x4;
6483       Imm = SplatBits >> 16;
6484       break;
6485     }
6486     if ((SplatBits & ~0xff000000) == 0) {
6487       // Value = 0xnn000000: Op=x, Cmode=011x.
6488       OpCmode = 0x6;
6489       Imm = SplatBits >> 24;
6490       break;
6491     }
6492 
6493     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6494     if (type == OtherModImm) return SDValue();
6495 
6496     if ((SplatBits & ~0xffff) == 0 &&
6497         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6498       // Value = 0x0000nnff: Op=x, Cmode=1100.
6499       OpCmode = 0xc;
6500       Imm = SplatBits >> 8;
6501       break;
6502     }
6503 
6504     // cmode == 0b1101 is not supported for MVE VMVN
6505     if (type == MVEVMVNModImm)
6506       return SDValue();
6507 
6508     if ((SplatBits & ~0xffffff) == 0 &&
6509         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6510       // Value = 0x00nnffff: Op=x, Cmode=1101.
6511       OpCmode = 0xd;
6512       Imm = SplatBits >> 16;
6513       break;
6514     }
6515 
6516     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6517     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6518     // VMOV.I32.  A (very) minor optimization would be to replicate the value
6519     // and fall through here to test for a valid 64-bit splat.  But, then the
6520     // caller would also need to check and handle the change in size.
6521     return SDValue();
6522 
6523   case 64: {
6524     if (type != VMOVModImm)
6525       return SDValue();
6526     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6527     uint64_t BitMask = 0xff;
6528     uint64_t Val = 0;
6529     unsigned ImmMask = 1;
6530     Imm = 0;
6531     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6532       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6533         Val |= BitMask;
6534         Imm |= ImmMask;
6535       } else if ((SplatBits & BitMask) != 0) {
6536         return SDValue();
6537       }
6538       BitMask <<= 8;
6539       ImmMask <<= 1;
6540     }
6541 
6542     if (DAG.getDataLayout().isBigEndian()) {
6543       // Reverse the order of elements within the vector.
6544       unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8;
6545       unsigned Mask = (1 << BytesPerElem) - 1;
6546       unsigned NumElems = 8 / BytesPerElem;
6547       unsigned NewImm = 0;
6548       for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) {
6549         unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask);
6550         NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem;
6551       }
6552       Imm = NewImm;
6553     }
6554 
6555     // Op=1, Cmode=1110.
6556     OpCmode = 0x1e;
6557     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6558     break;
6559   }
6560 
6561   default:
6562     llvm_unreachable("unexpected size for isVMOVModifiedImm");
6563   }
6564 
6565   unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6566   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6567 }
6568 
6569 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6570                                            const ARMSubtarget *ST) const {
6571   EVT VT = Op.getValueType();
6572   bool IsDouble = (VT == MVT::f64);
6573   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6574   const APFloat &FPVal = CFP->getValueAPF();
6575 
6576   // Prevent floating-point constants from using literal loads
6577   // when execute-only is enabled.
6578   if (ST->genExecuteOnly()) {
6579     // If we can represent the constant as an immediate, don't lower it
6580     if (isFPImmLegal(FPVal, VT))
6581       return Op;
6582     // Otherwise, construct as integer, and move to float register
6583     APInt INTVal = FPVal.bitcastToAPInt();
6584     SDLoc DL(CFP);
6585     switch (VT.getSimpleVT().SimpleTy) {
6586       default:
6587         llvm_unreachable("Unknown floating point type!");
6588         break;
6589       case MVT::f64: {
6590         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6591         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6592         if (!ST->isLittle())
6593           std::swap(Lo, Hi);
6594         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6595       }
6596       case MVT::f32:
6597           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6598               DAG.getConstant(INTVal, DL, MVT::i32));
6599     }
6600   }
6601 
6602   if (!ST->hasVFP3Base())
6603     return SDValue();
6604 
6605   // Use the default (constant pool) lowering for double constants when we have
6606   // an SP-only FPU
6607   if (IsDouble && !Subtarget->hasFP64())
6608     return SDValue();
6609 
6610   // Try splatting with a VMOV.f32...
6611   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6612 
6613   if (ImmVal != -1) {
6614     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6615       // We have code in place to select a valid ConstantFP already, no need to
6616       // do any mangling.
6617       return Op;
6618     }
6619 
6620     // It's a float and we are trying to use NEON operations where
6621     // possible. Lower it to a splat followed by an extract.
6622     SDLoc DL(Op);
6623     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6624     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6625                                       NewVal);
6626     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6627                        DAG.getConstant(0, DL, MVT::i32));
6628   }
6629 
6630   // The rest of our options are NEON only, make sure that's allowed before
6631   // proceeding..
6632   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6633     return SDValue();
6634 
6635   EVT VMovVT;
6636   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6637 
6638   // It wouldn't really be worth bothering for doubles except for one very
6639   // important value, which does happen to match: 0.0. So make sure we don't do
6640   // anything stupid.
6641   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6642     return SDValue();
6643 
6644   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6645   SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6646                                      VMovVT, VT, VMOVModImm);
6647   if (NewVal != SDValue()) {
6648     SDLoc DL(Op);
6649     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6650                                       NewVal);
6651     if (IsDouble)
6652       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6653 
6654     // It's a float: cast and extract a vector element.
6655     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6656                                        VecConstant);
6657     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6658                        DAG.getConstant(0, DL, MVT::i32));
6659   }
6660 
6661   // Finally, try a VMVN.i32
6662   NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6663                              VT, VMVNModImm);
6664   if (NewVal != SDValue()) {
6665     SDLoc DL(Op);
6666     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6667 
6668     if (IsDouble)
6669       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6670 
6671     // It's a float: cast and extract a vector element.
6672     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6673                                        VecConstant);
6674     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6675                        DAG.getConstant(0, DL, MVT::i32));
6676   }
6677 
6678   return SDValue();
6679 }
6680 
6681 // check if an VEXT instruction can handle the shuffle mask when the
6682 // vector sources of the shuffle are the same.
6683 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6684   unsigned NumElts = VT.getVectorNumElements();
6685 
6686   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6687   if (M[0] < 0)
6688     return false;
6689 
6690   Imm = M[0];
6691 
6692   // If this is a VEXT shuffle, the immediate value is the index of the first
6693   // element.  The other shuffle indices must be the successive elements after
6694   // the first one.
6695   unsigned ExpectedElt = Imm;
6696   for (unsigned i = 1; i < NumElts; ++i) {
6697     // Increment the expected index.  If it wraps around, just follow it
6698     // back to index zero and keep going.
6699     ++ExpectedElt;
6700     if (ExpectedElt == NumElts)
6701       ExpectedElt = 0;
6702 
6703     if (M[i] < 0) continue; // ignore UNDEF indices
6704     if (ExpectedElt != static_cast<unsigned>(M[i]))
6705       return false;
6706   }
6707 
6708   return true;
6709 }
6710 
6711 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6712                        bool &ReverseVEXT, unsigned &Imm) {
6713   unsigned NumElts = VT.getVectorNumElements();
6714   ReverseVEXT = false;
6715 
6716   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6717   if (M[0] < 0)
6718     return false;
6719 
6720   Imm = M[0];
6721 
6722   // If this is a VEXT shuffle, the immediate value is the index of the first
6723   // element.  The other shuffle indices must be the successive elements after
6724   // the first one.
6725   unsigned ExpectedElt = Imm;
6726   for (unsigned i = 1; i < NumElts; ++i) {
6727     // Increment the expected index.  If it wraps around, it may still be
6728     // a VEXT but the source vectors must be swapped.
6729     ExpectedElt += 1;
6730     if (ExpectedElt == NumElts * 2) {
6731       ExpectedElt = 0;
6732       ReverseVEXT = true;
6733     }
6734 
6735     if (M[i] < 0) continue; // ignore UNDEF indices
6736     if (ExpectedElt != static_cast<unsigned>(M[i]))
6737       return false;
6738   }
6739 
6740   // Adjust the index value if the source operands will be swapped.
6741   if (ReverseVEXT)
6742     Imm -= NumElts;
6743 
6744   return true;
6745 }
6746 
6747 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6748 /// instruction with the specified blocksize.  (The order of the elements
6749 /// within each block of the vector is reversed.)
6750 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6751   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6752          "Only possible block sizes for VREV are: 16, 32, 64");
6753 
6754   unsigned EltSz = VT.getScalarSizeInBits();
6755   if (EltSz == 64)
6756     return false;
6757 
6758   unsigned NumElts = VT.getVectorNumElements();
6759   unsigned BlockElts = M[0] + 1;
6760   // If the first shuffle index is UNDEF, be optimistic.
6761   if (M[0] < 0)
6762     BlockElts = BlockSize / EltSz;
6763 
6764   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6765     return false;
6766 
6767   for (unsigned i = 0; i < NumElts; ++i) {
6768     if (M[i] < 0) continue; // ignore UNDEF indices
6769     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6770       return false;
6771   }
6772 
6773   return true;
6774 }
6775 
6776 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6777   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6778   // range, then 0 is placed into the resulting vector. So pretty much any mask
6779   // of 8 elements can work here.
6780   return VT == MVT::v8i8 && M.size() == 8;
6781 }
6782 
6783 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6784                                unsigned Index) {
6785   if (Mask.size() == Elements * 2)
6786     return Index / Elements;
6787   return Mask[Index] == 0 ? 0 : 1;
6788 }
6789 
6790 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6791 // checking that pairs of elements in the shuffle mask represent the same index
6792 // in each vector, incrementing the expected index by 2 at each step.
6793 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6794 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6795 //  v2={e,f,g,h}
6796 // WhichResult gives the offset for each element in the mask based on which
6797 // of the two results it belongs to.
6798 //
6799 // The transpose can be represented either as:
6800 // result1 = shufflevector v1, v2, result1_shuffle_mask
6801 // result2 = shufflevector v1, v2, result2_shuffle_mask
6802 // where v1/v2 and the shuffle masks have the same number of elements
6803 // (here WhichResult (see below) indicates which result is being checked)
6804 //
6805 // or as:
6806 // results = shufflevector v1, v2, shuffle_mask
6807 // where both results are returned in one vector and the shuffle mask has twice
6808 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6809 // want to check the low half and high half of the shuffle mask as if it were
6810 // the other case
6811 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6812   unsigned EltSz = VT.getScalarSizeInBits();
6813   if (EltSz == 64)
6814     return false;
6815 
6816   unsigned NumElts = VT.getVectorNumElements();
6817   if (M.size() != NumElts && M.size() != NumElts*2)
6818     return false;
6819 
6820   // If the mask is twice as long as the input vector then we need to check the
6821   // upper and lower parts of the mask with a matching value for WhichResult
6822   // FIXME: A mask with only even values will be rejected in case the first
6823   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6824   // M[0] is used to determine WhichResult
6825   for (unsigned i = 0; i < M.size(); i += NumElts) {
6826     WhichResult = SelectPairHalf(NumElts, M, i);
6827     for (unsigned j = 0; j < NumElts; j += 2) {
6828       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6829           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6830         return false;
6831     }
6832   }
6833 
6834   if (M.size() == NumElts*2)
6835     WhichResult = 0;
6836 
6837   return true;
6838 }
6839 
6840 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6841 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6842 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6843 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6844   unsigned EltSz = VT.getScalarSizeInBits();
6845   if (EltSz == 64)
6846     return false;
6847 
6848   unsigned NumElts = VT.getVectorNumElements();
6849   if (M.size() != NumElts && M.size() != NumElts*2)
6850     return false;
6851 
6852   for (unsigned i = 0; i < M.size(); i += NumElts) {
6853     WhichResult = SelectPairHalf(NumElts, M, i);
6854     for (unsigned j = 0; j < NumElts; j += 2) {
6855       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6856           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6857         return false;
6858     }
6859   }
6860 
6861   if (M.size() == NumElts*2)
6862     WhichResult = 0;
6863 
6864   return true;
6865 }
6866 
6867 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6868 // that the mask elements are either all even and in steps of size 2 or all odd
6869 // and in steps of size 2.
6870 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6871 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6872 //  v2={e,f,g,h}
6873 // Requires similar checks to that of isVTRNMask with
6874 // respect the how results are returned.
6875 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6876   unsigned EltSz = VT.getScalarSizeInBits();
6877   if (EltSz == 64)
6878     return false;
6879 
6880   unsigned NumElts = VT.getVectorNumElements();
6881   if (M.size() != NumElts && M.size() != NumElts*2)
6882     return false;
6883 
6884   for (unsigned i = 0; i < M.size(); i += NumElts) {
6885     WhichResult = SelectPairHalf(NumElts, M, i);
6886     for (unsigned j = 0; j < NumElts; ++j) {
6887       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6888         return false;
6889     }
6890   }
6891 
6892   if (M.size() == NumElts*2)
6893     WhichResult = 0;
6894 
6895   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6896   if (VT.is64BitVector() && EltSz == 32)
6897     return false;
6898 
6899   return true;
6900 }
6901 
6902 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6903 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6904 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6905 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6906   unsigned EltSz = VT.getScalarSizeInBits();
6907   if (EltSz == 64)
6908     return false;
6909 
6910   unsigned NumElts = VT.getVectorNumElements();
6911   if (M.size() != NumElts && M.size() != NumElts*2)
6912     return false;
6913 
6914   unsigned Half = NumElts / 2;
6915   for (unsigned i = 0; i < M.size(); i += NumElts) {
6916     WhichResult = SelectPairHalf(NumElts, M, i);
6917     for (unsigned j = 0; j < NumElts; j += Half) {
6918       unsigned Idx = WhichResult;
6919       for (unsigned k = 0; k < Half; ++k) {
6920         int MIdx = M[i + j + k];
6921         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6922           return false;
6923         Idx += 2;
6924       }
6925     }
6926   }
6927 
6928   if (M.size() == NumElts*2)
6929     WhichResult = 0;
6930 
6931   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6932   if (VT.is64BitVector() && EltSz == 32)
6933     return false;
6934 
6935   return true;
6936 }
6937 
6938 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6939 // that pairs of elements of the shufflemask represent the same index in each
6940 // vector incrementing sequentially through the vectors.
6941 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6942 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6943 //  v2={e,f,g,h}
6944 // Requires similar checks to that of isVTRNMask with respect the how results
6945 // are returned.
6946 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6947   unsigned EltSz = VT.getScalarSizeInBits();
6948   if (EltSz == 64)
6949     return false;
6950 
6951   unsigned NumElts = VT.getVectorNumElements();
6952   if (M.size() != NumElts && M.size() != NumElts*2)
6953     return false;
6954 
6955   for (unsigned i = 0; i < M.size(); i += NumElts) {
6956     WhichResult = SelectPairHalf(NumElts, M, i);
6957     unsigned Idx = WhichResult * NumElts / 2;
6958     for (unsigned j = 0; j < NumElts; j += 2) {
6959       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6960           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6961         return false;
6962       Idx += 1;
6963     }
6964   }
6965 
6966   if (M.size() == NumElts*2)
6967     WhichResult = 0;
6968 
6969   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6970   if (VT.is64BitVector() && EltSz == 32)
6971     return false;
6972 
6973   return true;
6974 }
6975 
6976 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6977 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6978 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6979 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6980   unsigned EltSz = VT.getScalarSizeInBits();
6981   if (EltSz == 64)
6982     return false;
6983 
6984   unsigned NumElts = VT.getVectorNumElements();
6985   if (M.size() != NumElts && M.size() != NumElts*2)
6986     return false;
6987 
6988   for (unsigned i = 0; i < M.size(); i += NumElts) {
6989     WhichResult = SelectPairHalf(NumElts, M, i);
6990     unsigned Idx = WhichResult * NumElts / 2;
6991     for (unsigned j = 0; j < NumElts; j += 2) {
6992       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6993           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6994         return false;
6995       Idx += 1;
6996     }
6997   }
6998 
6999   if (M.size() == NumElts*2)
7000     WhichResult = 0;
7001 
7002   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7003   if (VT.is64BitVector() && EltSz == 32)
7004     return false;
7005 
7006   return true;
7007 }
7008 
7009 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7010 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7011 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7012                                            unsigned &WhichResult,
7013                                            bool &isV_UNDEF) {
7014   isV_UNDEF = false;
7015   if (isVTRNMask(ShuffleMask, VT, WhichResult))
7016     return ARMISD::VTRN;
7017   if (isVUZPMask(ShuffleMask, VT, WhichResult))
7018     return ARMISD::VUZP;
7019   if (isVZIPMask(ShuffleMask, VT, WhichResult))
7020     return ARMISD::VZIP;
7021 
7022   isV_UNDEF = true;
7023   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7024     return ARMISD::VTRN;
7025   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7026     return ARMISD::VUZP;
7027   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7028     return ARMISD::VZIP;
7029 
7030   return 0;
7031 }
7032 
7033 /// \return true if this is a reverse operation on an vector.
7034 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7035   unsigned NumElts = VT.getVectorNumElements();
7036   // Make sure the mask has the right size.
7037   if (NumElts != M.size())
7038       return false;
7039 
7040   // Look for <15, ..., 3, -1, 1, 0>.
7041   for (unsigned i = 0; i != NumElts; ++i)
7042     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7043       return false;
7044 
7045   return true;
7046 }
7047 
7048 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) {
7049   unsigned NumElts = VT.getVectorNumElements();
7050   // Make sure the mask has the right size.
7051   if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7052       return false;
7053 
7054   // If Top
7055   //   Look for <0, N, 2, N+2, 4, N+4, ..>.
7056   //   This inserts Input2 into Input1
7057   // else if not Top
7058   //   Look for <0, N+1, 2, N+3, 4, N+5, ..>
7059   //   This inserts Input1 into Input2
7060   unsigned Offset = Top ? 0 : 1;
7061   for (unsigned i = 0; i < NumElts; i+=2) {
7062     if (M[i] >= 0 && M[i] != (int)i)
7063       return false;
7064     if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset))
7065       return false;
7066   }
7067 
7068   return true;
7069 }
7070 
7071 // If N is an integer constant that can be moved into a register in one
7072 // instruction, return an SDValue of such a constant (will become a MOV
7073 // instruction).  Otherwise return null.
7074 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7075                                      const ARMSubtarget *ST, const SDLoc &dl) {
7076   uint64_t Val;
7077   if (!isa<ConstantSDNode>(N))
7078     return SDValue();
7079   Val = cast<ConstantSDNode>(N)->getZExtValue();
7080 
7081   if (ST->isThumb1Only()) {
7082     if (Val <= 255 || ~Val <= 255)
7083       return DAG.getConstant(Val, dl, MVT::i32);
7084   } else {
7085     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7086       return DAG.getConstant(Val, dl, MVT::i32);
7087   }
7088   return SDValue();
7089 }
7090 
7091 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7092                                     const ARMSubtarget *ST) {
7093   SDLoc dl(Op);
7094   EVT VT = Op.getValueType();
7095 
7096   assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7097 
7098   unsigned NumElts = VT.getVectorNumElements();
7099   unsigned BoolMask;
7100   unsigned BitsPerBool;
7101   if (NumElts == 4) {
7102     BitsPerBool = 4;
7103     BoolMask = 0xf;
7104   } else if (NumElts == 8) {
7105     BitsPerBool = 2;
7106     BoolMask = 0x3;
7107   } else if (NumElts == 16) {
7108     BitsPerBool = 1;
7109     BoolMask = 0x1;
7110   } else
7111     return SDValue();
7112 
7113   // If this is a single value copied into all lanes (a splat), we can just sign
7114   // extend that single value
7115   SDValue FirstOp = Op.getOperand(0);
7116   if (!isa<ConstantSDNode>(FirstOp) &&
7117       std::all_of(std::next(Op->op_begin()), Op->op_end(),
7118                   [&FirstOp](SDUse &U) {
7119                     return U.get().isUndef() || U.get() == FirstOp;
7120                   })) {
7121     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7122                               DAG.getValueType(MVT::i1));
7123     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7124   }
7125 
7126   // First create base with bits set where known
7127   unsigned Bits32 = 0;
7128   for (unsigned i = 0; i < NumElts; ++i) {
7129     SDValue V = Op.getOperand(i);
7130     if (!isa<ConstantSDNode>(V) && !V.isUndef())
7131       continue;
7132     bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7133     if (BitSet)
7134       Bits32 |= BoolMask << (i * BitsPerBool);
7135   }
7136 
7137   // Add in unknown nodes
7138   SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7139                              DAG.getConstant(Bits32, dl, MVT::i32));
7140   for (unsigned i = 0; i < NumElts; ++i) {
7141     SDValue V = Op.getOperand(i);
7142     if (isa<ConstantSDNode>(V) || V.isUndef())
7143       continue;
7144     Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7145                        DAG.getConstant(i, dl, MVT::i32));
7146   }
7147 
7148   return Base;
7149 }
7150 
7151 // If this is a case we can't handle, return null and let the default
7152 // expansion code take care of it.
7153 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7154                                              const ARMSubtarget *ST) const {
7155   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7156   SDLoc dl(Op);
7157   EVT VT = Op.getValueType();
7158 
7159   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7160     return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7161 
7162   APInt SplatBits, SplatUndef;
7163   unsigned SplatBitSize;
7164   bool HasAnyUndefs;
7165   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7166     if (SplatUndef.isAllOnesValue())
7167       return DAG.getUNDEF(VT);
7168 
7169     if ((ST->hasNEON() && SplatBitSize <= 64) ||
7170         (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7171       // Check if an immediate VMOV works.
7172       EVT VmovVT;
7173       SDValue Val =
7174           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7175                             SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7176 
7177       if (Val.getNode()) {
7178         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7179         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7180       }
7181 
7182       // Try an immediate VMVN.
7183       uint64_t NegatedImm = (~SplatBits).getZExtValue();
7184       Val = isVMOVModifiedImm(
7185           NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7186           VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7187       if (Val.getNode()) {
7188         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7189         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7190       }
7191 
7192       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7193       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7194         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7195         if (ImmVal != -1) {
7196           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7197           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7198         }
7199       }
7200     }
7201   }
7202 
7203   // Scan through the operands to see if only one value is used.
7204   //
7205   // As an optimisation, even if more than one value is used it may be more
7206   // profitable to splat with one value then change some lanes.
7207   //
7208   // Heuristically we decide to do this if the vector has a "dominant" value,
7209   // defined as splatted to more than half of the lanes.
7210   unsigned NumElts = VT.getVectorNumElements();
7211   bool isOnlyLowElement = true;
7212   bool usesOnlyOneValue = true;
7213   bool hasDominantValue = false;
7214   bool isConstant = true;
7215 
7216   // Map of the number of times a particular SDValue appears in the
7217   // element list.
7218   DenseMap<SDValue, unsigned> ValueCounts;
7219   SDValue Value;
7220   for (unsigned i = 0; i < NumElts; ++i) {
7221     SDValue V = Op.getOperand(i);
7222     if (V.isUndef())
7223       continue;
7224     if (i > 0)
7225       isOnlyLowElement = false;
7226     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7227       isConstant = false;
7228 
7229     ValueCounts.insert(std::make_pair(V, 0));
7230     unsigned &Count = ValueCounts[V];
7231 
7232     // Is this value dominant? (takes up more than half of the lanes)
7233     if (++Count > (NumElts / 2)) {
7234       hasDominantValue = true;
7235       Value = V;
7236     }
7237   }
7238   if (ValueCounts.size() != 1)
7239     usesOnlyOneValue = false;
7240   if (!Value.getNode() && !ValueCounts.empty())
7241     Value = ValueCounts.begin()->first;
7242 
7243   if (ValueCounts.empty())
7244     return DAG.getUNDEF(VT);
7245 
7246   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7247   // Keep going if we are hitting this case.
7248   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7249     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7250 
7251   unsigned EltSize = VT.getScalarSizeInBits();
7252 
7253   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
7254   // i32 and try again.
7255   if (hasDominantValue && EltSize <= 32) {
7256     if (!isConstant) {
7257       SDValue N;
7258 
7259       // If we are VDUPing a value that comes directly from a vector, that will
7260       // cause an unnecessary move to and from a GPR, where instead we could
7261       // just use VDUPLANE. We can only do this if the lane being extracted
7262       // is at a constant index, as the VDUP from lane instructions only have
7263       // constant-index forms.
7264       ConstantSDNode *constIndex;
7265       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7266           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7267         // We need to create a new undef vector to use for the VDUPLANE if the
7268         // size of the vector from which we get the value is different than the
7269         // size of the vector that we need to create. We will insert the element
7270         // such that the register coalescer will remove unnecessary copies.
7271         if (VT != Value->getOperand(0).getValueType()) {
7272           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7273                              VT.getVectorNumElements();
7274           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7275                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7276                         Value, DAG.getConstant(index, dl, MVT::i32)),
7277                            DAG.getConstant(index, dl, MVT::i32));
7278         } else
7279           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7280                         Value->getOperand(0), Value->getOperand(1));
7281       } else
7282         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7283 
7284       if (!usesOnlyOneValue) {
7285         // The dominant value was splatted as 'N', but we now have to insert
7286         // all differing elements.
7287         for (unsigned I = 0; I < NumElts; ++I) {
7288           if (Op.getOperand(I) == Value)
7289             continue;
7290           SmallVector<SDValue, 3> Ops;
7291           Ops.push_back(N);
7292           Ops.push_back(Op.getOperand(I));
7293           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7294           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7295         }
7296       }
7297       return N;
7298     }
7299     if (VT.getVectorElementType().isFloatingPoint()) {
7300       SmallVector<SDValue, 8> Ops;
7301       MVT FVT = VT.getVectorElementType().getSimpleVT();
7302       assert(FVT == MVT::f32 || FVT == MVT::f16);
7303       MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7304       for (unsigned i = 0; i < NumElts; ++i)
7305         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7306                                   Op.getOperand(i)));
7307       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7308       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7309       Val = LowerBUILD_VECTOR(Val, DAG, ST);
7310       if (Val.getNode())
7311         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7312     }
7313     if (usesOnlyOneValue) {
7314       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7315       if (isConstant && Val.getNode())
7316         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7317     }
7318   }
7319 
7320   // If all elements are constants and the case above didn't get hit, fall back
7321   // to the default expansion, which will generate a load from the constant
7322   // pool.
7323   if (isConstant)
7324     return SDValue();
7325 
7326   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7327   if (NumElts >= 4) {
7328     SDValue shuffle = ReconstructShuffle(Op, DAG);
7329     if (shuffle != SDValue())
7330       return shuffle;
7331   }
7332 
7333   if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7334     // If we haven't found an efficient lowering, try splitting a 128-bit vector
7335     // into two 64-bit vectors; we might discover a better way to lower it.
7336     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7337     EVT ExtVT = VT.getVectorElementType();
7338     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7339     SDValue Lower =
7340         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7341     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7342       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7343     SDValue Upper = DAG.getBuildVector(
7344         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7345     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7346       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7347     if (Lower && Upper)
7348       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7349   }
7350 
7351   // Vectors with 32- or 64-bit elements can be built by directly assigning
7352   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
7353   // will be legalized.
7354   if (EltSize >= 32) {
7355     // Do the expansion with floating-point types, since that is what the VFP
7356     // registers are defined to use, and since i64 is not legal.
7357     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7358     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7359     SmallVector<SDValue, 8> Ops;
7360     for (unsigned i = 0; i < NumElts; ++i)
7361       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7362     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7363     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7364   }
7365 
7366   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7367   // know the default expansion would otherwise fall back on something even
7368   // worse. For a vector with one or two non-undef values, that's
7369   // scalar_to_vector for the elements followed by a shuffle (provided the
7370   // shuffle is valid for the target) and materialization element by element
7371   // on the stack followed by a load for everything else.
7372   if (!isConstant && !usesOnlyOneValue) {
7373     SDValue Vec = DAG.getUNDEF(VT);
7374     for (unsigned i = 0 ; i < NumElts; ++i) {
7375       SDValue V = Op.getOperand(i);
7376       if (V.isUndef())
7377         continue;
7378       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7379       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7380     }
7381     return Vec;
7382   }
7383 
7384   return SDValue();
7385 }
7386 
7387 // Gather data to see if the operation can be modelled as a
7388 // shuffle in combination with VEXTs.
7389 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7390                                               SelectionDAG &DAG) const {
7391   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7392   SDLoc dl(Op);
7393   EVT VT = Op.getValueType();
7394   unsigned NumElts = VT.getVectorNumElements();
7395 
7396   struct ShuffleSourceInfo {
7397     SDValue Vec;
7398     unsigned MinElt = std::numeric_limits<unsigned>::max();
7399     unsigned MaxElt = 0;
7400 
7401     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7402     // be compatible with the shuffle we intend to construct. As a result
7403     // ShuffleVec will be some sliding window into the original Vec.
7404     SDValue ShuffleVec;
7405 
7406     // Code should guarantee that element i in Vec starts at element "WindowBase
7407     // + i * WindowScale in ShuffleVec".
7408     int WindowBase = 0;
7409     int WindowScale = 1;
7410 
7411     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7412 
7413     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7414   };
7415 
7416   // First gather all vectors used as an immediate source for this BUILD_VECTOR
7417   // node.
7418   SmallVector<ShuffleSourceInfo, 2> Sources;
7419   for (unsigned i = 0; i < NumElts; ++i) {
7420     SDValue V = Op.getOperand(i);
7421     if (V.isUndef())
7422       continue;
7423     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7424       // A shuffle can only come from building a vector from various
7425       // elements of other vectors.
7426       return SDValue();
7427     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7428       // Furthermore, shuffles require a constant mask, whereas extractelts
7429       // accept variable indices.
7430       return SDValue();
7431     }
7432 
7433     // Add this element source to the list if it's not already there.
7434     SDValue SourceVec = V.getOperand(0);
7435     auto Source = llvm::find(Sources, SourceVec);
7436     if (Source == Sources.end())
7437       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7438 
7439     // Update the minimum and maximum lane number seen.
7440     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7441     Source->MinElt = std::min(Source->MinElt, EltNo);
7442     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7443   }
7444 
7445   // Currently only do something sane when at most two source vectors
7446   // are involved.
7447   if (Sources.size() > 2)
7448     return SDValue();
7449 
7450   // Find out the smallest element size among result and two sources, and use
7451   // it as element size to build the shuffle_vector.
7452   EVT SmallestEltTy = VT.getVectorElementType();
7453   for (auto &Source : Sources) {
7454     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7455     if (SrcEltTy.bitsLT(SmallestEltTy))
7456       SmallestEltTy = SrcEltTy;
7457   }
7458   unsigned ResMultiplier =
7459       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7460   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7461   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7462 
7463   // If the source vector is too wide or too narrow, we may nevertheless be able
7464   // to construct a compatible shuffle either by concatenating it with UNDEF or
7465   // extracting a suitable range of elements.
7466   for (auto &Src : Sources) {
7467     EVT SrcVT = Src.ShuffleVec.getValueType();
7468 
7469     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7470       continue;
7471 
7472     // This stage of the search produces a source with the same element type as
7473     // the original, but with a total width matching the BUILD_VECTOR output.
7474     EVT EltVT = SrcVT.getVectorElementType();
7475     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7476     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7477 
7478     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7479       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7480         return SDValue();
7481       // We can pad out the smaller vector for free, so if it's part of a
7482       // shuffle...
7483       Src.ShuffleVec =
7484           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7485                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7486       continue;
7487     }
7488 
7489     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7490       return SDValue();
7491 
7492     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7493       // Span too large for a VEXT to cope
7494       return SDValue();
7495     }
7496 
7497     if (Src.MinElt >= NumSrcElts) {
7498       // The extraction can just take the second half
7499       Src.ShuffleVec =
7500           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7501                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7502       Src.WindowBase = -NumSrcElts;
7503     } else if (Src.MaxElt < NumSrcElts) {
7504       // The extraction can just take the first half
7505       Src.ShuffleVec =
7506           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7507                       DAG.getConstant(0, dl, MVT::i32));
7508     } else {
7509       // An actual VEXT is needed
7510       SDValue VEXTSrc1 =
7511           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7512                       DAG.getConstant(0, dl, MVT::i32));
7513       SDValue VEXTSrc2 =
7514           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7515                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7516 
7517       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7518                                    VEXTSrc2,
7519                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
7520       Src.WindowBase = -Src.MinElt;
7521     }
7522   }
7523 
7524   // Another possible incompatibility occurs from the vector element types. We
7525   // can fix this by bitcasting the source vectors to the same type we intend
7526   // for the shuffle.
7527   for (auto &Src : Sources) {
7528     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7529     if (SrcEltTy == SmallestEltTy)
7530       continue;
7531     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7532     Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
7533     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7534     Src.WindowBase *= Src.WindowScale;
7535   }
7536 
7537   // Final sanity check before we try to actually produce a shuffle.
7538   LLVM_DEBUG(for (auto Src
7539                   : Sources)
7540                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7541 
7542   // The stars all align, our next step is to produce the mask for the shuffle.
7543   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7544   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7545   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7546     SDValue Entry = Op.getOperand(i);
7547     if (Entry.isUndef())
7548       continue;
7549 
7550     auto Src = llvm::find(Sources, Entry.getOperand(0));
7551     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7552 
7553     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7554     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7555     // segment.
7556     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7557     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7558                                VT.getScalarSizeInBits());
7559     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7560 
7561     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7562     // starting at the appropriate offset.
7563     int *LaneMask = &Mask[i * ResMultiplier];
7564 
7565     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7566     ExtractBase += NumElts * (Src - Sources.begin());
7567     for (int j = 0; j < LanesDefined; ++j)
7568       LaneMask[j] = ExtractBase + j;
7569   }
7570 
7571 
7572   // We can't handle more than two sources. This should have already
7573   // been checked before this point.
7574   assert(Sources.size() <= 2 && "Too many sources!");
7575 
7576   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7577   for (unsigned i = 0; i < Sources.size(); ++i)
7578     ShuffleOps[i] = Sources[i].ShuffleVec;
7579 
7580   SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7581                                             ShuffleOps[1], Mask, DAG);
7582   if (!Shuffle)
7583     return SDValue();
7584   return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
7585 }
7586 
7587 enum ShuffleOpCodes {
7588   OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7589   OP_VREV,
7590   OP_VDUP0,
7591   OP_VDUP1,
7592   OP_VDUP2,
7593   OP_VDUP3,
7594   OP_VEXT1,
7595   OP_VEXT2,
7596   OP_VEXT3,
7597   OP_VUZPL, // VUZP, left result
7598   OP_VUZPR, // VUZP, right result
7599   OP_VZIPL, // VZIP, left result
7600   OP_VZIPR, // VZIP, right result
7601   OP_VTRNL, // VTRN, left result
7602   OP_VTRNR  // VTRN, right result
7603 };
7604 
7605 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7606   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7607   switch (OpNum) {
7608   case OP_COPY:
7609   case OP_VREV:
7610   case OP_VDUP0:
7611   case OP_VDUP1:
7612   case OP_VDUP2:
7613   case OP_VDUP3:
7614     return true;
7615   }
7616   return false;
7617 }
7618 
7619 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7620 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7621 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7622 /// are assumed to be legal.
7623 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7624   if (VT.getVectorNumElements() == 4 &&
7625       (VT.is128BitVector() || VT.is64BitVector())) {
7626     unsigned PFIndexes[4];
7627     for (unsigned i = 0; i != 4; ++i) {
7628       if (M[i] < 0)
7629         PFIndexes[i] = 8;
7630       else
7631         PFIndexes[i] = M[i];
7632     }
7633 
7634     // Compute the index in the perfect shuffle table.
7635     unsigned PFTableIndex =
7636       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7637     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7638     unsigned Cost = (PFEntry >> 30);
7639 
7640     if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7641       return true;
7642   }
7643 
7644   bool ReverseVEXT, isV_UNDEF;
7645   unsigned Imm, WhichResult;
7646 
7647   unsigned EltSize = VT.getScalarSizeInBits();
7648   if (EltSize >= 32 ||
7649       ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7650       ShuffleVectorInst::isIdentityMask(M) ||
7651       isVREVMask(M, VT, 64) ||
7652       isVREVMask(M, VT, 32) ||
7653       isVREVMask(M, VT, 16))
7654     return true;
7655   else if (Subtarget->hasNEON() &&
7656            (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7657             isVTBLMask(M, VT) ||
7658             isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7659     return true;
7660   else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7661            isReverseMask(M, VT))
7662     return true;
7663   else if (Subtarget->hasMVEIntegerOps() &&
7664            (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1)))
7665     return true;
7666   else
7667     return false;
7668 }
7669 
7670 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7671 /// the specified operations to build the shuffle.
7672 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7673                                       SDValue RHS, SelectionDAG &DAG,
7674                                       const SDLoc &dl) {
7675   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7676   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7677   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7678 
7679   if (OpNum == OP_COPY) {
7680     if (LHSID == (1*9+2)*9+3) return LHS;
7681     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7682     return RHS;
7683   }
7684 
7685   SDValue OpLHS, OpRHS;
7686   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7687   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7688   EVT VT = OpLHS.getValueType();
7689 
7690   switch (OpNum) {
7691   default: llvm_unreachable("Unknown shuffle opcode!");
7692   case OP_VREV:
7693     // VREV divides the vector in half and swaps within the half.
7694     if (VT.getVectorElementType() == MVT::i32 ||
7695         VT.getVectorElementType() == MVT::f32)
7696       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7697     // vrev <4 x i16> -> VREV32
7698     if (VT.getVectorElementType() == MVT::i16)
7699       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7700     // vrev <4 x i8> -> VREV16
7701     assert(VT.getVectorElementType() == MVT::i8);
7702     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7703   case OP_VDUP0:
7704   case OP_VDUP1:
7705   case OP_VDUP2:
7706   case OP_VDUP3:
7707     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7708                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7709   case OP_VEXT1:
7710   case OP_VEXT2:
7711   case OP_VEXT3:
7712     return DAG.getNode(ARMISD::VEXT, dl, VT,
7713                        OpLHS, OpRHS,
7714                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7715   case OP_VUZPL:
7716   case OP_VUZPR:
7717     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7718                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7719   case OP_VZIPL:
7720   case OP_VZIPR:
7721     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7722                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7723   case OP_VTRNL:
7724   case OP_VTRNR:
7725     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7726                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7727   }
7728 }
7729 
7730 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7731                                        ArrayRef<int> ShuffleMask,
7732                                        SelectionDAG &DAG) {
7733   // Check to see if we can use the VTBL instruction.
7734   SDValue V1 = Op.getOperand(0);
7735   SDValue V2 = Op.getOperand(1);
7736   SDLoc DL(Op);
7737 
7738   SmallVector<SDValue, 8> VTBLMask;
7739   for (ArrayRef<int>::iterator
7740          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7741     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7742 
7743   if (V2.getNode()->isUndef())
7744     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7745                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7746 
7747   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7748                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7749 }
7750 
7751 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7752                                                       SelectionDAG &DAG) {
7753   SDLoc DL(Op);
7754   SDValue OpLHS = Op.getOperand(0);
7755   EVT VT = OpLHS.getValueType();
7756 
7757   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7758          "Expect an v8i16/v16i8 type");
7759   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7760   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7761   // extract the first 8 bytes into the top double word and the last 8 bytes
7762   // into the bottom double word. The v8i16 case is similar.
7763   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7764   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7765                      DAG.getConstant(ExtractNum, DL, MVT::i32));
7766 }
7767 
7768 static EVT getVectorTyFromPredicateVector(EVT VT) {
7769   switch (VT.getSimpleVT().SimpleTy) {
7770   case MVT::v4i1:
7771     return MVT::v4i32;
7772   case MVT::v8i1:
7773     return MVT::v8i16;
7774   case MVT::v16i1:
7775     return MVT::v16i8;
7776   default:
7777     llvm_unreachable("Unexpected vector predicate type");
7778   }
7779 }
7780 
7781 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7782                                     SelectionDAG &DAG) {
7783   // Converting from boolean predicates to integers involves creating a vector
7784   // of all ones or all zeroes and selecting the lanes based upon the real
7785   // predicate.
7786   SDValue AllOnes =
7787       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7788   AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7789 
7790   SDValue AllZeroes =
7791       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7792   AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7793 
7794   // Get full vector type from predicate type
7795   EVT NewVT = getVectorTyFromPredicateVector(VT);
7796 
7797   SDValue RecastV1;
7798   // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7799   // this to a v16i1. This cannot be done with an ordinary bitcast because the
7800   // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7801   // since we know in hardware the sizes are really the same.
7802   if (VT != MVT::v16i1)
7803     RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7804   else
7805     RecastV1 = Pred;
7806 
7807   // Select either all ones or zeroes depending upon the real predicate bits.
7808   SDValue PredAsVector =
7809       DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7810 
7811   // Recast our new predicate-as-integer v16i8 vector into something
7812   // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7813   return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7814 }
7815 
7816 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7817                                       const ARMSubtarget *ST) {
7818   EVT VT = Op.getValueType();
7819   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7820   ArrayRef<int> ShuffleMask = SVN->getMask();
7821 
7822   assert(ST->hasMVEIntegerOps() &&
7823          "No support for vector shuffle of boolean predicates");
7824 
7825   SDValue V1 = Op.getOperand(0);
7826   SDLoc dl(Op);
7827   if (isReverseMask(ShuffleMask, VT)) {
7828     SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7829     SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7830     SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7831                               DAG.getConstant(16, dl, MVT::i32));
7832     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7833   }
7834 
7835   // Until we can come up with optimised cases for every single vector
7836   // shuffle in existence we have chosen the least painful strategy. This is
7837   // to essentially promote the boolean predicate to a 8-bit integer, where
7838   // each predicate represents a byte. Then we fall back on a normal integer
7839   // vector shuffle and convert the result back into a predicate vector. In
7840   // many cases the generated code might be even better than scalar code
7841   // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7842   // fields in a register into 8 other arbitrary 2-bit fields!
7843   SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7844   EVT NewVT = PredAsVector.getValueType();
7845 
7846   // Do the shuffle!
7847   SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7848                                           DAG.getUNDEF(NewVT), ShuffleMask);
7849 
7850   // Now return the result of comparing the shuffled vector with zero,
7851   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7852   return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7853                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7854 }
7855 
7856 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
7857                                             ArrayRef<int> ShuffleMask,
7858                                             SelectionDAG &DAG) {
7859   // Attempt to lower the vector shuffle using as many whole register movs as
7860   // possible. This is useful for types smaller than 32bits, which would
7861   // often otherwise become a series for grp movs.
7862   SDLoc dl(Op);
7863   EVT VT = Op.getValueType();
7864   if (VT.getScalarSizeInBits() >= 32)
7865     return SDValue();
7866 
7867   assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
7868          "Unexpected vector type");
7869   int NumElts = VT.getVectorNumElements();
7870   int QuarterSize = NumElts / 4;
7871   // The four final parts of the vector, as i32's
7872   SDValue Parts[4];
7873 
7874   // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
7875   // <u,u,u,u>), returning the vmov lane index
7876   auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
7877     // Detect which mov lane this would be from the first non-undef element.
7878     int MovIdx = -1;
7879     for (int i = 0; i < Length; i++) {
7880       if (ShuffleMask[Start + i] >= 0) {
7881         if (ShuffleMask[Start + i] % Length != i)
7882           return -1;
7883         MovIdx = ShuffleMask[Start + i] / Length;
7884         break;
7885       }
7886     }
7887     // If all items are undef, leave this for other combines
7888     if (MovIdx == -1)
7889       return -1;
7890     // Check the remaining values are the correct part of the same mov
7891     for (int i = 1; i < Length; i++) {
7892       if (ShuffleMask[Start + i] >= 0 &&
7893           (ShuffleMask[Start + i] / Length != MovIdx ||
7894            ShuffleMask[Start + i] % Length != i))
7895         return -1;
7896     }
7897     return MovIdx;
7898   };
7899 
7900   for (int Part = 0; Part < 4; ++Part) {
7901     // Does this part look like a mov
7902     int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
7903     if (Elt != -1) {
7904       SDValue Input = Op->getOperand(0);
7905       if (Elt >= 4) {
7906         Input = Op->getOperand(1);
7907         Elt -= 4;
7908       }
7909       SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input);
7910       Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast,
7911                                 DAG.getConstant(Elt, dl, MVT::i32));
7912     }
7913   }
7914 
7915   // Nothing interesting found, just return
7916   if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
7917     return SDValue();
7918 
7919   // The other parts need to be built with the old shuffle vector, cast to a
7920   // v4i32 and extract_vector_elts
7921   if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
7922     SmallVector<int, 16> NewShuffleMask;
7923     for (int Part = 0; Part < 4; ++Part)
7924       for (int i = 0; i < QuarterSize; i++)
7925         NewShuffleMask.push_back(
7926             Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
7927     SDValue NewShuffle = DAG.getVectorShuffle(
7928         VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
7929     SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle);
7930 
7931     for (int Part = 0; Part < 4; ++Part)
7932       if (!Parts[Part])
7933         Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7934                                   BitCast, DAG.getConstant(Part, dl, MVT::i32));
7935   }
7936   // Build a vector out of the various parts and bitcast it back to the original
7937   // type.
7938   SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts);
7939   return DAG.getBitcast(VT, NewVec);
7940 }
7941 
7942 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7943                                    const ARMSubtarget *ST) {
7944   SDValue V1 = Op.getOperand(0);
7945   SDValue V2 = Op.getOperand(1);
7946   SDLoc dl(Op);
7947   EVT VT = Op.getValueType();
7948   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7949   unsigned EltSize = VT.getScalarSizeInBits();
7950 
7951   if (ST->hasMVEIntegerOps() && EltSize == 1)
7952     return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7953 
7954   // Convert shuffles that are directly supported on NEON to target-specific
7955   // DAG nodes, instead of keeping them as shuffles and matching them again
7956   // during code selection.  This is more efficient and avoids the possibility
7957   // of inconsistencies between legalization and selection.
7958   // FIXME: floating-point vectors should be canonicalized to integer vectors
7959   // of the same time so that they get CSEd properly.
7960   ArrayRef<int> ShuffleMask = SVN->getMask();
7961 
7962   if (EltSize <= 32) {
7963     if (SVN->isSplat()) {
7964       int Lane = SVN->getSplatIndex();
7965       // If this is undef splat, generate it via "just" vdup, if possible.
7966       if (Lane == -1) Lane = 0;
7967 
7968       // Test if V1 is a SCALAR_TO_VECTOR.
7969       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7970         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7971       }
7972       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7973       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7974       // reaches it).
7975       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7976           !isa<ConstantSDNode>(V1.getOperand(0))) {
7977         bool IsScalarToVector = true;
7978         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7979           if (!V1.getOperand(i).isUndef()) {
7980             IsScalarToVector = false;
7981             break;
7982           }
7983         if (IsScalarToVector)
7984           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7985       }
7986       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7987                          DAG.getConstant(Lane, dl, MVT::i32));
7988     }
7989 
7990     bool ReverseVEXT = false;
7991     unsigned Imm = 0;
7992     if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7993       if (ReverseVEXT)
7994         std::swap(V1, V2);
7995       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7996                          DAG.getConstant(Imm, dl, MVT::i32));
7997     }
7998 
7999     if (isVREVMask(ShuffleMask, VT, 64))
8000       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8001     if (isVREVMask(ShuffleMask, VT, 32))
8002       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8003     if (isVREVMask(ShuffleMask, VT, 16))
8004       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8005 
8006     if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8007       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8008                          DAG.getConstant(Imm, dl, MVT::i32));
8009     }
8010 
8011     // Check for Neon shuffles that modify both input vectors in place.
8012     // If both results are used, i.e., if there are two shuffles with the same
8013     // source operands and with masks corresponding to both results of one of
8014     // these operations, DAG memoization will ensure that a single node is
8015     // used for both shuffles.
8016     unsigned WhichResult = 0;
8017     bool isV_UNDEF = false;
8018     if (ST->hasNEON()) {
8019       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8020               ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8021         if (isV_UNDEF)
8022           V2 = V1;
8023         return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8024             .getValue(WhichResult);
8025       }
8026     }
8027     if (ST->hasMVEIntegerOps()) {
8028       if (isVMOVNMask(ShuffleMask, VT, 0))
8029         return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8030                            DAG.getConstant(0, dl, MVT::i32));
8031       if (isVMOVNMask(ShuffleMask, VT, 1))
8032         return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8033                            DAG.getConstant(1, dl, MVT::i32));
8034     }
8035 
8036     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8037     // shuffles that produce a result larger than their operands with:
8038     //   shuffle(concat(v1, undef), concat(v2, undef))
8039     // ->
8040     //   shuffle(concat(v1, v2), undef)
8041     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8042     //
8043     // This is useful in the general case, but there are special cases where
8044     // native shuffles produce larger results: the two-result ops.
8045     //
8046     // Look through the concat when lowering them:
8047     //   shuffle(concat(v1, v2), undef)
8048     // ->
8049     //   concat(VZIP(v1, v2):0, :1)
8050     //
8051     if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8052       SDValue SubV1 = V1->getOperand(0);
8053       SDValue SubV2 = V1->getOperand(1);
8054       EVT SubVT = SubV1.getValueType();
8055 
8056       // We expect these to have been canonicalized to -1.
8057       assert(llvm::all_of(ShuffleMask, [&](int i) {
8058         return i < (int)VT.getVectorNumElements();
8059       }) && "Unexpected shuffle index into UNDEF operand!");
8060 
8061       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8062               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8063         if (isV_UNDEF)
8064           SubV2 = SubV1;
8065         assert((WhichResult == 0) &&
8066                "In-place shuffle of concat can only have one result!");
8067         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8068                                   SubV1, SubV2);
8069         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8070                            Res.getValue(1));
8071       }
8072     }
8073   }
8074 
8075   // If the shuffle is not directly supported and it has 4 elements, use
8076   // the PerfectShuffle-generated table to synthesize it from other shuffles.
8077   unsigned NumElts = VT.getVectorNumElements();
8078   if (NumElts == 4) {
8079     unsigned PFIndexes[4];
8080     for (unsigned i = 0; i != 4; ++i) {
8081       if (ShuffleMask[i] < 0)
8082         PFIndexes[i] = 8;
8083       else
8084         PFIndexes[i] = ShuffleMask[i];
8085     }
8086 
8087     // Compute the index in the perfect shuffle table.
8088     unsigned PFTableIndex =
8089       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8090     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8091     unsigned Cost = (PFEntry >> 30);
8092 
8093     if (Cost <= 4) {
8094       if (ST->hasNEON())
8095         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8096       else if (isLegalMVEShuffleOp(PFEntry)) {
8097         unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8098         unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8099         unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8100         unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8101         if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8102           return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8103       }
8104     }
8105   }
8106 
8107   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8108   if (EltSize >= 32) {
8109     // Do the expansion with floating-point types, since that is what the VFP
8110     // registers are defined to use, and since i64 is not legal.
8111     EVT EltVT = EVT::getFloatingPointVT(EltSize);
8112     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8113     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8114     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8115     SmallVector<SDValue, 8> Ops;
8116     for (unsigned i = 0; i < NumElts; ++i) {
8117       if (ShuffleMask[i] < 0)
8118         Ops.push_back(DAG.getUNDEF(EltVT));
8119       else
8120         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8121                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
8122                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8123                                                   dl, MVT::i32)));
8124     }
8125     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8126     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8127   }
8128 
8129   if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
8130     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
8131 
8132   if (ST->hasNEON() && VT == MVT::v8i8)
8133     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8134       return NewOp;
8135 
8136   if (ST->hasMVEIntegerOps())
8137     if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8138       return NewOp;
8139 
8140   return SDValue();
8141 }
8142 
8143 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8144                                          const ARMSubtarget *ST) {
8145   EVT VecVT = Op.getOperand(0).getValueType();
8146   SDLoc dl(Op);
8147 
8148   assert(ST->hasMVEIntegerOps() &&
8149          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8150 
8151   SDValue Conv =
8152       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8153   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8154   unsigned LaneWidth =
8155       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8156   unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8157   SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8158                             Op.getOperand(1), DAG.getValueType(MVT::i1));
8159   SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8160                             DAG.getConstant(~Mask, dl, MVT::i32));
8161   return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8162 }
8163 
8164 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8165                                                   SelectionDAG &DAG) const {
8166   // INSERT_VECTOR_ELT is legal only for immediate indexes.
8167   SDValue Lane = Op.getOperand(2);
8168   if (!isa<ConstantSDNode>(Lane))
8169     return SDValue();
8170 
8171   SDValue Elt = Op.getOperand(1);
8172   EVT EltVT = Elt.getValueType();
8173 
8174   if (Subtarget->hasMVEIntegerOps() &&
8175       Op.getValueType().getScalarSizeInBits() == 1)
8176     return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8177 
8178   if (getTypeAction(*DAG.getContext(), EltVT) ==
8179       TargetLowering::TypePromoteFloat) {
8180     // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8181     // but the type system will try to do that if we don't intervene.
8182     // Reinterpret any such vector-element insertion as one with the
8183     // corresponding integer types.
8184 
8185     SDLoc dl(Op);
8186 
8187     EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8188     assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8189            TargetLowering::TypePromoteFloat);
8190 
8191     SDValue VecIn = Op.getOperand(0);
8192     EVT VecVT = VecIn.getValueType();
8193     EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8194                                   VecVT.getVectorNumElements());
8195 
8196     SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8197     SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8198     SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8199                                   IVecIn, IElt, Lane);
8200     return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8201   }
8202 
8203   return Op;
8204 }
8205 
8206 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8207                                           const ARMSubtarget *ST) {
8208   EVT VecVT = Op.getOperand(0).getValueType();
8209   SDLoc dl(Op);
8210 
8211   assert(ST->hasMVEIntegerOps() &&
8212          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8213 
8214   SDValue Conv =
8215       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8216   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8217   unsigned LaneWidth =
8218       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8219   SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8220                               DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8221   return Shift;
8222 }
8223 
8224 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8225                                        const ARMSubtarget *ST) {
8226   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8227   SDValue Lane = Op.getOperand(1);
8228   if (!isa<ConstantSDNode>(Lane))
8229     return SDValue();
8230 
8231   SDValue Vec = Op.getOperand(0);
8232   EVT VT = Vec.getValueType();
8233 
8234   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8235     return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8236 
8237   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8238     SDLoc dl(Op);
8239     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8240   }
8241 
8242   return Op;
8243 }
8244 
8245 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8246                                       const ARMSubtarget *ST) {
8247   SDValue V1 = Op.getOperand(0);
8248   SDValue V2 = Op.getOperand(1);
8249   SDLoc dl(Op);
8250   EVT VT = Op.getValueType();
8251   EVT Op1VT = V1.getValueType();
8252   EVT Op2VT = V2.getValueType();
8253   unsigned NumElts = VT.getVectorNumElements();
8254 
8255   assert(Op1VT == Op2VT && "Operand types don't match!");
8256   assert(VT.getScalarSizeInBits() == 1 &&
8257          "Unexpected custom CONCAT_VECTORS lowering");
8258   assert(ST->hasMVEIntegerOps() &&
8259          "CONCAT_VECTORS lowering only supported for MVE");
8260 
8261   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8262   SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8263 
8264   // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8265   // promoted to v8i16, etc.
8266 
8267   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8268 
8269   // Extract the vector elements from Op1 and Op2 one by one and truncate them
8270   // to be the right size for the destination. For example, if Op1 is v4i1 then
8271   // the promoted vector is v4i32. The result of concatentation gives a v8i1,
8272   // which when promoted is v8i16. That means each i32 element from Op1 needs
8273   // truncating to i16 and inserting in the result.
8274   EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8275   SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8276   auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8277     EVT NewVT = NewV.getValueType();
8278     EVT ConcatVT = ConVec.getValueType();
8279     for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8280       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8281                                 DAG.getIntPtrConstant(i, dl));
8282       ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8283                            DAG.getConstant(j, dl, MVT::i32));
8284     }
8285     return ConVec;
8286   };
8287   unsigned j = 0;
8288   ConVec = ExractInto(NewV1, ConVec, j);
8289   ConVec = ExractInto(NewV2, ConVec, j);
8290 
8291   // Now return the result of comparing the subvector with zero,
8292   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8293   return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8294                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8295 }
8296 
8297 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8298                                    const ARMSubtarget *ST) {
8299   EVT VT = Op->getValueType(0);
8300   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8301     return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8302 
8303   // The only time a CONCAT_VECTORS operation can have legal types is when
8304   // two 64-bit vectors are concatenated to a 128-bit vector.
8305   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8306          "unexpected CONCAT_VECTORS");
8307   SDLoc dl(Op);
8308   SDValue Val = DAG.getUNDEF(MVT::v2f64);
8309   SDValue Op0 = Op.getOperand(0);
8310   SDValue Op1 = Op.getOperand(1);
8311   if (!Op0.isUndef())
8312     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8313                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8314                       DAG.getIntPtrConstant(0, dl));
8315   if (!Op1.isUndef())
8316     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8317                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8318                       DAG.getIntPtrConstant(1, dl));
8319   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8320 }
8321 
8322 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8323                                       const ARMSubtarget *ST) {
8324   SDValue V1 = Op.getOperand(0);
8325   SDValue V2 = Op.getOperand(1);
8326   SDLoc dl(Op);
8327   EVT VT = Op.getValueType();
8328   EVT Op1VT = V1.getValueType();
8329   unsigned NumElts = VT.getVectorNumElements();
8330   unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8331 
8332   assert(VT.getScalarSizeInBits() == 1 &&
8333          "Unexpected custom EXTRACT_SUBVECTOR lowering");
8334   assert(ST->hasMVEIntegerOps() &&
8335          "EXTRACT_SUBVECTOR lowering only supported for MVE");
8336 
8337   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8338 
8339   // We now have Op1 promoted to a vector of integers, where v8i1 gets
8340   // promoted to v8i16, etc.
8341 
8342   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8343 
8344   EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8345   SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8346   for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8347     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8348                               DAG.getIntPtrConstant(i, dl));
8349     SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8350                          DAG.getConstant(j, dl, MVT::i32));
8351   }
8352 
8353   // Now return the result of comparing the subvector with zero,
8354   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8355   return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8356                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8357 }
8358 
8359 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8360 /// element has been zero/sign-extended, depending on the isSigned parameter,
8361 /// from an integer type half its size.
8362 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8363                                    bool isSigned) {
8364   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8365   EVT VT = N->getValueType(0);
8366   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8367     SDNode *BVN = N->getOperand(0).getNode();
8368     if (BVN->getValueType(0) != MVT::v4i32 ||
8369         BVN->getOpcode() != ISD::BUILD_VECTOR)
8370       return false;
8371     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8372     unsigned HiElt = 1 - LoElt;
8373     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8374     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8375     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8376     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8377     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8378       return false;
8379     if (isSigned) {
8380       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8381           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8382         return true;
8383     } else {
8384       if (Hi0->isNullValue() && Hi1->isNullValue())
8385         return true;
8386     }
8387     return false;
8388   }
8389 
8390   if (N->getOpcode() != ISD::BUILD_VECTOR)
8391     return false;
8392 
8393   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8394     SDNode *Elt = N->getOperand(i).getNode();
8395     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8396       unsigned EltSize = VT.getScalarSizeInBits();
8397       unsigned HalfSize = EltSize / 2;
8398       if (isSigned) {
8399         if (!isIntN(HalfSize, C->getSExtValue()))
8400           return false;
8401       } else {
8402         if (!isUIntN(HalfSize, C->getZExtValue()))
8403           return false;
8404       }
8405       continue;
8406     }
8407     return false;
8408   }
8409 
8410   return true;
8411 }
8412 
8413 /// isSignExtended - Check if a node is a vector value that is sign-extended
8414 /// or a constant BUILD_VECTOR with sign-extended elements.
8415 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8416   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8417     return true;
8418   if (isExtendedBUILD_VECTOR(N, DAG, true))
8419     return true;
8420   return false;
8421 }
8422 
8423 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8424 /// or a constant BUILD_VECTOR with zero-extended elements.
8425 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8426   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8427     return true;
8428   if (isExtendedBUILD_VECTOR(N, DAG, false))
8429     return true;
8430   return false;
8431 }
8432 
8433 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8434   if (OrigVT.getSizeInBits() >= 64)
8435     return OrigVT;
8436 
8437   assert(OrigVT.isSimple() && "Expecting a simple value type");
8438 
8439   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8440   switch (OrigSimpleTy) {
8441   default: llvm_unreachable("Unexpected Vector Type");
8442   case MVT::v2i8:
8443   case MVT::v2i16:
8444      return MVT::v2i32;
8445   case MVT::v4i8:
8446     return  MVT::v4i16;
8447   }
8448 }
8449 
8450 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8451 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8452 /// We insert the required extension here to get the vector to fill a D register.
8453 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8454                                             const EVT &OrigTy,
8455                                             const EVT &ExtTy,
8456                                             unsigned ExtOpcode) {
8457   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8458   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8459   // 64-bits we need to insert a new extension so that it will be 64-bits.
8460   assert(ExtTy.is128BitVector() && "Unexpected extension size");
8461   if (OrigTy.getSizeInBits() >= 64)
8462     return N;
8463 
8464   // Must extend size to at least 64 bits to be used as an operand for VMULL.
8465   EVT NewVT = getExtensionTo64Bits(OrigTy);
8466 
8467   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8468 }
8469 
8470 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8471 /// does not do any sign/zero extension. If the original vector is less
8472 /// than 64 bits, an appropriate extension will be added after the load to
8473 /// reach a total size of 64 bits. We have to add the extension separately
8474 /// because ARM does not have a sign/zero extending load for vectors.
8475 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8476   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8477 
8478   // The load already has the right type.
8479   if (ExtendedTy == LD->getMemoryVT())
8480     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8481                        LD->getBasePtr(), LD->getPointerInfo(),
8482                        LD->getAlignment(), LD->getMemOperand()->getFlags());
8483 
8484   // We need to create a zextload/sextload. We cannot just create a load
8485   // followed by a zext/zext node because LowerMUL is also run during normal
8486   // operation legalization where we can't create illegal types.
8487   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8488                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8489                         LD->getMemoryVT(), LD->getAlignment(),
8490                         LD->getMemOperand()->getFlags());
8491 }
8492 
8493 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8494 /// extending load, or BUILD_VECTOR with extended elements, return the
8495 /// unextended value. The unextended vector should be 64 bits so that it can
8496 /// be used as an operand to a VMULL instruction. If the original vector size
8497 /// before extension is less than 64 bits we add a an extension to resize
8498 /// the vector to 64 bits.
8499 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8500   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8501     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8502                                         N->getOperand(0)->getValueType(0),
8503                                         N->getValueType(0),
8504                                         N->getOpcode());
8505 
8506   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8507     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8508            "Expected extending load");
8509 
8510     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8511     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8512     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8513     SDValue extLoad =
8514         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8515     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8516 
8517     return newLoad;
8518   }
8519 
8520   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
8521   // have been legalized as a BITCAST from v4i32.
8522   if (N->getOpcode() == ISD::BITCAST) {
8523     SDNode *BVN = N->getOperand(0).getNode();
8524     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8525            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8526     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8527     return DAG.getBuildVector(
8528         MVT::v2i32, SDLoc(N),
8529         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8530   }
8531   // Construct a new BUILD_VECTOR with elements truncated to half the size.
8532   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8533   EVT VT = N->getValueType(0);
8534   unsigned EltSize = VT.getScalarSizeInBits() / 2;
8535   unsigned NumElts = VT.getVectorNumElements();
8536   MVT TruncVT = MVT::getIntegerVT(EltSize);
8537   SmallVector<SDValue, 8> Ops;
8538   SDLoc dl(N);
8539   for (unsigned i = 0; i != NumElts; ++i) {
8540     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8541     const APInt &CInt = C->getAPIntValue();
8542     // Element types smaller than 32 bits are not legal, so use i32 elements.
8543     // The values are implicitly truncated so sext vs. zext doesn't matter.
8544     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8545   }
8546   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8547 }
8548 
8549 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8550   unsigned Opcode = N->getOpcode();
8551   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8552     SDNode *N0 = N->getOperand(0).getNode();
8553     SDNode *N1 = N->getOperand(1).getNode();
8554     return N0->hasOneUse() && N1->hasOneUse() &&
8555       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8556   }
8557   return false;
8558 }
8559 
8560 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8561   unsigned Opcode = N->getOpcode();
8562   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8563     SDNode *N0 = N->getOperand(0).getNode();
8564     SDNode *N1 = N->getOperand(1).getNode();
8565     return N0->hasOneUse() && N1->hasOneUse() &&
8566       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8567   }
8568   return false;
8569 }
8570 
8571 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8572   // Multiplications are only custom-lowered for 128-bit vectors so that
8573   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
8574   EVT VT = Op.getValueType();
8575   assert(VT.is128BitVector() && VT.isInteger() &&
8576          "unexpected type for custom-lowering ISD::MUL");
8577   SDNode *N0 = Op.getOperand(0).getNode();
8578   SDNode *N1 = Op.getOperand(1).getNode();
8579   unsigned NewOpc = 0;
8580   bool isMLA = false;
8581   bool isN0SExt = isSignExtended(N0, DAG);
8582   bool isN1SExt = isSignExtended(N1, DAG);
8583   if (isN0SExt && isN1SExt)
8584     NewOpc = ARMISD::VMULLs;
8585   else {
8586     bool isN0ZExt = isZeroExtended(N0, DAG);
8587     bool isN1ZExt = isZeroExtended(N1, DAG);
8588     if (isN0ZExt && isN1ZExt)
8589       NewOpc = ARMISD::VMULLu;
8590     else if (isN1SExt || isN1ZExt) {
8591       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8592       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8593       if (isN1SExt && isAddSubSExt(N0, DAG)) {
8594         NewOpc = ARMISD::VMULLs;
8595         isMLA = true;
8596       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8597         NewOpc = ARMISD::VMULLu;
8598         isMLA = true;
8599       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8600         std::swap(N0, N1);
8601         NewOpc = ARMISD::VMULLu;
8602         isMLA = true;
8603       }
8604     }
8605 
8606     if (!NewOpc) {
8607       if (VT == MVT::v2i64)
8608         // Fall through to expand this.  It is not legal.
8609         return SDValue();
8610       else
8611         // Other vector multiplications are legal.
8612         return Op;
8613     }
8614   }
8615 
8616   // Legalize to a VMULL instruction.
8617   SDLoc DL(Op);
8618   SDValue Op0;
8619   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8620   if (!isMLA) {
8621     Op0 = SkipExtensionForVMULL(N0, DAG);
8622     assert(Op0.getValueType().is64BitVector() &&
8623            Op1.getValueType().is64BitVector() &&
8624            "unexpected types for extended operands to VMULL");
8625     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8626   }
8627 
8628   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8629   // isel lowering to take advantage of no-stall back to back vmul + vmla.
8630   //   vmull q0, d4, d6
8631   //   vmlal q0, d5, d6
8632   // is faster than
8633   //   vaddl q0, d4, d5
8634   //   vmovl q1, d6
8635   //   vmul  q0, q0, q1
8636   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8637   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8638   EVT Op1VT = Op1.getValueType();
8639   return DAG.getNode(N0->getOpcode(), DL, VT,
8640                      DAG.getNode(NewOpc, DL, VT,
8641                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8642                      DAG.getNode(NewOpc, DL, VT,
8643                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8644 }
8645 
8646 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8647                               SelectionDAG &DAG) {
8648   // TODO: Should this propagate fast-math-flags?
8649 
8650   // Convert to float
8651   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8652   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8653   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8654   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8655   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8656   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8657   // Get reciprocal estimate.
8658   // float4 recip = vrecpeq_f32(yf);
8659   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8660                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8661                    Y);
8662   // Because char has a smaller range than uchar, we can actually get away
8663   // without any newton steps.  This requires that we use a weird bias
8664   // of 0xb000, however (again, this has been exhaustively tested).
8665   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8666   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8667   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8668   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8669   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8670   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8671   // Convert back to short.
8672   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8673   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8674   return X;
8675 }
8676 
8677 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8678                                SelectionDAG &DAG) {
8679   // TODO: Should this propagate fast-math-flags?
8680 
8681   SDValue N2;
8682   // Convert to float.
8683   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8684   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8685   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8686   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8687   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8688   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8689 
8690   // Use reciprocal estimate and one refinement step.
8691   // float4 recip = vrecpeq_f32(yf);
8692   // recip *= vrecpsq_f32(yf, recip);
8693   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8694                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8695                    N1);
8696   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8697                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8698                    N1, N2);
8699   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8700   // Because short has a smaller range than ushort, we can actually get away
8701   // with only a single newton step.  This requires that we use a weird bias
8702   // of 89, however (again, this has been exhaustively tested).
8703   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8704   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8705   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8706   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8707   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8708   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8709   // Convert back to integer and return.
8710   // return vmovn_s32(vcvt_s32_f32(result));
8711   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8712   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8713   return N0;
8714 }
8715 
8716 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8717                          const ARMSubtarget *ST) {
8718   EVT VT = Op.getValueType();
8719   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8720          "unexpected type for custom-lowering ISD::SDIV");
8721 
8722   SDLoc dl(Op);
8723   SDValue N0 = Op.getOperand(0);
8724   SDValue N1 = Op.getOperand(1);
8725   SDValue N2, N3;
8726 
8727   if (VT == MVT::v8i8) {
8728     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8729     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8730 
8731     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8732                      DAG.getIntPtrConstant(4, dl));
8733     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8734                      DAG.getIntPtrConstant(4, dl));
8735     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8736                      DAG.getIntPtrConstant(0, dl));
8737     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8738                      DAG.getIntPtrConstant(0, dl));
8739 
8740     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8741     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8742 
8743     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8744     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8745 
8746     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8747     return N0;
8748   }
8749   return LowerSDIV_v4i16(N0, N1, dl, DAG);
8750 }
8751 
8752 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8753                          const ARMSubtarget *ST) {
8754   // TODO: Should this propagate fast-math-flags?
8755   EVT VT = Op.getValueType();
8756   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8757          "unexpected type for custom-lowering ISD::UDIV");
8758 
8759   SDLoc dl(Op);
8760   SDValue N0 = Op.getOperand(0);
8761   SDValue N1 = Op.getOperand(1);
8762   SDValue N2, N3;
8763 
8764   if (VT == MVT::v8i8) {
8765     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8766     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8767 
8768     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8769                      DAG.getIntPtrConstant(4, dl));
8770     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8771                      DAG.getIntPtrConstant(4, dl));
8772     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8773                      DAG.getIntPtrConstant(0, dl));
8774     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8775                      DAG.getIntPtrConstant(0, dl));
8776 
8777     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8778     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8779 
8780     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8781     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8782 
8783     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8784                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8785                                      MVT::i32),
8786                      N0);
8787     return N0;
8788   }
8789 
8790   // v4i16 sdiv ... Convert to float.
8791   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8792   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8793   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8794   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8795   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8796   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8797 
8798   // Use reciprocal estimate and two refinement steps.
8799   // float4 recip = vrecpeq_f32(yf);
8800   // recip *= vrecpsq_f32(yf, recip);
8801   // recip *= vrecpsq_f32(yf, recip);
8802   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8803                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8804                    BN1);
8805   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8806                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8807                    BN1, N2);
8808   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8809   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8810                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8811                    BN1, N2);
8812   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8813   // Simply multiplying by the reciprocal estimate can leave us a few ulps
8814   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8815   // and that it will never cause us to return an answer too large).
8816   // float4 result = as_float4(as_int4(xf*recip) + 2);
8817   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8818   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8819   N1 = DAG.getConstant(2, dl, MVT::v4i32);
8820   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8821   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8822   // Convert back to integer and return.
8823   // return vmovn_u32(vcvt_s32_f32(result));
8824   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8825   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8826   return N0;
8827 }
8828 
8829 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8830   SDNode *N = Op.getNode();
8831   EVT VT = N->getValueType(0);
8832   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8833 
8834   SDValue Carry = Op.getOperand(2);
8835 
8836   SDLoc DL(Op);
8837 
8838   SDValue Result;
8839   if (Op.getOpcode() == ISD::ADDCARRY) {
8840     // This converts the boolean value carry into the carry flag.
8841     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8842 
8843     // Do the addition proper using the carry flag we wanted.
8844     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8845                          Op.getOperand(1), Carry);
8846 
8847     // Now convert the carry flag into a boolean value.
8848     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8849   } else {
8850     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8851     // have to invert the carry first.
8852     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8853                         DAG.getConstant(1, DL, MVT::i32), Carry);
8854     // This converts the boolean value carry into the carry flag.
8855     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8856 
8857     // Do the subtraction proper using the carry flag we wanted.
8858     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8859                          Op.getOperand(1), Carry);
8860 
8861     // Now convert the carry flag into a boolean value.
8862     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8863     // But the carry returned by ARMISD::SUBE is not a borrow as expected
8864     // by ISD::SUBCARRY, so compute 1 - C.
8865     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8866                         DAG.getConstant(1, DL, MVT::i32), Carry);
8867   }
8868 
8869   // Return both values.
8870   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8871 }
8872 
8873 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8874   assert(Subtarget->isTargetDarwin());
8875 
8876   // For iOS, we want to call an alternative entry point: __sincos_stret,
8877   // return values are passed via sret.
8878   SDLoc dl(Op);
8879   SDValue Arg = Op.getOperand(0);
8880   EVT ArgVT = Arg.getValueType();
8881   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8882   auto PtrVT = getPointerTy(DAG.getDataLayout());
8883 
8884   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8886 
8887   // Pair of floats / doubles used to pass the result.
8888   Type *RetTy = StructType::get(ArgTy, ArgTy);
8889   auto &DL = DAG.getDataLayout();
8890 
8891   ArgListTy Args;
8892   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8893   SDValue SRet;
8894   if (ShouldUseSRet) {
8895     // Create stack object for sret.
8896     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8897     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8898     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8899     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8900 
8901     ArgListEntry Entry;
8902     Entry.Node = SRet;
8903     Entry.Ty = RetTy->getPointerTo();
8904     Entry.IsSExt = false;
8905     Entry.IsZExt = false;
8906     Entry.IsSRet = true;
8907     Args.push_back(Entry);
8908     RetTy = Type::getVoidTy(*DAG.getContext());
8909   }
8910 
8911   ArgListEntry Entry;
8912   Entry.Node = Arg;
8913   Entry.Ty = ArgTy;
8914   Entry.IsSExt = false;
8915   Entry.IsZExt = false;
8916   Args.push_back(Entry);
8917 
8918   RTLIB::Libcall LC =
8919       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8920   const char *LibcallName = getLibcallName(LC);
8921   CallingConv::ID CC = getLibcallCallingConv(LC);
8922   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8923 
8924   TargetLowering::CallLoweringInfo CLI(DAG);
8925   CLI.setDebugLoc(dl)
8926       .setChain(DAG.getEntryNode())
8927       .setCallee(CC, RetTy, Callee, std::move(Args))
8928       .setDiscardResult(ShouldUseSRet);
8929   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8930 
8931   if (!ShouldUseSRet)
8932     return CallResult.first;
8933 
8934   SDValue LoadSin =
8935       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8936 
8937   // Address of cos field.
8938   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8939                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8940   SDValue LoadCos =
8941       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8942 
8943   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8944   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8945                      LoadSin.getValue(0), LoadCos.getValue(0));
8946 }
8947 
8948 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8949                                                   bool Signed,
8950                                                   SDValue &Chain) const {
8951   EVT VT = Op.getValueType();
8952   assert((VT == MVT::i32 || VT == MVT::i64) &&
8953          "unexpected type for custom lowering DIV");
8954   SDLoc dl(Op);
8955 
8956   const auto &DL = DAG.getDataLayout();
8957   const auto &TLI = DAG.getTargetLoweringInfo();
8958 
8959   const char *Name = nullptr;
8960   if (Signed)
8961     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8962   else
8963     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8964 
8965   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8966 
8967   ARMTargetLowering::ArgListTy Args;
8968 
8969   for (auto AI : {1, 0}) {
8970     ArgListEntry Arg;
8971     Arg.Node = Op.getOperand(AI);
8972     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8973     Args.push_back(Arg);
8974   }
8975 
8976   CallLoweringInfo CLI(DAG);
8977   CLI.setDebugLoc(dl)
8978     .setChain(Chain)
8979     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8980                ES, std::move(Args));
8981 
8982   return LowerCallTo(CLI).first;
8983 }
8984 
8985 // This is a code size optimisation: return the original SDIV node to
8986 // DAGCombiner when we don't want to expand SDIV into a sequence of
8987 // instructions, and an empty node otherwise which will cause the
8988 // SDIV to be expanded in DAGCombine.
8989 SDValue
8990 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8991                                  SelectionDAG &DAG,
8992                                  SmallVectorImpl<SDNode *> &Created) const {
8993   // TODO: Support SREM
8994   if (N->getOpcode() != ISD::SDIV)
8995     return SDValue();
8996 
8997   const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8998   const bool MinSize = ST.hasMinSize();
8999   const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9000                                       : ST.hasDivideInARMMode();
9001 
9002   // Don't touch vector types; rewriting this may lead to scalarizing
9003   // the int divs.
9004   if (N->getOperand(0).getValueType().isVector())
9005     return SDValue();
9006 
9007   // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9008   // hwdiv support for this to be really profitable.
9009   if (!(MinSize && HasDivide))
9010     return SDValue();
9011 
9012   // ARM mode is a bit simpler than Thumb: we can handle large power
9013   // of 2 immediates with 1 mov instruction; no further checks required,
9014   // just return the sdiv node.
9015   if (!ST.isThumb())
9016     return SDValue(N, 0);
9017 
9018   // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9019   // and thus lose the code size benefits of a MOVS that requires only 2.
9020   // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9021   // but as it's doing exactly this, it's not worth the trouble to get TTI.
9022   if (Divisor.sgt(128))
9023     return SDValue();
9024 
9025   return SDValue(N, 0);
9026 }
9027 
9028 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9029                                             bool Signed) const {
9030   assert(Op.getValueType() == MVT::i32 &&
9031          "unexpected type for custom lowering DIV");
9032   SDLoc dl(Op);
9033 
9034   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9035                                DAG.getEntryNode(), Op.getOperand(1));
9036 
9037   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9038 }
9039 
9040 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9041   SDLoc DL(N);
9042   SDValue Op = N->getOperand(1);
9043   if (N->getValueType(0) == MVT::i32)
9044     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9045   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9046                            DAG.getConstant(0, DL, MVT::i32));
9047   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9048                            DAG.getConstant(1, DL, MVT::i32));
9049   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9050                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9051 }
9052 
9053 void ARMTargetLowering::ExpandDIV_Windows(
9054     SDValue Op, SelectionDAG &DAG, bool Signed,
9055     SmallVectorImpl<SDValue> &Results) const {
9056   const auto &DL = DAG.getDataLayout();
9057   const auto &TLI = DAG.getTargetLoweringInfo();
9058 
9059   assert(Op.getValueType() == MVT::i64 &&
9060          "unexpected type for custom lowering DIV");
9061   SDLoc dl(Op);
9062 
9063   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9064 
9065   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9066 
9067   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9068   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9069                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
9070   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9071 
9072   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9073 }
9074 
9075 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9076   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9077   EVT MemVT = LD->getMemoryVT();
9078   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9079          "Expected a predicate type!");
9080   assert(MemVT == Op.getValueType());
9081   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9082          "Expected a non-extending load");
9083   assert(LD->isUnindexed() && "Expected a unindexed load");
9084 
9085   // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
9086   // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9087   // need to make sure that 8/4 bits are actually loaded into the correct
9088   // place, which means loading the value and then shuffling the values into
9089   // the bottom bits of the predicate.
9090   // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9091   // for BE).
9092 
9093   SDLoc dl(Op);
9094   SDValue Load = DAG.getExtLoad(
9095       ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9096       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9097       LD->getMemOperand());
9098   SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load);
9099   if (MemVT != MVT::v16i1)
9100     Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9101                        DAG.getConstant(0, dl, MVT::i32));
9102   return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9103 }
9104 
9105 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9106                                   SelectionDAG &DAG) const {
9107   LoadSDNode *LD = cast<LoadSDNode>(N);
9108   EVT MemVT = LD->getMemoryVT();
9109   assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
9110 
9111   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9112       !Subtarget->isThumb1Only() && LD->isVolatile()) {
9113     SDLoc dl(N);
9114     SDValue Result = DAG.getMemIntrinsicNode(
9115         ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
9116         {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
9117     SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9118     SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9119     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
9120     Results.append({Pair, Result.getValue(2)});
9121   }
9122 }
9123 
9124 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
9125   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9126   EVT MemVT = ST->getMemoryVT();
9127   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9128          "Expected a predicate type!");
9129   assert(MemVT == ST->getValue().getValueType());
9130   assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9131   assert(ST->isUnindexed() && "Expected a unindexed store");
9132 
9133   // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
9134   // unset and a scalar store.
9135   SDLoc dl(Op);
9136   SDValue Build = ST->getValue();
9137   if (MemVT != MVT::v16i1) {
9138     SmallVector<SDValue, 16> Ops;
9139     for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++)
9140       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9141                                 DAG.getConstant(I, dl, MVT::i32)));
9142     for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9143       Ops.push_back(DAG.getUNDEF(MVT::i32));
9144     Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9145   }
9146   SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9147   return DAG.getTruncStore(
9148       ST->getChain(), dl, GRP, ST->getBasePtr(),
9149       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9150       ST->getMemOperand());
9151 }
9152 
9153 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG,
9154                           const ARMSubtarget *Subtarget) {
9155   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9156   EVT MemVT = ST->getMemoryVT();
9157   assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
9158 
9159   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9160       !Subtarget->isThumb1Only() && ST->isVolatile()) {
9161     SDNode *N = Op.getNode();
9162     SDLoc dl(N);
9163 
9164     SDValue Lo = DAG.getNode(
9165         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9166         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
9167                               MVT::i32));
9168     SDValue Hi = DAG.getNode(
9169         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9170         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
9171                               MVT::i32));
9172 
9173     return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
9174                                    {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9175                                    MemVT, ST->getMemOperand());
9176   } else if (Subtarget->hasMVEIntegerOps() &&
9177              ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9178                MemVT == MVT::v16i1))) {
9179     return LowerPredicateStore(Op, DAG);
9180   }
9181 
9182   return SDValue();
9183 }
9184 
9185 static bool isZeroVector(SDValue N) {
9186   return (ISD::isBuildVectorAllZeros(N.getNode()) ||
9187           (N->getOpcode() == ARMISD::VMOVIMM &&
9188            isNullConstant(N->getOperand(0))));
9189 }
9190 
9191 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
9192   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
9193   MVT VT = Op.getSimpleValueType();
9194   SDValue Mask = N->getMask();
9195   SDValue PassThru = N->getPassThru();
9196   SDLoc dl(Op);
9197 
9198   if (isZeroVector(PassThru))
9199     return Op;
9200 
9201   // MVE Masked loads use zero as the passthru value. Here we convert undef to
9202   // zero too, and other values are lowered to a select.
9203   SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
9204                                 DAG.getTargetConstant(0, dl, MVT::i32));
9205   SDValue NewLoad = DAG.getMaskedLoad(
9206       VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
9207       N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
9208       N->getExtensionType(), N->isExpandingLoad());
9209   SDValue Combo = NewLoad;
9210   bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9211                              PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9212                             isZeroVector(PassThru->getOperand(0));
9213   if (!PassThru.isUndef() && !PassThruIsCastZero)
9214     Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
9215   return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
9216 }
9217 
9218 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
9219   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
9220     // Acquire/Release load/store is not legal for targets without a dmb or
9221     // equivalent available.
9222     return SDValue();
9223 
9224   // Monotonic load/store is legal for all targets.
9225   return Op;
9226 }
9227 
9228 static void ReplaceREADCYCLECOUNTER(SDNode *N,
9229                                     SmallVectorImpl<SDValue> &Results,
9230                                     SelectionDAG &DAG,
9231                                     const ARMSubtarget *Subtarget) {
9232   SDLoc DL(N);
9233   // Under Power Management extensions, the cycle-count is:
9234   //    mrc p15, #0, <Rt>, c9, c13, #0
9235   SDValue Ops[] = { N->getOperand(0), // Chain
9236                     DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
9237                     DAG.getTargetConstant(15, DL, MVT::i32),
9238                     DAG.getTargetConstant(0, DL, MVT::i32),
9239                     DAG.getTargetConstant(9, DL, MVT::i32),
9240                     DAG.getTargetConstant(13, DL, MVT::i32),
9241                     DAG.getTargetConstant(0, DL, MVT::i32)
9242   };
9243 
9244   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
9245                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
9246   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
9247                                 DAG.getConstant(0, DL, MVT::i32)));
9248   Results.push_back(Cycles32.getValue(1));
9249 }
9250 
9251 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
9252   SDLoc dl(V.getNode());
9253   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
9254   SDValue VHi = DAG.getAnyExtOrTrunc(
9255       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
9256       dl, MVT::i32);
9257   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9258   if (isBigEndian)
9259     std::swap (VLo, VHi);
9260   SDValue RegClass =
9261       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
9262   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
9263   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
9264   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
9265   return SDValue(
9266       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
9267 }
9268 
9269 static void ReplaceCMP_SWAP_64Results(SDNode *N,
9270                                        SmallVectorImpl<SDValue> & Results,
9271                                        SelectionDAG &DAG) {
9272   assert(N->getValueType(0) == MVT::i64 &&
9273          "AtomicCmpSwap on types less than 64 should be legal");
9274   SDValue Ops[] = {N->getOperand(1),
9275                    createGPRPairNode(DAG, N->getOperand(2)),
9276                    createGPRPairNode(DAG, N->getOperand(3)),
9277                    N->getOperand(0)};
9278   SDNode *CmpSwap = DAG.getMachineNode(
9279       ARM::CMP_SWAP_64, SDLoc(N),
9280       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
9281 
9282   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
9283   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
9284 
9285   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9286 
9287   SDValue Lo =
9288       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
9289                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9290   SDValue Hi =
9291       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
9292                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9293   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
9294   Results.push_back(SDValue(CmpSwap, 2));
9295 }
9296 
9297 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
9298   SDLoc dl(Op);
9299   EVT VT = Op.getValueType();
9300   SDValue Chain = Op.getOperand(0);
9301   SDValue LHS = Op.getOperand(1);
9302   SDValue RHS = Op.getOperand(2);
9303   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
9304   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
9305 
9306   // If we don't have instructions of this float type then soften to a libcall
9307   // and use SETCC instead.
9308   if (isUnsupportedFloatingType(LHS.getValueType())) {
9309     DAG.getTargetLoweringInfo().softenSetCCOperands(
9310       DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling);
9311     if (!RHS.getNode()) {
9312       RHS = DAG.getConstant(0, dl, LHS.getValueType());
9313       CC = ISD::SETNE;
9314     }
9315     SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
9316                                  DAG.getCondCode(CC));
9317     return DAG.getMergeValues({Result, Chain}, dl);
9318   }
9319 
9320   ARMCC::CondCodes CondCode, CondCode2;
9321   FPCCToARMCC(CC, CondCode, CondCode2);
9322 
9323   // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit
9324   // in CMPFP and CMPFPE, but instead it should be made explicit by these
9325   // instructions using a chain instead of glue. This would also fix the problem
9326   // here (and also in LowerSELECT_CC) where we generate two comparisons when
9327   // CondCode2 != AL.
9328   SDValue True = DAG.getConstant(1, dl, VT);
9329   SDValue False =  DAG.getConstant(0, dl, VT);
9330   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
9331   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
9332   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9333   SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG);
9334   if (CondCode2 != ARMCC::AL) {
9335     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
9336     Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9337     Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG);
9338   }
9339   return DAG.getMergeValues({Result, Chain}, dl);
9340 }
9341 
9342 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9343   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
9344   switch (Op.getOpcode()) {
9345   default: llvm_unreachable("Don't know how to custom lower this!");
9346   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
9347   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9348   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
9349   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9350   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9351   case ISD::SELECT:        return LowerSELECT(Op, DAG);
9352   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
9353   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
9354   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
9355   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
9356   case ISD::VASTART:       return LowerVASTART(Op, DAG);
9357   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
9358   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
9359   case ISD::SINT_TO_FP:
9360   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
9361   case ISD::STRICT_FP_TO_SINT:
9362   case ISD::STRICT_FP_TO_UINT:
9363   case ISD::FP_TO_SINT:
9364   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
9365   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
9366   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
9367   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
9368   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
9369   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
9370   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
9371   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
9372   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
9373                                                                Subtarget);
9374   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
9375   case ISD::SHL:
9376   case ISD::SRL:
9377   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
9378   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
9379   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
9380   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
9381   case ISD::SRL_PARTS:
9382   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
9383   case ISD::CTTZ:
9384   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
9385   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
9386   case ISD::SETCC:         return LowerVSETCC(Op, DAG, Subtarget);
9387   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
9388   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
9389   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
9390   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
9391   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
9392   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9393   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
9394   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
9395   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
9396   case ISD::MUL:           return LowerMUL(Op, DAG);
9397   case ISD::SDIV:
9398     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9399       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
9400     return LowerSDIV(Op, DAG, Subtarget);
9401   case ISD::UDIV:
9402     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9403       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
9404     return LowerUDIV(Op, DAG, Subtarget);
9405   case ISD::ADDCARRY:
9406   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
9407   case ISD::SADDO:
9408   case ISD::SSUBO:
9409     return LowerSignedALUO(Op, DAG);
9410   case ISD::UADDO:
9411   case ISD::USUBO:
9412     return LowerUnsignedALUO(Op, DAG);
9413   case ISD::SADDSAT:
9414   case ISD::SSUBSAT:
9415     return LowerSADDSUBSAT(Op, DAG, Subtarget);
9416   case ISD::LOAD:
9417     return LowerPredicateLoad(Op, DAG);
9418   case ISD::STORE:
9419     return LowerSTORE(Op, DAG, Subtarget);
9420   case ISD::MLOAD:
9421     return LowerMLOAD(Op, DAG);
9422   case ISD::ATOMIC_LOAD:
9423   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
9424   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
9425   case ISD::SDIVREM:
9426   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
9427   case ISD::DYNAMIC_STACKALLOC:
9428     if (Subtarget->isTargetWindows())
9429       return LowerDYNAMIC_STACKALLOC(Op, DAG);
9430     llvm_unreachable("Don't know how to custom lower this!");
9431   case ISD::STRICT_FP_ROUND:
9432   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
9433   case ISD::STRICT_FP_EXTEND:
9434   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9435   case ISD::STRICT_FSETCC:
9436   case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
9437   case ARMISD::WIN__DBZCHK: return SDValue();
9438   }
9439 }
9440 
9441 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9442                                  SelectionDAG &DAG) {
9443   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9444   unsigned Opc = 0;
9445   if (IntNo == Intrinsic::arm_smlald)
9446     Opc = ARMISD::SMLALD;
9447   else if (IntNo == Intrinsic::arm_smlaldx)
9448     Opc = ARMISD::SMLALDX;
9449   else if (IntNo == Intrinsic::arm_smlsld)
9450     Opc = ARMISD::SMLSLD;
9451   else if (IntNo == Intrinsic::arm_smlsldx)
9452     Opc = ARMISD::SMLSLDX;
9453   else
9454     return;
9455 
9456   SDLoc dl(N);
9457   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9458                            N->getOperand(3),
9459                            DAG.getConstant(0, dl, MVT::i32));
9460   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9461                            N->getOperand(3),
9462                            DAG.getConstant(1, dl, MVT::i32));
9463 
9464   SDValue LongMul = DAG.getNode(Opc, dl,
9465                                 DAG.getVTList(MVT::i32, MVT::i32),
9466                                 N->getOperand(1), N->getOperand(2),
9467                                 Lo, Hi);
9468   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
9469                                 LongMul.getValue(0), LongMul.getValue(1)));
9470 }
9471 
9472 /// ReplaceNodeResults - Replace the results of node with an illegal result
9473 /// type with new values built out of custom code.
9474 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9475                                            SmallVectorImpl<SDValue> &Results,
9476                                            SelectionDAG &DAG) const {
9477   SDValue Res;
9478   switch (N->getOpcode()) {
9479   default:
9480     llvm_unreachable("Don't know how to custom expand this!");
9481   case ISD::READ_REGISTER:
9482     ExpandREAD_REGISTER(N, Results, DAG);
9483     break;
9484   case ISD::BITCAST:
9485     Res = ExpandBITCAST(N, DAG, Subtarget);
9486     break;
9487   case ISD::SRL:
9488   case ISD::SRA:
9489   case ISD::SHL:
9490     Res = Expand64BitShift(N, DAG, Subtarget);
9491     break;
9492   case ISD::SREM:
9493   case ISD::UREM:
9494     Res = LowerREM(N, DAG);
9495     break;
9496   case ISD::SDIVREM:
9497   case ISD::UDIVREM:
9498     Res = LowerDivRem(SDValue(N, 0), DAG);
9499     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9500     Results.push_back(Res.getValue(0));
9501     Results.push_back(Res.getValue(1));
9502     return;
9503   case ISD::SADDSAT:
9504   case ISD::SSUBSAT:
9505     Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
9506     break;
9507   case ISD::READCYCLECOUNTER:
9508     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9509     return;
9510   case ISD::UDIV:
9511   case ISD::SDIV:
9512     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9513     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9514                              Results);
9515   case ISD::ATOMIC_CMP_SWAP:
9516     ReplaceCMP_SWAP_64Results(N, Results, DAG);
9517     return;
9518   case ISD::INTRINSIC_WO_CHAIN:
9519     return ReplaceLongIntrinsic(N, Results, DAG);
9520   case ISD::ABS:
9521      lowerABS(N, Results, DAG);
9522      return ;
9523   case ISD::LOAD:
9524     LowerLOAD(N, Results, DAG);
9525     break;
9526   }
9527   if (Res.getNode())
9528     Results.push_back(Res);
9529 }
9530 
9531 //===----------------------------------------------------------------------===//
9532 //                           ARM Scheduler Hooks
9533 //===----------------------------------------------------------------------===//
9534 
9535 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9536 /// registers the function context.
9537 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9538                                                MachineBasicBlock *MBB,
9539                                                MachineBasicBlock *DispatchBB,
9540                                                int FI) const {
9541   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9542          "ROPI/RWPI not currently supported with SjLj");
9543   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9544   DebugLoc dl = MI.getDebugLoc();
9545   MachineFunction *MF = MBB->getParent();
9546   MachineRegisterInfo *MRI = &MF->getRegInfo();
9547   MachineConstantPool *MCP = MF->getConstantPool();
9548   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9549   const Function &F = MF->getFunction();
9550 
9551   bool isThumb = Subtarget->isThumb();
9552   bool isThumb2 = Subtarget->isThumb2();
9553 
9554   unsigned PCLabelId = AFI->createPICLabelUId();
9555   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9556   ARMConstantPoolValue *CPV =
9557     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9558   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
9559 
9560   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9561                                            : &ARM::GPRRegClass;
9562 
9563   // Grab constant pool and fixed stack memory operands.
9564   MachineMemOperand *CPMMO =
9565       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9566                                MachineMemOperand::MOLoad, 4, Align(4));
9567 
9568   MachineMemOperand *FIMMOSt =
9569       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9570                                MachineMemOperand::MOStore, 4, Align(4));
9571 
9572   // Load the address of the dispatch MBB into the jump buffer.
9573   if (isThumb2) {
9574     // Incoming value: jbuf
9575     //   ldr.n  r5, LCPI1_1
9576     //   orr    r5, r5, #1
9577     //   add    r5, pc
9578     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
9579     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9580     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9581         .addConstantPoolIndex(CPI)
9582         .addMemOperand(CPMMO)
9583         .add(predOps(ARMCC::AL));
9584     // Set the low bit because of thumb mode.
9585     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9586     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9587         .addReg(NewVReg1, RegState::Kill)
9588         .addImm(0x01)
9589         .add(predOps(ARMCC::AL))
9590         .add(condCodeOp());
9591     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9592     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9593       .addReg(NewVReg2, RegState::Kill)
9594       .addImm(PCLabelId);
9595     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9596         .addReg(NewVReg3, RegState::Kill)
9597         .addFrameIndex(FI)
9598         .addImm(36) // &jbuf[1] :: pc
9599         .addMemOperand(FIMMOSt)
9600         .add(predOps(ARMCC::AL));
9601   } else if (isThumb) {
9602     // Incoming value: jbuf
9603     //   ldr.n  r1, LCPI1_4
9604     //   add    r1, pc
9605     //   mov    r2, #1
9606     //   orrs   r1, r2
9607     //   add    r2, $jbuf, #+4 ; &jbuf[1]
9608     //   str    r1, [r2]
9609     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9610     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9611         .addConstantPoolIndex(CPI)
9612         .addMemOperand(CPMMO)
9613         .add(predOps(ARMCC::AL));
9614     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9615     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9616       .addReg(NewVReg1, RegState::Kill)
9617       .addImm(PCLabelId);
9618     // Set the low bit because of thumb mode.
9619     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9620     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9621         .addReg(ARM::CPSR, RegState::Define)
9622         .addImm(1)
9623         .add(predOps(ARMCC::AL));
9624     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9625     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9626         .addReg(ARM::CPSR, RegState::Define)
9627         .addReg(NewVReg2, RegState::Kill)
9628         .addReg(NewVReg3, RegState::Kill)
9629         .add(predOps(ARMCC::AL));
9630     Register NewVReg5 = MRI->createVirtualRegister(TRC);
9631     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9632             .addFrameIndex(FI)
9633             .addImm(36); // &jbuf[1] :: pc
9634     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9635         .addReg(NewVReg4, RegState::Kill)
9636         .addReg(NewVReg5, RegState::Kill)
9637         .addImm(0)
9638         .addMemOperand(FIMMOSt)
9639         .add(predOps(ARMCC::AL));
9640   } else {
9641     // Incoming value: jbuf
9642     //   ldr  r1, LCPI1_1
9643     //   add  r1, pc, r1
9644     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
9645     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9646     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9647         .addConstantPoolIndex(CPI)
9648         .addImm(0)
9649         .addMemOperand(CPMMO)
9650         .add(predOps(ARMCC::AL));
9651     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9652     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9653         .addReg(NewVReg1, RegState::Kill)
9654         .addImm(PCLabelId)
9655         .add(predOps(ARMCC::AL));
9656     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9657         .addReg(NewVReg2, RegState::Kill)
9658         .addFrameIndex(FI)
9659         .addImm(36) // &jbuf[1] :: pc
9660         .addMemOperand(FIMMOSt)
9661         .add(predOps(ARMCC::AL));
9662   }
9663 }
9664 
9665 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9666                                               MachineBasicBlock *MBB) const {
9667   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9668   DebugLoc dl = MI.getDebugLoc();
9669   MachineFunction *MF = MBB->getParent();
9670   MachineRegisterInfo *MRI = &MF->getRegInfo();
9671   MachineFrameInfo &MFI = MF->getFrameInfo();
9672   int FI = MFI.getFunctionContextIndex();
9673 
9674   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9675                                                         : &ARM::GPRnopcRegClass;
9676 
9677   // Get a mapping of the call site numbers to all of the landing pads they're
9678   // associated with.
9679   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9680   unsigned MaxCSNum = 0;
9681   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9682        ++BB) {
9683     if (!BB->isEHPad()) continue;
9684 
9685     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9686     // pad.
9687     for (MachineBasicBlock::iterator
9688            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9689       if (!II->isEHLabel()) continue;
9690 
9691       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9692       if (!MF->hasCallSiteLandingPad(Sym)) continue;
9693 
9694       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9695       for (SmallVectorImpl<unsigned>::iterator
9696              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9697            CSI != CSE; ++CSI) {
9698         CallSiteNumToLPad[*CSI].push_back(&*BB);
9699         MaxCSNum = std::max(MaxCSNum, *CSI);
9700       }
9701       break;
9702     }
9703   }
9704 
9705   // Get an ordered list of the machine basic blocks for the jump table.
9706   std::vector<MachineBasicBlock*> LPadList;
9707   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9708   LPadList.reserve(CallSiteNumToLPad.size());
9709   for (unsigned I = 1; I <= MaxCSNum; ++I) {
9710     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9711     for (SmallVectorImpl<MachineBasicBlock*>::iterator
9712            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9713       LPadList.push_back(*II);
9714       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9715     }
9716   }
9717 
9718   assert(!LPadList.empty() &&
9719          "No landing pad destinations for the dispatch jump table!");
9720 
9721   // Create the jump table and associated information.
9722   MachineJumpTableInfo *JTI =
9723     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9724   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9725 
9726   // Create the MBBs for the dispatch code.
9727 
9728   // Shove the dispatch's address into the return slot in the function context.
9729   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9730   DispatchBB->setIsEHPad();
9731 
9732   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9733   unsigned trap_opcode;
9734   if (Subtarget->isThumb())
9735     trap_opcode = ARM::tTRAP;
9736   else
9737     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9738 
9739   BuildMI(TrapBB, dl, TII->get(trap_opcode));
9740   DispatchBB->addSuccessor(TrapBB);
9741 
9742   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9743   DispatchBB->addSuccessor(DispContBB);
9744 
9745   // Insert and MBBs.
9746   MF->insert(MF->end(), DispatchBB);
9747   MF->insert(MF->end(), DispContBB);
9748   MF->insert(MF->end(), TrapBB);
9749 
9750   // Insert code into the entry block that creates and registers the function
9751   // context.
9752   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9753 
9754   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9755       MachinePointerInfo::getFixedStack(*MF, FI),
9756       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4));
9757 
9758   MachineInstrBuilder MIB;
9759   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9760 
9761   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9762   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9763 
9764   // Add a register mask with no preserved registers.  This results in all
9765   // registers being marked as clobbered. This can't work if the dispatch block
9766   // is in a Thumb1 function and is linked with ARM code which uses the FP
9767   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9768   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9769 
9770   bool IsPositionIndependent = isPositionIndependent();
9771   unsigned NumLPads = LPadList.size();
9772   if (Subtarget->isThumb2()) {
9773     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9774     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9775         .addFrameIndex(FI)
9776         .addImm(4)
9777         .addMemOperand(FIMMOLd)
9778         .add(predOps(ARMCC::AL));
9779 
9780     if (NumLPads < 256) {
9781       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9782           .addReg(NewVReg1)
9783           .addImm(LPadList.size())
9784           .add(predOps(ARMCC::AL));
9785     } else {
9786       Register VReg1 = MRI->createVirtualRegister(TRC);
9787       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9788           .addImm(NumLPads & 0xFFFF)
9789           .add(predOps(ARMCC::AL));
9790 
9791       unsigned VReg2 = VReg1;
9792       if ((NumLPads & 0xFFFF0000) != 0) {
9793         VReg2 = MRI->createVirtualRegister(TRC);
9794         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9795             .addReg(VReg1)
9796             .addImm(NumLPads >> 16)
9797             .add(predOps(ARMCC::AL));
9798       }
9799 
9800       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9801           .addReg(NewVReg1)
9802           .addReg(VReg2)
9803           .add(predOps(ARMCC::AL));
9804     }
9805 
9806     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9807       .addMBB(TrapBB)
9808       .addImm(ARMCC::HI)
9809       .addReg(ARM::CPSR);
9810 
9811     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9812     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9813         .addJumpTableIndex(MJTI)
9814         .add(predOps(ARMCC::AL));
9815 
9816     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9817     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9818         .addReg(NewVReg3, RegState::Kill)
9819         .addReg(NewVReg1)
9820         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9821         .add(predOps(ARMCC::AL))
9822         .add(condCodeOp());
9823 
9824     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9825       .addReg(NewVReg4, RegState::Kill)
9826       .addReg(NewVReg1)
9827       .addJumpTableIndex(MJTI);
9828   } else if (Subtarget->isThumb()) {
9829     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9830     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9831         .addFrameIndex(FI)
9832         .addImm(1)
9833         .addMemOperand(FIMMOLd)
9834         .add(predOps(ARMCC::AL));
9835 
9836     if (NumLPads < 256) {
9837       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9838           .addReg(NewVReg1)
9839           .addImm(NumLPads)
9840           .add(predOps(ARMCC::AL));
9841     } else {
9842       MachineConstantPool *ConstantPool = MF->getConstantPool();
9843       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9844       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9845 
9846       // MachineConstantPool wants an explicit alignment.
9847       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9848       if (Align == 0)
9849         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9850       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9851 
9852       Register VReg1 = MRI->createVirtualRegister(TRC);
9853       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9854           .addReg(VReg1, RegState::Define)
9855           .addConstantPoolIndex(Idx)
9856           .add(predOps(ARMCC::AL));
9857       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9858           .addReg(NewVReg1)
9859           .addReg(VReg1)
9860           .add(predOps(ARMCC::AL));
9861     }
9862 
9863     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9864       .addMBB(TrapBB)
9865       .addImm(ARMCC::HI)
9866       .addReg(ARM::CPSR);
9867 
9868     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9869     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9870         .addReg(ARM::CPSR, RegState::Define)
9871         .addReg(NewVReg1)
9872         .addImm(2)
9873         .add(predOps(ARMCC::AL));
9874 
9875     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9876     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9877         .addJumpTableIndex(MJTI)
9878         .add(predOps(ARMCC::AL));
9879 
9880     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9881     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9882         .addReg(ARM::CPSR, RegState::Define)
9883         .addReg(NewVReg2, RegState::Kill)
9884         .addReg(NewVReg3)
9885         .add(predOps(ARMCC::AL));
9886 
9887     MachineMemOperand *JTMMOLd =
9888         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
9889                                  MachineMemOperand::MOLoad, 4, Align(4));
9890 
9891     Register NewVReg5 = MRI->createVirtualRegister(TRC);
9892     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9893         .addReg(NewVReg4, RegState::Kill)
9894         .addImm(0)
9895         .addMemOperand(JTMMOLd)
9896         .add(predOps(ARMCC::AL));
9897 
9898     unsigned NewVReg6 = NewVReg5;
9899     if (IsPositionIndependent) {
9900       NewVReg6 = MRI->createVirtualRegister(TRC);
9901       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9902           .addReg(ARM::CPSR, RegState::Define)
9903           .addReg(NewVReg5, RegState::Kill)
9904           .addReg(NewVReg3)
9905           .add(predOps(ARMCC::AL));
9906     }
9907 
9908     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9909       .addReg(NewVReg6, RegState::Kill)
9910       .addJumpTableIndex(MJTI);
9911   } else {
9912     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9913     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9914         .addFrameIndex(FI)
9915         .addImm(4)
9916         .addMemOperand(FIMMOLd)
9917         .add(predOps(ARMCC::AL));
9918 
9919     if (NumLPads < 256) {
9920       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9921           .addReg(NewVReg1)
9922           .addImm(NumLPads)
9923           .add(predOps(ARMCC::AL));
9924     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9925       Register VReg1 = MRI->createVirtualRegister(TRC);
9926       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9927           .addImm(NumLPads & 0xFFFF)
9928           .add(predOps(ARMCC::AL));
9929 
9930       unsigned VReg2 = VReg1;
9931       if ((NumLPads & 0xFFFF0000) != 0) {
9932         VReg2 = MRI->createVirtualRegister(TRC);
9933         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9934             .addReg(VReg1)
9935             .addImm(NumLPads >> 16)
9936             .add(predOps(ARMCC::AL));
9937       }
9938 
9939       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9940           .addReg(NewVReg1)
9941           .addReg(VReg2)
9942           .add(predOps(ARMCC::AL));
9943     } else {
9944       MachineConstantPool *ConstantPool = MF->getConstantPool();
9945       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9946       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9947 
9948       // MachineConstantPool wants an explicit alignment.
9949       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9950       if (Align == 0)
9951         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9952       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9953 
9954       Register VReg1 = MRI->createVirtualRegister(TRC);
9955       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9956           .addReg(VReg1, RegState::Define)
9957           .addConstantPoolIndex(Idx)
9958           .addImm(0)
9959           .add(predOps(ARMCC::AL));
9960       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9961           .addReg(NewVReg1)
9962           .addReg(VReg1, RegState::Kill)
9963           .add(predOps(ARMCC::AL));
9964     }
9965 
9966     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9967       .addMBB(TrapBB)
9968       .addImm(ARMCC::HI)
9969       .addReg(ARM::CPSR);
9970 
9971     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9972     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9973         .addReg(NewVReg1)
9974         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9975         .add(predOps(ARMCC::AL))
9976         .add(condCodeOp());
9977     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9978     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9979         .addJumpTableIndex(MJTI)
9980         .add(predOps(ARMCC::AL));
9981 
9982     MachineMemOperand *JTMMOLd =
9983         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
9984                                  MachineMemOperand::MOLoad, 4, Align(4));
9985     Register NewVReg5 = MRI->createVirtualRegister(TRC);
9986     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9987         .addReg(NewVReg3, RegState::Kill)
9988         .addReg(NewVReg4)
9989         .addImm(0)
9990         .addMemOperand(JTMMOLd)
9991         .add(predOps(ARMCC::AL));
9992 
9993     if (IsPositionIndependent) {
9994       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9995         .addReg(NewVReg5, RegState::Kill)
9996         .addReg(NewVReg4)
9997         .addJumpTableIndex(MJTI);
9998     } else {
9999       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
10000         .addReg(NewVReg5, RegState::Kill)
10001         .addJumpTableIndex(MJTI);
10002     }
10003   }
10004 
10005   // Add the jump table entries as successors to the MBB.
10006   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
10007   for (std::vector<MachineBasicBlock*>::iterator
10008          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
10009     MachineBasicBlock *CurMBB = *I;
10010     if (SeenMBBs.insert(CurMBB).second)
10011       DispContBB->addSuccessor(CurMBB);
10012   }
10013 
10014   // N.B. the order the invoke BBs are processed in doesn't matter here.
10015   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
10016   SmallVector<MachineBasicBlock*, 64> MBBLPads;
10017   for (MachineBasicBlock *BB : InvokeBBs) {
10018 
10019     // Remove the landing pad successor from the invoke block and replace it
10020     // with the new dispatch block.
10021     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
10022                                                   BB->succ_end());
10023     while (!Successors.empty()) {
10024       MachineBasicBlock *SMBB = Successors.pop_back_val();
10025       if (SMBB->isEHPad()) {
10026         BB->removeSuccessor(SMBB);
10027         MBBLPads.push_back(SMBB);
10028       }
10029     }
10030 
10031     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
10032     BB->normalizeSuccProbs();
10033 
10034     // Find the invoke call and mark all of the callee-saved registers as
10035     // 'implicit defined' so that they're spilled. This prevents code from
10036     // moving instructions to before the EH block, where they will never be
10037     // executed.
10038     for (MachineBasicBlock::reverse_iterator
10039            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
10040       if (!II->isCall()) continue;
10041 
10042       DenseMap<unsigned, bool> DefRegs;
10043       for (MachineInstr::mop_iterator
10044              OI = II->operands_begin(), OE = II->operands_end();
10045            OI != OE; ++OI) {
10046         if (!OI->isReg()) continue;
10047         DefRegs[OI->getReg()] = true;
10048       }
10049 
10050       MachineInstrBuilder MIB(*MF, &*II);
10051 
10052       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
10053         unsigned Reg = SavedRegs[i];
10054         if (Subtarget->isThumb2() &&
10055             !ARM::tGPRRegClass.contains(Reg) &&
10056             !ARM::hGPRRegClass.contains(Reg))
10057           continue;
10058         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
10059           continue;
10060         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
10061           continue;
10062         if (!DefRegs[Reg])
10063           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
10064       }
10065 
10066       break;
10067     }
10068   }
10069 
10070   // Mark all former landing pads as non-landing pads. The dispatch is the only
10071   // landing pad now.
10072   for (SmallVectorImpl<MachineBasicBlock*>::iterator
10073          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
10074     (*I)->setIsEHPad(false);
10075 
10076   // The instruction is gone now.
10077   MI.eraseFromParent();
10078 }
10079 
10080 static
10081 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
10082   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
10083        E = MBB->succ_end(); I != E; ++I)
10084     if (*I != Succ)
10085       return *I;
10086   llvm_unreachable("Expecting a BB with two successors!");
10087 }
10088 
10089 /// Return the load opcode for a given load size. If load size >= 8,
10090 /// neon opcode will be returned.
10091 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
10092   if (LdSize >= 8)
10093     return LdSize == 16 ? ARM::VLD1q32wb_fixed
10094                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
10095   if (IsThumb1)
10096     return LdSize == 4 ? ARM::tLDRi
10097                        : LdSize == 2 ? ARM::tLDRHi
10098                                      : LdSize == 1 ? ARM::tLDRBi : 0;
10099   if (IsThumb2)
10100     return LdSize == 4 ? ARM::t2LDR_POST
10101                        : LdSize == 2 ? ARM::t2LDRH_POST
10102                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
10103   return LdSize == 4 ? ARM::LDR_POST_IMM
10104                      : LdSize == 2 ? ARM::LDRH_POST
10105                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
10106 }
10107 
10108 /// Return the store opcode for a given store size. If store size >= 8,
10109 /// neon opcode will be returned.
10110 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
10111   if (StSize >= 8)
10112     return StSize == 16 ? ARM::VST1q32wb_fixed
10113                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
10114   if (IsThumb1)
10115     return StSize == 4 ? ARM::tSTRi
10116                        : StSize == 2 ? ARM::tSTRHi
10117                                      : StSize == 1 ? ARM::tSTRBi : 0;
10118   if (IsThumb2)
10119     return StSize == 4 ? ARM::t2STR_POST
10120                        : StSize == 2 ? ARM::t2STRH_POST
10121                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
10122   return StSize == 4 ? ARM::STR_POST_IMM
10123                      : StSize == 2 ? ARM::STRH_POST
10124                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
10125 }
10126 
10127 /// Emit a post-increment load operation with given size. The instructions
10128 /// will be added to BB at Pos.
10129 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10130                        const TargetInstrInfo *TII, const DebugLoc &dl,
10131                        unsigned LdSize, unsigned Data, unsigned AddrIn,
10132                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10133   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
10134   assert(LdOpc != 0 && "Should have a load opcode");
10135   if (LdSize >= 8) {
10136     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10137         .addReg(AddrOut, RegState::Define)
10138         .addReg(AddrIn)
10139         .addImm(0)
10140         .add(predOps(ARMCC::AL));
10141   } else if (IsThumb1) {
10142     // load + update AddrIn
10143     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10144         .addReg(AddrIn)
10145         .addImm(0)
10146         .add(predOps(ARMCC::AL));
10147     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10148         .add(t1CondCodeOp())
10149         .addReg(AddrIn)
10150         .addImm(LdSize)
10151         .add(predOps(ARMCC::AL));
10152   } else if (IsThumb2) {
10153     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10154         .addReg(AddrOut, RegState::Define)
10155         .addReg(AddrIn)
10156         .addImm(LdSize)
10157         .add(predOps(ARMCC::AL));
10158   } else { // arm
10159     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10160         .addReg(AddrOut, RegState::Define)
10161         .addReg(AddrIn)
10162         .addReg(0)
10163         .addImm(LdSize)
10164         .add(predOps(ARMCC::AL));
10165   }
10166 }
10167 
10168 /// Emit a post-increment store operation with given size. The instructions
10169 /// will be added to BB at Pos.
10170 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10171                        const TargetInstrInfo *TII, const DebugLoc &dl,
10172                        unsigned StSize, unsigned Data, unsigned AddrIn,
10173                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10174   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
10175   assert(StOpc != 0 && "Should have a store opcode");
10176   if (StSize >= 8) {
10177     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10178         .addReg(AddrIn)
10179         .addImm(0)
10180         .addReg(Data)
10181         .add(predOps(ARMCC::AL));
10182   } else if (IsThumb1) {
10183     // store + update AddrIn
10184     BuildMI(*BB, Pos, dl, TII->get(StOpc))
10185         .addReg(Data)
10186         .addReg(AddrIn)
10187         .addImm(0)
10188         .add(predOps(ARMCC::AL));
10189     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10190         .add(t1CondCodeOp())
10191         .addReg(AddrIn)
10192         .addImm(StSize)
10193         .add(predOps(ARMCC::AL));
10194   } else if (IsThumb2) {
10195     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10196         .addReg(Data)
10197         .addReg(AddrIn)
10198         .addImm(StSize)
10199         .add(predOps(ARMCC::AL));
10200   } else { // arm
10201     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10202         .addReg(Data)
10203         .addReg(AddrIn)
10204         .addReg(0)
10205         .addImm(StSize)
10206         .add(predOps(ARMCC::AL));
10207   }
10208 }
10209 
10210 MachineBasicBlock *
10211 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
10212                                    MachineBasicBlock *BB) const {
10213   // This pseudo instruction has 3 operands: dst, src, size
10214   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
10215   // Otherwise, we will generate unrolled scalar copies.
10216   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10217   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10218   MachineFunction::iterator It = ++BB->getIterator();
10219 
10220   Register dest = MI.getOperand(0).getReg();
10221   Register src = MI.getOperand(1).getReg();
10222   unsigned SizeVal = MI.getOperand(2).getImm();
10223   unsigned Alignment = MI.getOperand(3).getImm();
10224   DebugLoc dl = MI.getDebugLoc();
10225 
10226   MachineFunction *MF = BB->getParent();
10227   MachineRegisterInfo &MRI = MF->getRegInfo();
10228   unsigned UnitSize = 0;
10229   const TargetRegisterClass *TRC = nullptr;
10230   const TargetRegisterClass *VecTRC = nullptr;
10231 
10232   bool IsThumb1 = Subtarget->isThumb1Only();
10233   bool IsThumb2 = Subtarget->isThumb2();
10234   bool IsThumb = Subtarget->isThumb();
10235 
10236   if (Alignment & 1) {
10237     UnitSize = 1;
10238   } else if (Alignment & 2) {
10239     UnitSize = 2;
10240   } else {
10241     // Check whether we can use NEON instructions.
10242     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
10243         Subtarget->hasNEON()) {
10244       if ((Alignment % 16 == 0) && SizeVal >= 16)
10245         UnitSize = 16;
10246       else if ((Alignment % 8 == 0) && SizeVal >= 8)
10247         UnitSize = 8;
10248     }
10249     // Can't use NEON instructions.
10250     if (UnitSize == 0)
10251       UnitSize = 4;
10252   }
10253 
10254   // Select the correct opcode and register class for unit size load/store
10255   bool IsNeon = UnitSize >= 8;
10256   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
10257   if (IsNeon)
10258     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
10259                             : UnitSize == 8 ? &ARM::DPRRegClass
10260                                             : nullptr;
10261 
10262   unsigned BytesLeft = SizeVal % UnitSize;
10263   unsigned LoopSize = SizeVal - BytesLeft;
10264 
10265   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
10266     // Use LDR and STR to copy.
10267     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
10268     // [destOut] = STR_POST(scratch, destIn, UnitSize)
10269     unsigned srcIn = src;
10270     unsigned destIn = dest;
10271     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
10272       Register srcOut = MRI.createVirtualRegister(TRC);
10273       Register destOut = MRI.createVirtualRegister(TRC);
10274       Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10275       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
10276                  IsThumb1, IsThumb2);
10277       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
10278                  IsThumb1, IsThumb2);
10279       srcIn = srcOut;
10280       destIn = destOut;
10281     }
10282 
10283     // Handle the leftover bytes with LDRB and STRB.
10284     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
10285     // [destOut] = STRB_POST(scratch, destIn, 1)
10286     for (unsigned i = 0; i < BytesLeft; i++) {
10287       Register srcOut = MRI.createVirtualRegister(TRC);
10288       Register destOut = MRI.createVirtualRegister(TRC);
10289       Register scratch = MRI.createVirtualRegister(TRC);
10290       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
10291                  IsThumb1, IsThumb2);
10292       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
10293                  IsThumb1, IsThumb2);
10294       srcIn = srcOut;
10295       destIn = destOut;
10296     }
10297     MI.eraseFromParent(); // The instruction is gone now.
10298     return BB;
10299   }
10300 
10301   // Expand the pseudo op to a loop.
10302   // thisMBB:
10303   //   ...
10304   //   movw varEnd, # --> with thumb2
10305   //   movt varEnd, #
10306   //   ldrcp varEnd, idx --> without thumb2
10307   //   fallthrough --> loopMBB
10308   // loopMBB:
10309   //   PHI varPhi, varEnd, varLoop
10310   //   PHI srcPhi, src, srcLoop
10311   //   PHI destPhi, dst, destLoop
10312   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10313   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
10314   //   subs varLoop, varPhi, #UnitSize
10315   //   bne loopMBB
10316   //   fallthrough --> exitMBB
10317   // exitMBB:
10318   //   epilogue to handle left-over bytes
10319   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10320   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10321   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10322   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10323   MF->insert(It, loopMBB);
10324   MF->insert(It, exitMBB);
10325 
10326   // Transfer the remainder of BB and its successor edges to exitMBB.
10327   exitMBB->splice(exitMBB->begin(), BB,
10328                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10329   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10330 
10331   // Load an immediate to varEnd.
10332   Register varEnd = MRI.createVirtualRegister(TRC);
10333   if (Subtarget->useMovt()) {
10334     unsigned Vtmp = varEnd;
10335     if ((LoopSize & 0xFFFF0000) != 0)
10336       Vtmp = MRI.createVirtualRegister(TRC);
10337     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
10338         .addImm(LoopSize & 0xFFFF)
10339         .add(predOps(ARMCC::AL));
10340 
10341     if ((LoopSize & 0xFFFF0000) != 0)
10342       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
10343           .addReg(Vtmp)
10344           .addImm(LoopSize >> 16)
10345           .add(predOps(ARMCC::AL));
10346   } else {
10347     MachineConstantPool *ConstantPool = MF->getConstantPool();
10348     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10349     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
10350 
10351     // MachineConstantPool wants an explicit alignment.
10352     Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10353     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment.value());
10354     MachineMemOperand *CPMMO =
10355         MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10356                                  MachineMemOperand::MOLoad, 4, Align(4));
10357 
10358     if (IsThumb)
10359       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
10360           .addReg(varEnd, RegState::Define)
10361           .addConstantPoolIndex(Idx)
10362           .add(predOps(ARMCC::AL))
10363           .addMemOperand(CPMMO);
10364     else
10365       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
10366           .addReg(varEnd, RegState::Define)
10367           .addConstantPoolIndex(Idx)
10368           .addImm(0)
10369           .add(predOps(ARMCC::AL))
10370           .addMemOperand(CPMMO);
10371   }
10372   BB->addSuccessor(loopMBB);
10373 
10374   // Generate the loop body:
10375   //   varPhi = PHI(varLoop, varEnd)
10376   //   srcPhi = PHI(srcLoop, src)
10377   //   destPhi = PHI(destLoop, dst)
10378   MachineBasicBlock *entryBB = BB;
10379   BB = loopMBB;
10380   Register varLoop = MRI.createVirtualRegister(TRC);
10381   Register varPhi = MRI.createVirtualRegister(TRC);
10382   Register srcLoop = MRI.createVirtualRegister(TRC);
10383   Register srcPhi = MRI.createVirtualRegister(TRC);
10384   Register destLoop = MRI.createVirtualRegister(TRC);
10385   Register destPhi = MRI.createVirtualRegister(TRC);
10386 
10387   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
10388     .addReg(varLoop).addMBB(loopMBB)
10389     .addReg(varEnd).addMBB(entryBB);
10390   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
10391     .addReg(srcLoop).addMBB(loopMBB)
10392     .addReg(src).addMBB(entryBB);
10393   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
10394     .addReg(destLoop).addMBB(loopMBB)
10395     .addReg(dest).addMBB(entryBB);
10396 
10397   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10398   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
10399   Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10400   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
10401              IsThumb1, IsThumb2);
10402   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
10403              IsThumb1, IsThumb2);
10404 
10405   // Decrement loop variable by UnitSize.
10406   if (IsThumb1) {
10407     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
10408         .add(t1CondCodeOp())
10409         .addReg(varPhi)
10410         .addImm(UnitSize)
10411         .add(predOps(ARMCC::AL));
10412   } else {
10413     MachineInstrBuilder MIB =
10414         BuildMI(*BB, BB->end(), dl,
10415                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
10416     MIB.addReg(varPhi)
10417         .addImm(UnitSize)
10418         .add(predOps(ARMCC::AL))
10419         .add(condCodeOp());
10420     MIB->getOperand(5).setReg(ARM::CPSR);
10421     MIB->getOperand(5).setIsDef(true);
10422   }
10423   BuildMI(*BB, BB->end(), dl,
10424           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
10425       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
10426 
10427   // loopMBB can loop back to loopMBB or fall through to exitMBB.
10428   BB->addSuccessor(loopMBB);
10429   BB->addSuccessor(exitMBB);
10430 
10431   // Add epilogue to handle BytesLeft.
10432   BB = exitMBB;
10433   auto StartOfExit = exitMBB->begin();
10434 
10435   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10436   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10437   unsigned srcIn = srcLoop;
10438   unsigned destIn = destLoop;
10439   for (unsigned i = 0; i < BytesLeft; i++) {
10440     Register srcOut = MRI.createVirtualRegister(TRC);
10441     Register destOut = MRI.createVirtualRegister(TRC);
10442     Register scratch = MRI.createVirtualRegister(TRC);
10443     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
10444                IsThumb1, IsThumb2);
10445     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10446                IsThumb1, IsThumb2);
10447     srcIn = srcOut;
10448     destIn = destOut;
10449   }
10450 
10451   MI.eraseFromParent(); // The instruction is gone now.
10452   return BB;
10453 }
10454 
10455 MachineBasicBlock *
10456 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10457                                        MachineBasicBlock *MBB) const {
10458   const TargetMachine &TM = getTargetMachine();
10459   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10460   DebugLoc DL = MI.getDebugLoc();
10461 
10462   assert(Subtarget->isTargetWindows() &&
10463          "__chkstk is only supported on Windows");
10464   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10465 
10466   // __chkstk takes the number of words to allocate on the stack in R4, and
10467   // returns the stack adjustment in number of bytes in R4.  This will not
10468   // clober any other registers (other than the obvious lr).
10469   //
10470   // Although, technically, IP should be considered a register which may be
10471   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
10472   // thumb-2 environment, so there is no interworking required.  As a result, we
10473   // do not expect a veneer to be emitted by the linker, clobbering IP.
10474   //
10475   // Each module receives its own copy of __chkstk, so no import thunk is
10476   // required, again, ensuring that IP is not clobbered.
10477   //
10478   // Finally, although some linkers may theoretically provide a trampoline for
10479   // out of range calls (which is quite common due to a 32M range limitation of
10480   // branches for Thumb), we can generate the long-call version via
10481   // -mcmodel=large, alleviating the need for the trampoline which may clobber
10482   // IP.
10483 
10484   switch (TM.getCodeModel()) {
10485   case CodeModel::Tiny:
10486     llvm_unreachable("Tiny code model not available on ARM.");
10487   case CodeModel::Small:
10488   case CodeModel::Medium:
10489   case CodeModel::Kernel:
10490     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10491         .add(predOps(ARMCC::AL))
10492         .addExternalSymbol("__chkstk")
10493         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10494         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10495         .addReg(ARM::R12,
10496                 RegState::Implicit | RegState::Define | RegState::Dead)
10497         .addReg(ARM::CPSR,
10498                 RegState::Implicit | RegState::Define | RegState::Dead);
10499     break;
10500   case CodeModel::Large: {
10501     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10502     Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10503 
10504     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10505       .addExternalSymbol("__chkstk");
10506     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10507         .add(predOps(ARMCC::AL))
10508         .addReg(Reg, RegState::Kill)
10509         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10510         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10511         .addReg(ARM::R12,
10512                 RegState::Implicit | RegState::Define | RegState::Dead)
10513         .addReg(ARM::CPSR,
10514                 RegState::Implicit | RegState::Define | RegState::Dead);
10515     break;
10516   }
10517   }
10518 
10519   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10520       .addReg(ARM::SP, RegState::Kill)
10521       .addReg(ARM::R4, RegState::Kill)
10522       .setMIFlags(MachineInstr::FrameSetup)
10523       .add(predOps(ARMCC::AL))
10524       .add(condCodeOp());
10525 
10526   MI.eraseFromParent();
10527   return MBB;
10528 }
10529 
10530 MachineBasicBlock *
10531 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10532                                        MachineBasicBlock *MBB) const {
10533   DebugLoc DL = MI.getDebugLoc();
10534   MachineFunction *MF = MBB->getParent();
10535   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10536 
10537   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10538   MF->insert(++MBB->getIterator(), ContBB);
10539   ContBB->splice(ContBB->begin(), MBB,
10540                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10541   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10542   MBB->addSuccessor(ContBB);
10543 
10544   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10545   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10546   MF->push_back(TrapBB);
10547   MBB->addSuccessor(TrapBB);
10548 
10549   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10550       .addReg(MI.getOperand(0).getReg())
10551       .addImm(0)
10552       .add(predOps(ARMCC::AL));
10553   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10554       .addMBB(TrapBB)
10555       .addImm(ARMCC::EQ)
10556       .addReg(ARM::CPSR);
10557 
10558   MI.eraseFromParent();
10559   return ContBB;
10560 }
10561 
10562 // The CPSR operand of SelectItr might be missing a kill marker
10563 // because there were multiple uses of CPSR, and ISel didn't know
10564 // which to mark. Figure out whether SelectItr should have had a
10565 // kill marker, and set it if it should. Returns the correct kill
10566 // marker value.
10567 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10568                                    MachineBasicBlock* BB,
10569                                    const TargetRegisterInfo* TRI) {
10570   // Scan forward through BB for a use/def of CPSR.
10571   MachineBasicBlock::iterator miI(std::next(SelectItr));
10572   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10573     const MachineInstr& mi = *miI;
10574     if (mi.readsRegister(ARM::CPSR))
10575       return false;
10576     if (mi.definesRegister(ARM::CPSR))
10577       break; // Should have kill-flag - update below.
10578   }
10579 
10580   // If we hit the end of the block, check whether CPSR is live into a
10581   // successor.
10582   if (miI == BB->end()) {
10583     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10584                                           sEnd = BB->succ_end();
10585          sItr != sEnd; ++sItr) {
10586       MachineBasicBlock* succ = *sItr;
10587       if (succ->isLiveIn(ARM::CPSR))
10588         return false;
10589     }
10590   }
10591 
10592   // We found a def, or hit the end of the basic block and CPSR wasn't live
10593   // out. SelectMI should have a kill flag on CPSR.
10594   SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10595   return true;
10596 }
10597 
10598 MachineBasicBlock *
10599 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10600                                                MachineBasicBlock *BB) const {
10601   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10602   DebugLoc dl = MI.getDebugLoc();
10603   bool isThumb2 = Subtarget->isThumb2();
10604   switch (MI.getOpcode()) {
10605   default: {
10606     MI.print(errs());
10607     llvm_unreachable("Unexpected instr type to insert");
10608   }
10609 
10610   // Thumb1 post-indexed loads are really just single-register LDMs.
10611   case ARM::tLDR_postidx: {
10612     MachineOperand Def(MI.getOperand(1));
10613     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10614         .add(Def)  // Rn_wb
10615         .add(MI.getOperand(2))  // Rn
10616         .add(MI.getOperand(3))  // PredImm
10617         .add(MI.getOperand(4))  // PredReg
10618         .add(MI.getOperand(0))  // Rt
10619         .cloneMemRefs(MI);
10620     MI.eraseFromParent();
10621     return BB;
10622   }
10623 
10624   // The Thumb2 pre-indexed stores have the same MI operands, they just
10625   // define them differently in the .td files from the isel patterns, so
10626   // they need pseudos.
10627   case ARM::t2STR_preidx:
10628     MI.setDesc(TII->get(ARM::t2STR_PRE));
10629     return BB;
10630   case ARM::t2STRB_preidx:
10631     MI.setDesc(TII->get(ARM::t2STRB_PRE));
10632     return BB;
10633   case ARM::t2STRH_preidx:
10634     MI.setDesc(TII->get(ARM::t2STRH_PRE));
10635     return BB;
10636 
10637   case ARM::STRi_preidx:
10638   case ARM::STRBi_preidx: {
10639     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10640                                                          : ARM::STRB_PRE_IMM;
10641     // Decode the offset.
10642     unsigned Offset = MI.getOperand(4).getImm();
10643     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10644     Offset = ARM_AM::getAM2Offset(Offset);
10645     if (isSub)
10646       Offset = -Offset;
10647 
10648     MachineMemOperand *MMO = *MI.memoperands_begin();
10649     BuildMI(*BB, MI, dl, TII->get(NewOpc))
10650         .add(MI.getOperand(0)) // Rn_wb
10651         .add(MI.getOperand(1)) // Rt
10652         .add(MI.getOperand(2)) // Rn
10653         .addImm(Offset)        // offset (skip GPR==zero_reg)
10654         .add(MI.getOperand(5)) // pred
10655         .add(MI.getOperand(6))
10656         .addMemOperand(MMO);
10657     MI.eraseFromParent();
10658     return BB;
10659   }
10660   case ARM::STRr_preidx:
10661   case ARM::STRBr_preidx:
10662   case ARM::STRH_preidx: {
10663     unsigned NewOpc;
10664     switch (MI.getOpcode()) {
10665     default: llvm_unreachable("unexpected opcode!");
10666     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10667     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10668     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10669     }
10670     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10671     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10672       MIB.add(MI.getOperand(i));
10673     MI.eraseFromParent();
10674     return BB;
10675   }
10676 
10677   case ARM::tMOVCCr_pseudo: {
10678     // To "insert" a SELECT_CC instruction, we actually have to insert the
10679     // diamond control-flow pattern.  The incoming instruction knows the
10680     // destination vreg to set, the condition code register to branch on, the
10681     // true/false values to select between, and a branch opcode to use.
10682     const BasicBlock *LLVM_BB = BB->getBasicBlock();
10683     MachineFunction::iterator It = ++BB->getIterator();
10684 
10685     //  thisMBB:
10686     //  ...
10687     //   TrueVal = ...
10688     //   cmpTY ccX, r1, r2
10689     //   bCC copy1MBB
10690     //   fallthrough --> copy0MBB
10691     MachineBasicBlock *thisMBB  = BB;
10692     MachineFunction *F = BB->getParent();
10693     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10694     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
10695     F->insert(It, copy0MBB);
10696     F->insert(It, sinkMBB);
10697 
10698     // Check whether CPSR is live past the tMOVCCr_pseudo.
10699     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10700     if (!MI.killsRegister(ARM::CPSR) &&
10701         !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10702       copy0MBB->addLiveIn(ARM::CPSR);
10703       sinkMBB->addLiveIn(ARM::CPSR);
10704     }
10705 
10706     // Transfer the remainder of BB and its successor edges to sinkMBB.
10707     sinkMBB->splice(sinkMBB->begin(), BB,
10708                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10709     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10710 
10711     BB->addSuccessor(copy0MBB);
10712     BB->addSuccessor(sinkMBB);
10713 
10714     BuildMI(BB, dl, TII->get(ARM::tBcc))
10715         .addMBB(sinkMBB)
10716         .addImm(MI.getOperand(3).getImm())
10717         .addReg(MI.getOperand(4).getReg());
10718 
10719     //  copy0MBB:
10720     //   %FalseValue = ...
10721     //   # fallthrough to sinkMBB
10722     BB = copy0MBB;
10723 
10724     // Update machine-CFG edges
10725     BB->addSuccessor(sinkMBB);
10726 
10727     //  sinkMBB:
10728     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10729     //  ...
10730     BB = sinkMBB;
10731     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10732         .addReg(MI.getOperand(1).getReg())
10733         .addMBB(copy0MBB)
10734         .addReg(MI.getOperand(2).getReg())
10735         .addMBB(thisMBB);
10736 
10737     MI.eraseFromParent(); // The pseudo instruction is gone now.
10738     return BB;
10739   }
10740 
10741   case ARM::BCCi64:
10742   case ARM::BCCZi64: {
10743     // If there is an unconditional branch to the other successor, remove it.
10744     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10745 
10746     // Compare both parts that make up the double comparison separately for
10747     // equality.
10748     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10749 
10750     Register LHS1 = MI.getOperand(1).getReg();
10751     Register LHS2 = MI.getOperand(2).getReg();
10752     if (RHSisZero) {
10753       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10754           .addReg(LHS1)
10755           .addImm(0)
10756           .add(predOps(ARMCC::AL));
10757       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10758         .addReg(LHS2).addImm(0)
10759         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10760     } else {
10761       Register RHS1 = MI.getOperand(3).getReg();
10762       Register RHS2 = MI.getOperand(4).getReg();
10763       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10764           .addReg(LHS1)
10765           .addReg(RHS1)
10766           .add(predOps(ARMCC::AL));
10767       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10768         .addReg(LHS2).addReg(RHS2)
10769         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10770     }
10771 
10772     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10773     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10774     if (MI.getOperand(0).getImm() == ARMCC::NE)
10775       std::swap(destMBB, exitMBB);
10776 
10777     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10778       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10779     if (isThumb2)
10780       BuildMI(BB, dl, TII->get(ARM::t2B))
10781           .addMBB(exitMBB)
10782           .add(predOps(ARMCC::AL));
10783     else
10784       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10785 
10786     MI.eraseFromParent(); // The pseudo instruction is gone now.
10787     return BB;
10788   }
10789 
10790   case ARM::Int_eh_sjlj_setjmp:
10791   case ARM::Int_eh_sjlj_setjmp_nofp:
10792   case ARM::tInt_eh_sjlj_setjmp:
10793   case ARM::t2Int_eh_sjlj_setjmp:
10794   case ARM::t2Int_eh_sjlj_setjmp_nofp:
10795     return BB;
10796 
10797   case ARM::Int_eh_sjlj_setup_dispatch:
10798     EmitSjLjDispatchBlock(MI, BB);
10799     return BB;
10800 
10801   case ARM::ABS:
10802   case ARM::t2ABS: {
10803     // To insert an ABS instruction, we have to insert the
10804     // diamond control-flow pattern.  The incoming instruction knows the
10805     // source vreg to test against 0, the destination vreg to set,
10806     // the condition code register to branch on, the
10807     // true/false values to select between, and a branch opcode to use.
10808     // It transforms
10809     //     V1 = ABS V0
10810     // into
10811     //     V2 = MOVS V0
10812     //     BCC                      (branch to SinkBB if V0 >= 0)
10813     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
10814     //     SinkBB: V1 = PHI(V2, V3)
10815     const BasicBlock *LLVM_BB = BB->getBasicBlock();
10816     MachineFunction::iterator BBI = ++BB->getIterator();
10817     MachineFunction *Fn = BB->getParent();
10818     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10819     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
10820     Fn->insert(BBI, RSBBB);
10821     Fn->insert(BBI, SinkBB);
10822 
10823     Register ABSSrcReg = MI.getOperand(1).getReg();
10824     Register ABSDstReg = MI.getOperand(0).getReg();
10825     bool ABSSrcKIll = MI.getOperand(1).isKill();
10826     bool isThumb2 = Subtarget->isThumb2();
10827     MachineRegisterInfo &MRI = Fn->getRegInfo();
10828     // In Thumb mode S must not be specified if source register is the SP or
10829     // PC and if destination register is the SP, so restrict register class
10830     Register NewRsbDstReg = MRI.createVirtualRegister(
10831         isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10832 
10833     // Transfer the remainder of BB and its successor edges to sinkMBB.
10834     SinkBB->splice(SinkBB->begin(), BB,
10835                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
10836     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10837 
10838     BB->addSuccessor(RSBBB);
10839     BB->addSuccessor(SinkBB);
10840 
10841     // fall through to SinkMBB
10842     RSBBB->addSuccessor(SinkBB);
10843 
10844     // insert a cmp at the end of BB
10845     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10846         .addReg(ABSSrcReg)
10847         .addImm(0)
10848         .add(predOps(ARMCC::AL));
10849 
10850     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10851     BuildMI(BB, dl,
10852       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10853       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10854 
10855     // insert rsbri in RSBBB
10856     // Note: BCC and rsbri will be converted into predicated rsbmi
10857     // by if-conversion pass
10858     BuildMI(*RSBBB, RSBBB->begin(), dl,
10859             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10860         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10861         .addImm(0)
10862         .add(predOps(ARMCC::AL))
10863         .add(condCodeOp());
10864 
10865     // insert PHI in SinkBB,
10866     // reuse ABSDstReg to not change uses of ABS instruction
10867     BuildMI(*SinkBB, SinkBB->begin(), dl,
10868       TII->get(ARM::PHI), ABSDstReg)
10869       .addReg(NewRsbDstReg).addMBB(RSBBB)
10870       .addReg(ABSSrcReg).addMBB(BB);
10871 
10872     // remove ABS instruction
10873     MI.eraseFromParent();
10874 
10875     // return last added BB
10876     return SinkBB;
10877   }
10878   case ARM::COPY_STRUCT_BYVAL_I32:
10879     ++NumLoopByVals;
10880     return EmitStructByval(MI, BB);
10881   case ARM::WIN__CHKSTK:
10882     return EmitLowered__chkstk(MI, BB);
10883   case ARM::WIN__DBZCHK:
10884     return EmitLowered__dbzchk(MI, BB);
10885   }
10886 }
10887 
10888 /// Attaches vregs to MEMCPY that it will use as scratch registers
10889 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10890 /// instead of as a custom inserter because we need the use list from the SDNode.
10891 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10892                                     MachineInstr &MI, const SDNode *Node) {
10893   bool isThumb1 = Subtarget->isThumb1Only();
10894 
10895   DebugLoc DL = MI.getDebugLoc();
10896   MachineFunction *MF = MI.getParent()->getParent();
10897   MachineRegisterInfo &MRI = MF->getRegInfo();
10898   MachineInstrBuilder MIB(*MF, MI);
10899 
10900   // If the new dst/src is unused mark it as dead.
10901   if (!Node->hasAnyUseOfValue(0)) {
10902     MI.getOperand(0).setIsDead(true);
10903   }
10904   if (!Node->hasAnyUseOfValue(1)) {
10905     MI.getOperand(1).setIsDead(true);
10906   }
10907 
10908   // The MEMCPY both defines and kills the scratch registers.
10909   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10910     Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10911                                                          : &ARM::GPRRegClass);
10912     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10913   }
10914 }
10915 
10916 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10917                                                       SDNode *Node) const {
10918   if (MI.getOpcode() == ARM::MEMCPY) {
10919     attachMEMCPYScratchRegs(Subtarget, MI, Node);
10920     return;
10921   }
10922 
10923   const MCInstrDesc *MCID = &MI.getDesc();
10924   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10925   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10926   // operand is still set to noreg. If needed, set the optional operand's
10927   // register to CPSR, and remove the redundant implicit def.
10928   //
10929   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10930 
10931   // Rename pseudo opcodes.
10932   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10933   unsigned ccOutIdx;
10934   if (NewOpc) {
10935     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10936     MCID = &TII->get(NewOpc);
10937 
10938     assert(MCID->getNumOperands() ==
10939            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10940         && "converted opcode should be the same except for cc_out"
10941            " (and, on Thumb1, pred)");
10942 
10943     MI.setDesc(*MCID);
10944 
10945     // Add the optional cc_out operand
10946     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10947 
10948     // On Thumb1, move all input operands to the end, then add the predicate
10949     if (Subtarget->isThumb1Only()) {
10950       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10951         MI.addOperand(MI.getOperand(1));
10952         MI.RemoveOperand(1);
10953       }
10954 
10955       // Restore the ties
10956       for (unsigned i = MI.getNumOperands(); i--;) {
10957         const MachineOperand& op = MI.getOperand(i);
10958         if (op.isReg() && op.isUse()) {
10959           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10960           if (DefIdx != -1)
10961             MI.tieOperands(DefIdx, i);
10962         }
10963       }
10964 
10965       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10966       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10967       ccOutIdx = 1;
10968     } else
10969       ccOutIdx = MCID->getNumOperands() - 1;
10970   } else
10971     ccOutIdx = MCID->getNumOperands() - 1;
10972 
10973   // Any ARM instruction that sets the 's' bit should specify an optional
10974   // "cc_out" operand in the last operand position.
10975   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10976     assert(!NewOpc && "Optional cc_out operand required");
10977     return;
10978   }
10979   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10980   // since we already have an optional CPSR def.
10981   bool definesCPSR = false;
10982   bool deadCPSR = false;
10983   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10984        ++i) {
10985     const MachineOperand &MO = MI.getOperand(i);
10986     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10987       definesCPSR = true;
10988       if (MO.isDead())
10989         deadCPSR = true;
10990       MI.RemoveOperand(i);
10991       break;
10992     }
10993   }
10994   if (!definesCPSR) {
10995     assert(!NewOpc && "Optional cc_out operand required");
10996     return;
10997   }
10998   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10999   if (deadCPSR) {
11000     assert(!MI.getOperand(ccOutIdx).getReg() &&
11001            "expect uninitialized optional cc_out operand");
11002     // Thumb1 instructions must have the S bit even if the CPSR is dead.
11003     if (!Subtarget->isThumb1Only())
11004       return;
11005   }
11006 
11007   // If this instruction was defined with an optional CPSR def and its dag node
11008   // had a live implicit CPSR def, then activate the optional CPSR def.
11009   MachineOperand &MO = MI.getOperand(ccOutIdx);
11010   MO.setReg(ARM::CPSR);
11011   MO.setIsDef(true);
11012 }
11013 
11014 //===----------------------------------------------------------------------===//
11015 //                           ARM Optimization Hooks
11016 //===----------------------------------------------------------------------===//
11017 
11018 // Helper function that checks if N is a null or all ones constant.
11019 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
11020   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
11021 }
11022 
11023 // Return true if N is conditionally 0 or all ones.
11024 // Detects these expressions where cc is an i1 value:
11025 //
11026 //   (select cc 0, y)   [AllOnes=0]
11027 //   (select cc y, 0)   [AllOnes=0]
11028 //   (zext cc)          [AllOnes=0]
11029 //   (sext cc)          [AllOnes=0/1]
11030 //   (select cc -1, y)  [AllOnes=1]
11031 //   (select cc y, -1)  [AllOnes=1]
11032 //
11033 // Invert is set when N is the null/all ones constant when CC is false.
11034 // OtherOp is set to the alternative value of N.
11035 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
11036                                        SDValue &CC, bool &Invert,
11037                                        SDValue &OtherOp,
11038                                        SelectionDAG &DAG) {
11039   switch (N->getOpcode()) {
11040   default: return false;
11041   case ISD::SELECT: {
11042     CC = N->getOperand(0);
11043     SDValue N1 = N->getOperand(1);
11044     SDValue N2 = N->getOperand(2);
11045     if (isZeroOrAllOnes(N1, AllOnes)) {
11046       Invert = false;
11047       OtherOp = N2;
11048       return true;
11049     }
11050     if (isZeroOrAllOnes(N2, AllOnes)) {
11051       Invert = true;
11052       OtherOp = N1;
11053       return true;
11054     }
11055     return false;
11056   }
11057   case ISD::ZERO_EXTEND:
11058     // (zext cc) can never be the all ones value.
11059     if (AllOnes)
11060       return false;
11061     LLVM_FALLTHROUGH;
11062   case ISD::SIGN_EXTEND: {
11063     SDLoc dl(N);
11064     EVT VT = N->getValueType(0);
11065     CC = N->getOperand(0);
11066     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
11067       return false;
11068     Invert = !AllOnes;
11069     if (AllOnes)
11070       // When looking for an AllOnes constant, N is an sext, and the 'other'
11071       // value is 0.
11072       OtherOp = DAG.getConstant(0, dl, VT);
11073     else if (N->getOpcode() == ISD::ZERO_EXTEND)
11074       // When looking for a 0 constant, N can be zext or sext.
11075       OtherOp = DAG.getConstant(1, dl, VT);
11076     else
11077       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
11078                                 VT);
11079     return true;
11080   }
11081   }
11082 }
11083 
11084 // Combine a constant select operand into its use:
11085 //
11086 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
11087 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
11088 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
11089 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
11090 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
11091 //
11092 // The transform is rejected if the select doesn't have a constant operand that
11093 // is null, or all ones when AllOnes is set.
11094 //
11095 // Also recognize sext/zext from i1:
11096 //
11097 //   (add (zext cc), x) -> (select cc (add x, 1), x)
11098 //   (add (sext cc), x) -> (select cc (add x, -1), x)
11099 //
11100 // These transformations eventually create predicated instructions.
11101 //
11102 // @param N       The node to transform.
11103 // @param Slct    The N operand that is a select.
11104 // @param OtherOp The other N operand (x above).
11105 // @param DCI     Context.
11106 // @param AllOnes Require the select constant to be all ones instead of null.
11107 // @returns The new node, or SDValue() on failure.
11108 static
11109 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
11110                             TargetLowering::DAGCombinerInfo &DCI,
11111                             bool AllOnes = false) {
11112   SelectionDAG &DAG = DCI.DAG;
11113   EVT VT = N->getValueType(0);
11114   SDValue NonConstantVal;
11115   SDValue CCOp;
11116   bool SwapSelectOps;
11117   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
11118                                   NonConstantVal, DAG))
11119     return SDValue();
11120 
11121   // Slct is now know to be the desired identity constant when CC is true.
11122   SDValue TrueVal = OtherOp;
11123   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11124                                  OtherOp, NonConstantVal);
11125   // Unless SwapSelectOps says CC should be false.
11126   if (SwapSelectOps)
11127     std::swap(TrueVal, FalseVal);
11128 
11129   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
11130                      CCOp, TrueVal, FalseVal);
11131 }
11132 
11133 // Attempt combineSelectAndUse on each operand of a commutative operator N.
11134 static
11135 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
11136                                        TargetLowering::DAGCombinerInfo &DCI) {
11137   SDValue N0 = N->getOperand(0);
11138   SDValue N1 = N->getOperand(1);
11139   if (N0.getNode()->hasOneUse())
11140     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
11141       return Result;
11142   if (N1.getNode()->hasOneUse())
11143     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
11144       return Result;
11145   return SDValue();
11146 }
11147 
11148 static bool IsVUZPShuffleNode(SDNode *N) {
11149   // VUZP shuffle node.
11150   if (N->getOpcode() == ARMISD::VUZP)
11151     return true;
11152 
11153   // "VUZP" on i32 is an alias for VTRN.
11154   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
11155     return true;
11156 
11157   return false;
11158 }
11159 
11160 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
11161                                  TargetLowering::DAGCombinerInfo &DCI,
11162                                  const ARMSubtarget *Subtarget) {
11163   // Look for ADD(VUZP.0, VUZP.1).
11164   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
11165       N0 == N1)
11166    return SDValue();
11167 
11168   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
11169   if (!N->getValueType(0).is64BitVector())
11170     return SDValue();
11171 
11172   // Generate vpadd.
11173   SelectionDAG &DAG = DCI.DAG;
11174   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11175   SDLoc dl(N);
11176   SDNode *Unzip = N0.getNode();
11177   EVT VT = N->getValueType(0);
11178 
11179   SmallVector<SDValue, 8> Ops;
11180   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
11181                                 TLI.getPointerTy(DAG.getDataLayout())));
11182   Ops.push_back(Unzip->getOperand(0));
11183   Ops.push_back(Unzip->getOperand(1));
11184 
11185   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11186 }
11187 
11188 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11189                                       TargetLowering::DAGCombinerInfo &DCI,
11190                                       const ARMSubtarget *Subtarget) {
11191   // Check for two extended operands.
11192   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
11193         N1.getOpcode() == ISD::SIGN_EXTEND) &&
11194       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
11195         N1.getOpcode() == ISD::ZERO_EXTEND))
11196     return SDValue();
11197 
11198   SDValue N00 = N0.getOperand(0);
11199   SDValue N10 = N1.getOperand(0);
11200 
11201   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
11202   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
11203       N00 == N10)
11204     return SDValue();
11205 
11206   // We only recognize Q register paddl here; this can't be reached until
11207   // after type legalization.
11208   if (!N00.getValueType().is64BitVector() ||
11209       !N0.getValueType().is128BitVector())
11210     return SDValue();
11211 
11212   // Generate vpaddl.
11213   SelectionDAG &DAG = DCI.DAG;
11214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11215   SDLoc dl(N);
11216   EVT VT = N->getValueType(0);
11217 
11218   SmallVector<SDValue, 8> Ops;
11219   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
11220   unsigned Opcode;
11221   if (N0.getOpcode() == ISD::SIGN_EXTEND)
11222     Opcode = Intrinsic::arm_neon_vpaddls;
11223   else
11224     Opcode = Intrinsic::arm_neon_vpaddlu;
11225   Ops.push_back(DAG.getConstant(Opcode, dl,
11226                                 TLI.getPointerTy(DAG.getDataLayout())));
11227   EVT ElemTy = N00.getValueType().getVectorElementType();
11228   unsigned NumElts = VT.getVectorNumElements();
11229   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
11230   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
11231                                N00.getOperand(0), N00.getOperand(1));
11232   Ops.push_back(Concat);
11233 
11234   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11235 }
11236 
11237 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
11238 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
11239 // much easier to match.
11240 static SDValue
11241 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11242                                TargetLowering::DAGCombinerInfo &DCI,
11243                                const ARMSubtarget *Subtarget) {
11244   // Only perform optimization if after legalize, and if NEON is available. We
11245   // also expected both operands to be BUILD_VECTORs.
11246   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
11247       || N0.getOpcode() != ISD::BUILD_VECTOR
11248       || N1.getOpcode() != ISD::BUILD_VECTOR)
11249     return SDValue();
11250 
11251   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
11252   EVT VT = N->getValueType(0);
11253   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
11254     return SDValue();
11255 
11256   // Check that the vector operands are of the right form.
11257   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
11258   // operands, where N is the size of the formed vector.
11259   // Each EXTRACT_VECTOR should have the same input vector and odd or even
11260   // index such that we have a pair wise add pattern.
11261 
11262   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
11263   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11264     return SDValue();
11265   SDValue Vec = N0->getOperand(0)->getOperand(0);
11266   SDNode *V = Vec.getNode();
11267   unsigned nextIndex = 0;
11268 
11269   // For each operands to the ADD which are BUILD_VECTORs,
11270   // check to see if each of their operands are an EXTRACT_VECTOR with
11271   // the same vector and appropriate index.
11272   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
11273     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
11274         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11275 
11276       SDValue ExtVec0 = N0->getOperand(i);
11277       SDValue ExtVec1 = N1->getOperand(i);
11278 
11279       // First operand is the vector, verify its the same.
11280       if (V != ExtVec0->getOperand(0).getNode() ||
11281           V != ExtVec1->getOperand(0).getNode())
11282         return SDValue();
11283 
11284       // Second is the constant, verify its correct.
11285       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
11286       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
11287 
11288       // For the constant, we want to see all the even or all the odd.
11289       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
11290           || C1->getZExtValue() != nextIndex+1)
11291         return SDValue();
11292 
11293       // Increment index.
11294       nextIndex+=2;
11295     } else
11296       return SDValue();
11297   }
11298 
11299   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
11300   // we're using the entire input vector, otherwise there's a size/legality
11301   // mismatch somewhere.
11302   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
11303       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
11304     return SDValue();
11305 
11306   // Create VPADDL node.
11307   SelectionDAG &DAG = DCI.DAG;
11308   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11309 
11310   SDLoc dl(N);
11311 
11312   // Build operand list.
11313   SmallVector<SDValue, 8> Ops;
11314   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
11315                                 TLI.getPointerTy(DAG.getDataLayout())));
11316 
11317   // Input is the vector.
11318   Ops.push_back(Vec);
11319 
11320   // Get widened type and narrowed type.
11321   MVT widenType;
11322   unsigned numElem = VT.getVectorNumElements();
11323 
11324   EVT inputLaneType = Vec.getValueType().getVectorElementType();
11325   switch (inputLaneType.getSimpleVT().SimpleTy) {
11326     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
11327     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
11328     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
11329     default:
11330       llvm_unreachable("Invalid vector element type for padd optimization.");
11331   }
11332 
11333   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
11334   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
11335   return DAG.getNode(ExtOp, dl, VT, tmp);
11336 }
11337 
11338 static SDValue findMUL_LOHI(SDValue V) {
11339   if (V->getOpcode() == ISD::UMUL_LOHI ||
11340       V->getOpcode() == ISD::SMUL_LOHI)
11341     return V;
11342   return SDValue();
11343 }
11344 
11345 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
11346                                         TargetLowering::DAGCombinerInfo &DCI,
11347                                         const ARMSubtarget *Subtarget) {
11348   if (!Subtarget->hasBaseDSP())
11349     return SDValue();
11350 
11351   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
11352   // accumulates the product into a 64-bit value. The 16-bit values will
11353   // be sign extended somehow or SRA'd into 32-bit values
11354   // (addc (adde (mul 16bit, 16bit), lo), hi)
11355   SDValue Mul = AddcNode->getOperand(0);
11356   SDValue Lo = AddcNode->getOperand(1);
11357   if (Mul.getOpcode() != ISD::MUL) {
11358     Lo = AddcNode->getOperand(0);
11359     Mul = AddcNode->getOperand(1);
11360     if (Mul.getOpcode() != ISD::MUL)
11361       return SDValue();
11362   }
11363 
11364   SDValue SRA = AddeNode->getOperand(0);
11365   SDValue Hi = AddeNode->getOperand(1);
11366   if (SRA.getOpcode() != ISD::SRA) {
11367     SRA = AddeNode->getOperand(1);
11368     Hi = AddeNode->getOperand(0);
11369     if (SRA.getOpcode() != ISD::SRA)
11370       return SDValue();
11371   }
11372   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
11373     if (Const->getZExtValue() != 31)
11374       return SDValue();
11375   } else
11376     return SDValue();
11377 
11378   if (SRA.getOperand(0) != Mul)
11379     return SDValue();
11380 
11381   SelectionDAG &DAG = DCI.DAG;
11382   SDLoc dl(AddcNode);
11383   unsigned Opcode = 0;
11384   SDValue Op0;
11385   SDValue Op1;
11386 
11387   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
11388     Opcode = ARMISD::SMLALBB;
11389     Op0 = Mul.getOperand(0);
11390     Op1 = Mul.getOperand(1);
11391   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
11392     Opcode = ARMISD::SMLALBT;
11393     Op0 = Mul.getOperand(0);
11394     Op1 = Mul.getOperand(1).getOperand(0);
11395   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
11396     Opcode = ARMISD::SMLALTB;
11397     Op0 = Mul.getOperand(0).getOperand(0);
11398     Op1 = Mul.getOperand(1);
11399   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
11400     Opcode = ARMISD::SMLALTT;
11401     Op0 = Mul->getOperand(0).getOperand(0);
11402     Op1 = Mul->getOperand(1).getOperand(0);
11403   }
11404 
11405   if (!Op0 || !Op1)
11406     return SDValue();
11407 
11408   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
11409                               Op0, Op1, Lo, Hi);
11410   // Replace the ADDs' nodes uses by the MLA node's values.
11411   SDValue HiMLALResult(SMLAL.getNode(), 1);
11412   SDValue LoMLALResult(SMLAL.getNode(), 0);
11413 
11414   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
11415   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
11416 
11417   // Return original node to notify the driver to stop replacing.
11418   SDValue resNode(AddcNode, 0);
11419   return resNode;
11420 }
11421 
11422 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
11423                                      TargetLowering::DAGCombinerInfo &DCI,
11424                                      const ARMSubtarget *Subtarget) {
11425   // Look for multiply add opportunities.
11426   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
11427   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
11428   // a glue link from the first add to the second add.
11429   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
11430   // a S/UMLAL instruction.
11431   //                  UMUL_LOHI
11432   //                 / :lo    \ :hi
11433   //                V          \          [no multiline comment]
11434   //    loAdd ->  ADDC         |
11435   //                 \ :carry /
11436   //                  V      V
11437   //                    ADDE   <- hiAdd
11438   //
11439   // In the special case where only the higher part of a signed result is used
11440   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
11441   // a constant with the exact value of 0x80000000, we recognize we are dealing
11442   // with a "rounded multiply and add" (or subtract) and transform it into
11443   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11444 
11445   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11446           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11447          "Expect an ADDE or SUBE");
11448 
11449   assert(AddeSubeNode->getNumOperands() == 3 &&
11450          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11451          "ADDE node has the wrong inputs");
11452 
11453   // Check that we are chained to the right ADDC or SUBC node.
11454   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11455   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11456        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11457       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11458        AddcSubcNode->getOpcode() != ARMISD::SUBC))
11459     return SDValue();
11460 
11461   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11462   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11463 
11464   // Check if the two operands are from the same mul_lohi node.
11465   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11466     return SDValue();
11467 
11468   assert(AddcSubcNode->getNumValues() == 2 &&
11469          AddcSubcNode->getValueType(0) == MVT::i32 &&
11470          "Expect ADDC with two result values. First: i32");
11471 
11472   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11473   // maybe a SMLAL which multiplies two 16-bit values.
11474   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11475       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11476       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11477       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11478       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11479     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11480 
11481   // Check for the triangle shape.
11482   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11483   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11484 
11485   // Make sure that the ADDE/SUBE operands are not coming from the same node.
11486   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11487     return SDValue();
11488 
11489   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11490   bool IsLeftOperandMUL = false;
11491   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11492   if (MULOp == SDValue())
11493     MULOp = findMUL_LOHI(AddeSubeOp1);
11494   else
11495     IsLeftOperandMUL = true;
11496   if (MULOp == SDValue())
11497     return SDValue();
11498 
11499   // Figure out the right opcode.
11500   unsigned Opc = MULOp->getOpcode();
11501   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11502 
11503   // Figure out the high and low input values to the MLAL node.
11504   SDValue *HiAddSub = nullptr;
11505   SDValue *LoMul = nullptr;
11506   SDValue *LowAddSub = nullptr;
11507 
11508   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11509   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11510     return SDValue();
11511 
11512   if (IsLeftOperandMUL)
11513     HiAddSub = &AddeSubeOp1;
11514   else
11515     HiAddSub = &AddeSubeOp0;
11516 
11517   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11518   // whose low result is fed to the ADDC/SUBC we are checking.
11519 
11520   if (AddcSubcOp0 == MULOp.getValue(0)) {
11521     LoMul = &AddcSubcOp0;
11522     LowAddSub = &AddcSubcOp1;
11523   }
11524   if (AddcSubcOp1 == MULOp.getValue(0)) {
11525     LoMul = &AddcSubcOp1;
11526     LowAddSub = &AddcSubcOp0;
11527   }
11528 
11529   if (!LoMul)
11530     return SDValue();
11531 
11532   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11533   // the replacement below will create a cycle.
11534   if (AddcSubcNode == HiAddSub->getNode() ||
11535       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11536     return SDValue();
11537 
11538   // Create the merged node.
11539   SelectionDAG &DAG = DCI.DAG;
11540 
11541   // Start building operand list.
11542   SmallVector<SDValue, 8> Ops;
11543   Ops.push_back(LoMul->getOperand(0));
11544   Ops.push_back(LoMul->getOperand(1));
11545 
11546   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
11547   // the case, we must be doing signed multiplication and only use the higher
11548   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11549   // addition or subtraction with the value of 0x800000.
11550   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11551       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11552       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11553       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11554           0x80000000) {
11555     Ops.push_back(*HiAddSub);
11556     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11557       FinalOpc = ARMISD::SMMLSR;
11558     } else {
11559       FinalOpc = ARMISD::SMMLAR;
11560     }
11561     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11562     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11563 
11564     return SDValue(AddeSubeNode, 0);
11565   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11566     // SMMLS is generated during instruction selection and the rest of this
11567     // function can not handle the case where AddcSubcNode is a SUBC.
11568     return SDValue();
11569 
11570   // Finish building the operand list for {U/S}MLAL
11571   Ops.push_back(*LowAddSub);
11572   Ops.push_back(*HiAddSub);
11573 
11574   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11575                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
11576 
11577   // Replace the ADDs' nodes uses by the MLA node's values.
11578   SDValue HiMLALResult(MLALNode.getNode(), 1);
11579   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11580 
11581   SDValue LoMLALResult(MLALNode.getNode(), 0);
11582   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11583 
11584   // Return original node to notify the driver to stop replacing.
11585   return SDValue(AddeSubeNode, 0);
11586 }
11587 
11588 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11589                                       TargetLowering::DAGCombinerInfo &DCI,
11590                                       const ARMSubtarget *Subtarget) {
11591   // UMAAL is similar to UMLAL except that it adds two unsigned values.
11592   // While trying to combine for the other MLAL nodes, first search for the
11593   // chance to use UMAAL. Check if Addc uses a node which has already
11594   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11595   // as the addend, and it's handled in PerformUMLALCombine.
11596 
11597   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11598     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11599 
11600   // Check that we have a glued ADDC node.
11601   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11602   if (AddcNode->getOpcode() != ARMISD::ADDC)
11603     return SDValue();
11604 
11605   // Find the converted UMAAL or quit if it doesn't exist.
11606   SDNode *UmlalNode = nullptr;
11607   SDValue AddHi;
11608   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11609     UmlalNode = AddcNode->getOperand(0).getNode();
11610     AddHi = AddcNode->getOperand(1);
11611   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11612     UmlalNode = AddcNode->getOperand(1).getNode();
11613     AddHi = AddcNode->getOperand(0);
11614   } else {
11615     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11616   }
11617 
11618   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11619   // the ADDC as well as Zero.
11620   if (!isNullConstant(UmlalNode->getOperand(3)))
11621     return SDValue();
11622 
11623   if ((isNullConstant(AddeNode->getOperand(0)) &&
11624        AddeNode->getOperand(1).getNode() == UmlalNode) ||
11625       (AddeNode->getOperand(0).getNode() == UmlalNode &&
11626        isNullConstant(AddeNode->getOperand(1)))) {
11627     SelectionDAG &DAG = DCI.DAG;
11628     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11629                       UmlalNode->getOperand(2), AddHi };
11630     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11631                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
11632 
11633     // Replace the ADDs' nodes uses by the UMAAL node's values.
11634     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11635     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11636 
11637     // Return original node to notify the driver to stop replacing.
11638     return SDValue(AddeNode, 0);
11639   }
11640   return SDValue();
11641 }
11642 
11643 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11644                                    const ARMSubtarget *Subtarget) {
11645   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11646     return SDValue();
11647 
11648   // Check that we have a pair of ADDC and ADDE as operands.
11649   // Both addends of the ADDE must be zero.
11650   SDNode* AddcNode = N->getOperand(2).getNode();
11651   SDNode* AddeNode = N->getOperand(3).getNode();
11652   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11653       (AddeNode->getOpcode() == ARMISD::ADDE) &&
11654       isNullConstant(AddeNode->getOperand(0)) &&
11655       isNullConstant(AddeNode->getOperand(1)) &&
11656       (AddeNode->getOperand(2).getNode() == AddcNode))
11657     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11658                        DAG.getVTList(MVT::i32, MVT::i32),
11659                        {N->getOperand(0), N->getOperand(1),
11660                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
11661   else
11662     return SDValue();
11663 }
11664 
11665 static SDValue PerformAddcSubcCombine(SDNode *N,
11666                                       TargetLowering::DAGCombinerInfo &DCI,
11667                                       const ARMSubtarget *Subtarget) {
11668   SelectionDAG &DAG(DCI.DAG);
11669 
11670   if (N->getOpcode() == ARMISD::SUBC) {
11671     // (SUBC (ADDE 0, 0, C), 1) -> C
11672     SDValue LHS = N->getOperand(0);
11673     SDValue RHS = N->getOperand(1);
11674     if (LHS->getOpcode() == ARMISD::ADDE &&
11675         isNullConstant(LHS->getOperand(0)) &&
11676         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11677       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11678     }
11679   }
11680 
11681   if (Subtarget->isThumb1Only()) {
11682     SDValue RHS = N->getOperand(1);
11683     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11684       int32_t imm = C->getSExtValue();
11685       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11686         SDLoc DL(N);
11687         RHS = DAG.getConstant(-imm, DL, MVT::i32);
11688         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11689                                                            : ARMISD::ADDC;
11690         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11691       }
11692     }
11693   }
11694 
11695   return SDValue();
11696 }
11697 
11698 static SDValue PerformAddeSubeCombine(SDNode *N,
11699                                       TargetLowering::DAGCombinerInfo &DCI,
11700                                       const ARMSubtarget *Subtarget) {
11701   if (Subtarget->isThumb1Only()) {
11702     SelectionDAG &DAG = DCI.DAG;
11703     SDValue RHS = N->getOperand(1);
11704     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11705       int64_t imm = C->getSExtValue();
11706       if (imm < 0) {
11707         SDLoc DL(N);
11708 
11709         // The with-carry-in form matches bitwise not instead of the negation.
11710         // Effectively, the inverse interpretation of the carry flag already
11711         // accounts for part of the negation.
11712         RHS = DAG.getConstant(~imm, DL, MVT::i32);
11713 
11714         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11715                                                            : ARMISD::ADDE;
11716         return DAG.getNode(Opcode, DL, N->getVTList(),
11717                            N->getOperand(0), RHS, N->getOperand(2));
11718       }
11719     }
11720   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11721     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11722   }
11723   return SDValue();
11724 }
11725 
11726 static SDValue PerformVSELECTCombine(SDNode *N,
11727                                      TargetLowering::DAGCombinerInfo &DCI,
11728                                      const ARMSubtarget *Subtarget) {
11729   // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
11730   //
11731   // We need to re-implement this optimization here as the implementation in the
11732   // Target-Independent DAGCombiner does not handle the kind of constant we make
11733   // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
11734   // good reason, allowing truncation there would break other targets).
11735   //
11736   // Currently, this is only done for MVE, as it's the only target that benefits
11737   // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
11738   if (!Subtarget->hasMVEIntegerOps())
11739     return SDValue();
11740 
11741   if (N->getOperand(0).getOpcode() != ISD::XOR)
11742     return SDValue();
11743   SDValue XOR = N->getOperand(0);
11744 
11745   // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
11746   // It is important to check with truncation allowed as the BUILD_VECTORs we
11747   // generate in those situations will truncate their operands.
11748   ConstantSDNode *Const =
11749       isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
11750                           /*AllowTruncation*/ true);
11751   if (!Const || !Const->isOne())
11752     return SDValue();
11753 
11754   // Rewrite into vselect(cond, rhs, lhs).
11755   SDValue Cond = XOR->getOperand(0);
11756   SDValue LHS = N->getOperand(1);
11757   SDValue RHS = N->getOperand(2);
11758   EVT Type = N->getValueType(0);
11759   return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
11760 }
11761 
11762 static SDValue PerformABSCombine(SDNode *N,
11763                                   TargetLowering::DAGCombinerInfo &DCI,
11764                                   const ARMSubtarget *Subtarget) {
11765   SDValue res;
11766   SelectionDAG &DAG = DCI.DAG;
11767   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11768 
11769   if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11770     return SDValue();
11771 
11772   if (!TLI.expandABS(N, res, DAG))
11773       return SDValue();
11774 
11775   return res;
11776 }
11777 
11778 /// PerformADDECombine - Target-specific dag combine transform from
11779 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11780 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11781 static SDValue PerformADDECombine(SDNode *N,
11782                                   TargetLowering::DAGCombinerInfo &DCI,
11783                                   const ARMSubtarget *Subtarget) {
11784   // Only ARM and Thumb2 support UMLAL/SMLAL.
11785   if (Subtarget->isThumb1Only())
11786     return PerformAddeSubeCombine(N, DCI, Subtarget);
11787 
11788   // Only perform the checks after legalize when the pattern is available.
11789   if (DCI.isBeforeLegalize()) return SDValue();
11790 
11791   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11792 }
11793 
11794 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11795 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
11796 /// called with the default operands, and if that fails, with commuted
11797 /// operands.
11798 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11799                                           TargetLowering::DAGCombinerInfo &DCI,
11800                                           const ARMSubtarget *Subtarget){
11801   // Attempt to create vpadd for this add.
11802   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11803     return Result;
11804 
11805   // Attempt to create vpaddl for this add.
11806   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11807     return Result;
11808   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11809                                                       Subtarget))
11810     return Result;
11811 
11812   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11813   if (N0.getNode()->hasOneUse())
11814     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11815       return Result;
11816   return SDValue();
11817 }
11818 
11819 static SDValue PerformADDVecReduce(SDNode *N,
11820                                    TargetLowering::DAGCombinerInfo &DCI,
11821                                    const ARMSubtarget *Subtarget) {
11822   if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64)
11823     return SDValue();
11824 
11825   SDValue N0 = N->getOperand(0);
11826   SDValue N1 = N->getOperand(1);
11827 
11828   // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
11829   // will look like:
11830   //   t1: i32,i32 = ARMISD::VADDLVs x
11831   //   t2: i64 = build_pair t1, t1:1
11832   //   t3: i64 = add t2, y
11833   // We also need to check for sext / zext and commutitive adds.
11834   auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
11835                            SDValue NB) {
11836     if (NB->getOpcode() != ISD::BUILD_PAIR)
11837       return SDValue();
11838     SDValue VecRed = NB->getOperand(0);
11839     if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 ||
11840         NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
11841       return SDValue();
11842 
11843     SDLoc dl(N);
11844     SmallVector<SDValue, 4> Ops;
11845     Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
11846                                   DCI.DAG.getConstant(0, dl, MVT::i32)));
11847     Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
11848                                   DCI.DAG.getConstant(1, dl, MVT::i32)));
11849     for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++)
11850       Ops.push_back(VecRed->getOperand(i));
11851     SDValue Red = DCI.DAG.getNode(OpcodeA, dl,
11852                                   DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops);
11853     return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
11854                            SDValue(Red.getNode(), 1));
11855   };
11856 
11857   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
11858     return M;
11859   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
11860     return M;
11861   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
11862     return M;
11863   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
11864     return M;
11865   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
11866     return M;
11867   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
11868     return M;
11869   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
11870     return M;
11871   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
11872     return M;
11873   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
11874     return M;
11875   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
11876     return M;
11877   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
11878     return M;
11879   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
11880     return M;
11881   return SDValue();
11882 }
11883 
11884 bool
11885 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11886                                                  CombineLevel Level) const {
11887   if (Level == BeforeLegalizeTypes)
11888     return true;
11889 
11890   if (N->getOpcode() != ISD::SHL)
11891     return true;
11892 
11893   if (Subtarget->isThumb1Only()) {
11894     // Avoid making expensive immediates by commuting shifts. (This logic
11895     // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11896     // for free.)
11897     if (N->getOpcode() != ISD::SHL)
11898       return true;
11899     SDValue N1 = N->getOperand(0);
11900     if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11901         N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11902       return true;
11903     if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11904       if (Const->getAPIntValue().ult(256))
11905         return false;
11906       if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11907           Const->getAPIntValue().sgt(-256))
11908         return false;
11909     }
11910     return true;
11911   }
11912 
11913   // Turn off commute-with-shift transform after legalization, so it doesn't
11914   // conflict with PerformSHLSimplify.  (We could try to detect when
11915   // PerformSHLSimplify would trigger more precisely, but it isn't
11916   // really necessary.)
11917   return false;
11918 }
11919 
11920 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11921     const SDNode *N, CombineLevel Level) const {
11922   if (!Subtarget->isThumb1Only())
11923     return true;
11924 
11925   if (Level == BeforeLegalizeTypes)
11926     return true;
11927 
11928   return false;
11929 }
11930 
11931 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11932   if (!Subtarget->hasNEON()) {
11933     if (Subtarget->isThumb1Only())
11934       return VT.getScalarSizeInBits() <= 32;
11935     return true;
11936   }
11937   return VT.isScalarInteger();
11938 }
11939 
11940 static SDValue PerformSHLSimplify(SDNode *N,
11941                                 TargetLowering::DAGCombinerInfo &DCI,
11942                                 const ARMSubtarget *ST) {
11943   // Allow the generic combiner to identify potential bswaps.
11944   if (DCI.isBeforeLegalize())
11945     return SDValue();
11946 
11947   // DAG combiner will fold:
11948   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11949   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11950   // Other code patterns that can be also be modified have the following form:
11951   // b + ((a << 1) | 510)
11952   // b + ((a << 1) & 510)
11953   // b + ((a << 1) ^ 510)
11954   // b + ((a << 1) + 510)
11955 
11956   // Many instructions can  perform the shift for free, but it requires both
11957   // the operands to be registers. If c1 << c2 is too large, a mov immediate
11958   // instruction will needed. So, unfold back to the original pattern if:
11959   // - if c1 and c2 are small enough that they don't require mov imms.
11960   // - the user(s) of the node can perform an shl
11961 
11962   // No shifted operands for 16-bit instructions.
11963   if (ST->isThumb() && ST->isThumb1Only())
11964     return SDValue();
11965 
11966   // Check that all the users could perform the shl themselves.
11967   for (auto U : N->uses()) {
11968     switch(U->getOpcode()) {
11969     default:
11970       return SDValue();
11971     case ISD::SUB:
11972     case ISD::ADD:
11973     case ISD::AND:
11974     case ISD::OR:
11975     case ISD::XOR:
11976     case ISD::SETCC:
11977     case ARMISD::CMP:
11978       // Check that the user isn't already using a constant because there
11979       // aren't any instructions that support an immediate operand and a
11980       // shifted operand.
11981       if (isa<ConstantSDNode>(U->getOperand(0)) ||
11982           isa<ConstantSDNode>(U->getOperand(1)))
11983         return SDValue();
11984 
11985       // Check that it's not already using a shift.
11986       if (U->getOperand(0).getOpcode() == ISD::SHL ||
11987           U->getOperand(1).getOpcode() == ISD::SHL)
11988         return SDValue();
11989       break;
11990     }
11991   }
11992 
11993   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11994       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11995     return SDValue();
11996 
11997   if (N->getOperand(0).getOpcode() != ISD::SHL)
11998     return SDValue();
11999 
12000   SDValue SHL = N->getOperand(0);
12001 
12002   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
12003   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
12004   if (!C1ShlC2 || !C2)
12005     return SDValue();
12006 
12007   APInt C2Int = C2->getAPIntValue();
12008   APInt C1Int = C1ShlC2->getAPIntValue();
12009 
12010   // Check that performing a lshr will not lose any information.
12011   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
12012                                      C2Int.getBitWidth() - C2->getZExtValue());
12013   if ((C1Int & Mask) != C1Int)
12014     return SDValue();
12015 
12016   // Shift the first constant.
12017   C1Int.lshrInPlace(C2Int);
12018 
12019   // The immediates are encoded as an 8-bit value that can be rotated.
12020   auto LargeImm = [](const APInt &Imm) {
12021     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
12022     return Imm.getBitWidth() - Zeros > 8;
12023   };
12024 
12025   if (LargeImm(C1Int) || LargeImm(C2Int))
12026     return SDValue();
12027 
12028   SelectionDAG &DAG = DCI.DAG;
12029   SDLoc dl(N);
12030   SDValue X = SHL.getOperand(0);
12031   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
12032                               DAG.getConstant(C1Int, dl, MVT::i32));
12033   // Shift left to compensate for the lshr of C1Int.
12034   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
12035 
12036   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
12037              SHL.dump(); N->dump());
12038   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
12039   return Res;
12040 }
12041 
12042 
12043 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
12044 ///
12045 static SDValue PerformADDCombine(SDNode *N,
12046                                  TargetLowering::DAGCombinerInfo &DCI,
12047                                  const ARMSubtarget *Subtarget) {
12048   SDValue N0 = N->getOperand(0);
12049   SDValue N1 = N->getOperand(1);
12050 
12051   // Only works one way, because it needs an immediate operand.
12052   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12053     return Result;
12054 
12055   if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget))
12056     return Result;
12057 
12058   // First try with the default operand order.
12059   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
12060     return Result;
12061 
12062   // If that didn't work, try again with the operands commuted.
12063   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
12064 }
12065 
12066 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
12067 ///
12068 static SDValue PerformSUBCombine(SDNode *N,
12069                                  TargetLowering::DAGCombinerInfo &DCI,
12070                                  const ARMSubtarget *Subtarget) {
12071   SDValue N0 = N->getOperand(0);
12072   SDValue N1 = N->getOperand(1);
12073 
12074   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12075   if (N1.getNode()->hasOneUse())
12076     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
12077       return Result;
12078 
12079   if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
12080     return SDValue();
12081 
12082   // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
12083   // so that we can readily pattern match more mve instructions which can use
12084   // a scalar operand.
12085   SDValue VDup = N->getOperand(1);
12086   if (VDup->getOpcode() != ARMISD::VDUP)
12087     return SDValue();
12088 
12089   SDValue VMov = N->getOperand(0);
12090   if (VMov->getOpcode() == ISD::BITCAST)
12091     VMov = VMov->getOperand(0);
12092 
12093   if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
12094     return SDValue();
12095 
12096   SDLoc dl(N);
12097   SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
12098                                    DCI.DAG.getConstant(0, dl, MVT::i32),
12099                                    VDup->getOperand(0));
12100   return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
12101 }
12102 
12103 /// PerformVMULCombine
12104 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
12105 /// special multiplier accumulator forwarding.
12106 ///   vmul d3, d0, d2
12107 ///   vmla d3, d1, d2
12108 /// is faster than
12109 ///   vadd d3, d0, d1
12110 ///   vmul d3, d3, d2
12111 //  However, for (A + B) * (A + B),
12112 //    vadd d2, d0, d1
12113 //    vmul d3, d0, d2
12114 //    vmla d3, d1, d2
12115 //  is slower than
12116 //    vadd d2, d0, d1
12117 //    vmul d3, d2, d2
12118 static SDValue PerformVMULCombine(SDNode *N,
12119                                   TargetLowering::DAGCombinerInfo &DCI,
12120                                   const ARMSubtarget *Subtarget) {
12121   if (!Subtarget->hasVMLxForwarding())
12122     return SDValue();
12123 
12124   SelectionDAG &DAG = DCI.DAG;
12125   SDValue N0 = N->getOperand(0);
12126   SDValue N1 = N->getOperand(1);
12127   unsigned Opcode = N0.getOpcode();
12128   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12129       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
12130     Opcode = N1.getOpcode();
12131     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12132         Opcode != ISD::FADD && Opcode != ISD::FSUB)
12133       return SDValue();
12134     std::swap(N0, N1);
12135   }
12136 
12137   if (N0 == N1)
12138     return SDValue();
12139 
12140   EVT VT = N->getValueType(0);
12141   SDLoc DL(N);
12142   SDValue N00 = N0->getOperand(0);
12143   SDValue N01 = N0->getOperand(1);
12144   return DAG.getNode(Opcode, DL, VT,
12145                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
12146                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
12147 }
12148 
12149 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
12150                                       const ARMSubtarget *Subtarget) {
12151   EVT VT = N->getValueType(0);
12152   if (VT != MVT::v2i64)
12153     return SDValue();
12154 
12155   SDValue N0 = N->getOperand(0);
12156   SDValue N1 = N->getOperand(1);
12157 
12158   auto IsSignExt = [&](SDValue Op) {
12159     if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
12160       return SDValue();
12161     EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
12162     if (VT.getScalarSizeInBits() == 32)
12163       return Op->getOperand(0);
12164     return SDValue();
12165   };
12166   auto IsZeroExt = [&](SDValue Op) {
12167     // Zero extends are a little more awkward. At the point we are matching
12168     // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
12169     // That might be before of after a bitcast depending on how the and is
12170     // placed. Because this has to look through bitcasts, it is currently only
12171     // supported on LE.
12172     if (!Subtarget->isLittle())
12173       return SDValue();
12174 
12175     SDValue And = Op;
12176     if (And->getOpcode() == ISD::BITCAST)
12177       And = And->getOperand(0);
12178     if (And->getOpcode() != ISD::AND)
12179       return SDValue();
12180     SDValue Mask = And->getOperand(1);
12181     if (Mask->getOpcode() == ISD::BITCAST)
12182       Mask = Mask->getOperand(0);
12183 
12184     if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
12185         Mask.getValueType() != MVT::v4i32)
12186       return SDValue();
12187     if (isAllOnesConstant(Mask->getOperand(0)) &&
12188         isNullConstant(Mask->getOperand(1)) &&
12189         isAllOnesConstant(Mask->getOperand(2)) &&
12190         isNullConstant(Mask->getOperand(3)))
12191       return And->getOperand(0);
12192     return SDValue();
12193   };
12194 
12195   SDLoc dl(N);
12196   if (SDValue Op0 = IsSignExt(N0)) {
12197     if (SDValue Op1 = IsSignExt(N1)) {
12198       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12199       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12200       return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
12201     }
12202   }
12203   if (SDValue Op0 = IsZeroExt(N0)) {
12204     if (SDValue Op1 = IsZeroExt(N1)) {
12205       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12206       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12207       return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
12208     }
12209   }
12210 
12211   return SDValue();
12212 }
12213 
12214 static SDValue PerformMULCombine(SDNode *N,
12215                                  TargetLowering::DAGCombinerInfo &DCI,
12216                                  const ARMSubtarget *Subtarget) {
12217   SelectionDAG &DAG = DCI.DAG;
12218 
12219   EVT VT = N->getValueType(0);
12220   if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
12221     return PerformMVEVMULLCombine(N, DAG, Subtarget);
12222 
12223   if (Subtarget->isThumb1Only())
12224     return SDValue();
12225 
12226   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12227     return SDValue();
12228 
12229   if (VT.is64BitVector() || VT.is128BitVector())
12230     return PerformVMULCombine(N, DCI, Subtarget);
12231   if (VT != MVT::i32)
12232     return SDValue();
12233 
12234   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12235   if (!C)
12236     return SDValue();
12237 
12238   int64_t MulAmt = C->getSExtValue();
12239   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
12240 
12241   ShiftAmt = ShiftAmt & (32 - 1);
12242   SDValue V = N->getOperand(0);
12243   SDLoc DL(N);
12244 
12245   SDValue Res;
12246   MulAmt >>= ShiftAmt;
12247 
12248   if (MulAmt >= 0) {
12249     if (isPowerOf2_32(MulAmt - 1)) {
12250       // (mul x, 2^N + 1) => (add (shl x, N), x)
12251       Res = DAG.getNode(ISD::ADD, DL, VT,
12252                         V,
12253                         DAG.getNode(ISD::SHL, DL, VT,
12254                                     V,
12255                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
12256                                                     MVT::i32)));
12257     } else if (isPowerOf2_32(MulAmt + 1)) {
12258       // (mul x, 2^N - 1) => (sub (shl x, N), x)
12259       Res = DAG.getNode(ISD::SUB, DL, VT,
12260                         DAG.getNode(ISD::SHL, DL, VT,
12261                                     V,
12262                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
12263                                                     MVT::i32)),
12264                         V);
12265     } else
12266       return SDValue();
12267   } else {
12268     uint64_t MulAmtAbs = -MulAmt;
12269     if (isPowerOf2_32(MulAmtAbs + 1)) {
12270       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
12271       Res = DAG.getNode(ISD::SUB, DL, VT,
12272                         V,
12273                         DAG.getNode(ISD::SHL, DL, VT,
12274                                     V,
12275                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
12276                                                     MVT::i32)));
12277     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
12278       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
12279       Res = DAG.getNode(ISD::ADD, DL, VT,
12280                         V,
12281                         DAG.getNode(ISD::SHL, DL, VT,
12282                                     V,
12283                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
12284                                                     MVT::i32)));
12285       Res = DAG.getNode(ISD::SUB, DL, VT,
12286                         DAG.getConstant(0, DL, MVT::i32), Res);
12287     } else
12288       return SDValue();
12289   }
12290 
12291   if (ShiftAmt != 0)
12292     Res = DAG.getNode(ISD::SHL, DL, VT,
12293                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
12294 
12295   // Do not add new nodes to DAG combiner worklist.
12296   DCI.CombineTo(N, Res, false);
12297   return SDValue();
12298 }
12299 
12300 static SDValue CombineANDShift(SDNode *N,
12301                                TargetLowering::DAGCombinerInfo &DCI,
12302                                const ARMSubtarget *Subtarget) {
12303   // Allow DAGCombine to pattern-match before we touch the canonical form.
12304   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12305     return SDValue();
12306 
12307   if (N->getValueType(0) != MVT::i32)
12308     return SDValue();
12309 
12310   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12311   if (!N1C)
12312     return SDValue();
12313 
12314   uint32_t C1 = (uint32_t)N1C->getZExtValue();
12315   // Don't transform uxtb/uxth.
12316   if (C1 == 255 || C1 == 65535)
12317     return SDValue();
12318 
12319   SDNode *N0 = N->getOperand(0).getNode();
12320   if (!N0->hasOneUse())
12321     return SDValue();
12322 
12323   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
12324     return SDValue();
12325 
12326   bool LeftShift = N0->getOpcode() == ISD::SHL;
12327 
12328   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12329   if (!N01C)
12330     return SDValue();
12331 
12332   uint32_t C2 = (uint32_t)N01C->getZExtValue();
12333   if (!C2 || C2 >= 32)
12334     return SDValue();
12335 
12336   // Clear irrelevant bits in the mask.
12337   if (LeftShift)
12338     C1 &= (-1U << C2);
12339   else
12340     C1 &= (-1U >> C2);
12341 
12342   SelectionDAG &DAG = DCI.DAG;
12343   SDLoc DL(N);
12344 
12345   // We have a pattern of the form "(and (shl x, c2) c1)" or
12346   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
12347   // transform to a pair of shifts, to save materializing c1.
12348 
12349   // First pattern: right shift, then mask off leading bits.
12350   // FIXME: Use demanded bits?
12351   if (!LeftShift && isMask_32(C1)) {
12352     uint32_t C3 = countLeadingZeros(C1);
12353     if (C2 < C3) {
12354       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12355                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12356       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12357                          DAG.getConstant(C3, DL, MVT::i32));
12358     }
12359   }
12360 
12361   // First pattern, reversed: left shift, then mask off trailing bits.
12362   if (LeftShift && isMask_32(~C1)) {
12363     uint32_t C3 = countTrailingZeros(C1);
12364     if (C2 < C3) {
12365       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12366                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12367       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12368                          DAG.getConstant(C3, DL, MVT::i32));
12369     }
12370   }
12371 
12372   // Second pattern: left shift, then mask off leading bits.
12373   // FIXME: Use demanded bits?
12374   if (LeftShift && isShiftedMask_32(C1)) {
12375     uint32_t Trailing = countTrailingZeros(C1);
12376     uint32_t C3 = countLeadingZeros(C1);
12377     if (Trailing == C2 && C2 + C3 < 32) {
12378       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12379                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12380       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12381                         DAG.getConstant(C3, DL, MVT::i32));
12382     }
12383   }
12384 
12385   // Second pattern, reversed: right shift, then mask off trailing bits.
12386   // FIXME: Handle other patterns of known/demanded bits.
12387   if (!LeftShift && isShiftedMask_32(C1)) {
12388     uint32_t Leading = countLeadingZeros(C1);
12389     uint32_t C3 = countTrailingZeros(C1);
12390     if (Leading == C2 && C2 + C3 < 32) {
12391       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12392                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12393       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12394                          DAG.getConstant(C3, DL, MVT::i32));
12395     }
12396   }
12397 
12398   // FIXME: Transform "(and (shl x, c2) c1)" ->
12399   // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
12400   // c1.
12401   return SDValue();
12402 }
12403 
12404 static SDValue PerformANDCombine(SDNode *N,
12405                                  TargetLowering::DAGCombinerInfo &DCI,
12406                                  const ARMSubtarget *Subtarget) {
12407   // Attempt to use immediate-form VBIC
12408   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12409   SDLoc dl(N);
12410   EVT VT = N->getValueType(0);
12411   SelectionDAG &DAG = DCI.DAG;
12412 
12413   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12414     return SDValue();
12415 
12416   APInt SplatBits, SplatUndef;
12417   unsigned SplatBitSize;
12418   bool HasAnyUndefs;
12419   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
12420       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12421     if (SplatBitSize <= 64) {
12422       EVT VbicVT;
12423       SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
12424                                       SplatUndef.getZExtValue(), SplatBitSize,
12425                                       DAG, dl, VbicVT, VT, OtherModImm);
12426       if (Val.getNode()) {
12427         SDValue Input =
12428           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
12429         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
12430         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
12431       }
12432     }
12433   }
12434 
12435   if (!Subtarget->isThumb1Only()) {
12436     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
12437     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
12438       return Result;
12439 
12440     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12441       return Result;
12442   }
12443 
12444   if (Subtarget->isThumb1Only())
12445     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
12446       return Result;
12447 
12448   return SDValue();
12449 }
12450 
12451 // Try combining OR nodes to SMULWB, SMULWT.
12452 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
12453                                          TargetLowering::DAGCombinerInfo &DCI,
12454                                          const ARMSubtarget *Subtarget) {
12455   if (!Subtarget->hasV6Ops() ||
12456       (Subtarget->isThumb() &&
12457        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
12458     return SDValue();
12459 
12460   SDValue SRL = OR->getOperand(0);
12461   SDValue SHL = OR->getOperand(1);
12462 
12463   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
12464     SRL = OR->getOperand(1);
12465     SHL = OR->getOperand(0);
12466   }
12467   if (!isSRL16(SRL) || !isSHL16(SHL))
12468     return SDValue();
12469 
12470   // The first operands to the shifts need to be the two results from the
12471   // same smul_lohi node.
12472   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
12473        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
12474     return SDValue();
12475 
12476   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
12477   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
12478       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
12479     return SDValue();
12480 
12481   // Now we have:
12482   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
12483   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
12484   // For SMUWB the 16-bit value will signed extended somehow.
12485   // For SMULWT only the SRA is required.
12486   // Check both sides of SMUL_LOHI
12487   SDValue OpS16 = SMULLOHI->getOperand(0);
12488   SDValue OpS32 = SMULLOHI->getOperand(1);
12489 
12490   SelectionDAG &DAG = DCI.DAG;
12491   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
12492     OpS16 = OpS32;
12493     OpS32 = SMULLOHI->getOperand(0);
12494   }
12495 
12496   SDLoc dl(OR);
12497   unsigned Opcode = 0;
12498   if (isS16(OpS16, DAG))
12499     Opcode = ARMISD::SMULWB;
12500   else if (isSRA16(OpS16)) {
12501     Opcode = ARMISD::SMULWT;
12502     OpS16 = OpS16->getOperand(0);
12503   }
12504   else
12505     return SDValue();
12506 
12507   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
12508   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
12509   return SDValue(OR, 0);
12510 }
12511 
12512 static SDValue PerformORCombineToBFI(SDNode *N,
12513                                      TargetLowering::DAGCombinerInfo &DCI,
12514                                      const ARMSubtarget *Subtarget) {
12515   // BFI is only available on V6T2+
12516   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
12517     return SDValue();
12518 
12519   EVT VT = N->getValueType(0);
12520   SDValue N0 = N->getOperand(0);
12521   SDValue N1 = N->getOperand(1);
12522   SelectionDAG &DAG = DCI.DAG;
12523   SDLoc DL(N);
12524   // 1) or (and A, mask), val => ARMbfi A, val, mask
12525   //      iff (val & mask) == val
12526   //
12527   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12528   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
12529   //          && mask == ~mask2
12530   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
12531   //          && ~mask == mask2
12532   //  (i.e., copy a bitfield value into another bitfield of the same width)
12533 
12534   if (VT != MVT::i32)
12535     return SDValue();
12536 
12537   SDValue N00 = N0.getOperand(0);
12538 
12539   // The value and the mask need to be constants so we can verify this is
12540   // actually a bitfield set. If the mask is 0xffff, we can do better
12541   // via a movt instruction, so don't use BFI in that case.
12542   SDValue MaskOp = N0.getOperand(1);
12543   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
12544   if (!MaskC)
12545     return SDValue();
12546   unsigned Mask = MaskC->getZExtValue();
12547   if (Mask == 0xffff)
12548     return SDValue();
12549   SDValue Res;
12550   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
12551   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12552   if (N1C) {
12553     unsigned Val = N1C->getZExtValue();
12554     if ((Val & ~Mask) != Val)
12555       return SDValue();
12556 
12557     if (ARM::isBitFieldInvertedMask(Mask)) {
12558       Val >>= countTrailingZeros(~Mask);
12559 
12560       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
12561                         DAG.getConstant(Val, DL, MVT::i32),
12562                         DAG.getConstant(Mask, DL, MVT::i32));
12563 
12564       DCI.CombineTo(N, Res, false);
12565       // Return value from the original node to inform the combiner than N is
12566       // now dead.
12567       return SDValue(N, 0);
12568     }
12569   } else if (N1.getOpcode() == ISD::AND) {
12570     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12571     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12572     if (!N11C)
12573       return SDValue();
12574     unsigned Mask2 = N11C->getZExtValue();
12575 
12576     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
12577     // as is to match.
12578     if (ARM::isBitFieldInvertedMask(Mask) &&
12579         (Mask == ~Mask2)) {
12580       // The pack halfword instruction works better for masks that fit it,
12581       // so use that when it's available.
12582       if (Subtarget->hasDSP() &&
12583           (Mask == 0xffff || Mask == 0xffff0000))
12584         return SDValue();
12585       // 2a
12586       unsigned amt = countTrailingZeros(Mask2);
12587       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
12588                         DAG.getConstant(amt, DL, MVT::i32));
12589       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
12590                         DAG.getConstant(Mask, DL, MVT::i32));
12591       DCI.CombineTo(N, Res, false);
12592       // Return value from the original node to inform the combiner than N is
12593       // now dead.
12594       return SDValue(N, 0);
12595     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
12596                (~Mask == Mask2)) {
12597       // The pack halfword instruction works better for masks that fit it,
12598       // so use that when it's available.
12599       if (Subtarget->hasDSP() &&
12600           (Mask2 == 0xffff || Mask2 == 0xffff0000))
12601         return SDValue();
12602       // 2b
12603       unsigned lsb = countTrailingZeros(Mask);
12604       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
12605                         DAG.getConstant(lsb, DL, MVT::i32));
12606       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
12607                         DAG.getConstant(Mask2, DL, MVT::i32));
12608       DCI.CombineTo(N, Res, false);
12609       // Return value from the original node to inform the combiner than N is
12610       // now dead.
12611       return SDValue(N, 0);
12612     }
12613   }
12614 
12615   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
12616       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
12617       ARM::isBitFieldInvertedMask(~Mask)) {
12618     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
12619     // where lsb(mask) == #shamt and masked bits of B are known zero.
12620     SDValue ShAmt = N00.getOperand(1);
12621     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
12622     unsigned LSB = countTrailingZeros(Mask);
12623     if (ShAmtC != LSB)
12624       return SDValue();
12625 
12626     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
12627                       DAG.getConstant(~Mask, DL, MVT::i32));
12628 
12629     DCI.CombineTo(N, Res, false);
12630     // Return value from the original node to inform the combiner than N is
12631     // now dead.
12632     return SDValue(N, 0);
12633   }
12634 
12635   return SDValue();
12636 }
12637 
12638 static bool isValidMVECond(unsigned CC, bool IsFloat) {
12639   switch (CC) {
12640   case ARMCC::EQ:
12641   case ARMCC::NE:
12642   case ARMCC::LE:
12643   case ARMCC::GT:
12644   case ARMCC::GE:
12645   case ARMCC::LT:
12646     return true;
12647   case ARMCC::HS:
12648   case ARMCC::HI:
12649     return !IsFloat;
12650   default:
12651     return false;
12652   };
12653 }
12654 
12655 static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
12656   if (N->getOpcode() == ARMISD::VCMP)
12657     return (ARMCC::CondCodes)N->getConstantOperandVal(2);
12658   else if (N->getOpcode() == ARMISD::VCMPZ)
12659     return (ARMCC::CondCodes)N->getConstantOperandVal(1);
12660   else
12661     llvm_unreachable("Not a VCMP/VCMPZ!");
12662 }
12663 
12664 static bool CanInvertMVEVCMP(SDValue N) {
12665   ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N));
12666   return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
12667 }
12668 
12669 static SDValue PerformORCombine_i1(SDNode *N,
12670                                    TargetLowering::DAGCombinerInfo &DCI,
12671                                    const ARMSubtarget *Subtarget) {
12672   // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
12673   // together with predicates
12674   EVT VT = N->getValueType(0);
12675   SDLoc DL(N);
12676   SDValue N0 = N->getOperand(0);
12677   SDValue N1 = N->getOperand(1);
12678 
12679   auto IsFreelyInvertable = [&](SDValue V) {
12680     if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
12681       return CanInvertMVEVCMP(V);
12682     return false;
12683   };
12684 
12685   // At least one operand must be freely invertable.
12686   if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
12687     return SDValue();
12688 
12689   SDValue NewN0 = DCI.DAG.getLogicalNOT(DL, N0, VT);
12690   SDValue NewN1 = DCI.DAG.getLogicalNOT(DL, N1, VT);
12691   SDValue And = DCI.DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
12692   return DCI.DAG.getLogicalNOT(DL, And, VT);
12693 }
12694 
12695 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
12696 static SDValue PerformORCombine(SDNode *N,
12697                                 TargetLowering::DAGCombinerInfo &DCI,
12698                                 const ARMSubtarget *Subtarget) {
12699   // Attempt to use immediate-form VORR
12700   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12701   SDLoc dl(N);
12702   EVT VT = N->getValueType(0);
12703   SelectionDAG &DAG = DCI.DAG;
12704 
12705   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12706     return SDValue();
12707 
12708   APInt SplatBits, SplatUndef;
12709   unsigned SplatBitSize;
12710   bool HasAnyUndefs;
12711   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
12712       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12713     if (SplatBitSize <= 64) {
12714       EVT VorrVT;
12715       SDValue Val =
12716           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
12717                             SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
12718       if (Val.getNode()) {
12719         SDValue Input =
12720           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
12721         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
12722         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
12723       }
12724     }
12725   }
12726 
12727   if (!Subtarget->isThumb1Only()) {
12728     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12729     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12730       return Result;
12731     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
12732       return Result;
12733   }
12734 
12735   SDValue N0 = N->getOperand(0);
12736   SDValue N1 = N->getOperand(1);
12737 
12738   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
12739   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
12740       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12741 
12742     // The code below optimizes (or (and X, Y), Z).
12743     // The AND operand needs to have a single user to make these optimizations
12744     // profitable.
12745     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
12746       return SDValue();
12747 
12748     APInt SplatUndef;
12749     unsigned SplatBitSize;
12750     bool HasAnyUndefs;
12751 
12752     APInt SplatBits0, SplatBits1;
12753     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
12754     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
12755     // Ensure that the second operand of both ands are constants
12756     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
12757                                       HasAnyUndefs) && !HasAnyUndefs) {
12758         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
12759                                           HasAnyUndefs) && !HasAnyUndefs) {
12760             // Ensure that the bit width of the constants are the same and that
12761             // the splat arguments are logical inverses as per the pattern we
12762             // are trying to simplify.
12763             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
12764                 SplatBits0 == ~SplatBits1) {
12765                 // Canonicalize the vector type to make instruction selection
12766                 // simpler.
12767                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
12768                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
12769                                              N0->getOperand(1),
12770                                              N0->getOperand(0),
12771                                              N1->getOperand(0));
12772                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12773             }
12774         }
12775     }
12776   }
12777 
12778   if (Subtarget->hasMVEIntegerOps() &&
12779       (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
12780     return PerformORCombine_i1(N, DCI, Subtarget);
12781 
12782   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
12783   // reasonable.
12784   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
12785     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
12786       return Res;
12787   }
12788 
12789   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12790     return Result;
12791 
12792   return SDValue();
12793 }
12794 
12795 static SDValue PerformXORCombine(SDNode *N,
12796                                  TargetLowering::DAGCombinerInfo &DCI,
12797                                  const ARMSubtarget *Subtarget) {
12798   EVT VT = N->getValueType(0);
12799   SelectionDAG &DAG = DCI.DAG;
12800 
12801   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12802     return SDValue();
12803 
12804   if (!Subtarget->isThumb1Only()) {
12805     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12806     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12807       return Result;
12808 
12809     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12810       return Result;
12811   }
12812 
12813   if (Subtarget->hasMVEIntegerOps()) {
12814     // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
12815     SDValue N0 = N->getOperand(0);
12816     SDValue N1 = N->getOperand(1);
12817     const TargetLowering *TLI = Subtarget->getTargetLowering();
12818     if (TLI->isConstTrueVal(N1.getNode()) &&
12819         (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
12820       if (CanInvertMVEVCMP(N0)) {
12821         SDLoc DL(N0);
12822         ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0));
12823 
12824         SmallVector<SDValue, 4> Ops;
12825         Ops.push_back(N0->getOperand(0));
12826         if (N0->getOpcode() == ARMISD::VCMP)
12827           Ops.push_back(N0->getOperand(1));
12828         Ops.push_back(DCI.DAG.getConstant(CC, DL, MVT::i32));
12829         return DCI.DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
12830       }
12831     }
12832   }
12833 
12834   return SDValue();
12835 }
12836 
12837 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12838 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12839 // their position in "to" (Rd).
12840 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12841   assert(N->getOpcode() == ARMISD::BFI);
12842 
12843   SDValue From = N->getOperand(1);
12844   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12845   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12846 
12847   // If the Base came from a SHR #C, we can deduce that it is really testing bit
12848   // #C in the base of the SHR.
12849   if (From->getOpcode() == ISD::SRL &&
12850       isa<ConstantSDNode>(From->getOperand(1))) {
12851     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12852     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12853     FromMask <<= Shift.getLimitedValue(31);
12854     From = From->getOperand(0);
12855   }
12856 
12857   return From;
12858 }
12859 
12860 // If A and B contain one contiguous set of bits, does A | B == A . B?
12861 //
12862 // Neither A nor B must be zero.
12863 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12864   unsigned LastActiveBitInA =  A.countTrailingZeros();
12865   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12866   return LastActiveBitInA - 1 == FirstActiveBitInB;
12867 }
12868 
12869 static SDValue FindBFIToCombineWith(SDNode *N) {
12870   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12871   // if one exists.
12872   APInt ToMask, FromMask;
12873   SDValue From = ParseBFI(N, ToMask, FromMask);
12874   SDValue To = N->getOperand(0);
12875 
12876   // Now check for a compatible BFI to merge with. We can pass through BFIs that
12877   // aren't compatible, but not if they set the same bit in their destination as
12878   // we do (or that of any BFI we're going to combine with).
12879   SDValue V = To;
12880   APInt CombinedToMask = ToMask;
12881   while (V.getOpcode() == ARMISD::BFI) {
12882     APInt NewToMask, NewFromMask;
12883     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12884     if (NewFrom != From) {
12885       // This BFI has a different base. Keep going.
12886       CombinedToMask |= NewToMask;
12887       V = V.getOperand(0);
12888       continue;
12889     }
12890 
12891     // Do the written bits conflict with any we've seen so far?
12892     if ((NewToMask & CombinedToMask).getBoolValue())
12893       // Conflicting bits - bail out because going further is unsafe.
12894       return SDValue();
12895 
12896     // Are the new bits contiguous when combined with the old bits?
12897     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12898         BitsProperlyConcatenate(FromMask, NewFromMask))
12899       return V;
12900     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12901         BitsProperlyConcatenate(NewFromMask, FromMask))
12902       return V;
12903 
12904     // We've seen a write to some bits, so track it.
12905     CombinedToMask |= NewToMask;
12906     // Keep going...
12907     V = V.getOperand(0);
12908   }
12909 
12910   return SDValue();
12911 }
12912 
12913 static SDValue PerformBFICombine(SDNode *N,
12914                                  TargetLowering::DAGCombinerInfo &DCI) {
12915   SDValue N1 = N->getOperand(1);
12916   if (N1.getOpcode() == ISD::AND) {
12917     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12918     // the bits being cleared by the AND are not demanded by the BFI.
12919     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12920     if (!N11C)
12921       return SDValue();
12922     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12923     unsigned LSB = countTrailingZeros(~InvMask);
12924     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12925     assert(Width <
12926                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12927            "undefined behavior");
12928     unsigned Mask = (1u << Width) - 1;
12929     unsigned Mask2 = N11C->getZExtValue();
12930     if ((Mask & (~Mask2)) == 0)
12931       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12932                              N->getOperand(0), N1.getOperand(0),
12933                              N->getOperand(2));
12934   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12935     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12936     // Keep track of any consecutive bits set that all come from the same base
12937     // value. We can combine these together into a single BFI.
12938     SDValue CombineBFI = FindBFIToCombineWith(N);
12939     if (CombineBFI == SDValue())
12940       return SDValue();
12941 
12942     // We've found a BFI.
12943     APInt ToMask1, FromMask1;
12944     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12945 
12946     APInt ToMask2, FromMask2;
12947     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12948     assert(From1 == From2);
12949     (void)From2;
12950 
12951     // First, unlink CombineBFI.
12952     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12953     // Then create a new BFI, combining the two together.
12954     APInt NewFromMask = FromMask1 | FromMask2;
12955     APInt NewToMask = ToMask1 | ToMask2;
12956 
12957     EVT VT = N->getValueType(0);
12958     SDLoc dl(N);
12959 
12960     if (NewFromMask[0] == 0)
12961       From1 = DCI.DAG.getNode(
12962         ISD::SRL, dl, VT, From1,
12963         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12964     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12965                            DCI.DAG.getConstant(~NewToMask, dl, VT));
12966   }
12967   return SDValue();
12968 }
12969 
12970 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12971 /// ARMISD::VMOVRRD.
12972 static SDValue PerformVMOVRRDCombine(SDNode *N,
12973                                      TargetLowering::DAGCombinerInfo &DCI,
12974                                      const ARMSubtarget *Subtarget) {
12975   // vmovrrd(vmovdrr x, y) -> x,y
12976   SDValue InDouble = N->getOperand(0);
12977   if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12978     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12979 
12980   // vmovrrd(load f64) -> (load i32), (load i32)
12981   SDNode *InNode = InDouble.getNode();
12982   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12983       InNode->getValueType(0) == MVT::f64 &&
12984       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12985       !cast<LoadSDNode>(InNode)->isVolatile()) {
12986     // TODO: Should this be done for non-FrameIndex operands?
12987     LoadSDNode *LD = cast<LoadSDNode>(InNode);
12988 
12989     SelectionDAG &DAG = DCI.DAG;
12990     SDLoc DL(LD);
12991     SDValue BasePtr = LD->getBasePtr();
12992     SDValue NewLD1 =
12993         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12994                     LD->getAlignment(), LD->getMemOperand()->getFlags());
12995 
12996     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12997                                     DAG.getConstant(4, DL, MVT::i32));
12998 
12999     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
13000                                  LD->getPointerInfo().getWithOffset(4),
13001                                  std::min(4U, LD->getAlignment()),
13002                                  LD->getMemOperand()->getFlags());
13003 
13004     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
13005     if (DCI.DAG.getDataLayout().isBigEndian())
13006       std::swap (NewLD1, NewLD2);
13007     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
13008     return Result;
13009   }
13010 
13011   return SDValue();
13012 }
13013 
13014 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
13015 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
13016 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
13017   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
13018   SDValue Op0 = N->getOperand(0);
13019   SDValue Op1 = N->getOperand(1);
13020   if (Op0.getOpcode() == ISD::BITCAST)
13021     Op0 = Op0.getOperand(0);
13022   if (Op1.getOpcode() == ISD::BITCAST)
13023     Op1 = Op1.getOperand(0);
13024   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
13025       Op0.getNode() == Op1.getNode() &&
13026       Op0.getResNo() == 0 && Op1.getResNo() == 1)
13027     return DAG.getNode(ISD::BITCAST, SDLoc(N),
13028                        N->getValueType(0), Op0.getOperand(0));
13029   return SDValue();
13030 }
13031 
13032 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13033   SDValue Op0 = N->getOperand(0);
13034 
13035   // VMOVhr (VMOVrh (X)) -> X
13036   if (Op0->getOpcode() == ARMISD::VMOVrh)
13037     return Op0->getOperand(0);
13038 
13039   // FullFP16: half values are passed in S-registers, and we don't
13040   // need any of the bitcast and moves:
13041   //
13042   //     t2: f32,ch = CopyFromReg t0, Register:f32 %0
13043   //   t5: i32 = bitcast t2
13044   // t18: f16 = ARMISD::VMOVhr t5
13045   if (Op0->getOpcode() == ISD::BITCAST) {
13046     SDValue Copy = Op0->getOperand(0);
13047     if (Copy.getValueType() == MVT::f32 &&
13048         Copy->getOpcode() == ISD::CopyFromReg) {
13049       SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)};
13050       SDValue NewCopy =
13051           DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), MVT::f16, Ops);
13052       return NewCopy;
13053     }
13054   }
13055 
13056   // fold (VMOVhr (load x)) -> (load (f16*)x)
13057   if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
13058     if (LN0->hasOneUse() && LN0->isUnindexed() &&
13059         LN0->getMemoryVT() == MVT::i16) {
13060       SDValue Load = DCI.DAG.getLoad(MVT::f16, SDLoc(N), LN0->getChain(),
13061                                      LN0->getBasePtr(), LN0->getMemOperand());
13062       DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13063       DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
13064       return Load;
13065     }
13066   }
13067 
13068   // Only the bottom 16 bits of the source register are used.
13069   APInt DemandedMask = APInt::getLowBitsSet(32, 16);
13070   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
13071   if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
13072     return SDValue(N, 0);
13073 
13074   return SDValue();
13075 }
13076 
13077 static SDValue PerformVMOVrhCombine(SDNode *N,
13078                                     TargetLowering::DAGCombinerInfo &DCI) {
13079   SDValue N0 = N->getOperand(0);
13080   EVT VT = N->getValueType(0);
13081 
13082   // fold (VMOVrh (load x)) -> (zextload (i16*)x)
13083   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
13084     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
13085 
13086     SDValue Load =
13087         DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
13088                            LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
13089     DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13090     DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
13091     return Load;
13092   }
13093 
13094   return SDValue();
13095 }
13096 
13097 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
13098 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
13099 /// i64 vector to have f64 elements, since the value can then be loaded
13100 /// directly into a VFP register.
13101 static bool hasNormalLoadOperand(SDNode *N) {
13102   unsigned NumElts = N->getValueType(0).getVectorNumElements();
13103   for (unsigned i = 0; i < NumElts; ++i) {
13104     SDNode *Elt = N->getOperand(i).getNode();
13105     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
13106       return true;
13107   }
13108   return false;
13109 }
13110 
13111 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
13112 /// ISD::BUILD_VECTOR.
13113 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
13114                                           TargetLowering::DAGCombinerInfo &DCI,
13115                                           const ARMSubtarget *Subtarget) {
13116   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
13117   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
13118   // into a pair of GPRs, which is fine when the value is used as a scalar,
13119   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
13120   SelectionDAG &DAG = DCI.DAG;
13121   if (N->getNumOperands() == 2)
13122     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
13123       return RV;
13124 
13125   // Load i64 elements as f64 values so that type legalization does not split
13126   // them up into i32 values.
13127   EVT VT = N->getValueType(0);
13128   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
13129     return SDValue();
13130   SDLoc dl(N);
13131   SmallVector<SDValue, 8> Ops;
13132   unsigned NumElts = VT.getVectorNumElements();
13133   for (unsigned i = 0; i < NumElts; ++i) {
13134     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
13135     Ops.push_back(V);
13136     // Make the DAGCombiner fold the bitcast.
13137     DCI.AddToWorklist(V.getNode());
13138   }
13139   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
13140   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
13141   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
13142 }
13143 
13144 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
13145 static SDValue
13146 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13147   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
13148   // At that time, we may have inserted bitcasts from integer to float.
13149   // If these bitcasts have survived DAGCombine, change the lowering of this
13150   // BUILD_VECTOR in something more vector friendly, i.e., that does not
13151   // force to use floating point types.
13152 
13153   // Make sure we can change the type of the vector.
13154   // This is possible iff:
13155   // 1. The vector is only used in a bitcast to a integer type. I.e.,
13156   //    1.1. Vector is used only once.
13157   //    1.2. Use is a bit convert to an integer type.
13158   // 2. The size of its operands are 32-bits (64-bits are not legal).
13159   EVT VT = N->getValueType(0);
13160   EVT EltVT = VT.getVectorElementType();
13161 
13162   // Check 1.1. and 2.
13163   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
13164     return SDValue();
13165 
13166   // By construction, the input type must be float.
13167   assert(EltVT == MVT::f32 && "Unexpected type!");
13168 
13169   // Check 1.2.
13170   SDNode *Use = *N->use_begin();
13171   if (Use->getOpcode() != ISD::BITCAST ||
13172       Use->getValueType(0).isFloatingPoint())
13173     return SDValue();
13174 
13175   // Check profitability.
13176   // Model is, if more than half of the relevant operands are bitcast from
13177   // i32, turn the build_vector into a sequence of insert_vector_elt.
13178   // Relevant operands are everything that is not statically
13179   // (i.e., at compile time) bitcasted.
13180   unsigned NumOfBitCastedElts = 0;
13181   unsigned NumElts = VT.getVectorNumElements();
13182   unsigned NumOfRelevantElts = NumElts;
13183   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
13184     SDValue Elt = N->getOperand(Idx);
13185     if (Elt->getOpcode() == ISD::BITCAST) {
13186       // Assume only bit cast to i32 will go away.
13187       if (Elt->getOperand(0).getValueType() == MVT::i32)
13188         ++NumOfBitCastedElts;
13189     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
13190       // Constants are statically casted, thus do not count them as
13191       // relevant operands.
13192       --NumOfRelevantElts;
13193   }
13194 
13195   // Check if more than half of the elements require a non-free bitcast.
13196   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
13197     return SDValue();
13198 
13199   SelectionDAG &DAG = DCI.DAG;
13200   // Create the new vector type.
13201   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
13202   // Check if the type is legal.
13203   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13204   if (!TLI.isTypeLegal(VecVT))
13205     return SDValue();
13206 
13207   // Combine:
13208   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
13209   // => BITCAST INSERT_VECTOR_ELT
13210   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
13211   //                      (BITCAST EN), N.
13212   SDValue Vec = DAG.getUNDEF(VecVT);
13213   SDLoc dl(N);
13214   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
13215     SDValue V = N->getOperand(Idx);
13216     if (V.isUndef())
13217       continue;
13218     if (V.getOpcode() == ISD::BITCAST &&
13219         V->getOperand(0).getValueType() == MVT::i32)
13220       // Fold obvious case.
13221       V = V.getOperand(0);
13222     else {
13223       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
13224       // Make the DAGCombiner fold the bitcasts.
13225       DCI.AddToWorklist(V.getNode());
13226     }
13227     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
13228     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
13229   }
13230   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
13231   // Make the DAGCombiner fold the bitcasts.
13232   DCI.AddToWorklist(Vec.getNode());
13233   return Vec;
13234 }
13235 
13236 static SDValue
13237 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13238   EVT VT = N->getValueType(0);
13239   SDValue Op = N->getOperand(0);
13240   SDLoc dl(N);
13241 
13242   // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
13243   if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
13244     // If the valuetypes are the same, we can remove the cast entirely.
13245     if (Op->getOperand(0).getValueType() == VT)
13246       return Op->getOperand(0);
13247     return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
13248   }
13249 
13250   return SDValue();
13251 }
13252 
13253 static SDValue
13254 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13255                               const ARMSubtarget *ST) {
13256   EVT VT = N->getValueType(0);
13257   SDValue Op = N->getOperand(0);
13258   SDLoc dl(N);
13259 
13260   // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
13261   if (ST->isLittle())
13262     return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op);
13263 
13264   // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
13265   if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
13266     // If the valuetypes are the same, we can remove the cast entirely.
13267     if (Op->getOperand(0).getValueType() == VT)
13268       return Op->getOperand(0);
13269     return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
13270   }
13271 
13272   return SDValue();
13273 }
13274 
13275 static SDValue PerformVCMPCombine(SDNode *N,
13276                                   TargetLowering::DAGCombinerInfo &DCI,
13277                                   const ARMSubtarget *Subtarget) {
13278   if (!Subtarget->hasMVEIntegerOps())
13279     return SDValue();
13280 
13281   EVT VT = N->getValueType(0);
13282   SDValue Op0 = N->getOperand(0);
13283   SDValue Op1 = N->getOperand(1);
13284   ARMCC::CondCodes Cond =
13285       (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13286   SDLoc dl(N);
13287 
13288   // vcmp X, 0, cc -> vcmpz X, cc
13289   if (isZeroVector(Op1))
13290     return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0,
13291                            N->getOperand(2));
13292 
13293   unsigned SwappedCond = getSwappedCondition(Cond);
13294   if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
13295     // vcmp 0, X, cc -> vcmpz X, reversed(cc)
13296     if (isZeroVector(Op0))
13297       return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
13298                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13299     // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
13300     if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
13301       return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
13302                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13303   }
13304 
13305   return SDValue();
13306 }
13307 
13308 /// PerformInsertEltCombine - Target-specific dag combine xforms for
13309 /// ISD::INSERT_VECTOR_ELT.
13310 static SDValue PerformInsertEltCombine(SDNode *N,
13311                                        TargetLowering::DAGCombinerInfo &DCI) {
13312   // Bitcast an i64 load inserted into a vector to f64.
13313   // Otherwise, the i64 value will be legalized to a pair of i32 values.
13314   EVT VT = N->getValueType(0);
13315   SDNode *Elt = N->getOperand(1).getNode();
13316   if (VT.getVectorElementType() != MVT::i64 ||
13317       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
13318     return SDValue();
13319 
13320   SelectionDAG &DAG = DCI.DAG;
13321   SDLoc dl(N);
13322   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13323                                  VT.getVectorNumElements());
13324   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
13325   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
13326   // Make the DAGCombiner fold the bitcasts.
13327   DCI.AddToWorklist(Vec.getNode());
13328   DCI.AddToWorklist(V.getNode());
13329   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
13330                                Vec, V, N->getOperand(2));
13331   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
13332 }
13333 
13334 static SDValue PerformExtractEltCombine(SDNode *N,
13335                                         TargetLowering::DAGCombinerInfo &DCI) {
13336   SDValue Op0 = N->getOperand(0);
13337   EVT VT = N->getValueType(0);
13338   SDLoc dl(N);
13339 
13340   // extract (vdup x) -> x
13341   if (Op0->getOpcode() == ARMISD::VDUP) {
13342     SDValue X = Op0->getOperand(0);
13343     if (VT == MVT::f16 && X.getValueType() == MVT::i32)
13344       return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
13345     if (VT == MVT::i32 && X.getValueType() == MVT::f16)
13346       return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
13347 
13348     while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
13349       X = X->getOperand(0);
13350     if (X.getValueType() == VT)
13351       return X;
13352   }
13353 
13354   return SDValue();
13355 }
13356 
13357 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
13358 /// ISD::VECTOR_SHUFFLE.
13359 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
13360   // The LLVM shufflevector instruction does not require the shuffle mask
13361   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
13362   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
13363   // operands do not match the mask length, they are extended by concatenating
13364   // them with undef vectors.  That is probably the right thing for other
13365   // targets, but for NEON it is better to concatenate two double-register
13366   // size vector operands into a single quad-register size vector.  Do that
13367   // transformation here:
13368   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
13369   //   shuffle(concat(v1, v2), undef)
13370   SDValue Op0 = N->getOperand(0);
13371   SDValue Op1 = N->getOperand(1);
13372   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
13373       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
13374       Op0.getNumOperands() != 2 ||
13375       Op1.getNumOperands() != 2)
13376     return SDValue();
13377   SDValue Concat0Op1 = Op0.getOperand(1);
13378   SDValue Concat1Op1 = Op1.getOperand(1);
13379   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
13380     return SDValue();
13381   // Skip the transformation if any of the types are illegal.
13382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13383   EVT VT = N->getValueType(0);
13384   if (!TLI.isTypeLegal(VT) ||
13385       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
13386       !TLI.isTypeLegal(Concat1Op1.getValueType()))
13387     return SDValue();
13388 
13389   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13390                                   Op0.getOperand(0), Op1.getOperand(0));
13391   // Translate the shuffle mask.
13392   SmallVector<int, 16> NewMask;
13393   unsigned NumElts = VT.getVectorNumElements();
13394   unsigned HalfElts = NumElts/2;
13395   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13396   for (unsigned n = 0; n < NumElts; ++n) {
13397     int MaskElt = SVN->getMaskElt(n);
13398     int NewElt = -1;
13399     if (MaskElt < (int)HalfElts)
13400       NewElt = MaskElt;
13401     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
13402       NewElt = HalfElts + MaskElt - NumElts;
13403     NewMask.push_back(NewElt);
13404   }
13405   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
13406                               DAG.getUNDEF(VT), NewMask);
13407 }
13408 
13409 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
13410 /// NEON load/store intrinsics, and generic vector load/stores, to merge
13411 /// base address updates.
13412 /// For generic load/stores, the memory type is assumed to be a vector.
13413 /// The caller is assumed to have checked legality.
13414 static SDValue CombineBaseUpdate(SDNode *N,
13415                                  TargetLowering::DAGCombinerInfo &DCI) {
13416   SelectionDAG &DAG = DCI.DAG;
13417   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
13418                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
13419   const bool isStore = N->getOpcode() == ISD::STORE;
13420   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
13421   SDValue Addr = N->getOperand(AddrOpIdx);
13422   MemSDNode *MemN = cast<MemSDNode>(N);
13423   SDLoc dl(N);
13424 
13425   // Search for a use of the address operand that is an increment.
13426   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
13427          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
13428     SDNode *User = *UI;
13429     if (User->getOpcode() != ISD::ADD ||
13430         UI.getUse().getResNo() != Addr.getResNo())
13431       continue;
13432 
13433     // Check that the add is independent of the load/store.  Otherwise, folding
13434     // it would create a cycle. We can avoid searching through Addr as it's a
13435     // predecessor to both.
13436     SmallPtrSet<const SDNode *, 32> Visited;
13437     SmallVector<const SDNode *, 16> Worklist;
13438     Visited.insert(Addr.getNode());
13439     Worklist.push_back(N);
13440     Worklist.push_back(User);
13441     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
13442         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13443       continue;
13444 
13445     // Find the new opcode for the updating load/store.
13446     bool isLoadOp = true;
13447     bool isLaneOp = false;
13448     unsigned NewOpc = 0;
13449     unsigned NumVecs = 0;
13450     if (isIntrinsic) {
13451       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
13452       switch (IntNo) {
13453       default: llvm_unreachable("unexpected intrinsic for Neon base update");
13454       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
13455         NumVecs = 1; break;
13456       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
13457         NumVecs = 2; break;
13458       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
13459         NumVecs = 3; break;
13460       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
13461         NumVecs = 4; break;
13462       case Intrinsic::arm_neon_vld2dup:
13463       case Intrinsic::arm_neon_vld3dup:
13464       case Intrinsic::arm_neon_vld4dup:
13465         // TODO: Support updating VLDxDUP nodes. For now, we just skip
13466         // combining base updates for such intrinsics.
13467         continue;
13468       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
13469         NumVecs = 2; isLaneOp = true; break;
13470       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
13471         NumVecs = 3; isLaneOp = true; break;
13472       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
13473         NumVecs = 4; isLaneOp = true; break;
13474       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
13475         NumVecs = 1; isLoadOp = false; break;
13476       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
13477         NumVecs = 2; isLoadOp = false; break;
13478       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
13479         NumVecs = 3; isLoadOp = false; break;
13480       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
13481         NumVecs = 4; isLoadOp = false; break;
13482       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
13483         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
13484       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
13485         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
13486       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
13487         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
13488       }
13489     } else {
13490       isLaneOp = true;
13491       switch (N->getOpcode()) {
13492       default: llvm_unreachable("unexpected opcode for Neon base update");
13493       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
13494       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
13495       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
13496       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
13497       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
13498         NumVecs = 1; isLaneOp = false; break;
13499       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
13500         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
13501       }
13502     }
13503 
13504     // Find the size of memory referenced by the load/store.
13505     EVT VecTy;
13506     if (isLoadOp) {
13507       VecTy = N->getValueType(0);
13508     } else if (isIntrinsic) {
13509       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
13510     } else {
13511       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
13512       VecTy = N->getOperand(1).getValueType();
13513     }
13514 
13515     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
13516     if (isLaneOp)
13517       NumBytes /= VecTy.getVectorNumElements();
13518 
13519     // If the increment is a constant, it must match the memory ref size.
13520     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13521     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
13522     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
13523       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
13524       // separate instructions that make it harder to use a non-constant update.
13525       continue;
13526     }
13527 
13528     // OK, we found an ADD we can fold into the base update.
13529     // Now, create a _UPD node, taking care of not breaking alignment.
13530 
13531     EVT AlignedVecTy = VecTy;
13532     unsigned Alignment = MemN->getAlignment();
13533 
13534     // If this is a less-than-standard-aligned load/store, change the type to
13535     // match the standard alignment.
13536     // The alignment is overlooked when selecting _UPD variants; and it's
13537     // easier to introduce bitcasts here than fix that.
13538     // There are 3 ways to get to this base-update combine:
13539     // - intrinsics: they are assumed to be properly aligned (to the standard
13540     //   alignment of the memory type), so we don't need to do anything.
13541     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
13542     //   intrinsics, so, likewise, there's nothing to do.
13543     // - generic load/store instructions: the alignment is specified as an
13544     //   explicit operand, rather than implicitly as the standard alignment
13545     //   of the memory type (like the intrisics).  We need to change the
13546     //   memory type to match the explicit alignment.  That way, we don't
13547     //   generate non-standard-aligned ARMISD::VLDx nodes.
13548     if (isa<LSBaseSDNode>(N)) {
13549       if (Alignment == 0)
13550         Alignment = 1;
13551       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
13552         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
13553         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
13554         assert(!isLaneOp && "Unexpected generic load/store lane.");
13555         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
13556         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
13557       }
13558       // Don't set an explicit alignment on regular load/stores that we want
13559       // to transform to VLD/VST 1_UPD nodes.
13560       // This matches the behavior of regular load/stores, which only get an
13561       // explicit alignment if the MMO alignment is larger than the standard
13562       // alignment of the memory type.
13563       // Intrinsics, however, always get an explicit alignment, set to the
13564       // alignment of the MMO.
13565       Alignment = 1;
13566     }
13567 
13568     // Create the new updating load/store node.
13569     // First, create an SDVTList for the new updating node's results.
13570     EVT Tys[6];
13571     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
13572     unsigned n;
13573     for (n = 0; n < NumResultVecs; ++n)
13574       Tys[n] = AlignedVecTy;
13575     Tys[n++] = MVT::i32;
13576     Tys[n] = MVT::Other;
13577     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
13578 
13579     // Then, gather the new node's operands.
13580     SmallVector<SDValue, 8> Ops;
13581     Ops.push_back(N->getOperand(0)); // incoming chain
13582     Ops.push_back(N->getOperand(AddrOpIdx));
13583     Ops.push_back(Inc);
13584 
13585     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
13586       // Try to match the intrinsic's signature
13587       Ops.push_back(StN->getValue());
13588     } else {
13589       // Loads (and of course intrinsics) match the intrinsics' signature,
13590       // so just add all but the alignment operand.
13591       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
13592         Ops.push_back(N->getOperand(i));
13593     }
13594 
13595     // For all node types, the alignment operand is always the last one.
13596     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
13597 
13598     // If this is a non-standard-aligned STORE, the penultimate operand is the
13599     // stored value.  Bitcast it to the aligned type.
13600     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
13601       SDValue &StVal = Ops[Ops.size()-2];
13602       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
13603     }
13604 
13605     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
13606     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
13607                                            MemN->getMemOperand());
13608 
13609     // Update the uses.
13610     SmallVector<SDValue, 5> NewResults;
13611     for (unsigned i = 0; i < NumResultVecs; ++i)
13612       NewResults.push_back(SDValue(UpdN.getNode(), i));
13613 
13614     // If this is an non-standard-aligned LOAD, the first result is the loaded
13615     // value.  Bitcast it to the expected result type.
13616     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
13617       SDValue &LdVal = NewResults[0];
13618       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
13619     }
13620 
13621     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
13622     DCI.CombineTo(N, NewResults);
13623     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13624 
13625     break;
13626   }
13627   return SDValue();
13628 }
13629 
13630 static SDValue PerformVLDCombine(SDNode *N,
13631                                  TargetLowering::DAGCombinerInfo &DCI) {
13632   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13633     return SDValue();
13634 
13635   return CombineBaseUpdate(N, DCI);
13636 }
13637 
13638 static SDValue PerformMVEVLDCombine(SDNode *N,
13639                                     TargetLowering::DAGCombinerInfo &DCI) {
13640   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13641     return SDValue();
13642 
13643   SelectionDAG &DAG = DCI.DAG;
13644   SDValue Addr = N->getOperand(2);
13645   MemSDNode *MemN = cast<MemSDNode>(N);
13646   SDLoc dl(N);
13647 
13648   // For the stores, where there are multiple intrinsics we only actually want
13649   // to post-inc the last of the them.
13650   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
13651   if (IntNo == Intrinsic::arm_mve_vst2q &&
13652       cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1)
13653     return SDValue();
13654   if (IntNo == Intrinsic::arm_mve_vst4q &&
13655       cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3)
13656     return SDValue();
13657 
13658   // Search for a use of the address operand that is an increment.
13659   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
13660                             UE = Addr.getNode()->use_end();
13661        UI != UE; ++UI) {
13662     SDNode *User = *UI;
13663     if (User->getOpcode() != ISD::ADD ||
13664         UI.getUse().getResNo() != Addr.getResNo())
13665       continue;
13666 
13667     // Check that the add is independent of the load/store.  Otherwise, folding
13668     // it would create a cycle. We can avoid searching through Addr as it's a
13669     // predecessor to both.
13670     SmallPtrSet<const SDNode *, 32> Visited;
13671     SmallVector<const SDNode *, 16> Worklist;
13672     Visited.insert(Addr.getNode());
13673     Worklist.push_back(N);
13674     Worklist.push_back(User);
13675     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
13676         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13677       continue;
13678 
13679     // Find the new opcode for the updating load/store.
13680     bool isLoadOp = true;
13681     unsigned NewOpc = 0;
13682     unsigned NumVecs = 0;
13683     switch (IntNo) {
13684     default:
13685       llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
13686     case Intrinsic::arm_mve_vld2q:
13687       NewOpc = ARMISD::VLD2_UPD;
13688       NumVecs = 2;
13689       break;
13690     case Intrinsic::arm_mve_vld4q:
13691       NewOpc = ARMISD::VLD4_UPD;
13692       NumVecs = 4;
13693       break;
13694     case Intrinsic::arm_mve_vst2q:
13695       NewOpc = ARMISD::VST2_UPD;
13696       NumVecs = 2;
13697       isLoadOp = false;
13698       break;
13699     case Intrinsic::arm_mve_vst4q:
13700       NewOpc = ARMISD::VST4_UPD;
13701       NumVecs = 4;
13702       isLoadOp = false;
13703       break;
13704     }
13705 
13706     // Find the size of memory referenced by the load/store.
13707     EVT VecTy;
13708     if (isLoadOp) {
13709       VecTy = N->getValueType(0);
13710     } else {
13711       VecTy = N->getOperand(3).getValueType();
13712     }
13713 
13714     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
13715 
13716     // If the increment is a constant, it must match the memory ref size.
13717     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13718     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
13719     if (!CInc || CInc->getZExtValue() != NumBytes)
13720       continue;
13721 
13722     // Create the new updating load/store node.
13723     // First, create an SDVTList for the new updating node's results.
13724     EVT Tys[6];
13725     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
13726     unsigned n;
13727     for (n = 0; n < NumResultVecs; ++n)
13728       Tys[n] = VecTy;
13729     Tys[n++] = MVT::i32;
13730     Tys[n] = MVT::Other;
13731     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
13732 
13733     // Then, gather the new node's operands.
13734     SmallVector<SDValue, 8> Ops;
13735     Ops.push_back(N->getOperand(0)); // incoming chain
13736     Ops.push_back(N->getOperand(2)); // ptr
13737     Ops.push_back(Inc);
13738 
13739     for (unsigned i = 3; i < N->getNumOperands(); ++i)
13740       Ops.push_back(N->getOperand(i));
13741 
13742     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
13743                                            MemN->getMemOperand());
13744 
13745     // Update the uses.
13746     SmallVector<SDValue, 5> NewResults;
13747     for (unsigned i = 0; i < NumResultVecs; ++i)
13748       NewResults.push_back(SDValue(UpdN.getNode(), i));
13749 
13750     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
13751     DCI.CombineTo(N, NewResults);
13752     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13753 
13754     break;
13755   }
13756 
13757   return SDValue();
13758 }
13759 
13760 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
13761 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
13762 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
13763 /// return true.
13764 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13765   SelectionDAG &DAG = DCI.DAG;
13766   EVT VT = N->getValueType(0);
13767   // vldN-dup instructions only support 64-bit vectors for N > 1.
13768   if (!VT.is64BitVector())
13769     return false;
13770 
13771   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
13772   SDNode *VLD = N->getOperand(0).getNode();
13773   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
13774     return false;
13775   unsigned NumVecs = 0;
13776   unsigned NewOpc = 0;
13777   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
13778   if (IntNo == Intrinsic::arm_neon_vld2lane) {
13779     NumVecs = 2;
13780     NewOpc = ARMISD::VLD2DUP;
13781   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
13782     NumVecs = 3;
13783     NewOpc = ARMISD::VLD3DUP;
13784   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
13785     NumVecs = 4;
13786     NewOpc = ARMISD::VLD4DUP;
13787   } else {
13788     return false;
13789   }
13790 
13791   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
13792   // numbers match the load.
13793   unsigned VLDLaneNo =
13794     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
13795   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13796        UI != UE; ++UI) {
13797     // Ignore uses of the chain result.
13798     if (UI.getUse().getResNo() == NumVecs)
13799       continue;
13800     SDNode *User = *UI;
13801     if (User->getOpcode() != ARMISD::VDUPLANE ||
13802         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
13803       return false;
13804   }
13805 
13806   // Create the vldN-dup node.
13807   EVT Tys[5];
13808   unsigned n;
13809   for (n = 0; n < NumVecs; ++n)
13810     Tys[n] = VT;
13811   Tys[n] = MVT::Other;
13812   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
13813   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
13814   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
13815   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
13816                                            Ops, VLDMemInt->getMemoryVT(),
13817                                            VLDMemInt->getMemOperand());
13818 
13819   // Update the uses.
13820   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13821        UI != UE; ++UI) {
13822     unsigned ResNo = UI.getUse().getResNo();
13823     // Ignore uses of the chain result.
13824     if (ResNo == NumVecs)
13825       continue;
13826     SDNode *User = *UI;
13827     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
13828   }
13829 
13830   // Now the vldN-lane intrinsic is dead except for its chain result.
13831   // Update uses of the chain.
13832   std::vector<SDValue> VLDDupResults;
13833   for (unsigned n = 0; n < NumVecs; ++n)
13834     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
13835   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
13836   DCI.CombineTo(VLD, VLDDupResults);
13837 
13838   return true;
13839 }
13840 
13841 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
13842 /// ARMISD::VDUPLANE.
13843 static SDValue PerformVDUPLANECombine(SDNode *N,
13844                                       TargetLowering::DAGCombinerInfo &DCI) {
13845   SDValue Op = N->getOperand(0);
13846 
13847   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
13848   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
13849   if (CombineVLDDUP(N, DCI))
13850     return SDValue(N, 0);
13851 
13852   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
13853   // redundant.  Ignore bit_converts for now; element sizes are checked below.
13854   while (Op.getOpcode() == ISD::BITCAST)
13855     Op = Op.getOperand(0);
13856   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
13857     return SDValue();
13858 
13859   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
13860   unsigned EltSize = Op.getScalarValueSizeInBits();
13861   // The canonical VMOV for a zero vector uses a 32-bit element size.
13862   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13863   unsigned EltBits;
13864   if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
13865     EltSize = 8;
13866   EVT VT = N->getValueType(0);
13867   if (EltSize > VT.getScalarSizeInBits())
13868     return SDValue();
13869 
13870   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
13871 }
13872 
13873 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
13874 static SDValue PerformVDUPCombine(SDNode *N,
13875                                   TargetLowering::DAGCombinerInfo &DCI,
13876                                   const ARMSubtarget *Subtarget) {
13877   SelectionDAG &DAG = DCI.DAG;
13878   SDValue Op = N->getOperand(0);
13879   SDLoc dl(N);
13880 
13881   if (Subtarget->hasMVEIntegerOps()) {
13882     // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
13883     // need to come from a GPR.
13884     if (Op.getValueType() == MVT::f32)
13885       return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
13886                              DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
13887     else if (Op.getValueType() == MVT::f16)
13888       return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
13889                              DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
13890   }
13891 
13892   if (!Subtarget->hasNEON())
13893     return SDValue();
13894 
13895   // Match VDUP(LOAD) -> VLD1DUP.
13896   // We match this pattern here rather than waiting for isel because the
13897   // transform is only legal for unindexed loads.
13898   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
13899   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
13900       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
13901     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
13902                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
13903     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
13904     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
13905                                              Ops, LD->getMemoryVT(),
13906                                              LD->getMemOperand());
13907     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
13908     return VLDDup;
13909   }
13910 
13911   return SDValue();
13912 }
13913 
13914 static SDValue PerformLOADCombine(SDNode *N,
13915                                   TargetLowering::DAGCombinerInfo &DCI) {
13916   EVT VT = N->getValueType(0);
13917 
13918   // If this is a legal vector load, try to combine it into a VLD1_UPD.
13919   if (ISD::isNormalLoad(N) && VT.isVector() &&
13920       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13921     return CombineBaseUpdate(N, DCI);
13922 
13923   return SDValue();
13924 }
13925 
13926 // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
13927 // pack all of the elements in one place.  Next, store to memory in fewer
13928 // chunks.
13929 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
13930                                              SelectionDAG &DAG) {
13931   SDValue StVal = St->getValue();
13932   EVT VT = StVal.getValueType();
13933   if (!St->isTruncatingStore() || !VT.isVector())
13934     return SDValue();
13935   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13936   EVT StVT = St->getMemoryVT();
13937   unsigned NumElems = VT.getVectorNumElements();
13938   assert(StVT != VT && "Cannot truncate to the same type");
13939   unsigned FromEltSz = VT.getScalarSizeInBits();
13940   unsigned ToEltSz = StVT.getScalarSizeInBits();
13941 
13942   // From, To sizes and ElemCount must be pow of two
13943   if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
13944     return SDValue();
13945 
13946   // We are going to use the original vector elt for storing.
13947   // Accumulated smaller vector elements must be a multiple of the store size.
13948   if (0 != (NumElems * FromEltSz) % ToEltSz)
13949     return SDValue();
13950 
13951   unsigned SizeRatio = FromEltSz / ToEltSz;
13952   assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
13953 
13954   // Create a type on which we perform the shuffle.
13955   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
13956                                    NumElems * SizeRatio);
13957   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13958 
13959   SDLoc DL(St);
13960   SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
13961   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13962   for (unsigned i = 0; i < NumElems; ++i)
13963     ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
13964                                                       : i * SizeRatio;
13965 
13966   // Can't shuffle using an illegal type.
13967   if (!TLI.isTypeLegal(WideVecVT))
13968     return SDValue();
13969 
13970   SDValue Shuff = DAG.getVectorShuffle(
13971       WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
13972   // At this point all of the data is stored at the bottom of the
13973   // register. We now need to save it to mem.
13974 
13975   // Find the largest store unit
13976   MVT StoreType = MVT::i8;
13977   for (MVT Tp : MVT::integer_valuetypes()) {
13978     if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
13979       StoreType = Tp;
13980   }
13981   // Didn't find a legal store type.
13982   if (!TLI.isTypeLegal(StoreType))
13983     return SDValue();
13984 
13985   // Bitcast the original vector into a vector of store-size units
13986   EVT StoreVecVT =
13987       EVT::getVectorVT(*DAG.getContext(), StoreType,
13988                        VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
13989   assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13990   SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
13991   SmallVector<SDValue, 8> Chains;
13992   SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
13993                                       TLI.getPointerTy(DAG.getDataLayout()));
13994   SDValue BasePtr = St->getBasePtr();
13995 
13996   // Perform one or more big stores into memory.
13997   unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
13998   for (unsigned I = 0; I < E; I++) {
13999     SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
14000                                  ShuffWide, DAG.getIntPtrConstant(I, DL));
14001     SDValue Ch =
14002         DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
14003                      St->getAlignment(), St->getMemOperand()->getFlags());
14004     BasePtr =
14005         DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
14006     Chains.push_back(Ch);
14007   }
14008   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
14009 }
14010 
14011 // Try taking a single vector store from an truncate (which would otherwise turn
14012 // into an expensive buildvector) and splitting it into a series of narrowing
14013 // stores.
14014 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
14015                                                  SelectionDAG &DAG) {
14016   if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
14017     return SDValue();
14018   SDValue Trunc = St->getValue();
14019   if (Trunc->getOpcode() != ISD::TRUNCATE)
14020     return SDValue();
14021   EVT FromVT = Trunc->getOperand(0).getValueType();
14022   EVT ToVT = Trunc.getValueType();
14023   if (!ToVT.isVector())
14024     return SDValue();
14025   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
14026   EVT ToEltVT = ToVT.getVectorElementType();
14027   EVT FromEltVT = FromVT.getVectorElementType();
14028 
14029   unsigned NumElements = 0;
14030   if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8))
14031     NumElements = 4;
14032   if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8)
14033     NumElements = 8;
14034   if (NumElements == 0 || FromVT.getVectorNumElements() == NumElements ||
14035       FromVT.getVectorNumElements() % NumElements != 0)
14036     return SDValue();
14037 
14038   // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so
14039   // use the VMOVN over splitting the store. We are looking for patterns of:
14040   // !rev: 0 N 1 N+1 2 N+2 ...
14041   //  rev: N 0 N+1 1 N+2 2 ...
14042   auto isVMOVNOriginalMask = [&](ArrayRef<int> M, bool rev) {
14043     unsigned NumElts = ToVT.getVectorNumElements();
14044     if (NumElts != M.size() || (ToVT != MVT::v8i16 && ToVT != MVT::v16i8))
14045       return false;
14046 
14047     unsigned Off0 = rev ? NumElts : 0;
14048     unsigned Off1 = rev ? 0 : NumElts;
14049 
14050     for (unsigned i = 0; i < NumElts; i += 2) {
14051       if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
14052         return false;
14053       if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
14054         return false;
14055     }
14056 
14057     return true;
14058   };
14059 
14060   if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc->getOperand(0)))
14061     if (isVMOVNOriginalMask(Shuffle->getMask(), false) ||
14062         isVMOVNOriginalMask(Shuffle->getMask(), true))
14063       return SDValue();
14064 
14065   SDLoc DL(St);
14066   // Details about the old store
14067   SDValue Ch = St->getChain();
14068   SDValue BasePtr = St->getBasePtr();
14069   Align Alignment = St->getOriginalAlign();
14070   MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
14071   AAMDNodes AAInfo = St->getAAInfo();
14072 
14073   EVT NewFromVT = EVT::getVectorVT(*DAG.getContext(), FromEltVT, NumElements);
14074   EVT NewToVT = EVT::getVectorVT(*DAG.getContext(), ToEltVT, NumElements);
14075 
14076   SmallVector<SDValue, 4> Stores;
14077   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
14078     unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
14079     SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
14080 
14081     SDValue Extract =
14082         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
14083                     DAG.getConstant(i * NumElements, DL, MVT::i32));
14084     SDValue Store = DAG.getTruncStore(
14085         Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
14086         NewToVT, Alignment.value(), MMOFlags, AAInfo);
14087     Stores.push_back(Store);
14088   }
14089   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
14090 }
14091 
14092 /// PerformSTORECombine - Target-specific dag combine xforms for
14093 /// ISD::STORE.
14094 static SDValue PerformSTORECombine(SDNode *N,
14095                                    TargetLowering::DAGCombinerInfo &DCI,
14096                                    const ARMSubtarget *Subtarget) {
14097   StoreSDNode *St = cast<StoreSDNode>(N);
14098   if (St->isVolatile())
14099     return SDValue();
14100   SDValue StVal = St->getValue();
14101   EVT VT = StVal.getValueType();
14102 
14103   if (Subtarget->hasNEON())
14104     if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
14105       return Store;
14106 
14107   if (Subtarget->hasMVEIntegerOps())
14108     if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
14109       return NewToken;
14110 
14111   if (!ISD::isNormalStore(St))
14112     return SDValue();
14113 
14114   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
14115   // ARM stores of arguments in the same cache line.
14116   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
14117       StVal.getNode()->hasOneUse()) {
14118     SelectionDAG  &DAG = DCI.DAG;
14119     bool isBigEndian = DAG.getDataLayout().isBigEndian();
14120     SDLoc DL(St);
14121     SDValue BasePtr = St->getBasePtr();
14122     SDValue NewST1 = DAG.getStore(
14123         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
14124         BasePtr, St->getPointerInfo(), St->getAlignment(),
14125         St->getMemOperand()->getFlags());
14126 
14127     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
14128                                     DAG.getConstant(4, DL, MVT::i32));
14129     return DAG.getStore(NewST1.getValue(0), DL,
14130                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
14131                         OffsetPtr, St->getPointerInfo(),
14132                         std::min(4U, St->getAlignment() / 2),
14133                         St->getMemOperand()->getFlags());
14134   }
14135 
14136   if (StVal.getValueType() == MVT::i64 &&
14137       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14138 
14139     // Bitcast an i64 store extracted from a vector to f64.
14140     // Otherwise, the i64 value will be legalized to a pair of i32 values.
14141     SelectionDAG &DAG = DCI.DAG;
14142     SDLoc dl(StVal);
14143     SDValue IntVec = StVal.getOperand(0);
14144     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
14145                                    IntVec.getValueType().getVectorNumElements());
14146     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
14147     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
14148                                  Vec, StVal.getOperand(1));
14149     dl = SDLoc(N);
14150     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
14151     // Make the DAGCombiner fold the bitcasts.
14152     DCI.AddToWorklist(Vec.getNode());
14153     DCI.AddToWorklist(ExtElt.getNode());
14154     DCI.AddToWorklist(V.getNode());
14155     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
14156                         St->getPointerInfo(), St->getAlignment(),
14157                         St->getMemOperand()->getFlags(), St->getAAInfo());
14158   }
14159 
14160   // If this is a legal vector store, try to combine it into a VST1_UPD.
14161   if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
14162       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
14163     return CombineBaseUpdate(N, DCI);
14164 
14165   return SDValue();
14166 }
14167 
14168 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
14169 /// can replace combinations of VMUL and VCVT (floating-point to integer)
14170 /// when the VMUL has a constant operand that is a power of 2.
14171 ///
14172 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14173 ///  vmul.f32        d16, d17, d16
14174 ///  vcvt.s32.f32    d16, d16
14175 /// becomes:
14176 ///  vcvt.s32.f32    d16, d16, #3
14177 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
14178                                   const ARMSubtarget *Subtarget) {
14179   if (!Subtarget->hasNEON())
14180     return SDValue();
14181 
14182   SDValue Op = N->getOperand(0);
14183   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
14184       Op.getOpcode() != ISD::FMUL)
14185     return SDValue();
14186 
14187   SDValue ConstVec = Op->getOperand(1);
14188   if (!isa<BuildVectorSDNode>(ConstVec))
14189     return SDValue();
14190 
14191   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
14192   uint32_t FloatBits = FloatTy.getSizeInBits();
14193   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
14194   uint32_t IntBits = IntTy.getSizeInBits();
14195   unsigned NumLanes = Op.getValueType().getVectorNumElements();
14196   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14197     // These instructions only exist converting from f32 to i32. We can handle
14198     // smaller integers by generating an extra truncate, but larger ones would
14199     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14200     // these intructions only support v2i32/v4i32 types.
14201     return SDValue();
14202   }
14203 
14204   BitVector UndefElements;
14205   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14206   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14207   if (C == -1 || C == 0 || C > 32)
14208     return SDValue();
14209 
14210   SDLoc dl(N);
14211   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
14212   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
14213     Intrinsic::arm_neon_vcvtfp2fxu;
14214   SDValue FixConv = DAG.getNode(
14215       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14216       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
14217       DAG.getConstant(C, dl, MVT::i32));
14218 
14219   if (IntBits < FloatBits)
14220     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
14221 
14222   return FixConv;
14223 }
14224 
14225 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
14226 /// can replace combinations of VCVT (integer to floating-point) and VDIV
14227 /// when the VDIV has a constant operand that is a power of 2.
14228 ///
14229 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14230 ///  vcvt.f32.s32    d16, d16
14231 ///  vdiv.f32        d16, d17, d16
14232 /// becomes:
14233 ///  vcvt.f32.s32    d16, d16, #3
14234 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
14235                                   const ARMSubtarget *Subtarget) {
14236   if (!Subtarget->hasNEON())
14237     return SDValue();
14238 
14239   SDValue Op = N->getOperand(0);
14240   unsigned OpOpcode = Op.getNode()->getOpcode();
14241   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
14242       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
14243     return SDValue();
14244 
14245   SDValue ConstVec = N->getOperand(1);
14246   if (!isa<BuildVectorSDNode>(ConstVec))
14247     return SDValue();
14248 
14249   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
14250   uint32_t FloatBits = FloatTy.getSizeInBits();
14251   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
14252   uint32_t IntBits = IntTy.getSizeInBits();
14253   unsigned NumLanes = Op.getValueType().getVectorNumElements();
14254   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14255     // These instructions only exist converting from i32 to f32. We can handle
14256     // smaller integers by generating an extra extend, but larger ones would
14257     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14258     // these intructions only support v2i32/v4i32 types.
14259     return SDValue();
14260   }
14261 
14262   BitVector UndefElements;
14263   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14264   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14265   if (C == -1 || C == 0 || C > 32)
14266     return SDValue();
14267 
14268   SDLoc dl(N);
14269   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
14270   SDValue ConvInput = Op.getOperand(0);
14271   if (IntBits < FloatBits)
14272     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
14273                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14274                             ConvInput);
14275 
14276   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
14277     Intrinsic::arm_neon_vcvtfxu2fp;
14278   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
14279                      Op.getValueType(),
14280                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
14281                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
14282 }
14283 
14284 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
14285                                            const ARMSubtarget *ST) {
14286   if (!ST->hasMVEIntegerOps())
14287     return SDValue();
14288 
14289   assert(N->getOpcode() == ISD::VECREDUCE_ADD);
14290   EVT ResVT = N->getValueType(0);
14291   SDValue N0 = N->getOperand(0);
14292   SDLoc dl(N);
14293 
14294   // We are looking for something that will have illegal types if left alone,
14295   // but that we can convert to a single instruction undef MVE. For example
14296   // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
14297   // or
14298   // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
14299 
14300   // Cases:
14301   //   VADDV u/s 8/16/32
14302   //   VMLAV u/s 8/16/32
14303   //   VADDLV u/s 32
14304   //   VMLALV u/s 16/32
14305 
14306   auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
14307     if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
14308       return SDValue();
14309     SDValue A = N0->getOperand(0);
14310     if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14311       return A;
14312     return SDValue();
14313   };
14314   auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
14315                      SDValue &A, SDValue &B) {
14316     if (ResVT != RetTy || N0->getOpcode() != ISD::MUL)
14317       return false;
14318     SDValue ExtA = N0->getOperand(0);
14319     SDValue ExtB = N0->getOperand(1);
14320     if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode)
14321       return false;
14322     A = ExtA->getOperand(0);
14323     B = ExtB->getOperand(0);
14324     if (A.getValueType() == B.getValueType() &&
14325         llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14326       return true;
14327     return false;
14328   };
14329   auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
14330     SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
14331     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
14332                        SDValue(Node.getNode(), 1));
14333   };
14334 
14335   if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
14336     return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
14337   if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
14338     return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
14339   if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
14340     return Create64bitNode(ARMISD::VADDLVs, {A});
14341   if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
14342     return Create64bitNode(ARMISD::VADDLVu, {A});
14343 
14344   SDValue A, B;
14345   if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
14346     return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
14347   if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
14348     return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
14349   if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B))
14350     return Create64bitNode(ARMISD::VMLALVs, {A, B});
14351   if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B))
14352     return Create64bitNode(ARMISD::VMLALVu, {A, B});
14353   return SDValue();
14354 }
14355 
14356 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
14357   SDLoc DL(N);
14358   SDValue Op0 = N->getOperand(0);
14359   SDValue Op1 = N->getOperand(1);
14360 
14361   // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
14362   // uses of the intrinsics.
14363   if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
14364     int ShiftAmt = C->getSExtValue();
14365     if (ShiftAmt == 0) {
14366       SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
14367       DAG.ReplaceAllUsesWith(N, Merge.getNode());
14368       return SDValue();
14369     }
14370 
14371     if (ShiftAmt >= -32 && ShiftAmt < 0) {
14372       unsigned NewOpcode =
14373           N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
14374       SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
14375                                      DAG.getConstant(-ShiftAmt, DL, MVT::i32));
14376       DAG.ReplaceAllUsesWith(N, NewShift.getNode());
14377       return NewShift;
14378     }
14379   }
14380 
14381   return SDValue();
14382 }
14383 
14384 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
14385 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
14386                                                    DAGCombinerInfo &DCI) const {
14387   SelectionDAG &DAG = DCI.DAG;
14388   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14389   switch (IntNo) {
14390   default:
14391     // Don't do anything for most intrinsics.
14392     break;
14393 
14394   // Vector shifts: check for immediate versions and lower them.
14395   // Note: This is done during DAG combining instead of DAG legalizing because
14396   // the build_vectors for 64-bit vector element shift counts are generally
14397   // not legal, and it is hard to see their values after they get legalized to
14398   // loads from a constant pool.
14399   case Intrinsic::arm_neon_vshifts:
14400   case Intrinsic::arm_neon_vshiftu:
14401   case Intrinsic::arm_neon_vrshifts:
14402   case Intrinsic::arm_neon_vrshiftu:
14403   case Intrinsic::arm_neon_vrshiftn:
14404   case Intrinsic::arm_neon_vqshifts:
14405   case Intrinsic::arm_neon_vqshiftu:
14406   case Intrinsic::arm_neon_vqshiftsu:
14407   case Intrinsic::arm_neon_vqshiftns:
14408   case Intrinsic::arm_neon_vqshiftnu:
14409   case Intrinsic::arm_neon_vqshiftnsu:
14410   case Intrinsic::arm_neon_vqrshiftns:
14411   case Intrinsic::arm_neon_vqrshiftnu:
14412   case Intrinsic::arm_neon_vqrshiftnsu: {
14413     EVT VT = N->getOperand(1).getValueType();
14414     int64_t Cnt;
14415     unsigned VShiftOpc = 0;
14416 
14417     switch (IntNo) {
14418     case Intrinsic::arm_neon_vshifts:
14419     case Intrinsic::arm_neon_vshiftu:
14420       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
14421         VShiftOpc = ARMISD::VSHLIMM;
14422         break;
14423       }
14424       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
14425         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
14426                                                           : ARMISD::VSHRuIMM);
14427         break;
14428       }
14429       return SDValue();
14430 
14431     case Intrinsic::arm_neon_vrshifts:
14432     case Intrinsic::arm_neon_vrshiftu:
14433       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
14434         break;
14435       return SDValue();
14436 
14437     case Intrinsic::arm_neon_vqshifts:
14438     case Intrinsic::arm_neon_vqshiftu:
14439       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
14440         break;
14441       return SDValue();
14442 
14443     case Intrinsic::arm_neon_vqshiftsu:
14444       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
14445         break;
14446       llvm_unreachable("invalid shift count for vqshlu intrinsic");
14447 
14448     case Intrinsic::arm_neon_vrshiftn:
14449     case Intrinsic::arm_neon_vqshiftns:
14450     case Intrinsic::arm_neon_vqshiftnu:
14451     case Intrinsic::arm_neon_vqshiftnsu:
14452     case Intrinsic::arm_neon_vqrshiftns:
14453     case Intrinsic::arm_neon_vqrshiftnu:
14454     case Intrinsic::arm_neon_vqrshiftnsu:
14455       // Narrowing shifts require an immediate right shift.
14456       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
14457         break;
14458       llvm_unreachable("invalid shift count for narrowing vector shift "
14459                        "intrinsic");
14460 
14461     default:
14462       llvm_unreachable("unhandled vector shift");
14463     }
14464 
14465     switch (IntNo) {
14466     case Intrinsic::arm_neon_vshifts:
14467     case Intrinsic::arm_neon_vshiftu:
14468       // Opcode already set above.
14469       break;
14470     case Intrinsic::arm_neon_vrshifts:
14471       VShiftOpc = ARMISD::VRSHRsIMM;
14472       break;
14473     case Intrinsic::arm_neon_vrshiftu:
14474       VShiftOpc = ARMISD::VRSHRuIMM;
14475       break;
14476     case Intrinsic::arm_neon_vrshiftn:
14477       VShiftOpc = ARMISD::VRSHRNIMM;
14478       break;
14479     case Intrinsic::arm_neon_vqshifts:
14480       VShiftOpc = ARMISD::VQSHLsIMM;
14481       break;
14482     case Intrinsic::arm_neon_vqshiftu:
14483       VShiftOpc = ARMISD::VQSHLuIMM;
14484       break;
14485     case Intrinsic::arm_neon_vqshiftsu:
14486       VShiftOpc = ARMISD::VQSHLsuIMM;
14487       break;
14488     case Intrinsic::arm_neon_vqshiftns:
14489       VShiftOpc = ARMISD::VQSHRNsIMM;
14490       break;
14491     case Intrinsic::arm_neon_vqshiftnu:
14492       VShiftOpc = ARMISD::VQSHRNuIMM;
14493       break;
14494     case Intrinsic::arm_neon_vqshiftnsu:
14495       VShiftOpc = ARMISD::VQSHRNsuIMM;
14496       break;
14497     case Intrinsic::arm_neon_vqrshiftns:
14498       VShiftOpc = ARMISD::VQRSHRNsIMM;
14499       break;
14500     case Intrinsic::arm_neon_vqrshiftnu:
14501       VShiftOpc = ARMISD::VQRSHRNuIMM;
14502       break;
14503     case Intrinsic::arm_neon_vqrshiftnsu:
14504       VShiftOpc = ARMISD::VQRSHRNsuIMM;
14505       break;
14506     }
14507 
14508     SDLoc dl(N);
14509     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
14510                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
14511   }
14512 
14513   case Intrinsic::arm_neon_vshiftins: {
14514     EVT VT = N->getOperand(1).getValueType();
14515     int64_t Cnt;
14516     unsigned VShiftOpc = 0;
14517 
14518     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
14519       VShiftOpc = ARMISD::VSLIIMM;
14520     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
14521       VShiftOpc = ARMISD::VSRIIMM;
14522     else {
14523       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
14524     }
14525 
14526     SDLoc dl(N);
14527     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
14528                        N->getOperand(1), N->getOperand(2),
14529                        DAG.getConstant(Cnt, dl, MVT::i32));
14530   }
14531 
14532   case Intrinsic::arm_neon_vqrshifts:
14533   case Intrinsic::arm_neon_vqrshiftu:
14534     // No immediate versions of these to check for.
14535     break;
14536 
14537   case Intrinsic::arm_mve_vqdmlah:
14538   case Intrinsic::arm_mve_vqdmlash:
14539   case Intrinsic::arm_mve_vqrdmlah:
14540   case Intrinsic::arm_mve_vqrdmlash:
14541   case Intrinsic::arm_mve_vmla_n_predicated:
14542   case Intrinsic::arm_mve_vmlas_n_predicated:
14543   case Intrinsic::arm_mve_vqdmlah_predicated:
14544   case Intrinsic::arm_mve_vqdmlash_predicated:
14545   case Intrinsic::arm_mve_vqrdmlah_predicated:
14546   case Intrinsic::arm_mve_vqrdmlash_predicated: {
14547     // These intrinsics all take an i32 scalar operand which is narrowed to the
14548     // size of a single lane of the vector type they return. So we don't need
14549     // any bits of that operand above that point, which allows us to eliminate
14550     // uxth/sxth.
14551     unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
14552     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
14553     if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
14554       return SDValue();
14555     break;
14556   }
14557 
14558   case Intrinsic::arm_mve_minv:
14559   case Intrinsic::arm_mve_maxv:
14560   case Intrinsic::arm_mve_minav:
14561   case Intrinsic::arm_mve_maxav:
14562   case Intrinsic::arm_mve_minv_predicated:
14563   case Intrinsic::arm_mve_maxv_predicated:
14564   case Intrinsic::arm_mve_minav_predicated:
14565   case Intrinsic::arm_mve_maxav_predicated: {
14566     // These intrinsics all take an i32 scalar operand which is narrowed to the
14567     // size of a single lane of the vector type they take as the other input.
14568     unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
14569     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
14570     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14571       return SDValue();
14572     break;
14573   }
14574 
14575   case Intrinsic::arm_mve_addv: {
14576     // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
14577     // which allow PerformADDVecReduce to turn it into VADDLV when possible.
14578     bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14579     unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
14580     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
14581   }
14582 
14583   case Intrinsic::arm_mve_addlv:
14584   case Intrinsic::arm_mve_addlv_predicated: {
14585     // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
14586     // which recombines the two outputs into an i64
14587     bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14588     unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
14589                     (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
14590                     (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
14591 
14592     SmallVector<SDValue, 4> Ops;
14593     for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
14594       if (i != 2)                      // skip the unsigned flag
14595         Ops.push_back(N->getOperand(i));
14596 
14597     SDLoc dl(N);
14598     SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
14599     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
14600                        val.getValue(1));
14601   }
14602   }
14603 
14604   return SDValue();
14605 }
14606 
14607 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
14608 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
14609 /// combining instead of DAG legalizing because the build_vectors for 64-bit
14610 /// vector element shift counts are generally not legal, and it is hard to see
14611 /// their values after they get legalized to loads from a constant pool.
14612 static SDValue PerformShiftCombine(SDNode *N,
14613                                    TargetLowering::DAGCombinerInfo &DCI,
14614                                    const ARMSubtarget *ST) {
14615   SelectionDAG &DAG = DCI.DAG;
14616   EVT VT = N->getValueType(0);
14617   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
14618     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
14619     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
14620     SDValue N1 = N->getOperand(1);
14621     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
14622       SDValue N0 = N->getOperand(0);
14623       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
14624           DAG.MaskedValueIsZero(N0.getOperand(0),
14625                                 APInt::getHighBitsSet(32, 16)))
14626         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
14627     }
14628   }
14629 
14630   if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
14631       N->getOperand(0)->getOpcode() == ISD::AND &&
14632       N->getOperand(0)->hasOneUse()) {
14633     if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14634       return SDValue();
14635     // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
14636     // usually show up because instcombine prefers to canonicalize it to
14637     // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
14638     // out of GEP lowering in some cases.
14639     SDValue N0 = N->getOperand(0);
14640     ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
14641     if (!ShiftAmtNode)
14642       return SDValue();
14643     uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
14644     ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14645     if (!AndMaskNode)
14646       return SDValue();
14647     uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
14648     // Don't transform uxtb/uxth.
14649     if (AndMask == 255 || AndMask == 65535)
14650       return SDValue();
14651     if (isMask_32(AndMask)) {
14652       uint32_t MaskedBits = countLeadingZeros(AndMask);
14653       if (MaskedBits > ShiftAmt) {
14654         SDLoc DL(N);
14655         SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14656                                   DAG.getConstant(MaskedBits, DL, MVT::i32));
14657         return DAG.getNode(
14658             ISD::SRL, DL, MVT::i32, SHL,
14659             DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
14660       }
14661     }
14662   }
14663 
14664   // Nothing to be done for scalar shifts.
14665   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14666   if (!VT.isVector() || !TLI.isTypeLegal(VT))
14667     return SDValue();
14668   if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
14669     return SDValue();
14670 
14671   int64_t Cnt;
14672 
14673   switch (N->getOpcode()) {
14674   default: llvm_unreachable("unexpected shift opcode");
14675 
14676   case ISD::SHL:
14677     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
14678       SDLoc dl(N);
14679       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
14680                          DAG.getConstant(Cnt, dl, MVT::i32));
14681     }
14682     break;
14683 
14684   case ISD::SRA:
14685   case ISD::SRL:
14686     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
14687       unsigned VShiftOpc =
14688           (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
14689       SDLoc dl(N);
14690       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
14691                          DAG.getConstant(Cnt, dl, MVT::i32));
14692     }
14693   }
14694   return SDValue();
14695 }
14696 
14697 // Look for a sign/zero extend of a larger than legal load. This can be split
14698 // into two extending loads, which are simpler to deal with than an arbitrary
14699 // sign extend.
14700 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
14701   SDValue N0 = N->getOperand(0);
14702   if (N0.getOpcode() != ISD::LOAD)
14703     return SDValue();
14704   LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
14705   if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
14706       LD->getExtensionType() != ISD::NON_EXTLOAD)
14707     return SDValue();
14708   EVT FromVT = LD->getValueType(0);
14709   EVT ToVT = N->getValueType(0);
14710   if (!ToVT.isVector())
14711     return SDValue();
14712   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
14713   EVT ToEltVT = ToVT.getVectorElementType();
14714   EVT FromEltVT = FromVT.getVectorElementType();
14715 
14716   unsigned NumElements = 0;
14717   if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
14718     NumElements = 4;
14719   if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
14720     NumElements = 8;
14721   if (NumElements == 0 ||
14722       FromVT.getVectorNumElements() == NumElements ||
14723       FromVT.getVectorNumElements() % NumElements != 0 ||
14724       !isPowerOf2_32(NumElements))
14725     return SDValue();
14726 
14727   SDLoc DL(LD);
14728   // Details about the old load
14729   SDValue Ch = LD->getChain();
14730   SDValue BasePtr = LD->getBasePtr();
14731   Align Alignment = LD->getOriginalAlign();
14732   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
14733   AAMDNodes AAInfo = LD->getAAInfo();
14734 
14735   ISD::LoadExtType NewExtType =
14736       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
14737   SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
14738   EVT NewFromVT = FromVT.getHalfNumVectorElementsVT(*DAG.getContext());
14739   EVT NewToVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
14740   unsigned NewOffset = NewFromVT.getSizeInBits() / 8;
14741   SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
14742 
14743   // Split the load in half, each side of which is extended separately. This
14744   // is good enough, as legalisation will take it from there. They are either
14745   // already legal or they will be split further into something that is
14746   // legal.
14747   SDValue NewLoad1 = DAG.getLoad(
14748       ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, BasePtr, Offset,
14749       LD->getPointerInfo(), NewFromVT, Alignment.value(), MMOFlags, AAInfo);
14750   SDValue NewLoad2 =
14751       DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
14752                   LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
14753                   Alignment.value(), MMOFlags, AAInfo);
14754 
14755   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14756                                  SDValue(NewLoad1.getNode(), 1),
14757                                  SDValue(NewLoad2.getNode(), 1));
14758   DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
14759   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, NewLoad1, NewLoad2);
14760 }
14761 
14762 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
14763 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
14764 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
14765                                     const ARMSubtarget *ST) {
14766   SDValue N0 = N->getOperand(0);
14767 
14768   // Check for sign- and zero-extensions of vector extract operations of 8- and
14769   // 16-bit vector elements. NEON and MVE support these directly. They are
14770   // handled during DAG combining because type legalization will promote them
14771   // to 32-bit types and it is messy to recognize the operations after that.
14772   if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
14773       N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14774     SDValue Vec = N0.getOperand(0);
14775     SDValue Lane = N0.getOperand(1);
14776     EVT VT = N->getValueType(0);
14777     EVT EltVT = N0.getValueType();
14778     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14779 
14780     if (VT == MVT::i32 &&
14781         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
14782         TLI.isTypeLegal(Vec.getValueType()) &&
14783         isa<ConstantSDNode>(Lane)) {
14784 
14785       unsigned Opc = 0;
14786       switch (N->getOpcode()) {
14787       default: llvm_unreachable("unexpected opcode");
14788       case ISD::SIGN_EXTEND:
14789         Opc = ARMISD::VGETLANEs;
14790         break;
14791       case ISD::ZERO_EXTEND:
14792       case ISD::ANY_EXTEND:
14793         Opc = ARMISD::VGETLANEu;
14794         break;
14795       }
14796       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
14797     }
14798   }
14799 
14800   if (ST->hasMVEIntegerOps())
14801     if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
14802       return NewLoad;
14803 
14804   return SDValue();
14805 }
14806 
14807 static const APInt *isPowerOf2Constant(SDValue V) {
14808   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
14809   if (!C)
14810     return nullptr;
14811   const APInt *CV = &C->getAPIntValue();
14812   return CV->isPowerOf2() ? CV : nullptr;
14813 }
14814 
14815 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
14816   // If we have a CMOV, OR and AND combination such as:
14817   //   if (x & CN)
14818   //     y |= CM;
14819   //
14820   // And:
14821   //   * CN is a single bit;
14822   //   * All bits covered by CM are known zero in y
14823   //
14824   // Then we can convert this into a sequence of BFI instructions. This will
14825   // always be a win if CM is a single bit, will always be no worse than the
14826   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
14827   // three bits (due to the extra IT instruction).
14828 
14829   SDValue Op0 = CMOV->getOperand(0);
14830   SDValue Op1 = CMOV->getOperand(1);
14831   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
14832   auto CC = CCNode->getAPIntValue().getLimitedValue();
14833   SDValue CmpZ = CMOV->getOperand(4);
14834 
14835   // The compare must be against zero.
14836   if (!isNullConstant(CmpZ->getOperand(1)))
14837     return SDValue();
14838 
14839   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
14840   SDValue And = CmpZ->getOperand(0);
14841   if (And->getOpcode() != ISD::AND)
14842     return SDValue();
14843   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
14844   if (!AndC)
14845     return SDValue();
14846   SDValue X = And->getOperand(0);
14847 
14848   if (CC == ARMCC::EQ) {
14849     // We're performing an "equal to zero" compare. Swap the operands so we
14850     // canonicalize on a "not equal to zero" compare.
14851     std::swap(Op0, Op1);
14852   } else {
14853     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
14854   }
14855 
14856   if (Op1->getOpcode() != ISD::OR)
14857     return SDValue();
14858 
14859   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
14860   if (!OrC)
14861     return SDValue();
14862   SDValue Y = Op1->getOperand(0);
14863 
14864   if (Op0 != Y)
14865     return SDValue();
14866 
14867   // Now, is it profitable to continue?
14868   APInt OrCI = OrC->getAPIntValue();
14869   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
14870   if (OrCI.countPopulation() > Heuristic)
14871     return SDValue();
14872 
14873   // Lastly, can we determine that the bits defined by OrCI
14874   // are zero in Y?
14875   KnownBits Known = DAG.computeKnownBits(Y);
14876   if ((OrCI & Known.Zero) != OrCI)
14877     return SDValue();
14878 
14879   // OK, we can do the combine.
14880   SDValue V = Y;
14881   SDLoc dl(X);
14882   EVT VT = X.getValueType();
14883   unsigned BitInX = AndC->logBase2();
14884 
14885   if (BitInX != 0) {
14886     // We must shift X first.
14887     X = DAG.getNode(ISD::SRL, dl, VT, X,
14888                     DAG.getConstant(BitInX, dl, VT));
14889   }
14890 
14891   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
14892        BitInY < NumActiveBits; ++BitInY) {
14893     if (OrCI[BitInY] == 0)
14894       continue;
14895     APInt Mask(VT.getSizeInBits(), 0);
14896     Mask.setBit(BitInY);
14897     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
14898                     // Confusingly, the operand is an *inverted* mask.
14899                     DAG.getConstant(~Mask, dl, VT));
14900   }
14901 
14902   return V;
14903 }
14904 
14905 // Given N, the value controlling the conditional branch, search for the loop
14906 // intrinsic, returning it, along with how the value is used. We need to handle
14907 // patterns such as the following:
14908 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
14909 // (brcond (setcc (loop.decrement), 0, eq), exit)
14910 // (brcond (setcc (loop.decrement), 0, ne), header)
14911 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
14912                                    bool &Negate) {
14913   switch (N->getOpcode()) {
14914   default:
14915     break;
14916   case ISD::XOR: {
14917     if (!isa<ConstantSDNode>(N.getOperand(1)))
14918       return SDValue();
14919     if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
14920       return SDValue();
14921     Negate = !Negate;
14922     return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
14923   }
14924   case ISD::SETCC: {
14925     auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
14926     if (!Const)
14927       return SDValue();
14928     if (Const->isNullValue())
14929       Imm = 0;
14930     else if (Const->isOne())
14931       Imm = 1;
14932     else
14933       return SDValue();
14934     CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
14935     return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
14936   }
14937   case ISD::INTRINSIC_W_CHAIN: {
14938     unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
14939     if (IntOp != Intrinsic::test_set_loop_iterations &&
14940         IntOp != Intrinsic::loop_decrement_reg)
14941       return SDValue();
14942     return N;
14943   }
14944   }
14945   return SDValue();
14946 }
14947 
14948 static SDValue PerformHWLoopCombine(SDNode *N,
14949                                     TargetLowering::DAGCombinerInfo &DCI,
14950                                     const ARMSubtarget *ST) {
14951 
14952   // The hwloop intrinsics that we're interested are used for control-flow,
14953   // either for entering or exiting the loop:
14954   // - test.set.loop.iterations will test whether its operand is zero. If it
14955   //   is zero, the proceeding branch should not enter the loop.
14956   // - loop.decrement.reg also tests whether its operand is zero. If it is
14957   //   zero, the proceeding branch should not branch back to the beginning of
14958   //   the loop.
14959   // So here, we need to check that how the brcond is using the result of each
14960   // of the intrinsics to ensure that we're branching to the right place at the
14961   // right time.
14962 
14963   ISD::CondCode CC;
14964   SDValue Cond;
14965   int Imm = 1;
14966   bool Negate = false;
14967   SDValue Chain = N->getOperand(0);
14968   SDValue Dest;
14969 
14970   if (N->getOpcode() == ISD::BRCOND) {
14971     CC = ISD::SETEQ;
14972     Cond = N->getOperand(1);
14973     Dest = N->getOperand(2);
14974   } else {
14975     assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
14976     CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14977     Cond = N->getOperand(2);
14978     Dest = N->getOperand(4);
14979     if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
14980       if (!Const->isOne() && !Const->isNullValue())
14981         return SDValue();
14982       Imm = Const->getZExtValue();
14983     } else
14984       return SDValue();
14985   }
14986 
14987   SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
14988   if (!Int)
14989     return SDValue();
14990 
14991   if (Negate)
14992     CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
14993 
14994   auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
14995     return (CC == ISD::SETEQ && Imm == 0) ||
14996            (CC == ISD::SETNE && Imm == 1) ||
14997            (CC == ISD::SETLT && Imm == 1) ||
14998            (CC == ISD::SETULT && Imm == 1);
14999   };
15000 
15001   auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
15002     return (CC == ISD::SETEQ && Imm == 1) ||
15003            (CC == ISD::SETNE && Imm == 0) ||
15004            (CC == ISD::SETGT && Imm == 0) ||
15005            (CC == ISD::SETUGT && Imm == 0) ||
15006            (CC == ISD::SETGE && Imm == 1) ||
15007            (CC == ISD::SETUGE && Imm == 1);
15008   };
15009 
15010   assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
15011          "unsupported condition");
15012 
15013   SDLoc dl(Int);
15014   SelectionDAG &DAG = DCI.DAG;
15015   SDValue Elements = Int.getOperand(2);
15016   unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
15017   assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
15018           && "expected single br user");
15019   SDNode *Br = *N->use_begin();
15020   SDValue OtherTarget = Br->getOperand(1);
15021 
15022   // Update the unconditional branch to branch to the given Dest.
15023   auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
15024     SDValue NewBrOps[] = { Br->getOperand(0), Dest };
15025     SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
15026     DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
15027   };
15028 
15029   if (IntOp == Intrinsic::test_set_loop_iterations) {
15030     SDValue Res;
15031     // We expect this 'instruction' to branch when the counter is zero.
15032     if (IsTrueIfZero(CC, Imm)) {
15033       SDValue Ops[] = { Chain, Elements, Dest };
15034       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
15035     } else {
15036       // The logic is the reverse of what we need for WLS, so find the other
15037       // basic block target: the target of the proceeding br.
15038       UpdateUncondBr(Br, Dest, DAG);
15039 
15040       SDValue Ops[] = { Chain, Elements, OtherTarget };
15041       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
15042     }
15043     DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
15044     return Res;
15045   } else {
15046     SDValue Size = DAG.getTargetConstant(
15047       cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
15048     SDValue Args[] = { Int.getOperand(0), Elements, Size, };
15049     SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
15050                                   DAG.getVTList(MVT::i32, MVT::Other), Args);
15051     DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
15052 
15053     // We expect this instruction to branch when the count is not zero.
15054     SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
15055 
15056     // Update the unconditional branch to target the loop preheader if we've
15057     // found the condition has been reversed.
15058     if (Target == OtherTarget)
15059       UpdateUncondBr(Br, Dest, DAG);
15060 
15061     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15062                         SDValue(LoopDec.getNode(), 1), Chain);
15063 
15064     SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
15065     return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
15066   }
15067   return SDValue();
15068 }
15069 
15070 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
15071 SDValue
15072 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
15073   SDValue Cmp = N->getOperand(4);
15074   if (Cmp.getOpcode() != ARMISD::CMPZ)
15075     // Only looking at NE cases.
15076     return SDValue();
15077 
15078   EVT VT = N->getValueType(0);
15079   SDLoc dl(N);
15080   SDValue LHS = Cmp.getOperand(0);
15081   SDValue RHS = Cmp.getOperand(1);
15082   SDValue Chain = N->getOperand(0);
15083   SDValue BB = N->getOperand(1);
15084   SDValue ARMcc = N->getOperand(2);
15085   ARMCC::CondCodes CC =
15086     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
15087 
15088   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
15089   // -> (brcond Chain BB CC CPSR Cmp)
15090   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
15091       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
15092       LHS->getOperand(0)->hasOneUse()) {
15093     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
15094     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
15095     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
15096     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
15097     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
15098         (LHS01C && LHS01C->getZExtValue() == 1) &&
15099         (LHS1C && LHS1C->getZExtValue() == 1) &&
15100         (RHSC && RHSC->getZExtValue() == 0)) {
15101       return DAG.getNode(
15102           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
15103           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
15104     }
15105   }
15106 
15107   return SDValue();
15108 }
15109 
15110 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
15111 SDValue
15112 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
15113   SDValue Cmp = N->getOperand(4);
15114   if (Cmp.getOpcode() != ARMISD::CMPZ)
15115     // Only looking at EQ and NE cases.
15116     return SDValue();
15117 
15118   EVT VT = N->getValueType(0);
15119   SDLoc dl(N);
15120   SDValue LHS = Cmp.getOperand(0);
15121   SDValue RHS = Cmp.getOperand(1);
15122   SDValue FalseVal = N->getOperand(0);
15123   SDValue TrueVal = N->getOperand(1);
15124   SDValue ARMcc = N->getOperand(2);
15125   ARMCC::CondCodes CC =
15126     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
15127 
15128   // BFI is only available on V6T2+.
15129   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
15130     SDValue R = PerformCMOVToBFICombine(N, DAG);
15131     if (R)
15132       return R;
15133   }
15134 
15135   // Simplify
15136   //   mov     r1, r0
15137   //   cmp     r1, x
15138   //   mov     r0, y
15139   //   moveq   r0, x
15140   // to
15141   //   cmp     r0, x
15142   //   movne   r0, y
15143   //
15144   //   mov     r1, r0
15145   //   cmp     r1, x
15146   //   mov     r0, x
15147   //   movne   r0, y
15148   // to
15149   //   cmp     r0, x
15150   //   movne   r0, y
15151   /// FIXME: Turn this into a target neutral optimization?
15152   SDValue Res;
15153   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
15154     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
15155                       N->getOperand(3), Cmp);
15156   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
15157     SDValue ARMcc;
15158     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
15159     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
15160                       N->getOperand(3), NewCmp);
15161   }
15162 
15163   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
15164   // -> (cmov F T CC CPSR Cmp)
15165   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
15166     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
15167     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
15168     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
15169     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
15170         (LHS1C && LHS1C->getZExtValue() == 1) &&
15171         (RHSC && RHSC->getZExtValue() == 0)) {
15172       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
15173                          LHS->getOperand(2), LHS->getOperand(3),
15174                          LHS->getOperand(4));
15175     }
15176   }
15177 
15178   if (!VT.isInteger())
15179       return SDValue();
15180 
15181   // Materialize a boolean comparison for integers so we can avoid branching.
15182   if (isNullConstant(FalseVal)) {
15183     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
15184       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
15185         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
15186         // right 5 bits will make that 32 be 1, otherwise it will be 0.
15187         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
15188         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
15189         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
15190                           DAG.getConstant(5, dl, MVT::i32));
15191       } else {
15192         // CMOV 0, 1, ==, (CMPZ x, y) ->
15193         //     (ADDCARRY (SUB x, y), t:0, t:1)
15194         // where t = (SUBCARRY 0, (SUB x, y), 0)
15195         //
15196         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
15197         // x != y. In other words, a carry C == 1 when x == y, C == 0
15198         // otherwise.
15199         // The final ADDCARRY computes
15200         //     x - y + (0 - (x - y)) + C == C
15201         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
15202         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15203         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
15204         // ISD::SUBCARRY returns a borrow but we want the carry here
15205         // actually.
15206         SDValue Carry =
15207             DAG.getNode(ISD::SUB, dl, MVT::i32,
15208                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
15209         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
15210       }
15211     } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
15212                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
15213       // This seems pointless but will allow us to combine it further below.
15214       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
15215       SDValue Sub =
15216           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
15217       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
15218                                           Sub.getValue(1), SDValue());
15219       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
15220                         N->getOperand(3), CPSRGlue.getValue(1));
15221       FalseVal = Sub;
15222     }
15223   } else if (isNullConstant(TrueVal)) {
15224     if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
15225         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
15226       // This seems pointless but will allow us to combine it further below
15227       // Note that we change == for != as this is the dual for the case above.
15228       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
15229       SDValue Sub =
15230           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
15231       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
15232                                           Sub.getValue(1), SDValue());
15233       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
15234                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
15235                         N->getOperand(3), CPSRGlue.getValue(1));
15236       FalseVal = Sub;
15237     }
15238   }
15239 
15240   // On Thumb1, the DAG above may be further combined if z is a power of 2
15241   // (z == 2 ^ K).
15242   // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
15243   // t1 = (USUBO (SUB x, y), 1)
15244   // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
15245   // Result = if K != 0 then (SHL t2:0, K) else t2:0
15246   //
15247   // This also handles the special case of comparing against zero; it's
15248   // essentially, the same pattern, except there's no SUBS:
15249   // CMOV x, z, !=, (CMPZ x, 0) ->
15250   // t1 = (USUBO x, 1)
15251   // t2 = (SUBCARRY x, t1:0, t1:1)
15252   // Result = if K != 0 then (SHL t2:0, K) else t2:0
15253   const APInt *TrueConst;
15254   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
15255       ((FalseVal.getOpcode() == ARMISD::SUBS &&
15256         FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
15257        (FalseVal == LHS && isNullConstant(RHS))) &&
15258       (TrueConst = isPowerOf2Constant(TrueVal))) {
15259     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15260     unsigned ShiftAmount = TrueConst->logBase2();
15261     if (ShiftAmount)
15262       TrueVal = DAG.getConstant(1, dl, VT);
15263     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
15264     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
15265 
15266     if (ShiftAmount)
15267       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
15268                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
15269   }
15270 
15271   if (Res.getNode()) {
15272     KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
15273     // Capture demanded bits information that would be otherwise lost.
15274     if (Known.Zero == 0xfffffffe)
15275       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
15276                         DAG.getValueType(MVT::i1));
15277     else if (Known.Zero == 0xffffff00)
15278       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
15279                         DAG.getValueType(MVT::i8));
15280     else if (Known.Zero == 0xffff0000)
15281       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
15282                         DAG.getValueType(MVT::i16));
15283   }
15284 
15285   return Res;
15286 }
15287 
15288 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
15289                                     const ARMSubtarget *ST) {
15290   SDValue Src = N->getOperand(0);
15291   EVT DstVT = N->getValueType(0);
15292 
15293   // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
15294   if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
15295     EVT SrcVT = Src.getValueType();
15296     if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
15297       return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
15298   }
15299 
15300   // We may have a bitcast of something that has already had this bitcast
15301   // combine performed on it, so skip past any VECTOR_REG_CASTs.
15302   while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST)
15303     Src = Src.getOperand(0);
15304 
15305   // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
15306   // would be generated is at least the width of the element type.
15307   EVT SrcVT = Src.getValueType();
15308   if ((Src.getOpcode() == ARMISD::VMOVIMM ||
15309        Src.getOpcode() == ARMISD::VMVNIMM ||
15310        Src.getOpcode() == ARMISD::VMOVFPIMM) &&
15311       SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
15312       DAG.getDataLayout().isBigEndian())
15313     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
15314 
15315   return SDValue();
15316 }
15317 
15318 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
15319                                              DAGCombinerInfo &DCI) const {
15320   switch (N->getOpcode()) {
15321   default: break;
15322   case ISD::VSELECT:    return PerformVSELECTCombine(N, DCI, Subtarget);
15323   case ISD::ABS:        return PerformABSCombine(N, DCI, Subtarget);
15324   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
15325   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
15326   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
15327   case ISD::SUB:        return PerformSUBCombine(N, DCI, Subtarget);
15328   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
15329   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
15330   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
15331   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
15332   case ISD::BRCOND:
15333   case ISD::BR_CC:      return PerformHWLoopCombine(N, DCI, Subtarget);
15334   case ARMISD::ADDC:
15335   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
15336   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
15337   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
15338   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
15339   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
15340   case ARMISD::VMOVhr:  return PerformVMOVhrCombine(N, DCI);
15341   case ARMISD::VMOVrh:  return PerformVMOVrhCombine(N, DCI);
15342   case ISD::STORE:      return PerformSTORECombine(N, DCI, Subtarget);
15343   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
15344   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
15345   case ISD::EXTRACT_VECTOR_ELT: return PerformExtractEltCombine(N, DCI);
15346   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
15347   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
15348   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
15349   case ISD::FP_TO_SINT:
15350   case ISD::FP_TO_UINT:
15351     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
15352   case ISD::FDIV:
15353     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
15354   case ISD::INTRINSIC_WO_CHAIN:
15355     return PerformIntrinsicCombine(N, DCI);
15356   case ISD::SHL:
15357   case ISD::SRA:
15358   case ISD::SRL:
15359     return PerformShiftCombine(N, DCI, Subtarget);
15360   case ISD::SIGN_EXTEND:
15361   case ISD::ZERO_EXTEND:
15362   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
15363   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
15364   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
15365   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
15366   case ARMISD::VLD1DUP:
15367   case ARMISD::VLD2DUP:
15368   case ARMISD::VLD3DUP:
15369   case ARMISD::VLD4DUP:
15370     return PerformVLDCombine(N, DCI);
15371   case ARMISD::BUILD_VECTOR:
15372     return PerformARMBUILD_VECTORCombine(N, DCI);
15373   case ISD::BITCAST:
15374     return PerformBITCASTCombine(N, DCI.DAG, Subtarget);
15375   case ARMISD::PREDICATE_CAST:
15376     return PerformPREDICATE_CASTCombine(N, DCI);
15377   case ARMISD::VECTOR_REG_CAST:
15378     return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget);
15379   case ARMISD::VCMP:
15380     return PerformVCMPCombine(N, DCI, Subtarget);
15381   case ISD::VECREDUCE_ADD:
15382     return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
15383   case ARMISD::ASRL:
15384   case ARMISD::LSRL:
15385   case ARMISD::LSLL:
15386     return PerformLongShiftCombine(N, DCI.DAG);
15387   case ARMISD::SMULWB: {
15388     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15389     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
15390     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
15391       return SDValue();
15392     break;
15393   }
15394   case ARMISD::SMULWT: {
15395     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15396     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
15397     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
15398       return SDValue();
15399     break;
15400   }
15401   case ARMISD::SMLALBB:
15402   case ARMISD::QADD16b:
15403   case ARMISD::QSUB16b: {
15404     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15405     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
15406     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
15407         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
15408       return SDValue();
15409     break;
15410   }
15411   case ARMISD::SMLALBT: {
15412     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
15413     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
15414     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
15415     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
15416     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
15417         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
15418       return SDValue();
15419     break;
15420   }
15421   case ARMISD::SMLALTB: {
15422     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
15423     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
15424     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
15425     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
15426     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
15427         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
15428       return SDValue();
15429     break;
15430   }
15431   case ARMISD::SMLALTT: {
15432     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15433     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
15434     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
15435         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
15436       return SDValue();
15437     break;
15438   }
15439   case ARMISD::QADD8b:
15440   case ARMISD::QSUB8b: {
15441     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15442     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
15443     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
15444         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
15445       return SDValue();
15446     break;
15447   }
15448   case ISD::INTRINSIC_VOID:
15449   case ISD::INTRINSIC_W_CHAIN:
15450     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15451     case Intrinsic::arm_neon_vld1:
15452     case Intrinsic::arm_neon_vld1x2:
15453     case Intrinsic::arm_neon_vld1x3:
15454     case Intrinsic::arm_neon_vld1x4:
15455     case Intrinsic::arm_neon_vld2:
15456     case Intrinsic::arm_neon_vld3:
15457     case Intrinsic::arm_neon_vld4:
15458     case Intrinsic::arm_neon_vld2lane:
15459     case Intrinsic::arm_neon_vld3lane:
15460     case Intrinsic::arm_neon_vld4lane:
15461     case Intrinsic::arm_neon_vld2dup:
15462     case Intrinsic::arm_neon_vld3dup:
15463     case Intrinsic::arm_neon_vld4dup:
15464     case Intrinsic::arm_neon_vst1:
15465     case Intrinsic::arm_neon_vst1x2:
15466     case Intrinsic::arm_neon_vst1x3:
15467     case Intrinsic::arm_neon_vst1x4:
15468     case Intrinsic::arm_neon_vst2:
15469     case Intrinsic::arm_neon_vst3:
15470     case Intrinsic::arm_neon_vst4:
15471     case Intrinsic::arm_neon_vst2lane:
15472     case Intrinsic::arm_neon_vst3lane:
15473     case Intrinsic::arm_neon_vst4lane:
15474       return PerformVLDCombine(N, DCI);
15475     case Intrinsic::arm_mve_vld2q:
15476     case Intrinsic::arm_mve_vld4q:
15477     case Intrinsic::arm_mve_vst2q:
15478     case Intrinsic::arm_mve_vst4q:
15479       return PerformMVEVLDCombine(N, DCI);
15480     default: break;
15481     }
15482     break;
15483   }
15484   return SDValue();
15485 }
15486 
15487 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
15488                                                           EVT VT) const {
15489   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
15490 }
15491 
15492 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
15493                                                        unsigned Alignment,
15494                                                        MachineMemOperand::Flags,
15495                                                        bool *Fast) const {
15496   // Depends what it gets converted into if the type is weird.
15497   if (!VT.isSimple())
15498     return false;
15499 
15500   // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
15501   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
15502   auto Ty = VT.getSimpleVT().SimpleTy;
15503 
15504   if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
15505     // Unaligned access can use (for example) LRDB, LRDH, LDR
15506     if (AllowsUnaligned) {
15507       if (Fast)
15508         *Fast = Subtarget->hasV7Ops();
15509       return true;
15510     }
15511   }
15512 
15513   if (Ty == MVT::f64 || Ty == MVT::v2f64) {
15514     // For any little-endian targets with neon, we can support unaligned ld/st
15515     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
15516     // A big-endian target may also explicitly support unaligned accesses
15517     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
15518       if (Fast)
15519         *Fast = true;
15520       return true;
15521     }
15522   }
15523 
15524   if (!Subtarget->hasMVEIntegerOps())
15525     return false;
15526 
15527   // These are for predicates
15528   if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
15529     if (Fast)
15530       *Fast = true;
15531     return true;
15532   }
15533 
15534   // These are for truncated stores/narrowing loads. They are fine so long as
15535   // the alignment is at least the size of the item being loaded
15536   if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
15537       Alignment >= VT.getScalarSizeInBits() / 8) {
15538     if (Fast)
15539       *Fast = true;
15540     return true;
15541   }
15542 
15543   // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
15544   // VSTRW.U32 all store the vector register in exactly the same format, and
15545   // differ only in the range of their immediate offset field and the required
15546   // alignment. So there is always a store that can be used, regardless of
15547   // actual type.
15548   //
15549   // For big endian, that is not the case. But can still emit a (VSTRB.U8;
15550   // VREV64.8) pair and get the same effect. This will likely be better than
15551   // aligning the vector through the stack.
15552   if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
15553       Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
15554       Ty == MVT::v2f64) {
15555     if (Fast)
15556       *Fast = true;
15557     return true;
15558   }
15559 
15560   return false;
15561 }
15562 
15563 
15564 EVT ARMTargetLowering::getOptimalMemOpType(
15565     const MemOp &Op, const AttributeList &FuncAttributes) const {
15566   // See if we can use NEON instructions for this...
15567   if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
15568       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15569     bool Fast;
15570     if (Op.size() >= 16 &&
15571         (Op.isAligned(Align(16)) ||
15572          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
15573                                          MachineMemOperand::MONone, &Fast) &&
15574           Fast))) {
15575       return MVT::v2f64;
15576     } else if (Op.size() >= 8 &&
15577                (Op.isAligned(Align(8)) ||
15578                 (allowsMisalignedMemoryAccesses(
15579                      MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
15580                  Fast))) {
15581       return MVT::f64;
15582     }
15583   }
15584 
15585   // Let the target-independent logic figure it out.
15586   return MVT::Other;
15587 }
15588 
15589 // 64-bit integers are split into their high and low parts and held in two
15590 // different registers, so the trunc is free since the low register can just
15591 // be used.
15592 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
15593   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
15594     return false;
15595   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
15596   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
15597   return (SrcBits == 64 && DestBits == 32);
15598 }
15599 
15600 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
15601   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
15602       !DstVT.isInteger())
15603     return false;
15604   unsigned SrcBits = SrcVT.getSizeInBits();
15605   unsigned DestBits = DstVT.getSizeInBits();
15606   return (SrcBits == 64 && DestBits == 32);
15607 }
15608 
15609 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15610   if (Val.getOpcode() != ISD::LOAD)
15611     return false;
15612 
15613   EVT VT1 = Val.getValueType();
15614   if (!VT1.isSimple() || !VT1.isInteger() ||
15615       !VT2.isSimple() || !VT2.isInteger())
15616     return false;
15617 
15618   switch (VT1.getSimpleVT().SimpleTy) {
15619   default: break;
15620   case MVT::i1:
15621   case MVT::i8:
15622   case MVT::i16:
15623     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
15624     return true;
15625   }
15626 
15627   return false;
15628 }
15629 
15630 bool ARMTargetLowering::isFNegFree(EVT VT) const {
15631   if (!VT.isSimple())
15632     return false;
15633 
15634   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
15635   // negate values directly (fneg is free). So, we don't want to let the DAG
15636   // combiner rewrite fneg into xors and some other instructions.  For f16 and
15637   // FullFP16 argument passing, some bitcast nodes may be introduced,
15638   // triggering this DAG combine rewrite, so we are avoiding that with this.
15639   switch (VT.getSimpleVT().SimpleTy) {
15640   default: break;
15641   case MVT::f16:
15642     return Subtarget->hasFullFP16();
15643   }
15644 
15645   return false;
15646 }
15647 
15648 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
15649 /// of the vector elements.
15650 static bool areExtractExts(Value *Ext1, Value *Ext2) {
15651   auto areExtDoubled = [](Instruction *Ext) {
15652     return Ext->getType()->getScalarSizeInBits() ==
15653            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
15654   };
15655 
15656   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
15657       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
15658       !areExtDoubled(cast<Instruction>(Ext1)) ||
15659       !areExtDoubled(cast<Instruction>(Ext2)))
15660     return false;
15661 
15662   return true;
15663 }
15664 
15665 /// Check if sinking \p I's operands to I's basic block is profitable, because
15666 /// the operands can be folded into a target instruction, e.g.
15667 /// sext/zext can be folded into vsubl.
15668 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
15669                                            SmallVectorImpl<Use *> &Ops) const {
15670   if (!I->getType()->isVectorTy())
15671     return false;
15672 
15673   if (Subtarget->hasNEON()) {
15674     switch (I->getOpcode()) {
15675     case Instruction::Sub:
15676     case Instruction::Add: {
15677       if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
15678         return false;
15679       Ops.push_back(&I->getOperandUse(0));
15680       Ops.push_back(&I->getOperandUse(1));
15681       return true;
15682     }
15683     default:
15684       return false;
15685     }
15686   }
15687 
15688   if (!Subtarget->hasMVEIntegerOps())
15689     return false;
15690 
15691   auto IsFMSMul = [&](Instruction *I) {
15692     if (!I->hasOneUse())
15693       return false;
15694     auto *Sub = cast<Instruction>(*I->users().begin());
15695     return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I;
15696   };
15697 
15698   auto IsSinker = [&](Instruction *I, int Operand) {
15699     switch (I->getOpcode()) {
15700     case Instruction::Add:
15701     case Instruction::Mul:
15702     case Instruction::FAdd:
15703     case Instruction::ICmp:
15704     case Instruction::FCmp:
15705       return true;
15706     case Instruction::FMul:
15707       return !IsFMSMul(I);
15708     case Instruction::Sub:
15709     case Instruction::FSub:
15710     case Instruction::Shl:
15711     case Instruction::LShr:
15712     case Instruction::AShr:
15713       return Operand == 1;
15714     default:
15715       return false;
15716     }
15717   };
15718 
15719   int Op = 0;
15720   if (!isa<ShuffleVectorInst>(I->getOperand(Op)))
15721     Op = 1;
15722   if (!IsSinker(I, Op))
15723     return false;
15724   if (!match(I->getOperand(Op),
15725              m_ShuffleVector(m_InsertElement(m_Undef(), m_Value(), m_ZeroInt()),
15726                              m_Undef(), m_ZeroMask()))) {
15727     return false;
15728   }
15729   Instruction *Shuffle = cast<Instruction>(I->getOperand(Op));
15730   // All uses of the shuffle should be sunk to avoid duplicating it across gpr
15731   // and vector registers
15732   for (Use &U : Shuffle->uses()) {
15733     Instruction *Insn = cast<Instruction>(U.getUser());
15734     if (!IsSinker(Insn, U.getOperandNo()))
15735       return false;
15736   }
15737   Ops.push_back(&Shuffle->getOperandUse(0));
15738   Ops.push_back(&I->getOperandUse(Op));
15739   return true;
15740 }
15741 
15742 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
15743   EVT VT = ExtVal.getValueType();
15744 
15745   if (!isTypeLegal(VT))
15746     return false;
15747 
15748   if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
15749     if (Ld->isExpandingLoad())
15750       return false;
15751   }
15752 
15753   if (Subtarget->hasMVEIntegerOps())
15754     return true;
15755 
15756   // Don't create a loadext if we can fold the extension into a wide/long
15757   // instruction.
15758   // If there's more than one user instruction, the loadext is desirable no
15759   // matter what.  There can be two uses by the same instruction.
15760   if (ExtVal->use_empty() ||
15761       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
15762     return true;
15763 
15764   SDNode *U = *ExtVal->use_begin();
15765   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
15766        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
15767     return false;
15768 
15769   return true;
15770 }
15771 
15772 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15773   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15774     return false;
15775 
15776   if (!isTypeLegal(EVT::getEVT(Ty1)))
15777     return false;
15778 
15779   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15780 
15781   // Assuming the caller doesn't have a zeroext or signext return parameter,
15782   // truncation all the way down to i1 is valid.
15783   return true;
15784 }
15785 
15786 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
15787                                                 const AddrMode &AM, Type *Ty,
15788                                                 unsigned AS) const {
15789   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
15790     if (Subtarget->hasFPAO())
15791       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
15792     return 0;
15793   }
15794   return -1;
15795 }
15796 
15797 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
15798 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
15799 /// expanded to FMAs when this method returns true, otherwise fmuladd is
15800 /// expanded to fmul + fadd.
15801 ///
15802 /// ARM supports both fused and unfused multiply-add operations; we already
15803 /// lower a pair of fmul and fadd to the latter so it's not clear that there
15804 /// would be a gain or that the gain would be worthwhile enough to risk
15805 /// correctness bugs.
15806 ///
15807 /// For MVE, we set this to true as it helps simplify the need for some
15808 /// patterns (and we don't have the non-fused floating point instruction).
15809 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15810                                                    EVT VT) const {
15811   if (!VT.isSimple())
15812     return false;
15813 
15814   switch (VT.getSimpleVT().SimpleTy) {
15815   case MVT::v4f32:
15816   case MVT::v8f16:
15817     return Subtarget->hasMVEFloatOps();
15818   case MVT::f16:
15819     return Subtarget->useFPVFMx16();
15820   case MVT::f32:
15821     return Subtarget->useFPVFMx();
15822   case MVT::f64:
15823     return Subtarget->useFPVFMx64();
15824   default:
15825     break;
15826   }
15827 
15828   return false;
15829 }
15830 
15831 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
15832   if (V < 0)
15833     return false;
15834 
15835   unsigned Scale = 1;
15836   switch (VT.getSimpleVT().SimpleTy) {
15837   case MVT::i1:
15838   case MVT::i8:
15839     // Scale == 1;
15840     break;
15841   case MVT::i16:
15842     // Scale == 2;
15843     Scale = 2;
15844     break;
15845   default:
15846     // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
15847     // Scale == 4;
15848     Scale = 4;
15849     break;
15850   }
15851 
15852   if ((V & (Scale - 1)) != 0)
15853     return false;
15854   return isUInt<5>(V / Scale);
15855 }
15856 
15857 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
15858                                       const ARMSubtarget *Subtarget) {
15859   if (!VT.isInteger() && !VT.isFloatingPoint())
15860     return false;
15861   if (VT.isVector() && Subtarget->hasNEON())
15862     return false;
15863   if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
15864       !Subtarget->hasMVEFloatOps())
15865     return false;
15866 
15867   bool IsNeg = false;
15868   if (V < 0) {
15869     IsNeg = true;
15870     V = -V;
15871   }
15872 
15873   unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
15874 
15875   // MVE: size * imm7
15876   if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
15877     switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
15878     case MVT::i32:
15879     case MVT::f32:
15880       return isShiftedUInt<7,2>(V);
15881     case MVT::i16:
15882     case MVT::f16:
15883       return isShiftedUInt<7,1>(V);
15884     case MVT::i8:
15885       return isUInt<7>(V);
15886     default:
15887       return false;
15888     }
15889   }
15890 
15891   // half VLDR: 2 * imm8
15892   if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
15893     return isShiftedUInt<8, 1>(V);
15894   // VLDR and LDRD: 4 * imm8
15895   if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
15896     return isShiftedUInt<8, 2>(V);
15897 
15898   if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
15899     // + imm12 or - imm8
15900     if (IsNeg)
15901       return isUInt<8>(V);
15902     return isUInt<12>(V);
15903   }
15904 
15905   return false;
15906 }
15907 
15908 /// isLegalAddressImmediate - Return true if the integer value can be used
15909 /// as the offset of the target addressing mode for load / store of the
15910 /// given type.
15911 static bool isLegalAddressImmediate(int64_t V, EVT VT,
15912                                     const ARMSubtarget *Subtarget) {
15913   if (V == 0)
15914     return true;
15915 
15916   if (!VT.isSimple())
15917     return false;
15918 
15919   if (Subtarget->isThumb1Only())
15920     return isLegalT1AddressImmediate(V, VT);
15921   else if (Subtarget->isThumb2())
15922     return isLegalT2AddressImmediate(V, VT, Subtarget);
15923 
15924   // ARM mode.
15925   if (V < 0)
15926     V = - V;
15927   switch (VT.getSimpleVT().SimpleTy) {
15928   default: return false;
15929   case MVT::i1:
15930   case MVT::i8:
15931   case MVT::i32:
15932     // +- imm12
15933     return isUInt<12>(V);
15934   case MVT::i16:
15935     // +- imm8
15936     return isUInt<8>(V);
15937   case MVT::f32:
15938   case MVT::f64:
15939     if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
15940       return false;
15941     return isShiftedUInt<8, 2>(V);
15942   }
15943 }
15944 
15945 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
15946                                                       EVT VT) const {
15947   int Scale = AM.Scale;
15948   if (Scale < 0)
15949     return false;
15950 
15951   switch (VT.getSimpleVT().SimpleTy) {
15952   default: return false;
15953   case MVT::i1:
15954   case MVT::i8:
15955   case MVT::i16:
15956   case MVT::i32:
15957     if (Scale == 1)
15958       return true;
15959     // r + r << imm
15960     Scale = Scale & ~1;
15961     return Scale == 2 || Scale == 4 || Scale == 8;
15962   case MVT::i64:
15963     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
15964     // version in Thumb mode.
15965     // r + r
15966     if (Scale == 1)
15967       return true;
15968     // r * 2 (this can be lowered to r + r).
15969     if (!AM.HasBaseReg && Scale == 2)
15970       return true;
15971     return false;
15972   case MVT::isVoid:
15973     // Note, we allow "void" uses (basically, uses that aren't loads or
15974     // stores), because arm allows folding a scale into many arithmetic
15975     // operations.  This should be made more precise and revisited later.
15976 
15977     // Allow r << imm, but the imm has to be a multiple of two.
15978     if (Scale & 1) return false;
15979     return isPowerOf2_32(Scale);
15980   }
15981 }
15982 
15983 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
15984                                                       EVT VT) const {
15985   const int Scale = AM.Scale;
15986 
15987   // Negative scales are not supported in Thumb1.
15988   if (Scale < 0)
15989     return false;
15990 
15991   // Thumb1 addressing modes do not support register scaling excepting the
15992   // following cases:
15993   // 1. Scale == 1 means no scaling.
15994   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
15995   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
15996 }
15997 
15998 /// isLegalAddressingMode - Return true if the addressing mode represented
15999 /// by AM is legal for this target, for a load/store of the specified type.
16000 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16001                                               const AddrMode &AM, Type *Ty,
16002                                               unsigned AS, Instruction *I) const {
16003   EVT VT = getValueType(DL, Ty, true);
16004   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
16005     return false;
16006 
16007   // Can never fold addr of global into load/store.
16008   if (AM.BaseGV)
16009     return false;
16010 
16011   switch (AM.Scale) {
16012   case 0:  // no scale reg, must be "r+i" or "r", or "i".
16013     break;
16014   default:
16015     // ARM doesn't support any R+R*scale+imm addr modes.
16016     if (AM.BaseOffs)
16017       return false;
16018 
16019     if (!VT.isSimple())
16020       return false;
16021 
16022     if (Subtarget->isThumb1Only())
16023       return isLegalT1ScaledAddressingMode(AM, VT);
16024 
16025     if (Subtarget->isThumb2())
16026       return isLegalT2ScaledAddressingMode(AM, VT);
16027 
16028     int Scale = AM.Scale;
16029     switch (VT.getSimpleVT().SimpleTy) {
16030     default: return false;
16031     case MVT::i1:
16032     case MVT::i8:
16033     case MVT::i32:
16034       if (Scale < 0) Scale = -Scale;
16035       if (Scale == 1)
16036         return true;
16037       // r + r << imm
16038       return isPowerOf2_32(Scale & ~1);
16039     case MVT::i16:
16040     case MVT::i64:
16041       // r +/- r
16042       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
16043         return true;
16044       // r * 2 (this can be lowered to r + r).
16045       if (!AM.HasBaseReg && Scale == 2)
16046         return true;
16047       return false;
16048 
16049     case MVT::isVoid:
16050       // Note, we allow "void" uses (basically, uses that aren't loads or
16051       // stores), because arm allows folding a scale into many arithmetic
16052       // operations.  This should be made more precise and revisited later.
16053 
16054       // Allow r << imm, but the imm has to be a multiple of two.
16055       if (Scale & 1) return false;
16056       return isPowerOf2_32(Scale);
16057     }
16058   }
16059   return true;
16060 }
16061 
16062 /// isLegalICmpImmediate - Return true if the specified immediate is legal
16063 /// icmp immediate, that is the target has icmp instructions which can compare
16064 /// a register against the immediate without having to materialize the
16065 /// immediate into a register.
16066 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16067   // Thumb2 and ARM modes can use cmn for negative immediates.
16068   if (!Subtarget->isThumb())
16069     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
16070            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
16071   if (Subtarget->isThumb2())
16072     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
16073            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
16074   // Thumb1 doesn't have cmn, and only 8-bit immediates.
16075   return Imm >= 0 && Imm <= 255;
16076 }
16077 
16078 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
16079 /// *or sub* immediate, that is the target has add or sub instructions which can
16080 /// add a register with the immediate without having to materialize the
16081 /// immediate into a register.
16082 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16083   // Same encoding for add/sub, just flip the sign.
16084   int64_t AbsImm = std::abs(Imm);
16085   if (!Subtarget->isThumb())
16086     return ARM_AM::getSOImmVal(AbsImm) != -1;
16087   if (Subtarget->isThumb2())
16088     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
16089   // Thumb1 only has 8-bit unsigned immediate.
16090   return AbsImm >= 0 && AbsImm <= 255;
16091 }
16092 
16093 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
16094                                       bool isSEXTLoad, SDValue &Base,
16095                                       SDValue &Offset, bool &isInc,
16096                                       SelectionDAG &DAG) {
16097   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
16098     return false;
16099 
16100   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
16101     // AddressingMode 3
16102     Base = Ptr->getOperand(0);
16103     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
16104       int RHSC = (int)RHS->getZExtValue();
16105       if (RHSC < 0 && RHSC > -256) {
16106         assert(Ptr->getOpcode() == ISD::ADD);
16107         isInc = false;
16108         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16109         return true;
16110       }
16111     }
16112     isInc = (Ptr->getOpcode() == ISD::ADD);
16113     Offset = Ptr->getOperand(1);
16114     return true;
16115   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
16116     // AddressingMode 2
16117     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
16118       int RHSC = (int)RHS->getZExtValue();
16119       if (RHSC < 0 && RHSC > -0x1000) {
16120         assert(Ptr->getOpcode() == ISD::ADD);
16121         isInc = false;
16122         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16123         Base = Ptr->getOperand(0);
16124         return true;
16125       }
16126     }
16127 
16128     if (Ptr->getOpcode() == ISD::ADD) {
16129       isInc = true;
16130       ARM_AM::ShiftOpc ShOpcVal=
16131         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
16132       if (ShOpcVal != ARM_AM::no_shift) {
16133         Base = Ptr->getOperand(1);
16134         Offset = Ptr->getOperand(0);
16135       } else {
16136         Base = Ptr->getOperand(0);
16137         Offset = Ptr->getOperand(1);
16138       }
16139       return true;
16140     }
16141 
16142     isInc = (Ptr->getOpcode() == ISD::ADD);
16143     Base = Ptr->getOperand(0);
16144     Offset = Ptr->getOperand(1);
16145     return true;
16146   }
16147 
16148   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
16149   return false;
16150 }
16151 
16152 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
16153                                      bool isSEXTLoad, SDValue &Base,
16154                                      SDValue &Offset, bool &isInc,
16155                                      SelectionDAG &DAG) {
16156   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
16157     return false;
16158 
16159   Base = Ptr->getOperand(0);
16160   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
16161     int RHSC = (int)RHS->getZExtValue();
16162     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
16163       assert(Ptr->getOpcode() == ISD::ADD);
16164       isInc = false;
16165       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16166       return true;
16167     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
16168       isInc = Ptr->getOpcode() == ISD::ADD;
16169       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
16170       return true;
16171     }
16172   }
16173 
16174   return false;
16175 }
16176 
16177 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align,
16178                                       bool isSEXTLoad, bool IsMasked, bool isLE,
16179                                       SDValue &Base, SDValue &Offset,
16180                                       bool &isInc, SelectionDAG &DAG) {
16181   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
16182     return false;
16183   if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
16184     return false;
16185 
16186   // We allow LE non-masked loads to change the type (for example use a vldrb.8
16187   // as opposed to a vldrw.32). This can allow extra addressing modes or
16188   // alignments for what is otherwise an equivalent instruction.
16189   bool CanChangeType = isLE && !IsMasked;
16190 
16191   ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
16192   int RHSC = (int)RHS->getZExtValue();
16193 
16194   auto IsInRange = [&](int RHSC, int Limit, int Scale) {
16195     if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
16196       assert(Ptr->getOpcode() == ISD::ADD);
16197       isInc = false;
16198       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16199       return true;
16200     } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
16201       isInc = Ptr->getOpcode() == ISD::ADD;
16202       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
16203       return true;
16204     }
16205     return false;
16206   };
16207 
16208   // Try to find a matching instruction based on s/zext, Alignment, Offset and
16209   // (in BE/masked) type.
16210   Base = Ptr->getOperand(0);
16211   if (VT == MVT::v4i16) {
16212     if (Align >= 2 && IsInRange(RHSC, 0x80, 2))
16213       return true;
16214   } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
16215     if (IsInRange(RHSC, 0x80, 1))
16216       return true;
16217   } else if (Align >= 4 &&
16218              (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
16219              IsInRange(RHSC, 0x80, 4))
16220     return true;
16221   else if (Align >= 2 &&
16222            (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
16223            IsInRange(RHSC, 0x80, 2))
16224     return true;
16225   else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
16226     return true;
16227   return false;
16228 }
16229 
16230 /// getPreIndexedAddressParts - returns true by value, base pointer and
16231 /// offset pointer and addressing mode by reference if the node's address
16232 /// can be legally represented as pre-indexed load / store address.
16233 bool
16234 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
16235                                              SDValue &Offset,
16236                                              ISD::MemIndexedMode &AM,
16237                                              SelectionDAG &DAG) const {
16238   if (Subtarget->isThumb1Only())
16239     return false;
16240 
16241   EVT VT;
16242   SDValue Ptr;
16243   unsigned Align;
16244   bool isSEXTLoad = false;
16245   bool IsMasked = false;
16246   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
16247     Ptr = LD->getBasePtr();
16248     VT = LD->getMemoryVT();
16249     Align = LD->getAlignment();
16250     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
16251   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
16252     Ptr = ST->getBasePtr();
16253     VT = ST->getMemoryVT();
16254     Align = ST->getAlignment();
16255   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
16256     Ptr = LD->getBasePtr();
16257     VT = LD->getMemoryVT();
16258     Align = LD->getAlignment();
16259     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
16260     IsMasked = true;
16261   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
16262     Ptr = ST->getBasePtr();
16263     VT = ST->getMemoryVT();
16264     Align = ST->getAlignment();
16265     IsMasked = true;
16266   } else
16267     return false;
16268 
16269   bool isInc;
16270   bool isLegal = false;
16271   if (VT.isVector())
16272     isLegal = Subtarget->hasMVEIntegerOps() &&
16273               getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad,
16274                                         IsMasked, Subtarget->isLittle(), Base,
16275                                         Offset, isInc, DAG);
16276   else {
16277     if (Subtarget->isThumb2())
16278       isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
16279                                          Offset, isInc, DAG);
16280     else
16281       isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
16282                                           Offset, isInc, DAG);
16283   }
16284   if (!isLegal)
16285     return false;
16286 
16287   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
16288   return true;
16289 }
16290 
16291 /// getPostIndexedAddressParts - returns true by value, base pointer and
16292 /// offset pointer and addressing mode by reference if this node can be
16293 /// combined with a load / store to form a post-indexed load / store.
16294 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
16295                                                    SDValue &Base,
16296                                                    SDValue &Offset,
16297                                                    ISD::MemIndexedMode &AM,
16298                                                    SelectionDAG &DAG) const {
16299   EVT VT;
16300   SDValue Ptr;
16301   unsigned Align;
16302   bool isSEXTLoad = false, isNonExt;
16303   bool IsMasked = false;
16304   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
16305     VT = LD->getMemoryVT();
16306     Ptr = LD->getBasePtr();
16307     Align = LD->getAlignment();
16308     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
16309     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
16310   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
16311     VT = ST->getMemoryVT();
16312     Ptr = ST->getBasePtr();
16313     Align = ST->getAlignment();
16314     isNonExt = !ST->isTruncatingStore();
16315   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
16316     VT = LD->getMemoryVT();
16317     Ptr = LD->getBasePtr();
16318     Align = LD->getAlignment();
16319     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
16320     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
16321     IsMasked = true;
16322   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
16323     VT = ST->getMemoryVT();
16324     Ptr = ST->getBasePtr();
16325     Align = ST->getAlignment();
16326     isNonExt = !ST->isTruncatingStore();
16327     IsMasked = true;
16328   } else
16329     return false;
16330 
16331   if (Subtarget->isThumb1Only()) {
16332     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
16333     // must be non-extending/truncating, i32, with an offset of 4.
16334     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
16335     if (Op->getOpcode() != ISD::ADD || !isNonExt)
16336       return false;
16337     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
16338     if (!RHS || RHS->getZExtValue() != 4)
16339       return false;
16340 
16341     Offset = Op->getOperand(1);
16342     Base = Op->getOperand(0);
16343     AM = ISD::POST_INC;
16344     return true;
16345   }
16346 
16347   bool isInc;
16348   bool isLegal = false;
16349   if (VT.isVector())
16350     isLegal = Subtarget->hasMVEIntegerOps() &&
16351               getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad, IsMasked,
16352                                         Subtarget->isLittle(), Base, Offset,
16353                                         isInc, DAG);
16354   else {
16355     if (Subtarget->isThumb2())
16356       isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
16357                                          isInc, DAG);
16358     else
16359       isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
16360                                           isInc, DAG);
16361   }
16362   if (!isLegal)
16363     return false;
16364 
16365   if (Ptr != Base) {
16366     // Swap base ptr and offset to catch more post-index load / store when
16367     // it's legal. In Thumb2 mode, offset must be an immediate.
16368     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
16369         !Subtarget->isThumb2())
16370       std::swap(Base, Offset);
16371 
16372     // Post-indexed load / store update the base pointer.
16373     if (Ptr != Base)
16374       return false;
16375   }
16376 
16377   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
16378   return true;
16379 }
16380 
16381 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
16382                                                       KnownBits &Known,
16383                                                       const APInt &DemandedElts,
16384                                                       const SelectionDAG &DAG,
16385                                                       unsigned Depth) const {
16386   unsigned BitWidth = Known.getBitWidth();
16387   Known.resetAll();
16388   switch (Op.getOpcode()) {
16389   default: break;
16390   case ARMISD::ADDC:
16391   case ARMISD::ADDE:
16392   case ARMISD::SUBC:
16393   case ARMISD::SUBE:
16394     // Special cases when we convert a carry to a boolean.
16395     if (Op.getResNo() == 0) {
16396       SDValue LHS = Op.getOperand(0);
16397       SDValue RHS = Op.getOperand(1);
16398       // (ADDE 0, 0, C) will give us a single bit.
16399       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
16400           isNullConstant(RHS)) {
16401         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16402         return;
16403       }
16404     }
16405     break;
16406   case ARMISD::CMOV: {
16407     // Bits are known zero/one if known on the LHS and RHS.
16408     Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
16409     if (Known.isUnknown())
16410       return;
16411 
16412     KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
16413     Known.Zero &= KnownRHS.Zero;
16414     Known.One  &= KnownRHS.One;
16415     return;
16416   }
16417   case ISD::INTRINSIC_W_CHAIN: {
16418     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
16419     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
16420     switch (IntID) {
16421     default: return;
16422     case Intrinsic::arm_ldaex:
16423     case Intrinsic::arm_ldrex: {
16424       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
16425       unsigned MemBits = VT.getScalarSizeInBits();
16426       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
16427       return;
16428     }
16429     }
16430   }
16431   case ARMISD::BFI: {
16432     // Conservatively, we can recurse down the first operand
16433     // and just mask out all affected bits.
16434     Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
16435 
16436     // The operand to BFI is already a mask suitable for removing the bits it
16437     // sets.
16438     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
16439     const APInt &Mask = CI->getAPIntValue();
16440     Known.Zero &= Mask;
16441     Known.One &= Mask;
16442     return;
16443   }
16444   case ARMISD::VGETLANEs:
16445   case ARMISD::VGETLANEu: {
16446     const SDValue &SrcSV = Op.getOperand(0);
16447     EVT VecVT = SrcSV.getValueType();
16448     assert(VecVT.isVector() && "VGETLANE expected a vector type");
16449     const unsigned NumSrcElts = VecVT.getVectorNumElements();
16450     ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
16451     assert(Pos->getAPIntValue().ult(NumSrcElts) &&
16452            "VGETLANE index out of bounds");
16453     unsigned Idx = Pos->getZExtValue();
16454     APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
16455     Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
16456 
16457     EVT VT = Op.getValueType();
16458     const unsigned DstSz = VT.getScalarSizeInBits();
16459     const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
16460     (void)SrcSz;
16461     assert(SrcSz == Known.getBitWidth());
16462     assert(DstSz > SrcSz);
16463     if (Op.getOpcode() == ARMISD::VGETLANEs)
16464       Known = Known.sext(DstSz);
16465     else {
16466       Known = Known.zext(DstSz);
16467     }
16468     assert(DstSz == Known.getBitWidth());
16469     break;
16470   }
16471   case ARMISD::VMOVrh: {
16472     KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
16473     assert(KnownOp.getBitWidth() == 16);
16474     Known = KnownOp.zext(32);
16475     break;
16476   }
16477   }
16478 }
16479 
16480 bool
16481 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
16482                                                 const APInt &DemandedAPInt,
16483                                                 TargetLoweringOpt &TLO) const {
16484   // Delay optimization, so we don't have to deal with illegal types, or block
16485   // optimizations.
16486   if (!TLO.LegalOps)
16487     return false;
16488 
16489   // Only optimize AND for now.
16490   if (Op.getOpcode() != ISD::AND)
16491     return false;
16492 
16493   EVT VT = Op.getValueType();
16494 
16495   // Ignore vectors.
16496   if (VT.isVector())
16497     return false;
16498 
16499   assert(VT == MVT::i32 && "Unexpected integer type");
16500 
16501   // Make sure the RHS really is a constant.
16502   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
16503   if (!C)
16504     return false;
16505 
16506   unsigned Mask = C->getZExtValue();
16507 
16508   unsigned Demanded = DemandedAPInt.getZExtValue();
16509   unsigned ShrunkMask = Mask & Demanded;
16510   unsigned ExpandedMask = Mask | ~Demanded;
16511 
16512   // If the mask is all zeros, let the target-independent code replace the
16513   // result with zero.
16514   if (ShrunkMask == 0)
16515     return false;
16516 
16517   // If the mask is all ones, erase the AND. (Currently, the target-independent
16518   // code won't do this, so we have to do it explicitly to avoid an infinite
16519   // loop in obscure cases.)
16520   if (ExpandedMask == ~0U)
16521     return TLO.CombineTo(Op, Op.getOperand(0));
16522 
16523   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
16524     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
16525   };
16526   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
16527     if (NewMask == Mask)
16528       return true;
16529     SDLoc DL(Op);
16530     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
16531     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
16532     return TLO.CombineTo(Op, NewOp);
16533   };
16534 
16535   // Prefer uxtb mask.
16536   if (IsLegalMask(0xFF))
16537     return UseMask(0xFF);
16538 
16539   // Prefer uxth mask.
16540   if (IsLegalMask(0xFFFF))
16541     return UseMask(0xFFFF);
16542 
16543   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
16544   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
16545   if (ShrunkMask < 256)
16546     return UseMask(ShrunkMask);
16547 
16548   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
16549   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
16550   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
16551     return UseMask(ExpandedMask);
16552 
16553   // Potential improvements:
16554   //
16555   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
16556   // We could try to prefer Thumb1 immediates which can be lowered to a
16557   // two-instruction sequence.
16558   // We could try to recognize more legal ARM/Thumb2 immediates here.
16559 
16560   return false;
16561 }
16562 
16563 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
16564     SDValue Op, const APInt &OriginalDemandedBits,
16565     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
16566     unsigned Depth) const {
16567   unsigned Opc = Op.getOpcode();
16568 
16569   switch (Opc) {
16570   case ARMISD::ASRL:
16571   case ARMISD::LSRL: {
16572     // If this is result 0 and the other result is unused, see if the demand
16573     // bits allow us to shrink this long shift into a standard small shift in
16574     // the opposite direction.
16575     if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
16576         isa<ConstantSDNode>(Op->getOperand(2))) {
16577       unsigned ShAmt = Op->getConstantOperandVal(2);
16578       if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(
16579                             APInt::getAllOnesValue(32) << (32 - ShAmt)))
16580         return TLO.CombineTo(
16581             Op, TLO.DAG.getNode(
16582                     ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
16583                     TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
16584     }
16585     break;
16586   }
16587   }
16588 
16589   return TargetLowering::SimplifyDemandedBitsForTargetNode(
16590       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
16591 }
16592 
16593 //===----------------------------------------------------------------------===//
16594 //                           ARM Inline Assembly Support
16595 //===----------------------------------------------------------------------===//
16596 
16597 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
16598   // Looking for "rev" which is V6+.
16599   if (!Subtarget->hasV6Ops())
16600     return false;
16601 
16602   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
16603   std::string AsmStr = IA->getAsmString();
16604   SmallVector<StringRef, 4> AsmPieces;
16605   SplitString(AsmStr, AsmPieces, ";\n");
16606 
16607   switch (AsmPieces.size()) {
16608   default: return false;
16609   case 1:
16610     AsmStr = std::string(AsmPieces[0]);
16611     AsmPieces.clear();
16612     SplitString(AsmStr, AsmPieces, " \t,");
16613 
16614     // rev $0, $1
16615     if (AsmPieces.size() == 3 &&
16616         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
16617         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
16618       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16619       if (Ty && Ty->getBitWidth() == 32)
16620         return IntrinsicLowering::LowerToByteSwap(CI);
16621     }
16622     break;
16623   }
16624 
16625   return false;
16626 }
16627 
16628 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
16629   // At this point, we have to lower this constraint to something else, so we
16630   // lower it to an "r" or "w". However, by doing this we will force the result
16631   // to be in register, while the X constraint is much more permissive.
16632   //
16633   // Although we are correct (we are free to emit anything, without
16634   // constraints), we might break use cases that would expect us to be more
16635   // efficient and emit something else.
16636   if (!Subtarget->hasVFP2Base())
16637     return "r";
16638   if (ConstraintVT.isFloatingPoint())
16639     return "w";
16640   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
16641      (ConstraintVT.getSizeInBits() == 64 ||
16642       ConstraintVT.getSizeInBits() == 128))
16643     return "w";
16644 
16645   return "r";
16646 }
16647 
16648 /// getConstraintType - Given a constraint letter, return the type of
16649 /// constraint it is for this target.
16650 ARMTargetLowering::ConstraintType
16651 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
16652   unsigned S = Constraint.size();
16653   if (S == 1) {
16654     switch (Constraint[0]) {
16655     default:  break;
16656     case 'l': return C_RegisterClass;
16657     case 'w': return C_RegisterClass;
16658     case 'h': return C_RegisterClass;
16659     case 'x': return C_RegisterClass;
16660     case 't': return C_RegisterClass;
16661     case 'j': return C_Immediate; // Constant for movw.
16662     // An address with a single base register. Due to the way we
16663     // currently handle addresses it is the same as an 'r' memory constraint.
16664     case 'Q': return C_Memory;
16665     }
16666   } else if (S == 2) {
16667     switch (Constraint[0]) {
16668     default: break;
16669     case 'T': return C_RegisterClass;
16670     // All 'U+' constraints are addresses.
16671     case 'U': return C_Memory;
16672     }
16673   }
16674   return TargetLowering::getConstraintType(Constraint);
16675 }
16676 
16677 /// Examine constraint type and operand type and determine a weight value.
16678 /// This object must already have been set up with the operand type
16679 /// and the current alternative constraint selected.
16680 TargetLowering::ConstraintWeight
16681 ARMTargetLowering::getSingleConstraintMatchWeight(
16682     AsmOperandInfo &info, const char *constraint) const {
16683   ConstraintWeight weight = CW_Invalid;
16684   Value *CallOperandVal = info.CallOperandVal;
16685     // If we don't have a value, we can't do a match,
16686     // but allow it at the lowest weight.
16687   if (!CallOperandVal)
16688     return CW_Default;
16689   Type *type = CallOperandVal->getType();
16690   // Look at the constraint type.
16691   switch (*constraint) {
16692   default:
16693     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16694     break;
16695   case 'l':
16696     if (type->isIntegerTy()) {
16697       if (Subtarget->isThumb())
16698         weight = CW_SpecificReg;
16699       else
16700         weight = CW_Register;
16701     }
16702     break;
16703   case 'w':
16704     if (type->isFloatingPointTy())
16705       weight = CW_Register;
16706     break;
16707   }
16708   return weight;
16709 }
16710 
16711 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
16712 
16713 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
16714     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
16715   switch (Constraint.size()) {
16716   case 1:
16717     // GCC ARM Constraint Letters
16718     switch (Constraint[0]) {
16719     case 'l': // Low regs or general regs.
16720       if (Subtarget->isThumb())
16721         return RCPair(0U, &ARM::tGPRRegClass);
16722       return RCPair(0U, &ARM::GPRRegClass);
16723     case 'h': // High regs or no regs.
16724       if (Subtarget->isThumb())
16725         return RCPair(0U, &ARM::hGPRRegClass);
16726       break;
16727     case 'r':
16728       if (Subtarget->isThumb1Only())
16729         return RCPair(0U, &ARM::tGPRRegClass);
16730       return RCPair(0U, &ARM::GPRRegClass);
16731     case 'w':
16732       if (VT == MVT::Other)
16733         break;
16734       if (VT == MVT::f32)
16735         return RCPair(0U, &ARM::SPRRegClass);
16736       if (VT.getSizeInBits() == 64)
16737         return RCPair(0U, &ARM::DPRRegClass);
16738       if (VT.getSizeInBits() == 128)
16739         return RCPair(0U, &ARM::QPRRegClass);
16740       break;
16741     case 'x':
16742       if (VT == MVT::Other)
16743         break;
16744       if (VT == MVT::f32)
16745         return RCPair(0U, &ARM::SPR_8RegClass);
16746       if (VT.getSizeInBits() == 64)
16747         return RCPair(0U, &ARM::DPR_8RegClass);
16748       if (VT.getSizeInBits() == 128)
16749         return RCPair(0U, &ARM::QPR_8RegClass);
16750       break;
16751     case 't':
16752       if (VT == MVT::Other)
16753         break;
16754       if (VT == MVT::f32 || VT == MVT::i32)
16755         return RCPair(0U, &ARM::SPRRegClass);
16756       if (VT.getSizeInBits() == 64)
16757         return RCPair(0U, &ARM::DPR_VFP2RegClass);
16758       if (VT.getSizeInBits() == 128)
16759         return RCPair(0U, &ARM::QPR_VFP2RegClass);
16760       break;
16761     }
16762     break;
16763 
16764   case 2:
16765     if (Constraint[0] == 'T') {
16766       switch (Constraint[1]) {
16767       default:
16768         break;
16769       case 'e':
16770         return RCPair(0U, &ARM::tGPREvenRegClass);
16771       case 'o':
16772         return RCPair(0U, &ARM::tGPROddRegClass);
16773       }
16774     }
16775     break;
16776 
16777   default:
16778     break;
16779   }
16780 
16781   if (StringRef("{cc}").equals_lower(Constraint))
16782     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
16783 
16784   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
16785 }
16786 
16787 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16788 /// vector.  If it is invalid, don't add anything to Ops.
16789 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16790                                                      std::string &Constraint,
16791                                                      std::vector<SDValue>&Ops,
16792                                                      SelectionDAG &DAG) const {
16793   SDValue Result;
16794 
16795   // Currently only support length 1 constraints.
16796   if (Constraint.length() != 1) return;
16797 
16798   char ConstraintLetter = Constraint[0];
16799   switch (ConstraintLetter) {
16800   default: break;
16801   case 'j':
16802   case 'I': case 'J': case 'K': case 'L':
16803   case 'M': case 'N': case 'O':
16804     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
16805     if (!C)
16806       return;
16807 
16808     int64_t CVal64 = C->getSExtValue();
16809     int CVal = (int) CVal64;
16810     // None of these constraints allow values larger than 32 bits.  Check
16811     // that the value fits in an int.
16812     if (CVal != CVal64)
16813       return;
16814 
16815     switch (ConstraintLetter) {
16816       case 'j':
16817         // Constant suitable for movw, must be between 0 and
16818         // 65535.
16819         if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
16820           if (CVal >= 0 && CVal <= 65535)
16821             break;
16822         return;
16823       case 'I':
16824         if (Subtarget->isThumb1Only()) {
16825           // This must be a constant between 0 and 255, for ADD
16826           // immediates.
16827           if (CVal >= 0 && CVal <= 255)
16828             break;
16829         } else if (Subtarget->isThumb2()) {
16830           // A constant that can be used as an immediate value in a
16831           // data-processing instruction.
16832           if (ARM_AM::getT2SOImmVal(CVal) != -1)
16833             break;
16834         } else {
16835           // A constant that can be used as an immediate value in a
16836           // data-processing instruction.
16837           if (ARM_AM::getSOImmVal(CVal) != -1)
16838             break;
16839         }
16840         return;
16841 
16842       case 'J':
16843         if (Subtarget->isThumb1Only()) {
16844           // This must be a constant between -255 and -1, for negated ADD
16845           // immediates. This can be used in GCC with an "n" modifier that
16846           // prints the negated value, for use with SUB instructions. It is
16847           // not useful otherwise but is implemented for compatibility.
16848           if (CVal >= -255 && CVal <= -1)
16849             break;
16850         } else {
16851           // This must be a constant between -4095 and 4095. It is not clear
16852           // what this constraint is intended for. Implemented for
16853           // compatibility with GCC.
16854           if (CVal >= -4095 && CVal <= 4095)
16855             break;
16856         }
16857         return;
16858 
16859       case 'K':
16860         if (Subtarget->isThumb1Only()) {
16861           // A 32-bit value where only one byte has a nonzero value. Exclude
16862           // zero to match GCC. This constraint is used by GCC internally for
16863           // constants that can be loaded with a move/shift combination.
16864           // It is not useful otherwise but is implemented for compatibility.
16865           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
16866             break;
16867         } else if (Subtarget->isThumb2()) {
16868           // A constant whose bitwise inverse can be used as an immediate
16869           // value in a data-processing instruction. This can be used in GCC
16870           // with a "B" modifier that prints the inverted value, for use with
16871           // BIC and MVN instructions. It is not useful otherwise but is
16872           // implemented for compatibility.
16873           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
16874             break;
16875         } else {
16876           // A constant whose bitwise inverse can be used as an immediate
16877           // value in a data-processing instruction. This can be used in GCC
16878           // with a "B" modifier that prints the inverted value, for use with
16879           // BIC and MVN instructions. It is not useful otherwise but is
16880           // implemented for compatibility.
16881           if (ARM_AM::getSOImmVal(~CVal) != -1)
16882             break;
16883         }
16884         return;
16885 
16886       case 'L':
16887         if (Subtarget->isThumb1Only()) {
16888           // This must be a constant between -7 and 7,
16889           // for 3-operand ADD/SUB immediate instructions.
16890           if (CVal >= -7 && CVal < 7)
16891             break;
16892         } else if (Subtarget->isThumb2()) {
16893           // A constant whose negation can be used as an immediate value in a
16894           // data-processing instruction. This can be used in GCC with an "n"
16895           // modifier that prints the negated value, for use with SUB
16896           // instructions. It is not useful otherwise but is implemented for
16897           // compatibility.
16898           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
16899             break;
16900         } else {
16901           // A constant whose negation can be used as an immediate value in a
16902           // data-processing instruction. This can be used in GCC with an "n"
16903           // modifier that prints the negated value, for use with SUB
16904           // instructions. It is not useful otherwise but is implemented for
16905           // compatibility.
16906           if (ARM_AM::getSOImmVal(-CVal) != -1)
16907             break;
16908         }
16909         return;
16910 
16911       case 'M':
16912         if (Subtarget->isThumb1Only()) {
16913           // This must be a multiple of 4 between 0 and 1020, for
16914           // ADD sp + immediate.
16915           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
16916             break;
16917         } else {
16918           // A power of two or a constant between 0 and 32.  This is used in
16919           // GCC for the shift amount on shifted register operands, but it is
16920           // useful in general for any shift amounts.
16921           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
16922             break;
16923         }
16924         return;
16925 
16926       case 'N':
16927         if (Subtarget->isThumb1Only()) {
16928           // This must be a constant between 0 and 31, for shift amounts.
16929           if (CVal >= 0 && CVal <= 31)
16930             break;
16931         }
16932         return;
16933 
16934       case 'O':
16935         if (Subtarget->isThumb1Only()) {
16936           // This must be a multiple of 4 between -508 and 508, for
16937           // ADD/SUB sp = sp + immediate.
16938           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
16939             break;
16940         }
16941         return;
16942     }
16943     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
16944     break;
16945   }
16946 
16947   if (Result.getNode()) {
16948     Ops.push_back(Result);
16949     return;
16950   }
16951   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16952 }
16953 
16954 static RTLIB::Libcall getDivRemLibcall(
16955     const SDNode *N, MVT::SimpleValueType SVT) {
16956   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
16957           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
16958          "Unhandled Opcode in getDivRemLibcall");
16959   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
16960                   N->getOpcode() == ISD::SREM;
16961   RTLIB::Libcall LC;
16962   switch (SVT) {
16963   default: llvm_unreachable("Unexpected request for libcall!");
16964   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
16965   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
16966   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
16967   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
16968   }
16969   return LC;
16970 }
16971 
16972 static TargetLowering::ArgListTy getDivRemArgList(
16973     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
16974   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
16975           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
16976          "Unhandled Opcode in getDivRemArgList");
16977   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
16978                   N->getOpcode() == ISD::SREM;
16979   TargetLowering::ArgListTy Args;
16980   TargetLowering::ArgListEntry Entry;
16981   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
16982     EVT ArgVT = N->getOperand(i).getValueType();
16983     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
16984     Entry.Node = N->getOperand(i);
16985     Entry.Ty = ArgTy;
16986     Entry.IsSExt = isSigned;
16987     Entry.IsZExt = !isSigned;
16988     Args.push_back(Entry);
16989   }
16990   if (Subtarget->isTargetWindows() && Args.size() >= 2)
16991     std::swap(Args[0], Args[1]);
16992   return Args;
16993 }
16994 
16995 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
16996   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
16997           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
16998           Subtarget->isTargetWindows()) &&
16999          "Register-based DivRem lowering only");
17000   unsigned Opcode = Op->getOpcode();
17001   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
17002          "Invalid opcode for Div/Rem lowering");
17003   bool isSigned = (Opcode == ISD::SDIVREM);
17004   EVT VT = Op->getValueType(0);
17005   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
17006   SDLoc dl(Op);
17007 
17008   // If the target has hardware divide, use divide + multiply + subtract:
17009   //     div = a / b
17010   //     rem = a - b * div
17011   //     return {div, rem}
17012   // This should be lowered into UDIV/SDIV + MLS later on.
17013   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
17014                                         : Subtarget->hasDivideInARMMode();
17015   if (hasDivide && Op->getValueType(0).isSimple() &&
17016       Op->getSimpleValueType(0) == MVT::i32) {
17017     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
17018     const SDValue Dividend = Op->getOperand(0);
17019     const SDValue Divisor = Op->getOperand(1);
17020     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
17021     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
17022     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
17023 
17024     SDValue Values[2] = {Div, Rem};
17025     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
17026   }
17027 
17028   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
17029                                        VT.getSimpleVT().SimpleTy);
17030   SDValue InChain = DAG.getEntryNode();
17031 
17032   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
17033                                                     DAG.getContext(),
17034                                                     Subtarget);
17035 
17036   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17037                                          getPointerTy(DAG.getDataLayout()));
17038 
17039   Type *RetTy = StructType::get(Ty, Ty);
17040 
17041   if (Subtarget->isTargetWindows())
17042     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
17043 
17044   TargetLowering::CallLoweringInfo CLI(DAG);
17045   CLI.setDebugLoc(dl).setChain(InChain)
17046     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
17047     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17048 
17049   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17050   return CallInfo.first;
17051 }
17052 
17053 // Lowers REM using divmod helpers
17054 // see RTABI section 4.2/4.3
17055 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
17056   // Build return types (div and rem)
17057   std::vector<Type*> RetTyParams;
17058   Type *RetTyElement;
17059 
17060   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
17061   default: llvm_unreachable("Unexpected request for libcall!");
17062   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
17063   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
17064   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
17065   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
17066   }
17067 
17068   RetTyParams.push_back(RetTyElement);
17069   RetTyParams.push_back(RetTyElement);
17070   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
17071   Type *RetTy = StructType::get(*DAG.getContext(), ret);
17072 
17073   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
17074                                                              SimpleTy);
17075   SDValue InChain = DAG.getEntryNode();
17076   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
17077                                                     Subtarget);
17078   bool isSigned = N->getOpcode() == ISD::SREM;
17079   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17080                                          getPointerTy(DAG.getDataLayout()));
17081 
17082   if (Subtarget->isTargetWindows())
17083     InChain = WinDBZCheckDenominator(DAG, N, InChain);
17084 
17085   // Lower call
17086   CallLoweringInfo CLI(DAG);
17087   CLI.setChain(InChain)
17088      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
17089      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
17090   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
17091 
17092   // Return second (rem) result operand (first contains div)
17093   SDNode *ResNode = CallResult.first.getNode();
17094   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
17095   return ResNode->getOperand(1);
17096 }
17097 
17098 SDValue
17099 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
17100   assert(Subtarget->isTargetWindows() && "unsupported target platform");
17101   SDLoc DL(Op);
17102 
17103   // Get the inputs.
17104   SDValue Chain = Op.getOperand(0);
17105   SDValue Size  = Op.getOperand(1);
17106 
17107   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
17108           "no-stack-arg-probe")) {
17109     unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
17110     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
17111     Chain = SP.getValue(1);
17112     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
17113     if (Align)
17114       SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
17115                        DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
17116     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
17117     SDValue Ops[2] = { SP, Chain };
17118     return DAG.getMergeValues(Ops, DL);
17119   }
17120 
17121   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
17122                               DAG.getConstant(2, DL, MVT::i32));
17123 
17124   SDValue Flag;
17125   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
17126   Flag = Chain.getValue(1);
17127 
17128   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
17129   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
17130 
17131   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
17132   Chain = NewSP.getValue(1);
17133 
17134   SDValue Ops[2] = { NewSP, Chain };
17135   return DAG.getMergeValues(Ops, DL);
17136 }
17137 
17138 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
17139   bool IsStrict = Op->isStrictFPOpcode();
17140   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
17141   const unsigned DstSz = Op.getValueType().getSizeInBits();
17142   const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
17143   assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
17144          "Unexpected type for custom-lowering FP_EXTEND");
17145 
17146   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
17147          "With both FP DP and 16, any FP conversion is legal!");
17148 
17149   assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
17150          "With FP16, 16 to 32 conversion is legal!");
17151 
17152   // Converting from 32 -> 64 is valid if we have FP64.
17153   if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
17154     // FIXME: Remove this when we have strict fp instruction selection patterns
17155     if (IsStrict) {
17156       SDLoc Loc(Op);
17157       SDValue Result = DAG.getNode(ISD::FP_EXTEND,
17158                                    Loc, Op.getValueType(), SrcVal);
17159       return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
17160     }
17161     return Op;
17162   }
17163 
17164   // Either we are converting from 16 -> 64, without FP16 and/or
17165   // FP.double-precision or without Armv8-fp. So we must do it in two
17166   // steps.
17167   // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
17168   // without FP16. So we must do a function call.
17169   SDLoc Loc(Op);
17170   RTLIB::Libcall LC;
17171   MakeLibCallOptions CallOptions;
17172   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
17173   for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
17174     bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
17175     MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
17176     MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
17177     if (Supported) {
17178       if (IsStrict) {
17179         SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
17180                              {DstVT, MVT::Other}, {Chain, SrcVal});
17181         Chain = SrcVal.getValue(1);
17182       } else {
17183         SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
17184       }
17185     } else {
17186       LC = RTLIB::getFPEXT(SrcVT, DstVT);
17187       assert(LC != RTLIB::UNKNOWN_LIBCALL &&
17188              "Unexpected type for custom-lowering FP_EXTEND");
17189       std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
17190                                             Loc, Chain);
17191     }
17192   }
17193 
17194   return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
17195 }
17196 
17197 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
17198   bool IsStrict = Op->isStrictFPOpcode();
17199 
17200   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
17201   EVT SrcVT = SrcVal.getValueType();
17202   EVT DstVT = Op.getValueType();
17203   const unsigned DstSz = Op.getValueType().getSizeInBits();
17204   const unsigned SrcSz = SrcVT.getSizeInBits();
17205   (void)DstSz;
17206   assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
17207          "Unexpected type for custom-lowering FP_ROUND");
17208 
17209   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
17210          "With both FP DP and 16, any FP conversion is legal!");
17211 
17212   SDLoc Loc(Op);
17213 
17214   // Instruction from 32 -> 16 if hasFP16 is valid
17215   if (SrcSz == 32 && Subtarget->hasFP16())
17216     return Op;
17217 
17218   // Lib call from 32 -> 16 / 64 -> [32, 16]
17219   RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
17220   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
17221          "Unexpected type for custom-lowering FP_ROUND");
17222   MakeLibCallOptions CallOptions;
17223   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
17224   SDValue Result;
17225   std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
17226                                         Loc, Chain);
17227   return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
17228 }
17229 
17230 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
17231                                  SelectionDAG &DAG) const {
17232   assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
17233   MVT HalfT = MVT::i32;
17234   SDLoc dl(N);
17235   SDValue Hi, Lo, Tmp;
17236 
17237   if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
17238       !isOperationLegalOrCustom(ISD::UADDO, HalfT))
17239     return ;
17240 
17241   unsigned OpTypeBits = HalfT.getScalarSizeInBits();
17242   SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
17243 
17244   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
17245                    DAG.getConstant(0, dl, HalfT));
17246   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
17247                    DAG.getConstant(1, dl, HalfT));
17248 
17249   Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
17250                     DAG.getConstant(OpTypeBits - 1, dl,
17251                     getShiftAmountTy(HalfT, DAG.getDataLayout())));
17252   Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
17253   Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
17254                    SDValue(Lo.getNode(), 1));
17255   Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
17256   Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
17257 
17258   Results.push_back(Lo);
17259   Results.push_back(Hi);
17260 }
17261 
17262 bool
17263 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
17264   // The ARM target isn't yet aware of offsets.
17265   return false;
17266 }
17267 
17268 bool ARM::isBitFieldInvertedMask(unsigned v) {
17269   if (v == 0xffffffff)
17270     return false;
17271 
17272   // there can be 1's on either or both "outsides", all the "inside"
17273   // bits must be 0's
17274   return isShiftedMask_32(~v);
17275 }
17276 
17277 /// isFPImmLegal - Returns true if the target can instruction select the
17278 /// specified FP immediate natively. If false, the legalizer will
17279 /// materialize the FP immediate as a load from a constant pool.
17280 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
17281                                      bool ForCodeSize) const {
17282   if (!Subtarget->hasVFP3Base())
17283     return false;
17284   if (VT == MVT::f16 && Subtarget->hasFullFP16())
17285     return ARM_AM::getFP16Imm(Imm) != -1;
17286   if (VT == MVT::f32)
17287     return ARM_AM::getFP32Imm(Imm) != -1;
17288   if (VT == MVT::f64 && Subtarget->hasFP64())
17289     return ARM_AM::getFP64Imm(Imm) != -1;
17290   return false;
17291 }
17292 
17293 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
17294 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
17295 /// specified in the intrinsic calls.
17296 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
17297                                            const CallInst &I,
17298                                            MachineFunction &MF,
17299                                            unsigned Intrinsic) const {
17300   switch (Intrinsic) {
17301   case Intrinsic::arm_neon_vld1:
17302   case Intrinsic::arm_neon_vld2:
17303   case Intrinsic::arm_neon_vld3:
17304   case Intrinsic::arm_neon_vld4:
17305   case Intrinsic::arm_neon_vld2lane:
17306   case Intrinsic::arm_neon_vld3lane:
17307   case Intrinsic::arm_neon_vld4lane:
17308   case Intrinsic::arm_neon_vld2dup:
17309   case Intrinsic::arm_neon_vld3dup:
17310   case Intrinsic::arm_neon_vld4dup: {
17311     Info.opc = ISD::INTRINSIC_W_CHAIN;
17312     // Conservatively set memVT to the entire set of vectors loaded.
17313     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17314     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
17315     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
17316     Info.ptrVal = I.getArgOperand(0);
17317     Info.offset = 0;
17318     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
17319     Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
17320     // volatile loads with NEON intrinsics not supported
17321     Info.flags = MachineMemOperand::MOLoad;
17322     return true;
17323   }
17324   case Intrinsic::arm_neon_vld1x2:
17325   case Intrinsic::arm_neon_vld1x3:
17326   case Intrinsic::arm_neon_vld1x4: {
17327     Info.opc = ISD::INTRINSIC_W_CHAIN;
17328     // Conservatively set memVT to the entire set of vectors loaded.
17329     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17330     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
17331     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
17332     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
17333     Info.offset = 0;
17334     Info.align.reset();
17335     // volatile loads with NEON intrinsics not supported
17336     Info.flags = MachineMemOperand::MOLoad;
17337     return true;
17338   }
17339   case Intrinsic::arm_neon_vst1:
17340   case Intrinsic::arm_neon_vst2:
17341   case Intrinsic::arm_neon_vst3:
17342   case Intrinsic::arm_neon_vst4:
17343   case Intrinsic::arm_neon_vst2lane:
17344   case Intrinsic::arm_neon_vst3lane:
17345   case Intrinsic::arm_neon_vst4lane: {
17346     Info.opc = ISD::INTRINSIC_VOID;
17347     // Conservatively set memVT to the entire set of vectors stored.
17348     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17349     unsigned NumElts = 0;
17350     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
17351       Type *ArgTy = I.getArgOperand(ArgI)->getType();
17352       if (!ArgTy->isVectorTy())
17353         break;
17354       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
17355     }
17356     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
17357     Info.ptrVal = I.getArgOperand(0);
17358     Info.offset = 0;
17359     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
17360     Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
17361     // volatile stores with NEON intrinsics not supported
17362     Info.flags = MachineMemOperand::MOStore;
17363     return true;
17364   }
17365   case Intrinsic::arm_neon_vst1x2:
17366   case Intrinsic::arm_neon_vst1x3:
17367   case Intrinsic::arm_neon_vst1x4: {
17368     Info.opc = ISD::INTRINSIC_VOID;
17369     // Conservatively set memVT to the entire set of vectors stored.
17370     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17371     unsigned NumElts = 0;
17372     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
17373       Type *ArgTy = I.getArgOperand(ArgI)->getType();
17374       if (!ArgTy->isVectorTy())
17375         break;
17376       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
17377     }
17378     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
17379     Info.ptrVal = I.getArgOperand(0);
17380     Info.offset = 0;
17381     Info.align.reset();
17382     // volatile stores with NEON intrinsics not supported
17383     Info.flags = MachineMemOperand::MOStore;
17384     return true;
17385   }
17386   case Intrinsic::arm_mve_vld2q:
17387   case Intrinsic::arm_mve_vld4q: {
17388     Info.opc = ISD::INTRINSIC_W_CHAIN;
17389     // Conservatively set memVT to the entire set of vectors loaded.
17390     Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
17391     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
17392     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
17393     Info.ptrVal = I.getArgOperand(0);
17394     Info.offset = 0;
17395     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
17396     // volatile loads with MVE intrinsics not supported
17397     Info.flags = MachineMemOperand::MOLoad;
17398     return true;
17399   }
17400   case Intrinsic::arm_mve_vst2q:
17401   case Intrinsic::arm_mve_vst4q: {
17402     Info.opc = ISD::INTRINSIC_VOID;
17403     // Conservatively set memVT to the entire set of vectors stored.
17404     Type *VecTy = I.getArgOperand(1)->getType();
17405     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
17406     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
17407     Info.ptrVal = I.getArgOperand(0);
17408     Info.offset = 0;
17409     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
17410     // volatile stores with MVE intrinsics not supported
17411     Info.flags = MachineMemOperand::MOStore;
17412     return true;
17413   }
17414   case Intrinsic::arm_ldaex:
17415   case Intrinsic::arm_ldrex: {
17416     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17417     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
17418     Info.opc = ISD::INTRINSIC_W_CHAIN;
17419     Info.memVT = MVT::getVT(PtrTy->getElementType());
17420     Info.ptrVal = I.getArgOperand(0);
17421     Info.offset = 0;
17422     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
17423     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
17424     return true;
17425   }
17426   case Intrinsic::arm_stlex:
17427   case Intrinsic::arm_strex: {
17428     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17429     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
17430     Info.opc = ISD::INTRINSIC_W_CHAIN;
17431     Info.memVT = MVT::getVT(PtrTy->getElementType());
17432     Info.ptrVal = I.getArgOperand(1);
17433     Info.offset = 0;
17434     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
17435     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
17436     return true;
17437   }
17438   case Intrinsic::arm_stlexd:
17439   case Intrinsic::arm_strexd:
17440     Info.opc = ISD::INTRINSIC_W_CHAIN;
17441     Info.memVT = MVT::i64;
17442     Info.ptrVal = I.getArgOperand(2);
17443     Info.offset = 0;
17444     Info.align = Align(8);
17445     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
17446     return true;
17447 
17448   case Intrinsic::arm_ldaexd:
17449   case Intrinsic::arm_ldrexd:
17450     Info.opc = ISD::INTRINSIC_W_CHAIN;
17451     Info.memVT = MVT::i64;
17452     Info.ptrVal = I.getArgOperand(0);
17453     Info.offset = 0;
17454     Info.align = Align(8);
17455     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
17456     return true;
17457 
17458   default:
17459     break;
17460   }
17461 
17462   return false;
17463 }
17464 
17465 /// Returns true if it is beneficial to convert a load of a constant
17466 /// to just the constant itself.
17467 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
17468                                                           Type *Ty) const {
17469   assert(Ty->isIntegerTy());
17470 
17471   unsigned Bits = Ty->getPrimitiveSizeInBits();
17472   if (Bits == 0 || Bits > 32)
17473     return false;
17474   return true;
17475 }
17476 
17477 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
17478                                                 unsigned Index) const {
17479   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
17480     return false;
17481 
17482   return (Index == 0 || Index == ResVT.getVectorNumElements());
17483 }
17484 
17485 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
17486                                         ARM_MB::MemBOpt Domain) const {
17487   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17488 
17489   // First, if the target has no DMB, see what fallback we can use.
17490   if (!Subtarget->hasDataBarrier()) {
17491     // Some ARMv6 cpus can support data barriers with an mcr instruction.
17492     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
17493     // here.
17494     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
17495       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
17496       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
17497                         Builder.getInt32(0), Builder.getInt32(7),
17498                         Builder.getInt32(10), Builder.getInt32(5)};
17499       return Builder.CreateCall(MCR, args);
17500     } else {
17501       // Instead of using barriers, atomic accesses on these subtargets use
17502       // libcalls.
17503       llvm_unreachable("makeDMB on a target so old that it has no barriers");
17504     }
17505   } else {
17506     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
17507     // Only a full system barrier exists in the M-class architectures.
17508     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
17509     Constant *CDomain = Builder.getInt32(Domain);
17510     return Builder.CreateCall(DMB, CDomain);
17511   }
17512 }
17513 
17514 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
17515 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
17516                                                  Instruction *Inst,
17517                                                  AtomicOrdering Ord) const {
17518   switch (Ord) {
17519   case AtomicOrdering::NotAtomic:
17520   case AtomicOrdering::Unordered:
17521     llvm_unreachable("Invalid fence: unordered/non-atomic");
17522   case AtomicOrdering::Monotonic:
17523   case AtomicOrdering::Acquire:
17524     return nullptr; // Nothing to do
17525   case AtomicOrdering::SequentiallyConsistent:
17526     if (!Inst->hasAtomicStore())
17527       return nullptr; // Nothing to do
17528     LLVM_FALLTHROUGH;
17529   case AtomicOrdering::Release:
17530   case AtomicOrdering::AcquireRelease:
17531     if (Subtarget->preferISHSTBarriers())
17532       return makeDMB(Builder, ARM_MB::ISHST);
17533     // FIXME: add a comment with a link to documentation justifying this.
17534     else
17535       return makeDMB(Builder, ARM_MB::ISH);
17536   }
17537   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
17538 }
17539 
17540 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
17541                                                   Instruction *Inst,
17542                                                   AtomicOrdering Ord) const {
17543   switch (Ord) {
17544   case AtomicOrdering::NotAtomic:
17545   case AtomicOrdering::Unordered:
17546     llvm_unreachable("Invalid fence: unordered/not-atomic");
17547   case AtomicOrdering::Monotonic:
17548   case AtomicOrdering::Release:
17549     return nullptr; // Nothing to do
17550   case AtomicOrdering::Acquire:
17551   case AtomicOrdering::AcquireRelease:
17552   case AtomicOrdering::SequentiallyConsistent:
17553     return makeDMB(Builder, ARM_MB::ISH);
17554   }
17555   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
17556 }
17557 
17558 // Loads and stores less than 64-bits are already atomic; ones above that
17559 // are doomed anyway, so defer to the default libcall and blame the OS when
17560 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
17561 // anything for those.
17562 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17563   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
17564   return (Size == 64) && !Subtarget->isMClass();
17565 }
17566 
17567 // Loads and stores less than 64-bits are already atomic; ones above that
17568 // are doomed anyway, so defer to the default libcall and blame the OS when
17569 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
17570 // anything for those.
17571 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
17572 // guarantee, see DDI0406C ARM architecture reference manual,
17573 // sections A8.8.72-74 LDRD)
17574 TargetLowering::AtomicExpansionKind
17575 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17576   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
17577   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
17578                                                   : AtomicExpansionKind::None;
17579 }
17580 
17581 // For the real atomic operations, we have ldrex/strex up to 32 bits,
17582 // and up to 64 bits on the non-M profiles
17583 TargetLowering::AtomicExpansionKind
17584 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17585   if (AI->isFloatingPointOperation())
17586     return AtomicExpansionKind::CmpXChg;
17587 
17588   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
17589   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
17590   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
17591              ? AtomicExpansionKind::LLSC
17592              : AtomicExpansionKind::None;
17593 }
17594 
17595 TargetLowering::AtomicExpansionKind
17596 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
17597   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
17598   // implement cmpxchg without spilling. If the address being exchanged is also
17599   // on the stack and close enough to the spill slot, this can lead to a
17600   // situation where the monitor always gets cleared and the atomic operation
17601   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
17602   bool HasAtomicCmpXchg =
17603       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
17604   if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
17605     return AtomicExpansionKind::LLSC;
17606   return AtomicExpansionKind::None;
17607 }
17608 
17609 bool ARMTargetLowering::shouldInsertFencesForAtomic(
17610     const Instruction *I) const {
17611   return InsertFencesForAtomic;
17612 }
17613 
17614 // This has so far only been implemented for MachO.
17615 bool ARMTargetLowering::useLoadStackGuardNode() const {
17616   return Subtarget->isTargetMachO();
17617 }
17618 
17619 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
17620   if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
17621     return TargetLowering::insertSSPDeclarations(M);
17622 
17623   // MSVC CRT has a global variable holding security cookie.
17624   M.getOrInsertGlobal("__security_cookie",
17625                       Type::getInt8PtrTy(M.getContext()));
17626 
17627   // MSVC CRT has a function to validate security cookie.
17628   FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
17629       "__security_check_cookie", Type::getVoidTy(M.getContext()),
17630       Type::getInt8PtrTy(M.getContext()));
17631   if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
17632     F->addAttribute(1, Attribute::AttrKind::InReg);
17633 }
17634 
17635 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
17636   // MSVC CRT has a global variable holding security cookie.
17637   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
17638     return M.getGlobalVariable("__security_cookie");
17639   return TargetLowering::getSDagStackGuard(M);
17640 }
17641 
17642 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
17643   // MSVC CRT has a function to validate security cookie.
17644   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
17645     return M.getFunction("__security_check_cookie");
17646   return TargetLowering::getSSPStackGuardCheck(M);
17647 }
17648 
17649 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
17650                                                   unsigned &Cost) const {
17651   // If we do not have NEON, vector types are not natively supported.
17652   if (!Subtarget->hasNEON())
17653     return false;
17654 
17655   // Floating point values and vector values map to the same register file.
17656   // Therefore, although we could do a store extract of a vector type, this is
17657   // better to leave at float as we have more freedom in the addressing mode for
17658   // those.
17659   if (VectorTy->isFPOrFPVectorTy())
17660     return false;
17661 
17662   // If the index is unknown at compile time, this is very expensive to lower
17663   // and it is not possible to combine the store with the extract.
17664   if (!isa<ConstantInt>(Idx))
17665     return false;
17666 
17667   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
17668   unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize();
17669   // We can do a store + vector extract on any vector that fits perfectly in a D
17670   // or Q register.
17671   if (BitWidth == 64 || BitWidth == 128) {
17672     Cost = 0;
17673     return true;
17674   }
17675   return false;
17676 }
17677 
17678 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
17679   return Subtarget->hasV6T2Ops();
17680 }
17681 
17682 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
17683   return Subtarget->hasV6T2Ops();
17684 }
17685 
17686 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
17687   return !Subtarget->hasMinSize() || Subtarget->isTargetWindows();
17688 }
17689 
17690 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
17691                                          AtomicOrdering Ord) const {
17692   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17693   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
17694   bool IsAcquire = isAcquireOrStronger(Ord);
17695 
17696   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
17697   // intrinsic must return {i32, i32} and we have to recombine them into a
17698   // single i64 here.
17699   if (ValTy->getPrimitiveSizeInBits() == 64) {
17700     Intrinsic::ID Int =
17701         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
17702     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
17703 
17704     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
17705     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
17706 
17707     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17708     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17709     if (!Subtarget->isLittle())
17710       std::swap (Lo, Hi);
17711     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
17712     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
17713     return Builder.CreateOr(
17714         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
17715   }
17716 
17717   Type *Tys[] = { Addr->getType() };
17718   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
17719   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
17720 
17721   return Builder.CreateTruncOrBitCast(
17722       Builder.CreateCall(Ldrex, Addr),
17723       cast<PointerType>(Addr->getType())->getElementType());
17724 }
17725 
17726 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
17727     IRBuilder<> &Builder) const {
17728   if (!Subtarget->hasV7Ops())
17729     return;
17730   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17731   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
17732 }
17733 
17734 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
17735                                                Value *Addr,
17736                                                AtomicOrdering Ord) const {
17737   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17738   bool IsRelease = isReleaseOrStronger(Ord);
17739 
17740   // Since the intrinsics must have legal type, the i64 intrinsics take two
17741   // parameters: "i32, i32". We must marshal Val into the appropriate form
17742   // before the call.
17743   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
17744     Intrinsic::ID Int =
17745         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
17746     Function *Strex = Intrinsic::getDeclaration(M, Int);
17747     Type *Int32Ty = Type::getInt32Ty(M->getContext());
17748 
17749     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
17750     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
17751     if (!Subtarget->isLittle())
17752       std::swap(Lo, Hi);
17753     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
17754     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
17755   }
17756 
17757   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
17758   Type *Tys[] = { Addr->getType() };
17759   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
17760 
17761   return Builder.CreateCall(
17762       Strex, {Builder.CreateZExtOrBitCast(
17763                   Val, Strex->getFunctionType()->getParamType(0)),
17764               Addr});
17765 }
17766 
17767 
17768 bool ARMTargetLowering::alignLoopsWithOptSize() const {
17769   return Subtarget->isMClass();
17770 }
17771 
17772 /// A helper function for determining the number of interleaved accesses we
17773 /// will generate when lowering accesses of the given type.
17774 unsigned
17775 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
17776                                              const DataLayout &DL) const {
17777   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
17778 }
17779 
17780 bool ARMTargetLowering::isLegalInterleavedAccessType(
17781     unsigned Factor, VectorType *VecTy, const DataLayout &DL) const {
17782 
17783   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
17784   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
17785 
17786   if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
17787     return false;
17788 
17789   // Ensure the vector doesn't have f16 elements. Even though we could do an
17790   // i16 vldN, we can't hold the f16 vectors and will end up converting via
17791   // f32.
17792   if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
17793     return false;
17794   if (Subtarget->hasMVEIntegerOps() && Factor == 3)
17795     return false;
17796 
17797   // Ensure the number of vector elements is greater than 1.
17798   if (VecTy->getNumElements() < 2)
17799     return false;
17800 
17801   // Ensure the element type is legal.
17802   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
17803     return false;
17804 
17805   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
17806   // 128 will be split into multiple interleaved accesses.
17807   if (Subtarget->hasNEON() && VecSize == 64)
17808     return true;
17809   return VecSize % 128 == 0;
17810 }
17811 
17812 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
17813   if (Subtarget->hasNEON())
17814     return 4;
17815   if (Subtarget->hasMVEIntegerOps())
17816     return MVEMaxSupportedInterleaveFactor;
17817   return TargetLoweringBase::getMaxSupportedInterleaveFactor();
17818 }
17819 
17820 /// Lower an interleaved load into a vldN intrinsic.
17821 ///
17822 /// E.g. Lower an interleaved load (Factor = 2):
17823 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
17824 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
17825 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
17826 ///
17827 ///      Into:
17828 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
17829 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
17830 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
17831 bool ARMTargetLowering::lowerInterleavedLoad(
17832     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
17833     ArrayRef<unsigned> Indices, unsigned Factor) const {
17834   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
17835          "Invalid interleave factor");
17836   assert(!Shuffles.empty() && "Empty shufflevector input");
17837   assert(Shuffles.size() == Indices.size() &&
17838          "Unmatched number of shufflevectors and indices");
17839 
17840   VectorType *VecTy = Shuffles[0]->getType();
17841   Type *EltTy = VecTy->getElementType();
17842 
17843   const DataLayout &DL = LI->getModule()->getDataLayout();
17844 
17845   // Skip if we do not have NEON and skip illegal vector types. We can
17846   // "legalize" wide vector types into multiple interleaved accesses as long as
17847   // the vector types are divisible by 128.
17848   if (!isLegalInterleavedAccessType(Factor, VecTy, DL))
17849     return false;
17850 
17851   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
17852 
17853   // A pointer vector can not be the return type of the ldN intrinsics. Need to
17854   // load integer vectors first and then convert to pointer vectors.
17855   if (EltTy->isPointerTy())
17856     VecTy = VectorType::get(DL.getIntPtrType(EltTy), VecTy->getNumElements());
17857 
17858   IRBuilder<> Builder(LI);
17859 
17860   // The base address of the load.
17861   Value *BaseAddr = LI->getPointerOperand();
17862 
17863   if (NumLoads > 1) {
17864     // If we're going to generate more than one load, reset the sub-vector type
17865     // to something legal.
17866     VecTy = VectorType::get(VecTy->getElementType(),
17867                             VecTy->getNumElements() / NumLoads);
17868 
17869     // We will compute the pointer operand of each load from the original base
17870     // address using GEPs. Cast the base address to a pointer to the scalar
17871     // element type.
17872     BaseAddr = Builder.CreateBitCast(
17873         BaseAddr,
17874         VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
17875   }
17876 
17877   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
17878 
17879   auto createLoadIntrinsic = [&](Value *BaseAddr) {
17880     if (Subtarget->hasNEON()) {
17881       Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
17882       Type *Tys[] = {VecTy, Int8Ptr};
17883       static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
17884                                                 Intrinsic::arm_neon_vld3,
17885                                                 Intrinsic::arm_neon_vld4};
17886       Function *VldnFunc =
17887           Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
17888 
17889       SmallVector<Value *, 2> Ops;
17890       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
17891       Ops.push_back(Builder.getInt32(LI->getAlignment()));
17892 
17893       return Builder.CreateCall(VldnFunc, Ops, "vldN");
17894     } else {
17895       assert((Factor == 2 || Factor == 4) &&
17896              "expected interleave factor of 2 or 4 for MVE");
17897       Intrinsic::ID LoadInts =
17898           Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
17899       Type *VecEltTy =
17900           VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace());
17901       Type *Tys[] = {VecTy, VecEltTy};
17902       Function *VldnFunc =
17903           Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys);
17904 
17905       SmallVector<Value *, 2> Ops;
17906       Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy));
17907       return Builder.CreateCall(VldnFunc, Ops, "vldN");
17908     }
17909   };
17910 
17911   // Holds sub-vectors extracted from the load intrinsic return values. The
17912   // sub-vectors are associated with the shufflevector instructions they will
17913   // replace.
17914   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
17915 
17916   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
17917     // If we're generating more than one load, compute the base address of
17918     // subsequent loads as an offset from the previous.
17919     if (LoadCount > 0)
17920       BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
17921                                             VecTy->getNumElements() * Factor);
17922 
17923     CallInst *VldN = createLoadIntrinsic(BaseAddr);
17924 
17925     // Replace uses of each shufflevector with the corresponding vector loaded
17926     // by ldN.
17927     for (unsigned i = 0; i < Shuffles.size(); i++) {
17928       ShuffleVectorInst *SV = Shuffles[i];
17929       unsigned Index = Indices[i];
17930 
17931       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
17932 
17933       // Convert the integer vector to pointer vector if the element is pointer.
17934       if (EltTy->isPointerTy())
17935         SubVec = Builder.CreateIntToPtr(
17936             SubVec, VectorType::get(SV->getType()->getElementType(),
17937                                     VecTy->getNumElements()));
17938 
17939       SubVecs[SV].push_back(SubVec);
17940     }
17941   }
17942 
17943   // Replace uses of the shufflevector instructions with the sub-vectors
17944   // returned by the load intrinsic. If a shufflevector instruction is
17945   // associated with more than one sub-vector, those sub-vectors will be
17946   // concatenated into a single wide vector.
17947   for (ShuffleVectorInst *SVI : Shuffles) {
17948     auto &SubVec = SubVecs[SVI];
17949     auto *WideVec =
17950         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
17951     SVI->replaceAllUsesWith(WideVec);
17952   }
17953 
17954   return true;
17955 }
17956 
17957 /// Lower an interleaved store into a vstN intrinsic.
17958 ///
17959 /// E.g. Lower an interleaved store (Factor = 3):
17960 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
17961 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
17962 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
17963 ///
17964 ///      Into:
17965 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
17966 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
17967 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
17968 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
17969 ///
17970 /// Note that the new shufflevectors will be removed and we'll only generate one
17971 /// vst3 instruction in CodeGen.
17972 ///
17973 /// Example for a more general valid mask (Factor 3). Lower:
17974 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
17975 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
17976 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
17977 ///
17978 ///      Into:
17979 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
17980 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
17981 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
17982 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
17983 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
17984                                               ShuffleVectorInst *SVI,
17985                                               unsigned Factor) const {
17986   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
17987          "Invalid interleave factor");
17988 
17989   VectorType *VecTy = SVI->getType();
17990   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
17991 
17992   unsigned LaneLen = VecTy->getNumElements() / Factor;
17993   Type *EltTy = VecTy->getElementType();
17994   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
17995 
17996   const DataLayout &DL = SI->getModule()->getDataLayout();
17997 
17998   // Skip if we do not have NEON and skip illegal vector types. We can
17999   // "legalize" wide vector types into multiple interleaved accesses as long as
18000   // the vector types are divisible by 128.
18001   if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL))
18002     return false;
18003 
18004   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
18005 
18006   Value *Op0 = SVI->getOperand(0);
18007   Value *Op1 = SVI->getOperand(1);
18008   IRBuilder<> Builder(SI);
18009 
18010   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
18011   // vectors to integer vectors.
18012   if (EltTy->isPointerTy()) {
18013     Type *IntTy = DL.getIntPtrType(EltTy);
18014 
18015     // Convert to the corresponding integer vector.
18016     Type *IntVecTy = VectorType::get(
18017         IntTy, cast<VectorType>(Op0->getType())->getNumElements());
18018     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
18019     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
18020 
18021     SubVecTy = VectorType::get(IntTy, LaneLen);
18022   }
18023 
18024   // The base address of the store.
18025   Value *BaseAddr = SI->getPointerOperand();
18026 
18027   if (NumStores > 1) {
18028     // If we're going to generate more than one store, reset the lane length
18029     // and sub-vector type to something legal.
18030     LaneLen /= NumStores;
18031     SubVecTy = VectorType::get(SubVecTy->getElementType(), LaneLen);
18032 
18033     // We will compute the pointer operand of each store from the original base
18034     // address using GEPs. Cast the base address to a pointer to the scalar
18035     // element type.
18036     BaseAddr = Builder.CreateBitCast(
18037         BaseAddr,
18038         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
18039   }
18040 
18041   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
18042 
18043   auto Mask = SVI->getShuffleMask();
18044 
18045   auto createStoreIntrinsic = [&](Value *BaseAddr,
18046                                   SmallVectorImpl<Value *> &Shuffles) {
18047     if (Subtarget->hasNEON()) {
18048       static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
18049                                                  Intrinsic::arm_neon_vst3,
18050                                                  Intrinsic::arm_neon_vst4};
18051       Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
18052       Type *Tys[] = {Int8Ptr, SubVecTy};
18053 
18054       Function *VstNFunc = Intrinsic::getDeclaration(
18055           SI->getModule(), StoreInts[Factor - 2], Tys);
18056 
18057       SmallVector<Value *, 6> Ops;
18058       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
18059       for (auto S : Shuffles)
18060         Ops.push_back(S);
18061       Ops.push_back(Builder.getInt32(SI->getAlignment()));
18062       Builder.CreateCall(VstNFunc, Ops);
18063     } else {
18064       assert((Factor == 2 || Factor == 4) &&
18065              "expected interleave factor of 2 or 4 for MVE");
18066       Intrinsic::ID StoreInts =
18067           Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
18068       Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo(
18069           SI->getPointerAddressSpace());
18070       Type *Tys[] = {EltPtrTy, SubVecTy};
18071       Function *VstNFunc =
18072           Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys);
18073 
18074       SmallVector<Value *, 6> Ops;
18075       Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy));
18076       for (auto S : Shuffles)
18077         Ops.push_back(S);
18078       for (unsigned F = 0; F < Factor; F++) {
18079         Ops.push_back(Builder.getInt32(F));
18080         Builder.CreateCall(VstNFunc, Ops);
18081         Ops.pop_back();
18082       }
18083     }
18084   };
18085 
18086   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
18087     // If we generating more than one store, we compute the base address of
18088     // subsequent stores as an offset from the previous.
18089     if (StoreCount > 0)
18090       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
18091                                             BaseAddr, LaneLen * Factor);
18092 
18093     SmallVector<Value *, 4> Shuffles;
18094 
18095     // Split the shufflevector operands into sub vectors for the new vstN call.
18096     for (unsigned i = 0; i < Factor; i++) {
18097       unsigned IdxI = StoreCount * LaneLen * Factor + i;
18098       if (Mask[IdxI] >= 0) {
18099         Shuffles.push_back(Builder.CreateShuffleVector(
18100             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
18101       } else {
18102         unsigned StartMask = 0;
18103         for (unsigned j = 1; j < LaneLen; j++) {
18104           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
18105           if (Mask[IdxJ * Factor + IdxI] >= 0) {
18106             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
18107             break;
18108           }
18109         }
18110         // Note: If all elements in a chunk are undefs, StartMask=0!
18111         // Note: Filling undef gaps with random elements is ok, since
18112         // those elements were being written anyway (with undefs).
18113         // In the case of all undefs we're defaulting to using elems from 0
18114         // Note: StartMask cannot be negative, it's checked in
18115         // isReInterleaveMask
18116         Shuffles.push_back(Builder.CreateShuffleVector(
18117             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
18118       }
18119     }
18120 
18121     createStoreIntrinsic(BaseAddr, Shuffles);
18122   }
18123   return true;
18124 }
18125 
18126 enum HABaseType {
18127   HA_UNKNOWN = 0,
18128   HA_FLOAT,
18129   HA_DOUBLE,
18130   HA_VECT64,
18131   HA_VECT128
18132 };
18133 
18134 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
18135                                    uint64_t &Members) {
18136   if (auto *ST = dyn_cast<StructType>(Ty)) {
18137     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
18138       uint64_t SubMembers = 0;
18139       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
18140         return false;
18141       Members += SubMembers;
18142     }
18143   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
18144     uint64_t SubMembers = 0;
18145     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
18146       return false;
18147     Members += SubMembers * AT->getNumElements();
18148   } else if (Ty->isFloatTy()) {
18149     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
18150       return false;
18151     Members = 1;
18152     Base = HA_FLOAT;
18153   } else if (Ty->isDoubleTy()) {
18154     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
18155       return false;
18156     Members = 1;
18157     Base = HA_DOUBLE;
18158   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
18159     Members = 1;
18160     switch (Base) {
18161     case HA_FLOAT:
18162     case HA_DOUBLE:
18163       return false;
18164     case HA_VECT64:
18165       return VT->getPrimitiveSizeInBits().getFixedSize() == 64;
18166     case HA_VECT128:
18167       return VT->getPrimitiveSizeInBits().getFixedSize() == 128;
18168     case HA_UNKNOWN:
18169       switch (VT->getPrimitiveSizeInBits().getFixedSize()) {
18170       case 64:
18171         Base = HA_VECT64;
18172         return true;
18173       case 128:
18174         Base = HA_VECT128;
18175         return true;
18176       default:
18177         return false;
18178       }
18179     }
18180   }
18181 
18182   return (Members > 0 && Members <= 4);
18183 }
18184 
18185 /// Return the correct alignment for the current calling convention.
18186 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
18187                                                        DataLayout DL) const {
18188   const Align ABITypeAlign(DL.getABITypeAlignment(ArgTy));
18189   if (!ArgTy->isVectorTy())
18190     return ABITypeAlign;
18191 
18192   // Avoid over-aligning vector parameters. It would require realigning the
18193   // stack and waste space for no real benefit.
18194   return std::min(ABITypeAlign, DL.getStackAlignment());
18195 }
18196 
18197 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
18198 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
18199 /// passing according to AAPCS rules.
18200 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
18201     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
18202   if (getEffectiveCallingConv(CallConv, isVarArg) !=
18203       CallingConv::ARM_AAPCS_VFP)
18204     return false;
18205 
18206   HABaseType Base = HA_UNKNOWN;
18207   uint64_t Members = 0;
18208   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
18209   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
18210 
18211   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
18212   return IsHA || IsIntArray;
18213 }
18214 
18215 Register ARMTargetLowering::getExceptionPointerRegister(
18216     const Constant *PersonalityFn) const {
18217   // Platforms which do not use SjLj EH may return values in these registers
18218   // via the personality function.
18219   return Subtarget->useSjLjEH() ? Register() : ARM::R0;
18220 }
18221 
18222 Register ARMTargetLowering::getExceptionSelectorRegister(
18223     const Constant *PersonalityFn) const {
18224   // Platforms which do not use SjLj EH may return values in these registers
18225   // via the personality function.
18226   return Subtarget->useSjLjEH() ? Register() : ARM::R1;
18227 }
18228 
18229 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
18230   // Update IsSplitCSR in ARMFunctionInfo.
18231   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
18232   AFI->setIsSplitCSR(true);
18233 }
18234 
18235 void ARMTargetLowering::insertCopiesSplitCSR(
18236     MachineBasicBlock *Entry,
18237     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
18238   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
18239   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
18240   if (!IStart)
18241     return;
18242 
18243   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18244   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
18245   MachineBasicBlock::iterator MBBI = Entry->begin();
18246   for (const MCPhysReg *I = IStart; *I; ++I) {
18247     const TargetRegisterClass *RC = nullptr;
18248     if (ARM::GPRRegClass.contains(*I))
18249       RC = &ARM::GPRRegClass;
18250     else if (ARM::DPRRegClass.contains(*I))
18251       RC = &ARM::DPRRegClass;
18252     else
18253       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
18254 
18255     Register NewVR = MRI->createVirtualRegister(RC);
18256     // Create copy from CSR to a virtual register.
18257     // FIXME: this currently does not emit CFI pseudo-instructions, it works
18258     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
18259     // nounwind. If we want to generalize this later, we may need to emit
18260     // CFI pseudo-instructions.
18261     assert(Entry->getParent()->getFunction().hasFnAttribute(
18262                Attribute::NoUnwind) &&
18263            "Function should be nounwind in insertCopiesSplitCSR!");
18264     Entry->addLiveIn(*I);
18265     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
18266         .addReg(*I);
18267 
18268     // Insert the copy-back instructions right before the terminator.
18269     for (auto *Exit : Exits)
18270       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
18271               TII->get(TargetOpcode::COPY), *I)
18272           .addReg(NewVR);
18273   }
18274 }
18275 
18276 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
18277   MF.getFrameInfo().computeMaxCallFrameSize(MF);
18278   TargetLoweringBase::finalizeLowering(MF);
18279 }
18280