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::STORE);
938     setTargetDAGCombine(ISD::SIGN_EXTEND);
939     setTargetDAGCombine(ISD::ZERO_EXTEND);
940     setTargetDAGCombine(ISD::ANY_EXTEND);
941     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
942     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
943     setTargetDAGCombine(ISD::INTRINSIC_VOID);
944     setTargetDAGCombine(ISD::VECREDUCE_ADD);
945     setTargetDAGCombine(ISD::ADD);
946     setTargetDAGCombine(ISD::BITCAST);
947   }
948 
949   if (!Subtarget->hasFP64()) {
950     // When targeting a floating-point unit with only single-precision
951     // operations, f64 is legal for the few double-precision instructions which
952     // are present However, no double-precision operations other than moves,
953     // loads and stores are provided by the hardware.
954     setOperationAction(ISD::FADD,       MVT::f64, Expand);
955     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
956     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
957     setOperationAction(ISD::FMA,        MVT::f64, Expand);
958     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
959     setOperationAction(ISD::FREM,       MVT::f64, Expand);
960     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
961     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
962     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
963     setOperationAction(ISD::FABS,       MVT::f64, Expand);
964     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
965     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
966     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
967     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
968     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
969     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
970     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
971     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
972     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
973     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
974     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
975     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
976     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
977     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
978     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
979     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
980     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
981     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
982     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
983     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
984     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
985     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
986     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
987     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
988     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
989     setOperationAction(ISD::STRICT_FP_ROUND,   MVT::f32, Custom);
990   }
991 
992   if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
993     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
994     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
995     if (Subtarget->hasFullFP16()) {
996       setOperationAction(ISD::FP_ROUND,  MVT::f16, Custom);
997       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
998     }
999   }
1000 
1001   if (!Subtarget->hasFP16()) {
1002     setOperationAction(ISD::FP_EXTEND,  MVT::f32, Custom);
1003     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1004   }
1005 
1006   computeRegisterProperties(Subtarget->getRegisterInfo());
1007 
1008   // ARM does not have floating-point extending loads.
1009   for (MVT VT : MVT::fp_valuetypes()) {
1010     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1011     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1012   }
1013 
1014   // ... or truncating stores
1015   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1016   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1017   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1018 
1019   // ARM does not have i1 sign extending load.
1020   for (MVT VT : MVT::integer_valuetypes())
1021     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1022 
1023   // ARM supports all 4 flavors of integer indexed load / store.
1024   if (!Subtarget->isThumb1Only()) {
1025     for (unsigned im = (unsigned)ISD::PRE_INC;
1026          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1027       setIndexedLoadAction(im,  MVT::i1,  Legal);
1028       setIndexedLoadAction(im,  MVT::i8,  Legal);
1029       setIndexedLoadAction(im,  MVT::i16, Legal);
1030       setIndexedLoadAction(im,  MVT::i32, Legal);
1031       setIndexedStoreAction(im, MVT::i1,  Legal);
1032       setIndexedStoreAction(im, MVT::i8,  Legal);
1033       setIndexedStoreAction(im, MVT::i16, Legal);
1034       setIndexedStoreAction(im, MVT::i32, Legal);
1035     }
1036   } else {
1037     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1038     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
1039     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
1040   }
1041 
1042   setOperationAction(ISD::SADDO, MVT::i32, Custom);
1043   setOperationAction(ISD::UADDO, MVT::i32, Custom);
1044   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1045   setOperationAction(ISD::USUBO, MVT::i32, Custom);
1046 
1047   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1048   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1049   if (Subtarget->hasDSP()) {
1050     setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1051     setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1052     setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1053     setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1054   }
1055   if (Subtarget->hasBaseDSP()) {
1056     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1057     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1058   }
1059 
1060   // i64 operation support.
1061   setOperationAction(ISD::MUL,     MVT::i64, Expand);
1062   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
1063   if (Subtarget->isThumb1Only()) {
1064     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1065     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1066   }
1067   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1068       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1069     setOperationAction(ISD::MULHS, MVT::i32, Expand);
1070 
1071   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1072   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1073   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1074   setOperationAction(ISD::SRL,       MVT::i64, Custom);
1075   setOperationAction(ISD::SRA,       MVT::i64, Custom);
1076   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1077   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1078   setOperationAction(ISD::LOAD, MVT::i64, Custom);
1079   setOperationAction(ISD::STORE, MVT::i64, Custom);
1080 
1081   // MVE lowers 64 bit shifts to lsll and lsrl
1082   // assuming that ISD::SRL and SRA of i64 are already marked custom
1083   if (Subtarget->hasMVEIntegerOps())
1084     setOperationAction(ISD::SHL, MVT::i64, Custom);
1085 
1086   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1087   if (Subtarget->isThumb1Only()) {
1088     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1089     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1090     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1091   }
1092 
1093   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1094     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1095 
1096   // ARM does not have ROTL.
1097   setOperationAction(ISD::ROTL, MVT::i32, Expand);
1098   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1099     setOperationAction(ISD::ROTL, VT, Expand);
1100     setOperationAction(ISD::ROTR, VT, Expand);
1101   }
1102   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
1103   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1104   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1105     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1106     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1107   }
1108 
1109   // @llvm.readcyclecounter requires the Performance Monitors extension.
1110   // Default to the 0 expansion on unsupported platforms.
1111   // FIXME: Technically there are older ARM CPUs that have
1112   // implementation-specific ways of obtaining this information.
1113   if (Subtarget->hasPerfMon())
1114     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1115 
1116   // Only ARMv6 has BSWAP.
1117   if (!Subtarget->hasV6Ops())
1118     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1119 
1120   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1121                                         : Subtarget->hasDivideInARMMode();
1122   if (!hasDivide) {
1123     // These are expanded into libcalls if the cpu doesn't have HW divider.
1124     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
1125     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
1126   }
1127 
1128   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1129     setOperationAction(ISD::SDIV, MVT::i32, Custom);
1130     setOperationAction(ISD::UDIV, MVT::i32, Custom);
1131 
1132     setOperationAction(ISD::SDIV, MVT::i64, Custom);
1133     setOperationAction(ISD::UDIV, MVT::i64, Custom);
1134   }
1135 
1136   setOperationAction(ISD::SREM,  MVT::i32, Expand);
1137   setOperationAction(ISD::UREM,  MVT::i32, Expand);
1138 
1139   // Register based DivRem for AEABI (RTABI 4.2)
1140   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1141       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1142       Subtarget->isTargetWindows()) {
1143     setOperationAction(ISD::SREM, MVT::i64, Custom);
1144     setOperationAction(ISD::UREM, MVT::i64, Custom);
1145     HasStandaloneRem = false;
1146 
1147     if (Subtarget->isTargetWindows()) {
1148       const struct {
1149         const RTLIB::Libcall Op;
1150         const char * const Name;
1151         const CallingConv::ID CC;
1152       } LibraryCalls[] = {
1153         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1154         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1155         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1156         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1157 
1158         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1159         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1160         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1161         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1162       };
1163 
1164       for (const auto &LC : LibraryCalls) {
1165         setLibcallName(LC.Op, LC.Name);
1166         setLibcallCallingConv(LC.Op, LC.CC);
1167       }
1168     } else {
1169       const struct {
1170         const RTLIB::Libcall Op;
1171         const char * const Name;
1172         const CallingConv::ID CC;
1173       } LibraryCalls[] = {
1174         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1175         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1176         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1177         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1178 
1179         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1180         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1181         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1182         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1183       };
1184 
1185       for (const auto &LC : LibraryCalls) {
1186         setLibcallName(LC.Op, LC.Name);
1187         setLibcallCallingConv(LC.Op, LC.CC);
1188       }
1189     }
1190 
1191     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1192     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1193     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1194     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1195   } else {
1196     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1197     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1198   }
1199 
1200   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
1201     // MSVCRT doesn't have powi; fall back to pow
1202     setLibcallName(RTLIB::POWI_F32, nullptr);
1203     setLibcallName(RTLIB::POWI_F64, nullptr);
1204   }
1205 
1206   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
1207   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
1208   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1209   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1210 
1211   setOperationAction(ISD::TRAP, MVT::Other, Legal);
1212   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1213 
1214   // Use the default implementation.
1215   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
1216   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
1217   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
1218   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
1219   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
1220   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
1221 
1222   if (Subtarget->isTargetWindows())
1223     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1224   else
1225     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1226 
1227   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1228   // the default expansion.
1229   InsertFencesForAtomic = false;
1230   if (Subtarget->hasAnyDataBarrier() &&
1231       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1232     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1233     // to ldrex/strex loops already.
1234     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
1235     if (!Subtarget->isThumb() || !Subtarget->isMClass())
1236       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
1237 
1238     // On v8, we have particularly efficient implementations of atomic fences
1239     // if they can be combined with nearby atomic loads and stores.
1240     if (!Subtarget->hasAcquireRelease() ||
1241         getTargetMachine().getOptLevel() == 0) {
1242       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1243       InsertFencesForAtomic = true;
1244     }
1245   } else {
1246     // If there's anything we can use as a barrier, go through custom lowering
1247     // for ATOMIC_FENCE.
1248     // If target has DMB in thumb, Fences can be inserted.
1249     if (Subtarget->hasDataBarrier())
1250       InsertFencesForAtomic = true;
1251 
1252     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1253                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1254 
1255     // Set them all for expansion, which will force libcalls.
1256     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1257     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1258     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1259     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1260     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1261     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1262     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1263     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1264     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1265     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1266     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1267     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1268     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1269     // Unordered/Monotonic case.
1270     if (!InsertFencesForAtomic) {
1271       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1272       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1273     }
1274   }
1275 
1276   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1277 
1278   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1279   if (!Subtarget->hasV6Ops()) {
1280     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1281     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1282   }
1283   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1284 
1285   if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1286       !Subtarget->isThumb1Only()) {
1287     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1288     // iff target supports vfp2.
1289     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1290     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1291   }
1292 
1293   // We want to custom lower some of our intrinsics.
1294   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1295   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1296   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1297   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1298   if (Subtarget->useSjLjEH())
1299     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1300 
1301   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1302   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1303   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1304   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1305   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1306   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1307   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1308   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1309   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1310   if (Subtarget->hasFullFP16()) {
1311     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1312     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1313     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1314   }
1315 
1316   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1317 
1318   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1319   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1320   if (Subtarget->hasFullFP16())
1321       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1322   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1323   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1324   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1325 
1326   // We don't support sin/cos/fmod/copysign/pow
1327   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1328   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1329   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1330   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1331   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1332   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1333   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1334   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1335   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1336       !Subtarget->isThumb1Only()) {
1337     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1338     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1339   }
1340   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1341   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1342 
1343   if (!Subtarget->hasVFP4Base()) {
1344     setOperationAction(ISD::FMA, MVT::f64, Expand);
1345     setOperationAction(ISD::FMA, MVT::f32, Expand);
1346   }
1347 
1348   // Various VFP goodness
1349   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1350     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1351     if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1352       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1353       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1354     }
1355 
1356     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1357     if (!Subtarget->hasFP16()) {
1358       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1359       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1360     }
1361 
1362     // Strict floating-point comparisons need custom lowering.
1363     setOperationAction(ISD::STRICT_FSETCC,  MVT::f16, Custom);
1364     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
1365     setOperationAction(ISD::STRICT_FSETCC,  MVT::f32, Custom);
1366     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
1367     setOperationAction(ISD::STRICT_FSETCC,  MVT::f64, Custom);
1368     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
1369   }
1370 
1371   // Use __sincos_stret if available.
1372   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1373       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1374     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1375     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1376   }
1377 
1378   // FP-ARMv8 implements a lot of rounding-like FP operations.
1379   if (Subtarget->hasFPARMv8Base()) {
1380     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1381     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1382     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1383     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1384     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1385     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1386     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1387     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1388     if (Subtarget->hasNEON()) {
1389       setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1390       setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1391       setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1392       setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1393     }
1394 
1395     if (Subtarget->hasFP64()) {
1396       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1397       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1398       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1399       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1400       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1401       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1402       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1403       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1404     }
1405   }
1406 
1407   // FP16 often need to be promoted to call lib functions
1408   if (Subtarget->hasFullFP16()) {
1409     setOperationAction(ISD::FREM, MVT::f16, Promote);
1410     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1411     setOperationAction(ISD::FSIN, MVT::f16, Promote);
1412     setOperationAction(ISD::FCOS, MVT::f16, Promote);
1413     setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1414     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1415     setOperationAction(ISD::FPOW, MVT::f16, Promote);
1416     setOperationAction(ISD::FEXP, MVT::f16, Promote);
1417     setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1418     setOperationAction(ISD::FLOG, MVT::f16, Promote);
1419     setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1420     setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1421 
1422     setOperationAction(ISD::FROUND, MVT::f16, Legal);
1423   }
1424 
1425   if (Subtarget->hasNEON()) {
1426     // vmin and vmax aren't available in a scalar form, so we can use
1427     // a NEON instruction with an undef lane instead.  This has a performance
1428     // penalty on some cores, so we don't do this unless we have been
1429     // asked to by the core tuning model.
1430     if (Subtarget->useNEONForSinglePrecisionFP()) {
1431       setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1432       setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1433       setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1434       setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1435     }
1436     setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1437     setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1438     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1439     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1440 
1441     if (Subtarget->hasFullFP16()) {
1442       setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1443       setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1444       setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1445       setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1446 
1447       setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1448       setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1449       setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1450       setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1451     }
1452   }
1453 
1454   // We have target-specific dag combine patterns for the following nodes:
1455   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1456   setTargetDAGCombine(ISD::ADD);
1457   setTargetDAGCombine(ISD::SUB);
1458   setTargetDAGCombine(ISD::MUL);
1459   setTargetDAGCombine(ISD::AND);
1460   setTargetDAGCombine(ISD::OR);
1461   setTargetDAGCombine(ISD::XOR);
1462 
1463   if (Subtarget->hasV6Ops())
1464     setTargetDAGCombine(ISD::SRL);
1465   if (Subtarget->isThumb1Only())
1466     setTargetDAGCombine(ISD::SHL);
1467 
1468   setStackPointerRegisterToSaveRestore(ARM::SP);
1469 
1470   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1471       !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1472     setSchedulingPreference(Sched::RegPressure);
1473   else
1474     setSchedulingPreference(Sched::Hybrid);
1475 
1476   //// temporary - rewrite interface to use type
1477   MaxStoresPerMemset = 8;
1478   MaxStoresPerMemsetOptSize = 4;
1479   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1480   MaxStoresPerMemcpyOptSize = 2;
1481   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1482   MaxStoresPerMemmoveOptSize = 2;
1483 
1484   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1485   // are at least 4 bytes aligned.
1486   setMinStackArgumentAlignment(Align(4));
1487 
1488   // Prefer likely predicted branches to selects on out-of-order cores.
1489   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1490 
1491   setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1492 
1493   setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1494 
1495   if (Subtarget->isThumb() || Subtarget->isThumb2())
1496     setTargetDAGCombine(ISD::ABS);
1497 }
1498 
1499 bool ARMTargetLowering::useSoftFloat() const {
1500   return Subtarget->useSoftFloat();
1501 }
1502 
1503 // FIXME: It might make sense to define the representative register class as the
1504 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1505 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1506 // SPR's representative would be DPR_VFP2. This should work well if register
1507 // pressure tracking were modified such that a register use would increment the
1508 // pressure of the register class's representative and all of it's super
1509 // classes' representatives transitively. We have not implemented this because
1510 // of the difficulty prior to coalescing of modeling operand register classes
1511 // due to the common occurrence of cross class copies and subregister insertions
1512 // and extractions.
1513 std::pair<const TargetRegisterClass *, uint8_t>
1514 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1515                                            MVT VT) const {
1516   const TargetRegisterClass *RRC = nullptr;
1517   uint8_t Cost = 1;
1518   switch (VT.SimpleTy) {
1519   default:
1520     return TargetLowering::findRepresentativeClass(TRI, VT);
1521   // Use DPR as representative register class for all floating point
1522   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1523   // the cost is 1 for both f32 and f64.
1524   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1525   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1526     RRC = &ARM::DPRRegClass;
1527     // When NEON is used for SP, only half of the register file is available
1528     // because operations that define both SP and DP results will be constrained
1529     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1530     // coalescing by double-counting the SP regs. See the FIXME above.
1531     if (Subtarget->useNEONForSinglePrecisionFP())
1532       Cost = 2;
1533     break;
1534   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1535   case MVT::v4f32: case MVT::v2f64:
1536     RRC = &ARM::DPRRegClass;
1537     Cost = 2;
1538     break;
1539   case MVT::v4i64:
1540     RRC = &ARM::DPRRegClass;
1541     Cost = 4;
1542     break;
1543   case MVT::v8i64:
1544     RRC = &ARM::DPRRegClass;
1545     Cost = 8;
1546     break;
1547   }
1548   return std::make_pair(RRC, Cost);
1549 }
1550 
1551 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1552   switch ((ARMISD::NodeType)Opcode) {
1553   case ARMISD::FIRST_NUMBER:  break;
1554   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1555   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1556   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1557   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1558   case ARMISD::CALL:          return "ARMISD::CALL";
1559   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1560   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1561   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1562   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1563   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1564   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1565   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1566   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1567   case ARMISD::CMP:           return "ARMISD::CMP";
1568   case ARMISD::CMN:           return "ARMISD::CMN";
1569   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1570   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1571   case ARMISD::CMPFPE:        return "ARMISD::CMPFPE";
1572   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1573   case ARMISD::CMPFPEw0:      return "ARMISD::CMPFPEw0";
1574   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1575   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1576 
1577   case ARMISD::CMOV:          return "ARMISD::CMOV";
1578   case ARMISD::SUBS:          return "ARMISD::SUBS";
1579 
1580   case ARMISD::SSAT:          return "ARMISD::SSAT";
1581   case ARMISD::USAT:          return "ARMISD::USAT";
1582 
1583   case ARMISD::ASRL:          return "ARMISD::ASRL";
1584   case ARMISD::LSRL:          return "ARMISD::LSRL";
1585   case ARMISD::LSLL:          return "ARMISD::LSLL";
1586 
1587   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1588   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1589   case ARMISD::RRX:           return "ARMISD::RRX";
1590 
1591   case ARMISD::ADDC:          return "ARMISD::ADDC";
1592   case ARMISD::ADDE:          return "ARMISD::ADDE";
1593   case ARMISD::SUBC:          return "ARMISD::SUBC";
1594   case ARMISD::SUBE:          return "ARMISD::SUBE";
1595   case ARMISD::LSLS:          return "ARMISD::LSLS";
1596 
1597   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1598   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1599   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1600   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1601   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
1602 
1603   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1604   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1605   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1606 
1607   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1608 
1609   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1610 
1611   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1612 
1613   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1614 
1615   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1616 
1617   case ARMISD::LDRD:          return "ARMISD::LDRD";
1618   case ARMISD::STRD:          return "ARMISD::STRD";
1619 
1620   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1621   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1622 
1623   case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1624   case ARMISD::VECTOR_REG_CAST: return "ARMISD::VECTOR_REG_CAST";
1625   case ARMISD::VCMP:          return "ARMISD::VCMP";
1626   case ARMISD::VCMPZ:         return "ARMISD::VCMPZ";
1627   case ARMISD::VTST:          return "ARMISD::VTST";
1628 
1629   case ARMISD::VSHLs:         return "ARMISD::VSHLs";
1630   case ARMISD::VSHLu:         return "ARMISD::VSHLu";
1631   case ARMISD::VSHLIMM:       return "ARMISD::VSHLIMM";
1632   case ARMISD::VSHRsIMM:      return "ARMISD::VSHRsIMM";
1633   case ARMISD::VSHRuIMM:      return "ARMISD::VSHRuIMM";
1634   case ARMISD::VRSHRsIMM:     return "ARMISD::VRSHRsIMM";
1635   case ARMISD::VRSHRuIMM:     return "ARMISD::VRSHRuIMM";
1636   case ARMISD::VRSHRNIMM:     return "ARMISD::VRSHRNIMM";
1637   case ARMISD::VQSHLsIMM:     return "ARMISD::VQSHLsIMM";
1638   case ARMISD::VQSHLuIMM:     return "ARMISD::VQSHLuIMM";
1639   case ARMISD::VQSHLsuIMM:    return "ARMISD::VQSHLsuIMM";
1640   case ARMISD::VQSHRNsIMM:    return "ARMISD::VQSHRNsIMM";
1641   case ARMISD::VQSHRNuIMM:    return "ARMISD::VQSHRNuIMM";
1642   case ARMISD::VQSHRNsuIMM:   return "ARMISD::VQSHRNsuIMM";
1643   case ARMISD::VQRSHRNsIMM:   return "ARMISD::VQRSHRNsIMM";
1644   case ARMISD::VQRSHRNuIMM:   return "ARMISD::VQRSHRNuIMM";
1645   case ARMISD::VQRSHRNsuIMM:  return "ARMISD::VQRSHRNsuIMM";
1646   case ARMISD::VSLIIMM:       return "ARMISD::VSLIIMM";
1647   case ARMISD::VSRIIMM:       return "ARMISD::VSRIIMM";
1648   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1649   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1650   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1651   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1652   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1653   case ARMISD::VDUP:          return "ARMISD::VDUP";
1654   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1655   case ARMISD::VEXT:          return "ARMISD::VEXT";
1656   case ARMISD::VREV64:        return "ARMISD::VREV64";
1657   case ARMISD::VREV32:        return "ARMISD::VREV32";
1658   case ARMISD::VREV16:        return "ARMISD::VREV16";
1659   case ARMISD::VZIP:          return "ARMISD::VZIP";
1660   case ARMISD::VUZP:          return "ARMISD::VUZP";
1661   case ARMISD::VTRN:          return "ARMISD::VTRN";
1662   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1663   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1664   case ARMISD::VMOVN:         return "ARMISD::VMOVN";
1665   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1666   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1667   case ARMISD::VADDVs:        return "ARMISD::VADDVs";
1668   case ARMISD::VADDVu:        return "ARMISD::VADDVu";
1669   case ARMISD::VADDLVs:       return "ARMISD::VADDLVs";
1670   case ARMISD::VADDLVu:       return "ARMISD::VADDLVu";
1671   case ARMISD::VADDLVAs:      return "ARMISD::VADDLVAs";
1672   case ARMISD::VADDLVAu:      return "ARMISD::VADDLVAu";
1673   case ARMISD::VADDLVps:      return "ARMISD::VADDLVps";
1674   case ARMISD::VADDLVpu:      return "ARMISD::VADDLVpu";
1675   case ARMISD::VADDLVAps:     return "ARMISD::VADDLVAps";
1676   case ARMISD::VADDLVApu:     return "ARMISD::VADDLVApu";
1677   case ARMISD::VMLAVs:        return "ARMISD::VMLAVs";
1678   case ARMISD::VMLAVu:        return "ARMISD::VMLAVu";
1679   case ARMISD::VMLALVs:       return "ARMISD::VMLALVs";
1680   case ARMISD::VMLALVu:       return "ARMISD::VMLALVu";
1681   case ARMISD::VMLALVAs:      return "ARMISD::VMLALVAs";
1682   case ARMISD::VMLALVAu:      return "ARMISD::VMLALVAu";
1683   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1684   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1685   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1686   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1687   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1688   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1689   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1690   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1691   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1692   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1693   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1694   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1695   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1696   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1697   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1698   case ARMISD::QADD16b:       return "ARMISD::QADD16b";
1699   case ARMISD::QSUB16b:       return "ARMISD::QSUB16b";
1700   case ARMISD::QADD8b:        return "ARMISD::QADD8b";
1701   case ARMISD::QSUB8b:        return "ARMISD::QSUB8b";
1702   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1703   case ARMISD::BFI:           return "ARMISD::BFI";
1704   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1705   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1706   case ARMISD::VBSL:          return "ARMISD::VBSL";
1707   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1708   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1709   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1710   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1711   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1712   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1713   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1714   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1715   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1716   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1717   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1718   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1719   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1720   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1721   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1722   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1723   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1724   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1725   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1726   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1727   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1728   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1729   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1730   case ARMISD::WLS:           return "ARMISD::WLS";
1731   case ARMISD::LE:            return "ARMISD::LE";
1732   case ARMISD::LOOP_DEC:      return "ARMISD::LOOP_DEC";
1733   case ARMISD::CSINV:         return "ARMISD::CSINV";
1734   case ARMISD::CSNEG:         return "ARMISD::CSNEG";
1735   case ARMISD::CSINC:         return "ARMISD::CSINC";
1736   }
1737   return nullptr;
1738 }
1739 
1740 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1741                                           EVT VT) const {
1742   if (!VT.isVector())
1743     return getPointerTy(DL);
1744 
1745   // MVE has a predicate register.
1746   if (Subtarget->hasMVEIntegerOps() &&
1747       (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1748     return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1749   return VT.changeVectorElementTypeToInteger();
1750 }
1751 
1752 /// getRegClassFor - Return the register class that should be used for the
1753 /// specified value type.
1754 const TargetRegisterClass *
1755 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1756   (void)isDivergent;
1757   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1758   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1759   // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1760   // MVE Q registers.
1761   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1762     if (VT == MVT::v4i64)
1763       return &ARM::QQPRRegClass;
1764     if (VT == MVT::v8i64)
1765       return &ARM::QQQQPRRegClass;
1766   }
1767   return TargetLowering::getRegClassFor(VT);
1768 }
1769 
1770 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1771 // source/dest is aligned and the copy size is large enough. We therefore want
1772 // to align such objects passed to memory intrinsics.
1773 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1774                                                unsigned &PrefAlign) const {
1775   if (!isa<MemIntrinsic>(CI))
1776     return false;
1777   MinSize = 8;
1778   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1779   // cycle faster than 4-byte aligned LDM.
1780   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1781   return true;
1782 }
1783 
1784 // Create a fast isel object.
1785 FastISel *
1786 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1787                                   const TargetLibraryInfo *libInfo) const {
1788   return ARM::createFastISel(funcInfo, libInfo);
1789 }
1790 
1791 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1792   unsigned NumVals = N->getNumValues();
1793   if (!NumVals)
1794     return Sched::RegPressure;
1795 
1796   for (unsigned i = 0; i != NumVals; ++i) {
1797     EVT VT = N->getValueType(i);
1798     if (VT == MVT::Glue || VT == MVT::Other)
1799       continue;
1800     if (VT.isFloatingPoint() || VT.isVector())
1801       return Sched::ILP;
1802   }
1803 
1804   if (!N->isMachineOpcode())
1805     return Sched::RegPressure;
1806 
1807   // Load are scheduled for latency even if there instruction itinerary
1808   // is not available.
1809   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1810   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1811 
1812   if (MCID.getNumDefs() == 0)
1813     return Sched::RegPressure;
1814   if (!Itins->isEmpty() &&
1815       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1816     return Sched::ILP;
1817 
1818   return Sched::RegPressure;
1819 }
1820 
1821 //===----------------------------------------------------------------------===//
1822 // Lowering Code
1823 //===----------------------------------------------------------------------===//
1824 
1825 static bool isSRL16(const SDValue &Op) {
1826   if (Op.getOpcode() != ISD::SRL)
1827     return false;
1828   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1829     return Const->getZExtValue() == 16;
1830   return false;
1831 }
1832 
1833 static bool isSRA16(const SDValue &Op) {
1834   if (Op.getOpcode() != ISD::SRA)
1835     return false;
1836   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1837     return Const->getZExtValue() == 16;
1838   return false;
1839 }
1840 
1841 static bool isSHL16(const SDValue &Op) {
1842   if (Op.getOpcode() != ISD::SHL)
1843     return false;
1844   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1845     return Const->getZExtValue() == 16;
1846   return false;
1847 }
1848 
1849 // Check for a signed 16-bit value. We special case SRA because it makes it
1850 // more simple when also looking for SRAs that aren't sign extending a
1851 // smaller value. Without the check, we'd need to take extra care with
1852 // checking order for some operations.
1853 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1854   if (isSRA16(Op))
1855     return isSHL16(Op.getOperand(0));
1856   return DAG.ComputeNumSignBits(Op) == 17;
1857 }
1858 
1859 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1860 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1861   switch (CC) {
1862   default: llvm_unreachable("Unknown condition code!");
1863   case ISD::SETNE:  return ARMCC::NE;
1864   case ISD::SETEQ:  return ARMCC::EQ;
1865   case ISD::SETGT:  return ARMCC::GT;
1866   case ISD::SETGE:  return ARMCC::GE;
1867   case ISD::SETLT:  return ARMCC::LT;
1868   case ISD::SETLE:  return ARMCC::LE;
1869   case ISD::SETUGT: return ARMCC::HI;
1870   case ISD::SETUGE: return ARMCC::HS;
1871   case ISD::SETULT: return ARMCC::LO;
1872   case ISD::SETULE: return ARMCC::LS;
1873   }
1874 }
1875 
1876 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1877 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1878                         ARMCC::CondCodes &CondCode2) {
1879   CondCode2 = ARMCC::AL;
1880   switch (CC) {
1881   default: llvm_unreachable("Unknown FP condition!");
1882   case ISD::SETEQ:
1883   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1884   case ISD::SETGT:
1885   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1886   case ISD::SETGE:
1887   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1888   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1889   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1890   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1891   case ISD::SETO:   CondCode = ARMCC::VC; break;
1892   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1893   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1894   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1895   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1896   case ISD::SETLT:
1897   case ISD::SETULT: CondCode = ARMCC::LT; break;
1898   case ISD::SETLE:
1899   case ISD::SETULE: CondCode = ARMCC::LE; break;
1900   case ISD::SETNE:
1901   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1902   }
1903 }
1904 
1905 //===----------------------------------------------------------------------===//
1906 //                      Calling Convention Implementation
1907 //===----------------------------------------------------------------------===//
1908 
1909 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1910 /// account presence of floating point hardware and calling convention
1911 /// limitations, such as support for variadic functions.
1912 CallingConv::ID
1913 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1914                                            bool isVarArg) const {
1915   switch (CC) {
1916   default:
1917     report_fatal_error("Unsupported calling convention");
1918   case CallingConv::ARM_AAPCS:
1919   case CallingConv::ARM_APCS:
1920   case CallingConv::GHC:
1921   case CallingConv::CFGuard_Check:
1922     return CC;
1923   case CallingConv::PreserveMost:
1924     return CallingConv::PreserveMost;
1925   case CallingConv::ARM_AAPCS_VFP:
1926   case CallingConv::Swift:
1927     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1928   case CallingConv::C:
1929     if (!Subtarget->isAAPCS_ABI())
1930       return CallingConv::ARM_APCS;
1931     else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1932              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1933              !isVarArg)
1934       return CallingConv::ARM_AAPCS_VFP;
1935     else
1936       return CallingConv::ARM_AAPCS;
1937   case CallingConv::Fast:
1938   case CallingConv::CXX_FAST_TLS:
1939     if (!Subtarget->isAAPCS_ABI()) {
1940       if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1941         return CallingConv::Fast;
1942       return CallingConv::ARM_APCS;
1943     } else if (Subtarget->hasVFP2Base() &&
1944                !Subtarget->isThumb1Only() && !isVarArg)
1945       return CallingConv::ARM_AAPCS_VFP;
1946     else
1947       return CallingConv::ARM_AAPCS;
1948   }
1949 }
1950 
1951 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1952                                                  bool isVarArg) const {
1953   return CCAssignFnForNode(CC, false, isVarArg);
1954 }
1955 
1956 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1957                                                    bool isVarArg) const {
1958   return CCAssignFnForNode(CC, true, isVarArg);
1959 }
1960 
1961 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1962 /// CallingConvention.
1963 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1964                                                  bool Return,
1965                                                  bool isVarArg) const {
1966   switch (getEffectiveCallingConv(CC, isVarArg)) {
1967   default:
1968     report_fatal_error("Unsupported calling convention");
1969   case CallingConv::ARM_APCS:
1970     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1971   case CallingConv::ARM_AAPCS:
1972     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1973   case CallingConv::ARM_AAPCS_VFP:
1974     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1975   case CallingConv::Fast:
1976     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1977   case CallingConv::GHC:
1978     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1979   case CallingConv::PreserveMost:
1980     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1981   case CallingConv::CFGuard_Check:
1982     return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
1983   }
1984 }
1985 
1986 /// LowerCallResult - Lower the result values of a call into the
1987 /// appropriate copies out of appropriate physical registers.
1988 SDValue ARMTargetLowering::LowerCallResult(
1989     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1990     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1991     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1992     SDValue ThisVal) const {
1993   // Assign locations to each value returned by this call.
1994   SmallVector<CCValAssign, 16> RVLocs;
1995   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1996                  *DAG.getContext());
1997   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1998 
1999   // Copy all of the result registers out of their specified physreg.
2000   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2001     CCValAssign VA = RVLocs[i];
2002 
2003     // Pass 'this' value directly from the argument to return value, to avoid
2004     // reg unit interference
2005     if (i == 0 && isThisReturn) {
2006       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
2007              "unexpected return calling convention register assignment");
2008       InVals.push_back(ThisVal);
2009       continue;
2010     }
2011 
2012     SDValue Val;
2013     if (VA.needsCustom()) {
2014       // Handle f64 or half of a v2f64.
2015       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2016                                       InFlag);
2017       Chain = Lo.getValue(1);
2018       InFlag = Lo.getValue(2);
2019       VA = RVLocs[++i]; // skip ahead to next loc
2020       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2021                                       InFlag);
2022       Chain = Hi.getValue(1);
2023       InFlag = Hi.getValue(2);
2024       if (!Subtarget->isLittle())
2025         std::swap (Lo, Hi);
2026       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2027 
2028       if (VA.getLocVT() == MVT::v2f64) {
2029         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2030         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2031                           DAG.getConstant(0, dl, MVT::i32));
2032 
2033         VA = RVLocs[++i]; // skip ahead to next loc
2034         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2035         Chain = Lo.getValue(1);
2036         InFlag = Lo.getValue(2);
2037         VA = RVLocs[++i]; // skip ahead to next loc
2038         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2039         Chain = Hi.getValue(1);
2040         InFlag = Hi.getValue(2);
2041         if (!Subtarget->isLittle())
2042           std::swap (Lo, Hi);
2043         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2044         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2045                           DAG.getConstant(1, dl, MVT::i32));
2046       }
2047     } else {
2048       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2049                                InFlag);
2050       Chain = Val.getValue(1);
2051       InFlag = Val.getValue(2);
2052     }
2053 
2054     switch (VA.getLocInfo()) {
2055     default: llvm_unreachable("Unknown loc info!");
2056     case CCValAssign::Full: break;
2057     case CCValAssign::BCvt:
2058       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2059       break;
2060     }
2061 
2062     InVals.push_back(Val);
2063   }
2064 
2065   return Chain;
2066 }
2067 
2068 /// LowerMemOpCallTo - Store the argument to the stack.
2069 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
2070                                             SDValue Arg, const SDLoc &dl,
2071                                             SelectionDAG &DAG,
2072                                             const CCValAssign &VA,
2073                                             ISD::ArgFlagsTy Flags) const {
2074   unsigned LocMemOffset = VA.getLocMemOffset();
2075   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2076   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2077                        StackPtr, PtrOff);
2078   return DAG.getStore(
2079       Chain, dl, Arg, PtrOff,
2080       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2081 }
2082 
2083 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2084                                          SDValue Chain, SDValue &Arg,
2085                                          RegsToPassVector &RegsToPass,
2086                                          CCValAssign &VA, CCValAssign &NextVA,
2087                                          SDValue &StackPtr,
2088                                          SmallVectorImpl<SDValue> &MemOpChains,
2089                                          ISD::ArgFlagsTy Flags) const {
2090   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2091                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
2092   unsigned id = Subtarget->isLittle() ? 0 : 1;
2093   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2094 
2095   if (NextVA.isRegLoc())
2096     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2097   else {
2098     assert(NextVA.isMemLoc());
2099     if (!StackPtr.getNode())
2100       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2101                                     getPointerTy(DAG.getDataLayout()));
2102 
2103     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2104                                            dl, DAG, NextVA,
2105                                            Flags));
2106   }
2107 }
2108 
2109 /// LowerCall - Lowering a call into a callseq_start <-
2110 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2111 /// nodes.
2112 SDValue
2113 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2114                              SmallVectorImpl<SDValue> &InVals) const {
2115   SelectionDAG &DAG                     = CLI.DAG;
2116   SDLoc &dl                             = CLI.DL;
2117   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2118   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2119   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2120   SDValue Chain                         = CLI.Chain;
2121   SDValue Callee                        = CLI.Callee;
2122   bool &isTailCall                      = CLI.IsTailCall;
2123   CallingConv::ID CallConv              = CLI.CallConv;
2124   bool doesNotRet                       = CLI.DoesNotReturn;
2125   bool isVarArg                         = CLI.IsVarArg;
2126 
2127   MachineFunction &MF = DAG.getMachineFunction();
2128   MachineFunction::CallSiteInfo CSInfo;
2129   bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2130   bool isThisReturn = false;
2131   bool PreferIndirect = false;
2132 
2133   // Disable tail calls if they're not supported.
2134   if (!Subtarget->supportsTailCall())
2135     isTailCall = false;
2136 
2137   if (isa<GlobalAddressSDNode>(Callee)) {
2138     // If we're optimizing for minimum size and the function is called three or
2139     // more times in this block, we can improve codesize by calling indirectly
2140     // as BLXr has a 16-bit encoding.
2141     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2142     if (CLI.CB) {
2143       auto *BB = CLI.CB->getParent();
2144       PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2145                        count_if(GV->users(), [&BB](const User *U) {
2146                          return isa<Instruction>(U) &&
2147                                 cast<Instruction>(U)->getParent() == BB;
2148                        }) > 2;
2149     }
2150   }
2151   if (isTailCall) {
2152     // Check if it's really possible to do a tail call.
2153     isTailCall = IsEligibleForTailCallOptimization(
2154         Callee, CallConv, isVarArg, isStructRet,
2155         MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2156         PreferIndirect);
2157     if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2158       report_fatal_error("failed to perform tail call elimination on a call "
2159                          "site marked musttail");
2160     // We don't support GuaranteedTailCallOpt for ARM, only automatically
2161     // detected sibcalls.
2162     if (isTailCall)
2163       ++NumTailCalls;
2164   }
2165 
2166   // Analyze operands of the call, assigning locations to each operand.
2167   SmallVector<CCValAssign, 16> ArgLocs;
2168   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2169                  *DAG.getContext());
2170   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2171 
2172   // Get a count of how many bytes are to be pushed on the stack.
2173   unsigned NumBytes = CCInfo.getNextStackOffset();
2174 
2175   if (isTailCall) {
2176     // For tail calls, memory operands are available in our caller's stack.
2177     NumBytes = 0;
2178   } else {
2179     // Adjust the stack pointer for the new arguments...
2180     // These operations are automatically eliminated by the prolog/epilog pass
2181     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2182   }
2183 
2184   SDValue StackPtr =
2185       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2186 
2187   RegsToPassVector RegsToPass;
2188   SmallVector<SDValue, 8> MemOpChains;
2189 
2190   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2191   // of tail call optimization, arguments are handled later.
2192   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2193        i != e;
2194        ++i, ++realArgIdx) {
2195     CCValAssign &VA = ArgLocs[i];
2196     SDValue Arg = OutVals[realArgIdx];
2197     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2198     bool isByVal = Flags.isByVal();
2199 
2200     // Promote the value if needed.
2201     switch (VA.getLocInfo()) {
2202     default: llvm_unreachable("Unknown loc info!");
2203     case CCValAssign::Full: break;
2204     case CCValAssign::SExt:
2205       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2206       break;
2207     case CCValAssign::ZExt:
2208       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2209       break;
2210     case CCValAssign::AExt:
2211       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2212       break;
2213     case CCValAssign::BCvt:
2214       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2215       break;
2216     }
2217 
2218     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2219     if (VA.needsCustom()) {
2220       if (VA.getLocVT() == MVT::v2f64) {
2221         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2222                                   DAG.getConstant(0, dl, MVT::i32));
2223         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2224                                   DAG.getConstant(1, dl, MVT::i32));
2225 
2226         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2227                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2228 
2229         VA = ArgLocs[++i]; // skip ahead to next loc
2230         if (VA.isRegLoc()) {
2231           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2232                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2233         } else {
2234           assert(VA.isMemLoc());
2235 
2236           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2237                                                  dl, DAG, VA, Flags));
2238         }
2239       } else {
2240         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2241                          StackPtr, MemOpChains, Flags);
2242       }
2243     } else if (VA.isRegLoc()) {
2244       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2245           Outs[0].VT == MVT::i32) {
2246         assert(VA.getLocVT() == MVT::i32 &&
2247                "unexpected calling convention register assignment");
2248         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2249                "unexpected use of 'returned'");
2250         isThisReturn = true;
2251       }
2252       const TargetOptions &Options = DAG.getTarget().Options;
2253       if (Options.EmitCallSiteInfo)
2254         CSInfo.emplace_back(VA.getLocReg(), i);
2255       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2256     } else if (isByVal) {
2257       assert(VA.isMemLoc());
2258       unsigned offset = 0;
2259 
2260       // True if this byval aggregate will be split between registers
2261       // and memory.
2262       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2263       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2264 
2265       if (CurByValIdx < ByValArgsCount) {
2266 
2267         unsigned RegBegin, RegEnd;
2268         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2269 
2270         EVT PtrVT =
2271             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2272         unsigned int i, j;
2273         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2274           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2275           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2276           SDValue Load =
2277               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2278                           DAG.InferPtrAlign(AddArg));
2279           MemOpChains.push_back(Load.getValue(1));
2280           RegsToPass.push_back(std::make_pair(j, Load));
2281         }
2282 
2283         // If parameter size outsides register area, "offset" value
2284         // helps us to calculate stack slot for remained part properly.
2285         offset = RegEnd - RegBegin;
2286 
2287         CCInfo.nextInRegsParam();
2288       }
2289 
2290       if (Flags.getByValSize() > 4*offset) {
2291         auto PtrVT = getPointerTy(DAG.getDataLayout());
2292         unsigned LocMemOffset = VA.getLocMemOffset();
2293         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2294         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2295         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2296         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2297         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2298                                            MVT::i32);
2299         SDValue AlignNode =
2300             DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2301 
2302         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2303         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2304         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2305                                           Ops));
2306       }
2307     } else if (!isTailCall) {
2308       assert(VA.isMemLoc());
2309 
2310       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2311                                              dl, DAG, VA, Flags));
2312     }
2313   }
2314 
2315   if (!MemOpChains.empty())
2316     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2317 
2318   // Build a sequence of copy-to-reg nodes chained together with token chain
2319   // and flag operands which copy the outgoing args into the appropriate regs.
2320   SDValue InFlag;
2321   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2322     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2323                              RegsToPass[i].second, InFlag);
2324     InFlag = Chain.getValue(1);
2325   }
2326 
2327   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2328   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2329   // node so that legalize doesn't hack it.
2330   bool isDirect = false;
2331 
2332   const TargetMachine &TM = getTargetMachine();
2333   const Module *Mod = MF.getFunction().getParent();
2334   const GlobalValue *GV = nullptr;
2335   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2336     GV = G->getGlobal();
2337   bool isStub =
2338       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2339 
2340   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2341   bool isLocalARMFunc = false;
2342   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2343   auto PtrVt = getPointerTy(DAG.getDataLayout());
2344 
2345   if (Subtarget->genLongCalls()) {
2346     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2347            "long-calls codegen is not position independent!");
2348     // Handle a global address or an external symbol. If it's not one of
2349     // those, the target's already in a register, so we don't need to do
2350     // anything extra.
2351     if (isa<GlobalAddressSDNode>(Callee)) {
2352       // Create a constant pool entry for the callee address
2353       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2354       ARMConstantPoolValue *CPV =
2355         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2356 
2357       // Get the address of the callee into a register
2358       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2359       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2360       Callee = DAG.getLoad(
2361           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2362           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2363     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2364       const char *Sym = S->getSymbol();
2365 
2366       // Create a constant pool entry for the callee address
2367       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2368       ARMConstantPoolValue *CPV =
2369         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2370                                       ARMPCLabelIndex, 0);
2371       // Get the address of the callee into a register
2372       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2373       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2374       Callee = DAG.getLoad(
2375           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2376           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2377     }
2378   } else if (isa<GlobalAddressSDNode>(Callee)) {
2379     if (!PreferIndirect) {
2380       isDirect = true;
2381       bool isDef = GV->isStrongDefinitionForLinker();
2382 
2383       // ARM call to a local ARM function is predicable.
2384       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2385       // tBX takes a register source operand.
2386       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2387         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2388         Callee = DAG.getNode(
2389             ARMISD::WrapperPIC, dl, PtrVt,
2390             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2391         Callee = DAG.getLoad(
2392             PtrVt, dl, DAG.getEntryNode(), Callee,
2393             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2394             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2395                                      MachineMemOperand::MOInvariant);
2396       } else if (Subtarget->isTargetCOFF()) {
2397         assert(Subtarget->isTargetWindows() &&
2398                "Windows is the only supported COFF target");
2399         unsigned TargetFlags = ARMII::MO_NO_FLAG;
2400         if (GV->hasDLLImportStorageClass())
2401           TargetFlags = ARMII::MO_DLLIMPORT;
2402         else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
2403           TargetFlags = ARMII::MO_COFFSTUB;
2404         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2405                                             TargetFlags);
2406         if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2407           Callee =
2408               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2409                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2410                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2411       } else {
2412         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2413       }
2414     }
2415   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2416     isDirect = true;
2417     // tBX takes a register source operand.
2418     const char *Sym = S->getSymbol();
2419     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2420       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2421       ARMConstantPoolValue *CPV =
2422         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2423                                       ARMPCLabelIndex, 4);
2424       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2425       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2426       Callee = DAG.getLoad(
2427           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2428           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2429       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2430       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2431     } else {
2432       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2433     }
2434   }
2435 
2436   // FIXME: handle tail calls differently.
2437   unsigned CallOpc;
2438   if (Subtarget->isThumb()) {
2439     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2440       CallOpc = ARMISD::CALL_NOLINK;
2441     else
2442       CallOpc = ARMISD::CALL;
2443   } else {
2444     if (!isDirect && !Subtarget->hasV5TOps())
2445       CallOpc = ARMISD::CALL_NOLINK;
2446     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2447              // Emit regular call when code size is the priority
2448              !Subtarget->hasMinSize())
2449       // "mov lr, pc; b _foo" to avoid confusing the RSP
2450       CallOpc = ARMISD::CALL_NOLINK;
2451     else
2452       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2453   }
2454 
2455   std::vector<SDValue> Ops;
2456   Ops.push_back(Chain);
2457   Ops.push_back(Callee);
2458 
2459   // Add argument registers to the end of the list so that they are known live
2460   // into the call.
2461   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2462     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2463                                   RegsToPass[i].second.getValueType()));
2464 
2465   // Add a register mask operand representing the call-preserved registers.
2466   if (!isTailCall) {
2467     const uint32_t *Mask;
2468     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2469     if (isThisReturn) {
2470       // For 'this' returns, use the R0-preserving mask if applicable
2471       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2472       if (!Mask) {
2473         // Set isThisReturn to false if the calling convention is not one that
2474         // allows 'returned' to be modeled in this way, so LowerCallResult does
2475         // not try to pass 'this' straight through
2476         isThisReturn = false;
2477         Mask = ARI->getCallPreservedMask(MF, CallConv);
2478       }
2479     } else
2480       Mask = ARI->getCallPreservedMask(MF, CallConv);
2481 
2482     assert(Mask && "Missing call preserved mask for calling convention");
2483     Ops.push_back(DAG.getRegisterMask(Mask));
2484   }
2485 
2486   if (InFlag.getNode())
2487     Ops.push_back(InFlag);
2488 
2489   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2490   if (isTailCall) {
2491     MF.getFrameInfo().setHasTailCall();
2492     SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2493     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2494     return Ret;
2495   }
2496 
2497   // Returns a chain and a flag for retval copy to use.
2498   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2499   InFlag = Chain.getValue(1);
2500   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2501 
2502   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2503                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2504   if (!Ins.empty())
2505     InFlag = Chain.getValue(1);
2506 
2507   // Handle result values, copying them out of physregs into vregs that we
2508   // return.
2509   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2510                          InVals, isThisReturn,
2511                          isThisReturn ? OutVals[0] : SDValue());
2512 }
2513 
2514 /// HandleByVal - Every parameter *after* a byval parameter is passed
2515 /// on the stack.  Remember the next parameter register to allocate,
2516 /// and then confiscate the rest of the parameter registers to insure
2517 /// this.
2518 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2519                                     unsigned Align) const {
2520   // Byval (as with any stack) slots are always at least 4 byte aligned.
2521   Align = std::max(Align, 4U);
2522 
2523   unsigned Reg = State->AllocateReg(GPRArgRegs);
2524   if (!Reg)
2525     return;
2526 
2527   unsigned AlignInRegs = Align / 4;
2528   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2529   for (unsigned i = 0; i < Waste; ++i)
2530     Reg = State->AllocateReg(GPRArgRegs);
2531 
2532   if (!Reg)
2533     return;
2534 
2535   unsigned Excess = 4 * (ARM::R4 - Reg);
2536 
2537   // Special case when NSAA != SP and parameter size greater than size of
2538   // all remained GPR regs. In that case we can't split parameter, we must
2539   // send it to stack. We also must set NCRN to R4, so waste all
2540   // remained registers.
2541   const unsigned NSAAOffset = State->getNextStackOffset();
2542   if (NSAAOffset != 0 && Size > Excess) {
2543     while (State->AllocateReg(GPRArgRegs))
2544       ;
2545     return;
2546   }
2547 
2548   // First register for byval parameter is the first register that wasn't
2549   // allocated before this method call, so it would be "reg".
2550   // If parameter is small enough to be saved in range [reg, r4), then
2551   // the end (first after last) register would be reg + param-size-in-regs,
2552   // else parameter would be splitted between registers and stack,
2553   // end register would be r4 in this case.
2554   unsigned ByValRegBegin = Reg;
2555   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2556   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2557   // Note, first register is allocated in the beginning of function already,
2558   // allocate remained amount of registers we need.
2559   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2560     State->AllocateReg(GPRArgRegs);
2561   // A byval parameter that is split between registers and memory needs its
2562   // size truncated here.
2563   // In the case where the entire structure fits in registers, we set the
2564   // size in memory to zero.
2565   Size = std::max<int>(Size - Excess, 0);
2566 }
2567 
2568 /// MatchingStackOffset - Return true if the given stack call argument is
2569 /// already available in the same position (relatively) of the caller's
2570 /// incoming argument stack.
2571 static
2572 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2573                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2574                          const TargetInstrInfo *TII) {
2575   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2576   int FI = std::numeric_limits<int>::max();
2577   if (Arg.getOpcode() == ISD::CopyFromReg) {
2578     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2579     if (!Register::isVirtualRegister(VR))
2580       return false;
2581     MachineInstr *Def = MRI->getVRegDef(VR);
2582     if (!Def)
2583       return false;
2584     if (!Flags.isByVal()) {
2585       if (!TII->isLoadFromStackSlot(*Def, FI))
2586         return false;
2587     } else {
2588       return false;
2589     }
2590   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2591     if (Flags.isByVal())
2592       // ByVal argument is passed in as a pointer but it's now being
2593       // dereferenced. e.g.
2594       // define @foo(%struct.X* %A) {
2595       //   tail call @bar(%struct.X* byval %A)
2596       // }
2597       return false;
2598     SDValue Ptr = Ld->getBasePtr();
2599     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2600     if (!FINode)
2601       return false;
2602     FI = FINode->getIndex();
2603   } else
2604     return false;
2605 
2606   assert(FI != std::numeric_limits<int>::max());
2607   if (!MFI.isFixedObjectIndex(FI))
2608     return false;
2609   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2610 }
2611 
2612 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2613 /// for tail call optimization. Targets which want to do tail call
2614 /// optimization should implement this function.
2615 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2616     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2617     bool isCalleeStructRet, bool isCallerStructRet,
2618     const SmallVectorImpl<ISD::OutputArg> &Outs,
2619     const SmallVectorImpl<SDValue> &OutVals,
2620     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2621     const bool isIndirect) const {
2622   MachineFunction &MF = DAG.getMachineFunction();
2623   const Function &CallerF = MF.getFunction();
2624   CallingConv::ID CallerCC = CallerF.getCallingConv();
2625 
2626   assert(Subtarget->supportsTailCall());
2627 
2628   // Indirect tail calls cannot be optimized for Thumb1 if the args
2629   // to the call take up r0-r3. The reason is that there are no legal registers
2630   // left to hold the pointer to the function to be called.
2631   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2632       (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2633     return false;
2634 
2635   // Look for obvious safe cases to perform tail call optimization that do not
2636   // require ABI changes. This is what gcc calls sibcall.
2637 
2638   // Exception-handling functions need a special set of instructions to indicate
2639   // a return to the hardware. Tail-calling another function would probably
2640   // break this.
2641   if (CallerF.hasFnAttribute("interrupt"))
2642     return false;
2643 
2644   // Also avoid sibcall optimization if either caller or callee uses struct
2645   // return semantics.
2646   if (isCalleeStructRet || isCallerStructRet)
2647     return false;
2648 
2649   // Externally-defined functions with weak linkage should not be
2650   // tail-called on ARM when the OS does not support dynamic
2651   // pre-emption of symbols, as the AAELF spec requires normal calls
2652   // to undefined weak functions to be replaced with a NOP or jump to the
2653   // next instruction. The behaviour of branch instructions in this
2654   // situation (as used for tail calls) is implementation-defined, so we
2655   // cannot rely on the linker replacing the tail call with a return.
2656   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2657     const GlobalValue *GV = G->getGlobal();
2658     const Triple &TT = getTargetMachine().getTargetTriple();
2659     if (GV->hasExternalWeakLinkage() &&
2660         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2661       return false;
2662   }
2663 
2664   // Check that the call results are passed in the same way.
2665   LLVMContext &C = *DAG.getContext();
2666   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2667                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2668                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2669     return false;
2670   // The callee has to preserve all registers the caller needs to preserve.
2671   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2672   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2673   if (CalleeCC != CallerCC) {
2674     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2675     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2676       return false;
2677   }
2678 
2679   // If Caller's vararg or byval argument has been split between registers and
2680   // stack, do not perform tail call, since part of the argument is in caller's
2681   // local frame.
2682   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2683   if (AFI_Caller->getArgRegsSaveSize())
2684     return false;
2685 
2686   // If the callee takes no arguments then go on to check the results of the
2687   // call.
2688   if (!Outs.empty()) {
2689     // Check if stack adjustment is needed. For now, do not do this if any
2690     // argument is passed on the stack.
2691     SmallVector<CCValAssign, 16> ArgLocs;
2692     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2693     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2694     if (CCInfo.getNextStackOffset()) {
2695       // Check if the arguments are already laid out in the right way as
2696       // the caller's fixed stack objects.
2697       MachineFrameInfo &MFI = MF.getFrameInfo();
2698       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2699       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2700       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2701            i != e;
2702            ++i, ++realArgIdx) {
2703         CCValAssign &VA = ArgLocs[i];
2704         EVT RegVT = VA.getLocVT();
2705         SDValue Arg = OutVals[realArgIdx];
2706         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2707         if (VA.getLocInfo() == CCValAssign::Indirect)
2708           return false;
2709         if (VA.needsCustom()) {
2710           // f64 and vector types are split into multiple registers or
2711           // register/stack-slot combinations.  The types will not match
2712           // the registers; give up on memory f64 refs until we figure
2713           // out what to do about this.
2714           if (!VA.isRegLoc())
2715             return false;
2716           if (!ArgLocs[++i].isRegLoc())
2717             return false;
2718           if (RegVT == MVT::v2f64) {
2719             if (!ArgLocs[++i].isRegLoc())
2720               return false;
2721             if (!ArgLocs[++i].isRegLoc())
2722               return false;
2723           }
2724         } else if (!VA.isRegLoc()) {
2725           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2726                                    MFI, MRI, TII))
2727             return false;
2728         }
2729       }
2730     }
2731 
2732     const MachineRegisterInfo &MRI = MF.getRegInfo();
2733     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2734       return false;
2735   }
2736 
2737   return true;
2738 }
2739 
2740 bool
2741 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2742                                   MachineFunction &MF, bool isVarArg,
2743                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2744                                   LLVMContext &Context) const {
2745   SmallVector<CCValAssign, 16> RVLocs;
2746   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2747   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2748 }
2749 
2750 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2751                                     const SDLoc &DL, SelectionDAG &DAG) {
2752   const MachineFunction &MF = DAG.getMachineFunction();
2753   const Function &F = MF.getFunction();
2754 
2755   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2756 
2757   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2758   // version of the "preferred return address". These offsets affect the return
2759   // instruction if this is a return from PL1 without hypervisor extensions.
2760   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2761   //    SWI:     0      "subs pc, lr, #0"
2762   //    ABORT:   +4     "subs pc, lr, #4"
2763   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2764   // UNDEF varies depending on where the exception came from ARM or Thumb
2765   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2766 
2767   int64_t LROffset;
2768   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2769       IntKind == "ABORT")
2770     LROffset = 4;
2771   else if (IntKind == "SWI" || IntKind == "UNDEF")
2772     LROffset = 0;
2773   else
2774     report_fatal_error("Unsupported interrupt attribute. If present, value "
2775                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2776 
2777   RetOps.insert(RetOps.begin() + 1,
2778                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2779 
2780   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2781 }
2782 
2783 SDValue
2784 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2785                                bool isVarArg,
2786                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2787                                const SmallVectorImpl<SDValue> &OutVals,
2788                                const SDLoc &dl, SelectionDAG &DAG) const {
2789   // CCValAssign - represent the assignment of the return value to a location.
2790   SmallVector<CCValAssign, 16> RVLocs;
2791 
2792   // CCState - Info about the registers and stack slots.
2793   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2794                  *DAG.getContext());
2795 
2796   // Analyze outgoing return values.
2797   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2798 
2799   SDValue Flag;
2800   SmallVector<SDValue, 4> RetOps;
2801   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2802   bool isLittleEndian = Subtarget->isLittle();
2803 
2804   MachineFunction &MF = DAG.getMachineFunction();
2805   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2806   AFI->setReturnRegsCount(RVLocs.size());
2807 
2808   // Copy the result values into the output registers.
2809   for (unsigned i = 0, realRVLocIdx = 0;
2810        i != RVLocs.size();
2811        ++i, ++realRVLocIdx) {
2812     CCValAssign &VA = RVLocs[i];
2813     assert(VA.isRegLoc() && "Can only return in registers!");
2814 
2815     SDValue Arg = OutVals[realRVLocIdx];
2816     bool ReturnF16 = false;
2817 
2818     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2819       // Half-precision return values can be returned like this:
2820       //
2821       // t11 f16 = fadd ...
2822       // t12: i16 = bitcast t11
2823       //   t13: i32 = zero_extend t12
2824       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2825       //
2826       // to avoid code generation for bitcasts, we simply set Arg to the node
2827       // that produces the f16 value, t11 in this case.
2828       //
2829       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2830         SDValue ZE = Arg.getOperand(0);
2831         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2832           SDValue BC = ZE.getOperand(0);
2833           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2834             Arg = BC.getOperand(0);
2835             ReturnF16 = true;
2836           }
2837         }
2838       }
2839     }
2840 
2841     switch (VA.getLocInfo()) {
2842     default: llvm_unreachable("Unknown loc info!");
2843     case CCValAssign::Full: break;
2844     case CCValAssign::BCvt:
2845       if (!ReturnF16)
2846         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2847       break;
2848     }
2849 
2850     if (VA.needsCustom()) {
2851       if (VA.getLocVT() == MVT::v2f64) {
2852         // Extract the first half and return it in two registers.
2853         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2854                                    DAG.getConstant(0, dl, MVT::i32));
2855         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2856                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2857 
2858         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2859                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2860                                  Flag);
2861         Flag = Chain.getValue(1);
2862         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2863         VA = RVLocs[++i]; // skip ahead to next loc
2864         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2865                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
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 
2871         // Extract the 2nd half and fall through to handle it as an f64 value.
2872         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2873                           DAG.getConstant(1, dl, MVT::i32));
2874       }
2875       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2876       // available.
2877       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2878                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2879       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2880                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2881                                Flag);
2882       Flag = Chain.getValue(1);
2883       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2884       VA = RVLocs[++i]; // skip ahead to next loc
2885       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2886                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2887                                Flag);
2888     } else
2889       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2890 
2891     // Guarantee that all emitted copies are
2892     // stuck together, avoiding something bad.
2893     Flag = Chain.getValue(1);
2894     RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2895                                      ReturnF16 ? MVT::f16 : VA.getLocVT()));
2896   }
2897   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2898   const MCPhysReg *I =
2899       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2900   if (I) {
2901     for (; *I; ++I) {
2902       if (ARM::GPRRegClass.contains(*I))
2903         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2904       else if (ARM::DPRRegClass.contains(*I))
2905         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2906       else
2907         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2908     }
2909   }
2910 
2911   // Update chain and glue.
2912   RetOps[0] = Chain;
2913   if (Flag.getNode())
2914     RetOps.push_back(Flag);
2915 
2916   // CPUs which aren't M-class use a special sequence to return from
2917   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2918   // though we use "subs pc, lr, #N").
2919   //
2920   // M-class CPUs actually use a normal return sequence with a special
2921   // (hardware-provided) value in LR, so the normal code path works.
2922   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2923       !Subtarget->isMClass()) {
2924     if (Subtarget->isThumb1Only())
2925       report_fatal_error("interrupt attribute is not supported in Thumb1");
2926     return LowerInterruptReturn(RetOps, dl, DAG);
2927   }
2928 
2929   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2930 }
2931 
2932 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2933   if (N->getNumValues() != 1)
2934     return false;
2935   if (!N->hasNUsesOfValue(1, 0))
2936     return false;
2937 
2938   SDValue TCChain = Chain;
2939   SDNode *Copy = *N->use_begin();
2940   if (Copy->getOpcode() == ISD::CopyToReg) {
2941     // If the copy has a glue operand, we conservatively assume it isn't safe to
2942     // perform a tail call.
2943     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2944       return false;
2945     TCChain = Copy->getOperand(0);
2946   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2947     SDNode *VMov = Copy;
2948     // f64 returned in a pair of GPRs.
2949     SmallPtrSet<SDNode*, 2> Copies;
2950     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2951          UI != UE; ++UI) {
2952       if (UI->getOpcode() != ISD::CopyToReg)
2953         return false;
2954       Copies.insert(*UI);
2955     }
2956     if (Copies.size() > 2)
2957       return false;
2958 
2959     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2960          UI != UE; ++UI) {
2961       SDValue UseChain = UI->getOperand(0);
2962       if (Copies.count(UseChain.getNode()))
2963         // Second CopyToReg
2964         Copy = *UI;
2965       else {
2966         // We are at the top of this chain.
2967         // If the copy has a glue operand, we conservatively assume it
2968         // isn't safe to perform a tail call.
2969         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2970           return false;
2971         // First CopyToReg
2972         TCChain = UseChain;
2973       }
2974     }
2975   } else if (Copy->getOpcode() == ISD::BITCAST) {
2976     // f32 returned in a single GPR.
2977     if (!Copy->hasOneUse())
2978       return false;
2979     Copy = *Copy->use_begin();
2980     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2981       return false;
2982     // If the copy has a glue operand, we conservatively assume it isn't safe to
2983     // perform a tail call.
2984     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2985       return false;
2986     TCChain = Copy->getOperand(0);
2987   } else {
2988     return false;
2989   }
2990 
2991   bool HasRet = false;
2992   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2993        UI != UE; ++UI) {
2994     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2995         UI->getOpcode() != ARMISD::INTRET_FLAG)
2996       return false;
2997     HasRet = true;
2998   }
2999 
3000   if (!HasRet)
3001     return false;
3002 
3003   Chain = TCChain;
3004   return true;
3005 }
3006 
3007 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3008   if (!Subtarget->supportsTailCall())
3009     return false;
3010 
3011   if (!CI->isTailCall())
3012     return false;
3013 
3014   return true;
3015 }
3016 
3017 // Trying to write a 64 bit value so need to split into two 32 bit values first,
3018 // and pass the lower and high parts through.
3019 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3020   SDLoc DL(Op);
3021   SDValue WriteValue = Op->getOperand(2);
3022 
3023   // This function is only supposed to be called for i64 type argument.
3024   assert(WriteValue.getValueType() == MVT::i64
3025           && "LowerWRITE_REGISTER called for non-i64 type argument.");
3026 
3027   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3028                            DAG.getConstant(0, DL, MVT::i32));
3029   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3030                            DAG.getConstant(1, DL, MVT::i32));
3031   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3032   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3033 }
3034 
3035 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3036 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3037 // one of the above mentioned nodes. It has to be wrapped because otherwise
3038 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3039 // be used to form addressing mode. These wrapped nodes will be selected
3040 // into MOVi.
3041 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3042                                              SelectionDAG &DAG) const {
3043   EVT PtrVT = Op.getValueType();
3044   // FIXME there is no actual debug info here
3045   SDLoc dl(Op);
3046   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3047   SDValue Res;
3048 
3049   // When generating execute-only code Constant Pools must be promoted to the
3050   // global data section. It's a bit ugly that we can't share them across basic
3051   // blocks, but this way we guarantee that execute-only behaves correct with
3052   // position-independent addressing modes.
3053   if (Subtarget->genExecuteOnly()) {
3054     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3055     auto T = const_cast<Type*>(CP->getType());
3056     auto C = const_cast<Constant*>(CP->getConstVal());
3057     auto M = const_cast<Module*>(DAG.getMachineFunction().
3058                                  getFunction().getParent());
3059     auto GV = new GlobalVariable(
3060                     *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3061                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3062                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3063                     Twine(AFI->createPICLabelUId())
3064                   );
3065     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3066                                             dl, PtrVT);
3067     return LowerGlobalAddress(GA, DAG);
3068   }
3069 
3070   if (CP->isMachineConstantPoolEntry())
3071     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
3072                                     CP->getAlignment());
3073   else
3074     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
3075                                     CP->getAlignment());
3076   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3077 }
3078 
3079 unsigned ARMTargetLowering::getJumpTableEncoding() const {
3080   return MachineJumpTableInfo::EK_Inline;
3081 }
3082 
3083 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3084                                              SelectionDAG &DAG) const {
3085   MachineFunction &MF = DAG.getMachineFunction();
3086   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3087   unsigned ARMPCLabelIndex = 0;
3088   SDLoc DL(Op);
3089   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3090   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3091   SDValue CPAddr;
3092   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3093   if (!IsPositionIndependent) {
3094     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
3095   } else {
3096     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3097     ARMPCLabelIndex = AFI->createPICLabelUId();
3098     ARMConstantPoolValue *CPV =
3099       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3100                                       ARMCP::CPBlockAddress, PCAdj);
3101     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3102   }
3103   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3104   SDValue Result = DAG.getLoad(
3105       PtrVT, DL, DAG.getEntryNode(), CPAddr,
3106       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3107   if (!IsPositionIndependent)
3108     return Result;
3109   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3110   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3111 }
3112 
3113 /// Convert a TLS address reference into the correct sequence of loads
3114 /// and calls to compute the variable's address for Darwin, and return an
3115 /// SDValue containing the final node.
3116 
3117 /// Darwin only has one TLS scheme which must be capable of dealing with the
3118 /// fully general situation, in the worst case. This means:
3119 ///     + "extern __thread" declaration.
3120 ///     + Defined in a possibly unknown dynamic library.
3121 ///
3122 /// The general system is that each __thread variable has a [3 x i32] descriptor
3123 /// which contains information used by the runtime to calculate the address. The
3124 /// only part of this the compiler needs to know about is the first word, which
3125 /// contains a function pointer that must be called with the address of the
3126 /// entire descriptor in "r0".
3127 ///
3128 /// Since this descriptor may be in a different unit, in general access must
3129 /// proceed along the usual ARM rules. A common sequence to produce is:
3130 ///
3131 ///     movw rT1, :lower16:_var$non_lazy_ptr
3132 ///     movt rT1, :upper16:_var$non_lazy_ptr
3133 ///     ldr r0, [rT1]
3134 ///     ldr rT2, [r0]
3135 ///     blx rT2
3136 ///     [...address now in r0...]
3137 SDValue
3138 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3139                                                SelectionDAG &DAG) const {
3140   assert(Subtarget->isTargetDarwin() &&
3141          "This function expects a Darwin target");
3142   SDLoc DL(Op);
3143 
3144   // First step is to get the address of the actua global symbol. This is where
3145   // the TLS descriptor lives.
3146   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3147 
3148   // The first entry in the descriptor is a function pointer that we must call
3149   // to obtain the address of the variable.
3150   SDValue Chain = DAG.getEntryNode();
3151   SDValue FuncTLVGet = DAG.getLoad(
3152       MVT::i32, DL, Chain, DescAddr,
3153       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3154       /* Alignment = */ 4,
3155       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3156           MachineMemOperand::MOInvariant);
3157   Chain = FuncTLVGet.getValue(1);
3158 
3159   MachineFunction &F = DAG.getMachineFunction();
3160   MachineFrameInfo &MFI = F.getFrameInfo();
3161   MFI.setAdjustsStack(true);
3162 
3163   // TLS calls preserve all registers except those that absolutely must be
3164   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3165   // silly).
3166   auto TRI =
3167       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3168   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3169   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3170 
3171   // Finally, we can make the call. This is just a degenerate version of a
3172   // normal AArch64 call node: r0 takes the address of the descriptor, and
3173   // returns the address of the variable in this thread.
3174   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3175   Chain =
3176       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3177                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3178                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3179   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3180 }
3181 
3182 SDValue
3183 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3184                                                 SelectionDAG &DAG) const {
3185   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3186 
3187   SDValue Chain = DAG.getEntryNode();
3188   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3189   SDLoc DL(Op);
3190 
3191   // Load the current TEB (thread environment block)
3192   SDValue Ops[] = {Chain,
3193                    DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3194                    DAG.getTargetConstant(15, DL, MVT::i32),
3195                    DAG.getTargetConstant(0, DL, MVT::i32),
3196                    DAG.getTargetConstant(13, DL, MVT::i32),
3197                    DAG.getTargetConstant(0, DL, MVT::i32),
3198                    DAG.getTargetConstant(2, DL, MVT::i32)};
3199   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3200                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
3201 
3202   SDValue TEB = CurrentTEB.getValue(0);
3203   Chain = CurrentTEB.getValue(1);
3204 
3205   // Load the ThreadLocalStoragePointer from the TEB
3206   // A pointer to the TLS array is located at offset 0x2c from the TEB.
3207   SDValue TLSArray =
3208       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3209   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3210 
3211   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3212   // offset into the TLSArray.
3213 
3214   // Load the TLS index from the C runtime
3215   SDValue TLSIndex =
3216       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3217   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3218   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3219 
3220   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3221                               DAG.getConstant(2, DL, MVT::i32));
3222   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3223                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3224                             MachinePointerInfo());
3225 
3226   // Get the offset of the start of the .tls section (section base)
3227   const auto *GA = cast<GlobalAddressSDNode>(Op);
3228   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3229   SDValue Offset = DAG.getLoad(
3230       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3231                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3232       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3233 
3234   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3235 }
3236 
3237 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3238 SDValue
3239 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3240                                                  SelectionDAG &DAG) const {
3241   SDLoc dl(GA);
3242   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3243   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3244   MachineFunction &MF = DAG.getMachineFunction();
3245   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3246   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3247   ARMConstantPoolValue *CPV =
3248     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3249                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3250   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3251   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3252   Argument = DAG.getLoad(
3253       PtrVT, dl, DAG.getEntryNode(), Argument,
3254       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3255   SDValue Chain = Argument.getValue(1);
3256 
3257   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3258   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3259 
3260   // call __tls_get_addr.
3261   ArgListTy Args;
3262   ArgListEntry Entry;
3263   Entry.Node = Argument;
3264   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3265   Args.push_back(Entry);
3266 
3267   // FIXME: is there useful debug info available here?
3268   TargetLowering::CallLoweringInfo CLI(DAG);
3269   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3270       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3271       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3272 
3273   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3274   return CallResult.first;
3275 }
3276 
3277 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3278 // "local exec" model.
3279 SDValue
3280 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3281                                         SelectionDAG &DAG,
3282                                         TLSModel::Model model) const {
3283   const GlobalValue *GV = GA->getGlobal();
3284   SDLoc dl(GA);
3285   SDValue Offset;
3286   SDValue Chain = DAG.getEntryNode();
3287   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3288   // Get the Thread Pointer
3289   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3290 
3291   if (model == TLSModel::InitialExec) {
3292     MachineFunction &MF = DAG.getMachineFunction();
3293     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3294     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3295     // Initial exec model.
3296     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3297     ARMConstantPoolValue *CPV =
3298       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3299                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3300                                       true);
3301     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3302     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3303     Offset = DAG.getLoad(
3304         PtrVT, dl, Chain, Offset,
3305         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3306     Chain = Offset.getValue(1);
3307 
3308     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3309     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3310 
3311     Offset = DAG.getLoad(
3312         PtrVT, dl, Chain, Offset,
3313         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3314   } else {
3315     // local exec model
3316     assert(model == TLSModel::LocalExec);
3317     ARMConstantPoolValue *CPV =
3318       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3319     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3320     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3321     Offset = DAG.getLoad(
3322         PtrVT, dl, Chain, Offset,
3323         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3324   }
3325 
3326   // The address of the thread local variable is the add of the thread
3327   // pointer with the offset of the variable.
3328   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3329 }
3330 
3331 SDValue
3332 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3333   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3334   if (DAG.getTarget().useEmulatedTLS())
3335     return LowerToTLSEmulatedModel(GA, DAG);
3336 
3337   if (Subtarget->isTargetDarwin())
3338     return LowerGlobalTLSAddressDarwin(Op, DAG);
3339 
3340   if (Subtarget->isTargetWindows())
3341     return LowerGlobalTLSAddressWindows(Op, DAG);
3342 
3343   // TODO: implement the "local dynamic" model
3344   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3345   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3346 
3347   switch (model) {
3348     case TLSModel::GeneralDynamic:
3349     case TLSModel::LocalDynamic:
3350       return LowerToTLSGeneralDynamicModel(GA, DAG);
3351     case TLSModel::InitialExec:
3352     case TLSModel::LocalExec:
3353       return LowerToTLSExecModels(GA, DAG, model);
3354   }
3355   llvm_unreachable("bogus TLS model");
3356 }
3357 
3358 /// Return true if all users of V are within function F, looking through
3359 /// ConstantExprs.
3360 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3361   SmallVector<const User*,4> Worklist;
3362   for (auto *U : V->users())
3363     Worklist.push_back(U);
3364   while (!Worklist.empty()) {
3365     auto *U = Worklist.pop_back_val();
3366     if (isa<ConstantExpr>(U)) {
3367       for (auto *UU : U->users())
3368         Worklist.push_back(UU);
3369       continue;
3370     }
3371 
3372     auto *I = dyn_cast<Instruction>(U);
3373     if (!I || I->getParent()->getParent() != F)
3374       return false;
3375   }
3376   return true;
3377 }
3378 
3379 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3380                                      const GlobalValue *GV, SelectionDAG &DAG,
3381                                      EVT PtrVT, const SDLoc &dl) {
3382   // If we're creating a pool entry for a constant global with unnamed address,
3383   // and the global is small enough, we can emit it inline into the constant pool
3384   // to save ourselves an indirection.
3385   //
3386   // This is a win if the constant is only used in one function (so it doesn't
3387   // need to be duplicated) or duplicating the constant wouldn't increase code
3388   // size (implying the constant is no larger than 4 bytes).
3389   const Function &F = DAG.getMachineFunction().getFunction();
3390 
3391   // We rely on this decision to inline being idemopotent and unrelated to the
3392   // use-site. We know that if we inline a variable at one use site, we'll
3393   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3394   // doesn't know about this optimization, so bail out if it's enabled else
3395   // we could decide to inline here (and thus never emit the GV) but require
3396   // the GV from fast-isel generated code.
3397   if (!EnableConstpoolPromotion ||
3398       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3399       return SDValue();
3400 
3401   auto *GVar = dyn_cast<GlobalVariable>(GV);
3402   if (!GVar || !GVar->hasInitializer() ||
3403       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3404       !GVar->hasLocalLinkage())
3405     return SDValue();
3406 
3407   // If we inline a value that contains relocations, we move the relocations
3408   // from .data to .text. This is not allowed in position-independent code.
3409   auto *Init = GVar->getInitializer();
3410   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3411       Init->needsRelocation())
3412     return SDValue();
3413 
3414   // The constant islands pass can only really deal with alignment requests
3415   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3416   // any type wanting greater alignment requirements than 4 bytes. We also
3417   // can only promote constants that are multiples of 4 bytes in size or
3418   // are paddable to a multiple of 4. Currently we only try and pad constants
3419   // that are strings for simplicity.
3420   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3421   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3422   unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3423   unsigned RequiredPadding = 4 - (Size % 4);
3424   bool PaddingPossible =
3425     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3426   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3427       Size == 0)
3428     return SDValue();
3429 
3430   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3431   MachineFunction &MF = DAG.getMachineFunction();
3432   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3433 
3434   // We can't bloat the constant pool too much, else the ConstantIslands pass
3435   // may fail to converge. If we haven't promoted this global yet (it may have
3436   // multiple uses), and promoting it would increase the constant pool size (Sz
3437   // > 4), ensure we have space to do so up to MaxTotal.
3438   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3439     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3440         ConstpoolPromotionMaxTotal)
3441       return SDValue();
3442 
3443   // This is only valid if all users are in a single function; we can't clone
3444   // the constant in general. The LLVM IR unnamed_addr allows merging
3445   // constants, but not cloning them.
3446   //
3447   // We could potentially allow cloning if we could prove all uses of the
3448   // constant in the current function don't care about the address, like
3449   // printf format strings. But that isn't implemented for now.
3450   if (!allUsersAreInFunction(GVar, &F))
3451     return SDValue();
3452 
3453   // We're going to inline this global. Pad it out if needed.
3454   if (RequiredPadding != 4) {
3455     StringRef S = CDAInit->getAsString();
3456 
3457     SmallVector<uint8_t,16> V(S.size());
3458     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3459     while (RequiredPadding--)
3460       V.push_back(0);
3461     Init = ConstantDataArray::get(*DAG.getContext(), V);
3462   }
3463 
3464   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3465   SDValue CPAddr =
3466     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3467   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3468     AFI->markGlobalAsPromotedToConstantPool(GVar);
3469     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3470                                       PaddedSize - 4);
3471   }
3472   ++NumConstpoolPromoted;
3473   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3474 }
3475 
3476 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3477   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3478     if (!(GV = GA->getBaseObject()))
3479       return false;
3480   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3481     return V->isConstant();
3482   return isa<Function>(GV);
3483 }
3484 
3485 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3486                                               SelectionDAG &DAG) const {
3487   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3488   default: llvm_unreachable("unknown object format");
3489   case Triple::COFF:
3490     return LowerGlobalAddressWindows(Op, DAG);
3491   case Triple::ELF:
3492     return LowerGlobalAddressELF(Op, DAG);
3493   case Triple::MachO:
3494     return LowerGlobalAddressDarwin(Op, DAG);
3495   }
3496 }
3497 
3498 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3499                                                  SelectionDAG &DAG) const {
3500   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3501   SDLoc dl(Op);
3502   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3503   const TargetMachine &TM = getTargetMachine();
3504   bool IsRO = isReadOnly(GV);
3505 
3506   // promoteToConstantPool only if not generating XO text section
3507   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3508     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3509       return V;
3510 
3511   if (isPositionIndependent()) {
3512     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3513     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3514                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3515     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3516     if (UseGOT_PREL)
3517       Result =
3518           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3519                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3520     return Result;
3521   } else if (Subtarget->isROPI() && IsRO) {
3522     // PC-relative.
3523     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3524     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3525     return Result;
3526   } else if (Subtarget->isRWPI() && !IsRO) {
3527     // SB-relative.
3528     SDValue RelAddr;
3529     if (Subtarget->useMovt()) {
3530       ++NumMovwMovt;
3531       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3532       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3533     } else { // use literal pool for address constant
3534       ARMConstantPoolValue *CPV =
3535         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3536       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3537       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3538       RelAddr = DAG.getLoad(
3539           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3540           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3541     }
3542     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3543     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3544     return Result;
3545   }
3546 
3547   // If we have T2 ops, we can materialize the address directly via movt/movw
3548   // pair. This is always cheaper.
3549   if (Subtarget->useMovt()) {
3550     ++NumMovwMovt;
3551     // FIXME: Once remat is capable of dealing with instructions with register
3552     // operands, expand this into two nodes.
3553     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3554                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3555   } else {
3556     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3557     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3558     return DAG.getLoad(
3559         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3560         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3561   }
3562 }
3563 
3564 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3565                                                     SelectionDAG &DAG) const {
3566   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3567          "ROPI/RWPI not currently supported for Darwin");
3568   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3569   SDLoc dl(Op);
3570   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3571 
3572   if (Subtarget->useMovt())
3573     ++NumMovwMovt;
3574 
3575   // FIXME: Once remat is capable of dealing with instructions with register
3576   // operands, expand this into multiple nodes
3577   unsigned Wrapper =
3578       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3579 
3580   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3581   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3582 
3583   if (Subtarget->isGVIndirectSymbol(GV))
3584     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3585                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3586   return Result;
3587 }
3588 
3589 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3590                                                      SelectionDAG &DAG) const {
3591   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3592   assert(Subtarget->useMovt() &&
3593          "Windows on ARM expects to use movw/movt");
3594   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3595          "ROPI/RWPI not currently supported for Windows");
3596 
3597   const TargetMachine &TM = getTargetMachine();
3598   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3599   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3600   if (GV->hasDLLImportStorageClass())
3601     TargetFlags = ARMII::MO_DLLIMPORT;
3602   else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3603     TargetFlags = ARMII::MO_COFFSTUB;
3604   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3605   SDValue Result;
3606   SDLoc DL(Op);
3607 
3608   ++NumMovwMovt;
3609 
3610   // FIXME: Once remat is capable of dealing with instructions with register
3611   // operands, expand this into two nodes.
3612   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3613                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3614                                                   TargetFlags));
3615   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3616     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3617                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3618   return Result;
3619 }
3620 
3621 SDValue
3622 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3623   SDLoc dl(Op);
3624   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3625   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3626                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3627                      Op.getOperand(1), Val);
3628 }
3629 
3630 SDValue
3631 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3632   SDLoc dl(Op);
3633   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3634                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3635 }
3636 
3637 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3638                                                       SelectionDAG &DAG) const {
3639   SDLoc dl(Op);
3640   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3641                      Op.getOperand(0));
3642 }
3643 
3644 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3645     SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3646   unsigned IntNo =
3647       cast<ConstantSDNode>(
3648           Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3649           ->getZExtValue();
3650   switch (IntNo) {
3651     default:
3652       return SDValue();  // Don't custom lower most intrinsics.
3653     case Intrinsic::arm_gnu_eabi_mcount: {
3654       MachineFunction &MF = DAG.getMachineFunction();
3655       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3656       SDLoc dl(Op);
3657       SDValue Chain = Op.getOperand(0);
3658       // call "\01__gnu_mcount_nc"
3659       const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3660       const uint32_t *Mask =
3661           ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3662       assert(Mask && "Missing call preserved mask for calling convention");
3663       // Mark LR an implicit live-in.
3664       unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3665       SDValue ReturnAddress =
3666           DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3667       constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3668       SDValue Callee =
3669           DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3670       SDValue RegisterMask = DAG.getRegisterMask(Mask);
3671       if (Subtarget->isThumb())
3672         return SDValue(
3673             DAG.getMachineNode(
3674                 ARM::tBL_PUSHLR, dl, ResultTys,
3675                 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3676                  DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3677             0);
3678       return SDValue(
3679           DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3680                              {ReturnAddress, Callee, RegisterMask, Chain}),
3681           0);
3682     }
3683   }
3684 }
3685 
3686 SDValue
3687 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3688                                           const ARMSubtarget *Subtarget) const {
3689   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3690   SDLoc dl(Op);
3691   switch (IntNo) {
3692   default: return SDValue();    // Don't custom lower most intrinsics.
3693   case Intrinsic::thread_pointer: {
3694     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3695     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3696   }
3697   case Intrinsic::arm_cls: {
3698     const SDValue &Operand = Op.getOperand(1);
3699     const EVT VTy = Op.getValueType();
3700     SDValue SRA =
3701         DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
3702     SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
3703     SDValue SHL =
3704         DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
3705     SDValue OR =
3706         DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
3707     SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
3708     return Result;
3709   }
3710   case Intrinsic::arm_cls64: {
3711     // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
3712     //          else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
3713     const SDValue &Operand = Op.getOperand(1);
3714     const EVT VTy = Op.getValueType();
3715 
3716     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3717                              DAG.getConstant(1, dl, VTy));
3718     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3719                              DAG.getConstant(0, dl, VTy));
3720     SDValue Constant0 = DAG.getConstant(0, dl, VTy);
3721     SDValue Constant1 = DAG.getConstant(1, dl, VTy);
3722     SDValue Constant31 = DAG.getConstant(31, dl, VTy);
3723     SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
3724     SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
3725     SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
3726     SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
3727     SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
3728     SDValue CheckLo =
3729         DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
3730     SDValue HiIsZero =
3731         DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
3732     SDValue AdjustedLo =
3733         DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
3734     SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
3735     SDValue Result =
3736         DAG.getSelect(dl, VTy, CheckLo,
3737                       DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
3738     return Result;
3739   }
3740   case Intrinsic::eh_sjlj_lsda: {
3741     MachineFunction &MF = DAG.getMachineFunction();
3742     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3743     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3744     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3745     SDValue CPAddr;
3746     bool IsPositionIndependent = isPositionIndependent();
3747     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3748     ARMConstantPoolValue *CPV =
3749       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3750                                       ARMCP::CPLSDA, PCAdj);
3751     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3752     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3753     SDValue Result = DAG.getLoad(
3754         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3755         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3756 
3757     if (IsPositionIndependent) {
3758       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3759       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3760     }
3761     return Result;
3762   }
3763   case Intrinsic::arm_neon_vabs:
3764     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3765                         Op.getOperand(1));
3766   case Intrinsic::arm_neon_vmulls:
3767   case Intrinsic::arm_neon_vmullu: {
3768     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3769       ? ARMISD::VMULLs : ARMISD::VMULLu;
3770     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3771                        Op.getOperand(1), Op.getOperand(2));
3772   }
3773   case Intrinsic::arm_neon_vminnm:
3774   case Intrinsic::arm_neon_vmaxnm: {
3775     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3776       ? ISD::FMINNUM : ISD::FMAXNUM;
3777     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3778                        Op.getOperand(1), Op.getOperand(2));
3779   }
3780   case Intrinsic::arm_neon_vminu:
3781   case Intrinsic::arm_neon_vmaxu: {
3782     if (Op.getValueType().isFloatingPoint())
3783       return SDValue();
3784     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3785       ? ISD::UMIN : ISD::UMAX;
3786     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3787                          Op.getOperand(1), Op.getOperand(2));
3788   }
3789   case Intrinsic::arm_neon_vmins:
3790   case Intrinsic::arm_neon_vmaxs: {
3791     // v{min,max}s is overloaded between signed integers and floats.
3792     if (!Op.getValueType().isFloatingPoint()) {
3793       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3794         ? ISD::SMIN : ISD::SMAX;
3795       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3796                          Op.getOperand(1), Op.getOperand(2));
3797     }
3798     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3799       ? ISD::FMINIMUM : ISD::FMAXIMUM;
3800     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3801                        Op.getOperand(1), Op.getOperand(2));
3802   }
3803   case Intrinsic::arm_neon_vtbl1:
3804     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3805                        Op.getOperand(1), Op.getOperand(2));
3806   case Intrinsic::arm_neon_vtbl2:
3807     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3808                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3809   case Intrinsic::arm_mve_pred_i2v:
3810   case Intrinsic::arm_mve_pred_v2i:
3811     return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
3812                        Op.getOperand(1));
3813   case Intrinsic::arm_mve_vreinterpretq:
3814     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
3815                        Op.getOperand(1));
3816   case Intrinsic::arm_mve_lsll:
3817     return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
3818                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3819   case Intrinsic::arm_mve_asrl:
3820     return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
3821                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3822   }
3823 }
3824 
3825 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3826                                  const ARMSubtarget *Subtarget) {
3827   SDLoc dl(Op);
3828   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3829   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3830   if (SSID == SyncScope::SingleThread)
3831     return Op;
3832 
3833   if (!Subtarget->hasDataBarrier()) {
3834     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3835     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3836     // here.
3837     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3838            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3839     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3840                        DAG.getConstant(0, dl, MVT::i32));
3841   }
3842 
3843   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3844   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3845   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3846   if (Subtarget->isMClass()) {
3847     // Only a full system barrier exists in the M-class architectures.
3848     Domain = ARM_MB::SY;
3849   } else if (Subtarget->preferISHSTBarriers() &&
3850              Ord == AtomicOrdering::Release) {
3851     // Swift happens to implement ISHST barriers in a way that's compatible with
3852     // Release semantics but weaker than ISH so we'd be fools not to use
3853     // it. Beware: other processors probably don't!
3854     Domain = ARM_MB::ISHST;
3855   }
3856 
3857   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3858                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3859                      DAG.getConstant(Domain, dl, MVT::i32));
3860 }
3861 
3862 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3863                              const ARMSubtarget *Subtarget) {
3864   // ARM pre v5TE and Thumb1 does not have preload instructions.
3865   if (!(Subtarget->isThumb2() ||
3866         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3867     // Just preserve the chain.
3868     return Op.getOperand(0);
3869 
3870   SDLoc dl(Op);
3871   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3872   if (!isRead &&
3873       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3874     // ARMv7 with MP extension has PLDW.
3875     return Op.getOperand(0);
3876 
3877   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3878   if (Subtarget->isThumb()) {
3879     // Invert the bits.
3880     isRead = ~isRead & 1;
3881     isData = ~isData & 1;
3882   }
3883 
3884   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3885                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3886                      DAG.getConstant(isData, dl, MVT::i32));
3887 }
3888 
3889 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3890   MachineFunction &MF = DAG.getMachineFunction();
3891   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3892 
3893   // vastart just stores the address of the VarArgsFrameIndex slot into the
3894   // memory location argument.
3895   SDLoc dl(Op);
3896   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3897   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3898   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3899   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3900                       MachinePointerInfo(SV));
3901 }
3902 
3903 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3904                                                 CCValAssign &NextVA,
3905                                                 SDValue &Root,
3906                                                 SelectionDAG &DAG,
3907                                                 const SDLoc &dl) const {
3908   MachineFunction &MF = DAG.getMachineFunction();
3909   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3910 
3911   const TargetRegisterClass *RC;
3912   if (AFI->isThumb1OnlyFunction())
3913     RC = &ARM::tGPRRegClass;
3914   else
3915     RC = &ARM::GPRRegClass;
3916 
3917   // Transform the arguments stored in physical registers into virtual ones.
3918   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3919   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3920 
3921   SDValue ArgValue2;
3922   if (NextVA.isMemLoc()) {
3923     MachineFrameInfo &MFI = MF.getFrameInfo();
3924     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3925 
3926     // Create load node to retrieve arguments from the stack.
3927     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3928     ArgValue2 = DAG.getLoad(
3929         MVT::i32, dl, Root, FIN,
3930         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3931   } else {
3932     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3933     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3934   }
3935   if (!Subtarget->isLittle())
3936     std::swap (ArgValue, ArgValue2);
3937   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3938 }
3939 
3940 // The remaining GPRs hold either the beginning of variable-argument
3941 // data, or the beginning of an aggregate passed by value (usually
3942 // byval).  Either way, we allocate stack slots adjacent to the data
3943 // provided by our caller, and store the unallocated registers there.
3944 // If this is a variadic function, the va_list pointer will begin with
3945 // these values; otherwise, this reassembles a (byval) structure that
3946 // was split between registers and memory.
3947 // Return: The frame index registers were stored into.
3948 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3949                                       const SDLoc &dl, SDValue &Chain,
3950                                       const Value *OrigArg,
3951                                       unsigned InRegsParamRecordIdx,
3952                                       int ArgOffset, unsigned ArgSize) const {
3953   // Currently, two use-cases possible:
3954   // Case #1. Non-var-args function, and we meet first byval parameter.
3955   //          Setup first unallocated register as first byval register;
3956   //          eat all remained registers
3957   //          (these two actions are performed by HandleByVal method).
3958   //          Then, here, we initialize stack frame with
3959   //          "store-reg" instructions.
3960   // Case #2. Var-args function, that doesn't contain byval parameters.
3961   //          The same: eat all remained unallocated registers,
3962   //          initialize stack frame.
3963 
3964   MachineFunction &MF = DAG.getMachineFunction();
3965   MachineFrameInfo &MFI = MF.getFrameInfo();
3966   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3967   unsigned RBegin, REnd;
3968   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3969     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3970   } else {
3971     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3972     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3973     REnd = ARM::R4;
3974   }
3975 
3976   if (REnd != RBegin)
3977     ArgOffset = -4 * (ARM::R4 - RBegin);
3978 
3979   auto PtrVT = getPointerTy(DAG.getDataLayout());
3980   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3981   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3982 
3983   SmallVector<SDValue, 4> MemOps;
3984   const TargetRegisterClass *RC =
3985       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3986 
3987   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3988     unsigned VReg = MF.addLiveIn(Reg, RC);
3989     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3990     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3991                                  MachinePointerInfo(OrigArg, 4 * i));
3992     MemOps.push_back(Store);
3993     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3994   }
3995 
3996   if (!MemOps.empty())
3997     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3998   return FrameIndex;
3999 }
4000 
4001 // Setup stack frame, the va_list pointer will start from.
4002 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4003                                              const SDLoc &dl, SDValue &Chain,
4004                                              unsigned ArgOffset,
4005                                              unsigned TotalArgRegsSaveSize,
4006                                              bool ForceMutable) const {
4007   MachineFunction &MF = DAG.getMachineFunction();
4008   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4009 
4010   // Try to store any remaining integer argument regs
4011   // to their spots on the stack so that they may be loaded by dereferencing
4012   // the result of va_next.
4013   // If there is no regs to be stored, just point address after last
4014   // argument passed via stack.
4015   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
4016                                   CCInfo.getInRegsParamsCount(),
4017                                   CCInfo.getNextStackOffset(),
4018                                   std::max(4U, TotalArgRegsSaveSize));
4019   AFI->setVarArgsFrameIndex(FrameIndex);
4020 }
4021 
4022 SDValue ARMTargetLowering::LowerFormalArguments(
4023     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4024     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4025     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4026   MachineFunction &MF = DAG.getMachineFunction();
4027   MachineFrameInfo &MFI = MF.getFrameInfo();
4028 
4029   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4030 
4031   // Assign locations to all of the incoming arguments.
4032   SmallVector<CCValAssign, 16> ArgLocs;
4033   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4034                  *DAG.getContext());
4035   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4036 
4037   SmallVector<SDValue, 16> ArgValues;
4038   SDValue ArgValue;
4039   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4040   unsigned CurArgIdx = 0;
4041 
4042   // Initially ArgRegsSaveSize is zero.
4043   // Then we increase this value each time we meet byval parameter.
4044   // We also increase this value in case of varargs function.
4045   AFI->setArgRegsSaveSize(0);
4046 
4047   // Calculate the amount of stack space that we need to allocate to store
4048   // byval and variadic arguments that are passed in registers.
4049   // We need to know this before we allocate the first byval or variadic
4050   // argument, as they will be allocated a stack slot below the CFA (Canonical
4051   // Frame Address, the stack pointer at entry to the function).
4052   unsigned ArgRegBegin = ARM::R4;
4053   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4054     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4055       break;
4056 
4057     CCValAssign &VA = ArgLocs[i];
4058     unsigned Index = VA.getValNo();
4059     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4060     if (!Flags.isByVal())
4061       continue;
4062 
4063     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4064     unsigned RBegin, REnd;
4065     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4066     ArgRegBegin = std::min(ArgRegBegin, RBegin);
4067 
4068     CCInfo.nextInRegsParam();
4069   }
4070   CCInfo.rewindByValRegsInfo();
4071 
4072   int lastInsIndex = -1;
4073   if (isVarArg && MFI.hasVAStart()) {
4074     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4075     if (RegIdx != array_lengthof(GPRArgRegs))
4076       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4077   }
4078 
4079   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4080   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4081   auto PtrVT = getPointerTy(DAG.getDataLayout());
4082 
4083   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4084     CCValAssign &VA = ArgLocs[i];
4085     if (Ins[VA.getValNo()].isOrigArg()) {
4086       std::advance(CurOrigArg,
4087                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4088       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4089     }
4090     // Arguments stored in registers.
4091     if (VA.isRegLoc()) {
4092       EVT RegVT = VA.getLocVT();
4093 
4094       if (VA.needsCustom()) {
4095         // f64 and vector types are split up into multiple registers or
4096         // combinations of registers and stack slots.
4097         if (VA.getLocVT() == MVT::v2f64) {
4098           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
4099                                                    Chain, DAG, dl);
4100           VA = ArgLocs[++i]; // skip ahead to next loc
4101           SDValue ArgValue2;
4102           if (VA.isMemLoc()) {
4103             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4104             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4105             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
4106                                     MachinePointerInfo::getFixedStack(
4107                                         DAG.getMachineFunction(), FI));
4108           } else {
4109             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
4110                                              Chain, DAG, dl);
4111           }
4112           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4113           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
4114                                  ArgValue, ArgValue1,
4115                                  DAG.getIntPtrConstant(0, dl));
4116           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
4117                                  ArgValue, ArgValue2,
4118                                  DAG.getIntPtrConstant(1, dl));
4119         } else
4120           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4121       } else {
4122         const TargetRegisterClass *RC;
4123 
4124 
4125         if (RegVT == MVT::f16)
4126           RC = &ARM::HPRRegClass;
4127         else if (RegVT == MVT::f32)
4128           RC = &ARM::SPRRegClass;
4129         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
4130           RC = &ARM::DPRRegClass;
4131         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
4132           RC = &ARM::QPRRegClass;
4133         else if (RegVT == MVT::i32)
4134           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4135                                            : &ARM::GPRRegClass;
4136         else
4137           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4138 
4139         // Transform the arguments in physical registers into virtual ones.
4140         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4141         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4142 
4143         // If this value is passed in r0 and has the returned attribute (e.g.
4144         // C++ 'structors), record this fact for later use.
4145         if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4146           AFI->setPreservesR0();
4147         }
4148       }
4149 
4150       // If this is an 8 or 16-bit value, it is really passed promoted
4151       // to 32 bits.  Insert an assert[sz]ext to capture this, then
4152       // truncate to the right size.
4153       switch (VA.getLocInfo()) {
4154       default: llvm_unreachable("Unknown loc info!");
4155       case CCValAssign::Full: break;
4156       case CCValAssign::BCvt:
4157         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4158         break;
4159       case CCValAssign::SExt:
4160         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4161                                DAG.getValueType(VA.getValVT()));
4162         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4163         break;
4164       case CCValAssign::ZExt:
4165         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4166                                DAG.getValueType(VA.getValVT()));
4167         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4168         break;
4169       }
4170 
4171       InVals.push_back(ArgValue);
4172     } else { // VA.isRegLoc()
4173       // sanity check
4174       assert(VA.isMemLoc());
4175       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4176 
4177       int index = VA.getValNo();
4178 
4179       // Some Ins[] entries become multiple ArgLoc[] entries.
4180       // Process them only once.
4181       if (index != lastInsIndex)
4182         {
4183           ISD::ArgFlagsTy Flags = Ins[index].Flags;
4184           // FIXME: For now, all byval parameter objects are marked mutable.
4185           // This can be changed with more analysis.
4186           // In case of tail call optimization mark all arguments mutable.
4187           // Since they could be overwritten by lowering of arguments in case of
4188           // a tail call.
4189           if (Flags.isByVal()) {
4190             assert(Ins[index].isOrigArg() &&
4191                    "Byval arguments cannot be implicit");
4192             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4193 
4194             int FrameIndex = StoreByValRegs(
4195                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4196                 VA.getLocMemOffset(), Flags.getByValSize());
4197             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4198             CCInfo.nextInRegsParam();
4199           } else {
4200             unsigned FIOffset = VA.getLocMemOffset();
4201             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4202                                            FIOffset, true);
4203 
4204             // Create load nodes to retrieve arguments from the stack.
4205             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4206             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4207                                          MachinePointerInfo::getFixedStack(
4208                                              DAG.getMachineFunction(), FI)));
4209           }
4210           lastInsIndex = index;
4211         }
4212     }
4213   }
4214 
4215   // varargs
4216   if (isVarArg && MFI.hasVAStart())
4217     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4218                          CCInfo.getNextStackOffset(),
4219                          TotalArgRegsSaveSize);
4220 
4221   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4222 
4223   return Chain;
4224 }
4225 
4226 /// isFloatingPointZero - Return true if this is +0.0.
4227 static bool isFloatingPointZero(SDValue Op) {
4228   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4229     return CFP->getValueAPF().isPosZero();
4230   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4231     // Maybe this has already been legalized into the constant pool?
4232     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4233       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4234       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4235         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4236           return CFP->getValueAPF().isPosZero();
4237     }
4238   } else if (Op->getOpcode() == ISD::BITCAST &&
4239              Op->getValueType(0) == MVT::f64) {
4240     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4241     // created by LowerConstantFP().
4242     SDValue BitcastOp = Op->getOperand(0);
4243     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4244         isNullConstant(BitcastOp->getOperand(0)))
4245       return true;
4246   }
4247   return false;
4248 }
4249 
4250 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4251 /// the given operands.
4252 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4253                                      SDValue &ARMcc, SelectionDAG &DAG,
4254                                      const SDLoc &dl) const {
4255   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4256     unsigned C = RHSC->getZExtValue();
4257     if (!isLegalICmpImmediate((int32_t)C)) {
4258       // Constant does not fit, try adjusting it by one.
4259       switch (CC) {
4260       default: break;
4261       case ISD::SETLT:
4262       case ISD::SETGE:
4263         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4264           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4265           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4266         }
4267         break;
4268       case ISD::SETULT:
4269       case ISD::SETUGE:
4270         if (C != 0 && isLegalICmpImmediate(C-1)) {
4271           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4272           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4273         }
4274         break;
4275       case ISD::SETLE:
4276       case ISD::SETGT:
4277         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4278           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4279           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4280         }
4281         break;
4282       case ISD::SETULE:
4283       case ISD::SETUGT:
4284         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4285           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4286           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4287         }
4288         break;
4289       }
4290     }
4291   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4292              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4293     // In ARM and Thumb-2, the compare instructions can shift their second
4294     // operand.
4295     CC = ISD::getSetCCSwappedOperands(CC);
4296     std::swap(LHS, RHS);
4297   }
4298 
4299   // Thumb1 has very limited immediate modes, so turning an "and" into a
4300   // shift can save multiple instructions.
4301   //
4302   // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4303   // into "((x << n) >> n)".  But that isn't necessarily profitable on its
4304   // own. If it's the operand to an unsigned comparison with an immediate,
4305   // we can eliminate one of the shifts: we transform
4306   // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4307   //
4308   // We avoid transforming cases which aren't profitable due to encoding
4309   // details:
4310   //
4311   // 1. C2 fits into the immediate field of a cmp, and the transformed version
4312   // would not; in that case, we're essentially trading one immediate load for
4313   // another.
4314   // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4315   // 3. C2 is zero; we have other code for this special case.
4316   //
4317   // FIXME: Figure out profitability for Thumb2; we usually can't save an
4318   // instruction, since the AND is always one instruction anyway, but we could
4319   // use narrow instructions in some cases.
4320   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4321       LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4322       LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4323       !isSignedIntSetCC(CC)) {
4324     unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4325     auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4326     uint64_t RHSV = RHSC->getZExtValue();
4327     if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4328       unsigned ShiftBits = countLeadingZeros(Mask);
4329       if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4330         SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4331         LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4332         RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4333       }
4334     }
4335   }
4336 
4337   // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4338   // single "lsls x, c+1".  The shift sets the "C" and "Z" flags the same
4339   // way a cmp would.
4340   // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4341   // some tweaks to the heuristics for the previous and->shift transform.
4342   // FIXME: Optimize cases where the LHS isn't a shift.
4343   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4344       isa<ConstantSDNode>(RHS) &&
4345       cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4346       CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4347       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4348     unsigned ShiftAmt =
4349       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4350     SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4351                                 DAG.getVTList(MVT::i32, MVT::i32),
4352                                 LHS.getOperand(0),
4353                                 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4354     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4355                                      Shift.getValue(1), SDValue());
4356     ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4357     return Chain.getValue(1);
4358   }
4359 
4360   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4361 
4362   // If the RHS is a constant zero then the V (overflow) flag will never be
4363   // set. This can allow us to simplify GE to PL or LT to MI, which can be
4364   // simpler for other passes (like the peephole optimiser) to deal with.
4365   if (isNullConstant(RHS)) {
4366     switch (CondCode) {
4367       default: break;
4368       case ARMCC::GE:
4369         CondCode = ARMCC::PL;
4370         break;
4371       case ARMCC::LT:
4372         CondCode = ARMCC::MI;
4373         break;
4374     }
4375   }
4376 
4377   ARMISD::NodeType CompareType;
4378   switch (CondCode) {
4379   default:
4380     CompareType = ARMISD::CMP;
4381     break;
4382   case ARMCC::EQ:
4383   case ARMCC::NE:
4384     // Uses only Z Flag
4385     CompareType = ARMISD::CMPZ;
4386     break;
4387   }
4388   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4389   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4390 }
4391 
4392 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4393 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4394                                      SelectionDAG &DAG, const SDLoc &dl,
4395                                      bool Signaling) const {
4396   assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4397   SDValue Cmp;
4398   if (!isFloatingPointZero(RHS))
4399     Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP,
4400                       dl, MVT::Glue, LHS, RHS);
4401   else
4402     Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0,
4403                       dl, MVT::Glue, LHS);
4404   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4405 }
4406 
4407 /// duplicateCmp - Glue values can have only one use, so this function
4408 /// duplicates a comparison node.
4409 SDValue
4410 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4411   unsigned Opc = Cmp.getOpcode();
4412   SDLoc DL(Cmp);
4413   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4414     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4415 
4416   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4417   Cmp = Cmp.getOperand(0);
4418   Opc = Cmp.getOpcode();
4419   if (Opc == ARMISD::CMPFP)
4420     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4421   else {
4422     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4423     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4424   }
4425   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4426 }
4427 
4428 // This function returns three things: the arithmetic computation itself
4429 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
4430 // comparison and the condition code define the case in which the arithmetic
4431 // computation *does not* overflow.
4432 std::pair<SDValue, SDValue>
4433 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4434                                  SDValue &ARMcc) const {
4435   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
4436 
4437   SDValue Value, OverflowCmp;
4438   SDValue LHS = Op.getOperand(0);
4439   SDValue RHS = Op.getOperand(1);
4440   SDLoc dl(Op);
4441 
4442   // FIXME: We are currently always generating CMPs because we don't support
4443   // generating CMN through the backend. This is not as good as the natural
4444   // CMP case because it causes a register dependency and cannot be folded
4445   // later.
4446 
4447   switch (Op.getOpcode()) {
4448   default:
4449     llvm_unreachable("Unknown overflow instruction!");
4450   case ISD::SADDO:
4451     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4452     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4453     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4454     break;
4455   case ISD::UADDO:
4456     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4457     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4458     // We do not use it in the USUBO case as Value may not be used.
4459     Value = DAG.getNode(ARMISD::ADDC, dl,
4460                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4461                 .getValue(0);
4462     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4463     break;
4464   case ISD::SSUBO:
4465     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4466     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4467     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4468     break;
4469   case ISD::USUBO:
4470     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4471     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4472     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4473     break;
4474   case ISD::UMULO:
4475     // We generate a UMUL_LOHI and then check if the high word is 0.
4476     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4477     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4478                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4479                         LHS, RHS);
4480     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4481                               DAG.getConstant(0, dl, MVT::i32));
4482     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4483     break;
4484   case ISD::SMULO:
4485     // We generate a SMUL_LOHI and then check if all the bits of the high word
4486     // are the same as the sign bit of the low word.
4487     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4488     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4489                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4490                         LHS, RHS);
4491     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4492                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4493                                           Value.getValue(0),
4494                                           DAG.getConstant(31, dl, MVT::i32)));
4495     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4496     break;
4497   } // switch (...)
4498 
4499   return std::make_pair(Value, OverflowCmp);
4500 }
4501 
4502 SDValue
4503 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4504   // Let legalize expand this if it isn't a legal type yet.
4505   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4506     return SDValue();
4507 
4508   SDValue Value, OverflowCmp;
4509   SDValue ARMcc;
4510   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4511   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4512   SDLoc dl(Op);
4513   // We use 0 and 1 as false and true values.
4514   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4515   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4516   EVT VT = Op.getValueType();
4517 
4518   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4519                                  ARMcc, CCR, OverflowCmp);
4520 
4521   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4522   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4523 }
4524 
4525 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4526                                               SelectionDAG &DAG) {
4527   SDLoc DL(BoolCarry);
4528   EVT CarryVT = BoolCarry.getValueType();
4529 
4530   // This converts the boolean value carry into the carry flag by doing
4531   // ARMISD::SUBC Carry, 1
4532   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4533                               DAG.getVTList(CarryVT, MVT::i32),
4534                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
4535   return Carry.getValue(1);
4536 }
4537 
4538 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4539                                               SelectionDAG &DAG) {
4540   SDLoc DL(Flags);
4541 
4542   // Now convert the carry flag into a boolean carry. We do this
4543   // using ARMISD:ADDE 0, 0, Carry
4544   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4545                      DAG.getConstant(0, DL, MVT::i32),
4546                      DAG.getConstant(0, DL, MVT::i32), Flags);
4547 }
4548 
4549 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4550                                              SelectionDAG &DAG) const {
4551   // Let legalize expand this if it isn't a legal type yet.
4552   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4553     return SDValue();
4554 
4555   SDValue LHS = Op.getOperand(0);
4556   SDValue RHS = Op.getOperand(1);
4557   SDLoc dl(Op);
4558 
4559   EVT VT = Op.getValueType();
4560   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4561   SDValue Value;
4562   SDValue Overflow;
4563   switch (Op.getOpcode()) {
4564   default:
4565     llvm_unreachable("Unknown overflow instruction!");
4566   case ISD::UADDO:
4567     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4568     // Convert the carry flag into a boolean value.
4569     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4570     break;
4571   case ISD::USUBO: {
4572     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4573     // Convert the carry flag into a boolean value.
4574     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4575     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4576     // value. So compute 1 - C.
4577     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4578                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4579     break;
4580   }
4581   }
4582 
4583   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4584 }
4585 
4586 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4587                                const ARMSubtarget *Subtarget) {
4588   EVT VT = Op.getValueType();
4589   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
4590     return SDValue();
4591   if (!VT.isSimple())
4592     return SDValue();
4593 
4594   unsigned NewOpcode;
4595   bool IsAdd = Op->getOpcode() == ISD::SADDSAT;
4596   switch (VT.getSimpleVT().SimpleTy) {
4597   default:
4598     return SDValue();
4599   case MVT::i8:
4600     NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b;
4601     break;
4602   case MVT::i16:
4603     NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b;
4604     break;
4605   }
4606 
4607   SDLoc dl(Op);
4608   SDValue Add =
4609       DAG.getNode(NewOpcode, dl, MVT::i32,
4610                   DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
4611                   DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
4612   return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
4613 }
4614 
4615 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4616   SDValue Cond = Op.getOperand(0);
4617   SDValue SelectTrue = Op.getOperand(1);
4618   SDValue SelectFalse = Op.getOperand(2);
4619   SDLoc dl(Op);
4620   unsigned Opc = Cond.getOpcode();
4621 
4622   if (Cond.getResNo() == 1 &&
4623       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4624        Opc == ISD::USUBO)) {
4625     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4626       return SDValue();
4627 
4628     SDValue Value, OverflowCmp;
4629     SDValue ARMcc;
4630     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4631     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4632     EVT VT = Op.getValueType();
4633 
4634     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4635                    OverflowCmp, DAG);
4636   }
4637 
4638   // Convert:
4639   //
4640   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4641   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4642   //
4643   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4644     const ConstantSDNode *CMOVTrue =
4645       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4646     const ConstantSDNode *CMOVFalse =
4647       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4648 
4649     if (CMOVTrue && CMOVFalse) {
4650       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4651       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4652 
4653       SDValue True;
4654       SDValue False;
4655       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4656         True = SelectTrue;
4657         False = SelectFalse;
4658       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4659         True = SelectFalse;
4660         False = SelectTrue;
4661       }
4662 
4663       if (True.getNode() && False.getNode()) {
4664         EVT VT = Op.getValueType();
4665         SDValue ARMcc = Cond.getOperand(2);
4666         SDValue CCR = Cond.getOperand(3);
4667         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4668         assert(True.getValueType() == VT);
4669         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4670       }
4671     }
4672   }
4673 
4674   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4675   // undefined bits before doing a full-word comparison with zero.
4676   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4677                      DAG.getConstant(1, dl, Cond.getValueType()));
4678 
4679   return DAG.getSelectCC(dl, Cond,
4680                          DAG.getConstant(0, dl, Cond.getValueType()),
4681                          SelectTrue, SelectFalse, ISD::SETNE);
4682 }
4683 
4684 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4685                                  bool &swpCmpOps, bool &swpVselOps) {
4686   // Start by selecting the GE condition code for opcodes that return true for
4687   // 'equality'
4688   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4689       CC == ISD::SETULE || CC == ISD::SETGE  || CC == ISD::SETLE)
4690     CondCode = ARMCC::GE;
4691 
4692   // and GT for opcodes that return false for 'equality'.
4693   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4694            CC == ISD::SETULT || CC == ISD::SETGT  || CC == ISD::SETLT)
4695     CondCode = ARMCC::GT;
4696 
4697   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4698   // to swap the compare operands.
4699   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4700       CC == ISD::SETULT || CC == ISD::SETLE  || CC == ISD::SETLT)
4701     swpCmpOps = true;
4702 
4703   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4704   // If we have an unordered opcode, we need to swap the operands to the VSEL
4705   // instruction (effectively negating the condition).
4706   //
4707   // This also has the effect of swapping which one of 'less' or 'greater'
4708   // returns true, so we also swap the compare operands. It also switches
4709   // whether we return true for 'equality', so we compensate by picking the
4710   // opposite condition code to our original choice.
4711   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4712       CC == ISD::SETUGT) {
4713     swpCmpOps = !swpCmpOps;
4714     swpVselOps = !swpVselOps;
4715     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4716   }
4717 
4718   // 'ordered' is 'anything but unordered', so use the VS condition code and
4719   // swap the VSEL operands.
4720   if (CC == ISD::SETO) {
4721     CondCode = ARMCC::VS;
4722     swpVselOps = true;
4723   }
4724 
4725   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4726   // code and swap the VSEL operands. Also do this if we don't care about the
4727   // unordered case.
4728   if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4729     CondCode = ARMCC::EQ;
4730     swpVselOps = true;
4731   }
4732 }
4733 
4734 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4735                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4736                                    SDValue Cmp, SelectionDAG &DAG) const {
4737   if (!Subtarget->hasFP64() && VT == MVT::f64) {
4738     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4739                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4740     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4741                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4742 
4743     SDValue TrueLow = TrueVal.getValue(0);
4744     SDValue TrueHigh = TrueVal.getValue(1);
4745     SDValue FalseLow = FalseVal.getValue(0);
4746     SDValue FalseHigh = FalseVal.getValue(1);
4747 
4748     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4749                               ARMcc, CCR, Cmp);
4750     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4751                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4752 
4753     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4754   } else {
4755     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4756                        Cmp);
4757   }
4758 }
4759 
4760 static bool isGTorGE(ISD::CondCode CC) {
4761   return CC == ISD::SETGT || CC == ISD::SETGE;
4762 }
4763 
4764 static bool isLTorLE(ISD::CondCode CC) {
4765   return CC == ISD::SETLT || CC == ISD::SETLE;
4766 }
4767 
4768 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4769 // All of these conditions (and their <= and >= counterparts) will do:
4770 //          x < k ? k : x
4771 //          x > k ? x : k
4772 //          k < x ? x : k
4773 //          k > x ? k : x
4774 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4775                             const SDValue TrueVal, const SDValue FalseVal,
4776                             const ISD::CondCode CC, const SDValue K) {
4777   return (isGTorGE(CC) &&
4778           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4779          (isLTorLE(CC) &&
4780           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4781 }
4782 
4783 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4784 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4785                             const SDValue TrueVal, const SDValue FalseVal,
4786                             const ISD::CondCode CC, const SDValue K) {
4787   return (isGTorGE(CC) &&
4788           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4789          (isLTorLE(CC) &&
4790           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4791 }
4792 
4793 // Check if two chained conditionals could be converted into SSAT or USAT.
4794 //
4795 // SSAT can replace a set of two conditional selectors that bound a number to an
4796 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4797 //
4798 //     x < -k ? -k : (x > k ? k : x)
4799 //     x < -k ? -k : (x < k ? x : k)
4800 //     x > -k ? (x > k ? k : x) : -k
4801 //     x < k ? (x < -k ? -k : x) : k
4802 //     etc.
4803 //
4804 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4805 // a power of 2.
4806 //
4807 // It returns true if the conversion can be done, false otherwise.
4808 // Additionally, the variable is returned in parameter V, the constant in K and
4809 // usat is set to true if the conditional represents an unsigned saturation
4810 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4811                                     uint64_t &K, bool &usat) {
4812   SDValue LHS1 = Op.getOperand(0);
4813   SDValue RHS1 = Op.getOperand(1);
4814   SDValue TrueVal1 = Op.getOperand(2);
4815   SDValue FalseVal1 = Op.getOperand(3);
4816   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4817 
4818   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4819   if (Op2.getOpcode() != ISD::SELECT_CC)
4820     return false;
4821 
4822   SDValue LHS2 = Op2.getOperand(0);
4823   SDValue RHS2 = Op2.getOperand(1);
4824   SDValue TrueVal2 = Op2.getOperand(2);
4825   SDValue FalseVal2 = Op2.getOperand(3);
4826   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4827 
4828   // Find out which are the constants and which are the variables
4829   // in each conditional
4830   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4831                                                         ? &RHS1
4832                                                         : nullptr;
4833   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4834                                                         ? &RHS2
4835                                                         : nullptr;
4836   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4837   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4838   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4839   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4840 
4841   // We must detect cases where the original operations worked with 16- or
4842   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4843   // must work with sign-extended values but the select operations return
4844   // the original non-extended value.
4845   SDValue V2TmpReg = V2Tmp;
4846   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4847     V2TmpReg = V2Tmp->getOperand(0);
4848 
4849   // Check that the registers and the constants have the correct values
4850   // in both conditionals
4851   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4852       V2TmpReg != V2)
4853     return false;
4854 
4855   // Figure out which conditional is saturating the lower/upper bound.
4856   const SDValue *LowerCheckOp =
4857       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4858           ? &Op
4859           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4860                 ? &Op2
4861                 : nullptr;
4862   const SDValue *UpperCheckOp =
4863       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4864           ? &Op
4865           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4866                 ? &Op2
4867                 : nullptr;
4868 
4869   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4870     return false;
4871 
4872   // Check that the constant in the lower-bound check is
4873   // the opposite of the constant in the upper-bound check
4874   // in 1's complement.
4875   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4876   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4877   int64_t PosVal = std::max(Val1, Val2);
4878   int64_t NegVal = std::min(Val1, Val2);
4879 
4880   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4881        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4882       isPowerOf2_64(PosVal + 1)) {
4883 
4884     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4885     if (Val1 == ~Val2)
4886       usat = false;
4887     else if (NegVal == 0)
4888       usat = true;
4889     else
4890       return false;
4891 
4892     V = V2;
4893     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4894 
4895     return true;
4896   }
4897 
4898   return false;
4899 }
4900 
4901 // Check if a condition of the type x < k ? k : x can be converted into a
4902 // bit operation instead of conditional moves.
4903 // Currently this is allowed given:
4904 // - The conditions and values match up
4905 // - k is 0 or -1 (all ones)
4906 // This function will not check the last condition, thats up to the caller
4907 // It returns true if the transformation can be made, and in such case
4908 // returns x in V, and k in SatK.
4909 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4910                                          SDValue &SatK)
4911 {
4912   SDValue LHS = Op.getOperand(0);
4913   SDValue RHS = Op.getOperand(1);
4914   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4915   SDValue TrueVal = Op.getOperand(2);
4916   SDValue FalseVal = Op.getOperand(3);
4917 
4918   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4919                                                ? &RHS
4920                                                : nullptr;
4921 
4922   // No constant operation in comparison, early out
4923   if (!K)
4924     return false;
4925 
4926   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4927   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4928   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4929 
4930   // If the constant on left and right side, or variable on left and right,
4931   // does not match, early out
4932   if (*K != KTmp || V != VTmp)
4933     return false;
4934 
4935   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4936     SatK = *K;
4937     return true;
4938   }
4939 
4940   return false;
4941 }
4942 
4943 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4944   if (VT == MVT::f32)
4945     return !Subtarget->hasVFP2Base();
4946   if (VT == MVT::f64)
4947     return !Subtarget->hasFP64();
4948   if (VT == MVT::f16)
4949     return !Subtarget->hasFullFP16();
4950   return false;
4951 }
4952 
4953 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4954   EVT VT = Op.getValueType();
4955   SDLoc dl(Op);
4956 
4957   // Try to convert two saturating conditional selects into a single SSAT
4958   SDValue SatValue;
4959   uint64_t SatConstant;
4960   bool SatUSat;
4961   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4962       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4963     if (SatUSat)
4964       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4965                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4966     else
4967       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4968                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4969   }
4970 
4971   // Try to convert expressions of the form x < k ? k : x (and similar forms)
4972   // into more efficient bit operations, which is possible when k is 0 or -1
4973   // On ARM and Thumb-2 which have flexible operand 2 this will result in
4974   // single instructions. On Thumb the shift and the bit operation will be two
4975   // instructions.
4976   // Only allow this transformation on full-width (32-bit) operations
4977   SDValue LowerSatConstant;
4978   if (VT == MVT::i32 &&
4979       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4980     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4981                                  DAG.getConstant(31, dl, VT));
4982     if (isNullConstant(LowerSatConstant)) {
4983       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4984                                       DAG.getAllOnesConstant(dl, VT));
4985       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4986     } else if (isAllOnesConstant(LowerSatConstant))
4987       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4988   }
4989 
4990   SDValue LHS = Op.getOperand(0);
4991   SDValue RHS = Op.getOperand(1);
4992   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4993   SDValue TrueVal = Op.getOperand(2);
4994   SDValue FalseVal = Op.getOperand(3);
4995   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
4996   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
4997 
4998   if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
4999       LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
5000     unsigned TVal = CTVal->getZExtValue();
5001     unsigned FVal = CFVal->getZExtValue();
5002     unsigned Opcode = 0;
5003 
5004     if (TVal == ~FVal) {
5005       Opcode = ARMISD::CSINV;
5006     } else if (TVal == ~FVal + 1) {
5007       Opcode = ARMISD::CSNEG;
5008     } else if (TVal + 1 == FVal) {
5009       Opcode = ARMISD::CSINC;
5010     } else if (TVal == FVal + 1) {
5011       Opcode = ARMISD::CSINC;
5012       std::swap(TrueVal, FalseVal);
5013       std::swap(TVal, FVal);
5014       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5015     }
5016 
5017     if (Opcode) {
5018       // If one of the constants is cheaper than another, materialise the
5019       // cheaper one and let the csel generate the other.
5020       if (Opcode != ARMISD::CSINC &&
5021           HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5022         std::swap(TrueVal, FalseVal);
5023         std::swap(TVal, FVal);
5024         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5025       }
5026 
5027       // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5028       // to get there. CSINC not is invertable like the other two (~(~a) == a,
5029       // -(-a) == a, but (a+1)+1 != a).
5030       if (FVal == 0 && Opcode != ARMISD::CSINC) {
5031         std::swap(TrueVal, FalseVal);
5032         std::swap(TVal, FVal);
5033         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5034       }
5035       if (TVal == 0)
5036         TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
5037 
5038       // Drops F's value because we can get it by inverting/negating TVal.
5039       FalseVal = TrueVal;
5040 
5041       SDValue ARMcc;
5042       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5043       EVT VT = TrueVal.getValueType();
5044       return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
5045     }
5046   }
5047 
5048   if (isUnsupportedFloatingType(LHS.getValueType())) {
5049     DAG.getTargetLoweringInfo().softenSetCCOperands(
5050         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5051 
5052     // If softenSetCCOperands only returned one value, we should compare it to
5053     // zero.
5054     if (!RHS.getNode()) {
5055       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5056       CC = ISD::SETNE;
5057     }
5058   }
5059 
5060   if (LHS.getValueType() == MVT::i32) {
5061     // Try to generate VSEL on ARMv8.
5062     // The VSEL instruction can't use all the usual ARM condition
5063     // codes: it only has two bits to select the condition code, so it's
5064     // constrained to use only GE, GT, VS and EQ.
5065     //
5066     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5067     // swap the operands of the previous compare instruction (effectively
5068     // inverting the compare condition, swapping 'less' and 'greater') and
5069     // sometimes need to swap the operands to the VSEL (which inverts the
5070     // condition in the sense of firing whenever the previous condition didn't)
5071     if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5072                                         TrueVal.getValueType() == MVT::f32 ||
5073                                         TrueVal.getValueType() == MVT::f64)) {
5074       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5075       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5076           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5077         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5078         std::swap(TrueVal, FalseVal);
5079       }
5080     }
5081 
5082     SDValue ARMcc;
5083     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5084     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5085     // Choose GE over PL, which vsel does now support
5086     if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
5087       ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5088     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5089   }
5090 
5091   ARMCC::CondCodes CondCode, CondCode2;
5092   FPCCToARMCC(CC, CondCode, CondCode2);
5093 
5094   // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5095   // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5096   // must use VSEL (limited condition codes), due to not having conditional f16
5097   // moves.
5098   if (Subtarget->hasFPARMv8Base() &&
5099       !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5100       (TrueVal.getValueType() == MVT::f16 ||
5101        TrueVal.getValueType() == MVT::f32 ||
5102        TrueVal.getValueType() == MVT::f64)) {
5103     bool swpCmpOps = false;
5104     bool swpVselOps = false;
5105     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5106 
5107     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5108         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5109       if (swpCmpOps)
5110         std::swap(LHS, RHS);
5111       if (swpVselOps)
5112         std::swap(TrueVal, FalseVal);
5113     }
5114   }
5115 
5116   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5117   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5118   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5119   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5120   if (CondCode2 != ARMCC::AL) {
5121     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5122     // FIXME: Needs another CMP because flag can have but one use.
5123     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5124     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5125   }
5126   return Result;
5127 }
5128 
5129 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
5130 /// to morph to an integer compare sequence.
5131 static bool canChangeToInt(SDValue Op, bool &SeenZero,
5132                            const ARMSubtarget *Subtarget) {
5133   SDNode *N = Op.getNode();
5134   if (!N->hasOneUse())
5135     // Otherwise it requires moving the value from fp to integer registers.
5136     return false;
5137   if (!N->getNumValues())
5138     return false;
5139   EVT VT = Op.getValueType();
5140   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5141     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5142     // vmrs are very slow, e.g. cortex-a8.
5143     return false;
5144 
5145   if (isFloatingPointZero(Op)) {
5146     SeenZero = true;
5147     return true;
5148   }
5149   return ISD::isNormalLoad(N);
5150 }
5151 
5152 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5153   if (isFloatingPointZero(Op))
5154     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5155 
5156   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5157     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5158                        Ld->getPointerInfo(), Ld->getAlignment(),
5159                        Ld->getMemOperand()->getFlags());
5160 
5161   llvm_unreachable("Unknown VFP cmp argument!");
5162 }
5163 
5164 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5165                            SDValue &RetVal1, SDValue &RetVal2) {
5166   SDLoc dl(Op);
5167 
5168   if (isFloatingPointZero(Op)) {
5169     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5170     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5171     return;
5172   }
5173 
5174   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5175     SDValue Ptr = Ld->getBasePtr();
5176     RetVal1 =
5177         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5178                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5179 
5180     EVT PtrType = Ptr.getValueType();
5181     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5182     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5183                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5184     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5185                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
5186                           Ld->getMemOperand()->getFlags());
5187     return;
5188   }
5189 
5190   llvm_unreachable("Unknown VFP cmp argument!");
5191 }
5192 
5193 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5194 /// f32 and even f64 comparisons to integer ones.
5195 SDValue
5196 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5197   SDValue Chain = Op.getOperand(0);
5198   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5199   SDValue LHS = Op.getOperand(2);
5200   SDValue RHS = Op.getOperand(3);
5201   SDValue Dest = Op.getOperand(4);
5202   SDLoc dl(Op);
5203 
5204   bool LHSSeenZero = false;
5205   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5206   bool RHSSeenZero = false;
5207   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5208   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5209     // If unsafe fp math optimization is enabled and there are no other uses of
5210     // the CMP operands, and the condition code is EQ or NE, we can optimize it
5211     // to an integer comparison.
5212     if (CC == ISD::SETOEQ)
5213       CC = ISD::SETEQ;
5214     else if (CC == ISD::SETUNE)
5215       CC = ISD::SETNE;
5216 
5217     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5218     SDValue ARMcc;
5219     if (LHS.getValueType() == MVT::f32) {
5220       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5221                         bitcastf32Toi32(LHS, DAG), Mask);
5222       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5223                         bitcastf32Toi32(RHS, DAG), Mask);
5224       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5225       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5226       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5227                          Chain, Dest, ARMcc, CCR, Cmp);
5228     }
5229 
5230     SDValue LHS1, LHS2;
5231     SDValue RHS1, RHS2;
5232     expandf64Toi32(LHS, DAG, LHS1, LHS2);
5233     expandf64Toi32(RHS, DAG, RHS1, RHS2);
5234     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5235     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5236     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5237     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5238     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5239     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5240     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5241   }
5242 
5243   return SDValue();
5244 }
5245 
5246 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5247   SDValue Chain = Op.getOperand(0);
5248   SDValue Cond = Op.getOperand(1);
5249   SDValue Dest = Op.getOperand(2);
5250   SDLoc dl(Op);
5251 
5252   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5253   // instruction.
5254   unsigned Opc = Cond.getOpcode();
5255   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5256                       !Subtarget->isThumb1Only();
5257   if (Cond.getResNo() == 1 &&
5258       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5259        Opc == ISD::USUBO || OptimizeMul)) {
5260     // Only lower legal XALUO ops.
5261     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5262       return SDValue();
5263 
5264     // The actual operation with overflow check.
5265     SDValue Value, OverflowCmp;
5266     SDValue ARMcc;
5267     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5268 
5269     // Reverse the condition code.
5270     ARMCC::CondCodes CondCode =
5271         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5272     CondCode = ARMCC::getOppositeCondition(CondCode);
5273     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5274     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5275 
5276     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5277                        OverflowCmp);
5278   }
5279 
5280   return SDValue();
5281 }
5282 
5283 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5284   SDValue Chain = Op.getOperand(0);
5285   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5286   SDValue LHS = Op.getOperand(2);
5287   SDValue RHS = Op.getOperand(3);
5288   SDValue Dest = Op.getOperand(4);
5289   SDLoc dl(Op);
5290 
5291   if (isUnsupportedFloatingType(LHS.getValueType())) {
5292     DAG.getTargetLoweringInfo().softenSetCCOperands(
5293         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5294 
5295     // If softenSetCCOperands only returned one value, we should compare it to
5296     // zero.
5297     if (!RHS.getNode()) {
5298       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5299       CC = ISD::SETNE;
5300     }
5301   }
5302 
5303   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5304   // instruction.
5305   unsigned Opc = LHS.getOpcode();
5306   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5307                       !Subtarget->isThumb1Only();
5308   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5309       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5310        Opc == ISD::USUBO || OptimizeMul) &&
5311       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5312     // Only lower legal XALUO ops.
5313     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5314       return SDValue();
5315 
5316     // The actual operation with overflow check.
5317     SDValue Value, OverflowCmp;
5318     SDValue ARMcc;
5319     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5320 
5321     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5322       // Reverse the condition code.
5323       ARMCC::CondCodes CondCode =
5324           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5325       CondCode = ARMCC::getOppositeCondition(CondCode);
5326       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5327     }
5328     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5329 
5330     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5331                        OverflowCmp);
5332   }
5333 
5334   if (LHS.getValueType() == MVT::i32) {
5335     SDValue ARMcc;
5336     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5337     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5338     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5339                        Chain, Dest, ARMcc, CCR, Cmp);
5340   }
5341 
5342   if (getTargetMachine().Options.UnsafeFPMath &&
5343       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5344        CC == ISD::SETNE || CC == ISD::SETUNE)) {
5345     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5346       return Result;
5347   }
5348 
5349   ARMCC::CondCodes CondCode, CondCode2;
5350   FPCCToARMCC(CC, CondCode, CondCode2);
5351 
5352   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5353   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5354   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5355   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5356   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5357   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5358   if (CondCode2 != ARMCC::AL) {
5359     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5360     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5361     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5362   }
5363   return Res;
5364 }
5365 
5366 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5367   SDValue Chain = Op.getOperand(0);
5368   SDValue Table = Op.getOperand(1);
5369   SDValue Index = Op.getOperand(2);
5370   SDLoc dl(Op);
5371 
5372   EVT PTy = getPointerTy(DAG.getDataLayout());
5373   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5374   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5375   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5376   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5377   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5378   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5379     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5380     // which does another jump to the destination. This also makes it easier
5381     // to translate it to TBB / TBH later (Thumb2 only).
5382     // FIXME: This might not work if the function is extremely large.
5383     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5384                        Addr, Op.getOperand(2), JTI);
5385   }
5386   if (isPositionIndependent() || Subtarget->isROPI()) {
5387     Addr =
5388         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5389                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5390     Chain = Addr.getValue(1);
5391     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5392     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5393   } else {
5394     Addr =
5395         DAG.getLoad(PTy, dl, Chain, Addr,
5396                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5397     Chain = Addr.getValue(1);
5398     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5399   }
5400 }
5401 
5402 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5403   EVT VT = Op.getValueType();
5404   SDLoc dl(Op);
5405 
5406   if (Op.getValueType().getVectorElementType() == MVT::i32) {
5407     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5408       return Op;
5409     return DAG.UnrollVectorOp(Op.getNode());
5410   }
5411 
5412   const bool HasFullFP16 =
5413     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5414 
5415   EVT NewTy;
5416   const EVT OpTy = Op.getOperand(0).getValueType();
5417   if (OpTy == MVT::v4f32)
5418     NewTy = MVT::v4i32;
5419   else if (OpTy == MVT::v4f16 && HasFullFP16)
5420     NewTy = MVT::v4i16;
5421   else if (OpTy == MVT::v8f16 && HasFullFP16)
5422     NewTy = MVT::v8i16;
5423   else
5424     llvm_unreachable("Invalid type for custom lowering!");
5425 
5426   if (VT != MVT::v4i16 && VT != MVT::v8i16)
5427     return DAG.UnrollVectorOp(Op.getNode());
5428 
5429   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5430   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5431 }
5432 
5433 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5434   EVT VT = Op.getValueType();
5435   if (VT.isVector())
5436     return LowerVectorFP_TO_INT(Op, DAG);
5437 
5438   bool IsStrict = Op->isStrictFPOpcode();
5439   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5440 
5441   if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5442     RTLIB::Libcall LC;
5443     if (Op.getOpcode() == ISD::FP_TO_SINT ||
5444         Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5445       LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5446                               Op.getValueType());
5447     else
5448       LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5449                               Op.getValueType());
5450     SDLoc Loc(Op);
5451     MakeLibCallOptions CallOptions;
5452     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5453     SDValue Result;
5454     std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5455                                           CallOptions, Loc, Chain);
5456     return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5457   }
5458 
5459   // FIXME: Remove this when we have strict fp instruction selection patterns
5460   if (IsStrict) {
5461     SDLoc Loc(Op);
5462     SDValue Result =
5463         DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5464                                                              : ISD::FP_TO_UINT,
5465                     Loc, Op.getValueType(), SrcVal);
5466     return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
5467   }
5468 
5469   return Op;
5470 }
5471 
5472 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5473   EVT VT = Op.getValueType();
5474   SDLoc dl(Op);
5475 
5476   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5477     if (VT.getVectorElementType() == MVT::f32)
5478       return Op;
5479     return DAG.UnrollVectorOp(Op.getNode());
5480   }
5481 
5482   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5483           Op.getOperand(0).getValueType() == MVT::v8i16) &&
5484          "Invalid type for custom lowering!");
5485 
5486   const bool HasFullFP16 =
5487     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5488 
5489   EVT DestVecType;
5490   if (VT == MVT::v4f32)
5491     DestVecType = MVT::v4i32;
5492   else if (VT == MVT::v4f16 && HasFullFP16)
5493     DestVecType = MVT::v4i16;
5494   else if (VT == MVT::v8f16 && HasFullFP16)
5495     DestVecType = MVT::v8i16;
5496   else
5497     return DAG.UnrollVectorOp(Op.getNode());
5498 
5499   unsigned CastOpc;
5500   unsigned Opc;
5501   switch (Op.getOpcode()) {
5502   default: llvm_unreachable("Invalid opcode!");
5503   case ISD::SINT_TO_FP:
5504     CastOpc = ISD::SIGN_EXTEND;
5505     Opc = ISD::SINT_TO_FP;
5506     break;
5507   case ISD::UINT_TO_FP:
5508     CastOpc = ISD::ZERO_EXTEND;
5509     Opc = ISD::UINT_TO_FP;
5510     break;
5511   }
5512 
5513   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5514   return DAG.getNode(Opc, dl, VT, Op);
5515 }
5516 
5517 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5518   EVT VT = Op.getValueType();
5519   if (VT.isVector())
5520     return LowerVectorINT_TO_FP(Op, DAG);
5521   if (isUnsupportedFloatingType(VT)) {
5522     RTLIB::Libcall LC;
5523     if (Op.getOpcode() == ISD::SINT_TO_FP)
5524       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5525                               Op.getValueType());
5526     else
5527       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5528                               Op.getValueType());
5529     MakeLibCallOptions CallOptions;
5530     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5531                        CallOptions, SDLoc(Op)).first;
5532   }
5533 
5534   return Op;
5535 }
5536 
5537 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5538   // Implement fcopysign with a fabs and a conditional fneg.
5539   SDValue Tmp0 = Op.getOperand(0);
5540   SDValue Tmp1 = Op.getOperand(1);
5541   SDLoc dl(Op);
5542   EVT VT = Op.getValueType();
5543   EVT SrcVT = Tmp1.getValueType();
5544   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5545     Tmp0.getOpcode() == ARMISD::VMOVDRR;
5546   bool UseNEON = !InGPR && Subtarget->hasNEON();
5547 
5548   if (UseNEON) {
5549     // Use VBSL to copy the sign bit.
5550     unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5551     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5552                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5553     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5554     if (VT == MVT::f64)
5555       Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5556                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5557                          DAG.getConstant(32, dl, MVT::i32));
5558     else /*if (VT == MVT::f32)*/
5559       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5560     if (SrcVT == MVT::f32) {
5561       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5562       if (VT == MVT::f64)
5563         Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5564                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5565                            DAG.getConstant(32, dl, MVT::i32));
5566     } else if (VT == MVT::f32)
5567       Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5568                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5569                          DAG.getConstant(32, dl, MVT::i32));
5570     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5571     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5572 
5573     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5574                                             dl, MVT::i32);
5575     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5576     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5577                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5578 
5579     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5580                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5581                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5582     if (VT == MVT::f32) {
5583       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5584       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5585                         DAG.getConstant(0, dl, MVT::i32));
5586     } else {
5587       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5588     }
5589 
5590     return Res;
5591   }
5592 
5593   // Bitcast operand 1 to i32.
5594   if (SrcVT == MVT::f64)
5595     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5596                        Tmp1).getValue(1);
5597   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5598 
5599   // Or in the signbit with integer operations.
5600   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5601   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5602   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5603   if (VT == MVT::f32) {
5604     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5605                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5606     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5607                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5608   }
5609 
5610   // f64: Or the high part with signbit and then combine two parts.
5611   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5612                      Tmp0);
5613   SDValue Lo = Tmp0.getValue(0);
5614   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5615   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5616   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5617 }
5618 
5619 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5620   MachineFunction &MF = DAG.getMachineFunction();
5621   MachineFrameInfo &MFI = MF.getFrameInfo();
5622   MFI.setReturnAddressIsTaken(true);
5623 
5624   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5625     return SDValue();
5626 
5627   EVT VT = Op.getValueType();
5628   SDLoc dl(Op);
5629   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5630   if (Depth) {
5631     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5632     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5633     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5634                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5635                        MachinePointerInfo());
5636   }
5637 
5638   // Return LR, which contains the return address. Mark it an implicit live-in.
5639   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5640   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5641 }
5642 
5643 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5644   const ARMBaseRegisterInfo &ARI =
5645     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5646   MachineFunction &MF = DAG.getMachineFunction();
5647   MachineFrameInfo &MFI = MF.getFrameInfo();
5648   MFI.setFrameAddressIsTaken(true);
5649 
5650   EVT VT = Op.getValueType();
5651   SDLoc dl(Op);  // FIXME probably not meaningful
5652   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5653   Register FrameReg = ARI.getFrameRegister(MF);
5654   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5655   while (Depth--)
5656     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5657                             MachinePointerInfo());
5658   return FrameAddr;
5659 }
5660 
5661 // FIXME? Maybe this could be a TableGen attribute on some registers and
5662 // this table could be generated automatically from RegInfo.
5663 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
5664                                               const MachineFunction &MF) const {
5665   Register Reg = StringSwitch<unsigned>(RegName)
5666                        .Case("sp", ARM::SP)
5667                        .Default(0);
5668   if (Reg)
5669     return Reg;
5670   report_fatal_error(Twine("Invalid register name \""
5671                               + StringRef(RegName)  + "\"."));
5672 }
5673 
5674 // Result is 64 bit value so split into two 32 bit values and return as a
5675 // pair of values.
5676 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5677                                 SelectionDAG &DAG) {
5678   SDLoc DL(N);
5679 
5680   // This function is only supposed to be called for i64 type destination.
5681   assert(N->getValueType(0) == MVT::i64
5682           && "ExpandREAD_REGISTER called for non-i64 type result.");
5683 
5684   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5685                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5686                              N->getOperand(0),
5687                              N->getOperand(1));
5688 
5689   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5690                     Read.getValue(1)));
5691   Results.push_back(Read.getOperand(0));
5692 }
5693 
5694 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5695 /// When \p DstVT, the destination type of \p BC, is on the vector
5696 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5697 /// it might be possible to combine them, such that everything stays on the
5698 /// vector register bank.
5699 /// \p return The node that would replace \p BT, if the combine
5700 /// is possible.
5701 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5702                                                 SelectionDAG &DAG) {
5703   SDValue Op = BC->getOperand(0);
5704   EVT DstVT = BC->getValueType(0);
5705 
5706   // The only vector instruction that can produce a scalar (remember,
5707   // since the bitcast was about to be turned into VMOVDRR, the source
5708   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5709   // Moreover, we can do this combine only if there is one use.
5710   // Finally, if the destination type is not a vector, there is not
5711   // much point on forcing everything on the vector bank.
5712   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5713       !Op.hasOneUse())
5714     return SDValue();
5715 
5716   // If the index is not constant, we will introduce an additional
5717   // multiply that will stick.
5718   // Give up in that case.
5719   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5720   if (!Index)
5721     return SDValue();
5722   unsigned DstNumElt = DstVT.getVectorNumElements();
5723 
5724   // Compute the new index.
5725   const APInt &APIntIndex = Index->getAPIntValue();
5726   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5727   NewIndex *= APIntIndex;
5728   // Check if the new constant index fits into i32.
5729   if (NewIndex.getBitWidth() > 32)
5730     return SDValue();
5731 
5732   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5733   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5734   SDLoc dl(Op);
5735   SDValue ExtractSrc = Op.getOperand(0);
5736   EVT VecVT = EVT::getVectorVT(
5737       *DAG.getContext(), DstVT.getScalarType(),
5738       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5739   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5740   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5741                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5742 }
5743 
5744 /// ExpandBITCAST - If the target supports VFP, this function is called to
5745 /// expand a bit convert where either the source or destination type is i64 to
5746 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5747 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5748 /// vectors), since the legalizer won't know what to do with that.
5749 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5750                              const ARMSubtarget *Subtarget) {
5751   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5752   SDLoc dl(N);
5753   SDValue Op = N->getOperand(0);
5754 
5755   // This function is only supposed to be called for i16 and i64 types, either
5756   // as the source or destination of the bit convert.
5757   EVT SrcVT = Op.getValueType();
5758   EVT DstVT = N->getValueType(0);
5759 
5760   if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5761     if (!Subtarget->hasFullFP16())
5762       return SDValue();
5763     // f16 bitcast i16 -> VMOVhr
5764     return DAG.getNode(ARMISD::VMOVhr, SDLoc(N), MVT::f16,
5765                        DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
5766   }
5767 
5768   if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5769     if (!Subtarget->hasFullFP16())
5770       return SDValue();
5771     // i16 bitcast f16 -> VMOVrh
5772     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), MVT::i16,
5773                        DAG.getNode(ARMISD::VMOVrh, SDLoc(N), MVT::i32, Op));
5774   }
5775 
5776   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5777     return SDValue();
5778 
5779   // Turn i64->f64 into VMOVDRR.
5780   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5781     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5782     // if we can combine the bitcast with its source.
5783     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5784       return Val;
5785 
5786     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5787                              DAG.getConstant(0, dl, MVT::i32));
5788     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5789                              DAG.getConstant(1, dl, MVT::i32));
5790     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5791                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5792   }
5793 
5794   // Turn f64->i64 into VMOVRRD.
5795   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5796     SDValue Cvt;
5797     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5798         SrcVT.getVectorNumElements() > 1)
5799       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5800                         DAG.getVTList(MVT::i32, MVT::i32),
5801                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5802     else
5803       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5804                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5805     // Merge the pieces into a single i64 value.
5806     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5807   }
5808 
5809   return SDValue();
5810 }
5811 
5812 /// getZeroVector - Returns a vector of specified type with all zero elements.
5813 /// Zero vectors are used to represent vector negation and in those cases
5814 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5815 /// not support i64 elements, so sometimes the zero vectors will need to be
5816 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5817 /// zero vector.
5818 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5819   assert(VT.isVector() && "Expected a vector type");
5820   // The canonical modified immediate encoding of a zero vector is....0!
5821   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5822   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5823   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5824   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5825 }
5826 
5827 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5828 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5829 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5830                                                 SelectionDAG &DAG) const {
5831   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5832   EVT VT = Op.getValueType();
5833   unsigned VTBits = VT.getSizeInBits();
5834   SDLoc dl(Op);
5835   SDValue ShOpLo = Op.getOperand(0);
5836   SDValue ShOpHi = Op.getOperand(1);
5837   SDValue ShAmt  = Op.getOperand(2);
5838   SDValue ARMcc;
5839   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5840   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5841 
5842   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5843 
5844   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5845                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5846   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5847   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5848                                    DAG.getConstant(VTBits, dl, MVT::i32));
5849   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5850   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5851   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5852   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5853                             ISD::SETGE, ARMcc, DAG, dl);
5854   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5855                            ARMcc, CCR, CmpLo);
5856 
5857   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5858   SDValue HiBigShift = Opc == ISD::SRA
5859                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5860                                          DAG.getConstant(VTBits - 1, dl, VT))
5861                            : DAG.getConstant(0, dl, VT);
5862   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5863                             ISD::SETGE, ARMcc, DAG, dl);
5864   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5865                            ARMcc, CCR, CmpHi);
5866 
5867   SDValue Ops[2] = { Lo, Hi };
5868   return DAG.getMergeValues(Ops, dl);
5869 }
5870 
5871 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5872 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5873 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5874                                                SelectionDAG &DAG) const {
5875   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5876   EVT VT = Op.getValueType();
5877   unsigned VTBits = VT.getSizeInBits();
5878   SDLoc dl(Op);
5879   SDValue ShOpLo = Op.getOperand(0);
5880   SDValue ShOpHi = Op.getOperand(1);
5881   SDValue ShAmt  = Op.getOperand(2);
5882   SDValue ARMcc;
5883   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5884 
5885   assert(Op.getOpcode() == ISD::SHL_PARTS);
5886   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5887                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5888   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5889   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5890   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5891 
5892   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5893                                    DAG.getConstant(VTBits, dl, MVT::i32));
5894   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5895   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5896                             ISD::SETGE, ARMcc, DAG, dl);
5897   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5898                            ARMcc, CCR, CmpHi);
5899 
5900   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5901                           ISD::SETGE, ARMcc, DAG, dl);
5902   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5903   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5904                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5905 
5906   SDValue Ops[2] = { Lo, Hi };
5907   return DAG.getMergeValues(Ops, dl);
5908 }
5909 
5910 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5911                                             SelectionDAG &DAG) const {
5912   // The rounding mode is in bits 23:22 of the FPSCR.
5913   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5914   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5915   // so that the shift + and get folded into a bitfield extract.
5916   SDLoc dl(Op);
5917   SDValue Chain = Op.getOperand(0);
5918   SDValue Ops[] = {Chain,
5919                    DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
5920 
5921   SDValue FPSCR =
5922       DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
5923   Chain = FPSCR.getValue(1);
5924   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5925                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5926   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5927                               DAG.getConstant(22, dl, MVT::i32));
5928   SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5929                             DAG.getConstant(3, dl, MVT::i32));
5930   return DAG.getMergeValues({And, Chain}, dl);
5931 }
5932 
5933 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5934                          const ARMSubtarget *ST) {
5935   SDLoc dl(N);
5936   EVT VT = N->getValueType(0);
5937   if (VT.isVector() && ST->hasNEON()) {
5938 
5939     // Compute the least significant set bit: LSB = X & -X
5940     SDValue X = N->getOperand(0);
5941     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5942     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5943 
5944     EVT ElemTy = VT.getVectorElementType();
5945 
5946     if (ElemTy == MVT::i8) {
5947       // Compute with: cttz(x) = ctpop(lsb - 1)
5948       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5949                                 DAG.getTargetConstant(1, dl, ElemTy));
5950       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5951       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5952     }
5953 
5954     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5955         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5956       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5957       unsigned NumBits = ElemTy.getSizeInBits();
5958       SDValue WidthMinus1 =
5959           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5960                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5961       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5962       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5963     }
5964 
5965     // Compute with: cttz(x) = ctpop(lsb - 1)
5966 
5967     // Compute LSB - 1.
5968     SDValue Bits;
5969     if (ElemTy == MVT::i64) {
5970       // Load constant 0xffff'ffff'ffff'ffff to register.
5971       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5972                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5973       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5974     } else {
5975       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5976                                 DAG.getTargetConstant(1, dl, ElemTy));
5977       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5978     }
5979     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5980   }
5981 
5982   if (!ST->hasV6T2Ops())
5983     return SDValue();
5984 
5985   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5986   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5987 }
5988 
5989 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5990                           const ARMSubtarget *ST) {
5991   EVT VT = N->getValueType(0);
5992   SDLoc DL(N);
5993 
5994   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5995   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5996           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5997          "Unexpected type for custom ctpop lowering");
5998 
5999   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6000   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6001   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6002   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6003 
6004   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6005   unsigned EltSize = 8;
6006   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6007   while (EltSize != VT.getScalarSizeInBits()) {
6008     SmallVector<SDValue, 8> Ops;
6009     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6010                                   TLI.getPointerTy(DAG.getDataLayout())));
6011     Ops.push_back(Res);
6012 
6013     EltSize *= 2;
6014     NumElts /= 2;
6015     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6016     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6017   }
6018 
6019   return Res;
6020 }
6021 
6022 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
6023 /// operand of a vector shift operation, where all the elements of the
6024 /// build_vector must have the same constant integer value.
6025 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6026   // Ignore bit_converts.
6027   while (Op.getOpcode() == ISD::BITCAST)
6028     Op = Op.getOperand(0);
6029   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6030   APInt SplatBits, SplatUndef;
6031   unsigned SplatBitSize;
6032   bool HasAnyUndefs;
6033   if (!BVN ||
6034       !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6035                             ElementBits) ||
6036       SplatBitSize > ElementBits)
6037     return false;
6038   Cnt = SplatBits.getSExtValue();
6039   return true;
6040 }
6041 
6042 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6043 /// operand of a vector shift left operation.  That value must be in the range:
6044 ///   0 <= Value < ElementBits for a left shift; or
6045 ///   0 <= Value <= ElementBits for a long left shift.
6046 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6047   assert(VT.isVector() && "vector shift count is not a vector type");
6048   int64_t ElementBits = VT.getScalarSizeInBits();
6049   if (!getVShiftImm(Op, ElementBits, Cnt))
6050     return false;
6051   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6052 }
6053 
6054 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6055 /// operand of a vector shift right operation.  For a shift opcode, the value
6056 /// is positive, but for an intrinsic the value count must be negative. The
6057 /// absolute value must be in the range:
6058 ///   1 <= |Value| <= ElementBits for a right shift; or
6059 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6060 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6061                          int64_t &Cnt) {
6062   assert(VT.isVector() && "vector shift count is not a vector type");
6063   int64_t ElementBits = VT.getScalarSizeInBits();
6064   if (!getVShiftImm(Op, ElementBits, Cnt))
6065     return false;
6066   if (!isIntrinsic)
6067     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6068   if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6069     Cnt = -Cnt;
6070     return true;
6071   }
6072   return false;
6073 }
6074 
6075 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6076                           const ARMSubtarget *ST) {
6077   EVT VT = N->getValueType(0);
6078   SDLoc dl(N);
6079   int64_t Cnt;
6080 
6081   if (!VT.isVector())
6082     return SDValue();
6083 
6084   // We essentially have two forms here. Shift by an immediate and shift by a
6085   // vector register (there are also shift by a gpr, but that is just handled
6086   // with a tablegen pattern). We cannot easily match shift by an immediate in
6087   // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6088   // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6089   // signed or unsigned, and a negative shift indicates a shift right).
6090   if (N->getOpcode() == ISD::SHL) {
6091     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6092       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6093                          DAG.getConstant(Cnt, dl, MVT::i32));
6094     return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6095                        N->getOperand(1));
6096   }
6097 
6098   assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6099          "unexpected vector shift opcode");
6100 
6101   if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6102     unsigned VShiftOpc =
6103         (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6104     return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6105                        DAG.getConstant(Cnt, dl, MVT::i32));
6106   }
6107 
6108   // Other right shifts we don't have operations for (we use a shift left by a
6109   // negative number).
6110   EVT ShiftVT = N->getOperand(1).getValueType();
6111   SDValue NegatedCount = DAG.getNode(
6112       ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6113   unsigned VShiftOpc =
6114       (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6115   return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6116 }
6117 
6118 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6119                                 const ARMSubtarget *ST) {
6120   EVT VT = N->getValueType(0);
6121   SDLoc dl(N);
6122 
6123   // We can get here for a node like i32 = ISD::SHL i32, i64
6124   if (VT != MVT::i64)
6125     return SDValue();
6126 
6127   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6128           N->getOpcode() == ISD::SHL) &&
6129          "Unknown shift to lower!");
6130 
6131   unsigned ShOpc = N->getOpcode();
6132   if (ST->hasMVEIntegerOps()) {
6133     SDValue ShAmt = N->getOperand(1);
6134     unsigned ShPartsOpc = ARMISD::LSLL;
6135     ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6136 
6137     // If the shift amount is greater than 32 or has a greater bitwidth than 64
6138     // then do the default optimisation
6139     if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6140         (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6141       return SDValue();
6142 
6143     // Extract the lower 32 bits of the shift amount if it's not an i32
6144     if (ShAmt->getValueType(0) != MVT::i32)
6145       ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6146 
6147     if (ShOpc == ISD::SRL) {
6148       if (!Con)
6149         // There is no t2LSRLr instruction so negate and perform an lsll if the
6150         // shift amount is in a register, emulating a right shift.
6151         ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6152                             DAG.getConstant(0, dl, MVT::i32), ShAmt);
6153       else
6154         // Else generate an lsrl on the immediate shift amount
6155         ShPartsOpc = ARMISD::LSRL;
6156     } else if (ShOpc == ISD::SRA)
6157       ShPartsOpc = ARMISD::ASRL;
6158 
6159     // Lower 32 bits of the destination/source
6160     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6161                              DAG.getConstant(0, dl, MVT::i32));
6162     // Upper 32 bits of the destination/source
6163     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6164                              DAG.getConstant(1, dl, MVT::i32));
6165 
6166     // Generate the shift operation as computed above
6167     Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6168                      ShAmt);
6169     // The upper 32 bits come from the second return value of lsll
6170     Hi = SDValue(Lo.getNode(), 1);
6171     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6172   }
6173 
6174   // We only lower SRA, SRL of 1 here, all others use generic lowering.
6175   if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6176     return SDValue();
6177 
6178   // If we are in thumb mode, we don't have RRX.
6179   if (ST->isThumb1Only())
6180     return SDValue();
6181 
6182   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
6183   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6184                            DAG.getConstant(0, dl, MVT::i32));
6185   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6186                            DAG.getConstant(1, dl, MVT::i32));
6187 
6188   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6189   // captures the result into a carry flag.
6190   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6191   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6192 
6193   // The low part is an ARMISD::RRX operand, which shifts the carry in.
6194   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6195 
6196   // Merge the pieces into a single i64 value.
6197  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6198 }
6199 
6200 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6201                            const ARMSubtarget *ST) {
6202   bool Invert = false;
6203   bool Swap = false;
6204   unsigned Opc = ARMCC::AL;
6205 
6206   SDValue Op0 = Op.getOperand(0);
6207   SDValue Op1 = Op.getOperand(1);
6208   SDValue CC = Op.getOperand(2);
6209   EVT VT = Op.getValueType();
6210   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6211   SDLoc dl(Op);
6212 
6213   EVT CmpVT;
6214   if (ST->hasNEON())
6215     CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6216   else {
6217     assert(ST->hasMVEIntegerOps() &&
6218            "No hardware support for integer vector comparison!");
6219 
6220     if (Op.getValueType().getVectorElementType() != MVT::i1)
6221       return SDValue();
6222 
6223     // Make sure we expand floating point setcc to scalar if we do not have
6224     // mve.fp, so that we can handle them from there.
6225     if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6226       return SDValue();
6227 
6228     CmpVT = VT;
6229   }
6230 
6231   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6232       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6233     // Special-case integer 64-bit equality comparisons. They aren't legal,
6234     // but they can be lowered with a few vector instructions.
6235     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6236     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6237     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6238     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6239     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6240                               DAG.getCondCode(ISD::SETEQ));
6241     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6242     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6243     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6244     if (SetCCOpcode == ISD::SETNE)
6245       Merged = DAG.getNOT(dl, Merged, CmpVT);
6246     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6247     return Merged;
6248   }
6249 
6250   if (CmpVT.getVectorElementType() == MVT::i64)
6251     // 64-bit comparisons are not legal in general.
6252     return SDValue();
6253 
6254   if (Op1.getValueType().isFloatingPoint()) {
6255     switch (SetCCOpcode) {
6256     default: llvm_unreachable("Illegal FP comparison");
6257     case ISD::SETUNE:
6258     case ISD::SETNE:
6259       if (ST->hasMVEFloatOps()) {
6260         Opc = ARMCC::NE; break;
6261       } else {
6262         Invert = true; LLVM_FALLTHROUGH;
6263       }
6264     case ISD::SETOEQ:
6265     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6266     case ISD::SETOLT:
6267     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6268     case ISD::SETOGT:
6269     case ISD::SETGT:  Opc = ARMCC::GT; break;
6270     case ISD::SETOLE:
6271     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6272     case ISD::SETOGE:
6273     case ISD::SETGE: Opc = ARMCC::GE; break;
6274     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6275     case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6276     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6277     case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6278     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6279     case ISD::SETONE: {
6280       // Expand this to (OLT | OGT).
6281       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6282                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6283       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6284                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6285       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6286       if (Invert)
6287         Result = DAG.getNOT(dl, Result, VT);
6288       return Result;
6289     }
6290     case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6291     case ISD::SETO: {
6292       // Expand this to (OLT | OGE).
6293       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6294                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6295       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6296                                    DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6297       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6298       if (Invert)
6299         Result = DAG.getNOT(dl, Result, VT);
6300       return Result;
6301     }
6302     }
6303   } else {
6304     // Integer comparisons.
6305     switch (SetCCOpcode) {
6306     default: llvm_unreachable("Illegal integer comparison");
6307     case ISD::SETNE:
6308       if (ST->hasMVEIntegerOps()) {
6309         Opc = ARMCC::NE; break;
6310       } else {
6311         Invert = true; LLVM_FALLTHROUGH;
6312       }
6313     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6314     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
6315     case ISD::SETGT:  Opc = ARMCC::GT; break;
6316     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6317     case ISD::SETGE:  Opc = ARMCC::GE; break;
6318     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6319     case ISD::SETUGT: Opc = ARMCC::HI; break;
6320     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6321     case ISD::SETUGE: Opc = ARMCC::HS; break;
6322     }
6323 
6324     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6325     if (ST->hasNEON() && Opc == ARMCC::EQ) {
6326       SDValue AndOp;
6327       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6328         AndOp = Op0;
6329       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6330         AndOp = Op1;
6331 
6332       // Ignore bitconvert.
6333       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6334         AndOp = AndOp.getOperand(0);
6335 
6336       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6337         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6338         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6339         SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6340         if (!Invert)
6341           Result = DAG.getNOT(dl, Result, VT);
6342         return Result;
6343       }
6344     }
6345   }
6346 
6347   if (Swap)
6348     std::swap(Op0, Op1);
6349 
6350   // If one of the operands is a constant vector zero, attempt to fold the
6351   // comparison to a specialized compare-against-zero form.
6352   SDValue SingleOp;
6353   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6354     SingleOp = Op0;
6355   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6356     if (Opc == ARMCC::GE)
6357       Opc = ARMCC::LE;
6358     else if (Opc == ARMCC::GT)
6359       Opc = ARMCC::LT;
6360     SingleOp = Op1;
6361   }
6362 
6363   SDValue Result;
6364   if (SingleOp.getNode()) {
6365     Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6366                          DAG.getConstant(Opc, dl, MVT::i32));
6367   } else {
6368     Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6369                          DAG.getConstant(Opc, dl, MVT::i32));
6370   }
6371 
6372   Result = DAG.getSExtOrTrunc(Result, dl, VT);
6373 
6374   if (Invert)
6375     Result = DAG.getNOT(dl, Result, VT);
6376 
6377   return Result;
6378 }
6379 
6380 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6381   SDValue LHS = Op.getOperand(0);
6382   SDValue RHS = Op.getOperand(1);
6383   SDValue Carry = Op.getOperand(2);
6384   SDValue Cond = Op.getOperand(3);
6385   SDLoc DL(Op);
6386 
6387   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6388 
6389   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6390   // have to invert the carry first.
6391   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6392                       DAG.getConstant(1, DL, MVT::i32), Carry);
6393   // This converts the boolean value carry into the carry flag.
6394   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6395 
6396   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6397   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6398 
6399   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6400   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6401   SDValue ARMcc = DAG.getConstant(
6402       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6403   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6404   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6405                                    Cmp.getValue(1), SDValue());
6406   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6407                      CCR, Chain.getValue(1));
6408 }
6409 
6410 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6411 /// valid vector constant for a NEON or MVE instruction with a "modified
6412 /// immediate" operand (e.g., VMOV).  If so, return the encoded value.
6413 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6414                                  unsigned SplatBitSize, SelectionDAG &DAG,
6415                                  const SDLoc &dl, EVT &VT, EVT VectorVT,
6416                                  VMOVModImmType type) {
6417   unsigned OpCmode, Imm;
6418   bool is128Bits = VectorVT.is128BitVector();
6419 
6420   // SplatBitSize is set to the smallest size that splats the vector, so a
6421   // zero vector will always have SplatBitSize == 8.  However, NEON modified
6422   // immediate instructions others than VMOV do not support the 8-bit encoding
6423   // of a zero vector, and the default encoding of zero is supposed to be the
6424   // 32-bit version.
6425   if (SplatBits == 0)
6426     SplatBitSize = 32;
6427 
6428   switch (SplatBitSize) {
6429   case 8:
6430     if (type != VMOVModImm)
6431       return SDValue();
6432     // Any 1-byte value is OK.  Op=0, Cmode=1110.
6433     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6434     OpCmode = 0xe;
6435     Imm = SplatBits;
6436     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6437     break;
6438 
6439   case 16:
6440     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6441     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6442     if ((SplatBits & ~0xff) == 0) {
6443       // Value = 0x00nn: Op=x, Cmode=100x.
6444       OpCmode = 0x8;
6445       Imm = SplatBits;
6446       break;
6447     }
6448     if ((SplatBits & ~0xff00) == 0) {
6449       // Value = 0xnn00: Op=x, Cmode=101x.
6450       OpCmode = 0xa;
6451       Imm = SplatBits >> 8;
6452       break;
6453     }
6454     return SDValue();
6455 
6456   case 32:
6457     // NEON's 32-bit VMOV supports splat values where:
6458     // * only one byte is nonzero, or
6459     // * the least significant byte is 0xff and the second byte is nonzero, or
6460     // * the least significant 2 bytes are 0xff and the third is nonzero.
6461     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6462     if ((SplatBits & ~0xff) == 0) {
6463       // Value = 0x000000nn: Op=x, Cmode=000x.
6464       OpCmode = 0;
6465       Imm = SplatBits;
6466       break;
6467     }
6468     if ((SplatBits & ~0xff00) == 0) {
6469       // Value = 0x0000nn00: Op=x, Cmode=001x.
6470       OpCmode = 0x2;
6471       Imm = SplatBits >> 8;
6472       break;
6473     }
6474     if ((SplatBits & ~0xff0000) == 0) {
6475       // Value = 0x00nn0000: Op=x, Cmode=010x.
6476       OpCmode = 0x4;
6477       Imm = SplatBits >> 16;
6478       break;
6479     }
6480     if ((SplatBits & ~0xff000000) == 0) {
6481       // Value = 0xnn000000: Op=x, Cmode=011x.
6482       OpCmode = 0x6;
6483       Imm = SplatBits >> 24;
6484       break;
6485     }
6486 
6487     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6488     if (type == OtherModImm) return SDValue();
6489 
6490     if ((SplatBits & ~0xffff) == 0 &&
6491         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6492       // Value = 0x0000nnff: Op=x, Cmode=1100.
6493       OpCmode = 0xc;
6494       Imm = SplatBits >> 8;
6495       break;
6496     }
6497 
6498     // cmode == 0b1101 is not supported for MVE VMVN
6499     if (type == MVEVMVNModImm)
6500       return SDValue();
6501 
6502     if ((SplatBits & ~0xffffff) == 0 &&
6503         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6504       // Value = 0x00nnffff: Op=x, Cmode=1101.
6505       OpCmode = 0xd;
6506       Imm = SplatBits >> 16;
6507       break;
6508     }
6509 
6510     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6511     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6512     // VMOV.I32.  A (very) minor optimization would be to replicate the value
6513     // and fall through here to test for a valid 64-bit splat.  But, then the
6514     // caller would also need to check and handle the change in size.
6515     return SDValue();
6516 
6517   case 64: {
6518     if (type != VMOVModImm)
6519       return SDValue();
6520     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6521     uint64_t BitMask = 0xff;
6522     uint64_t Val = 0;
6523     unsigned ImmMask = 1;
6524     Imm = 0;
6525     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6526       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6527         Val |= BitMask;
6528         Imm |= ImmMask;
6529       } else if ((SplatBits & BitMask) != 0) {
6530         return SDValue();
6531       }
6532       BitMask <<= 8;
6533       ImmMask <<= 1;
6534     }
6535 
6536     if (DAG.getDataLayout().isBigEndian()) {
6537       // Reverse the order of elements within the vector.
6538       unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8;
6539       unsigned Mask = (1 << BytesPerElem) - 1;
6540       unsigned NumElems = 8 / BytesPerElem;
6541       unsigned NewImm = 0;
6542       for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) {
6543         unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask);
6544         NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem;
6545       }
6546       Imm = NewImm;
6547     }
6548 
6549     // Op=1, Cmode=1110.
6550     OpCmode = 0x1e;
6551     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6552     break;
6553   }
6554 
6555   default:
6556     llvm_unreachable("unexpected size for isVMOVModifiedImm");
6557   }
6558 
6559   unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6560   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6561 }
6562 
6563 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6564                                            const ARMSubtarget *ST) const {
6565   EVT VT = Op.getValueType();
6566   bool IsDouble = (VT == MVT::f64);
6567   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6568   const APFloat &FPVal = CFP->getValueAPF();
6569 
6570   // Prevent floating-point constants from using literal loads
6571   // when execute-only is enabled.
6572   if (ST->genExecuteOnly()) {
6573     // If we can represent the constant as an immediate, don't lower it
6574     if (isFPImmLegal(FPVal, VT))
6575       return Op;
6576     // Otherwise, construct as integer, and move to float register
6577     APInt INTVal = FPVal.bitcastToAPInt();
6578     SDLoc DL(CFP);
6579     switch (VT.getSimpleVT().SimpleTy) {
6580       default:
6581         llvm_unreachable("Unknown floating point type!");
6582         break;
6583       case MVT::f64: {
6584         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6585         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6586         if (!ST->isLittle())
6587           std::swap(Lo, Hi);
6588         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6589       }
6590       case MVT::f32:
6591           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6592               DAG.getConstant(INTVal, DL, MVT::i32));
6593     }
6594   }
6595 
6596   if (!ST->hasVFP3Base())
6597     return SDValue();
6598 
6599   // Use the default (constant pool) lowering for double constants when we have
6600   // an SP-only FPU
6601   if (IsDouble && !Subtarget->hasFP64())
6602     return SDValue();
6603 
6604   // Try splatting with a VMOV.f32...
6605   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6606 
6607   if (ImmVal != -1) {
6608     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6609       // We have code in place to select a valid ConstantFP already, no need to
6610       // do any mangling.
6611       return Op;
6612     }
6613 
6614     // It's a float and we are trying to use NEON operations where
6615     // possible. Lower it to a splat followed by an extract.
6616     SDLoc DL(Op);
6617     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6618     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6619                                       NewVal);
6620     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6621                        DAG.getConstant(0, DL, MVT::i32));
6622   }
6623 
6624   // The rest of our options are NEON only, make sure that's allowed before
6625   // proceeding..
6626   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6627     return SDValue();
6628 
6629   EVT VMovVT;
6630   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6631 
6632   // It wouldn't really be worth bothering for doubles except for one very
6633   // important value, which does happen to match: 0.0. So make sure we don't do
6634   // anything stupid.
6635   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6636     return SDValue();
6637 
6638   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6639   SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6640                                      VMovVT, VT, VMOVModImm);
6641   if (NewVal != SDValue()) {
6642     SDLoc DL(Op);
6643     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6644                                       NewVal);
6645     if (IsDouble)
6646       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6647 
6648     // It's a float: cast and extract a vector element.
6649     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6650                                        VecConstant);
6651     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6652                        DAG.getConstant(0, DL, MVT::i32));
6653   }
6654 
6655   // Finally, try a VMVN.i32
6656   NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6657                              VT, VMVNModImm);
6658   if (NewVal != SDValue()) {
6659     SDLoc DL(Op);
6660     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6661 
6662     if (IsDouble)
6663       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6664 
6665     // It's a float: cast and extract a vector element.
6666     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6667                                        VecConstant);
6668     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6669                        DAG.getConstant(0, DL, MVT::i32));
6670   }
6671 
6672   return SDValue();
6673 }
6674 
6675 // check if an VEXT instruction can handle the shuffle mask when the
6676 // vector sources of the shuffle are the same.
6677 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6678   unsigned NumElts = VT.getVectorNumElements();
6679 
6680   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6681   if (M[0] < 0)
6682     return false;
6683 
6684   Imm = M[0];
6685 
6686   // If this is a VEXT shuffle, the immediate value is the index of the first
6687   // element.  The other shuffle indices must be the successive elements after
6688   // the first one.
6689   unsigned ExpectedElt = Imm;
6690   for (unsigned i = 1; i < NumElts; ++i) {
6691     // Increment the expected index.  If it wraps around, just follow it
6692     // back to index zero and keep going.
6693     ++ExpectedElt;
6694     if (ExpectedElt == NumElts)
6695       ExpectedElt = 0;
6696 
6697     if (M[i] < 0) continue; // ignore UNDEF indices
6698     if (ExpectedElt != static_cast<unsigned>(M[i]))
6699       return false;
6700   }
6701 
6702   return true;
6703 }
6704 
6705 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6706                        bool &ReverseVEXT, unsigned &Imm) {
6707   unsigned NumElts = VT.getVectorNumElements();
6708   ReverseVEXT = false;
6709 
6710   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6711   if (M[0] < 0)
6712     return false;
6713 
6714   Imm = M[0];
6715 
6716   // If this is a VEXT shuffle, the immediate value is the index of the first
6717   // element.  The other shuffle indices must be the successive elements after
6718   // the first one.
6719   unsigned ExpectedElt = Imm;
6720   for (unsigned i = 1; i < NumElts; ++i) {
6721     // Increment the expected index.  If it wraps around, it may still be
6722     // a VEXT but the source vectors must be swapped.
6723     ExpectedElt += 1;
6724     if (ExpectedElt == NumElts * 2) {
6725       ExpectedElt = 0;
6726       ReverseVEXT = true;
6727     }
6728 
6729     if (M[i] < 0) continue; // ignore UNDEF indices
6730     if (ExpectedElt != static_cast<unsigned>(M[i]))
6731       return false;
6732   }
6733 
6734   // Adjust the index value if the source operands will be swapped.
6735   if (ReverseVEXT)
6736     Imm -= NumElts;
6737 
6738   return true;
6739 }
6740 
6741 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6742 /// instruction with the specified blocksize.  (The order of the elements
6743 /// within each block of the vector is reversed.)
6744 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6745   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6746          "Only possible block sizes for VREV are: 16, 32, 64");
6747 
6748   unsigned EltSz = VT.getScalarSizeInBits();
6749   if (EltSz == 64)
6750     return false;
6751 
6752   unsigned NumElts = VT.getVectorNumElements();
6753   unsigned BlockElts = M[0] + 1;
6754   // If the first shuffle index is UNDEF, be optimistic.
6755   if (M[0] < 0)
6756     BlockElts = BlockSize / EltSz;
6757 
6758   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6759     return false;
6760 
6761   for (unsigned i = 0; i < NumElts; ++i) {
6762     if (M[i] < 0) continue; // ignore UNDEF indices
6763     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6764       return false;
6765   }
6766 
6767   return true;
6768 }
6769 
6770 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6771   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6772   // range, then 0 is placed into the resulting vector. So pretty much any mask
6773   // of 8 elements can work here.
6774   return VT == MVT::v8i8 && M.size() == 8;
6775 }
6776 
6777 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6778                                unsigned Index) {
6779   if (Mask.size() == Elements * 2)
6780     return Index / Elements;
6781   return Mask[Index] == 0 ? 0 : 1;
6782 }
6783 
6784 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6785 // checking that pairs of elements in the shuffle mask represent the same index
6786 // in each vector, incrementing the expected index by 2 at each step.
6787 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6788 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6789 //  v2={e,f,g,h}
6790 // WhichResult gives the offset for each element in the mask based on which
6791 // of the two results it belongs to.
6792 //
6793 // The transpose can be represented either as:
6794 // result1 = shufflevector v1, v2, result1_shuffle_mask
6795 // result2 = shufflevector v1, v2, result2_shuffle_mask
6796 // where v1/v2 and the shuffle masks have the same number of elements
6797 // (here WhichResult (see below) indicates which result is being checked)
6798 //
6799 // or as:
6800 // results = shufflevector v1, v2, shuffle_mask
6801 // where both results are returned in one vector and the shuffle mask has twice
6802 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6803 // want to check the low half and high half of the shuffle mask as if it were
6804 // the other case
6805 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6806   unsigned EltSz = VT.getScalarSizeInBits();
6807   if (EltSz == 64)
6808     return false;
6809 
6810   unsigned NumElts = VT.getVectorNumElements();
6811   if (M.size() != NumElts && M.size() != NumElts*2)
6812     return false;
6813 
6814   // If the mask is twice as long as the input vector then we need to check the
6815   // upper and lower parts of the mask with a matching value for WhichResult
6816   // FIXME: A mask with only even values will be rejected in case the first
6817   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6818   // M[0] is used to determine WhichResult
6819   for (unsigned i = 0; i < M.size(); i += NumElts) {
6820     WhichResult = SelectPairHalf(NumElts, M, i);
6821     for (unsigned j = 0; j < NumElts; j += 2) {
6822       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6823           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6824         return false;
6825     }
6826   }
6827 
6828   if (M.size() == NumElts*2)
6829     WhichResult = 0;
6830 
6831   return true;
6832 }
6833 
6834 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6835 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6836 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6837 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6838   unsigned EltSz = VT.getScalarSizeInBits();
6839   if (EltSz == 64)
6840     return false;
6841 
6842   unsigned NumElts = VT.getVectorNumElements();
6843   if (M.size() != NumElts && M.size() != NumElts*2)
6844     return false;
6845 
6846   for (unsigned i = 0; i < M.size(); i += NumElts) {
6847     WhichResult = SelectPairHalf(NumElts, M, i);
6848     for (unsigned j = 0; j < NumElts; j += 2) {
6849       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6850           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6851         return false;
6852     }
6853   }
6854 
6855   if (M.size() == NumElts*2)
6856     WhichResult = 0;
6857 
6858   return true;
6859 }
6860 
6861 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6862 // that the mask elements are either all even and in steps of size 2 or all odd
6863 // and in steps of size 2.
6864 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6865 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6866 //  v2={e,f,g,h}
6867 // Requires similar checks to that of isVTRNMask with
6868 // respect the how results are returned.
6869 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6870   unsigned EltSz = VT.getScalarSizeInBits();
6871   if (EltSz == 64)
6872     return false;
6873 
6874   unsigned NumElts = VT.getVectorNumElements();
6875   if (M.size() != NumElts && M.size() != NumElts*2)
6876     return false;
6877 
6878   for (unsigned i = 0; i < M.size(); i += NumElts) {
6879     WhichResult = SelectPairHalf(NumElts, M, i);
6880     for (unsigned j = 0; j < NumElts; ++j) {
6881       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6882         return false;
6883     }
6884   }
6885 
6886   if (M.size() == NumElts*2)
6887     WhichResult = 0;
6888 
6889   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6890   if (VT.is64BitVector() && EltSz == 32)
6891     return false;
6892 
6893   return true;
6894 }
6895 
6896 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6897 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6898 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6899 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6900   unsigned EltSz = VT.getScalarSizeInBits();
6901   if (EltSz == 64)
6902     return false;
6903 
6904   unsigned NumElts = VT.getVectorNumElements();
6905   if (M.size() != NumElts && M.size() != NumElts*2)
6906     return false;
6907 
6908   unsigned Half = NumElts / 2;
6909   for (unsigned i = 0; i < M.size(); i += NumElts) {
6910     WhichResult = SelectPairHalf(NumElts, M, i);
6911     for (unsigned j = 0; j < NumElts; j += Half) {
6912       unsigned Idx = WhichResult;
6913       for (unsigned k = 0; k < Half; ++k) {
6914         int MIdx = M[i + j + k];
6915         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6916           return false;
6917         Idx += 2;
6918       }
6919     }
6920   }
6921 
6922   if (M.size() == NumElts*2)
6923     WhichResult = 0;
6924 
6925   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6926   if (VT.is64BitVector() && EltSz == 32)
6927     return false;
6928 
6929   return true;
6930 }
6931 
6932 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6933 // that pairs of elements of the shufflemask represent the same index in each
6934 // vector incrementing sequentially through the vectors.
6935 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6936 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6937 //  v2={e,f,g,h}
6938 // Requires similar checks to that of isVTRNMask with respect the how results
6939 // are returned.
6940 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6941   unsigned EltSz = VT.getScalarSizeInBits();
6942   if (EltSz == 64)
6943     return false;
6944 
6945   unsigned NumElts = VT.getVectorNumElements();
6946   if (M.size() != NumElts && M.size() != NumElts*2)
6947     return false;
6948 
6949   for (unsigned i = 0; i < M.size(); i += NumElts) {
6950     WhichResult = SelectPairHalf(NumElts, M, i);
6951     unsigned Idx = WhichResult * NumElts / 2;
6952     for (unsigned j = 0; j < NumElts; j += 2) {
6953       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6954           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6955         return false;
6956       Idx += 1;
6957     }
6958   }
6959 
6960   if (M.size() == NumElts*2)
6961     WhichResult = 0;
6962 
6963   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6964   if (VT.is64BitVector() && EltSz == 32)
6965     return false;
6966 
6967   return true;
6968 }
6969 
6970 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6971 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6972 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6973 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6974   unsigned EltSz = VT.getScalarSizeInBits();
6975   if (EltSz == 64)
6976     return false;
6977 
6978   unsigned NumElts = VT.getVectorNumElements();
6979   if (M.size() != NumElts && M.size() != NumElts*2)
6980     return false;
6981 
6982   for (unsigned i = 0; i < M.size(); i += NumElts) {
6983     WhichResult = SelectPairHalf(NumElts, M, i);
6984     unsigned Idx = WhichResult * NumElts / 2;
6985     for (unsigned j = 0; j < NumElts; j += 2) {
6986       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6987           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6988         return false;
6989       Idx += 1;
6990     }
6991   }
6992 
6993   if (M.size() == NumElts*2)
6994     WhichResult = 0;
6995 
6996   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6997   if (VT.is64BitVector() && EltSz == 32)
6998     return false;
6999 
7000   return true;
7001 }
7002 
7003 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7004 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7005 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7006                                            unsigned &WhichResult,
7007                                            bool &isV_UNDEF) {
7008   isV_UNDEF = false;
7009   if (isVTRNMask(ShuffleMask, VT, WhichResult))
7010     return ARMISD::VTRN;
7011   if (isVUZPMask(ShuffleMask, VT, WhichResult))
7012     return ARMISD::VUZP;
7013   if (isVZIPMask(ShuffleMask, VT, WhichResult))
7014     return ARMISD::VZIP;
7015 
7016   isV_UNDEF = true;
7017   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7018     return ARMISD::VTRN;
7019   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7020     return ARMISD::VUZP;
7021   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7022     return ARMISD::VZIP;
7023 
7024   return 0;
7025 }
7026 
7027 /// \return true if this is a reverse operation on an vector.
7028 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7029   unsigned NumElts = VT.getVectorNumElements();
7030   // Make sure the mask has the right size.
7031   if (NumElts != M.size())
7032       return false;
7033 
7034   // Look for <15, ..., 3, -1, 1, 0>.
7035   for (unsigned i = 0; i != NumElts; ++i)
7036     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7037       return false;
7038 
7039   return true;
7040 }
7041 
7042 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) {
7043   unsigned NumElts = VT.getVectorNumElements();
7044   // Make sure the mask has the right size.
7045   if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7046       return false;
7047 
7048   // If Top
7049   //   Look for <0, N, 2, N+2, 4, N+4, ..>.
7050   //   This inserts Input2 into Input1
7051   // else if not Top
7052   //   Look for <0, N+1, 2, N+3, 4, N+5, ..>
7053   //   This inserts Input1 into Input2
7054   unsigned Offset = Top ? 0 : 1;
7055   for (unsigned i = 0; i < NumElts; i+=2) {
7056     if (M[i] >= 0 && M[i] != (int)i)
7057       return false;
7058     if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset))
7059       return false;
7060   }
7061 
7062   return true;
7063 }
7064 
7065 // If N is an integer constant that can be moved into a register in one
7066 // instruction, return an SDValue of such a constant (will become a MOV
7067 // instruction).  Otherwise return null.
7068 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7069                                      const ARMSubtarget *ST, const SDLoc &dl) {
7070   uint64_t Val;
7071   if (!isa<ConstantSDNode>(N))
7072     return SDValue();
7073   Val = cast<ConstantSDNode>(N)->getZExtValue();
7074 
7075   if (ST->isThumb1Only()) {
7076     if (Val <= 255 || ~Val <= 255)
7077       return DAG.getConstant(Val, dl, MVT::i32);
7078   } else {
7079     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7080       return DAG.getConstant(Val, dl, MVT::i32);
7081   }
7082   return SDValue();
7083 }
7084 
7085 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7086                                     const ARMSubtarget *ST) {
7087   SDLoc dl(Op);
7088   EVT VT = Op.getValueType();
7089 
7090   assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7091 
7092   unsigned NumElts = VT.getVectorNumElements();
7093   unsigned BoolMask;
7094   unsigned BitsPerBool;
7095   if (NumElts == 4) {
7096     BitsPerBool = 4;
7097     BoolMask = 0xf;
7098   } else if (NumElts == 8) {
7099     BitsPerBool = 2;
7100     BoolMask = 0x3;
7101   } else if (NumElts == 16) {
7102     BitsPerBool = 1;
7103     BoolMask = 0x1;
7104   } else
7105     return SDValue();
7106 
7107   // If this is a single value copied into all lanes (a splat), we can just sign
7108   // extend that single value
7109   SDValue FirstOp = Op.getOperand(0);
7110   if (!isa<ConstantSDNode>(FirstOp) &&
7111       std::all_of(std::next(Op->op_begin()), Op->op_end(),
7112                   [&FirstOp](SDUse &U) {
7113                     return U.get().isUndef() || U.get() == FirstOp;
7114                   })) {
7115     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7116                               DAG.getValueType(MVT::i1));
7117     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7118   }
7119 
7120   // First create base with bits set where known
7121   unsigned Bits32 = 0;
7122   for (unsigned i = 0; i < NumElts; ++i) {
7123     SDValue V = Op.getOperand(i);
7124     if (!isa<ConstantSDNode>(V) && !V.isUndef())
7125       continue;
7126     bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7127     if (BitSet)
7128       Bits32 |= BoolMask << (i * BitsPerBool);
7129   }
7130 
7131   // Add in unknown nodes
7132   SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7133                              DAG.getConstant(Bits32, dl, MVT::i32));
7134   for (unsigned i = 0; i < NumElts; ++i) {
7135     SDValue V = Op.getOperand(i);
7136     if (isa<ConstantSDNode>(V) || V.isUndef())
7137       continue;
7138     Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7139                        DAG.getConstant(i, dl, MVT::i32));
7140   }
7141 
7142   return Base;
7143 }
7144 
7145 // If this is a case we can't handle, return null and let the default
7146 // expansion code take care of it.
7147 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7148                                              const ARMSubtarget *ST) const {
7149   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7150   SDLoc dl(Op);
7151   EVT VT = Op.getValueType();
7152 
7153   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7154     return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7155 
7156   APInt SplatBits, SplatUndef;
7157   unsigned SplatBitSize;
7158   bool HasAnyUndefs;
7159   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7160     if (SplatUndef.isAllOnesValue())
7161       return DAG.getUNDEF(VT);
7162 
7163     if ((ST->hasNEON() && SplatBitSize <= 64) ||
7164         (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7165       // Check if an immediate VMOV works.
7166       EVT VmovVT;
7167       SDValue Val =
7168           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7169                             SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7170 
7171       if (Val.getNode()) {
7172         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7173         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7174       }
7175 
7176       // Try an immediate VMVN.
7177       uint64_t NegatedImm = (~SplatBits).getZExtValue();
7178       Val = isVMOVModifiedImm(
7179           NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7180           VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7181       if (Val.getNode()) {
7182         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7183         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7184       }
7185 
7186       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7187       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7188         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7189         if (ImmVal != -1) {
7190           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7191           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7192         }
7193       }
7194     }
7195   }
7196 
7197   // Scan through the operands to see if only one value is used.
7198   //
7199   // As an optimisation, even if more than one value is used it may be more
7200   // profitable to splat with one value then change some lanes.
7201   //
7202   // Heuristically we decide to do this if the vector has a "dominant" value,
7203   // defined as splatted to more than half of the lanes.
7204   unsigned NumElts = VT.getVectorNumElements();
7205   bool isOnlyLowElement = true;
7206   bool usesOnlyOneValue = true;
7207   bool hasDominantValue = false;
7208   bool isConstant = true;
7209 
7210   // Map of the number of times a particular SDValue appears in the
7211   // element list.
7212   DenseMap<SDValue, unsigned> ValueCounts;
7213   SDValue Value;
7214   for (unsigned i = 0; i < NumElts; ++i) {
7215     SDValue V = Op.getOperand(i);
7216     if (V.isUndef())
7217       continue;
7218     if (i > 0)
7219       isOnlyLowElement = false;
7220     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7221       isConstant = false;
7222 
7223     ValueCounts.insert(std::make_pair(V, 0));
7224     unsigned &Count = ValueCounts[V];
7225 
7226     // Is this value dominant? (takes up more than half of the lanes)
7227     if (++Count > (NumElts / 2)) {
7228       hasDominantValue = true;
7229       Value = V;
7230     }
7231   }
7232   if (ValueCounts.size() != 1)
7233     usesOnlyOneValue = false;
7234   if (!Value.getNode() && !ValueCounts.empty())
7235     Value = ValueCounts.begin()->first;
7236 
7237   if (ValueCounts.empty())
7238     return DAG.getUNDEF(VT);
7239 
7240   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7241   // Keep going if we are hitting this case.
7242   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7243     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7244 
7245   unsigned EltSize = VT.getScalarSizeInBits();
7246 
7247   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
7248   // i32 and try again.
7249   if (hasDominantValue && EltSize <= 32) {
7250     if (!isConstant) {
7251       SDValue N;
7252 
7253       // If we are VDUPing a value that comes directly from a vector, that will
7254       // cause an unnecessary move to and from a GPR, where instead we could
7255       // just use VDUPLANE. We can only do this if the lane being extracted
7256       // is at a constant index, as the VDUP from lane instructions only have
7257       // constant-index forms.
7258       ConstantSDNode *constIndex;
7259       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7260           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7261         // We need to create a new undef vector to use for the VDUPLANE if the
7262         // size of the vector from which we get the value is different than the
7263         // size of the vector that we need to create. We will insert the element
7264         // such that the register coalescer will remove unnecessary copies.
7265         if (VT != Value->getOperand(0).getValueType()) {
7266           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7267                              VT.getVectorNumElements();
7268           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7269                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7270                         Value, DAG.getConstant(index, dl, MVT::i32)),
7271                            DAG.getConstant(index, dl, MVT::i32));
7272         } else
7273           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7274                         Value->getOperand(0), Value->getOperand(1));
7275       } else
7276         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7277 
7278       if (!usesOnlyOneValue) {
7279         // The dominant value was splatted as 'N', but we now have to insert
7280         // all differing elements.
7281         for (unsigned I = 0; I < NumElts; ++I) {
7282           if (Op.getOperand(I) == Value)
7283             continue;
7284           SmallVector<SDValue, 3> Ops;
7285           Ops.push_back(N);
7286           Ops.push_back(Op.getOperand(I));
7287           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7288           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7289         }
7290       }
7291       return N;
7292     }
7293     if (VT.getVectorElementType().isFloatingPoint()) {
7294       SmallVector<SDValue, 8> Ops;
7295       MVT FVT = VT.getVectorElementType().getSimpleVT();
7296       assert(FVT == MVT::f32 || FVT == MVT::f16);
7297       MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7298       for (unsigned i = 0; i < NumElts; ++i)
7299         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7300                                   Op.getOperand(i)));
7301       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7302       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7303       Val = LowerBUILD_VECTOR(Val, DAG, ST);
7304       if (Val.getNode())
7305         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7306     }
7307     if (usesOnlyOneValue) {
7308       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7309       if (isConstant && Val.getNode())
7310         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7311     }
7312   }
7313 
7314   // If all elements are constants and the case above didn't get hit, fall back
7315   // to the default expansion, which will generate a load from the constant
7316   // pool.
7317   if (isConstant)
7318     return SDValue();
7319 
7320   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7321   if (NumElts >= 4) {
7322     SDValue shuffle = ReconstructShuffle(Op, DAG);
7323     if (shuffle != SDValue())
7324       return shuffle;
7325   }
7326 
7327   if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7328     // If we haven't found an efficient lowering, try splitting a 128-bit vector
7329     // into two 64-bit vectors; we might discover a better way to lower it.
7330     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7331     EVT ExtVT = VT.getVectorElementType();
7332     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7333     SDValue Lower =
7334         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7335     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7336       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7337     SDValue Upper = DAG.getBuildVector(
7338         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7339     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7340       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7341     if (Lower && Upper)
7342       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7343   }
7344 
7345   // Vectors with 32- or 64-bit elements can be built by directly assigning
7346   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
7347   // will be legalized.
7348   if (EltSize >= 32) {
7349     // Do the expansion with floating-point types, since that is what the VFP
7350     // registers are defined to use, and since i64 is not legal.
7351     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7352     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7353     SmallVector<SDValue, 8> Ops;
7354     for (unsigned i = 0; i < NumElts; ++i)
7355       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7356     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7357     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7358   }
7359 
7360   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7361   // know the default expansion would otherwise fall back on something even
7362   // worse. For a vector with one or two non-undef values, that's
7363   // scalar_to_vector for the elements followed by a shuffle (provided the
7364   // shuffle is valid for the target) and materialization element by element
7365   // on the stack followed by a load for everything else.
7366   if (!isConstant && !usesOnlyOneValue) {
7367     SDValue Vec = DAG.getUNDEF(VT);
7368     for (unsigned i = 0 ; i < NumElts; ++i) {
7369       SDValue V = Op.getOperand(i);
7370       if (V.isUndef())
7371         continue;
7372       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7373       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7374     }
7375     return Vec;
7376   }
7377 
7378   return SDValue();
7379 }
7380 
7381 // Gather data to see if the operation can be modelled as a
7382 // shuffle in combination with VEXTs.
7383 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7384                                               SelectionDAG &DAG) const {
7385   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7386   SDLoc dl(Op);
7387   EVT VT = Op.getValueType();
7388   unsigned NumElts = VT.getVectorNumElements();
7389 
7390   struct ShuffleSourceInfo {
7391     SDValue Vec;
7392     unsigned MinElt = std::numeric_limits<unsigned>::max();
7393     unsigned MaxElt = 0;
7394 
7395     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7396     // be compatible with the shuffle we intend to construct. As a result
7397     // ShuffleVec will be some sliding window into the original Vec.
7398     SDValue ShuffleVec;
7399 
7400     // Code should guarantee that element i in Vec starts at element "WindowBase
7401     // + i * WindowScale in ShuffleVec".
7402     int WindowBase = 0;
7403     int WindowScale = 1;
7404 
7405     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7406 
7407     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7408   };
7409 
7410   // First gather all vectors used as an immediate source for this BUILD_VECTOR
7411   // node.
7412   SmallVector<ShuffleSourceInfo, 2> Sources;
7413   for (unsigned i = 0; i < NumElts; ++i) {
7414     SDValue V = Op.getOperand(i);
7415     if (V.isUndef())
7416       continue;
7417     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7418       // A shuffle can only come from building a vector from various
7419       // elements of other vectors.
7420       return SDValue();
7421     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7422       // Furthermore, shuffles require a constant mask, whereas extractelts
7423       // accept variable indices.
7424       return SDValue();
7425     }
7426 
7427     // Add this element source to the list if it's not already there.
7428     SDValue SourceVec = V.getOperand(0);
7429     auto Source = llvm::find(Sources, SourceVec);
7430     if (Source == Sources.end())
7431       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7432 
7433     // Update the minimum and maximum lane number seen.
7434     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7435     Source->MinElt = std::min(Source->MinElt, EltNo);
7436     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7437   }
7438 
7439   // Currently only do something sane when at most two source vectors
7440   // are involved.
7441   if (Sources.size() > 2)
7442     return SDValue();
7443 
7444   // Find out the smallest element size among result and two sources, and use
7445   // it as element size to build the shuffle_vector.
7446   EVT SmallestEltTy = VT.getVectorElementType();
7447   for (auto &Source : Sources) {
7448     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7449     if (SrcEltTy.bitsLT(SmallestEltTy))
7450       SmallestEltTy = SrcEltTy;
7451   }
7452   unsigned ResMultiplier =
7453       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7454   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7455   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7456 
7457   // If the source vector is too wide or too narrow, we may nevertheless be able
7458   // to construct a compatible shuffle either by concatenating it with UNDEF or
7459   // extracting a suitable range of elements.
7460   for (auto &Src : Sources) {
7461     EVT SrcVT = Src.ShuffleVec.getValueType();
7462 
7463     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7464       continue;
7465 
7466     // This stage of the search produces a source with the same element type as
7467     // the original, but with a total width matching the BUILD_VECTOR output.
7468     EVT EltVT = SrcVT.getVectorElementType();
7469     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7470     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7471 
7472     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7473       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7474         return SDValue();
7475       // We can pad out the smaller vector for free, so if it's part of a
7476       // shuffle...
7477       Src.ShuffleVec =
7478           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7479                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7480       continue;
7481     }
7482 
7483     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7484       return SDValue();
7485 
7486     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7487       // Span too large for a VEXT to cope
7488       return SDValue();
7489     }
7490 
7491     if (Src.MinElt >= NumSrcElts) {
7492       // The extraction can just take the second half
7493       Src.ShuffleVec =
7494           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7495                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7496       Src.WindowBase = -NumSrcElts;
7497     } else if (Src.MaxElt < NumSrcElts) {
7498       // The extraction can just take the first half
7499       Src.ShuffleVec =
7500           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7501                       DAG.getConstant(0, dl, MVT::i32));
7502     } else {
7503       // An actual VEXT is needed
7504       SDValue VEXTSrc1 =
7505           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7506                       DAG.getConstant(0, dl, MVT::i32));
7507       SDValue VEXTSrc2 =
7508           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7509                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7510 
7511       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7512                                    VEXTSrc2,
7513                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
7514       Src.WindowBase = -Src.MinElt;
7515     }
7516   }
7517 
7518   // Another possible incompatibility occurs from the vector element types. We
7519   // can fix this by bitcasting the source vectors to the same type we intend
7520   // for the shuffle.
7521   for (auto &Src : Sources) {
7522     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7523     if (SrcEltTy == SmallestEltTy)
7524       continue;
7525     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7526     Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
7527     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7528     Src.WindowBase *= Src.WindowScale;
7529   }
7530 
7531   // Final sanity check before we try to actually produce a shuffle.
7532   LLVM_DEBUG(for (auto Src
7533                   : Sources)
7534                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7535 
7536   // The stars all align, our next step is to produce the mask for the shuffle.
7537   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7538   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7539   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7540     SDValue Entry = Op.getOperand(i);
7541     if (Entry.isUndef())
7542       continue;
7543 
7544     auto Src = llvm::find(Sources, Entry.getOperand(0));
7545     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7546 
7547     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7548     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7549     // segment.
7550     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7551     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7552                                VT.getScalarSizeInBits());
7553     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7554 
7555     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7556     // starting at the appropriate offset.
7557     int *LaneMask = &Mask[i * ResMultiplier];
7558 
7559     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7560     ExtractBase += NumElts * (Src - Sources.begin());
7561     for (int j = 0; j < LanesDefined; ++j)
7562       LaneMask[j] = ExtractBase + j;
7563   }
7564 
7565 
7566   // We can't handle more than two sources. This should have already
7567   // been checked before this point.
7568   assert(Sources.size() <= 2 && "Too many sources!");
7569 
7570   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7571   for (unsigned i = 0; i < Sources.size(); ++i)
7572     ShuffleOps[i] = Sources[i].ShuffleVec;
7573 
7574   SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7575                                             ShuffleOps[1], Mask, DAG);
7576   if (!Shuffle)
7577     return SDValue();
7578   return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
7579 }
7580 
7581 enum ShuffleOpCodes {
7582   OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7583   OP_VREV,
7584   OP_VDUP0,
7585   OP_VDUP1,
7586   OP_VDUP2,
7587   OP_VDUP3,
7588   OP_VEXT1,
7589   OP_VEXT2,
7590   OP_VEXT3,
7591   OP_VUZPL, // VUZP, left result
7592   OP_VUZPR, // VUZP, right result
7593   OP_VZIPL, // VZIP, left result
7594   OP_VZIPR, // VZIP, right result
7595   OP_VTRNL, // VTRN, left result
7596   OP_VTRNR  // VTRN, right result
7597 };
7598 
7599 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7600   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7601   switch (OpNum) {
7602   case OP_COPY:
7603   case OP_VREV:
7604   case OP_VDUP0:
7605   case OP_VDUP1:
7606   case OP_VDUP2:
7607   case OP_VDUP3:
7608     return true;
7609   }
7610   return false;
7611 }
7612 
7613 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7614 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7615 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7616 /// are assumed to be legal.
7617 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7618   if (VT.getVectorNumElements() == 4 &&
7619       (VT.is128BitVector() || VT.is64BitVector())) {
7620     unsigned PFIndexes[4];
7621     for (unsigned i = 0; i != 4; ++i) {
7622       if (M[i] < 0)
7623         PFIndexes[i] = 8;
7624       else
7625         PFIndexes[i] = M[i];
7626     }
7627 
7628     // Compute the index in the perfect shuffle table.
7629     unsigned PFTableIndex =
7630       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7631     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7632     unsigned Cost = (PFEntry >> 30);
7633 
7634     if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7635       return true;
7636   }
7637 
7638   bool ReverseVEXT, isV_UNDEF;
7639   unsigned Imm, WhichResult;
7640 
7641   unsigned EltSize = VT.getScalarSizeInBits();
7642   if (EltSize >= 32 ||
7643       ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7644       ShuffleVectorInst::isIdentityMask(M) ||
7645       isVREVMask(M, VT, 64) ||
7646       isVREVMask(M, VT, 32) ||
7647       isVREVMask(M, VT, 16))
7648     return true;
7649   else if (Subtarget->hasNEON() &&
7650            (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7651             isVTBLMask(M, VT) ||
7652             isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7653     return true;
7654   else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7655            isReverseMask(M, VT))
7656     return true;
7657   else if (Subtarget->hasMVEIntegerOps() &&
7658            (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1)))
7659     return true;
7660   else
7661     return false;
7662 }
7663 
7664 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7665 /// the specified operations to build the shuffle.
7666 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7667                                       SDValue RHS, SelectionDAG &DAG,
7668                                       const SDLoc &dl) {
7669   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7670   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7671   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7672 
7673   if (OpNum == OP_COPY) {
7674     if (LHSID == (1*9+2)*9+3) return LHS;
7675     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7676     return RHS;
7677   }
7678 
7679   SDValue OpLHS, OpRHS;
7680   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7681   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7682   EVT VT = OpLHS.getValueType();
7683 
7684   switch (OpNum) {
7685   default: llvm_unreachable("Unknown shuffle opcode!");
7686   case OP_VREV:
7687     // VREV divides the vector in half and swaps within the half.
7688     if (VT.getVectorElementType() == MVT::i32 ||
7689         VT.getVectorElementType() == MVT::f32)
7690       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7691     // vrev <4 x i16> -> VREV32
7692     if (VT.getVectorElementType() == MVT::i16)
7693       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7694     // vrev <4 x i8> -> VREV16
7695     assert(VT.getVectorElementType() == MVT::i8);
7696     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7697   case OP_VDUP0:
7698   case OP_VDUP1:
7699   case OP_VDUP2:
7700   case OP_VDUP3:
7701     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7702                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7703   case OP_VEXT1:
7704   case OP_VEXT2:
7705   case OP_VEXT3:
7706     return DAG.getNode(ARMISD::VEXT, dl, VT,
7707                        OpLHS, OpRHS,
7708                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7709   case OP_VUZPL:
7710   case OP_VUZPR:
7711     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7712                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7713   case OP_VZIPL:
7714   case OP_VZIPR:
7715     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7716                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7717   case OP_VTRNL:
7718   case OP_VTRNR:
7719     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7720                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7721   }
7722 }
7723 
7724 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7725                                        ArrayRef<int> ShuffleMask,
7726                                        SelectionDAG &DAG) {
7727   // Check to see if we can use the VTBL instruction.
7728   SDValue V1 = Op.getOperand(0);
7729   SDValue V2 = Op.getOperand(1);
7730   SDLoc DL(Op);
7731 
7732   SmallVector<SDValue, 8> VTBLMask;
7733   for (ArrayRef<int>::iterator
7734          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7735     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7736 
7737   if (V2.getNode()->isUndef())
7738     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7739                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7740 
7741   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7742                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7743 }
7744 
7745 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7746                                                       SelectionDAG &DAG) {
7747   SDLoc DL(Op);
7748   SDValue OpLHS = Op.getOperand(0);
7749   EVT VT = OpLHS.getValueType();
7750 
7751   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7752          "Expect an v8i16/v16i8 type");
7753   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7754   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7755   // extract the first 8 bytes into the top double word and the last 8 bytes
7756   // into the bottom double word. The v8i16 case is similar.
7757   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7758   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7759                      DAG.getConstant(ExtractNum, DL, MVT::i32));
7760 }
7761 
7762 static EVT getVectorTyFromPredicateVector(EVT VT) {
7763   switch (VT.getSimpleVT().SimpleTy) {
7764   case MVT::v4i1:
7765     return MVT::v4i32;
7766   case MVT::v8i1:
7767     return MVT::v8i16;
7768   case MVT::v16i1:
7769     return MVT::v16i8;
7770   default:
7771     llvm_unreachable("Unexpected vector predicate type");
7772   }
7773 }
7774 
7775 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7776                                     SelectionDAG &DAG) {
7777   // Converting from boolean predicates to integers involves creating a vector
7778   // of all ones or all zeroes and selecting the lanes based upon the real
7779   // predicate.
7780   SDValue AllOnes =
7781       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7782   AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7783 
7784   SDValue AllZeroes =
7785       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7786   AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7787 
7788   // Get full vector type from predicate type
7789   EVT NewVT = getVectorTyFromPredicateVector(VT);
7790 
7791   SDValue RecastV1;
7792   // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7793   // this to a v16i1. This cannot be done with an ordinary bitcast because the
7794   // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7795   // since we know in hardware the sizes are really the same.
7796   if (VT != MVT::v16i1)
7797     RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7798   else
7799     RecastV1 = Pred;
7800 
7801   // Select either all ones or zeroes depending upon the real predicate bits.
7802   SDValue PredAsVector =
7803       DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7804 
7805   // Recast our new predicate-as-integer v16i8 vector into something
7806   // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7807   return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7808 }
7809 
7810 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7811                                       const ARMSubtarget *ST) {
7812   EVT VT = Op.getValueType();
7813   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7814   ArrayRef<int> ShuffleMask = SVN->getMask();
7815 
7816   assert(ST->hasMVEIntegerOps() &&
7817          "No support for vector shuffle of boolean predicates");
7818 
7819   SDValue V1 = Op.getOperand(0);
7820   SDLoc dl(Op);
7821   if (isReverseMask(ShuffleMask, VT)) {
7822     SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7823     SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7824     SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7825                               DAG.getConstant(16, dl, MVT::i32));
7826     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7827   }
7828 
7829   // Until we can come up with optimised cases for every single vector
7830   // shuffle in existence we have chosen the least painful strategy. This is
7831   // to essentially promote the boolean predicate to a 8-bit integer, where
7832   // each predicate represents a byte. Then we fall back on a normal integer
7833   // vector shuffle and convert the result back into a predicate vector. In
7834   // many cases the generated code might be even better than scalar code
7835   // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7836   // fields in a register into 8 other arbitrary 2-bit fields!
7837   SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7838   EVT NewVT = PredAsVector.getValueType();
7839 
7840   // Do the shuffle!
7841   SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7842                                           DAG.getUNDEF(NewVT), ShuffleMask);
7843 
7844   // Now return the result of comparing the shuffled vector with zero,
7845   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7846   return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7847                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7848 }
7849 
7850 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
7851                                             ArrayRef<int> ShuffleMask,
7852                                             SelectionDAG &DAG) {
7853   // Attempt to lower the vector shuffle using as many whole register movs as
7854   // possible. This is useful for types smaller than 32bits, which would
7855   // often otherwise become a series for grp movs.
7856   SDLoc dl(Op);
7857   EVT VT = Op.getValueType();
7858   if (VT.getScalarSizeInBits() >= 32)
7859     return SDValue();
7860 
7861   assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
7862          "Unexpected vector type");
7863   int NumElts = VT.getVectorNumElements();
7864   int QuarterSize = NumElts / 4;
7865   // The four final parts of the vector, as i32's
7866   SDValue Parts[4];
7867 
7868   // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
7869   // <u,u,u,u>), returning the vmov lane index
7870   auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
7871     // Detect which mov lane this would be from the first non-undef element.
7872     int MovIdx = -1;
7873     for (int i = 0; i < Length; i++) {
7874       if (ShuffleMask[Start + i] >= 0) {
7875         if (ShuffleMask[Start + i] % Length != i)
7876           return -1;
7877         MovIdx = ShuffleMask[Start + i] / Length;
7878         break;
7879       }
7880     }
7881     // If all items are undef, leave this for other combines
7882     if (MovIdx == -1)
7883       return -1;
7884     // Check the remaining values are the correct part of the same mov
7885     for (int i = 1; i < Length; i++) {
7886       if (ShuffleMask[Start + i] >= 0 &&
7887           (ShuffleMask[Start + i] / Length != MovIdx ||
7888            ShuffleMask[Start + i] % Length != i))
7889         return -1;
7890     }
7891     return MovIdx;
7892   };
7893 
7894   for (int Part = 0; Part < 4; ++Part) {
7895     // Does this part look like a mov
7896     int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
7897     if (Elt != -1) {
7898       SDValue Input = Op->getOperand(0);
7899       if (Elt >= 4) {
7900         Input = Op->getOperand(1);
7901         Elt -= 4;
7902       }
7903       SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input);
7904       Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast,
7905                                 DAG.getConstant(Elt, dl, MVT::i32));
7906     }
7907   }
7908 
7909   // Nothing interesting found, just return
7910   if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
7911     return SDValue();
7912 
7913   // The other parts need to be built with the old shuffle vector, cast to a
7914   // v4i32 and extract_vector_elts
7915   if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
7916     SmallVector<int, 16> NewShuffleMask;
7917     for (int Part = 0; Part < 4; ++Part)
7918       for (int i = 0; i < QuarterSize; i++)
7919         NewShuffleMask.push_back(
7920             Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
7921     SDValue NewShuffle = DAG.getVectorShuffle(
7922         VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
7923     SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle);
7924 
7925     for (int Part = 0; Part < 4; ++Part)
7926       if (!Parts[Part])
7927         Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7928                                   BitCast, DAG.getConstant(Part, dl, MVT::i32));
7929   }
7930   // Build a vector out of the various parts and bitcast it back to the original
7931   // type.
7932   SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts);
7933   return DAG.getBitcast(VT, NewVec);
7934 }
7935 
7936 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7937                                    const ARMSubtarget *ST) {
7938   SDValue V1 = Op.getOperand(0);
7939   SDValue V2 = Op.getOperand(1);
7940   SDLoc dl(Op);
7941   EVT VT = Op.getValueType();
7942   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7943   unsigned EltSize = VT.getScalarSizeInBits();
7944 
7945   if (ST->hasMVEIntegerOps() && EltSize == 1)
7946     return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7947 
7948   // Convert shuffles that are directly supported on NEON to target-specific
7949   // DAG nodes, instead of keeping them as shuffles and matching them again
7950   // during code selection.  This is more efficient and avoids the possibility
7951   // of inconsistencies between legalization and selection.
7952   // FIXME: floating-point vectors should be canonicalized to integer vectors
7953   // of the same time so that they get CSEd properly.
7954   ArrayRef<int> ShuffleMask = SVN->getMask();
7955 
7956   if (EltSize <= 32) {
7957     if (SVN->isSplat()) {
7958       int Lane = SVN->getSplatIndex();
7959       // If this is undef splat, generate it via "just" vdup, if possible.
7960       if (Lane == -1) Lane = 0;
7961 
7962       // Test if V1 is a SCALAR_TO_VECTOR.
7963       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7964         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7965       }
7966       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7967       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7968       // reaches it).
7969       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7970           !isa<ConstantSDNode>(V1.getOperand(0))) {
7971         bool IsScalarToVector = true;
7972         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7973           if (!V1.getOperand(i).isUndef()) {
7974             IsScalarToVector = false;
7975             break;
7976           }
7977         if (IsScalarToVector)
7978           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7979       }
7980       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7981                          DAG.getConstant(Lane, dl, MVT::i32));
7982     }
7983 
7984     bool ReverseVEXT = false;
7985     unsigned Imm = 0;
7986     if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7987       if (ReverseVEXT)
7988         std::swap(V1, V2);
7989       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7990                          DAG.getConstant(Imm, dl, MVT::i32));
7991     }
7992 
7993     if (isVREVMask(ShuffleMask, VT, 64))
7994       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7995     if (isVREVMask(ShuffleMask, VT, 32))
7996       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7997     if (isVREVMask(ShuffleMask, VT, 16))
7998       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7999 
8000     if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8001       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8002                          DAG.getConstant(Imm, dl, MVT::i32));
8003     }
8004 
8005     // Check for Neon shuffles that modify both input vectors in place.
8006     // If both results are used, i.e., if there are two shuffles with the same
8007     // source operands and with masks corresponding to both results of one of
8008     // these operations, DAG memoization will ensure that a single node is
8009     // used for both shuffles.
8010     unsigned WhichResult = 0;
8011     bool isV_UNDEF = false;
8012     if (ST->hasNEON()) {
8013       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8014               ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8015         if (isV_UNDEF)
8016           V2 = V1;
8017         return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8018             .getValue(WhichResult);
8019       }
8020     }
8021     if (ST->hasMVEIntegerOps()) {
8022       if (isVMOVNMask(ShuffleMask, VT, 0))
8023         return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8024                            DAG.getConstant(0, dl, MVT::i32));
8025       if (isVMOVNMask(ShuffleMask, VT, 1))
8026         return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8027                            DAG.getConstant(1, dl, MVT::i32));
8028     }
8029 
8030     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8031     // shuffles that produce a result larger than their operands with:
8032     //   shuffle(concat(v1, undef), concat(v2, undef))
8033     // ->
8034     //   shuffle(concat(v1, v2), undef)
8035     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8036     //
8037     // This is useful in the general case, but there are special cases where
8038     // native shuffles produce larger results: the two-result ops.
8039     //
8040     // Look through the concat when lowering them:
8041     //   shuffle(concat(v1, v2), undef)
8042     // ->
8043     //   concat(VZIP(v1, v2):0, :1)
8044     //
8045     if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8046       SDValue SubV1 = V1->getOperand(0);
8047       SDValue SubV2 = V1->getOperand(1);
8048       EVT SubVT = SubV1.getValueType();
8049 
8050       // We expect these to have been canonicalized to -1.
8051       assert(llvm::all_of(ShuffleMask, [&](int i) {
8052         return i < (int)VT.getVectorNumElements();
8053       }) && "Unexpected shuffle index into UNDEF operand!");
8054 
8055       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8056               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8057         if (isV_UNDEF)
8058           SubV2 = SubV1;
8059         assert((WhichResult == 0) &&
8060                "In-place shuffle of concat can only have one result!");
8061         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8062                                   SubV1, SubV2);
8063         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8064                            Res.getValue(1));
8065       }
8066     }
8067   }
8068 
8069   // If the shuffle is not directly supported and it has 4 elements, use
8070   // the PerfectShuffle-generated table to synthesize it from other shuffles.
8071   unsigned NumElts = VT.getVectorNumElements();
8072   if (NumElts == 4) {
8073     unsigned PFIndexes[4];
8074     for (unsigned i = 0; i != 4; ++i) {
8075       if (ShuffleMask[i] < 0)
8076         PFIndexes[i] = 8;
8077       else
8078         PFIndexes[i] = ShuffleMask[i];
8079     }
8080 
8081     // Compute the index in the perfect shuffle table.
8082     unsigned PFTableIndex =
8083       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8084     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8085     unsigned Cost = (PFEntry >> 30);
8086 
8087     if (Cost <= 4) {
8088       if (ST->hasNEON())
8089         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8090       else if (isLegalMVEShuffleOp(PFEntry)) {
8091         unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8092         unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8093         unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8094         unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8095         if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8096           return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8097       }
8098     }
8099   }
8100 
8101   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8102   if (EltSize >= 32) {
8103     // Do the expansion with floating-point types, since that is what the VFP
8104     // registers are defined to use, and since i64 is not legal.
8105     EVT EltVT = EVT::getFloatingPointVT(EltSize);
8106     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8107     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8108     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8109     SmallVector<SDValue, 8> Ops;
8110     for (unsigned i = 0; i < NumElts; ++i) {
8111       if (ShuffleMask[i] < 0)
8112         Ops.push_back(DAG.getUNDEF(EltVT));
8113       else
8114         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8115                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
8116                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8117                                                   dl, MVT::i32)));
8118     }
8119     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8120     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8121   }
8122 
8123   if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
8124     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
8125 
8126   if (ST->hasNEON() && VT == MVT::v8i8)
8127     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8128       return NewOp;
8129 
8130   if (ST->hasMVEIntegerOps())
8131     if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8132       return NewOp;
8133 
8134   return SDValue();
8135 }
8136 
8137 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8138                                          const ARMSubtarget *ST) {
8139   EVT VecVT = Op.getOperand(0).getValueType();
8140   SDLoc dl(Op);
8141 
8142   assert(ST->hasMVEIntegerOps() &&
8143          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8144 
8145   SDValue Conv =
8146       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8147   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8148   unsigned LaneWidth =
8149       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8150   unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8151   SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8152                             Op.getOperand(1), DAG.getValueType(MVT::i1));
8153   SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8154                             DAG.getConstant(~Mask, dl, MVT::i32));
8155   return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8156 }
8157 
8158 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8159                                                   SelectionDAG &DAG) const {
8160   // INSERT_VECTOR_ELT is legal only for immediate indexes.
8161   SDValue Lane = Op.getOperand(2);
8162   if (!isa<ConstantSDNode>(Lane))
8163     return SDValue();
8164 
8165   SDValue Elt = Op.getOperand(1);
8166   EVT EltVT = Elt.getValueType();
8167 
8168   if (Subtarget->hasMVEIntegerOps() &&
8169       Op.getValueType().getScalarSizeInBits() == 1)
8170     return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8171 
8172   if (getTypeAction(*DAG.getContext(), EltVT) ==
8173       TargetLowering::TypePromoteFloat) {
8174     // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8175     // but the type system will try to do that if we don't intervene.
8176     // Reinterpret any such vector-element insertion as one with the
8177     // corresponding integer types.
8178 
8179     SDLoc dl(Op);
8180 
8181     EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8182     assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8183            TargetLowering::TypePromoteFloat);
8184 
8185     SDValue VecIn = Op.getOperand(0);
8186     EVT VecVT = VecIn.getValueType();
8187     EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8188                                   VecVT.getVectorNumElements());
8189 
8190     SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8191     SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8192     SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8193                                   IVecIn, IElt, Lane);
8194     return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8195   }
8196 
8197   return Op;
8198 }
8199 
8200 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8201                                           const ARMSubtarget *ST) {
8202   EVT VecVT = Op.getOperand(0).getValueType();
8203   SDLoc dl(Op);
8204 
8205   assert(ST->hasMVEIntegerOps() &&
8206          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8207 
8208   SDValue Conv =
8209       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8210   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8211   unsigned LaneWidth =
8212       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8213   SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8214                               DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8215   return Shift;
8216 }
8217 
8218 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8219                                        const ARMSubtarget *ST) {
8220   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8221   SDValue Lane = Op.getOperand(1);
8222   if (!isa<ConstantSDNode>(Lane))
8223     return SDValue();
8224 
8225   SDValue Vec = Op.getOperand(0);
8226   EVT VT = Vec.getValueType();
8227 
8228   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8229     return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8230 
8231   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8232     SDLoc dl(Op);
8233     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8234   }
8235 
8236   return Op;
8237 }
8238 
8239 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8240                                       const ARMSubtarget *ST) {
8241   SDValue V1 = Op.getOperand(0);
8242   SDValue V2 = Op.getOperand(1);
8243   SDLoc dl(Op);
8244   EVT VT = Op.getValueType();
8245   EVT Op1VT = V1.getValueType();
8246   EVT Op2VT = V2.getValueType();
8247   unsigned NumElts = VT.getVectorNumElements();
8248 
8249   assert(Op1VT == Op2VT && "Operand types don't match!");
8250   assert(VT.getScalarSizeInBits() == 1 &&
8251          "Unexpected custom CONCAT_VECTORS lowering");
8252   assert(ST->hasMVEIntegerOps() &&
8253          "CONCAT_VECTORS lowering only supported for MVE");
8254 
8255   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8256   SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8257 
8258   // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8259   // promoted to v8i16, etc.
8260 
8261   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8262 
8263   // Extract the vector elements from Op1 and Op2 one by one and truncate them
8264   // to be the right size for the destination. For example, if Op1 is v4i1 then
8265   // the promoted vector is v4i32. The result of concatentation gives a v8i1,
8266   // which when promoted is v8i16. That means each i32 element from Op1 needs
8267   // truncating to i16 and inserting in the result.
8268   EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8269   SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8270   auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8271     EVT NewVT = NewV.getValueType();
8272     EVT ConcatVT = ConVec.getValueType();
8273     for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8274       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8275                                 DAG.getIntPtrConstant(i, dl));
8276       ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8277                            DAG.getConstant(j, dl, MVT::i32));
8278     }
8279     return ConVec;
8280   };
8281   unsigned j = 0;
8282   ConVec = ExractInto(NewV1, ConVec, j);
8283   ConVec = ExractInto(NewV2, ConVec, j);
8284 
8285   // Now return the result of comparing the subvector with zero,
8286   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8287   return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8288                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8289 }
8290 
8291 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8292                                    const ARMSubtarget *ST) {
8293   EVT VT = Op->getValueType(0);
8294   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8295     return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8296 
8297   // The only time a CONCAT_VECTORS operation can have legal types is when
8298   // two 64-bit vectors are concatenated to a 128-bit vector.
8299   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8300          "unexpected CONCAT_VECTORS");
8301   SDLoc dl(Op);
8302   SDValue Val = DAG.getUNDEF(MVT::v2f64);
8303   SDValue Op0 = Op.getOperand(0);
8304   SDValue Op1 = Op.getOperand(1);
8305   if (!Op0.isUndef())
8306     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8307                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8308                       DAG.getIntPtrConstant(0, dl));
8309   if (!Op1.isUndef())
8310     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8311                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8312                       DAG.getIntPtrConstant(1, dl));
8313   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8314 }
8315 
8316 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8317                                       const ARMSubtarget *ST) {
8318   SDValue V1 = Op.getOperand(0);
8319   SDValue V2 = Op.getOperand(1);
8320   SDLoc dl(Op);
8321   EVT VT = Op.getValueType();
8322   EVT Op1VT = V1.getValueType();
8323   unsigned NumElts = VT.getVectorNumElements();
8324   unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8325 
8326   assert(VT.getScalarSizeInBits() == 1 &&
8327          "Unexpected custom EXTRACT_SUBVECTOR lowering");
8328   assert(ST->hasMVEIntegerOps() &&
8329          "EXTRACT_SUBVECTOR lowering only supported for MVE");
8330 
8331   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8332 
8333   // We now have Op1 promoted to a vector of integers, where v8i1 gets
8334   // promoted to v8i16, etc.
8335 
8336   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8337 
8338   EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8339   SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8340   for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8341     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8342                               DAG.getIntPtrConstant(i, dl));
8343     SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8344                          DAG.getConstant(j, dl, MVT::i32));
8345   }
8346 
8347   // Now return the result of comparing the subvector with zero,
8348   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8349   return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8350                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8351 }
8352 
8353 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8354 /// element has been zero/sign-extended, depending on the isSigned parameter,
8355 /// from an integer type half its size.
8356 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8357                                    bool isSigned) {
8358   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8359   EVT VT = N->getValueType(0);
8360   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8361     SDNode *BVN = N->getOperand(0).getNode();
8362     if (BVN->getValueType(0) != MVT::v4i32 ||
8363         BVN->getOpcode() != ISD::BUILD_VECTOR)
8364       return false;
8365     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8366     unsigned HiElt = 1 - LoElt;
8367     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8368     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8369     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8370     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8371     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8372       return false;
8373     if (isSigned) {
8374       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8375           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8376         return true;
8377     } else {
8378       if (Hi0->isNullValue() && Hi1->isNullValue())
8379         return true;
8380     }
8381     return false;
8382   }
8383 
8384   if (N->getOpcode() != ISD::BUILD_VECTOR)
8385     return false;
8386 
8387   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8388     SDNode *Elt = N->getOperand(i).getNode();
8389     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8390       unsigned EltSize = VT.getScalarSizeInBits();
8391       unsigned HalfSize = EltSize / 2;
8392       if (isSigned) {
8393         if (!isIntN(HalfSize, C->getSExtValue()))
8394           return false;
8395       } else {
8396         if (!isUIntN(HalfSize, C->getZExtValue()))
8397           return false;
8398       }
8399       continue;
8400     }
8401     return false;
8402   }
8403 
8404   return true;
8405 }
8406 
8407 /// isSignExtended - Check if a node is a vector value that is sign-extended
8408 /// or a constant BUILD_VECTOR with sign-extended elements.
8409 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8410   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8411     return true;
8412   if (isExtendedBUILD_VECTOR(N, DAG, true))
8413     return true;
8414   return false;
8415 }
8416 
8417 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8418 /// or a constant BUILD_VECTOR with zero-extended elements.
8419 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8420   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8421     return true;
8422   if (isExtendedBUILD_VECTOR(N, DAG, false))
8423     return true;
8424   return false;
8425 }
8426 
8427 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8428   if (OrigVT.getSizeInBits() >= 64)
8429     return OrigVT;
8430 
8431   assert(OrigVT.isSimple() && "Expecting a simple value type");
8432 
8433   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8434   switch (OrigSimpleTy) {
8435   default: llvm_unreachable("Unexpected Vector Type");
8436   case MVT::v2i8:
8437   case MVT::v2i16:
8438      return MVT::v2i32;
8439   case MVT::v4i8:
8440     return  MVT::v4i16;
8441   }
8442 }
8443 
8444 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8445 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8446 /// We insert the required extension here to get the vector to fill a D register.
8447 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8448                                             const EVT &OrigTy,
8449                                             const EVT &ExtTy,
8450                                             unsigned ExtOpcode) {
8451   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8452   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8453   // 64-bits we need to insert a new extension so that it will be 64-bits.
8454   assert(ExtTy.is128BitVector() && "Unexpected extension size");
8455   if (OrigTy.getSizeInBits() >= 64)
8456     return N;
8457 
8458   // Must extend size to at least 64 bits to be used as an operand for VMULL.
8459   EVT NewVT = getExtensionTo64Bits(OrigTy);
8460 
8461   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8462 }
8463 
8464 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8465 /// does not do any sign/zero extension. If the original vector is less
8466 /// than 64 bits, an appropriate extension will be added after the load to
8467 /// reach a total size of 64 bits. We have to add the extension separately
8468 /// because ARM does not have a sign/zero extending load for vectors.
8469 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8470   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8471 
8472   // The load already has the right type.
8473   if (ExtendedTy == LD->getMemoryVT())
8474     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8475                        LD->getBasePtr(), LD->getPointerInfo(),
8476                        LD->getAlignment(), LD->getMemOperand()->getFlags());
8477 
8478   // We need to create a zextload/sextload. We cannot just create a load
8479   // followed by a zext/zext node because LowerMUL is also run during normal
8480   // operation legalization where we can't create illegal types.
8481   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8482                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8483                         LD->getMemoryVT(), LD->getAlignment(),
8484                         LD->getMemOperand()->getFlags());
8485 }
8486 
8487 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8488 /// extending load, or BUILD_VECTOR with extended elements, return the
8489 /// unextended value. The unextended vector should be 64 bits so that it can
8490 /// be used as an operand to a VMULL instruction. If the original vector size
8491 /// before extension is less than 64 bits we add a an extension to resize
8492 /// the vector to 64 bits.
8493 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8494   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8495     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8496                                         N->getOperand(0)->getValueType(0),
8497                                         N->getValueType(0),
8498                                         N->getOpcode());
8499 
8500   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8501     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8502            "Expected extending load");
8503 
8504     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8505     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8506     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8507     SDValue extLoad =
8508         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8509     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8510 
8511     return newLoad;
8512   }
8513 
8514   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
8515   // have been legalized as a BITCAST from v4i32.
8516   if (N->getOpcode() == ISD::BITCAST) {
8517     SDNode *BVN = N->getOperand(0).getNode();
8518     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8519            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8520     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8521     return DAG.getBuildVector(
8522         MVT::v2i32, SDLoc(N),
8523         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8524   }
8525   // Construct a new BUILD_VECTOR with elements truncated to half the size.
8526   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8527   EVT VT = N->getValueType(0);
8528   unsigned EltSize = VT.getScalarSizeInBits() / 2;
8529   unsigned NumElts = VT.getVectorNumElements();
8530   MVT TruncVT = MVT::getIntegerVT(EltSize);
8531   SmallVector<SDValue, 8> Ops;
8532   SDLoc dl(N);
8533   for (unsigned i = 0; i != NumElts; ++i) {
8534     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8535     const APInt &CInt = C->getAPIntValue();
8536     // Element types smaller than 32 bits are not legal, so use i32 elements.
8537     // The values are implicitly truncated so sext vs. zext doesn't matter.
8538     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8539   }
8540   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8541 }
8542 
8543 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8544   unsigned Opcode = N->getOpcode();
8545   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8546     SDNode *N0 = N->getOperand(0).getNode();
8547     SDNode *N1 = N->getOperand(1).getNode();
8548     return N0->hasOneUse() && N1->hasOneUse() &&
8549       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8550   }
8551   return false;
8552 }
8553 
8554 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8555   unsigned Opcode = N->getOpcode();
8556   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8557     SDNode *N0 = N->getOperand(0).getNode();
8558     SDNode *N1 = N->getOperand(1).getNode();
8559     return N0->hasOneUse() && N1->hasOneUse() &&
8560       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8561   }
8562   return false;
8563 }
8564 
8565 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8566   // Multiplications are only custom-lowered for 128-bit vectors so that
8567   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
8568   EVT VT = Op.getValueType();
8569   assert(VT.is128BitVector() && VT.isInteger() &&
8570          "unexpected type for custom-lowering ISD::MUL");
8571   SDNode *N0 = Op.getOperand(0).getNode();
8572   SDNode *N1 = Op.getOperand(1).getNode();
8573   unsigned NewOpc = 0;
8574   bool isMLA = false;
8575   bool isN0SExt = isSignExtended(N0, DAG);
8576   bool isN1SExt = isSignExtended(N1, DAG);
8577   if (isN0SExt && isN1SExt)
8578     NewOpc = ARMISD::VMULLs;
8579   else {
8580     bool isN0ZExt = isZeroExtended(N0, DAG);
8581     bool isN1ZExt = isZeroExtended(N1, DAG);
8582     if (isN0ZExt && isN1ZExt)
8583       NewOpc = ARMISD::VMULLu;
8584     else if (isN1SExt || isN1ZExt) {
8585       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8586       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8587       if (isN1SExt && isAddSubSExt(N0, DAG)) {
8588         NewOpc = ARMISD::VMULLs;
8589         isMLA = true;
8590       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8591         NewOpc = ARMISD::VMULLu;
8592         isMLA = true;
8593       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8594         std::swap(N0, N1);
8595         NewOpc = ARMISD::VMULLu;
8596         isMLA = true;
8597       }
8598     }
8599 
8600     if (!NewOpc) {
8601       if (VT == MVT::v2i64)
8602         // Fall through to expand this.  It is not legal.
8603         return SDValue();
8604       else
8605         // Other vector multiplications are legal.
8606         return Op;
8607     }
8608   }
8609 
8610   // Legalize to a VMULL instruction.
8611   SDLoc DL(Op);
8612   SDValue Op0;
8613   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8614   if (!isMLA) {
8615     Op0 = SkipExtensionForVMULL(N0, DAG);
8616     assert(Op0.getValueType().is64BitVector() &&
8617            Op1.getValueType().is64BitVector() &&
8618            "unexpected types for extended operands to VMULL");
8619     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8620   }
8621 
8622   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8623   // isel lowering to take advantage of no-stall back to back vmul + vmla.
8624   //   vmull q0, d4, d6
8625   //   vmlal q0, d5, d6
8626   // is faster than
8627   //   vaddl q0, d4, d5
8628   //   vmovl q1, d6
8629   //   vmul  q0, q0, q1
8630   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8631   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8632   EVT Op1VT = Op1.getValueType();
8633   return DAG.getNode(N0->getOpcode(), DL, VT,
8634                      DAG.getNode(NewOpc, DL, VT,
8635                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8636                      DAG.getNode(NewOpc, DL, VT,
8637                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8638 }
8639 
8640 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8641                               SelectionDAG &DAG) {
8642   // TODO: Should this propagate fast-math-flags?
8643 
8644   // Convert to float
8645   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8646   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8647   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8648   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8649   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8650   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8651   // Get reciprocal estimate.
8652   // float4 recip = vrecpeq_f32(yf);
8653   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8654                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8655                    Y);
8656   // Because char has a smaller range than uchar, we can actually get away
8657   // without any newton steps.  This requires that we use a weird bias
8658   // of 0xb000, however (again, this has been exhaustively tested).
8659   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8660   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8661   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8662   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8663   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8664   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8665   // Convert back to short.
8666   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8667   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8668   return X;
8669 }
8670 
8671 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8672                                SelectionDAG &DAG) {
8673   // TODO: Should this propagate fast-math-flags?
8674 
8675   SDValue N2;
8676   // Convert to float.
8677   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8678   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8679   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8680   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8681   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8682   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8683 
8684   // Use reciprocal estimate and one refinement step.
8685   // float4 recip = vrecpeq_f32(yf);
8686   // recip *= vrecpsq_f32(yf, recip);
8687   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8688                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8689                    N1);
8690   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8691                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8692                    N1, N2);
8693   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8694   // Because short has a smaller range than ushort, we can actually get away
8695   // with only a single newton step.  This requires that we use a weird bias
8696   // of 89, however (again, this has been exhaustively tested).
8697   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8698   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8699   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8700   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8701   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8702   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8703   // Convert back to integer and return.
8704   // return vmovn_s32(vcvt_s32_f32(result));
8705   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8706   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8707   return N0;
8708 }
8709 
8710 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8711                          const ARMSubtarget *ST) {
8712   EVT VT = Op.getValueType();
8713   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8714          "unexpected type for custom-lowering ISD::SDIV");
8715 
8716   SDLoc dl(Op);
8717   SDValue N0 = Op.getOperand(0);
8718   SDValue N1 = Op.getOperand(1);
8719   SDValue N2, N3;
8720 
8721   if (VT == MVT::v8i8) {
8722     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8723     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8724 
8725     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8726                      DAG.getIntPtrConstant(4, dl));
8727     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8728                      DAG.getIntPtrConstant(4, dl));
8729     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8730                      DAG.getIntPtrConstant(0, dl));
8731     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8732                      DAG.getIntPtrConstant(0, dl));
8733 
8734     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8735     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8736 
8737     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8738     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8739 
8740     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8741     return N0;
8742   }
8743   return LowerSDIV_v4i16(N0, N1, dl, DAG);
8744 }
8745 
8746 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8747                          const ARMSubtarget *ST) {
8748   // TODO: Should this propagate fast-math-flags?
8749   EVT VT = Op.getValueType();
8750   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8751          "unexpected type for custom-lowering ISD::UDIV");
8752 
8753   SDLoc dl(Op);
8754   SDValue N0 = Op.getOperand(0);
8755   SDValue N1 = Op.getOperand(1);
8756   SDValue N2, N3;
8757 
8758   if (VT == MVT::v8i8) {
8759     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8760     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8761 
8762     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8763                      DAG.getIntPtrConstant(4, dl));
8764     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8765                      DAG.getIntPtrConstant(4, dl));
8766     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8767                      DAG.getIntPtrConstant(0, dl));
8768     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8769                      DAG.getIntPtrConstant(0, dl));
8770 
8771     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8772     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8773 
8774     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8775     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8776 
8777     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8778                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8779                                      MVT::i32),
8780                      N0);
8781     return N0;
8782   }
8783 
8784   // v4i16 sdiv ... Convert to float.
8785   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8786   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8787   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8788   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8789   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8790   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8791 
8792   // Use reciprocal estimate and two refinement steps.
8793   // float4 recip = vrecpeq_f32(yf);
8794   // recip *= vrecpsq_f32(yf, recip);
8795   // recip *= vrecpsq_f32(yf, recip);
8796   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8797                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8798                    BN1);
8799   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8800                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8801                    BN1, N2);
8802   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8803   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8804                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8805                    BN1, N2);
8806   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8807   // Simply multiplying by the reciprocal estimate can leave us a few ulps
8808   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8809   // and that it will never cause us to return an answer too large).
8810   // float4 result = as_float4(as_int4(xf*recip) + 2);
8811   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8812   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8813   N1 = DAG.getConstant(2, dl, MVT::v4i32);
8814   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8815   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8816   // Convert back to integer and return.
8817   // return vmovn_u32(vcvt_s32_f32(result));
8818   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8819   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8820   return N0;
8821 }
8822 
8823 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8824   SDNode *N = Op.getNode();
8825   EVT VT = N->getValueType(0);
8826   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8827 
8828   SDValue Carry = Op.getOperand(2);
8829 
8830   SDLoc DL(Op);
8831 
8832   SDValue Result;
8833   if (Op.getOpcode() == ISD::ADDCARRY) {
8834     // This converts the boolean value carry into the carry flag.
8835     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8836 
8837     // Do the addition proper using the carry flag we wanted.
8838     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8839                          Op.getOperand(1), Carry);
8840 
8841     // Now convert the carry flag into a boolean value.
8842     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8843   } else {
8844     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8845     // have to invert the carry first.
8846     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8847                         DAG.getConstant(1, DL, MVT::i32), Carry);
8848     // This converts the boolean value carry into the carry flag.
8849     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8850 
8851     // Do the subtraction proper using the carry flag we wanted.
8852     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8853                          Op.getOperand(1), Carry);
8854 
8855     // Now convert the carry flag into a boolean value.
8856     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8857     // But the carry returned by ARMISD::SUBE is not a borrow as expected
8858     // by ISD::SUBCARRY, so compute 1 - C.
8859     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8860                         DAG.getConstant(1, DL, MVT::i32), Carry);
8861   }
8862 
8863   // Return both values.
8864   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8865 }
8866 
8867 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8868   assert(Subtarget->isTargetDarwin());
8869 
8870   // For iOS, we want to call an alternative entry point: __sincos_stret,
8871   // return values are passed via sret.
8872   SDLoc dl(Op);
8873   SDValue Arg = Op.getOperand(0);
8874   EVT ArgVT = Arg.getValueType();
8875   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8876   auto PtrVT = getPointerTy(DAG.getDataLayout());
8877 
8878   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8880 
8881   // Pair of floats / doubles used to pass the result.
8882   Type *RetTy = StructType::get(ArgTy, ArgTy);
8883   auto &DL = DAG.getDataLayout();
8884 
8885   ArgListTy Args;
8886   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8887   SDValue SRet;
8888   if (ShouldUseSRet) {
8889     // Create stack object for sret.
8890     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8891     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8892     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8893     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8894 
8895     ArgListEntry Entry;
8896     Entry.Node = SRet;
8897     Entry.Ty = RetTy->getPointerTo();
8898     Entry.IsSExt = false;
8899     Entry.IsZExt = false;
8900     Entry.IsSRet = true;
8901     Args.push_back(Entry);
8902     RetTy = Type::getVoidTy(*DAG.getContext());
8903   }
8904 
8905   ArgListEntry Entry;
8906   Entry.Node = Arg;
8907   Entry.Ty = ArgTy;
8908   Entry.IsSExt = false;
8909   Entry.IsZExt = false;
8910   Args.push_back(Entry);
8911 
8912   RTLIB::Libcall LC =
8913       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8914   const char *LibcallName = getLibcallName(LC);
8915   CallingConv::ID CC = getLibcallCallingConv(LC);
8916   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8917 
8918   TargetLowering::CallLoweringInfo CLI(DAG);
8919   CLI.setDebugLoc(dl)
8920       .setChain(DAG.getEntryNode())
8921       .setCallee(CC, RetTy, Callee, std::move(Args))
8922       .setDiscardResult(ShouldUseSRet);
8923   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8924 
8925   if (!ShouldUseSRet)
8926     return CallResult.first;
8927 
8928   SDValue LoadSin =
8929       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8930 
8931   // Address of cos field.
8932   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8933                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8934   SDValue LoadCos =
8935       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8936 
8937   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8938   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8939                      LoadSin.getValue(0), LoadCos.getValue(0));
8940 }
8941 
8942 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8943                                                   bool Signed,
8944                                                   SDValue &Chain) const {
8945   EVT VT = Op.getValueType();
8946   assert((VT == MVT::i32 || VT == MVT::i64) &&
8947          "unexpected type for custom lowering DIV");
8948   SDLoc dl(Op);
8949 
8950   const auto &DL = DAG.getDataLayout();
8951   const auto &TLI = DAG.getTargetLoweringInfo();
8952 
8953   const char *Name = nullptr;
8954   if (Signed)
8955     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8956   else
8957     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8958 
8959   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8960 
8961   ARMTargetLowering::ArgListTy Args;
8962 
8963   for (auto AI : {1, 0}) {
8964     ArgListEntry Arg;
8965     Arg.Node = Op.getOperand(AI);
8966     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8967     Args.push_back(Arg);
8968   }
8969 
8970   CallLoweringInfo CLI(DAG);
8971   CLI.setDebugLoc(dl)
8972     .setChain(Chain)
8973     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8974                ES, std::move(Args));
8975 
8976   return LowerCallTo(CLI).first;
8977 }
8978 
8979 // This is a code size optimisation: return the original SDIV node to
8980 // DAGCombiner when we don't want to expand SDIV into a sequence of
8981 // instructions, and an empty node otherwise which will cause the
8982 // SDIV to be expanded in DAGCombine.
8983 SDValue
8984 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8985                                  SelectionDAG &DAG,
8986                                  SmallVectorImpl<SDNode *> &Created) const {
8987   // TODO: Support SREM
8988   if (N->getOpcode() != ISD::SDIV)
8989     return SDValue();
8990 
8991   const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8992   const bool MinSize = ST.hasMinSize();
8993   const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8994                                       : ST.hasDivideInARMMode();
8995 
8996   // Don't touch vector types; rewriting this may lead to scalarizing
8997   // the int divs.
8998   if (N->getOperand(0).getValueType().isVector())
8999     return SDValue();
9000 
9001   // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9002   // hwdiv support for this to be really profitable.
9003   if (!(MinSize && HasDivide))
9004     return SDValue();
9005 
9006   // ARM mode is a bit simpler than Thumb: we can handle large power
9007   // of 2 immediates with 1 mov instruction; no further checks required,
9008   // just return the sdiv node.
9009   if (!ST.isThumb())
9010     return SDValue(N, 0);
9011 
9012   // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9013   // and thus lose the code size benefits of a MOVS that requires only 2.
9014   // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9015   // but as it's doing exactly this, it's not worth the trouble to get TTI.
9016   if (Divisor.sgt(128))
9017     return SDValue();
9018 
9019   return SDValue(N, 0);
9020 }
9021 
9022 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9023                                             bool Signed) const {
9024   assert(Op.getValueType() == MVT::i32 &&
9025          "unexpected type for custom lowering DIV");
9026   SDLoc dl(Op);
9027 
9028   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9029                                DAG.getEntryNode(), Op.getOperand(1));
9030 
9031   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9032 }
9033 
9034 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9035   SDLoc DL(N);
9036   SDValue Op = N->getOperand(1);
9037   if (N->getValueType(0) == MVT::i32)
9038     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9039   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9040                            DAG.getConstant(0, DL, MVT::i32));
9041   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9042                            DAG.getConstant(1, DL, MVT::i32));
9043   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9044                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9045 }
9046 
9047 void ARMTargetLowering::ExpandDIV_Windows(
9048     SDValue Op, SelectionDAG &DAG, bool Signed,
9049     SmallVectorImpl<SDValue> &Results) const {
9050   const auto &DL = DAG.getDataLayout();
9051   const auto &TLI = DAG.getTargetLoweringInfo();
9052 
9053   assert(Op.getValueType() == MVT::i64 &&
9054          "unexpected type for custom lowering DIV");
9055   SDLoc dl(Op);
9056 
9057   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9058 
9059   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9060 
9061   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9062   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9063                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
9064   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9065 
9066   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9067 }
9068 
9069 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9070   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9071   EVT MemVT = LD->getMemoryVT();
9072   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9073          "Expected a predicate type!");
9074   assert(MemVT == Op.getValueType());
9075   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9076          "Expected a non-extending load");
9077   assert(LD->isUnindexed() && "Expected a unindexed load");
9078 
9079   // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
9080   // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9081   // need to make sure that 8/4 bits are actually loaded into the correct
9082   // place, which means loading the value and then shuffling the values into
9083   // the bottom bits of the predicate.
9084   // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9085   // for BE).
9086 
9087   SDLoc dl(Op);
9088   SDValue Load = DAG.getExtLoad(
9089       ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9090       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9091       LD->getMemOperand());
9092   SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load);
9093   if (MemVT != MVT::v16i1)
9094     Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9095                        DAG.getConstant(0, dl, MVT::i32));
9096   return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9097 }
9098 
9099 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9100                                   SelectionDAG &DAG) const {
9101   LoadSDNode *LD = cast<LoadSDNode>(N);
9102   EVT MemVT = LD->getMemoryVT();
9103   assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
9104 
9105   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9106       !Subtarget->isThumb1Only() && LD->isVolatile()) {
9107     SDLoc dl(N);
9108     SDValue Result = DAG.getMemIntrinsicNode(
9109         ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
9110         {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
9111     SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9112     SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9113     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
9114     Results.append({Pair, Result.getValue(2)});
9115   }
9116 }
9117 
9118 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
9119   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9120   EVT MemVT = ST->getMemoryVT();
9121   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9122          "Expected a predicate type!");
9123   assert(MemVT == ST->getValue().getValueType());
9124   assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9125   assert(ST->isUnindexed() && "Expected a unindexed store");
9126 
9127   // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
9128   // unset and a scalar store.
9129   SDLoc dl(Op);
9130   SDValue Build = ST->getValue();
9131   if (MemVT != MVT::v16i1) {
9132     SmallVector<SDValue, 16> Ops;
9133     for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++)
9134       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9135                                 DAG.getConstant(I, dl, MVT::i32)));
9136     for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9137       Ops.push_back(DAG.getUNDEF(MVT::i32));
9138     Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9139   }
9140   SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9141   return DAG.getTruncStore(
9142       ST->getChain(), dl, GRP, ST->getBasePtr(),
9143       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9144       ST->getMemOperand());
9145 }
9146 
9147 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG,
9148                           const ARMSubtarget *Subtarget) {
9149   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9150   EVT MemVT = ST->getMemoryVT();
9151   assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
9152 
9153   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9154       !Subtarget->isThumb1Only() && ST->isVolatile()) {
9155     SDNode *N = Op.getNode();
9156     SDLoc dl(N);
9157 
9158     SDValue Lo = DAG.getNode(
9159         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9160         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
9161                               MVT::i32));
9162     SDValue Hi = DAG.getNode(
9163         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9164         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
9165                               MVT::i32));
9166 
9167     return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
9168                                    {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9169                                    MemVT, ST->getMemOperand());
9170   } else if (Subtarget->hasMVEIntegerOps() &&
9171              ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9172                MemVT == MVT::v16i1))) {
9173     return LowerPredicateStore(Op, DAG);
9174   }
9175 
9176   return SDValue();
9177 }
9178 
9179 static bool isZeroVector(SDValue N) {
9180   return (ISD::isBuildVectorAllZeros(N.getNode()) ||
9181           (N->getOpcode() == ARMISD::VMOVIMM &&
9182            isNullConstant(N->getOperand(0))));
9183 }
9184 
9185 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
9186   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
9187   MVT VT = Op.getSimpleValueType();
9188   SDValue Mask = N->getMask();
9189   SDValue PassThru = N->getPassThru();
9190   SDLoc dl(Op);
9191 
9192   if (isZeroVector(PassThru))
9193     return Op;
9194 
9195   // MVE Masked loads use zero as the passthru value. Here we convert undef to
9196   // zero too, and other values are lowered to a select.
9197   SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
9198                                 DAG.getTargetConstant(0, dl, MVT::i32));
9199   SDValue NewLoad = DAG.getMaskedLoad(
9200       VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
9201       N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
9202       N->getExtensionType(), N->isExpandingLoad());
9203   SDValue Combo = NewLoad;
9204   bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9205                              PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9206                             isZeroVector(PassThru->getOperand(0));
9207   if (!PassThru.isUndef() && !PassThruIsCastZero)
9208     Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
9209   return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
9210 }
9211 
9212 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
9213   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
9214     // Acquire/Release load/store is not legal for targets without a dmb or
9215     // equivalent available.
9216     return SDValue();
9217 
9218   // Monotonic load/store is legal for all targets.
9219   return Op;
9220 }
9221 
9222 static void ReplaceREADCYCLECOUNTER(SDNode *N,
9223                                     SmallVectorImpl<SDValue> &Results,
9224                                     SelectionDAG &DAG,
9225                                     const ARMSubtarget *Subtarget) {
9226   SDLoc DL(N);
9227   // Under Power Management extensions, the cycle-count is:
9228   //    mrc p15, #0, <Rt>, c9, c13, #0
9229   SDValue Ops[] = { N->getOperand(0), // Chain
9230                     DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
9231                     DAG.getTargetConstant(15, DL, MVT::i32),
9232                     DAG.getTargetConstant(0, DL, MVT::i32),
9233                     DAG.getTargetConstant(9, DL, MVT::i32),
9234                     DAG.getTargetConstant(13, DL, MVT::i32),
9235                     DAG.getTargetConstant(0, DL, MVT::i32)
9236   };
9237 
9238   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
9239                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
9240   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
9241                                 DAG.getConstant(0, DL, MVT::i32)));
9242   Results.push_back(Cycles32.getValue(1));
9243 }
9244 
9245 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
9246   SDLoc dl(V.getNode());
9247   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
9248   SDValue VHi = DAG.getAnyExtOrTrunc(
9249       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
9250       dl, MVT::i32);
9251   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9252   if (isBigEndian)
9253     std::swap (VLo, VHi);
9254   SDValue RegClass =
9255       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
9256   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
9257   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
9258   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
9259   return SDValue(
9260       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
9261 }
9262 
9263 static void ReplaceCMP_SWAP_64Results(SDNode *N,
9264                                        SmallVectorImpl<SDValue> & Results,
9265                                        SelectionDAG &DAG) {
9266   assert(N->getValueType(0) == MVT::i64 &&
9267          "AtomicCmpSwap on types less than 64 should be legal");
9268   SDValue Ops[] = {N->getOperand(1),
9269                    createGPRPairNode(DAG, N->getOperand(2)),
9270                    createGPRPairNode(DAG, N->getOperand(3)),
9271                    N->getOperand(0)};
9272   SDNode *CmpSwap = DAG.getMachineNode(
9273       ARM::CMP_SWAP_64, SDLoc(N),
9274       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
9275 
9276   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
9277   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
9278 
9279   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9280 
9281   SDValue Lo =
9282       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
9283                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9284   SDValue Hi =
9285       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
9286                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9287   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
9288   Results.push_back(SDValue(CmpSwap, 2));
9289 }
9290 
9291 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
9292   SDLoc dl(Op);
9293   EVT VT = Op.getValueType();
9294   SDValue Chain = Op.getOperand(0);
9295   SDValue LHS = Op.getOperand(1);
9296   SDValue RHS = Op.getOperand(2);
9297   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
9298   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
9299 
9300   // If we don't have instructions of this float type then soften to a libcall
9301   // and use SETCC instead.
9302   if (isUnsupportedFloatingType(LHS.getValueType())) {
9303     DAG.getTargetLoweringInfo().softenSetCCOperands(
9304       DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling);
9305     if (!RHS.getNode()) {
9306       RHS = DAG.getConstant(0, dl, LHS.getValueType());
9307       CC = ISD::SETNE;
9308     }
9309     SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
9310                                  DAG.getCondCode(CC));
9311     return DAG.getMergeValues({Result, Chain}, dl);
9312   }
9313 
9314   ARMCC::CondCodes CondCode, CondCode2;
9315   FPCCToARMCC(CC, CondCode, CondCode2);
9316 
9317   // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit
9318   // in CMPFP and CMPFPE, but instead it should be made explicit by these
9319   // instructions using a chain instead of glue. This would also fix the problem
9320   // here (and also in LowerSELECT_CC) where we generate two comparisons when
9321   // CondCode2 != AL.
9322   SDValue True = DAG.getConstant(1, dl, VT);
9323   SDValue False =  DAG.getConstant(0, dl, VT);
9324   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
9325   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
9326   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9327   SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG);
9328   if (CondCode2 != ARMCC::AL) {
9329     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
9330     Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9331     Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG);
9332   }
9333   return DAG.getMergeValues({Result, Chain}, dl);
9334 }
9335 
9336 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9337   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
9338   switch (Op.getOpcode()) {
9339   default: llvm_unreachable("Don't know how to custom lower this!");
9340   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
9341   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9342   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
9343   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9344   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9345   case ISD::SELECT:        return LowerSELECT(Op, DAG);
9346   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
9347   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
9348   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
9349   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
9350   case ISD::VASTART:       return LowerVASTART(Op, DAG);
9351   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
9352   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
9353   case ISD::SINT_TO_FP:
9354   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
9355   case ISD::STRICT_FP_TO_SINT:
9356   case ISD::STRICT_FP_TO_UINT:
9357   case ISD::FP_TO_SINT:
9358   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
9359   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
9360   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
9361   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
9362   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
9363   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
9364   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
9365   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
9366   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
9367                                                                Subtarget);
9368   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
9369   case ISD::SHL:
9370   case ISD::SRL:
9371   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
9372   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
9373   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
9374   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
9375   case ISD::SRL_PARTS:
9376   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
9377   case ISD::CTTZ:
9378   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
9379   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
9380   case ISD::SETCC:         return LowerVSETCC(Op, DAG, Subtarget);
9381   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
9382   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
9383   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
9384   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
9385   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
9386   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9387   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
9388   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
9389   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
9390   case ISD::MUL:           return LowerMUL(Op, DAG);
9391   case ISD::SDIV:
9392     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9393       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
9394     return LowerSDIV(Op, DAG, Subtarget);
9395   case ISD::UDIV:
9396     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9397       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
9398     return LowerUDIV(Op, DAG, Subtarget);
9399   case ISD::ADDCARRY:
9400   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
9401   case ISD::SADDO:
9402   case ISD::SSUBO:
9403     return LowerSignedALUO(Op, DAG);
9404   case ISD::UADDO:
9405   case ISD::USUBO:
9406     return LowerUnsignedALUO(Op, DAG);
9407   case ISD::SADDSAT:
9408   case ISD::SSUBSAT:
9409     return LowerSADDSUBSAT(Op, DAG, Subtarget);
9410   case ISD::LOAD:
9411     return LowerPredicateLoad(Op, DAG);
9412   case ISD::STORE:
9413     return LowerSTORE(Op, DAG, Subtarget);
9414   case ISD::MLOAD:
9415     return LowerMLOAD(Op, DAG);
9416   case ISD::ATOMIC_LOAD:
9417   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
9418   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
9419   case ISD::SDIVREM:
9420   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
9421   case ISD::DYNAMIC_STACKALLOC:
9422     if (Subtarget->isTargetWindows())
9423       return LowerDYNAMIC_STACKALLOC(Op, DAG);
9424     llvm_unreachable("Don't know how to custom lower this!");
9425   case ISD::STRICT_FP_ROUND:
9426   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
9427   case ISD::STRICT_FP_EXTEND:
9428   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9429   case ISD::STRICT_FSETCC:
9430   case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
9431   case ARMISD::WIN__DBZCHK: return SDValue();
9432   }
9433 }
9434 
9435 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9436                                  SelectionDAG &DAG) {
9437   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9438   unsigned Opc = 0;
9439   if (IntNo == Intrinsic::arm_smlald)
9440     Opc = ARMISD::SMLALD;
9441   else if (IntNo == Intrinsic::arm_smlaldx)
9442     Opc = ARMISD::SMLALDX;
9443   else if (IntNo == Intrinsic::arm_smlsld)
9444     Opc = ARMISD::SMLSLD;
9445   else if (IntNo == Intrinsic::arm_smlsldx)
9446     Opc = ARMISD::SMLSLDX;
9447   else
9448     return;
9449 
9450   SDLoc dl(N);
9451   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9452                            N->getOperand(3),
9453                            DAG.getConstant(0, dl, MVT::i32));
9454   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9455                            N->getOperand(3),
9456                            DAG.getConstant(1, dl, MVT::i32));
9457 
9458   SDValue LongMul = DAG.getNode(Opc, dl,
9459                                 DAG.getVTList(MVT::i32, MVT::i32),
9460                                 N->getOperand(1), N->getOperand(2),
9461                                 Lo, Hi);
9462   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
9463                                 LongMul.getValue(0), LongMul.getValue(1)));
9464 }
9465 
9466 /// ReplaceNodeResults - Replace the results of node with an illegal result
9467 /// type with new values built out of custom code.
9468 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9469                                            SmallVectorImpl<SDValue> &Results,
9470                                            SelectionDAG &DAG) const {
9471   SDValue Res;
9472   switch (N->getOpcode()) {
9473   default:
9474     llvm_unreachable("Don't know how to custom expand this!");
9475   case ISD::READ_REGISTER:
9476     ExpandREAD_REGISTER(N, Results, DAG);
9477     break;
9478   case ISD::BITCAST:
9479     Res = ExpandBITCAST(N, DAG, Subtarget);
9480     break;
9481   case ISD::SRL:
9482   case ISD::SRA:
9483   case ISD::SHL:
9484     Res = Expand64BitShift(N, DAG, Subtarget);
9485     break;
9486   case ISD::SREM:
9487   case ISD::UREM:
9488     Res = LowerREM(N, DAG);
9489     break;
9490   case ISD::SDIVREM:
9491   case ISD::UDIVREM:
9492     Res = LowerDivRem(SDValue(N, 0), DAG);
9493     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9494     Results.push_back(Res.getValue(0));
9495     Results.push_back(Res.getValue(1));
9496     return;
9497   case ISD::SADDSAT:
9498   case ISD::SSUBSAT:
9499     Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
9500     break;
9501   case ISD::READCYCLECOUNTER:
9502     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9503     return;
9504   case ISD::UDIV:
9505   case ISD::SDIV:
9506     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9507     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9508                              Results);
9509   case ISD::ATOMIC_CMP_SWAP:
9510     ReplaceCMP_SWAP_64Results(N, Results, DAG);
9511     return;
9512   case ISD::INTRINSIC_WO_CHAIN:
9513     return ReplaceLongIntrinsic(N, Results, DAG);
9514   case ISD::ABS:
9515      lowerABS(N, Results, DAG);
9516      return ;
9517   case ISD::LOAD:
9518     LowerLOAD(N, Results, DAG);
9519     break;
9520   }
9521   if (Res.getNode())
9522     Results.push_back(Res);
9523 }
9524 
9525 //===----------------------------------------------------------------------===//
9526 //                           ARM Scheduler Hooks
9527 //===----------------------------------------------------------------------===//
9528 
9529 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9530 /// registers the function context.
9531 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9532                                                MachineBasicBlock *MBB,
9533                                                MachineBasicBlock *DispatchBB,
9534                                                int FI) const {
9535   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9536          "ROPI/RWPI not currently supported with SjLj");
9537   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9538   DebugLoc dl = MI.getDebugLoc();
9539   MachineFunction *MF = MBB->getParent();
9540   MachineRegisterInfo *MRI = &MF->getRegInfo();
9541   MachineConstantPool *MCP = MF->getConstantPool();
9542   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9543   const Function &F = MF->getFunction();
9544 
9545   bool isThumb = Subtarget->isThumb();
9546   bool isThumb2 = Subtarget->isThumb2();
9547 
9548   unsigned PCLabelId = AFI->createPICLabelUId();
9549   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9550   ARMConstantPoolValue *CPV =
9551     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9552   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
9553 
9554   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9555                                            : &ARM::GPRRegClass;
9556 
9557   // Grab constant pool and fixed stack memory operands.
9558   MachineMemOperand *CPMMO =
9559       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9560                                MachineMemOperand::MOLoad, 4, Align(4));
9561 
9562   MachineMemOperand *FIMMOSt =
9563       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9564                                MachineMemOperand::MOStore, 4, Align(4));
9565 
9566   // Load the address of the dispatch MBB into the jump buffer.
9567   if (isThumb2) {
9568     // Incoming value: jbuf
9569     //   ldr.n  r5, LCPI1_1
9570     //   orr    r5, r5, #1
9571     //   add    r5, pc
9572     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
9573     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9574     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9575         .addConstantPoolIndex(CPI)
9576         .addMemOperand(CPMMO)
9577         .add(predOps(ARMCC::AL));
9578     // Set the low bit because of thumb mode.
9579     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9580     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9581         .addReg(NewVReg1, RegState::Kill)
9582         .addImm(0x01)
9583         .add(predOps(ARMCC::AL))
9584         .add(condCodeOp());
9585     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9586     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9587       .addReg(NewVReg2, RegState::Kill)
9588       .addImm(PCLabelId);
9589     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9590         .addReg(NewVReg3, RegState::Kill)
9591         .addFrameIndex(FI)
9592         .addImm(36) // &jbuf[1] :: pc
9593         .addMemOperand(FIMMOSt)
9594         .add(predOps(ARMCC::AL));
9595   } else if (isThumb) {
9596     // Incoming value: jbuf
9597     //   ldr.n  r1, LCPI1_4
9598     //   add    r1, pc
9599     //   mov    r2, #1
9600     //   orrs   r1, r2
9601     //   add    r2, $jbuf, #+4 ; &jbuf[1]
9602     //   str    r1, [r2]
9603     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9604     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9605         .addConstantPoolIndex(CPI)
9606         .addMemOperand(CPMMO)
9607         .add(predOps(ARMCC::AL));
9608     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9609     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9610       .addReg(NewVReg1, RegState::Kill)
9611       .addImm(PCLabelId);
9612     // Set the low bit because of thumb mode.
9613     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9614     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9615         .addReg(ARM::CPSR, RegState::Define)
9616         .addImm(1)
9617         .add(predOps(ARMCC::AL));
9618     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9619     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9620         .addReg(ARM::CPSR, RegState::Define)
9621         .addReg(NewVReg2, RegState::Kill)
9622         .addReg(NewVReg3, RegState::Kill)
9623         .add(predOps(ARMCC::AL));
9624     Register NewVReg5 = MRI->createVirtualRegister(TRC);
9625     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9626             .addFrameIndex(FI)
9627             .addImm(36); // &jbuf[1] :: pc
9628     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9629         .addReg(NewVReg4, RegState::Kill)
9630         .addReg(NewVReg5, RegState::Kill)
9631         .addImm(0)
9632         .addMemOperand(FIMMOSt)
9633         .add(predOps(ARMCC::AL));
9634   } else {
9635     // Incoming value: jbuf
9636     //   ldr  r1, LCPI1_1
9637     //   add  r1, pc, r1
9638     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
9639     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9640     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9641         .addConstantPoolIndex(CPI)
9642         .addImm(0)
9643         .addMemOperand(CPMMO)
9644         .add(predOps(ARMCC::AL));
9645     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9646     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9647         .addReg(NewVReg1, RegState::Kill)
9648         .addImm(PCLabelId)
9649         .add(predOps(ARMCC::AL));
9650     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9651         .addReg(NewVReg2, RegState::Kill)
9652         .addFrameIndex(FI)
9653         .addImm(36) // &jbuf[1] :: pc
9654         .addMemOperand(FIMMOSt)
9655         .add(predOps(ARMCC::AL));
9656   }
9657 }
9658 
9659 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9660                                               MachineBasicBlock *MBB) const {
9661   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9662   DebugLoc dl = MI.getDebugLoc();
9663   MachineFunction *MF = MBB->getParent();
9664   MachineRegisterInfo *MRI = &MF->getRegInfo();
9665   MachineFrameInfo &MFI = MF->getFrameInfo();
9666   int FI = MFI.getFunctionContextIndex();
9667 
9668   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9669                                                         : &ARM::GPRnopcRegClass;
9670 
9671   // Get a mapping of the call site numbers to all of the landing pads they're
9672   // associated with.
9673   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9674   unsigned MaxCSNum = 0;
9675   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9676        ++BB) {
9677     if (!BB->isEHPad()) continue;
9678 
9679     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9680     // pad.
9681     for (MachineBasicBlock::iterator
9682            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9683       if (!II->isEHLabel()) continue;
9684 
9685       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9686       if (!MF->hasCallSiteLandingPad(Sym)) continue;
9687 
9688       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9689       for (SmallVectorImpl<unsigned>::iterator
9690              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9691            CSI != CSE; ++CSI) {
9692         CallSiteNumToLPad[*CSI].push_back(&*BB);
9693         MaxCSNum = std::max(MaxCSNum, *CSI);
9694       }
9695       break;
9696     }
9697   }
9698 
9699   // Get an ordered list of the machine basic blocks for the jump table.
9700   std::vector<MachineBasicBlock*> LPadList;
9701   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9702   LPadList.reserve(CallSiteNumToLPad.size());
9703   for (unsigned I = 1; I <= MaxCSNum; ++I) {
9704     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9705     for (SmallVectorImpl<MachineBasicBlock*>::iterator
9706            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9707       LPadList.push_back(*II);
9708       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9709     }
9710   }
9711 
9712   assert(!LPadList.empty() &&
9713          "No landing pad destinations for the dispatch jump table!");
9714 
9715   // Create the jump table and associated information.
9716   MachineJumpTableInfo *JTI =
9717     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9718   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9719 
9720   // Create the MBBs for the dispatch code.
9721 
9722   // Shove the dispatch's address into the return slot in the function context.
9723   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9724   DispatchBB->setIsEHPad();
9725 
9726   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9727   unsigned trap_opcode;
9728   if (Subtarget->isThumb())
9729     trap_opcode = ARM::tTRAP;
9730   else
9731     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9732 
9733   BuildMI(TrapBB, dl, TII->get(trap_opcode));
9734   DispatchBB->addSuccessor(TrapBB);
9735 
9736   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9737   DispatchBB->addSuccessor(DispContBB);
9738 
9739   // Insert and MBBs.
9740   MF->insert(MF->end(), DispatchBB);
9741   MF->insert(MF->end(), DispContBB);
9742   MF->insert(MF->end(), TrapBB);
9743 
9744   // Insert code into the entry block that creates and registers the function
9745   // context.
9746   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9747 
9748   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9749       MachinePointerInfo::getFixedStack(*MF, FI),
9750       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4));
9751 
9752   MachineInstrBuilder MIB;
9753   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9754 
9755   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9756   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9757 
9758   // Add a register mask with no preserved registers.  This results in all
9759   // registers being marked as clobbered. This can't work if the dispatch block
9760   // is in a Thumb1 function and is linked with ARM code which uses the FP
9761   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9762   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9763 
9764   bool IsPositionIndependent = isPositionIndependent();
9765   unsigned NumLPads = LPadList.size();
9766   if (Subtarget->isThumb2()) {
9767     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9768     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9769         .addFrameIndex(FI)
9770         .addImm(4)
9771         .addMemOperand(FIMMOLd)
9772         .add(predOps(ARMCC::AL));
9773 
9774     if (NumLPads < 256) {
9775       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9776           .addReg(NewVReg1)
9777           .addImm(LPadList.size())
9778           .add(predOps(ARMCC::AL));
9779     } else {
9780       Register VReg1 = MRI->createVirtualRegister(TRC);
9781       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9782           .addImm(NumLPads & 0xFFFF)
9783           .add(predOps(ARMCC::AL));
9784 
9785       unsigned VReg2 = VReg1;
9786       if ((NumLPads & 0xFFFF0000) != 0) {
9787         VReg2 = MRI->createVirtualRegister(TRC);
9788         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9789             .addReg(VReg1)
9790             .addImm(NumLPads >> 16)
9791             .add(predOps(ARMCC::AL));
9792       }
9793 
9794       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9795           .addReg(NewVReg1)
9796           .addReg(VReg2)
9797           .add(predOps(ARMCC::AL));
9798     }
9799 
9800     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9801       .addMBB(TrapBB)
9802       .addImm(ARMCC::HI)
9803       .addReg(ARM::CPSR);
9804 
9805     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9806     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9807         .addJumpTableIndex(MJTI)
9808         .add(predOps(ARMCC::AL));
9809 
9810     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9811     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9812         .addReg(NewVReg3, RegState::Kill)
9813         .addReg(NewVReg1)
9814         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9815         .add(predOps(ARMCC::AL))
9816         .add(condCodeOp());
9817 
9818     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9819       .addReg(NewVReg4, RegState::Kill)
9820       .addReg(NewVReg1)
9821       .addJumpTableIndex(MJTI);
9822   } else if (Subtarget->isThumb()) {
9823     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9824     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9825         .addFrameIndex(FI)
9826         .addImm(1)
9827         .addMemOperand(FIMMOLd)
9828         .add(predOps(ARMCC::AL));
9829 
9830     if (NumLPads < 256) {
9831       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9832           .addReg(NewVReg1)
9833           .addImm(NumLPads)
9834           .add(predOps(ARMCC::AL));
9835     } else {
9836       MachineConstantPool *ConstantPool = MF->getConstantPool();
9837       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9838       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9839 
9840       // MachineConstantPool wants an explicit alignment.
9841       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9842       if (Align == 0)
9843         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9844       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9845 
9846       Register VReg1 = MRI->createVirtualRegister(TRC);
9847       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9848           .addReg(VReg1, RegState::Define)
9849           .addConstantPoolIndex(Idx)
9850           .add(predOps(ARMCC::AL));
9851       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9852           .addReg(NewVReg1)
9853           .addReg(VReg1)
9854           .add(predOps(ARMCC::AL));
9855     }
9856 
9857     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9858       .addMBB(TrapBB)
9859       .addImm(ARMCC::HI)
9860       .addReg(ARM::CPSR);
9861 
9862     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9863     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9864         .addReg(ARM::CPSR, RegState::Define)
9865         .addReg(NewVReg1)
9866         .addImm(2)
9867         .add(predOps(ARMCC::AL));
9868 
9869     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9870     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9871         .addJumpTableIndex(MJTI)
9872         .add(predOps(ARMCC::AL));
9873 
9874     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9875     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9876         .addReg(ARM::CPSR, RegState::Define)
9877         .addReg(NewVReg2, RegState::Kill)
9878         .addReg(NewVReg3)
9879         .add(predOps(ARMCC::AL));
9880 
9881     MachineMemOperand *JTMMOLd =
9882         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
9883                                  MachineMemOperand::MOLoad, 4, Align(4));
9884 
9885     Register NewVReg5 = MRI->createVirtualRegister(TRC);
9886     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9887         .addReg(NewVReg4, RegState::Kill)
9888         .addImm(0)
9889         .addMemOperand(JTMMOLd)
9890         .add(predOps(ARMCC::AL));
9891 
9892     unsigned NewVReg6 = NewVReg5;
9893     if (IsPositionIndependent) {
9894       NewVReg6 = MRI->createVirtualRegister(TRC);
9895       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9896           .addReg(ARM::CPSR, RegState::Define)
9897           .addReg(NewVReg5, RegState::Kill)
9898           .addReg(NewVReg3)
9899           .add(predOps(ARMCC::AL));
9900     }
9901 
9902     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9903       .addReg(NewVReg6, RegState::Kill)
9904       .addJumpTableIndex(MJTI);
9905   } else {
9906     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9907     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9908         .addFrameIndex(FI)
9909         .addImm(4)
9910         .addMemOperand(FIMMOLd)
9911         .add(predOps(ARMCC::AL));
9912 
9913     if (NumLPads < 256) {
9914       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9915           .addReg(NewVReg1)
9916           .addImm(NumLPads)
9917           .add(predOps(ARMCC::AL));
9918     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9919       Register VReg1 = MRI->createVirtualRegister(TRC);
9920       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9921           .addImm(NumLPads & 0xFFFF)
9922           .add(predOps(ARMCC::AL));
9923 
9924       unsigned VReg2 = VReg1;
9925       if ((NumLPads & 0xFFFF0000) != 0) {
9926         VReg2 = MRI->createVirtualRegister(TRC);
9927         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9928             .addReg(VReg1)
9929             .addImm(NumLPads >> 16)
9930             .add(predOps(ARMCC::AL));
9931       }
9932 
9933       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9934           .addReg(NewVReg1)
9935           .addReg(VReg2)
9936           .add(predOps(ARMCC::AL));
9937     } else {
9938       MachineConstantPool *ConstantPool = MF->getConstantPool();
9939       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9940       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9941 
9942       // MachineConstantPool wants an explicit alignment.
9943       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9944       if (Align == 0)
9945         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9946       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9947 
9948       Register VReg1 = MRI->createVirtualRegister(TRC);
9949       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9950           .addReg(VReg1, RegState::Define)
9951           .addConstantPoolIndex(Idx)
9952           .addImm(0)
9953           .add(predOps(ARMCC::AL));
9954       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9955           .addReg(NewVReg1)
9956           .addReg(VReg1, RegState::Kill)
9957           .add(predOps(ARMCC::AL));
9958     }
9959 
9960     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9961       .addMBB(TrapBB)
9962       .addImm(ARMCC::HI)
9963       .addReg(ARM::CPSR);
9964 
9965     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9966     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9967         .addReg(NewVReg1)
9968         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9969         .add(predOps(ARMCC::AL))
9970         .add(condCodeOp());
9971     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9972     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9973         .addJumpTableIndex(MJTI)
9974         .add(predOps(ARMCC::AL));
9975 
9976     MachineMemOperand *JTMMOLd =
9977         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
9978                                  MachineMemOperand::MOLoad, 4, Align(4));
9979     Register NewVReg5 = MRI->createVirtualRegister(TRC);
9980     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9981         .addReg(NewVReg3, RegState::Kill)
9982         .addReg(NewVReg4)
9983         .addImm(0)
9984         .addMemOperand(JTMMOLd)
9985         .add(predOps(ARMCC::AL));
9986 
9987     if (IsPositionIndependent) {
9988       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9989         .addReg(NewVReg5, RegState::Kill)
9990         .addReg(NewVReg4)
9991         .addJumpTableIndex(MJTI);
9992     } else {
9993       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
9994         .addReg(NewVReg5, RegState::Kill)
9995         .addJumpTableIndex(MJTI);
9996     }
9997   }
9998 
9999   // Add the jump table entries as successors to the MBB.
10000   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
10001   for (std::vector<MachineBasicBlock*>::iterator
10002          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
10003     MachineBasicBlock *CurMBB = *I;
10004     if (SeenMBBs.insert(CurMBB).second)
10005       DispContBB->addSuccessor(CurMBB);
10006   }
10007 
10008   // N.B. the order the invoke BBs are processed in doesn't matter here.
10009   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
10010   SmallVector<MachineBasicBlock*, 64> MBBLPads;
10011   for (MachineBasicBlock *BB : InvokeBBs) {
10012 
10013     // Remove the landing pad successor from the invoke block and replace it
10014     // with the new dispatch block.
10015     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
10016                                                   BB->succ_end());
10017     while (!Successors.empty()) {
10018       MachineBasicBlock *SMBB = Successors.pop_back_val();
10019       if (SMBB->isEHPad()) {
10020         BB->removeSuccessor(SMBB);
10021         MBBLPads.push_back(SMBB);
10022       }
10023     }
10024 
10025     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
10026     BB->normalizeSuccProbs();
10027 
10028     // Find the invoke call and mark all of the callee-saved registers as
10029     // 'implicit defined' so that they're spilled. This prevents code from
10030     // moving instructions to before the EH block, where they will never be
10031     // executed.
10032     for (MachineBasicBlock::reverse_iterator
10033            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
10034       if (!II->isCall()) continue;
10035 
10036       DenseMap<unsigned, bool> DefRegs;
10037       for (MachineInstr::mop_iterator
10038              OI = II->operands_begin(), OE = II->operands_end();
10039            OI != OE; ++OI) {
10040         if (!OI->isReg()) continue;
10041         DefRegs[OI->getReg()] = true;
10042       }
10043 
10044       MachineInstrBuilder MIB(*MF, &*II);
10045 
10046       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
10047         unsigned Reg = SavedRegs[i];
10048         if (Subtarget->isThumb2() &&
10049             !ARM::tGPRRegClass.contains(Reg) &&
10050             !ARM::hGPRRegClass.contains(Reg))
10051           continue;
10052         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
10053           continue;
10054         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
10055           continue;
10056         if (!DefRegs[Reg])
10057           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
10058       }
10059 
10060       break;
10061     }
10062   }
10063 
10064   // Mark all former landing pads as non-landing pads. The dispatch is the only
10065   // landing pad now.
10066   for (SmallVectorImpl<MachineBasicBlock*>::iterator
10067          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
10068     (*I)->setIsEHPad(false);
10069 
10070   // The instruction is gone now.
10071   MI.eraseFromParent();
10072 }
10073 
10074 static
10075 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
10076   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
10077        E = MBB->succ_end(); I != E; ++I)
10078     if (*I != Succ)
10079       return *I;
10080   llvm_unreachable("Expecting a BB with two successors!");
10081 }
10082 
10083 /// Return the load opcode for a given load size. If load size >= 8,
10084 /// neon opcode will be returned.
10085 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
10086   if (LdSize >= 8)
10087     return LdSize == 16 ? ARM::VLD1q32wb_fixed
10088                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
10089   if (IsThumb1)
10090     return LdSize == 4 ? ARM::tLDRi
10091                        : LdSize == 2 ? ARM::tLDRHi
10092                                      : LdSize == 1 ? ARM::tLDRBi : 0;
10093   if (IsThumb2)
10094     return LdSize == 4 ? ARM::t2LDR_POST
10095                        : LdSize == 2 ? ARM::t2LDRH_POST
10096                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
10097   return LdSize == 4 ? ARM::LDR_POST_IMM
10098                      : LdSize == 2 ? ARM::LDRH_POST
10099                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
10100 }
10101 
10102 /// Return the store opcode for a given store size. If store size >= 8,
10103 /// neon opcode will be returned.
10104 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
10105   if (StSize >= 8)
10106     return StSize == 16 ? ARM::VST1q32wb_fixed
10107                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
10108   if (IsThumb1)
10109     return StSize == 4 ? ARM::tSTRi
10110                        : StSize == 2 ? ARM::tSTRHi
10111                                      : StSize == 1 ? ARM::tSTRBi : 0;
10112   if (IsThumb2)
10113     return StSize == 4 ? ARM::t2STR_POST
10114                        : StSize == 2 ? ARM::t2STRH_POST
10115                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
10116   return StSize == 4 ? ARM::STR_POST_IMM
10117                      : StSize == 2 ? ARM::STRH_POST
10118                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
10119 }
10120 
10121 /// Emit a post-increment load operation with given size. The instructions
10122 /// will be added to BB at Pos.
10123 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10124                        const TargetInstrInfo *TII, const DebugLoc &dl,
10125                        unsigned LdSize, unsigned Data, unsigned AddrIn,
10126                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10127   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
10128   assert(LdOpc != 0 && "Should have a load opcode");
10129   if (LdSize >= 8) {
10130     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10131         .addReg(AddrOut, RegState::Define)
10132         .addReg(AddrIn)
10133         .addImm(0)
10134         .add(predOps(ARMCC::AL));
10135   } else if (IsThumb1) {
10136     // load + update AddrIn
10137     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10138         .addReg(AddrIn)
10139         .addImm(0)
10140         .add(predOps(ARMCC::AL));
10141     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10142         .add(t1CondCodeOp())
10143         .addReg(AddrIn)
10144         .addImm(LdSize)
10145         .add(predOps(ARMCC::AL));
10146   } else if (IsThumb2) {
10147     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10148         .addReg(AddrOut, RegState::Define)
10149         .addReg(AddrIn)
10150         .addImm(LdSize)
10151         .add(predOps(ARMCC::AL));
10152   } else { // arm
10153     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10154         .addReg(AddrOut, RegState::Define)
10155         .addReg(AddrIn)
10156         .addReg(0)
10157         .addImm(LdSize)
10158         .add(predOps(ARMCC::AL));
10159   }
10160 }
10161 
10162 /// Emit a post-increment store operation with given size. The instructions
10163 /// will be added to BB at Pos.
10164 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10165                        const TargetInstrInfo *TII, const DebugLoc &dl,
10166                        unsigned StSize, unsigned Data, unsigned AddrIn,
10167                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10168   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
10169   assert(StOpc != 0 && "Should have a store opcode");
10170   if (StSize >= 8) {
10171     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10172         .addReg(AddrIn)
10173         .addImm(0)
10174         .addReg(Data)
10175         .add(predOps(ARMCC::AL));
10176   } else if (IsThumb1) {
10177     // store + update AddrIn
10178     BuildMI(*BB, Pos, dl, TII->get(StOpc))
10179         .addReg(Data)
10180         .addReg(AddrIn)
10181         .addImm(0)
10182         .add(predOps(ARMCC::AL));
10183     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10184         .add(t1CondCodeOp())
10185         .addReg(AddrIn)
10186         .addImm(StSize)
10187         .add(predOps(ARMCC::AL));
10188   } else if (IsThumb2) {
10189     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10190         .addReg(Data)
10191         .addReg(AddrIn)
10192         .addImm(StSize)
10193         .add(predOps(ARMCC::AL));
10194   } else { // arm
10195     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10196         .addReg(Data)
10197         .addReg(AddrIn)
10198         .addReg(0)
10199         .addImm(StSize)
10200         .add(predOps(ARMCC::AL));
10201   }
10202 }
10203 
10204 MachineBasicBlock *
10205 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
10206                                    MachineBasicBlock *BB) const {
10207   // This pseudo instruction has 3 operands: dst, src, size
10208   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
10209   // Otherwise, we will generate unrolled scalar copies.
10210   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10211   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10212   MachineFunction::iterator It = ++BB->getIterator();
10213 
10214   Register dest = MI.getOperand(0).getReg();
10215   Register src = MI.getOperand(1).getReg();
10216   unsigned SizeVal = MI.getOperand(2).getImm();
10217   unsigned Alignment = MI.getOperand(3).getImm();
10218   DebugLoc dl = MI.getDebugLoc();
10219 
10220   MachineFunction *MF = BB->getParent();
10221   MachineRegisterInfo &MRI = MF->getRegInfo();
10222   unsigned UnitSize = 0;
10223   const TargetRegisterClass *TRC = nullptr;
10224   const TargetRegisterClass *VecTRC = nullptr;
10225 
10226   bool IsThumb1 = Subtarget->isThumb1Only();
10227   bool IsThumb2 = Subtarget->isThumb2();
10228   bool IsThumb = Subtarget->isThumb();
10229 
10230   if (Alignment & 1) {
10231     UnitSize = 1;
10232   } else if (Alignment & 2) {
10233     UnitSize = 2;
10234   } else {
10235     // Check whether we can use NEON instructions.
10236     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
10237         Subtarget->hasNEON()) {
10238       if ((Alignment % 16 == 0) && SizeVal >= 16)
10239         UnitSize = 16;
10240       else if ((Alignment % 8 == 0) && SizeVal >= 8)
10241         UnitSize = 8;
10242     }
10243     // Can't use NEON instructions.
10244     if (UnitSize == 0)
10245       UnitSize = 4;
10246   }
10247 
10248   // Select the correct opcode and register class for unit size load/store
10249   bool IsNeon = UnitSize >= 8;
10250   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
10251   if (IsNeon)
10252     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
10253                             : UnitSize == 8 ? &ARM::DPRRegClass
10254                                             : nullptr;
10255 
10256   unsigned BytesLeft = SizeVal % UnitSize;
10257   unsigned LoopSize = SizeVal - BytesLeft;
10258 
10259   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
10260     // Use LDR and STR to copy.
10261     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
10262     // [destOut] = STR_POST(scratch, destIn, UnitSize)
10263     unsigned srcIn = src;
10264     unsigned destIn = dest;
10265     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
10266       Register srcOut = MRI.createVirtualRegister(TRC);
10267       Register destOut = MRI.createVirtualRegister(TRC);
10268       Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10269       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
10270                  IsThumb1, IsThumb2);
10271       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
10272                  IsThumb1, IsThumb2);
10273       srcIn = srcOut;
10274       destIn = destOut;
10275     }
10276 
10277     // Handle the leftover bytes with LDRB and STRB.
10278     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
10279     // [destOut] = STRB_POST(scratch, destIn, 1)
10280     for (unsigned i = 0; i < BytesLeft; i++) {
10281       Register srcOut = MRI.createVirtualRegister(TRC);
10282       Register destOut = MRI.createVirtualRegister(TRC);
10283       Register scratch = MRI.createVirtualRegister(TRC);
10284       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
10285                  IsThumb1, IsThumb2);
10286       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
10287                  IsThumb1, IsThumb2);
10288       srcIn = srcOut;
10289       destIn = destOut;
10290     }
10291     MI.eraseFromParent(); // The instruction is gone now.
10292     return BB;
10293   }
10294 
10295   // Expand the pseudo op to a loop.
10296   // thisMBB:
10297   //   ...
10298   //   movw varEnd, # --> with thumb2
10299   //   movt varEnd, #
10300   //   ldrcp varEnd, idx --> without thumb2
10301   //   fallthrough --> loopMBB
10302   // loopMBB:
10303   //   PHI varPhi, varEnd, varLoop
10304   //   PHI srcPhi, src, srcLoop
10305   //   PHI destPhi, dst, destLoop
10306   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10307   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
10308   //   subs varLoop, varPhi, #UnitSize
10309   //   bne loopMBB
10310   //   fallthrough --> exitMBB
10311   // exitMBB:
10312   //   epilogue to handle left-over bytes
10313   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10314   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10315   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10316   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10317   MF->insert(It, loopMBB);
10318   MF->insert(It, exitMBB);
10319 
10320   // Transfer the remainder of BB and its successor edges to exitMBB.
10321   exitMBB->splice(exitMBB->begin(), BB,
10322                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10323   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10324 
10325   // Load an immediate to varEnd.
10326   Register varEnd = MRI.createVirtualRegister(TRC);
10327   if (Subtarget->useMovt()) {
10328     unsigned Vtmp = varEnd;
10329     if ((LoopSize & 0xFFFF0000) != 0)
10330       Vtmp = MRI.createVirtualRegister(TRC);
10331     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
10332         .addImm(LoopSize & 0xFFFF)
10333         .add(predOps(ARMCC::AL));
10334 
10335     if ((LoopSize & 0xFFFF0000) != 0)
10336       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
10337           .addReg(Vtmp)
10338           .addImm(LoopSize >> 16)
10339           .add(predOps(ARMCC::AL));
10340   } else {
10341     MachineConstantPool *ConstantPool = MF->getConstantPool();
10342     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10343     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
10344 
10345     // MachineConstantPool wants an explicit alignment.
10346     Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10347     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment.value());
10348     MachineMemOperand *CPMMO =
10349         MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10350                                  MachineMemOperand::MOLoad, 4, Align(4));
10351 
10352     if (IsThumb)
10353       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
10354           .addReg(varEnd, RegState::Define)
10355           .addConstantPoolIndex(Idx)
10356           .add(predOps(ARMCC::AL))
10357           .addMemOperand(CPMMO);
10358     else
10359       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
10360           .addReg(varEnd, RegState::Define)
10361           .addConstantPoolIndex(Idx)
10362           .addImm(0)
10363           .add(predOps(ARMCC::AL))
10364           .addMemOperand(CPMMO);
10365   }
10366   BB->addSuccessor(loopMBB);
10367 
10368   // Generate the loop body:
10369   //   varPhi = PHI(varLoop, varEnd)
10370   //   srcPhi = PHI(srcLoop, src)
10371   //   destPhi = PHI(destLoop, dst)
10372   MachineBasicBlock *entryBB = BB;
10373   BB = loopMBB;
10374   Register varLoop = MRI.createVirtualRegister(TRC);
10375   Register varPhi = MRI.createVirtualRegister(TRC);
10376   Register srcLoop = MRI.createVirtualRegister(TRC);
10377   Register srcPhi = MRI.createVirtualRegister(TRC);
10378   Register destLoop = MRI.createVirtualRegister(TRC);
10379   Register destPhi = MRI.createVirtualRegister(TRC);
10380 
10381   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
10382     .addReg(varLoop).addMBB(loopMBB)
10383     .addReg(varEnd).addMBB(entryBB);
10384   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
10385     .addReg(srcLoop).addMBB(loopMBB)
10386     .addReg(src).addMBB(entryBB);
10387   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
10388     .addReg(destLoop).addMBB(loopMBB)
10389     .addReg(dest).addMBB(entryBB);
10390 
10391   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10392   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
10393   Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10394   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
10395              IsThumb1, IsThumb2);
10396   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
10397              IsThumb1, IsThumb2);
10398 
10399   // Decrement loop variable by UnitSize.
10400   if (IsThumb1) {
10401     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
10402         .add(t1CondCodeOp())
10403         .addReg(varPhi)
10404         .addImm(UnitSize)
10405         .add(predOps(ARMCC::AL));
10406   } else {
10407     MachineInstrBuilder MIB =
10408         BuildMI(*BB, BB->end(), dl,
10409                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
10410     MIB.addReg(varPhi)
10411         .addImm(UnitSize)
10412         .add(predOps(ARMCC::AL))
10413         .add(condCodeOp());
10414     MIB->getOperand(5).setReg(ARM::CPSR);
10415     MIB->getOperand(5).setIsDef(true);
10416   }
10417   BuildMI(*BB, BB->end(), dl,
10418           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
10419       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
10420 
10421   // loopMBB can loop back to loopMBB or fall through to exitMBB.
10422   BB->addSuccessor(loopMBB);
10423   BB->addSuccessor(exitMBB);
10424 
10425   // Add epilogue to handle BytesLeft.
10426   BB = exitMBB;
10427   auto StartOfExit = exitMBB->begin();
10428 
10429   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10430   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10431   unsigned srcIn = srcLoop;
10432   unsigned destIn = destLoop;
10433   for (unsigned i = 0; i < BytesLeft; i++) {
10434     Register srcOut = MRI.createVirtualRegister(TRC);
10435     Register destOut = MRI.createVirtualRegister(TRC);
10436     Register scratch = MRI.createVirtualRegister(TRC);
10437     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
10438                IsThumb1, IsThumb2);
10439     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10440                IsThumb1, IsThumb2);
10441     srcIn = srcOut;
10442     destIn = destOut;
10443   }
10444 
10445   MI.eraseFromParent(); // The instruction is gone now.
10446   return BB;
10447 }
10448 
10449 MachineBasicBlock *
10450 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10451                                        MachineBasicBlock *MBB) const {
10452   const TargetMachine &TM = getTargetMachine();
10453   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10454   DebugLoc DL = MI.getDebugLoc();
10455 
10456   assert(Subtarget->isTargetWindows() &&
10457          "__chkstk is only supported on Windows");
10458   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10459 
10460   // __chkstk takes the number of words to allocate on the stack in R4, and
10461   // returns the stack adjustment in number of bytes in R4.  This will not
10462   // clober any other registers (other than the obvious lr).
10463   //
10464   // Although, technically, IP should be considered a register which may be
10465   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
10466   // thumb-2 environment, so there is no interworking required.  As a result, we
10467   // do not expect a veneer to be emitted by the linker, clobbering IP.
10468   //
10469   // Each module receives its own copy of __chkstk, so no import thunk is
10470   // required, again, ensuring that IP is not clobbered.
10471   //
10472   // Finally, although some linkers may theoretically provide a trampoline for
10473   // out of range calls (which is quite common due to a 32M range limitation of
10474   // branches for Thumb), we can generate the long-call version via
10475   // -mcmodel=large, alleviating the need for the trampoline which may clobber
10476   // IP.
10477 
10478   switch (TM.getCodeModel()) {
10479   case CodeModel::Tiny:
10480     llvm_unreachable("Tiny code model not available on ARM.");
10481   case CodeModel::Small:
10482   case CodeModel::Medium:
10483   case CodeModel::Kernel:
10484     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10485         .add(predOps(ARMCC::AL))
10486         .addExternalSymbol("__chkstk")
10487         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10488         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10489         .addReg(ARM::R12,
10490                 RegState::Implicit | RegState::Define | RegState::Dead)
10491         .addReg(ARM::CPSR,
10492                 RegState::Implicit | RegState::Define | RegState::Dead);
10493     break;
10494   case CodeModel::Large: {
10495     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10496     Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10497 
10498     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10499       .addExternalSymbol("__chkstk");
10500     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10501         .add(predOps(ARMCC::AL))
10502         .addReg(Reg, RegState::Kill)
10503         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10504         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10505         .addReg(ARM::R12,
10506                 RegState::Implicit | RegState::Define | RegState::Dead)
10507         .addReg(ARM::CPSR,
10508                 RegState::Implicit | RegState::Define | RegState::Dead);
10509     break;
10510   }
10511   }
10512 
10513   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10514       .addReg(ARM::SP, RegState::Kill)
10515       .addReg(ARM::R4, RegState::Kill)
10516       .setMIFlags(MachineInstr::FrameSetup)
10517       .add(predOps(ARMCC::AL))
10518       .add(condCodeOp());
10519 
10520   MI.eraseFromParent();
10521   return MBB;
10522 }
10523 
10524 MachineBasicBlock *
10525 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10526                                        MachineBasicBlock *MBB) const {
10527   DebugLoc DL = MI.getDebugLoc();
10528   MachineFunction *MF = MBB->getParent();
10529   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10530 
10531   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10532   MF->insert(++MBB->getIterator(), ContBB);
10533   ContBB->splice(ContBB->begin(), MBB,
10534                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10535   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10536   MBB->addSuccessor(ContBB);
10537 
10538   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10539   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10540   MF->push_back(TrapBB);
10541   MBB->addSuccessor(TrapBB);
10542 
10543   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10544       .addReg(MI.getOperand(0).getReg())
10545       .addImm(0)
10546       .add(predOps(ARMCC::AL));
10547   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10548       .addMBB(TrapBB)
10549       .addImm(ARMCC::EQ)
10550       .addReg(ARM::CPSR);
10551 
10552   MI.eraseFromParent();
10553   return ContBB;
10554 }
10555 
10556 // The CPSR operand of SelectItr might be missing a kill marker
10557 // because there were multiple uses of CPSR, and ISel didn't know
10558 // which to mark. Figure out whether SelectItr should have had a
10559 // kill marker, and set it if it should. Returns the correct kill
10560 // marker value.
10561 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10562                                    MachineBasicBlock* BB,
10563                                    const TargetRegisterInfo* TRI) {
10564   // Scan forward through BB for a use/def of CPSR.
10565   MachineBasicBlock::iterator miI(std::next(SelectItr));
10566   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10567     const MachineInstr& mi = *miI;
10568     if (mi.readsRegister(ARM::CPSR))
10569       return false;
10570     if (mi.definesRegister(ARM::CPSR))
10571       break; // Should have kill-flag - update below.
10572   }
10573 
10574   // If we hit the end of the block, check whether CPSR is live into a
10575   // successor.
10576   if (miI == BB->end()) {
10577     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10578                                           sEnd = BB->succ_end();
10579          sItr != sEnd; ++sItr) {
10580       MachineBasicBlock* succ = *sItr;
10581       if (succ->isLiveIn(ARM::CPSR))
10582         return false;
10583     }
10584   }
10585 
10586   // We found a def, or hit the end of the basic block and CPSR wasn't live
10587   // out. SelectMI should have a kill flag on CPSR.
10588   SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10589   return true;
10590 }
10591 
10592 MachineBasicBlock *
10593 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10594                                                MachineBasicBlock *BB) const {
10595   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10596   DebugLoc dl = MI.getDebugLoc();
10597   bool isThumb2 = Subtarget->isThumb2();
10598   switch (MI.getOpcode()) {
10599   default: {
10600     MI.print(errs());
10601     llvm_unreachable("Unexpected instr type to insert");
10602   }
10603 
10604   // Thumb1 post-indexed loads are really just single-register LDMs.
10605   case ARM::tLDR_postidx: {
10606     MachineOperand Def(MI.getOperand(1));
10607     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10608         .add(Def)  // Rn_wb
10609         .add(MI.getOperand(2))  // Rn
10610         .add(MI.getOperand(3))  // PredImm
10611         .add(MI.getOperand(4))  // PredReg
10612         .add(MI.getOperand(0))  // Rt
10613         .cloneMemRefs(MI);
10614     MI.eraseFromParent();
10615     return BB;
10616   }
10617 
10618   // The Thumb2 pre-indexed stores have the same MI operands, they just
10619   // define them differently in the .td files from the isel patterns, so
10620   // they need pseudos.
10621   case ARM::t2STR_preidx:
10622     MI.setDesc(TII->get(ARM::t2STR_PRE));
10623     return BB;
10624   case ARM::t2STRB_preidx:
10625     MI.setDesc(TII->get(ARM::t2STRB_PRE));
10626     return BB;
10627   case ARM::t2STRH_preidx:
10628     MI.setDesc(TII->get(ARM::t2STRH_PRE));
10629     return BB;
10630 
10631   case ARM::STRi_preidx:
10632   case ARM::STRBi_preidx: {
10633     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10634                                                          : ARM::STRB_PRE_IMM;
10635     // Decode the offset.
10636     unsigned Offset = MI.getOperand(4).getImm();
10637     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10638     Offset = ARM_AM::getAM2Offset(Offset);
10639     if (isSub)
10640       Offset = -Offset;
10641 
10642     MachineMemOperand *MMO = *MI.memoperands_begin();
10643     BuildMI(*BB, MI, dl, TII->get(NewOpc))
10644         .add(MI.getOperand(0)) // Rn_wb
10645         .add(MI.getOperand(1)) // Rt
10646         .add(MI.getOperand(2)) // Rn
10647         .addImm(Offset)        // offset (skip GPR==zero_reg)
10648         .add(MI.getOperand(5)) // pred
10649         .add(MI.getOperand(6))
10650         .addMemOperand(MMO);
10651     MI.eraseFromParent();
10652     return BB;
10653   }
10654   case ARM::STRr_preidx:
10655   case ARM::STRBr_preidx:
10656   case ARM::STRH_preidx: {
10657     unsigned NewOpc;
10658     switch (MI.getOpcode()) {
10659     default: llvm_unreachable("unexpected opcode!");
10660     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10661     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10662     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10663     }
10664     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10665     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10666       MIB.add(MI.getOperand(i));
10667     MI.eraseFromParent();
10668     return BB;
10669   }
10670 
10671   case ARM::tMOVCCr_pseudo: {
10672     // To "insert" a SELECT_CC instruction, we actually have to insert the
10673     // diamond control-flow pattern.  The incoming instruction knows the
10674     // destination vreg to set, the condition code register to branch on, the
10675     // true/false values to select between, and a branch opcode to use.
10676     const BasicBlock *LLVM_BB = BB->getBasicBlock();
10677     MachineFunction::iterator It = ++BB->getIterator();
10678 
10679     //  thisMBB:
10680     //  ...
10681     //   TrueVal = ...
10682     //   cmpTY ccX, r1, r2
10683     //   bCC copy1MBB
10684     //   fallthrough --> copy0MBB
10685     MachineBasicBlock *thisMBB  = BB;
10686     MachineFunction *F = BB->getParent();
10687     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10688     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
10689     F->insert(It, copy0MBB);
10690     F->insert(It, sinkMBB);
10691 
10692     // Check whether CPSR is live past the tMOVCCr_pseudo.
10693     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10694     if (!MI.killsRegister(ARM::CPSR) &&
10695         !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10696       copy0MBB->addLiveIn(ARM::CPSR);
10697       sinkMBB->addLiveIn(ARM::CPSR);
10698     }
10699 
10700     // Transfer the remainder of BB and its successor edges to sinkMBB.
10701     sinkMBB->splice(sinkMBB->begin(), BB,
10702                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10703     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10704 
10705     BB->addSuccessor(copy0MBB);
10706     BB->addSuccessor(sinkMBB);
10707 
10708     BuildMI(BB, dl, TII->get(ARM::tBcc))
10709         .addMBB(sinkMBB)
10710         .addImm(MI.getOperand(3).getImm())
10711         .addReg(MI.getOperand(4).getReg());
10712 
10713     //  copy0MBB:
10714     //   %FalseValue = ...
10715     //   # fallthrough to sinkMBB
10716     BB = copy0MBB;
10717 
10718     // Update machine-CFG edges
10719     BB->addSuccessor(sinkMBB);
10720 
10721     //  sinkMBB:
10722     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10723     //  ...
10724     BB = sinkMBB;
10725     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10726         .addReg(MI.getOperand(1).getReg())
10727         .addMBB(copy0MBB)
10728         .addReg(MI.getOperand(2).getReg())
10729         .addMBB(thisMBB);
10730 
10731     MI.eraseFromParent(); // The pseudo instruction is gone now.
10732     return BB;
10733   }
10734 
10735   case ARM::BCCi64:
10736   case ARM::BCCZi64: {
10737     // If there is an unconditional branch to the other successor, remove it.
10738     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10739 
10740     // Compare both parts that make up the double comparison separately for
10741     // equality.
10742     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10743 
10744     Register LHS1 = MI.getOperand(1).getReg();
10745     Register LHS2 = MI.getOperand(2).getReg();
10746     if (RHSisZero) {
10747       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10748           .addReg(LHS1)
10749           .addImm(0)
10750           .add(predOps(ARMCC::AL));
10751       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10752         .addReg(LHS2).addImm(0)
10753         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10754     } else {
10755       Register RHS1 = MI.getOperand(3).getReg();
10756       Register RHS2 = MI.getOperand(4).getReg();
10757       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10758           .addReg(LHS1)
10759           .addReg(RHS1)
10760           .add(predOps(ARMCC::AL));
10761       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10762         .addReg(LHS2).addReg(RHS2)
10763         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10764     }
10765 
10766     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10767     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10768     if (MI.getOperand(0).getImm() == ARMCC::NE)
10769       std::swap(destMBB, exitMBB);
10770 
10771     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10772       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10773     if (isThumb2)
10774       BuildMI(BB, dl, TII->get(ARM::t2B))
10775           .addMBB(exitMBB)
10776           .add(predOps(ARMCC::AL));
10777     else
10778       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10779 
10780     MI.eraseFromParent(); // The pseudo instruction is gone now.
10781     return BB;
10782   }
10783 
10784   case ARM::Int_eh_sjlj_setjmp:
10785   case ARM::Int_eh_sjlj_setjmp_nofp:
10786   case ARM::tInt_eh_sjlj_setjmp:
10787   case ARM::t2Int_eh_sjlj_setjmp:
10788   case ARM::t2Int_eh_sjlj_setjmp_nofp:
10789     return BB;
10790 
10791   case ARM::Int_eh_sjlj_setup_dispatch:
10792     EmitSjLjDispatchBlock(MI, BB);
10793     return BB;
10794 
10795   case ARM::ABS:
10796   case ARM::t2ABS: {
10797     // To insert an ABS instruction, we have to insert the
10798     // diamond control-flow pattern.  The incoming instruction knows the
10799     // source vreg to test against 0, the destination vreg to set,
10800     // the condition code register to branch on, the
10801     // true/false values to select between, and a branch opcode to use.
10802     // It transforms
10803     //     V1 = ABS V0
10804     // into
10805     //     V2 = MOVS V0
10806     //     BCC                      (branch to SinkBB if V0 >= 0)
10807     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
10808     //     SinkBB: V1 = PHI(V2, V3)
10809     const BasicBlock *LLVM_BB = BB->getBasicBlock();
10810     MachineFunction::iterator BBI = ++BB->getIterator();
10811     MachineFunction *Fn = BB->getParent();
10812     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10813     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
10814     Fn->insert(BBI, RSBBB);
10815     Fn->insert(BBI, SinkBB);
10816 
10817     Register ABSSrcReg = MI.getOperand(1).getReg();
10818     Register ABSDstReg = MI.getOperand(0).getReg();
10819     bool ABSSrcKIll = MI.getOperand(1).isKill();
10820     bool isThumb2 = Subtarget->isThumb2();
10821     MachineRegisterInfo &MRI = Fn->getRegInfo();
10822     // In Thumb mode S must not be specified if source register is the SP or
10823     // PC and if destination register is the SP, so restrict register class
10824     Register NewRsbDstReg = MRI.createVirtualRegister(
10825         isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10826 
10827     // Transfer the remainder of BB and its successor edges to sinkMBB.
10828     SinkBB->splice(SinkBB->begin(), BB,
10829                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
10830     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10831 
10832     BB->addSuccessor(RSBBB);
10833     BB->addSuccessor(SinkBB);
10834 
10835     // fall through to SinkMBB
10836     RSBBB->addSuccessor(SinkBB);
10837 
10838     // insert a cmp at the end of BB
10839     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10840         .addReg(ABSSrcReg)
10841         .addImm(0)
10842         .add(predOps(ARMCC::AL));
10843 
10844     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10845     BuildMI(BB, dl,
10846       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10847       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10848 
10849     // insert rsbri in RSBBB
10850     // Note: BCC and rsbri will be converted into predicated rsbmi
10851     // by if-conversion pass
10852     BuildMI(*RSBBB, RSBBB->begin(), dl,
10853             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10854         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10855         .addImm(0)
10856         .add(predOps(ARMCC::AL))
10857         .add(condCodeOp());
10858 
10859     // insert PHI in SinkBB,
10860     // reuse ABSDstReg to not change uses of ABS instruction
10861     BuildMI(*SinkBB, SinkBB->begin(), dl,
10862       TII->get(ARM::PHI), ABSDstReg)
10863       .addReg(NewRsbDstReg).addMBB(RSBBB)
10864       .addReg(ABSSrcReg).addMBB(BB);
10865 
10866     // remove ABS instruction
10867     MI.eraseFromParent();
10868 
10869     // return last added BB
10870     return SinkBB;
10871   }
10872   case ARM::COPY_STRUCT_BYVAL_I32:
10873     ++NumLoopByVals;
10874     return EmitStructByval(MI, BB);
10875   case ARM::WIN__CHKSTK:
10876     return EmitLowered__chkstk(MI, BB);
10877   case ARM::WIN__DBZCHK:
10878     return EmitLowered__dbzchk(MI, BB);
10879   }
10880 }
10881 
10882 /// Attaches vregs to MEMCPY that it will use as scratch registers
10883 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10884 /// instead of as a custom inserter because we need the use list from the SDNode.
10885 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10886                                     MachineInstr &MI, const SDNode *Node) {
10887   bool isThumb1 = Subtarget->isThumb1Only();
10888 
10889   DebugLoc DL = MI.getDebugLoc();
10890   MachineFunction *MF = MI.getParent()->getParent();
10891   MachineRegisterInfo &MRI = MF->getRegInfo();
10892   MachineInstrBuilder MIB(*MF, MI);
10893 
10894   // If the new dst/src is unused mark it as dead.
10895   if (!Node->hasAnyUseOfValue(0)) {
10896     MI.getOperand(0).setIsDead(true);
10897   }
10898   if (!Node->hasAnyUseOfValue(1)) {
10899     MI.getOperand(1).setIsDead(true);
10900   }
10901 
10902   // The MEMCPY both defines and kills the scratch registers.
10903   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10904     Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10905                                                          : &ARM::GPRRegClass);
10906     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10907   }
10908 }
10909 
10910 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10911                                                       SDNode *Node) const {
10912   if (MI.getOpcode() == ARM::MEMCPY) {
10913     attachMEMCPYScratchRegs(Subtarget, MI, Node);
10914     return;
10915   }
10916 
10917   const MCInstrDesc *MCID = &MI.getDesc();
10918   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10919   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10920   // operand is still set to noreg. If needed, set the optional operand's
10921   // register to CPSR, and remove the redundant implicit def.
10922   //
10923   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10924 
10925   // Rename pseudo opcodes.
10926   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10927   unsigned ccOutIdx;
10928   if (NewOpc) {
10929     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10930     MCID = &TII->get(NewOpc);
10931 
10932     assert(MCID->getNumOperands() ==
10933            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10934         && "converted opcode should be the same except for cc_out"
10935            " (and, on Thumb1, pred)");
10936 
10937     MI.setDesc(*MCID);
10938 
10939     // Add the optional cc_out operand
10940     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10941 
10942     // On Thumb1, move all input operands to the end, then add the predicate
10943     if (Subtarget->isThumb1Only()) {
10944       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10945         MI.addOperand(MI.getOperand(1));
10946         MI.RemoveOperand(1);
10947       }
10948 
10949       // Restore the ties
10950       for (unsigned i = MI.getNumOperands(); i--;) {
10951         const MachineOperand& op = MI.getOperand(i);
10952         if (op.isReg() && op.isUse()) {
10953           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10954           if (DefIdx != -1)
10955             MI.tieOperands(DefIdx, i);
10956         }
10957       }
10958 
10959       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10960       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10961       ccOutIdx = 1;
10962     } else
10963       ccOutIdx = MCID->getNumOperands() - 1;
10964   } else
10965     ccOutIdx = MCID->getNumOperands() - 1;
10966 
10967   // Any ARM instruction that sets the 's' bit should specify an optional
10968   // "cc_out" operand in the last operand position.
10969   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10970     assert(!NewOpc && "Optional cc_out operand required");
10971     return;
10972   }
10973   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10974   // since we already have an optional CPSR def.
10975   bool definesCPSR = false;
10976   bool deadCPSR = false;
10977   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10978        ++i) {
10979     const MachineOperand &MO = MI.getOperand(i);
10980     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10981       definesCPSR = true;
10982       if (MO.isDead())
10983         deadCPSR = true;
10984       MI.RemoveOperand(i);
10985       break;
10986     }
10987   }
10988   if (!definesCPSR) {
10989     assert(!NewOpc && "Optional cc_out operand required");
10990     return;
10991   }
10992   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10993   if (deadCPSR) {
10994     assert(!MI.getOperand(ccOutIdx).getReg() &&
10995            "expect uninitialized optional cc_out operand");
10996     // Thumb1 instructions must have the S bit even if the CPSR is dead.
10997     if (!Subtarget->isThumb1Only())
10998       return;
10999   }
11000 
11001   // If this instruction was defined with an optional CPSR def and its dag node
11002   // had a live implicit CPSR def, then activate the optional CPSR def.
11003   MachineOperand &MO = MI.getOperand(ccOutIdx);
11004   MO.setReg(ARM::CPSR);
11005   MO.setIsDef(true);
11006 }
11007 
11008 //===----------------------------------------------------------------------===//
11009 //                           ARM Optimization Hooks
11010 //===----------------------------------------------------------------------===//
11011 
11012 // Helper function that checks if N is a null or all ones constant.
11013 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
11014   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
11015 }
11016 
11017 // Return true if N is conditionally 0 or all ones.
11018 // Detects these expressions where cc is an i1 value:
11019 //
11020 //   (select cc 0, y)   [AllOnes=0]
11021 //   (select cc y, 0)   [AllOnes=0]
11022 //   (zext cc)          [AllOnes=0]
11023 //   (sext cc)          [AllOnes=0/1]
11024 //   (select cc -1, y)  [AllOnes=1]
11025 //   (select cc y, -1)  [AllOnes=1]
11026 //
11027 // Invert is set when N is the null/all ones constant when CC is false.
11028 // OtherOp is set to the alternative value of N.
11029 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
11030                                        SDValue &CC, bool &Invert,
11031                                        SDValue &OtherOp,
11032                                        SelectionDAG &DAG) {
11033   switch (N->getOpcode()) {
11034   default: return false;
11035   case ISD::SELECT: {
11036     CC = N->getOperand(0);
11037     SDValue N1 = N->getOperand(1);
11038     SDValue N2 = N->getOperand(2);
11039     if (isZeroOrAllOnes(N1, AllOnes)) {
11040       Invert = false;
11041       OtherOp = N2;
11042       return true;
11043     }
11044     if (isZeroOrAllOnes(N2, AllOnes)) {
11045       Invert = true;
11046       OtherOp = N1;
11047       return true;
11048     }
11049     return false;
11050   }
11051   case ISD::ZERO_EXTEND:
11052     // (zext cc) can never be the all ones value.
11053     if (AllOnes)
11054       return false;
11055     LLVM_FALLTHROUGH;
11056   case ISD::SIGN_EXTEND: {
11057     SDLoc dl(N);
11058     EVT VT = N->getValueType(0);
11059     CC = N->getOperand(0);
11060     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
11061       return false;
11062     Invert = !AllOnes;
11063     if (AllOnes)
11064       // When looking for an AllOnes constant, N is an sext, and the 'other'
11065       // value is 0.
11066       OtherOp = DAG.getConstant(0, dl, VT);
11067     else if (N->getOpcode() == ISD::ZERO_EXTEND)
11068       // When looking for a 0 constant, N can be zext or sext.
11069       OtherOp = DAG.getConstant(1, dl, VT);
11070     else
11071       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
11072                                 VT);
11073     return true;
11074   }
11075   }
11076 }
11077 
11078 // Combine a constant select operand into its use:
11079 //
11080 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
11081 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
11082 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
11083 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
11084 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
11085 //
11086 // The transform is rejected if the select doesn't have a constant operand that
11087 // is null, or all ones when AllOnes is set.
11088 //
11089 // Also recognize sext/zext from i1:
11090 //
11091 //   (add (zext cc), x) -> (select cc (add x, 1), x)
11092 //   (add (sext cc), x) -> (select cc (add x, -1), x)
11093 //
11094 // These transformations eventually create predicated instructions.
11095 //
11096 // @param N       The node to transform.
11097 // @param Slct    The N operand that is a select.
11098 // @param OtherOp The other N operand (x above).
11099 // @param DCI     Context.
11100 // @param AllOnes Require the select constant to be all ones instead of null.
11101 // @returns The new node, or SDValue() on failure.
11102 static
11103 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
11104                             TargetLowering::DAGCombinerInfo &DCI,
11105                             bool AllOnes = false) {
11106   SelectionDAG &DAG = DCI.DAG;
11107   EVT VT = N->getValueType(0);
11108   SDValue NonConstantVal;
11109   SDValue CCOp;
11110   bool SwapSelectOps;
11111   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
11112                                   NonConstantVal, DAG))
11113     return SDValue();
11114 
11115   // Slct is now know to be the desired identity constant when CC is true.
11116   SDValue TrueVal = OtherOp;
11117   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11118                                  OtherOp, NonConstantVal);
11119   // Unless SwapSelectOps says CC should be false.
11120   if (SwapSelectOps)
11121     std::swap(TrueVal, FalseVal);
11122 
11123   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
11124                      CCOp, TrueVal, FalseVal);
11125 }
11126 
11127 // Attempt combineSelectAndUse on each operand of a commutative operator N.
11128 static
11129 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
11130                                        TargetLowering::DAGCombinerInfo &DCI) {
11131   SDValue N0 = N->getOperand(0);
11132   SDValue N1 = N->getOperand(1);
11133   if (N0.getNode()->hasOneUse())
11134     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
11135       return Result;
11136   if (N1.getNode()->hasOneUse())
11137     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
11138       return Result;
11139   return SDValue();
11140 }
11141 
11142 static bool IsVUZPShuffleNode(SDNode *N) {
11143   // VUZP shuffle node.
11144   if (N->getOpcode() == ARMISD::VUZP)
11145     return true;
11146 
11147   // "VUZP" on i32 is an alias for VTRN.
11148   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
11149     return true;
11150 
11151   return false;
11152 }
11153 
11154 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
11155                                  TargetLowering::DAGCombinerInfo &DCI,
11156                                  const ARMSubtarget *Subtarget) {
11157   // Look for ADD(VUZP.0, VUZP.1).
11158   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
11159       N0 == N1)
11160    return SDValue();
11161 
11162   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
11163   if (!N->getValueType(0).is64BitVector())
11164     return SDValue();
11165 
11166   // Generate vpadd.
11167   SelectionDAG &DAG = DCI.DAG;
11168   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11169   SDLoc dl(N);
11170   SDNode *Unzip = N0.getNode();
11171   EVT VT = N->getValueType(0);
11172 
11173   SmallVector<SDValue, 8> Ops;
11174   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
11175                                 TLI.getPointerTy(DAG.getDataLayout())));
11176   Ops.push_back(Unzip->getOperand(0));
11177   Ops.push_back(Unzip->getOperand(1));
11178 
11179   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11180 }
11181 
11182 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11183                                       TargetLowering::DAGCombinerInfo &DCI,
11184                                       const ARMSubtarget *Subtarget) {
11185   // Check for two extended operands.
11186   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
11187         N1.getOpcode() == ISD::SIGN_EXTEND) &&
11188       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
11189         N1.getOpcode() == ISD::ZERO_EXTEND))
11190     return SDValue();
11191 
11192   SDValue N00 = N0.getOperand(0);
11193   SDValue N10 = N1.getOperand(0);
11194 
11195   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
11196   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
11197       N00 == N10)
11198     return SDValue();
11199 
11200   // We only recognize Q register paddl here; this can't be reached until
11201   // after type legalization.
11202   if (!N00.getValueType().is64BitVector() ||
11203       !N0.getValueType().is128BitVector())
11204     return SDValue();
11205 
11206   // Generate vpaddl.
11207   SelectionDAG &DAG = DCI.DAG;
11208   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11209   SDLoc dl(N);
11210   EVT VT = N->getValueType(0);
11211 
11212   SmallVector<SDValue, 8> Ops;
11213   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
11214   unsigned Opcode;
11215   if (N0.getOpcode() == ISD::SIGN_EXTEND)
11216     Opcode = Intrinsic::arm_neon_vpaddls;
11217   else
11218     Opcode = Intrinsic::arm_neon_vpaddlu;
11219   Ops.push_back(DAG.getConstant(Opcode, dl,
11220                                 TLI.getPointerTy(DAG.getDataLayout())));
11221   EVT ElemTy = N00.getValueType().getVectorElementType();
11222   unsigned NumElts = VT.getVectorNumElements();
11223   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
11224   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
11225                                N00.getOperand(0), N00.getOperand(1));
11226   Ops.push_back(Concat);
11227 
11228   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11229 }
11230 
11231 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
11232 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
11233 // much easier to match.
11234 static SDValue
11235 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11236                                TargetLowering::DAGCombinerInfo &DCI,
11237                                const ARMSubtarget *Subtarget) {
11238   // Only perform optimization if after legalize, and if NEON is available. We
11239   // also expected both operands to be BUILD_VECTORs.
11240   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
11241       || N0.getOpcode() != ISD::BUILD_VECTOR
11242       || N1.getOpcode() != ISD::BUILD_VECTOR)
11243     return SDValue();
11244 
11245   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
11246   EVT VT = N->getValueType(0);
11247   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
11248     return SDValue();
11249 
11250   // Check that the vector operands are of the right form.
11251   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
11252   // operands, where N is the size of the formed vector.
11253   // Each EXTRACT_VECTOR should have the same input vector and odd or even
11254   // index such that we have a pair wise add pattern.
11255 
11256   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
11257   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11258     return SDValue();
11259   SDValue Vec = N0->getOperand(0)->getOperand(0);
11260   SDNode *V = Vec.getNode();
11261   unsigned nextIndex = 0;
11262 
11263   // For each operands to the ADD which are BUILD_VECTORs,
11264   // check to see if each of their operands are an EXTRACT_VECTOR with
11265   // the same vector and appropriate index.
11266   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
11267     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
11268         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11269 
11270       SDValue ExtVec0 = N0->getOperand(i);
11271       SDValue ExtVec1 = N1->getOperand(i);
11272 
11273       // First operand is the vector, verify its the same.
11274       if (V != ExtVec0->getOperand(0).getNode() ||
11275           V != ExtVec1->getOperand(0).getNode())
11276         return SDValue();
11277 
11278       // Second is the constant, verify its correct.
11279       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
11280       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
11281 
11282       // For the constant, we want to see all the even or all the odd.
11283       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
11284           || C1->getZExtValue() != nextIndex+1)
11285         return SDValue();
11286 
11287       // Increment index.
11288       nextIndex+=2;
11289     } else
11290       return SDValue();
11291   }
11292 
11293   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
11294   // we're using the entire input vector, otherwise there's a size/legality
11295   // mismatch somewhere.
11296   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
11297       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
11298     return SDValue();
11299 
11300   // Create VPADDL node.
11301   SelectionDAG &DAG = DCI.DAG;
11302   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11303 
11304   SDLoc dl(N);
11305 
11306   // Build operand list.
11307   SmallVector<SDValue, 8> Ops;
11308   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
11309                                 TLI.getPointerTy(DAG.getDataLayout())));
11310 
11311   // Input is the vector.
11312   Ops.push_back(Vec);
11313 
11314   // Get widened type and narrowed type.
11315   MVT widenType;
11316   unsigned numElem = VT.getVectorNumElements();
11317 
11318   EVT inputLaneType = Vec.getValueType().getVectorElementType();
11319   switch (inputLaneType.getSimpleVT().SimpleTy) {
11320     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
11321     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
11322     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
11323     default:
11324       llvm_unreachable("Invalid vector element type for padd optimization.");
11325   }
11326 
11327   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
11328   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
11329   return DAG.getNode(ExtOp, dl, VT, tmp);
11330 }
11331 
11332 static SDValue findMUL_LOHI(SDValue V) {
11333   if (V->getOpcode() == ISD::UMUL_LOHI ||
11334       V->getOpcode() == ISD::SMUL_LOHI)
11335     return V;
11336   return SDValue();
11337 }
11338 
11339 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
11340                                         TargetLowering::DAGCombinerInfo &DCI,
11341                                         const ARMSubtarget *Subtarget) {
11342   if (!Subtarget->hasBaseDSP())
11343     return SDValue();
11344 
11345   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
11346   // accumulates the product into a 64-bit value. The 16-bit values will
11347   // be sign extended somehow or SRA'd into 32-bit values
11348   // (addc (adde (mul 16bit, 16bit), lo), hi)
11349   SDValue Mul = AddcNode->getOperand(0);
11350   SDValue Lo = AddcNode->getOperand(1);
11351   if (Mul.getOpcode() != ISD::MUL) {
11352     Lo = AddcNode->getOperand(0);
11353     Mul = AddcNode->getOperand(1);
11354     if (Mul.getOpcode() != ISD::MUL)
11355       return SDValue();
11356   }
11357 
11358   SDValue SRA = AddeNode->getOperand(0);
11359   SDValue Hi = AddeNode->getOperand(1);
11360   if (SRA.getOpcode() != ISD::SRA) {
11361     SRA = AddeNode->getOperand(1);
11362     Hi = AddeNode->getOperand(0);
11363     if (SRA.getOpcode() != ISD::SRA)
11364       return SDValue();
11365   }
11366   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
11367     if (Const->getZExtValue() != 31)
11368       return SDValue();
11369   } else
11370     return SDValue();
11371 
11372   if (SRA.getOperand(0) != Mul)
11373     return SDValue();
11374 
11375   SelectionDAG &DAG = DCI.DAG;
11376   SDLoc dl(AddcNode);
11377   unsigned Opcode = 0;
11378   SDValue Op0;
11379   SDValue Op1;
11380 
11381   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
11382     Opcode = ARMISD::SMLALBB;
11383     Op0 = Mul.getOperand(0);
11384     Op1 = Mul.getOperand(1);
11385   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
11386     Opcode = ARMISD::SMLALBT;
11387     Op0 = Mul.getOperand(0);
11388     Op1 = Mul.getOperand(1).getOperand(0);
11389   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
11390     Opcode = ARMISD::SMLALTB;
11391     Op0 = Mul.getOperand(0).getOperand(0);
11392     Op1 = Mul.getOperand(1);
11393   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
11394     Opcode = ARMISD::SMLALTT;
11395     Op0 = Mul->getOperand(0).getOperand(0);
11396     Op1 = Mul->getOperand(1).getOperand(0);
11397   }
11398 
11399   if (!Op0 || !Op1)
11400     return SDValue();
11401 
11402   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
11403                               Op0, Op1, Lo, Hi);
11404   // Replace the ADDs' nodes uses by the MLA node's values.
11405   SDValue HiMLALResult(SMLAL.getNode(), 1);
11406   SDValue LoMLALResult(SMLAL.getNode(), 0);
11407 
11408   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
11409   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
11410 
11411   // Return original node to notify the driver to stop replacing.
11412   SDValue resNode(AddcNode, 0);
11413   return resNode;
11414 }
11415 
11416 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
11417                                      TargetLowering::DAGCombinerInfo &DCI,
11418                                      const ARMSubtarget *Subtarget) {
11419   // Look for multiply add opportunities.
11420   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
11421   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
11422   // a glue link from the first add to the second add.
11423   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
11424   // a S/UMLAL instruction.
11425   //                  UMUL_LOHI
11426   //                 / :lo    \ :hi
11427   //                V          \          [no multiline comment]
11428   //    loAdd ->  ADDC         |
11429   //                 \ :carry /
11430   //                  V      V
11431   //                    ADDE   <- hiAdd
11432   //
11433   // In the special case where only the higher part of a signed result is used
11434   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
11435   // a constant with the exact value of 0x80000000, we recognize we are dealing
11436   // with a "rounded multiply and add" (or subtract) and transform it into
11437   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11438 
11439   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11440           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11441          "Expect an ADDE or SUBE");
11442 
11443   assert(AddeSubeNode->getNumOperands() == 3 &&
11444          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11445          "ADDE node has the wrong inputs");
11446 
11447   // Check that we are chained to the right ADDC or SUBC node.
11448   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11449   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11450        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11451       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11452        AddcSubcNode->getOpcode() != ARMISD::SUBC))
11453     return SDValue();
11454 
11455   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11456   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11457 
11458   // Check if the two operands are from the same mul_lohi node.
11459   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11460     return SDValue();
11461 
11462   assert(AddcSubcNode->getNumValues() == 2 &&
11463          AddcSubcNode->getValueType(0) == MVT::i32 &&
11464          "Expect ADDC with two result values. First: i32");
11465 
11466   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11467   // maybe a SMLAL which multiplies two 16-bit values.
11468   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11469       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11470       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11471       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11472       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11473     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11474 
11475   // Check for the triangle shape.
11476   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11477   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11478 
11479   // Make sure that the ADDE/SUBE operands are not coming from the same node.
11480   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11481     return SDValue();
11482 
11483   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11484   bool IsLeftOperandMUL = false;
11485   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11486   if (MULOp == SDValue())
11487     MULOp = findMUL_LOHI(AddeSubeOp1);
11488   else
11489     IsLeftOperandMUL = true;
11490   if (MULOp == SDValue())
11491     return SDValue();
11492 
11493   // Figure out the right opcode.
11494   unsigned Opc = MULOp->getOpcode();
11495   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11496 
11497   // Figure out the high and low input values to the MLAL node.
11498   SDValue *HiAddSub = nullptr;
11499   SDValue *LoMul = nullptr;
11500   SDValue *LowAddSub = nullptr;
11501 
11502   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11503   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11504     return SDValue();
11505 
11506   if (IsLeftOperandMUL)
11507     HiAddSub = &AddeSubeOp1;
11508   else
11509     HiAddSub = &AddeSubeOp0;
11510 
11511   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11512   // whose low result is fed to the ADDC/SUBC we are checking.
11513 
11514   if (AddcSubcOp0 == MULOp.getValue(0)) {
11515     LoMul = &AddcSubcOp0;
11516     LowAddSub = &AddcSubcOp1;
11517   }
11518   if (AddcSubcOp1 == MULOp.getValue(0)) {
11519     LoMul = &AddcSubcOp1;
11520     LowAddSub = &AddcSubcOp0;
11521   }
11522 
11523   if (!LoMul)
11524     return SDValue();
11525 
11526   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11527   // the replacement below will create a cycle.
11528   if (AddcSubcNode == HiAddSub->getNode() ||
11529       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11530     return SDValue();
11531 
11532   // Create the merged node.
11533   SelectionDAG &DAG = DCI.DAG;
11534 
11535   // Start building operand list.
11536   SmallVector<SDValue, 8> Ops;
11537   Ops.push_back(LoMul->getOperand(0));
11538   Ops.push_back(LoMul->getOperand(1));
11539 
11540   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
11541   // the case, we must be doing signed multiplication and only use the higher
11542   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11543   // addition or subtraction with the value of 0x800000.
11544   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11545       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11546       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11547       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11548           0x80000000) {
11549     Ops.push_back(*HiAddSub);
11550     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11551       FinalOpc = ARMISD::SMMLSR;
11552     } else {
11553       FinalOpc = ARMISD::SMMLAR;
11554     }
11555     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11556     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11557 
11558     return SDValue(AddeSubeNode, 0);
11559   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11560     // SMMLS is generated during instruction selection and the rest of this
11561     // function can not handle the case where AddcSubcNode is a SUBC.
11562     return SDValue();
11563 
11564   // Finish building the operand list for {U/S}MLAL
11565   Ops.push_back(*LowAddSub);
11566   Ops.push_back(*HiAddSub);
11567 
11568   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11569                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
11570 
11571   // Replace the ADDs' nodes uses by the MLA node's values.
11572   SDValue HiMLALResult(MLALNode.getNode(), 1);
11573   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11574 
11575   SDValue LoMLALResult(MLALNode.getNode(), 0);
11576   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11577 
11578   // Return original node to notify the driver to stop replacing.
11579   return SDValue(AddeSubeNode, 0);
11580 }
11581 
11582 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11583                                       TargetLowering::DAGCombinerInfo &DCI,
11584                                       const ARMSubtarget *Subtarget) {
11585   // UMAAL is similar to UMLAL except that it adds two unsigned values.
11586   // While trying to combine for the other MLAL nodes, first search for the
11587   // chance to use UMAAL. Check if Addc uses a node which has already
11588   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11589   // as the addend, and it's handled in PerformUMLALCombine.
11590 
11591   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11592     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11593 
11594   // Check that we have a glued ADDC node.
11595   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11596   if (AddcNode->getOpcode() != ARMISD::ADDC)
11597     return SDValue();
11598 
11599   // Find the converted UMAAL or quit if it doesn't exist.
11600   SDNode *UmlalNode = nullptr;
11601   SDValue AddHi;
11602   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11603     UmlalNode = AddcNode->getOperand(0).getNode();
11604     AddHi = AddcNode->getOperand(1);
11605   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11606     UmlalNode = AddcNode->getOperand(1).getNode();
11607     AddHi = AddcNode->getOperand(0);
11608   } else {
11609     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11610   }
11611 
11612   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11613   // the ADDC as well as Zero.
11614   if (!isNullConstant(UmlalNode->getOperand(3)))
11615     return SDValue();
11616 
11617   if ((isNullConstant(AddeNode->getOperand(0)) &&
11618        AddeNode->getOperand(1).getNode() == UmlalNode) ||
11619       (AddeNode->getOperand(0).getNode() == UmlalNode &&
11620        isNullConstant(AddeNode->getOperand(1)))) {
11621     SelectionDAG &DAG = DCI.DAG;
11622     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11623                       UmlalNode->getOperand(2), AddHi };
11624     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11625                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
11626 
11627     // Replace the ADDs' nodes uses by the UMAAL node's values.
11628     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11629     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11630 
11631     // Return original node to notify the driver to stop replacing.
11632     return SDValue(AddeNode, 0);
11633   }
11634   return SDValue();
11635 }
11636 
11637 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11638                                    const ARMSubtarget *Subtarget) {
11639   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11640     return SDValue();
11641 
11642   // Check that we have a pair of ADDC and ADDE as operands.
11643   // Both addends of the ADDE must be zero.
11644   SDNode* AddcNode = N->getOperand(2).getNode();
11645   SDNode* AddeNode = N->getOperand(3).getNode();
11646   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11647       (AddeNode->getOpcode() == ARMISD::ADDE) &&
11648       isNullConstant(AddeNode->getOperand(0)) &&
11649       isNullConstant(AddeNode->getOperand(1)) &&
11650       (AddeNode->getOperand(2).getNode() == AddcNode))
11651     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11652                        DAG.getVTList(MVT::i32, MVT::i32),
11653                        {N->getOperand(0), N->getOperand(1),
11654                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
11655   else
11656     return SDValue();
11657 }
11658 
11659 static SDValue PerformAddcSubcCombine(SDNode *N,
11660                                       TargetLowering::DAGCombinerInfo &DCI,
11661                                       const ARMSubtarget *Subtarget) {
11662   SelectionDAG &DAG(DCI.DAG);
11663 
11664   if (N->getOpcode() == ARMISD::SUBC) {
11665     // (SUBC (ADDE 0, 0, C), 1) -> C
11666     SDValue LHS = N->getOperand(0);
11667     SDValue RHS = N->getOperand(1);
11668     if (LHS->getOpcode() == ARMISD::ADDE &&
11669         isNullConstant(LHS->getOperand(0)) &&
11670         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11671       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11672     }
11673   }
11674 
11675   if (Subtarget->isThumb1Only()) {
11676     SDValue RHS = N->getOperand(1);
11677     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11678       int32_t imm = C->getSExtValue();
11679       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11680         SDLoc DL(N);
11681         RHS = DAG.getConstant(-imm, DL, MVT::i32);
11682         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11683                                                            : ARMISD::ADDC;
11684         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11685       }
11686     }
11687   }
11688 
11689   return SDValue();
11690 }
11691 
11692 static SDValue PerformAddeSubeCombine(SDNode *N,
11693                                       TargetLowering::DAGCombinerInfo &DCI,
11694                                       const ARMSubtarget *Subtarget) {
11695   if (Subtarget->isThumb1Only()) {
11696     SelectionDAG &DAG = DCI.DAG;
11697     SDValue RHS = N->getOperand(1);
11698     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11699       int64_t imm = C->getSExtValue();
11700       if (imm < 0) {
11701         SDLoc DL(N);
11702 
11703         // The with-carry-in form matches bitwise not instead of the negation.
11704         // Effectively, the inverse interpretation of the carry flag already
11705         // accounts for part of the negation.
11706         RHS = DAG.getConstant(~imm, DL, MVT::i32);
11707 
11708         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11709                                                            : ARMISD::ADDE;
11710         return DAG.getNode(Opcode, DL, N->getVTList(),
11711                            N->getOperand(0), RHS, N->getOperand(2));
11712       }
11713     }
11714   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11715     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11716   }
11717   return SDValue();
11718 }
11719 
11720 static SDValue PerformABSCombine(SDNode *N,
11721                                   TargetLowering::DAGCombinerInfo &DCI,
11722                                   const ARMSubtarget *Subtarget) {
11723   SDValue res;
11724   SelectionDAG &DAG = DCI.DAG;
11725   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11726 
11727   if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11728     return SDValue();
11729 
11730   if (!TLI.expandABS(N, res, DAG))
11731       return SDValue();
11732 
11733   return res;
11734 }
11735 
11736 /// PerformADDECombine - Target-specific dag combine transform from
11737 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11738 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11739 static SDValue PerformADDECombine(SDNode *N,
11740                                   TargetLowering::DAGCombinerInfo &DCI,
11741                                   const ARMSubtarget *Subtarget) {
11742   // Only ARM and Thumb2 support UMLAL/SMLAL.
11743   if (Subtarget->isThumb1Only())
11744     return PerformAddeSubeCombine(N, DCI, Subtarget);
11745 
11746   // Only perform the checks after legalize when the pattern is available.
11747   if (DCI.isBeforeLegalize()) return SDValue();
11748 
11749   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11750 }
11751 
11752 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11753 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
11754 /// called with the default operands, and if that fails, with commuted
11755 /// operands.
11756 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11757                                           TargetLowering::DAGCombinerInfo &DCI,
11758                                           const ARMSubtarget *Subtarget){
11759   // Attempt to create vpadd for this add.
11760   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11761     return Result;
11762 
11763   // Attempt to create vpaddl for this add.
11764   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11765     return Result;
11766   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11767                                                       Subtarget))
11768     return Result;
11769 
11770   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11771   if (N0.getNode()->hasOneUse())
11772     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11773       return Result;
11774   return SDValue();
11775 }
11776 
11777 static SDValue PerformADDVecReduce(SDNode *N,
11778                                    TargetLowering::DAGCombinerInfo &DCI,
11779                                    const ARMSubtarget *Subtarget) {
11780   if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64)
11781     return SDValue();
11782 
11783   SDValue N0 = N->getOperand(0);
11784   SDValue N1 = N->getOperand(1);
11785 
11786   // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
11787   // will look like:
11788   //   t1: i32,i32 = ARMISD::VADDLVs x
11789   //   t2: i64 = build_pair t1, t1:1
11790   //   t3: i64 = add t2, y
11791   // We also need to check for sext / zext and commutitive adds.
11792   auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
11793                            SDValue NB) {
11794     if (NB->getOpcode() != ISD::BUILD_PAIR)
11795       return SDValue();
11796     SDValue VecRed = NB->getOperand(0);
11797     if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 ||
11798         NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
11799       return SDValue();
11800 
11801     SDLoc dl(N);
11802     SmallVector<SDValue, 4> Ops;
11803     Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
11804                                   DCI.DAG.getConstant(0, dl, MVT::i32)));
11805     Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
11806                                   DCI.DAG.getConstant(1, dl, MVT::i32)));
11807     for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++)
11808       Ops.push_back(VecRed->getOperand(i));
11809     SDValue Red = DCI.DAG.getNode(OpcodeA, dl,
11810                                   DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops);
11811     return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
11812                            SDValue(Red.getNode(), 1));
11813   };
11814 
11815   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
11816     return M;
11817   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
11818     return M;
11819   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
11820     return M;
11821   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
11822     return M;
11823   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
11824     return M;
11825   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
11826     return M;
11827   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
11828     return M;
11829   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
11830     return M;
11831   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
11832     return M;
11833   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
11834     return M;
11835   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
11836     return M;
11837   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
11838     return M;
11839   return SDValue();
11840 }
11841 
11842 bool
11843 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11844                                                  CombineLevel Level) const {
11845   if (Level == BeforeLegalizeTypes)
11846     return true;
11847 
11848   if (N->getOpcode() != ISD::SHL)
11849     return true;
11850 
11851   if (Subtarget->isThumb1Only()) {
11852     // Avoid making expensive immediates by commuting shifts. (This logic
11853     // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11854     // for free.)
11855     if (N->getOpcode() != ISD::SHL)
11856       return true;
11857     SDValue N1 = N->getOperand(0);
11858     if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11859         N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11860       return true;
11861     if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11862       if (Const->getAPIntValue().ult(256))
11863         return false;
11864       if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11865           Const->getAPIntValue().sgt(-256))
11866         return false;
11867     }
11868     return true;
11869   }
11870 
11871   // Turn off commute-with-shift transform after legalization, so it doesn't
11872   // conflict with PerformSHLSimplify.  (We could try to detect when
11873   // PerformSHLSimplify would trigger more precisely, but it isn't
11874   // really necessary.)
11875   return false;
11876 }
11877 
11878 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11879     const SDNode *N, CombineLevel Level) const {
11880   if (!Subtarget->isThumb1Only())
11881     return true;
11882 
11883   if (Level == BeforeLegalizeTypes)
11884     return true;
11885 
11886   return false;
11887 }
11888 
11889 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11890   if (!Subtarget->hasNEON()) {
11891     if (Subtarget->isThumb1Only())
11892       return VT.getScalarSizeInBits() <= 32;
11893     return true;
11894   }
11895   return VT.isScalarInteger();
11896 }
11897 
11898 static SDValue PerformSHLSimplify(SDNode *N,
11899                                 TargetLowering::DAGCombinerInfo &DCI,
11900                                 const ARMSubtarget *ST) {
11901   // Allow the generic combiner to identify potential bswaps.
11902   if (DCI.isBeforeLegalize())
11903     return SDValue();
11904 
11905   // DAG combiner will fold:
11906   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11907   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11908   // Other code patterns that can be also be modified have the following form:
11909   // b + ((a << 1) | 510)
11910   // b + ((a << 1) & 510)
11911   // b + ((a << 1) ^ 510)
11912   // b + ((a << 1) + 510)
11913 
11914   // Many instructions can  perform the shift for free, but it requires both
11915   // the operands to be registers. If c1 << c2 is too large, a mov immediate
11916   // instruction will needed. So, unfold back to the original pattern if:
11917   // - if c1 and c2 are small enough that they don't require mov imms.
11918   // - the user(s) of the node can perform an shl
11919 
11920   // No shifted operands for 16-bit instructions.
11921   if (ST->isThumb() && ST->isThumb1Only())
11922     return SDValue();
11923 
11924   // Check that all the users could perform the shl themselves.
11925   for (auto U : N->uses()) {
11926     switch(U->getOpcode()) {
11927     default:
11928       return SDValue();
11929     case ISD::SUB:
11930     case ISD::ADD:
11931     case ISD::AND:
11932     case ISD::OR:
11933     case ISD::XOR:
11934     case ISD::SETCC:
11935     case ARMISD::CMP:
11936       // Check that the user isn't already using a constant because there
11937       // aren't any instructions that support an immediate operand and a
11938       // shifted operand.
11939       if (isa<ConstantSDNode>(U->getOperand(0)) ||
11940           isa<ConstantSDNode>(U->getOperand(1)))
11941         return SDValue();
11942 
11943       // Check that it's not already using a shift.
11944       if (U->getOperand(0).getOpcode() == ISD::SHL ||
11945           U->getOperand(1).getOpcode() == ISD::SHL)
11946         return SDValue();
11947       break;
11948     }
11949   }
11950 
11951   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11952       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11953     return SDValue();
11954 
11955   if (N->getOperand(0).getOpcode() != ISD::SHL)
11956     return SDValue();
11957 
11958   SDValue SHL = N->getOperand(0);
11959 
11960   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
11961   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
11962   if (!C1ShlC2 || !C2)
11963     return SDValue();
11964 
11965   APInt C2Int = C2->getAPIntValue();
11966   APInt C1Int = C1ShlC2->getAPIntValue();
11967 
11968   // Check that performing a lshr will not lose any information.
11969   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
11970                                      C2Int.getBitWidth() - C2->getZExtValue());
11971   if ((C1Int & Mask) != C1Int)
11972     return SDValue();
11973 
11974   // Shift the first constant.
11975   C1Int.lshrInPlace(C2Int);
11976 
11977   // The immediates are encoded as an 8-bit value that can be rotated.
11978   auto LargeImm = [](const APInt &Imm) {
11979     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
11980     return Imm.getBitWidth() - Zeros > 8;
11981   };
11982 
11983   if (LargeImm(C1Int) || LargeImm(C2Int))
11984     return SDValue();
11985 
11986   SelectionDAG &DAG = DCI.DAG;
11987   SDLoc dl(N);
11988   SDValue X = SHL.getOperand(0);
11989   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
11990                               DAG.getConstant(C1Int, dl, MVT::i32));
11991   // Shift left to compensate for the lshr of C1Int.
11992   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
11993 
11994   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
11995              SHL.dump(); N->dump());
11996   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
11997   return Res;
11998 }
11999 
12000 
12001 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
12002 ///
12003 static SDValue PerformADDCombine(SDNode *N,
12004                                  TargetLowering::DAGCombinerInfo &DCI,
12005                                  const ARMSubtarget *Subtarget) {
12006   SDValue N0 = N->getOperand(0);
12007   SDValue N1 = N->getOperand(1);
12008 
12009   // Only works one way, because it needs an immediate operand.
12010   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12011     return Result;
12012 
12013   if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget))
12014     return Result;
12015 
12016   // First try with the default operand order.
12017   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
12018     return Result;
12019 
12020   // If that didn't work, try again with the operands commuted.
12021   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
12022 }
12023 
12024 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
12025 ///
12026 static SDValue PerformSUBCombine(SDNode *N,
12027                                  TargetLowering::DAGCombinerInfo &DCI,
12028                                  const ARMSubtarget *Subtarget) {
12029   SDValue N0 = N->getOperand(0);
12030   SDValue N1 = N->getOperand(1);
12031 
12032   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12033   if (N1.getNode()->hasOneUse())
12034     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
12035       return Result;
12036 
12037   if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
12038     return SDValue();
12039 
12040   // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
12041   // so that we can readily pattern match more mve instructions which can use
12042   // a scalar operand.
12043   SDValue VDup = N->getOperand(1);
12044   if (VDup->getOpcode() != ARMISD::VDUP)
12045     return SDValue();
12046 
12047   SDValue VMov = N->getOperand(0);
12048   if (VMov->getOpcode() == ISD::BITCAST)
12049     VMov = VMov->getOperand(0);
12050 
12051   if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
12052     return SDValue();
12053 
12054   SDLoc dl(N);
12055   SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
12056                                    DCI.DAG.getConstant(0, dl, MVT::i32),
12057                                    VDup->getOperand(0));
12058   return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
12059 }
12060 
12061 /// PerformVMULCombine
12062 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
12063 /// special multiplier accumulator forwarding.
12064 ///   vmul d3, d0, d2
12065 ///   vmla d3, d1, d2
12066 /// is faster than
12067 ///   vadd d3, d0, d1
12068 ///   vmul d3, d3, d2
12069 //  However, for (A + B) * (A + B),
12070 //    vadd d2, d0, d1
12071 //    vmul d3, d0, d2
12072 //    vmla d3, d1, d2
12073 //  is slower than
12074 //    vadd d2, d0, d1
12075 //    vmul d3, d2, d2
12076 static SDValue PerformVMULCombine(SDNode *N,
12077                                   TargetLowering::DAGCombinerInfo &DCI,
12078                                   const ARMSubtarget *Subtarget) {
12079   if (!Subtarget->hasVMLxForwarding())
12080     return SDValue();
12081 
12082   SelectionDAG &DAG = DCI.DAG;
12083   SDValue N0 = N->getOperand(0);
12084   SDValue N1 = N->getOperand(1);
12085   unsigned Opcode = N0.getOpcode();
12086   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12087       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
12088     Opcode = N1.getOpcode();
12089     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12090         Opcode != ISD::FADD && Opcode != ISD::FSUB)
12091       return SDValue();
12092     std::swap(N0, N1);
12093   }
12094 
12095   if (N0 == N1)
12096     return SDValue();
12097 
12098   EVT VT = N->getValueType(0);
12099   SDLoc DL(N);
12100   SDValue N00 = N0->getOperand(0);
12101   SDValue N01 = N0->getOperand(1);
12102   return DAG.getNode(Opcode, DL, VT,
12103                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
12104                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
12105 }
12106 
12107 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
12108                                       const ARMSubtarget *Subtarget) {
12109   EVT VT = N->getValueType(0);
12110   if (VT != MVT::v2i64)
12111     return SDValue();
12112 
12113   SDValue N0 = N->getOperand(0);
12114   SDValue N1 = N->getOperand(1);
12115 
12116   auto IsSignExt = [&](SDValue Op) {
12117     if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
12118       return SDValue();
12119     EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
12120     if (VT.getScalarSizeInBits() == 32)
12121       return Op->getOperand(0);
12122     return SDValue();
12123   };
12124   auto IsZeroExt = [&](SDValue Op) {
12125     // Zero extends are a little more awkward. At the point we are matching
12126     // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
12127     // That might be before of after a bitcast depending on how the and is
12128     // placed. Because this has to look through bitcasts, it is currently only
12129     // supported on LE.
12130     if (!Subtarget->isLittle())
12131       return SDValue();
12132 
12133     SDValue And = Op;
12134     if (And->getOpcode() == ISD::BITCAST)
12135       And = And->getOperand(0);
12136     if (And->getOpcode() != ISD::AND)
12137       return SDValue();
12138     SDValue Mask = And->getOperand(1);
12139     if (Mask->getOpcode() == ISD::BITCAST)
12140       Mask = Mask->getOperand(0);
12141 
12142     if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
12143         Mask.getValueType() != MVT::v4i32)
12144       return SDValue();
12145     if (isAllOnesConstant(Mask->getOperand(0)) &&
12146         isNullConstant(Mask->getOperand(1)) &&
12147         isAllOnesConstant(Mask->getOperand(2)) &&
12148         isNullConstant(Mask->getOperand(3)))
12149       return And->getOperand(0);
12150     return SDValue();
12151   };
12152 
12153   SDLoc dl(N);
12154   if (SDValue Op0 = IsSignExt(N0)) {
12155     if (SDValue Op1 = IsSignExt(N1)) {
12156       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12157       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12158       return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
12159     }
12160   }
12161   if (SDValue Op0 = IsZeroExt(N0)) {
12162     if (SDValue Op1 = IsZeroExt(N1)) {
12163       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12164       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12165       return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
12166     }
12167   }
12168 
12169   return SDValue();
12170 }
12171 
12172 static SDValue PerformMULCombine(SDNode *N,
12173                                  TargetLowering::DAGCombinerInfo &DCI,
12174                                  const ARMSubtarget *Subtarget) {
12175   SelectionDAG &DAG = DCI.DAG;
12176 
12177   EVT VT = N->getValueType(0);
12178   if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
12179     return PerformMVEVMULLCombine(N, DAG, Subtarget);
12180 
12181   if (Subtarget->isThumb1Only())
12182     return SDValue();
12183 
12184   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12185     return SDValue();
12186 
12187   if (VT.is64BitVector() || VT.is128BitVector())
12188     return PerformVMULCombine(N, DCI, Subtarget);
12189   if (VT != MVT::i32)
12190     return SDValue();
12191 
12192   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12193   if (!C)
12194     return SDValue();
12195 
12196   int64_t MulAmt = C->getSExtValue();
12197   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
12198 
12199   ShiftAmt = ShiftAmt & (32 - 1);
12200   SDValue V = N->getOperand(0);
12201   SDLoc DL(N);
12202 
12203   SDValue Res;
12204   MulAmt >>= ShiftAmt;
12205 
12206   if (MulAmt >= 0) {
12207     if (isPowerOf2_32(MulAmt - 1)) {
12208       // (mul x, 2^N + 1) => (add (shl x, N), x)
12209       Res = DAG.getNode(ISD::ADD, DL, VT,
12210                         V,
12211                         DAG.getNode(ISD::SHL, DL, VT,
12212                                     V,
12213                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
12214                                                     MVT::i32)));
12215     } else if (isPowerOf2_32(MulAmt + 1)) {
12216       // (mul x, 2^N - 1) => (sub (shl x, N), x)
12217       Res = DAG.getNode(ISD::SUB, DL, VT,
12218                         DAG.getNode(ISD::SHL, DL, VT,
12219                                     V,
12220                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
12221                                                     MVT::i32)),
12222                         V);
12223     } else
12224       return SDValue();
12225   } else {
12226     uint64_t MulAmtAbs = -MulAmt;
12227     if (isPowerOf2_32(MulAmtAbs + 1)) {
12228       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
12229       Res = DAG.getNode(ISD::SUB, DL, VT,
12230                         V,
12231                         DAG.getNode(ISD::SHL, DL, VT,
12232                                     V,
12233                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
12234                                                     MVT::i32)));
12235     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
12236       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
12237       Res = DAG.getNode(ISD::ADD, DL, VT,
12238                         V,
12239                         DAG.getNode(ISD::SHL, DL, VT,
12240                                     V,
12241                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
12242                                                     MVT::i32)));
12243       Res = DAG.getNode(ISD::SUB, DL, VT,
12244                         DAG.getConstant(0, DL, MVT::i32), Res);
12245     } else
12246       return SDValue();
12247   }
12248 
12249   if (ShiftAmt != 0)
12250     Res = DAG.getNode(ISD::SHL, DL, VT,
12251                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
12252 
12253   // Do not add new nodes to DAG combiner worklist.
12254   DCI.CombineTo(N, Res, false);
12255   return SDValue();
12256 }
12257 
12258 static SDValue CombineANDShift(SDNode *N,
12259                                TargetLowering::DAGCombinerInfo &DCI,
12260                                const ARMSubtarget *Subtarget) {
12261   // Allow DAGCombine to pattern-match before we touch the canonical form.
12262   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12263     return SDValue();
12264 
12265   if (N->getValueType(0) != MVT::i32)
12266     return SDValue();
12267 
12268   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12269   if (!N1C)
12270     return SDValue();
12271 
12272   uint32_t C1 = (uint32_t)N1C->getZExtValue();
12273   // Don't transform uxtb/uxth.
12274   if (C1 == 255 || C1 == 65535)
12275     return SDValue();
12276 
12277   SDNode *N0 = N->getOperand(0).getNode();
12278   if (!N0->hasOneUse())
12279     return SDValue();
12280 
12281   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
12282     return SDValue();
12283 
12284   bool LeftShift = N0->getOpcode() == ISD::SHL;
12285 
12286   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12287   if (!N01C)
12288     return SDValue();
12289 
12290   uint32_t C2 = (uint32_t)N01C->getZExtValue();
12291   if (!C2 || C2 >= 32)
12292     return SDValue();
12293 
12294   // Clear irrelevant bits in the mask.
12295   if (LeftShift)
12296     C1 &= (-1U << C2);
12297   else
12298     C1 &= (-1U >> C2);
12299 
12300   SelectionDAG &DAG = DCI.DAG;
12301   SDLoc DL(N);
12302 
12303   // We have a pattern of the form "(and (shl x, c2) c1)" or
12304   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
12305   // transform to a pair of shifts, to save materializing c1.
12306 
12307   // First pattern: right shift, then mask off leading bits.
12308   // FIXME: Use demanded bits?
12309   if (!LeftShift && isMask_32(C1)) {
12310     uint32_t C3 = countLeadingZeros(C1);
12311     if (C2 < C3) {
12312       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12313                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12314       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12315                          DAG.getConstant(C3, DL, MVT::i32));
12316     }
12317   }
12318 
12319   // First pattern, reversed: left shift, then mask off trailing bits.
12320   if (LeftShift && isMask_32(~C1)) {
12321     uint32_t C3 = countTrailingZeros(C1);
12322     if (C2 < C3) {
12323       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12324                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12325       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12326                          DAG.getConstant(C3, DL, MVT::i32));
12327     }
12328   }
12329 
12330   // Second pattern: left shift, then mask off leading bits.
12331   // FIXME: Use demanded bits?
12332   if (LeftShift && isShiftedMask_32(C1)) {
12333     uint32_t Trailing = countTrailingZeros(C1);
12334     uint32_t C3 = countLeadingZeros(C1);
12335     if (Trailing == C2 && C2 + C3 < 32) {
12336       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12337                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12338       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12339                         DAG.getConstant(C3, DL, MVT::i32));
12340     }
12341   }
12342 
12343   // Second pattern, reversed: right shift, then mask off trailing bits.
12344   // FIXME: Handle other patterns of known/demanded bits.
12345   if (!LeftShift && isShiftedMask_32(C1)) {
12346     uint32_t Leading = countLeadingZeros(C1);
12347     uint32_t C3 = countTrailingZeros(C1);
12348     if (Leading == C2 && C2 + C3 < 32) {
12349       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12350                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12351       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12352                          DAG.getConstant(C3, DL, MVT::i32));
12353     }
12354   }
12355 
12356   // FIXME: Transform "(and (shl x, c2) c1)" ->
12357   // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
12358   // c1.
12359   return SDValue();
12360 }
12361 
12362 static SDValue PerformANDCombine(SDNode *N,
12363                                  TargetLowering::DAGCombinerInfo &DCI,
12364                                  const ARMSubtarget *Subtarget) {
12365   // Attempt to use immediate-form VBIC
12366   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12367   SDLoc dl(N);
12368   EVT VT = N->getValueType(0);
12369   SelectionDAG &DAG = DCI.DAG;
12370 
12371   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12372     return SDValue();
12373 
12374   APInt SplatBits, SplatUndef;
12375   unsigned SplatBitSize;
12376   bool HasAnyUndefs;
12377   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
12378       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12379     if (SplatBitSize <= 64) {
12380       EVT VbicVT;
12381       SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
12382                                       SplatUndef.getZExtValue(), SplatBitSize,
12383                                       DAG, dl, VbicVT, VT, OtherModImm);
12384       if (Val.getNode()) {
12385         SDValue Input =
12386           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
12387         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
12388         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
12389       }
12390     }
12391   }
12392 
12393   if (!Subtarget->isThumb1Only()) {
12394     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
12395     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
12396       return Result;
12397 
12398     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12399       return Result;
12400   }
12401 
12402   if (Subtarget->isThumb1Only())
12403     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
12404       return Result;
12405 
12406   return SDValue();
12407 }
12408 
12409 // Try combining OR nodes to SMULWB, SMULWT.
12410 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
12411                                          TargetLowering::DAGCombinerInfo &DCI,
12412                                          const ARMSubtarget *Subtarget) {
12413   if (!Subtarget->hasV6Ops() ||
12414       (Subtarget->isThumb() &&
12415        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
12416     return SDValue();
12417 
12418   SDValue SRL = OR->getOperand(0);
12419   SDValue SHL = OR->getOperand(1);
12420 
12421   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
12422     SRL = OR->getOperand(1);
12423     SHL = OR->getOperand(0);
12424   }
12425   if (!isSRL16(SRL) || !isSHL16(SHL))
12426     return SDValue();
12427 
12428   // The first operands to the shifts need to be the two results from the
12429   // same smul_lohi node.
12430   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
12431        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
12432     return SDValue();
12433 
12434   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
12435   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
12436       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
12437     return SDValue();
12438 
12439   // Now we have:
12440   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
12441   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
12442   // For SMUWB the 16-bit value will signed extended somehow.
12443   // For SMULWT only the SRA is required.
12444   // Check both sides of SMUL_LOHI
12445   SDValue OpS16 = SMULLOHI->getOperand(0);
12446   SDValue OpS32 = SMULLOHI->getOperand(1);
12447 
12448   SelectionDAG &DAG = DCI.DAG;
12449   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
12450     OpS16 = OpS32;
12451     OpS32 = SMULLOHI->getOperand(0);
12452   }
12453 
12454   SDLoc dl(OR);
12455   unsigned Opcode = 0;
12456   if (isS16(OpS16, DAG))
12457     Opcode = ARMISD::SMULWB;
12458   else if (isSRA16(OpS16)) {
12459     Opcode = ARMISD::SMULWT;
12460     OpS16 = OpS16->getOperand(0);
12461   }
12462   else
12463     return SDValue();
12464 
12465   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
12466   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
12467   return SDValue(OR, 0);
12468 }
12469 
12470 static SDValue PerformORCombineToBFI(SDNode *N,
12471                                      TargetLowering::DAGCombinerInfo &DCI,
12472                                      const ARMSubtarget *Subtarget) {
12473   // BFI is only available on V6T2+
12474   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
12475     return SDValue();
12476 
12477   EVT VT = N->getValueType(0);
12478   SDValue N0 = N->getOperand(0);
12479   SDValue N1 = N->getOperand(1);
12480   SelectionDAG &DAG = DCI.DAG;
12481   SDLoc DL(N);
12482   // 1) or (and A, mask), val => ARMbfi A, val, mask
12483   //      iff (val & mask) == val
12484   //
12485   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12486   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
12487   //          && mask == ~mask2
12488   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
12489   //          && ~mask == mask2
12490   //  (i.e., copy a bitfield value into another bitfield of the same width)
12491 
12492   if (VT != MVT::i32)
12493     return SDValue();
12494 
12495   SDValue N00 = N0.getOperand(0);
12496 
12497   // The value and the mask need to be constants so we can verify this is
12498   // actually a bitfield set. If the mask is 0xffff, we can do better
12499   // via a movt instruction, so don't use BFI in that case.
12500   SDValue MaskOp = N0.getOperand(1);
12501   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
12502   if (!MaskC)
12503     return SDValue();
12504   unsigned Mask = MaskC->getZExtValue();
12505   if (Mask == 0xffff)
12506     return SDValue();
12507   SDValue Res;
12508   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
12509   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12510   if (N1C) {
12511     unsigned Val = N1C->getZExtValue();
12512     if ((Val & ~Mask) != Val)
12513       return SDValue();
12514 
12515     if (ARM::isBitFieldInvertedMask(Mask)) {
12516       Val >>= countTrailingZeros(~Mask);
12517 
12518       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
12519                         DAG.getConstant(Val, DL, MVT::i32),
12520                         DAG.getConstant(Mask, DL, MVT::i32));
12521 
12522       DCI.CombineTo(N, Res, false);
12523       // Return value from the original node to inform the combiner than N is
12524       // now dead.
12525       return SDValue(N, 0);
12526     }
12527   } else if (N1.getOpcode() == ISD::AND) {
12528     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12529     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12530     if (!N11C)
12531       return SDValue();
12532     unsigned Mask2 = N11C->getZExtValue();
12533 
12534     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
12535     // as is to match.
12536     if (ARM::isBitFieldInvertedMask(Mask) &&
12537         (Mask == ~Mask2)) {
12538       // The pack halfword instruction works better for masks that fit it,
12539       // so use that when it's available.
12540       if (Subtarget->hasDSP() &&
12541           (Mask == 0xffff || Mask == 0xffff0000))
12542         return SDValue();
12543       // 2a
12544       unsigned amt = countTrailingZeros(Mask2);
12545       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
12546                         DAG.getConstant(amt, DL, MVT::i32));
12547       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
12548                         DAG.getConstant(Mask, DL, MVT::i32));
12549       DCI.CombineTo(N, Res, false);
12550       // Return value from the original node to inform the combiner than N is
12551       // now dead.
12552       return SDValue(N, 0);
12553     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
12554                (~Mask == Mask2)) {
12555       // The pack halfword instruction works better for masks that fit it,
12556       // so use that when it's available.
12557       if (Subtarget->hasDSP() &&
12558           (Mask2 == 0xffff || Mask2 == 0xffff0000))
12559         return SDValue();
12560       // 2b
12561       unsigned lsb = countTrailingZeros(Mask);
12562       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
12563                         DAG.getConstant(lsb, DL, MVT::i32));
12564       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
12565                         DAG.getConstant(Mask2, DL, MVT::i32));
12566       DCI.CombineTo(N, Res, false);
12567       // Return value from the original node to inform the combiner than N is
12568       // now dead.
12569       return SDValue(N, 0);
12570     }
12571   }
12572 
12573   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
12574       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
12575       ARM::isBitFieldInvertedMask(~Mask)) {
12576     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
12577     // where lsb(mask) == #shamt and masked bits of B are known zero.
12578     SDValue ShAmt = N00.getOperand(1);
12579     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
12580     unsigned LSB = countTrailingZeros(Mask);
12581     if (ShAmtC != LSB)
12582       return SDValue();
12583 
12584     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
12585                       DAG.getConstant(~Mask, DL, MVT::i32));
12586 
12587     DCI.CombineTo(N, Res, false);
12588     // Return value from the original node to inform the combiner than N is
12589     // now dead.
12590     return SDValue(N, 0);
12591   }
12592 
12593   return SDValue();
12594 }
12595 
12596 static bool isValidMVECond(unsigned CC, bool IsFloat) {
12597   switch (CC) {
12598   case ARMCC::EQ:
12599   case ARMCC::NE:
12600   case ARMCC::LE:
12601   case ARMCC::GT:
12602   case ARMCC::GE:
12603   case ARMCC::LT:
12604     return true;
12605   case ARMCC::HS:
12606   case ARMCC::HI:
12607     return !IsFloat;
12608   default:
12609     return false;
12610   };
12611 }
12612 
12613 static SDValue PerformORCombine_i1(SDNode *N,
12614                                    TargetLowering::DAGCombinerInfo &DCI,
12615                                    const ARMSubtarget *Subtarget) {
12616   // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
12617   // together with predicates
12618   EVT VT = N->getValueType(0);
12619   SDValue N0 = N->getOperand(0);
12620   SDValue N1 = N->getOperand(1);
12621 
12622   ARMCC::CondCodes CondCode0 = ARMCC::AL;
12623   ARMCC::CondCodes CondCode1 = ARMCC::AL;
12624   if (N0->getOpcode() == ARMISD::VCMP)
12625     CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2))
12626                     ->getZExtValue();
12627   else if (N0->getOpcode() == ARMISD::VCMPZ)
12628     CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1))
12629                     ->getZExtValue();
12630   if (N1->getOpcode() == ARMISD::VCMP)
12631     CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2))
12632                     ->getZExtValue();
12633   else if (N1->getOpcode() == ARMISD::VCMPZ)
12634     CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1))
12635                     ->getZExtValue();
12636 
12637   if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL)
12638     return SDValue();
12639 
12640   unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0);
12641   unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1);
12642 
12643   if (!isValidMVECond(Opposite0,
12644                       N0->getOperand(0)->getValueType(0).isFloatingPoint()) ||
12645       !isValidMVECond(Opposite1,
12646                       N1->getOperand(0)->getValueType(0).isFloatingPoint()))
12647     return SDValue();
12648 
12649   SmallVector<SDValue, 4> Ops0;
12650   Ops0.push_back(N0->getOperand(0));
12651   if (N0->getOpcode() == ARMISD::VCMP)
12652     Ops0.push_back(N0->getOperand(1));
12653   Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32));
12654   SmallVector<SDValue, 4> Ops1;
12655   Ops1.push_back(N1->getOperand(0));
12656   if (N1->getOpcode() == ARMISD::VCMP)
12657     Ops1.push_back(N1->getOperand(1));
12658   Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32));
12659 
12660   SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0);
12661   SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1);
12662   SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1);
12663   return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And,
12664                          DCI.DAG.getAllOnesConstant(SDLoc(N), VT));
12665 }
12666 
12667 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
12668 static SDValue PerformORCombine(SDNode *N,
12669                                 TargetLowering::DAGCombinerInfo &DCI,
12670                                 const ARMSubtarget *Subtarget) {
12671   // Attempt to use immediate-form VORR
12672   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12673   SDLoc dl(N);
12674   EVT VT = N->getValueType(0);
12675   SelectionDAG &DAG = DCI.DAG;
12676 
12677   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12678     return SDValue();
12679 
12680   APInt SplatBits, SplatUndef;
12681   unsigned SplatBitSize;
12682   bool HasAnyUndefs;
12683   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
12684       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12685     if (SplatBitSize <= 64) {
12686       EVT VorrVT;
12687       SDValue Val =
12688           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
12689                             SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
12690       if (Val.getNode()) {
12691         SDValue Input =
12692           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
12693         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
12694         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
12695       }
12696     }
12697   }
12698 
12699   if (!Subtarget->isThumb1Only()) {
12700     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12701     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12702       return Result;
12703     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
12704       return Result;
12705   }
12706 
12707   SDValue N0 = N->getOperand(0);
12708   SDValue N1 = N->getOperand(1);
12709 
12710   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
12711   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
12712       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12713 
12714     // The code below optimizes (or (and X, Y), Z).
12715     // The AND operand needs to have a single user to make these optimizations
12716     // profitable.
12717     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
12718       return SDValue();
12719 
12720     APInt SplatUndef;
12721     unsigned SplatBitSize;
12722     bool HasAnyUndefs;
12723 
12724     APInt SplatBits0, SplatBits1;
12725     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
12726     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
12727     // Ensure that the second operand of both ands are constants
12728     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
12729                                       HasAnyUndefs) && !HasAnyUndefs) {
12730         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
12731                                           HasAnyUndefs) && !HasAnyUndefs) {
12732             // Ensure that the bit width of the constants are the same and that
12733             // the splat arguments are logical inverses as per the pattern we
12734             // are trying to simplify.
12735             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
12736                 SplatBits0 == ~SplatBits1) {
12737                 // Canonicalize the vector type to make instruction selection
12738                 // simpler.
12739                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
12740                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
12741                                              N0->getOperand(1),
12742                                              N0->getOperand(0),
12743                                              N1->getOperand(0));
12744                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12745             }
12746         }
12747     }
12748   }
12749 
12750   if (Subtarget->hasMVEIntegerOps() &&
12751       (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
12752     return PerformORCombine_i1(N, DCI, Subtarget);
12753 
12754   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
12755   // reasonable.
12756   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
12757     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
12758       return Res;
12759   }
12760 
12761   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12762     return Result;
12763 
12764   return SDValue();
12765 }
12766 
12767 static SDValue PerformXORCombine(SDNode *N,
12768                                  TargetLowering::DAGCombinerInfo &DCI,
12769                                  const ARMSubtarget *Subtarget) {
12770   EVT VT = N->getValueType(0);
12771   SelectionDAG &DAG = DCI.DAG;
12772 
12773   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12774     return SDValue();
12775 
12776   if (!Subtarget->isThumb1Only()) {
12777     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12778     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12779       return Result;
12780 
12781     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12782       return Result;
12783   }
12784 
12785   return SDValue();
12786 }
12787 
12788 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12789 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12790 // their position in "to" (Rd).
12791 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12792   assert(N->getOpcode() == ARMISD::BFI);
12793 
12794   SDValue From = N->getOperand(1);
12795   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12796   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12797 
12798   // If the Base came from a SHR #C, we can deduce that it is really testing bit
12799   // #C in the base of the SHR.
12800   if (From->getOpcode() == ISD::SRL &&
12801       isa<ConstantSDNode>(From->getOperand(1))) {
12802     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12803     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12804     FromMask <<= Shift.getLimitedValue(31);
12805     From = From->getOperand(0);
12806   }
12807 
12808   return From;
12809 }
12810 
12811 // If A and B contain one contiguous set of bits, does A | B == A . B?
12812 //
12813 // Neither A nor B must be zero.
12814 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12815   unsigned LastActiveBitInA =  A.countTrailingZeros();
12816   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12817   return LastActiveBitInA - 1 == FirstActiveBitInB;
12818 }
12819 
12820 static SDValue FindBFIToCombineWith(SDNode *N) {
12821   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12822   // if one exists.
12823   APInt ToMask, FromMask;
12824   SDValue From = ParseBFI(N, ToMask, FromMask);
12825   SDValue To = N->getOperand(0);
12826 
12827   // Now check for a compatible BFI to merge with. We can pass through BFIs that
12828   // aren't compatible, but not if they set the same bit in their destination as
12829   // we do (or that of any BFI we're going to combine with).
12830   SDValue V = To;
12831   APInt CombinedToMask = ToMask;
12832   while (V.getOpcode() == ARMISD::BFI) {
12833     APInt NewToMask, NewFromMask;
12834     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12835     if (NewFrom != From) {
12836       // This BFI has a different base. Keep going.
12837       CombinedToMask |= NewToMask;
12838       V = V.getOperand(0);
12839       continue;
12840     }
12841 
12842     // Do the written bits conflict with any we've seen so far?
12843     if ((NewToMask & CombinedToMask).getBoolValue())
12844       // Conflicting bits - bail out because going further is unsafe.
12845       return SDValue();
12846 
12847     // Are the new bits contiguous when combined with the old bits?
12848     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12849         BitsProperlyConcatenate(FromMask, NewFromMask))
12850       return V;
12851     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12852         BitsProperlyConcatenate(NewFromMask, FromMask))
12853       return V;
12854 
12855     // We've seen a write to some bits, so track it.
12856     CombinedToMask |= NewToMask;
12857     // Keep going...
12858     V = V.getOperand(0);
12859   }
12860 
12861   return SDValue();
12862 }
12863 
12864 static SDValue PerformBFICombine(SDNode *N,
12865                                  TargetLowering::DAGCombinerInfo &DCI) {
12866   SDValue N1 = N->getOperand(1);
12867   if (N1.getOpcode() == ISD::AND) {
12868     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12869     // the bits being cleared by the AND are not demanded by the BFI.
12870     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12871     if (!N11C)
12872       return SDValue();
12873     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12874     unsigned LSB = countTrailingZeros(~InvMask);
12875     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12876     assert(Width <
12877                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12878            "undefined behavior");
12879     unsigned Mask = (1u << Width) - 1;
12880     unsigned Mask2 = N11C->getZExtValue();
12881     if ((Mask & (~Mask2)) == 0)
12882       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12883                              N->getOperand(0), N1.getOperand(0),
12884                              N->getOperand(2));
12885   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12886     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12887     // Keep track of any consecutive bits set that all come from the same base
12888     // value. We can combine these together into a single BFI.
12889     SDValue CombineBFI = FindBFIToCombineWith(N);
12890     if (CombineBFI == SDValue())
12891       return SDValue();
12892 
12893     // We've found a BFI.
12894     APInt ToMask1, FromMask1;
12895     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12896 
12897     APInt ToMask2, FromMask2;
12898     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12899     assert(From1 == From2);
12900     (void)From2;
12901 
12902     // First, unlink CombineBFI.
12903     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12904     // Then create a new BFI, combining the two together.
12905     APInt NewFromMask = FromMask1 | FromMask2;
12906     APInt NewToMask = ToMask1 | ToMask2;
12907 
12908     EVT VT = N->getValueType(0);
12909     SDLoc dl(N);
12910 
12911     if (NewFromMask[0] == 0)
12912       From1 = DCI.DAG.getNode(
12913         ISD::SRL, dl, VT, From1,
12914         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12915     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12916                            DCI.DAG.getConstant(~NewToMask, dl, VT));
12917   }
12918   return SDValue();
12919 }
12920 
12921 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12922 /// ARMISD::VMOVRRD.
12923 static SDValue PerformVMOVRRDCombine(SDNode *N,
12924                                      TargetLowering::DAGCombinerInfo &DCI,
12925                                      const ARMSubtarget *Subtarget) {
12926   // vmovrrd(vmovdrr x, y) -> x,y
12927   SDValue InDouble = N->getOperand(0);
12928   if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12929     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12930 
12931   // vmovrrd(load f64) -> (load i32), (load i32)
12932   SDNode *InNode = InDouble.getNode();
12933   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12934       InNode->getValueType(0) == MVT::f64 &&
12935       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12936       !cast<LoadSDNode>(InNode)->isVolatile()) {
12937     // TODO: Should this be done for non-FrameIndex operands?
12938     LoadSDNode *LD = cast<LoadSDNode>(InNode);
12939 
12940     SelectionDAG &DAG = DCI.DAG;
12941     SDLoc DL(LD);
12942     SDValue BasePtr = LD->getBasePtr();
12943     SDValue NewLD1 =
12944         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12945                     LD->getAlignment(), LD->getMemOperand()->getFlags());
12946 
12947     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12948                                     DAG.getConstant(4, DL, MVT::i32));
12949 
12950     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
12951                                  LD->getPointerInfo().getWithOffset(4),
12952                                  std::min(4U, LD->getAlignment()),
12953                                  LD->getMemOperand()->getFlags());
12954 
12955     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
12956     if (DCI.DAG.getDataLayout().isBigEndian())
12957       std::swap (NewLD1, NewLD2);
12958     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
12959     return Result;
12960   }
12961 
12962   return SDValue();
12963 }
12964 
12965 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
12966 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
12967 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
12968   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
12969   SDValue Op0 = N->getOperand(0);
12970   SDValue Op1 = N->getOperand(1);
12971   if (Op0.getOpcode() == ISD::BITCAST)
12972     Op0 = Op0.getOperand(0);
12973   if (Op1.getOpcode() == ISD::BITCAST)
12974     Op1 = Op1.getOperand(0);
12975   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
12976       Op0.getNode() == Op1.getNode() &&
12977       Op0.getResNo() == 0 && Op1.getResNo() == 1)
12978     return DAG.getNode(ISD::BITCAST, SDLoc(N),
12979                        N->getValueType(0), Op0.getOperand(0));
12980   return SDValue();
12981 }
12982 
12983 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12984   // FullFP16: half values are passed in S-registers, and we don't
12985   // need any of the bitcast and moves:
12986   //
12987   //     t2: f32,ch = CopyFromReg t0, Register:f32 %0
12988   //   t5: i32 = bitcast t2
12989   // t18: f16 = ARMISD::VMOVhr t5
12990   SDValue Op0 = N->getOperand(0);
12991   if (Op0->getOpcode() == ISD::BITCAST) {
12992     SDValue Copy = Op0->getOperand(0);
12993     if (Copy.getValueType() == MVT::f32 &&
12994         Copy->getOpcode() == ISD::CopyFromReg) {
12995       SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)};
12996       SDValue NewCopy =
12997           DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), MVT::f16, Ops);
12998       return NewCopy;
12999     }
13000   }
13001 
13002   // Only the bottom 16 bits of the source register are used.
13003   APInt DemandedMask = APInt::getLowBitsSet(32, 16);
13004   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
13005   if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
13006     return SDValue(N, 0);
13007 
13008   return SDValue();
13009 }
13010 
13011 static SDValue PerformVMOVrhCombine(SDNode *N,
13012                                     TargetLowering::DAGCombinerInfo &DCI) {
13013   SDValue N0 = N->getOperand(0);
13014   EVT VT = N->getValueType(0);
13015 
13016   // fold (VMOVrh (load x)) -> (zextload (i16*)x)
13017   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
13018     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
13019 
13020     SDValue Load =
13021         DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
13022                            LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
13023     DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13024     DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
13025     return Load;
13026   }
13027 
13028   return SDValue();
13029 }
13030 
13031 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
13032 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
13033 /// i64 vector to have f64 elements, since the value can then be loaded
13034 /// directly into a VFP register.
13035 static bool hasNormalLoadOperand(SDNode *N) {
13036   unsigned NumElts = N->getValueType(0).getVectorNumElements();
13037   for (unsigned i = 0; i < NumElts; ++i) {
13038     SDNode *Elt = N->getOperand(i).getNode();
13039     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
13040       return true;
13041   }
13042   return false;
13043 }
13044 
13045 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
13046 /// ISD::BUILD_VECTOR.
13047 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
13048                                           TargetLowering::DAGCombinerInfo &DCI,
13049                                           const ARMSubtarget *Subtarget) {
13050   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
13051   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
13052   // into a pair of GPRs, which is fine when the value is used as a scalar,
13053   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
13054   SelectionDAG &DAG = DCI.DAG;
13055   if (N->getNumOperands() == 2)
13056     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
13057       return RV;
13058 
13059   // Load i64 elements as f64 values so that type legalization does not split
13060   // them up into i32 values.
13061   EVT VT = N->getValueType(0);
13062   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
13063     return SDValue();
13064   SDLoc dl(N);
13065   SmallVector<SDValue, 8> Ops;
13066   unsigned NumElts = VT.getVectorNumElements();
13067   for (unsigned i = 0; i < NumElts; ++i) {
13068     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
13069     Ops.push_back(V);
13070     // Make the DAGCombiner fold the bitcast.
13071     DCI.AddToWorklist(V.getNode());
13072   }
13073   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
13074   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
13075   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
13076 }
13077 
13078 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
13079 static SDValue
13080 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13081   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
13082   // At that time, we may have inserted bitcasts from integer to float.
13083   // If these bitcasts have survived DAGCombine, change the lowering of this
13084   // BUILD_VECTOR in something more vector friendly, i.e., that does not
13085   // force to use floating point types.
13086 
13087   // Make sure we can change the type of the vector.
13088   // This is possible iff:
13089   // 1. The vector is only used in a bitcast to a integer type. I.e.,
13090   //    1.1. Vector is used only once.
13091   //    1.2. Use is a bit convert to an integer type.
13092   // 2. The size of its operands are 32-bits (64-bits are not legal).
13093   EVT VT = N->getValueType(0);
13094   EVT EltVT = VT.getVectorElementType();
13095 
13096   // Check 1.1. and 2.
13097   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
13098     return SDValue();
13099 
13100   // By construction, the input type must be float.
13101   assert(EltVT == MVT::f32 && "Unexpected type!");
13102 
13103   // Check 1.2.
13104   SDNode *Use = *N->use_begin();
13105   if (Use->getOpcode() != ISD::BITCAST ||
13106       Use->getValueType(0).isFloatingPoint())
13107     return SDValue();
13108 
13109   // Check profitability.
13110   // Model is, if more than half of the relevant operands are bitcast from
13111   // i32, turn the build_vector into a sequence of insert_vector_elt.
13112   // Relevant operands are everything that is not statically
13113   // (i.e., at compile time) bitcasted.
13114   unsigned NumOfBitCastedElts = 0;
13115   unsigned NumElts = VT.getVectorNumElements();
13116   unsigned NumOfRelevantElts = NumElts;
13117   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
13118     SDValue Elt = N->getOperand(Idx);
13119     if (Elt->getOpcode() == ISD::BITCAST) {
13120       // Assume only bit cast to i32 will go away.
13121       if (Elt->getOperand(0).getValueType() == MVT::i32)
13122         ++NumOfBitCastedElts;
13123     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
13124       // Constants are statically casted, thus do not count them as
13125       // relevant operands.
13126       --NumOfRelevantElts;
13127   }
13128 
13129   // Check if more than half of the elements require a non-free bitcast.
13130   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
13131     return SDValue();
13132 
13133   SelectionDAG &DAG = DCI.DAG;
13134   // Create the new vector type.
13135   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
13136   // Check if the type is legal.
13137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13138   if (!TLI.isTypeLegal(VecVT))
13139     return SDValue();
13140 
13141   // Combine:
13142   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
13143   // => BITCAST INSERT_VECTOR_ELT
13144   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
13145   //                      (BITCAST EN), N.
13146   SDValue Vec = DAG.getUNDEF(VecVT);
13147   SDLoc dl(N);
13148   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
13149     SDValue V = N->getOperand(Idx);
13150     if (V.isUndef())
13151       continue;
13152     if (V.getOpcode() == ISD::BITCAST &&
13153         V->getOperand(0).getValueType() == MVT::i32)
13154       // Fold obvious case.
13155       V = V.getOperand(0);
13156     else {
13157       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
13158       // Make the DAGCombiner fold the bitcasts.
13159       DCI.AddToWorklist(V.getNode());
13160     }
13161     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
13162     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
13163   }
13164   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
13165   // Make the DAGCombiner fold the bitcasts.
13166   DCI.AddToWorklist(Vec.getNode());
13167   return Vec;
13168 }
13169 
13170 static SDValue
13171 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13172   EVT VT = N->getValueType(0);
13173   SDValue Op = N->getOperand(0);
13174   SDLoc dl(N);
13175 
13176   // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
13177   if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
13178     // If the valuetypes are the same, we can remove the cast entirely.
13179     if (Op->getOperand(0).getValueType() == VT)
13180       return Op->getOperand(0);
13181     return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl,
13182                            Op->getOperand(0).getValueType(), Op->getOperand(0));
13183   }
13184 
13185   return SDValue();
13186 }
13187 
13188 static SDValue
13189 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13190                               const ARMSubtarget *ST) {
13191   EVT VT = N->getValueType(0);
13192   SDValue Op = N->getOperand(0);
13193   SDLoc dl(N);
13194 
13195   // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
13196   if (ST->isLittle())
13197     return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op);
13198 
13199   // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
13200   if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
13201     // If the valuetypes are the same, we can remove the cast entirely.
13202     if (Op->getOperand(0).getValueType() == VT)
13203       return Op->getOperand(0);
13204     return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
13205   }
13206 
13207   return SDValue();
13208 }
13209 
13210 static SDValue PerformVCMPCombine(SDNode *N,
13211                                   TargetLowering::DAGCombinerInfo &DCI,
13212                                   const ARMSubtarget *Subtarget) {
13213   if (!Subtarget->hasMVEIntegerOps())
13214     return SDValue();
13215 
13216   EVT VT = N->getValueType(0);
13217   SDValue Op0 = N->getOperand(0);
13218   SDValue Op1 = N->getOperand(1);
13219   ARMCC::CondCodes Cond =
13220       (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13221   SDLoc dl(N);
13222 
13223   // vcmp X, 0, cc -> vcmpz X, cc
13224   if (isZeroVector(Op1))
13225     return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0,
13226                            N->getOperand(2));
13227 
13228   unsigned SwappedCond = getSwappedCondition(Cond);
13229   if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
13230     // vcmp 0, X, cc -> vcmpz X, reversed(cc)
13231     if (isZeroVector(Op0))
13232       return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
13233                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13234     // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
13235     if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
13236       return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
13237                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13238   }
13239 
13240   return SDValue();
13241 }
13242 
13243 /// PerformInsertEltCombine - Target-specific dag combine xforms for
13244 /// ISD::INSERT_VECTOR_ELT.
13245 static SDValue PerformInsertEltCombine(SDNode *N,
13246                                        TargetLowering::DAGCombinerInfo &DCI) {
13247   // Bitcast an i64 load inserted into a vector to f64.
13248   // Otherwise, the i64 value will be legalized to a pair of i32 values.
13249   EVT VT = N->getValueType(0);
13250   SDNode *Elt = N->getOperand(1).getNode();
13251   if (VT.getVectorElementType() != MVT::i64 ||
13252       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
13253     return SDValue();
13254 
13255   SelectionDAG &DAG = DCI.DAG;
13256   SDLoc dl(N);
13257   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13258                                  VT.getVectorNumElements());
13259   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
13260   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
13261   // Make the DAGCombiner fold the bitcasts.
13262   DCI.AddToWorklist(Vec.getNode());
13263   DCI.AddToWorklist(V.getNode());
13264   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
13265                                Vec, V, N->getOperand(2));
13266   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
13267 }
13268 
13269 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
13270 /// ISD::VECTOR_SHUFFLE.
13271 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
13272   // The LLVM shufflevector instruction does not require the shuffle mask
13273   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
13274   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
13275   // operands do not match the mask length, they are extended by concatenating
13276   // them with undef vectors.  That is probably the right thing for other
13277   // targets, but for NEON it is better to concatenate two double-register
13278   // size vector operands into a single quad-register size vector.  Do that
13279   // transformation here:
13280   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
13281   //   shuffle(concat(v1, v2), undef)
13282   SDValue Op0 = N->getOperand(0);
13283   SDValue Op1 = N->getOperand(1);
13284   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
13285       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
13286       Op0.getNumOperands() != 2 ||
13287       Op1.getNumOperands() != 2)
13288     return SDValue();
13289   SDValue Concat0Op1 = Op0.getOperand(1);
13290   SDValue Concat1Op1 = Op1.getOperand(1);
13291   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
13292     return SDValue();
13293   // Skip the transformation if any of the types are illegal.
13294   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13295   EVT VT = N->getValueType(0);
13296   if (!TLI.isTypeLegal(VT) ||
13297       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
13298       !TLI.isTypeLegal(Concat1Op1.getValueType()))
13299     return SDValue();
13300 
13301   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13302                                   Op0.getOperand(0), Op1.getOperand(0));
13303   // Translate the shuffle mask.
13304   SmallVector<int, 16> NewMask;
13305   unsigned NumElts = VT.getVectorNumElements();
13306   unsigned HalfElts = NumElts/2;
13307   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13308   for (unsigned n = 0; n < NumElts; ++n) {
13309     int MaskElt = SVN->getMaskElt(n);
13310     int NewElt = -1;
13311     if (MaskElt < (int)HalfElts)
13312       NewElt = MaskElt;
13313     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
13314       NewElt = HalfElts + MaskElt - NumElts;
13315     NewMask.push_back(NewElt);
13316   }
13317   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
13318                               DAG.getUNDEF(VT), NewMask);
13319 }
13320 
13321 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
13322 /// NEON load/store intrinsics, and generic vector load/stores, to merge
13323 /// base address updates.
13324 /// For generic load/stores, the memory type is assumed to be a vector.
13325 /// The caller is assumed to have checked legality.
13326 static SDValue CombineBaseUpdate(SDNode *N,
13327                                  TargetLowering::DAGCombinerInfo &DCI) {
13328   SelectionDAG &DAG = DCI.DAG;
13329   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
13330                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
13331   const bool isStore = N->getOpcode() == ISD::STORE;
13332   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
13333   SDValue Addr = N->getOperand(AddrOpIdx);
13334   MemSDNode *MemN = cast<MemSDNode>(N);
13335   SDLoc dl(N);
13336 
13337   // Search for a use of the address operand that is an increment.
13338   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
13339          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
13340     SDNode *User = *UI;
13341     if (User->getOpcode() != ISD::ADD ||
13342         UI.getUse().getResNo() != Addr.getResNo())
13343       continue;
13344 
13345     // Check that the add is independent of the load/store.  Otherwise, folding
13346     // it would create a cycle. We can avoid searching through Addr as it's a
13347     // predecessor to both.
13348     SmallPtrSet<const SDNode *, 32> Visited;
13349     SmallVector<const SDNode *, 16> Worklist;
13350     Visited.insert(Addr.getNode());
13351     Worklist.push_back(N);
13352     Worklist.push_back(User);
13353     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
13354         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13355       continue;
13356 
13357     // Find the new opcode for the updating load/store.
13358     bool isLoadOp = true;
13359     bool isLaneOp = false;
13360     unsigned NewOpc = 0;
13361     unsigned NumVecs = 0;
13362     if (isIntrinsic) {
13363       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
13364       switch (IntNo) {
13365       default: llvm_unreachable("unexpected intrinsic for Neon base update");
13366       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
13367         NumVecs = 1; break;
13368       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
13369         NumVecs = 2; break;
13370       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
13371         NumVecs = 3; break;
13372       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
13373         NumVecs = 4; break;
13374       case Intrinsic::arm_neon_vld2dup:
13375       case Intrinsic::arm_neon_vld3dup:
13376       case Intrinsic::arm_neon_vld4dup:
13377         // TODO: Support updating VLDxDUP nodes. For now, we just skip
13378         // combining base updates for such intrinsics.
13379         continue;
13380       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
13381         NumVecs = 2; isLaneOp = true; break;
13382       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
13383         NumVecs = 3; isLaneOp = true; break;
13384       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
13385         NumVecs = 4; isLaneOp = true; break;
13386       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
13387         NumVecs = 1; isLoadOp = false; break;
13388       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
13389         NumVecs = 2; isLoadOp = false; break;
13390       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
13391         NumVecs = 3; isLoadOp = false; break;
13392       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
13393         NumVecs = 4; isLoadOp = false; break;
13394       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
13395         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
13396       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
13397         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
13398       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
13399         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
13400       }
13401     } else {
13402       isLaneOp = true;
13403       switch (N->getOpcode()) {
13404       default: llvm_unreachable("unexpected opcode for Neon base update");
13405       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
13406       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
13407       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
13408       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
13409       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
13410         NumVecs = 1; isLaneOp = false; break;
13411       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
13412         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
13413       }
13414     }
13415 
13416     // Find the size of memory referenced by the load/store.
13417     EVT VecTy;
13418     if (isLoadOp) {
13419       VecTy = N->getValueType(0);
13420     } else if (isIntrinsic) {
13421       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
13422     } else {
13423       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
13424       VecTy = N->getOperand(1).getValueType();
13425     }
13426 
13427     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
13428     if (isLaneOp)
13429       NumBytes /= VecTy.getVectorNumElements();
13430 
13431     // If the increment is a constant, it must match the memory ref size.
13432     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13433     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
13434     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
13435       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
13436       // separate instructions that make it harder to use a non-constant update.
13437       continue;
13438     }
13439 
13440     // OK, we found an ADD we can fold into the base update.
13441     // Now, create a _UPD node, taking care of not breaking alignment.
13442 
13443     EVT AlignedVecTy = VecTy;
13444     unsigned Alignment = MemN->getAlignment();
13445 
13446     // If this is a less-than-standard-aligned load/store, change the type to
13447     // match the standard alignment.
13448     // The alignment is overlooked when selecting _UPD variants; and it's
13449     // easier to introduce bitcasts here than fix that.
13450     // There are 3 ways to get to this base-update combine:
13451     // - intrinsics: they are assumed to be properly aligned (to the standard
13452     //   alignment of the memory type), so we don't need to do anything.
13453     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
13454     //   intrinsics, so, likewise, there's nothing to do.
13455     // - generic load/store instructions: the alignment is specified as an
13456     //   explicit operand, rather than implicitly as the standard alignment
13457     //   of the memory type (like the intrisics).  We need to change the
13458     //   memory type to match the explicit alignment.  That way, we don't
13459     //   generate non-standard-aligned ARMISD::VLDx nodes.
13460     if (isa<LSBaseSDNode>(N)) {
13461       if (Alignment == 0)
13462         Alignment = 1;
13463       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
13464         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
13465         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
13466         assert(!isLaneOp && "Unexpected generic load/store lane.");
13467         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
13468         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
13469       }
13470       // Don't set an explicit alignment on regular load/stores that we want
13471       // to transform to VLD/VST 1_UPD nodes.
13472       // This matches the behavior of regular load/stores, which only get an
13473       // explicit alignment if the MMO alignment is larger than the standard
13474       // alignment of the memory type.
13475       // Intrinsics, however, always get an explicit alignment, set to the
13476       // alignment of the MMO.
13477       Alignment = 1;
13478     }
13479 
13480     // Create the new updating load/store node.
13481     // First, create an SDVTList for the new updating node's results.
13482     EVT Tys[6];
13483     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
13484     unsigned n;
13485     for (n = 0; n < NumResultVecs; ++n)
13486       Tys[n] = AlignedVecTy;
13487     Tys[n++] = MVT::i32;
13488     Tys[n] = MVT::Other;
13489     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
13490 
13491     // Then, gather the new node's operands.
13492     SmallVector<SDValue, 8> Ops;
13493     Ops.push_back(N->getOperand(0)); // incoming chain
13494     Ops.push_back(N->getOperand(AddrOpIdx));
13495     Ops.push_back(Inc);
13496 
13497     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
13498       // Try to match the intrinsic's signature
13499       Ops.push_back(StN->getValue());
13500     } else {
13501       // Loads (and of course intrinsics) match the intrinsics' signature,
13502       // so just add all but the alignment operand.
13503       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
13504         Ops.push_back(N->getOperand(i));
13505     }
13506 
13507     // For all node types, the alignment operand is always the last one.
13508     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
13509 
13510     // If this is a non-standard-aligned STORE, the penultimate operand is the
13511     // stored value.  Bitcast it to the aligned type.
13512     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
13513       SDValue &StVal = Ops[Ops.size()-2];
13514       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
13515     }
13516 
13517     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
13518     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
13519                                            MemN->getMemOperand());
13520 
13521     // Update the uses.
13522     SmallVector<SDValue, 5> NewResults;
13523     for (unsigned i = 0; i < NumResultVecs; ++i)
13524       NewResults.push_back(SDValue(UpdN.getNode(), i));
13525 
13526     // If this is an non-standard-aligned LOAD, the first result is the loaded
13527     // value.  Bitcast it to the expected result type.
13528     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
13529       SDValue &LdVal = NewResults[0];
13530       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
13531     }
13532 
13533     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
13534     DCI.CombineTo(N, NewResults);
13535     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13536 
13537     break;
13538   }
13539   return SDValue();
13540 }
13541 
13542 static SDValue PerformVLDCombine(SDNode *N,
13543                                  TargetLowering::DAGCombinerInfo &DCI) {
13544   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13545     return SDValue();
13546 
13547   return CombineBaseUpdate(N, DCI);
13548 }
13549 
13550 static SDValue PerformMVEVLDCombine(SDNode *N,
13551                                     TargetLowering::DAGCombinerInfo &DCI) {
13552   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13553     return SDValue();
13554 
13555   SelectionDAG &DAG = DCI.DAG;
13556   SDValue Addr = N->getOperand(2);
13557   MemSDNode *MemN = cast<MemSDNode>(N);
13558   SDLoc dl(N);
13559 
13560   // For the stores, where there are multiple intrinsics we only actually want
13561   // to post-inc the last of the them.
13562   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
13563   if (IntNo == Intrinsic::arm_mve_vst2q &&
13564       cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1)
13565     return SDValue();
13566   if (IntNo == Intrinsic::arm_mve_vst4q &&
13567       cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3)
13568     return SDValue();
13569 
13570   // Search for a use of the address operand that is an increment.
13571   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
13572                             UE = Addr.getNode()->use_end();
13573        UI != UE; ++UI) {
13574     SDNode *User = *UI;
13575     if (User->getOpcode() != ISD::ADD ||
13576         UI.getUse().getResNo() != Addr.getResNo())
13577       continue;
13578 
13579     // Check that the add is independent of the load/store.  Otherwise, folding
13580     // it would create a cycle. We can avoid searching through Addr as it's a
13581     // predecessor to both.
13582     SmallPtrSet<const SDNode *, 32> Visited;
13583     SmallVector<const SDNode *, 16> Worklist;
13584     Visited.insert(Addr.getNode());
13585     Worklist.push_back(N);
13586     Worklist.push_back(User);
13587     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
13588         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13589       continue;
13590 
13591     // Find the new opcode for the updating load/store.
13592     bool isLoadOp = true;
13593     unsigned NewOpc = 0;
13594     unsigned NumVecs = 0;
13595     switch (IntNo) {
13596     default:
13597       llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
13598     case Intrinsic::arm_mve_vld2q:
13599       NewOpc = ARMISD::VLD2_UPD;
13600       NumVecs = 2;
13601       break;
13602     case Intrinsic::arm_mve_vld4q:
13603       NewOpc = ARMISD::VLD4_UPD;
13604       NumVecs = 4;
13605       break;
13606     case Intrinsic::arm_mve_vst2q:
13607       NewOpc = ARMISD::VST2_UPD;
13608       NumVecs = 2;
13609       isLoadOp = false;
13610       break;
13611     case Intrinsic::arm_mve_vst4q:
13612       NewOpc = ARMISD::VST4_UPD;
13613       NumVecs = 4;
13614       isLoadOp = false;
13615       break;
13616     }
13617 
13618     // Find the size of memory referenced by the load/store.
13619     EVT VecTy;
13620     if (isLoadOp) {
13621       VecTy = N->getValueType(0);
13622     } else {
13623       VecTy = N->getOperand(3).getValueType();
13624     }
13625 
13626     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
13627 
13628     // If the increment is a constant, it must match the memory ref size.
13629     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13630     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
13631     if (!CInc || CInc->getZExtValue() != NumBytes)
13632       continue;
13633 
13634     // Create the new updating load/store node.
13635     // First, create an SDVTList for the new updating node's results.
13636     EVT Tys[6];
13637     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
13638     unsigned n;
13639     for (n = 0; n < NumResultVecs; ++n)
13640       Tys[n] = VecTy;
13641     Tys[n++] = MVT::i32;
13642     Tys[n] = MVT::Other;
13643     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
13644 
13645     // Then, gather the new node's operands.
13646     SmallVector<SDValue, 8> Ops;
13647     Ops.push_back(N->getOperand(0)); // incoming chain
13648     Ops.push_back(N->getOperand(2)); // ptr
13649     Ops.push_back(Inc);
13650 
13651     for (unsigned i = 3; i < N->getNumOperands(); ++i)
13652       Ops.push_back(N->getOperand(i));
13653 
13654     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
13655                                            MemN->getMemOperand());
13656 
13657     // Update the uses.
13658     SmallVector<SDValue, 5> NewResults;
13659     for (unsigned i = 0; i < NumResultVecs; ++i)
13660       NewResults.push_back(SDValue(UpdN.getNode(), i));
13661 
13662     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
13663     DCI.CombineTo(N, NewResults);
13664     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13665 
13666     break;
13667   }
13668 
13669   return SDValue();
13670 }
13671 
13672 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
13673 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
13674 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
13675 /// return true.
13676 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13677   SelectionDAG &DAG = DCI.DAG;
13678   EVT VT = N->getValueType(0);
13679   // vldN-dup instructions only support 64-bit vectors for N > 1.
13680   if (!VT.is64BitVector())
13681     return false;
13682 
13683   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
13684   SDNode *VLD = N->getOperand(0).getNode();
13685   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
13686     return false;
13687   unsigned NumVecs = 0;
13688   unsigned NewOpc = 0;
13689   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
13690   if (IntNo == Intrinsic::arm_neon_vld2lane) {
13691     NumVecs = 2;
13692     NewOpc = ARMISD::VLD2DUP;
13693   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
13694     NumVecs = 3;
13695     NewOpc = ARMISD::VLD3DUP;
13696   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
13697     NumVecs = 4;
13698     NewOpc = ARMISD::VLD4DUP;
13699   } else {
13700     return false;
13701   }
13702 
13703   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
13704   // numbers match the load.
13705   unsigned VLDLaneNo =
13706     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
13707   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13708        UI != UE; ++UI) {
13709     // Ignore uses of the chain result.
13710     if (UI.getUse().getResNo() == NumVecs)
13711       continue;
13712     SDNode *User = *UI;
13713     if (User->getOpcode() != ARMISD::VDUPLANE ||
13714         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
13715       return false;
13716   }
13717 
13718   // Create the vldN-dup node.
13719   EVT Tys[5];
13720   unsigned n;
13721   for (n = 0; n < NumVecs; ++n)
13722     Tys[n] = VT;
13723   Tys[n] = MVT::Other;
13724   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
13725   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
13726   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
13727   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
13728                                            Ops, VLDMemInt->getMemoryVT(),
13729                                            VLDMemInt->getMemOperand());
13730 
13731   // Update the uses.
13732   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13733        UI != UE; ++UI) {
13734     unsigned ResNo = UI.getUse().getResNo();
13735     // Ignore uses of the chain result.
13736     if (ResNo == NumVecs)
13737       continue;
13738     SDNode *User = *UI;
13739     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
13740   }
13741 
13742   // Now the vldN-lane intrinsic is dead except for its chain result.
13743   // Update uses of the chain.
13744   std::vector<SDValue> VLDDupResults;
13745   for (unsigned n = 0; n < NumVecs; ++n)
13746     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
13747   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
13748   DCI.CombineTo(VLD, VLDDupResults);
13749 
13750   return true;
13751 }
13752 
13753 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
13754 /// ARMISD::VDUPLANE.
13755 static SDValue PerformVDUPLANECombine(SDNode *N,
13756                                       TargetLowering::DAGCombinerInfo &DCI) {
13757   SDValue Op = N->getOperand(0);
13758 
13759   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
13760   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
13761   if (CombineVLDDUP(N, DCI))
13762     return SDValue(N, 0);
13763 
13764   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
13765   // redundant.  Ignore bit_converts for now; element sizes are checked below.
13766   while (Op.getOpcode() == ISD::BITCAST)
13767     Op = Op.getOperand(0);
13768   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
13769     return SDValue();
13770 
13771   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
13772   unsigned EltSize = Op.getScalarValueSizeInBits();
13773   // The canonical VMOV for a zero vector uses a 32-bit element size.
13774   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13775   unsigned EltBits;
13776   if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
13777     EltSize = 8;
13778   EVT VT = N->getValueType(0);
13779   if (EltSize > VT.getScalarSizeInBits())
13780     return SDValue();
13781 
13782   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
13783 }
13784 
13785 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
13786 static SDValue PerformVDUPCombine(SDNode *N,
13787                                   TargetLowering::DAGCombinerInfo &DCI,
13788                                   const ARMSubtarget *Subtarget) {
13789   SelectionDAG &DAG = DCI.DAG;
13790   SDValue Op = N->getOperand(0);
13791   SDLoc dl(N);
13792 
13793   if (Subtarget->hasMVEIntegerOps()) {
13794     // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
13795     // need to come from a GPR.
13796     if (Op.getValueType() == MVT::f32)
13797       return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
13798                              DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
13799     else if (Op.getValueType() == MVT::f16)
13800       return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
13801                              DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
13802   }
13803 
13804   if (!Subtarget->hasNEON())
13805     return SDValue();
13806 
13807   // Match VDUP(LOAD) -> VLD1DUP.
13808   // We match this pattern here rather than waiting for isel because the
13809   // transform is only legal for unindexed loads.
13810   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
13811   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
13812       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
13813     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
13814                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
13815     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
13816     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
13817                                              Ops, LD->getMemoryVT(),
13818                                              LD->getMemOperand());
13819     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
13820     return VLDDup;
13821   }
13822 
13823   return SDValue();
13824 }
13825 
13826 static SDValue PerformLOADCombine(SDNode *N,
13827                                   TargetLowering::DAGCombinerInfo &DCI) {
13828   EVT VT = N->getValueType(0);
13829 
13830   // If this is a legal vector load, try to combine it into a VLD1_UPD.
13831   if (ISD::isNormalLoad(N) && VT.isVector() &&
13832       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13833     return CombineBaseUpdate(N, DCI);
13834 
13835   return SDValue();
13836 }
13837 
13838 // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
13839 // pack all of the elements in one place.  Next, store to memory in fewer
13840 // chunks.
13841 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
13842                                              SelectionDAG &DAG) {
13843   SDValue StVal = St->getValue();
13844   EVT VT = StVal.getValueType();
13845   if (!St->isTruncatingStore() || !VT.isVector())
13846     return SDValue();
13847   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13848   EVT StVT = St->getMemoryVT();
13849   unsigned NumElems = VT.getVectorNumElements();
13850   assert(StVT != VT && "Cannot truncate to the same type");
13851   unsigned FromEltSz = VT.getScalarSizeInBits();
13852   unsigned ToEltSz = StVT.getScalarSizeInBits();
13853 
13854   // From, To sizes and ElemCount must be pow of two
13855   if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
13856     return SDValue();
13857 
13858   // We are going to use the original vector elt for storing.
13859   // Accumulated smaller vector elements must be a multiple of the store size.
13860   if (0 != (NumElems * FromEltSz) % ToEltSz)
13861     return SDValue();
13862 
13863   unsigned SizeRatio = FromEltSz / ToEltSz;
13864   assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
13865 
13866   // Create a type on which we perform the shuffle.
13867   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
13868                                    NumElems * SizeRatio);
13869   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13870 
13871   SDLoc DL(St);
13872   SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
13873   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13874   for (unsigned i = 0; i < NumElems; ++i)
13875     ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
13876                                                       : i * SizeRatio;
13877 
13878   // Can't shuffle using an illegal type.
13879   if (!TLI.isTypeLegal(WideVecVT))
13880     return SDValue();
13881 
13882   SDValue Shuff = DAG.getVectorShuffle(
13883       WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
13884   // At this point all of the data is stored at the bottom of the
13885   // register. We now need to save it to mem.
13886 
13887   // Find the largest store unit
13888   MVT StoreType = MVT::i8;
13889   for (MVT Tp : MVT::integer_valuetypes()) {
13890     if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
13891       StoreType = Tp;
13892   }
13893   // Didn't find a legal store type.
13894   if (!TLI.isTypeLegal(StoreType))
13895     return SDValue();
13896 
13897   // Bitcast the original vector into a vector of store-size units
13898   EVT StoreVecVT =
13899       EVT::getVectorVT(*DAG.getContext(), StoreType,
13900                        VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
13901   assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13902   SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
13903   SmallVector<SDValue, 8> Chains;
13904   SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
13905                                       TLI.getPointerTy(DAG.getDataLayout()));
13906   SDValue BasePtr = St->getBasePtr();
13907 
13908   // Perform one or more big stores into memory.
13909   unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
13910   for (unsigned I = 0; I < E; I++) {
13911     SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
13912                                  ShuffWide, DAG.getIntPtrConstant(I, DL));
13913     SDValue Ch =
13914         DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
13915                      St->getAlignment(), St->getMemOperand()->getFlags());
13916     BasePtr =
13917         DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
13918     Chains.push_back(Ch);
13919   }
13920   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
13921 }
13922 
13923 // Try taking a single vector store from an truncate (which would otherwise turn
13924 // into an expensive buildvector) and splitting it into a series of narrowing
13925 // stores.
13926 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
13927                                                  SelectionDAG &DAG) {
13928   if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
13929     return SDValue();
13930   SDValue Trunc = St->getValue();
13931   if (Trunc->getOpcode() != ISD::TRUNCATE)
13932     return SDValue();
13933   EVT FromVT = Trunc->getOperand(0).getValueType();
13934   EVT ToVT = Trunc.getValueType();
13935   if (!ToVT.isVector())
13936     return SDValue();
13937   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
13938   EVT ToEltVT = ToVT.getVectorElementType();
13939   EVT FromEltVT = FromVT.getVectorElementType();
13940 
13941   unsigned NumElements = 0;
13942   if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8))
13943     NumElements = 4;
13944   if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8)
13945     NumElements = 8;
13946   if (NumElements == 0 || FromVT.getVectorNumElements() == NumElements ||
13947       FromVT.getVectorNumElements() % NumElements != 0)
13948     return SDValue();
13949 
13950   // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so
13951   // use the VMOVN over splitting the store. We are looking for patterns of:
13952   // !rev: 0 N 1 N+1 2 N+2 ...
13953   //  rev: N 0 N+1 1 N+2 2 ...
13954   auto isVMOVNOriginalMask = [&](ArrayRef<int> M, bool rev) {
13955     unsigned NumElts = ToVT.getVectorNumElements();
13956     if (NumElts != M.size() || (ToVT != MVT::v8i16 && ToVT != MVT::v16i8))
13957       return false;
13958 
13959     unsigned Off0 = rev ? NumElts : 0;
13960     unsigned Off1 = rev ? 0 : NumElts;
13961 
13962     for (unsigned i = 0; i < NumElts; i += 2) {
13963       if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
13964         return false;
13965       if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
13966         return false;
13967     }
13968 
13969     return true;
13970   };
13971 
13972   if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc->getOperand(0)))
13973     if (isVMOVNOriginalMask(Shuffle->getMask(), false) ||
13974         isVMOVNOriginalMask(Shuffle->getMask(), true))
13975       return SDValue();
13976 
13977   SDLoc DL(St);
13978   // Details about the old store
13979   SDValue Ch = St->getChain();
13980   SDValue BasePtr = St->getBasePtr();
13981   Align Alignment = St->getOriginalAlign();
13982   MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
13983   AAMDNodes AAInfo = St->getAAInfo();
13984 
13985   EVT NewFromVT = EVT::getVectorVT(*DAG.getContext(), FromEltVT, NumElements);
13986   EVT NewToVT = EVT::getVectorVT(*DAG.getContext(), ToEltVT, NumElements);
13987 
13988   SmallVector<SDValue, 4> Stores;
13989   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
13990     unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
13991     SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
13992 
13993     SDValue Extract =
13994         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
13995                     DAG.getConstant(i * NumElements, DL, MVT::i32));
13996     SDValue Store = DAG.getTruncStore(
13997         Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
13998         NewToVT, Alignment.value(), MMOFlags, AAInfo);
13999     Stores.push_back(Store);
14000   }
14001   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
14002 }
14003 
14004 /// PerformSTORECombine - Target-specific dag combine xforms for
14005 /// ISD::STORE.
14006 static SDValue PerformSTORECombine(SDNode *N,
14007                                    TargetLowering::DAGCombinerInfo &DCI,
14008                                    const ARMSubtarget *Subtarget) {
14009   StoreSDNode *St = cast<StoreSDNode>(N);
14010   if (St->isVolatile())
14011     return SDValue();
14012   SDValue StVal = St->getValue();
14013   EVT VT = StVal.getValueType();
14014 
14015   if (Subtarget->hasNEON())
14016     if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
14017       return Store;
14018 
14019   if (Subtarget->hasMVEIntegerOps())
14020     if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
14021       return NewToken;
14022 
14023   if (!ISD::isNormalStore(St))
14024     return SDValue();
14025 
14026   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
14027   // ARM stores of arguments in the same cache line.
14028   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
14029       StVal.getNode()->hasOneUse()) {
14030     SelectionDAG  &DAG = DCI.DAG;
14031     bool isBigEndian = DAG.getDataLayout().isBigEndian();
14032     SDLoc DL(St);
14033     SDValue BasePtr = St->getBasePtr();
14034     SDValue NewST1 = DAG.getStore(
14035         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
14036         BasePtr, St->getPointerInfo(), St->getAlignment(),
14037         St->getMemOperand()->getFlags());
14038 
14039     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
14040                                     DAG.getConstant(4, DL, MVT::i32));
14041     return DAG.getStore(NewST1.getValue(0), DL,
14042                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
14043                         OffsetPtr, St->getPointerInfo(),
14044                         std::min(4U, St->getAlignment() / 2),
14045                         St->getMemOperand()->getFlags());
14046   }
14047 
14048   if (StVal.getValueType() == MVT::i64 &&
14049       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14050 
14051     // Bitcast an i64 store extracted from a vector to f64.
14052     // Otherwise, the i64 value will be legalized to a pair of i32 values.
14053     SelectionDAG &DAG = DCI.DAG;
14054     SDLoc dl(StVal);
14055     SDValue IntVec = StVal.getOperand(0);
14056     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
14057                                    IntVec.getValueType().getVectorNumElements());
14058     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
14059     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
14060                                  Vec, StVal.getOperand(1));
14061     dl = SDLoc(N);
14062     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
14063     // Make the DAGCombiner fold the bitcasts.
14064     DCI.AddToWorklist(Vec.getNode());
14065     DCI.AddToWorklist(ExtElt.getNode());
14066     DCI.AddToWorklist(V.getNode());
14067     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
14068                         St->getPointerInfo(), St->getAlignment(),
14069                         St->getMemOperand()->getFlags(), St->getAAInfo());
14070   }
14071 
14072   // If this is a legal vector store, try to combine it into a VST1_UPD.
14073   if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
14074       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
14075     return CombineBaseUpdate(N, DCI);
14076 
14077   return SDValue();
14078 }
14079 
14080 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
14081 /// can replace combinations of VMUL and VCVT (floating-point to integer)
14082 /// when the VMUL has a constant operand that is a power of 2.
14083 ///
14084 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14085 ///  vmul.f32        d16, d17, d16
14086 ///  vcvt.s32.f32    d16, d16
14087 /// becomes:
14088 ///  vcvt.s32.f32    d16, d16, #3
14089 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
14090                                   const ARMSubtarget *Subtarget) {
14091   if (!Subtarget->hasNEON())
14092     return SDValue();
14093 
14094   SDValue Op = N->getOperand(0);
14095   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
14096       Op.getOpcode() != ISD::FMUL)
14097     return SDValue();
14098 
14099   SDValue ConstVec = Op->getOperand(1);
14100   if (!isa<BuildVectorSDNode>(ConstVec))
14101     return SDValue();
14102 
14103   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
14104   uint32_t FloatBits = FloatTy.getSizeInBits();
14105   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
14106   uint32_t IntBits = IntTy.getSizeInBits();
14107   unsigned NumLanes = Op.getValueType().getVectorNumElements();
14108   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14109     // These instructions only exist converting from f32 to i32. We can handle
14110     // smaller integers by generating an extra truncate, but larger ones would
14111     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14112     // these intructions only support v2i32/v4i32 types.
14113     return SDValue();
14114   }
14115 
14116   BitVector UndefElements;
14117   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14118   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14119   if (C == -1 || C == 0 || C > 32)
14120     return SDValue();
14121 
14122   SDLoc dl(N);
14123   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
14124   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
14125     Intrinsic::arm_neon_vcvtfp2fxu;
14126   SDValue FixConv = DAG.getNode(
14127       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14128       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
14129       DAG.getConstant(C, dl, MVT::i32));
14130 
14131   if (IntBits < FloatBits)
14132     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
14133 
14134   return FixConv;
14135 }
14136 
14137 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
14138 /// can replace combinations of VCVT (integer to floating-point) and VDIV
14139 /// when the VDIV has a constant operand that is a power of 2.
14140 ///
14141 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14142 ///  vcvt.f32.s32    d16, d16
14143 ///  vdiv.f32        d16, d17, d16
14144 /// becomes:
14145 ///  vcvt.f32.s32    d16, d16, #3
14146 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
14147                                   const ARMSubtarget *Subtarget) {
14148   if (!Subtarget->hasNEON())
14149     return SDValue();
14150 
14151   SDValue Op = N->getOperand(0);
14152   unsigned OpOpcode = Op.getNode()->getOpcode();
14153   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
14154       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
14155     return SDValue();
14156 
14157   SDValue ConstVec = N->getOperand(1);
14158   if (!isa<BuildVectorSDNode>(ConstVec))
14159     return SDValue();
14160 
14161   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
14162   uint32_t FloatBits = FloatTy.getSizeInBits();
14163   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
14164   uint32_t IntBits = IntTy.getSizeInBits();
14165   unsigned NumLanes = Op.getValueType().getVectorNumElements();
14166   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14167     // These instructions only exist converting from i32 to f32. We can handle
14168     // smaller integers by generating an extra extend, but larger ones would
14169     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14170     // these intructions only support v2i32/v4i32 types.
14171     return SDValue();
14172   }
14173 
14174   BitVector UndefElements;
14175   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14176   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14177   if (C == -1 || C == 0 || C > 32)
14178     return SDValue();
14179 
14180   SDLoc dl(N);
14181   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
14182   SDValue ConvInput = Op.getOperand(0);
14183   if (IntBits < FloatBits)
14184     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
14185                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14186                             ConvInput);
14187 
14188   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
14189     Intrinsic::arm_neon_vcvtfxu2fp;
14190   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
14191                      Op.getValueType(),
14192                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
14193                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
14194 }
14195 
14196 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
14197                                            const ARMSubtarget *ST) {
14198   if (!ST->hasMVEIntegerOps())
14199     return SDValue();
14200 
14201   assert(N->getOpcode() == ISD::VECREDUCE_ADD);
14202   EVT ResVT = N->getValueType(0);
14203   SDValue N0 = N->getOperand(0);
14204   SDLoc dl(N);
14205 
14206   // We are looking for something that will have illegal types if left alone,
14207   // but that we can convert to a single instruction undef MVE. For example
14208   // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
14209   // or
14210   // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
14211 
14212   // Cases:
14213   //   VADDV u/s 8/16/32
14214   //   VMLAV u/s 8/16/32
14215   //   VADDLV u/s 32
14216   //   VMLALV u/s 16/32
14217 
14218   auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
14219     if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
14220       return SDValue();
14221     SDValue A = N0->getOperand(0);
14222     if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14223       return A;
14224     return SDValue();
14225   };
14226   auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
14227                      SDValue &A, SDValue &B) {
14228     if (ResVT != RetTy || N0->getOpcode() != ISD::MUL)
14229       return false;
14230     SDValue ExtA = N0->getOperand(0);
14231     SDValue ExtB = N0->getOperand(1);
14232     if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode)
14233       return false;
14234     A = ExtA->getOperand(0);
14235     B = ExtB->getOperand(0);
14236     if (A.getValueType() == B.getValueType() &&
14237         llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14238       return true;
14239     return false;
14240   };
14241   auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
14242     SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
14243     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
14244                        SDValue(Node.getNode(), 1));
14245   };
14246 
14247   if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
14248     return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
14249   if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
14250     return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
14251   if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
14252     return Create64bitNode(ARMISD::VADDLVs, {A});
14253   if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
14254     return Create64bitNode(ARMISD::VADDLVu, {A});
14255 
14256   SDValue A, B;
14257   if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
14258     return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
14259   if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
14260     return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
14261   if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B))
14262     return Create64bitNode(ARMISD::VMLALVs, {A, B});
14263   if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B))
14264     return Create64bitNode(ARMISD::VMLALVu, {A, B});
14265   return SDValue();
14266 }
14267 
14268 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
14269   SDLoc DL(N);
14270   SDValue Op0 = N->getOperand(0);
14271   SDValue Op1 = N->getOperand(1);
14272 
14273   // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
14274   // uses of the intrinsics.
14275   if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
14276     int ShiftAmt = C->getSExtValue();
14277     if (ShiftAmt == 0) {
14278       SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
14279       DAG.ReplaceAllUsesWith(N, Merge.getNode());
14280       return SDValue();
14281     }
14282 
14283     if (ShiftAmt >= -32 && ShiftAmt < 0) {
14284       unsigned NewOpcode =
14285           N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
14286       SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
14287                                      DAG.getConstant(-ShiftAmt, DL, MVT::i32));
14288       DAG.ReplaceAllUsesWith(N, NewShift.getNode());
14289       return NewShift;
14290     }
14291   }
14292 
14293   return SDValue();
14294 }
14295 
14296 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
14297 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
14298                                                    DAGCombinerInfo &DCI) const {
14299   SelectionDAG &DAG = DCI.DAG;
14300   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14301   switch (IntNo) {
14302   default:
14303     // Don't do anything for most intrinsics.
14304     break;
14305 
14306   // Vector shifts: check for immediate versions and lower them.
14307   // Note: This is done during DAG combining instead of DAG legalizing because
14308   // the build_vectors for 64-bit vector element shift counts are generally
14309   // not legal, and it is hard to see their values after they get legalized to
14310   // loads from a constant pool.
14311   case Intrinsic::arm_neon_vshifts:
14312   case Intrinsic::arm_neon_vshiftu:
14313   case Intrinsic::arm_neon_vrshifts:
14314   case Intrinsic::arm_neon_vrshiftu:
14315   case Intrinsic::arm_neon_vrshiftn:
14316   case Intrinsic::arm_neon_vqshifts:
14317   case Intrinsic::arm_neon_vqshiftu:
14318   case Intrinsic::arm_neon_vqshiftsu:
14319   case Intrinsic::arm_neon_vqshiftns:
14320   case Intrinsic::arm_neon_vqshiftnu:
14321   case Intrinsic::arm_neon_vqshiftnsu:
14322   case Intrinsic::arm_neon_vqrshiftns:
14323   case Intrinsic::arm_neon_vqrshiftnu:
14324   case Intrinsic::arm_neon_vqrshiftnsu: {
14325     EVT VT = N->getOperand(1).getValueType();
14326     int64_t Cnt;
14327     unsigned VShiftOpc = 0;
14328 
14329     switch (IntNo) {
14330     case Intrinsic::arm_neon_vshifts:
14331     case Intrinsic::arm_neon_vshiftu:
14332       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
14333         VShiftOpc = ARMISD::VSHLIMM;
14334         break;
14335       }
14336       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
14337         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
14338                                                           : ARMISD::VSHRuIMM);
14339         break;
14340       }
14341       return SDValue();
14342 
14343     case Intrinsic::arm_neon_vrshifts:
14344     case Intrinsic::arm_neon_vrshiftu:
14345       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
14346         break;
14347       return SDValue();
14348 
14349     case Intrinsic::arm_neon_vqshifts:
14350     case Intrinsic::arm_neon_vqshiftu:
14351       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
14352         break;
14353       return SDValue();
14354 
14355     case Intrinsic::arm_neon_vqshiftsu:
14356       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
14357         break;
14358       llvm_unreachable("invalid shift count for vqshlu intrinsic");
14359 
14360     case Intrinsic::arm_neon_vrshiftn:
14361     case Intrinsic::arm_neon_vqshiftns:
14362     case Intrinsic::arm_neon_vqshiftnu:
14363     case Intrinsic::arm_neon_vqshiftnsu:
14364     case Intrinsic::arm_neon_vqrshiftns:
14365     case Intrinsic::arm_neon_vqrshiftnu:
14366     case Intrinsic::arm_neon_vqrshiftnsu:
14367       // Narrowing shifts require an immediate right shift.
14368       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
14369         break;
14370       llvm_unreachable("invalid shift count for narrowing vector shift "
14371                        "intrinsic");
14372 
14373     default:
14374       llvm_unreachable("unhandled vector shift");
14375     }
14376 
14377     switch (IntNo) {
14378     case Intrinsic::arm_neon_vshifts:
14379     case Intrinsic::arm_neon_vshiftu:
14380       // Opcode already set above.
14381       break;
14382     case Intrinsic::arm_neon_vrshifts:
14383       VShiftOpc = ARMISD::VRSHRsIMM;
14384       break;
14385     case Intrinsic::arm_neon_vrshiftu:
14386       VShiftOpc = ARMISD::VRSHRuIMM;
14387       break;
14388     case Intrinsic::arm_neon_vrshiftn:
14389       VShiftOpc = ARMISD::VRSHRNIMM;
14390       break;
14391     case Intrinsic::arm_neon_vqshifts:
14392       VShiftOpc = ARMISD::VQSHLsIMM;
14393       break;
14394     case Intrinsic::arm_neon_vqshiftu:
14395       VShiftOpc = ARMISD::VQSHLuIMM;
14396       break;
14397     case Intrinsic::arm_neon_vqshiftsu:
14398       VShiftOpc = ARMISD::VQSHLsuIMM;
14399       break;
14400     case Intrinsic::arm_neon_vqshiftns:
14401       VShiftOpc = ARMISD::VQSHRNsIMM;
14402       break;
14403     case Intrinsic::arm_neon_vqshiftnu:
14404       VShiftOpc = ARMISD::VQSHRNuIMM;
14405       break;
14406     case Intrinsic::arm_neon_vqshiftnsu:
14407       VShiftOpc = ARMISD::VQSHRNsuIMM;
14408       break;
14409     case Intrinsic::arm_neon_vqrshiftns:
14410       VShiftOpc = ARMISD::VQRSHRNsIMM;
14411       break;
14412     case Intrinsic::arm_neon_vqrshiftnu:
14413       VShiftOpc = ARMISD::VQRSHRNuIMM;
14414       break;
14415     case Intrinsic::arm_neon_vqrshiftnsu:
14416       VShiftOpc = ARMISD::VQRSHRNsuIMM;
14417       break;
14418     }
14419 
14420     SDLoc dl(N);
14421     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
14422                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
14423   }
14424 
14425   case Intrinsic::arm_neon_vshiftins: {
14426     EVT VT = N->getOperand(1).getValueType();
14427     int64_t Cnt;
14428     unsigned VShiftOpc = 0;
14429 
14430     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
14431       VShiftOpc = ARMISD::VSLIIMM;
14432     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
14433       VShiftOpc = ARMISD::VSRIIMM;
14434     else {
14435       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
14436     }
14437 
14438     SDLoc dl(N);
14439     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
14440                        N->getOperand(1), N->getOperand(2),
14441                        DAG.getConstant(Cnt, dl, MVT::i32));
14442   }
14443 
14444   case Intrinsic::arm_neon_vqrshifts:
14445   case Intrinsic::arm_neon_vqrshiftu:
14446     // No immediate versions of these to check for.
14447     break;
14448 
14449   case Intrinsic::arm_mve_vqdmlah:
14450   case Intrinsic::arm_mve_vqdmlash:
14451   case Intrinsic::arm_mve_vqrdmlah:
14452   case Intrinsic::arm_mve_vqrdmlash:
14453   case Intrinsic::arm_mve_vmla_n_predicated:
14454   case Intrinsic::arm_mve_vmlas_n_predicated:
14455   case Intrinsic::arm_mve_vqdmlah_predicated:
14456   case Intrinsic::arm_mve_vqdmlash_predicated:
14457   case Intrinsic::arm_mve_vqrdmlah_predicated:
14458   case Intrinsic::arm_mve_vqrdmlash_predicated: {
14459     // These intrinsics all take an i32 scalar operand which is narrowed to the
14460     // size of a single lane of the vector type they return. So we don't need
14461     // any bits of that operand above that point, which allows us to eliminate
14462     // uxth/sxth.
14463     unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
14464     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
14465     if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
14466       return SDValue();
14467     break;
14468   }
14469 
14470   case Intrinsic::arm_mve_minv:
14471   case Intrinsic::arm_mve_maxv:
14472   case Intrinsic::arm_mve_minav:
14473   case Intrinsic::arm_mve_maxav:
14474   case Intrinsic::arm_mve_minv_predicated:
14475   case Intrinsic::arm_mve_maxv_predicated:
14476   case Intrinsic::arm_mve_minav_predicated:
14477   case Intrinsic::arm_mve_maxav_predicated: {
14478     // These intrinsics all take an i32 scalar operand which is narrowed to the
14479     // size of a single lane of the vector type they take as the other input.
14480     unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
14481     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
14482     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14483       return SDValue();
14484     break;
14485   }
14486 
14487   case Intrinsic::arm_mve_addv: {
14488     // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
14489     // which allow PerformADDVecReduce to turn it into VADDLV when possible.
14490     bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14491     unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
14492     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
14493   }
14494 
14495   case Intrinsic::arm_mve_addlv:
14496   case Intrinsic::arm_mve_addlv_predicated: {
14497     // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
14498     // which recombines the two outputs into an i64
14499     bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
14500     unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
14501                     (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
14502                     (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
14503 
14504     SmallVector<SDValue, 4> Ops;
14505     for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
14506       if (i != 2)                      // skip the unsigned flag
14507         Ops.push_back(N->getOperand(i));
14508 
14509     SDLoc dl(N);
14510     SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
14511     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
14512                        val.getValue(1));
14513   }
14514   }
14515 
14516   return SDValue();
14517 }
14518 
14519 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
14520 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
14521 /// combining instead of DAG legalizing because the build_vectors for 64-bit
14522 /// vector element shift counts are generally not legal, and it is hard to see
14523 /// their values after they get legalized to loads from a constant pool.
14524 static SDValue PerformShiftCombine(SDNode *N,
14525                                    TargetLowering::DAGCombinerInfo &DCI,
14526                                    const ARMSubtarget *ST) {
14527   SelectionDAG &DAG = DCI.DAG;
14528   EVT VT = N->getValueType(0);
14529   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
14530     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
14531     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
14532     SDValue N1 = N->getOperand(1);
14533     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
14534       SDValue N0 = N->getOperand(0);
14535       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
14536           DAG.MaskedValueIsZero(N0.getOperand(0),
14537                                 APInt::getHighBitsSet(32, 16)))
14538         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
14539     }
14540   }
14541 
14542   if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
14543       N->getOperand(0)->getOpcode() == ISD::AND &&
14544       N->getOperand(0)->hasOneUse()) {
14545     if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14546       return SDValue();
14547     // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
14548     // usually show up because instcombine prefers to canonicalize it to
14549     // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
14550     // out of GEP lowering in some cases.
14551     SDValue N0 = N->getOperand(0);
14552     ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
14553     if (!ShiftAmtNode)
14554       return SDValue();
14555     uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
14556     ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
14557     if (!AndMaskNode)
14558       return SDValue();
14559     uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
14560     // Don't transform uxtb/uxth.
14561     if (AndMask == 255 || AndMask == 65535)
14562       return SDValue();
14563     if (isMask_32(AndMask)) {
14564       uint32_t MaskedBits = countLeadingZeros(AndMask);
14565       if (MaskedBits > ShiftAmt) {
14566         SDLoc DL(N);
14567         SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
14568                                   DAG.getConstant(MaskedBits, DL, MVT::i32));
14569         return DAG.getNode(
14570             ISD::SRL, DL, MVT::i32, SHL,
14571             DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
14572       }
14573     }
14574   }
14575 
14576   // Nothing to be done for scalar shifts.
14577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14578   if (!VT.isVector() || !TLI.isTypeLegal(VT))
14579     return SDValue();
14580   if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
14581     return SDValue();
14582 
14583   int64_t Cnt;
14584 
14585   switch (N->getOpcode()) {
14586   default: llvm_unreachable("unexpected shift opcode");
14587 
14588   case ISD::SHL:
14589     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
14590       SDLoc dl(N);
14591       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
14592                          DAG.getConstant(Cnt, dl, MVT::i32));
14593     }
14594     break;
14595 
14596   case ISD::SRA:
14597   case ISD::SRL:
14598     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
14599       unsigned VShiftOpc =
14600           (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
14601       SDLoc dl(N);
14602       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
14603                          DAG.getConstant(Cnt, dl, MVT::i32));
14604     }
14605   }
14606   return SDValue();
14607 }
14608 
14609 // Look for a sign/zero extend of a larger than legal load. This can be split
14610 // into two extending loads, which are simpler to deal with than an arbitrary
14611 // sign extend.
14612 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
14613   SDValue N0 = N->getOperand(0);
14614   if (N0.getOpcode() != ISD::LOAD)
14615     return SDValue();
14616   LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
14617   if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
14618       LD->getExtensionType() != ISD::NON_EXTLOAD)
14619     return SDValue();
14620   EVT FromVT = LD->getValueType(0);
14621   EVT ToVT = N->getValueType(0);
14622   if (!ToVT.isVector())
14623     return SDValue();
14624   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
14625   EVT ToEltVT = ToVT.getVectorElementType();
14626   EVT FromEltVT = FromVT.getVectorElementType();
14627 
14628   unsigned NumElements = 0;
14629   if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
14630     NumElements = 4;
14631   if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
14632     NumElements = 8;
14633   if (NumElements == 0 ||
14634       FromVT.getVectorNumElements() == NumElements ||
14635       FromVT.getVectorNumElements() % NumElements != 0 ||
14636       !isPowerOf2_32(NumElements))
14637     return SDValue();
14638 
14639   SDLoc DL(LD);
14640   // Details about the old load
14641   SDValue Ch = LD->getChain();
14642   SDValue BasePtr = LD->getBasePtr();
14643   Align Alignment = LD->getOriginalAlign();
14644   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
14645   AAMDNodes AAInfo = LD->getAAInfo();
14646 
14647   ISD::LoadExtType NewExtType =
14648       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
14649   SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
14650   EVT NewFromVT = FromVT.getHalfNumVectorElementsVT(*DAG.getContext());
14651   EVT NewToVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
14652   unsigned NewOffset = NewFromVT.getSizeInBits() / 8;
14653   SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
14654 
14655   // Split the load in half, each side of which is extended separately. This
14656   // is good enough, as legalisation will take it from there. They are either
14657   // already legal or they will be split further into something that is
14658   // legal.
14659   SDValue NewLoad1 = DAG.getLoad(
14660       ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, BasePtr, Offset,
14661       LD->getPointerInfo(), NewFromVT, Alignment.value(), MMOFlags, AAInfo);
14662   SDValue NewLoad2 =
14663       DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
14664                   LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
14665                   Alignment.value(), MMOFlags, AAInfo);
14666 
14667   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14668                                  SDValue(NewLoad1.getNode(), 1),
14669                                  SDValue(NewLoad2.getNode(), 1));
14670   DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
14671   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, NewLoad1, NewLoad2);
14672 }
14673 
14674 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
14675 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
14676 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
14677                                     const ARMSubtarget *ST) {
14678   SDValue N0 = N->getOperand(0);
14679 
14680   // Check for sign- and zero-extensions of vector extract operations of 8- and
14681   // 16-bit vector elements. NEON and MVE support these directly. They are
14682   // handled during DAG combining because type legalization will promote them
14683   // to 32-bit types and it is messy to recognize the operations after that.
14684   if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
14685       N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14686     SDValue Vec = N0.getOperand(0);
14687     SDValue Lane = N0.getOperand(1);
14688     EVT VT = N->getValueType(0);
14689     EVT EltVT = N0.getValueType();
14690     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14691 
14692     if (VT == MVT::i32 &&
14693         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
14694         TLI.isTypeLegal(Vec.getValueType()) &&
14695         isa<ConstantSDNode>(Lane)) {
14696 
14697       unsigned Opc = 0;
14698       switch (N->getOpcode()) {
14699       default: llvm_unreachable("unexpected opcode");
14700       case ISD::SIGN_EXTEND:
14701         Opc = ARMISD::VGETLANEs;
14702         break;
14703       case ISD::ZERO_EXTEND:
14704       case ISD::ANY_EXTEND:
14705         Opc = ARMISD::VGETLANEu;
14706         break;
14707       }
14708       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
14709     }
14710   }
14711 
14712   if (ST->hasMVEIntegerOps())
14713     if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
14714       return NewLoad;
14715 
14716   return SDValue();
14717 }
14718 
14719 static const APInt *isPowerOf2Constant(SDValue V) {
14720   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
14721   if (!C)
14722     return nullptr;
14723   const APInt *CV = &C->getAPIntValue();
14724   return CV->isPowerOf2() ? CV : nullptr;
14725 }
14726 
14727 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
14728   // If we have a CMOV, OR and AND combination such as:
14729   //   if (x & CN)
14730   //     y |= CM;
14731   //
14732   // And:
14733   //   * CN is a single bit;
14734   //   * All bits covered by CM are known zero in y
14735   //
14736   // Then we can convert this into a sequence of BFI instructions. This will
14737   // always be a win if CM is a single bit, will always be no worse than the
14738   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
14739   // three bits (due to the extra IT instruction).
14740 
14741   SDValue Op0 = CMOV->getOperand(0);
14742   SDValue Op1 = CMOV->getOperand(1);
14743   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
14744   auto CC = CCNode->getAPIntValue().getLimitedValue();
14745   SDValue CmpZ = CMOV->getOperand(4);
14746 
14747   // The compare must be against zero.
14748   if (!isNullConstant(CmpZ->getOperand(1)))
14749     return SDValue();
14750 
14751   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
14752   SDValue And = CmpZ->getOperand(0);
14753   if (And->getOpcode() != ISD::AND)
14754     return SDValue();
14755   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
14756   if (!AndC)
14757     return SDValue();
14758   SDValue X = And->getOperand(0);
14759 
14760   if (CC == ARMCC::EQ) {
14761     // We're performing an "equal to zero" compare. Swap the operands so we
14762     // canonicalize on a "not equal to zero" compare.
14763     std::swap(Op0, Op1);
14764   } else {
14765     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
14766   }
14767 
14768   if (Op1->getOpcode() != ISD::OR)
14769     return SDValue();
14770 
14771   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
14772   if (!OrC)
14773     return SDValue();
14774   SDValue Y = Op1->getOperand(0);
14775 
14776   if (Op0 != Y)
14777     return SDValue();
14778 
14779   // Now, is it profitable to continue?
14780   APInt OrCI = OrC->getAPIntValue();
14781   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
14782   if (OrCI.countPopulation() > Heuristic)
14783     return SDValue();
14784 
14785   // Lastly, can we determine that the bits defined by OrCI
14786   // are zero in Y?
14787   KnownBits Known = DAG.computeKnownBits(Y);
14788   if ((OrCI & Known.Zero) != OrCI)
14789     return SDValue();
14790 
14791   // OK, we can do the combine.
14792   SDValue V = Y;
14793   SDLoc dl(X);
14794   EVT VT = X.getValueType();
14795   unsigned BitInX = AndC->logBase2();
14796 
14797   if (BitInX != 0) {
14798     // We must shift X first.
14799     X = DAG.getNode(ISD::SRL, dl, VT, X,
14800                     DAG.getConstant(BitInX, dl, VT));
14801   }
14802 
14803   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
14804        BitInY < NumActiveBits; ++BitInY) {
14805     if (OrCI[BitInY] == 0)
14806       continue;
14807     APInt Mask(VT.getSizeInBits(), 0);
14808     Mask.setBit(BitInY);
14809     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
14810                     // Confusingly, the operand is an *inverted* mask.
14811                     DAG.getConstant(~Mask, dl, VT));
14812   }
14813 
14814   return V;
14815 }
14816 
14817 // Given N, the value controlling the conditional branch, search for the loop
14818 // intrinsic, returning it, along with how the value is used. We need to handle
14819 // patterns such as the following:
14820 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
14821 // (brcond (setcc (loop.decrement), 0, eq), exit)
14822 // (brcond (setcc (loop.decrement), 0, ne), header)
14823 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
14824                                    bool &Negate) {
14825   switch (N->getOpcode()) {
14826   default:
14827     break;
14828   case ISD::XOR: {
14829     if (!isa<ConstantSDNode>(N.getOperand(1)))
14830       return SDValue();
14831     if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
14832       return SDValue();
14833     Negate = !Negate;
14834     return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
14835   }
14836   case ISD::SETCC: {
14837     auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
14838     if (!Const)
14839       return SDValue();
14840     if (Const->isNullValue())
14841       Imm = 0;
14842     else if (Const->isOne())
14843       Imm = 1;
14844     else
14845       return SDValue();
14846     CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
14847     return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
14848   }
14849   case ISD::INTRINSIC_W_CHAIN: {
14850     unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
14851     if (IntOp != Intrinsic::test_set_loop_iterations &&
14852         IntOp != Intrinsic::loop_decrement_reg)
14853       return SDValue();
14854     return N;
14855   }
14856   }
14857   return SDValue();
14858 }
14859 
14860 static SDValue PerformHWLoopCombine(SDNode *N,
14861                                     TargetLowering::DAGCombinerInfo &DCI,
14862                                     const ARMSubtarget *ST) {
14863 
14864   // The hwloop intrinsics that we're interested are used for control-flow,
14865   // either for entering or exiting the loop:
14866   // - test.set.loop.iterations will test whether its operand is zero. If it
14867   //   is zero, the proceeding branch should not enter the loop.
14868   // - loop.decrement.reg also tests whether its operand is zero. If it is
14869   //   zero, the proceeding branch should not branch back to the beginning of
14870   //   the loop.
14871   // So here, we need to check that how the brcond is using the result of each
14872   // of the intrinsics to ensure that we're branching to the right place at the
14873   // right time.
14874 
14875   ISD::CondCode CC;
14876   SDValue Cond;
14877   int Imm = 1;
14878   bool Negate = false;
14879   SDValue Chain = N->getOperand(0);
14880   SDValue Dest;
14881 
14882   if (N->getOpcode() == ISD::BRCOND) {
14883     CC = ISD::SETEQ;
14884     Cond = N->getOperand(1);
14885     Dest = N->getOperand(2);
14886   } else {
14887     assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
14888     CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14889     Cond = N->getOperand(2);
14890     Dest = N->getOperand(4);
14891     if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
14892       if (!Const->isOne() && !Const->isNullValue())
14893         return SDValue();
14894       Imm = Const->getZExtValue();
14895     } else
14896       return SDValue();
14897   }
14898 
14899   SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
14900   if (!Int)
14901     return SDValue();
14902 
14903   if (Negate)
14904     CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
14905 
14906   auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
14907     return (CC == ISD::SETEQ && Imm == 0) ||
14908            (CC == ISD::SETNE && Imm == 1) ||
14909            (CC == ISD::SETLT && Imm == 1) ||
14910            (CC == ISD::SETULT && Imm == 1);
14911   };
14912 
14913   auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
14914     return (CC == ISD::SETEQ && Imm == 1) ||
14915            (CC == ISD::SETNE && Imm == 0) ||
14916            (CC == ISD::SETGT && Imm == 0) ||
14917            (CC == ISD::SETUGT && Imm == 0) ||
14918            (CC == ISD::SETGE && Imm == 1) ||
14919            (CC == ISD::SETUGE && Imm == 1);
14920   };
14921 
14922   assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
14923          "unsupported condition");
14924 
14925   SDLoc dl(Int);
14926   SelectionDAG &DAG = DCI.DAG;
14927   SDValue Elements = Int.getOperand(2);
14928   unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
14929   assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
14930           && "expected single br user");
14931   SDNode *Br = *N->use_begin();
14932   SDValue OtherTarget = Br->getOperand(1);
14933 
14934   // Update the unconditional branch to branch to the given Dest.
14935   auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
14936     SDValue NewBrOps[] = { Br->getOperand(0), Dest };
14937     SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
14938     DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
14939   };
14940 
14941   if (IntOp == Intrinsic::test_set_loop_iterations) {
14942     SDValue Res;
14943     // We expect this 'instruction' to branch when the counter is zero.
14944     if (IsTrueIfZero(CC, Imm)) {
14945       SDValue Ops[] = { Chain, Elements, Dest };
14946       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
14947     } else {
14948       // The logic is the reverse of what we need for WLS, so find the other
14949       // basic block target: the target of the proceeding br.
14950       UpdateUncondBr(Br, Dest, DAG);
14951 
14952       SDValue Ops[] = { Chain, Elements, OtherTarget };
14953       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
14954     }
14955     DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
14956     return Res;
14957   } else {
14958     SDValue Size = DAG.getTargetConstant(
14959       cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
14960     SDValue Args[] = { Int.getOperand(0), Elements, Size, };
14961     SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
14962                                   DAG.getVTList(MVT::i32, MVT::Other), Args);
14963     DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
14964 
14965     // We expect this instruction to branch when the count is not zero.
14966     SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
14967 
14968     // Update the unconditional branch to target the loop preheader if we've
14969     // found the condition has been reversed.
14970     if (Target == OtherTarget)
14971       UpdateUncondBr(Br, Dest, DAG);
14972 
14973     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14974                         SDValue(LoopDec.getNode(), 1), Chain);
14975 
14976     SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
14977     return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
14978   }
14979   return SDValue();
14980 }
14981 
14982 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
14983 SDValue
14984 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
14985   SDValue Cmp = N->getOperand(4);
14986   if (Cmp.getOpcode() != ARMISD::CMPZ)
14987     // Only looking at NE cases.
14988     return SDValue();
14989 
14990   EVT VT = N->getValueType(0);
14991   SDLoc dl(N);
14992   SDValue LHS = Cmp.getOperand(0);
14993   SDValue RHS = Cmp.getOperand(1);
14994   SDValue Chain = N->getOperand(0);
14995   SDValue BB = N->getOperand(1);
14996   SDValue ARMcc = N->getOperand(2);
14997   ARMCC::CondCodes CC =
14998     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
14999 
15000   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
15001   // -> (brcond Chain BB CC CPSR Cmp)
15002   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
15003       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
15004       LHS->getOperand(0)->hasOneUse()) {
15005     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
15006     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
15007     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
15008     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
15009     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
15010         (LHS01C && LHS01C->getZExtValue() == 1) &&
15011         (LHS1C && LHS1C->getZExtValue() == 1) &&
15012         (RHSC && RHSC->getZExtValue() == 0)) {
15013       return DAG.getNode(
15014           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
15015           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
15016     }
15017   }
15018 
15019   return SDValue();
15020 }
15021 
15022 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
15023 SDValue
15024 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
15025   SDValue Cmp = N->getOperand(4);
15026   if (Cmp.getOpcode() != ARMISD::CMPZ)
15027     // Only looking at EQ and NE cases.
15028     return SDValue();
15029 
15030   EVT VT = N->getValueType(0);
15031   SDLoc dl(N);
15032   SDValue LHS = Cmp.getOperand(0);
15033   SDValue RHS = Cmp.getOperand(1);
15034   SDValue FalseVal = N->getOperand(0);
15035   SDValue TrueVal = N->getOperand(1);
15036   SDValue ARMcc = N->getOperand(2);
15037   ARMCC::CondCodes CC =
15038     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
15039 
15040   // BFI is only available on V6T2+.
15041   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
15042     SDValue R = PerformCMOVToBFICombine(N, DAG);
15043     if (R)
15044       return R;
15045   }
15046 
15047   // Simplify
15048   //   mov     r1, r0
15049   //   cmp     r1, x
15050   //   mov     r0, y
15051   //   moveq   r0, x
15052   // to
15053   //   cmp     r0, x
15054   //   movne   r0, y
15055   //
15056   //   mov     r1, r0
15057   //   cmp     r1, x
15058   //   mov     r0, x
15059   //   movne   r0, y
15060   // to
15061   //   cmp     r0, x
15062   //   movne   r0, y
15063   /// FIXME: Turn this into a target neutral optimization?
15064   SDValue Res;
15065   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
15066     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
15067                       N->getOperand(3), Cmp);
15068   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
15069     SDValue ARMcc;
15070     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
15071     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
15072                       N->getOperand(3), NewCmp);
15073   }
15074 
15075   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
15076   // -> (cmov F T CC CPSR Cmp)
15077   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
15078     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
15079     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
15080     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
15081     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
15082         (LHS1C && LHS1C->getZExtValue() == 1) &&
15083         (RHSC && RHSC->getZExtValue() == 0)) {
15084       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
15085                          LHS->getOperand(2), LHS->getOperand(3),
15086                          LHS->getOperand(4));
15087     }
15088   }
15089 
15090   if (!VT.isInteger())
15091       return SDValue();
15092 
15093   // Materialize a boolean comparison for integers so we can avoid branching.
15094   if (isNullConstant(FalseVal)) {
15095     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
15096       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
15097         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
15098         // right 5 bits will make that 32 be 1, otherwise it will be 0.
15099         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
15100         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
15101         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
15102                           DAG.getConstant(5, dl, MVT::i32));
15103       } else {
15104         // CMOV 0, 1, ==, (CMPZ x, y) ->
15105         //     (ADDCARRY (SUB x, y), t:0, t:1)
15106         // where t = (SUBCARRY 0, (SUB x, y), 0)
15107         //
15108         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
15109         // x != y. In other words, a carry C == 1 when x == y, C == 0
15110         // otherwise.
15111         // The final ADDCARRY computes
15112         //     x - y + (0 - (x - y)) + C == C
15113         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
15114         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15115         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
15116         // ISD::SUBCARRY returns a borrow but we want the carry here
15117         // actually.
15118         SDValue Carry =
15119             DAG.getNode(ISD::SUB, dl, MVT::i32,
15120                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
15121         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
15122       }
15123     } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
15124                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
15125       // This seems pointless but will allow us to combine it further below.
15126       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
15127       SDValue Sub =
15128           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
15129       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
15130                                           Sub.getValue(1), SDValue());
15131       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
15132                         N->getOperand(3), CPSRGlue.getValue(1));
15133       FalseVal = Sub;
15134     }
15135   } else if (isNullConstant(TrueVal)) {
15136     if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
15137         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
15138       // This seems pointless but will allow us to combine it further below
15139       // Note that we change == for != as this is the dual for the case above.
15140       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
15141       SDValue Sub =
15142           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
15143       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
15144                                           Sub.getValue(1), SDValue());
15145       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
15146                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
15147                         N->getOperand(3), CPSRGlue.getValue(1));
15148       FalseVal = Sub;
15149     }
15150   }
15151 
15152   // On Thumb1, the DAG above may be further combined if z is a power of 2
15153   // (z == 2 ^ K).
15154   // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
15155   // t1 = (USUBO (SUB x, y), 1)
15156   // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
15157   // Result = if K != 0 then (SHL t2:0, K) else t2:0
15158   //
15159   // This also handles the special case of comparing against zero; it's
15160   // essentially, the same pattern, except there's no SUBS:
15161   // CMOV x, z, !=, (CMPZ x, 0) ->
15162   // t1 = (USUBO x, 1)
15163   // t2 = (SUBCARRY x, t1:0, t1:1)
15164   // Result = if K != 0 then (SHL t2:0, K) else t2:0
15165   const APInt *TrueConst;
15166   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
15167       ((FalseVal.getOpcode() == ARMISD::SUBS &&
15168         FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
15169        (FalseVal == LHS && isNullConstant(RHS))) &&
15170       (TrueConst = isPowerOf2Constant(TrueVal))) {
15171     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15172     unsigned ShiftAmount = TrueConst->logBase2();
15173     if (ShiftAmount)
15174       TrueVal = DAG.getConstant(1, dl, VT);
15175     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
15176     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
15177 
15178     if (ShiftAmount)
15179       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
15180                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
15181   }
15182 
15183   if (Res.getNode()) {
15184     KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
15185     // Capture demanded bits information that would be otherwise lost.
15186     if (Known.Zero == 0xfffffffe)
15187       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
15188                         DAG.getValueType(MVT::i1));
15189     else if (Known.Zero == 0xffffff00)
15190       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
15191                         DAG.getValueType(MVT::i8));
15192     else if (Known.Zero == 0xffff0000)
15193       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
15194                         DAG.getValueType(MVT::i16));
15195   }
15196 
15197   return Res;
15198 }
15199 
15200 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
15201   SDValue Src = N->getOperand(0);
15202 
15203   // We may have a bitcast of something that has already had this bitcast
15204   // combine performed on it, so skip past any VECTOR_REG_CASTs.
15205   while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST)
15206     Src = Src.getOperand(0);
15207 
15208   // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
15209   // would be generated is at least the width of the element type.
15210   EVT SrcVT = Src.getValueType();
15211   EVT DstVT = N->getValueType(0);
15212   if ((Src.getOpcode() == ARMISD::VMOVIMM ||
15213        Src.getOpcode() == ARMISD::VMVNIMM ||
15214        Src.getOpcode() == ARMISD::VMOVFPIMM) &&
15215       SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
15216       DAG.getDataLayout().isBigEndian())
15217     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
15218 
15219   return SDValue();
15220 }
15221 
15222 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
15223                                              DAGCombinerInfo &DCI) const {
15224   switch (N->getOpcode()) {
15225   default: break;
15226   case ISD::ABS:        return PerformABSCombine(N, DCI, Subtarget);
15227   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
15228   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
15229   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
15230   case ISD::SUB:        return PerformSUBCombine(N, DCI, Subtarget);
15231   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
15232   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
15233   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
15234   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
15235   case ISD::BRCOND:
15236   case ISD::BR_CC:      return PerformHWLoopCombine(N, DCI, Subtarget);
15237   case ARMISD::ADDC:
15238   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
15239   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
15240   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
15241   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
15242   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
15243   case ARMISD::VMOVhr:  return PerformVMOVhrCombine(N, DCI);
15244   case ARMISD::VMOVrh:  return PerformVMOVrhCombine(N, DCI);
15245   case ISD::STORE:      return PerformSTORECombine(N, DCI, Subtarget);
15246   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
15247   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
15248   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
15249   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
15250   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
15251   case ISD::FP_TO_SINT:
15252   case ISD::FP_TO_UINT:
15253     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
15254   case ISD::FDIV:
15255     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
15256   case ISD::INTRINSIC_WO_CHAIN:
15257     return PerformIntrinsicCombine(N, DCI);
15258   case ISD::SHL:
15259   case ISD::SRA:
15260   case ISD::SRL:
15261     return PerformShiftCombine(N, DCI, Subtarget);
15262   case ISD::SIGN_EXTEND:
15263   case ISD::ZERO_EXTEND:
15264   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
15265   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
15266   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
15267   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
15268   case ARMISD::VLD1DUP:
15269   case ARMISD::VLD2DUP:
15270   case ARMISD::VLD3DUP:
15271   case ARMISD::VLD4DUP:
15272     return PerformVLDCombine(N, DCI);
15273   case ARMISD::BUILD_VECTOR:
15274     return PerformARMBUILD_VECTORCombine(N, DCI);
15275   case ISD::BITCAST:
15276     return PerformBITCASTCombine(N, DCI.DAG);
15277   case ARMISD::PREDICATE_CAST:
15278     return PerformPREDICATE_CASTCombine(N, DCI);
15279   case ARMISD::VECTOR_REG_CAST:
15280     return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget);
15281   case ARMISD::VCMP:
15282     return PerformVCMPCombine(N, DCI, Subtarget);
15283   case ISD::VECREDUCE_ADD:
15284     return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
15285   case ARMISD::ASRL:
15286   case ARMISD::LSRL:
15287   case ARMISD::LSLL:
15288     return PerformLongShiftCombine(N, DCI.DAG);
15289   case ARMISD::SMULWB: {
15290     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15291     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
15292     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
15293       return SDValue();
15294     break;
15295   }
15296   case ARMISD::SMULWT: {
15297     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15298     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
15299     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
15300       return SDValue();
15301     break;
15302   }
15303   case ARMISD::SMLALBB:
15304   case ARMISD::QADD16b:
15305   case ARMISD::QSUB16b: {
15306     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15307     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
15308     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
15309         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
15310       return SDValue();
15311     break;
15312   }
15313   case ARMISD::SMLALBT: {
15314     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
15315     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
15316     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
15317     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
15318     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
15319         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
15320       return SDValue();
15321     break;
15322   }
15323   case ARMISD::SMLALTB: {
15324     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
15325     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
15326     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
15327     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
15328     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
15329         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
15330       return SDValue();
15331     break;
15332   }
15333   case ARMISD::SMLALTT: {
15334     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15335     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
15336     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
15337         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
15338       return SDValue();
15339     break;
15340   }
15341   case ARMISD::QADD8b:
15342   case ARMISD::QSUB8b: {
15343     unsigned BitWidth = N->getValueType(0).getSizeInBits();
15344     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
15345     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
15346         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
15347       return SDValue();
15348     break;
15349   }
15350   case ISD::INTRINSIC_VOID:
15351   case ISD::INTRINSIC_W_CHAIN:
15352     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
15353     case Intrinsic::arm_neon_vld1:
15354     case Intrinsic::arm_neon_vld1x2:
15355     case Intrinsic::arm_neon_vld1x3:
15356     case Intrinsic::arm_neon_vld1x4:
15357     case Intrinsic::arm_neon_vld2:
15358     case Intrinsic::arm_neon_vld3:
15359     case Intrinsic::arm_neon_vld4:
15360     case Intrinsic::arm_neon_vld2lane:
15361     case Intrinsic::arm_neon_vld3lane:
15362     case Intrinsic::arm_neon_vld4lane:
15363     case Intrinsic::arm_neon_vld2dup:
15364     case Intrinsic::arm_neon_vld3dup:
15365     case Intrinsic::arm_neon_vld4dup:
15366     case Intrinsic::arm_neon_vst1:
15367     case Intrinsic::arm_neon_vst1x2:
15368     case Intrinsic::arm_neon_vst1x3:
15369     case Intrinsic::arm_neon_vst1x4:
15370     case Intrinsic::arm_neon_vst2:
15371     case Intrinsic::arm_neon_vst3:
15372     case Intrinsic::arm_neon_vst4:
15373     case Intrinsic::arm_neon_vst2lane:
15374     case Intrinsic::arm_neon_vst3lane:
15375     case Intrinsic::arm_neon_vst4lane:
15376       return PerformVLDCombine(N, DCI);
15377     case Intrinsic::arm_mve_vld2q:
15378     case Intrinsic::arm_mve_vld4q:
15379     case Intrinsic::arm_mve_vst2q:
15380     case Intrinsic::arm_mve_vst4q:
15381       return PerformMVEVLDCombine(N, DCI);
15382     default: break;
15383     }
15384     break;
15385   }
15386   return SDValue();
15387 }
15388 
15389 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
15390                                                           EVT VT) const {
15391   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
15392 }
15393 
15394 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
15395                                                        unsigned Alignment,
15396                                                        MachineMemOperand::Flags,
15397                                                        bool *Fast) const {
15398   // Depends what it gets converted into if the type is weird.
15399   if (!VT.isSimple())
15400     return false;
15401 
15402   // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
15403   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
15404   auto Ty = VT.getSimpleVT().SimpleTy;
15405 
15406   if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
15407     // Unaligned access can use (for example) LRDB, LRDH, LDR
15408     if (AllowsUnaligned) {
15409       if (Fast)
15410         *Fast = Subtarget->hasV7Ops();
15411       return true;
15412     }
15413   }
15414 
15415   if (Ty == MVT::f64 || Ty == MVT::v2f64) {
15416     // For any little-endian targets with neon, we can support unaligned ld/st
15417     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
15418     // A big-endian target may also explicitly support unaligned accesses
15419     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
15420       if (Fast)
15421         *Fast = true;
15422       return true;
15423     }
15424   }
15425 
15426   if (!Subtarget->hasMVEIntegerOps())
15427     return false;
15428 
15429   // These are for predicates
15430   if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
15431     if (Fast)
15432       *Fast = true;
15433     return true;
15434   }
15435 
15436   // These are for truncated stores/narrowing loads. They are fine so long as
15437   // the alignment is at least the size of the item being loaded
15438   if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
15439       Alignment >= VT.getScalarSizeInBits() / 8) {
15440     if (Fast)
15441       *Fast = true;
15442     return true;
15443   }
15444 
15445   // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
15446   // VSTRW.U32 all store the vector register in exactly the same format, and
15447   // differ only in the range of their immediate offset field and the required
15448   // alignment. So there is always a store that can be used, regardless of
15449   // actual type.
15450   //
15451   // For big endian, that is not the case. But can still emit a (VSTRB.U8;
15452   // VREV64.8) pair and get the same effect. This will likely be better than
15453   // aligning the vector through the stack.
15454   if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
15455       Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
15456       Ty == MVT::v2f64) {
15457     if (Fast)
15458       *Fast = true;
15459     return true;
15460   }
15461 
15462   return false;
15463 }
15464 
15465 
15466 EVT ARMTargetLowering::getOptimalMemOpType(
15467     const MemOp &Op, const AttributeList &FuncAttributes) const {
15468   // See if we can use NEON instructions for this...
15469   if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
15470       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15471     bool Fast;
15472     if (Op.size() >= 16 &&
15473         (Op.isAligned(Align(16)) ||
15474          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
15475                                          MachineMemOperand::MONone, &Fast) &&
15476           Fast))) {
15477       return MVT::v2f64;
15478     } else if (Op.size() >= 8 &&
15479                (Op.isAligned(Align(8)) ||
15480                 (allowsMisalignedMemoryAccesses(
15481                      MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
15482                  Fast))) {
15483       return MVT::f64;
15484     }
15485   }
15486 
15487   // Let the target-independent logic figure it out.
15488   return MVT::Other;
15489 }
15490 
15491 // 64-bit integers are split into their high and low parts and held in two
15492 // different registers, so the trunc is free since the low register can just
15493 // be used.
15494 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
15495   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
15496     return false;
15497   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
15498   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
15499   return (SrcBits == 64 && DestBits == 32);
15500 }
15501 
15502 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
15503   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
15504       !DstVT.isInteger())
15505     return false;
15506   unsigned SrcBits = SrcVT.getSizeInBits();
15507   unsigned DestBits = DstVT.getSizeInBits();
15508   return (SrcBits == 64 && DestBits == 32);
15509 }
15510 
15511 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15512   if (Val.getOpcode() != ISD::LOAD)
15513     return false;
15514 
15515   EVT VT1 = Val.getValueType();
15516   if (!VT1.isSimple() || !VT1.isInteger() ||
15517       !VT2.isSimple() || !VT2.isInteger())
15518     return false;
15519 
15520   switch (VT1.getSimpleVT().SimpleTy) {
15521   default: break;
15522   case MVT::i1:
15523   case MVT::i8:
15524   case MVT::i16:
15525     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
15526     return true;
15527   }
15528 
15529   return false;
15530 }
15531 
15532 bool ARMTargetLowering::isFNegFree(EVT VT) const {
15533   if (!VT.isSimple())
15534     return false;
15535 
15536   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
15537   // negate values directly (fneg is free). So, we don't want to let the DAG
15538   // combiner rewrite fneg into xors and some other instructions.  For f16 and
15539   // FullFP16 argument passing, some bitcast nodes may be introduced,
15540   // triggering this DAG combine rewrite, so we are avoiding that with this.
15541   switch (VT.getSimpleVT().SimpleTy) {
15542   default: break;
15543   case MVT::f16:
15544     return Subtarget->hasFullFP16();
15545   }
15546 
15547   return false;
15548 }
15549 
15550 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
15551 /// of the vector elements.
15552 static bool areExtractExts(Value *Ext1, Value *Ext2) {
15553   auto areExtDoubled = [](Instruction *Ext) {
15554     return Ext->getType()->getScalarSizeInBits() ==
15555            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
15556   };
15557 
15558   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
15559       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
15560       !areExtDoubled(cast<Instruction>(Ext1)) ||
15561       !areExtDoubled(cast<Instruction>(Ext2)))
15562     return false;
15563 
15564   return true;
15565 }
15566 
15567 /// Check if sinking \p I's operands to I's basic block is profitable, because
15568 /// the operands can be folded into a target instruction, e.g.
15569 /// sext/zext can be folded into vsubl.
15570 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
15571                                            SmallVectorImpl<Use *> &Ops) const {
15572   if (!I->getType()->isVectorTy())
15573     return false;
15574 
15575   if (Subtarget->hasNEON()) {
15576     switch (I->getOpcode()) {
15577     case Instruction::Sub:
15578     case Instruction::Add: {
15579       if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
15580         return false;
15581       Ops.push_back(&I->getOperandUse(0));
15582       Ops.push_back(&I->getOperandUse(1));
15583       return true;
15584     }
15585     default:
15586       return false;
15587     }
15588   }
15589 
15590   if (!Subtarget->hasMVEIntegerOps())
15591     return false;
15592 
15593   auto IsFMSMul = [&](Instruction *I) {
15594     if (!I->hasOneUse())
15595       return false;
15596     auto *Sub = cast<Instruction>(*I->users().begin());
15597     return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I;
15598   };
15599 
15600   auto IsSinker = [&](Instruction *I, int Operand) {
15601     switch (I->getOpcode()) {
15602     case Instruction::Add:
15603     case Instruction::Mul:
15604     case Instruction::FAdd:
15605     case Instruction::ICmp:
15606     case Instruction::FCmp:
15607       return true;
15608     case Instruction::FMul:
15609       return !IsFMSMul(I);
15610     case Instruction::Sub:
15611     case Instruction::FSub:
15612     case Instruction::Shl:
15613     case Instruction::LShr:
15614     case Instruction::AShr:
15615       return Operand == 1;
15616     default:
15617       return false;
15618     }
15619   };
15620 
15621   int Op = 0;
15622   if (!isa<ShuffleVectorInst>(I->getOperand(Op)))
15623     Op = 1;
15624   if (!IsSinker(I, Op))
15625     return false;
15626   if (!match(I->getOperand(Op),
15627              m_ShuffleVector(m_InsertElement(m_Undef(), m_Value(), m_ZeroInt()),
15628                              m_Undef(), m_ZeroMask()))) {
15629     return false;
15630   }
15631   Instruction *Shuffle = cast<Instruction>(I->getOperand(Op));
15632   // All uses of the shuffle should be sunk to avoid duplicating it across gpr
15633   // and vector registers
15634   for (Use &U : Shuffle->uses()) {
15635     Instruction *Insn = cast<Instruction>(U.getUser());
15636     if (!IsSinker(Insn, U.getOperandNo()))
15637       return false;
15638   }
15639   Ops.push_back(&Shuffle->getOperandUse(0));
15640   Ops.push_back(&I->getOperandUse(Op));
15641   return true;
15642 }
15643 
15644 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
15645   EVT VT = ExtVal.getValueType();
15646 
15647   if (!isTypeLegal(VT))
15648     return false;
15649 
15650   if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
15651     if (Ld->isExpandingLoad())
15652       return false;
15653   }
15654 
15655   if (Subtarget->hasMVEIntegerOps())
15656     return true;
15657 
15658   // Don't create a loadext if we can fold the extension into a wide/long
15659   // instruction.
15660   // If there's more than one user instruction, the loadext is desirable no
15661   // matter what.  There can be two uses by the same instruction.
15662   if (ExtVal->use_empty() ||
15663       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
15664     return true;
15665 
15666   SDNode *U = *ExtVal->use_begin();
15667   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
15668        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
15669     return false;
15670 
15671   return true;
15672 }
15673 
15674 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15675   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15676     return false;
15677 
15678   if (!isTypeLegal(EVT::getEVT(Ty1)))
15679     return false;
15680 
15681   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15682 
15683   // Assuming the caller doesn't have a zeroext or signext return parameter,
15684   // truncation all the way down to i1 is valid.
15685   return true;
15686 }
15687 
15688 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
15689                                                 const AddrMode &AM, Type *Ty,
15690                                                 unsigned AS) const {
15691   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
15692     if (Subtarget->hasFPAO())
15693       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
15694     return 0;
15695   }
15696   return -1;
15697 }
15698 
15699 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
15700 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
15701 /// expanded to FMAs when this method returns true, otherwise fmuladd is
15702 /// expanded to fmul + fadd.
15703 ///
15704 /// ARM supports both fused and unfused multiply-add operations; we already
15705 /// lower a pair of fmul and fadd to the latter so it's not clear that there
15706 /// would be a gain or that the gain would be worthwhile enough to risk
15707 /// correctness bugs.
15708 ///
15709 /// For MVE, we set this to true as it helps simplify the need for some
15710 /// patterns (and we don't have the non-fused floating point instruction).
15711 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15712                                                    EVT VT) const {
15713   if (!VT.isSimple())
15714     return false;
15715 
15716   switch (VT.getSimpleVT().SimpleTy) {
15717   case MVT::v4f32:
15718   case MVT::v8f16:
15719     return Subtarget->hasMVEFloatOps();
15720   case MVT::f16:
15721     return Subtarget->useFPVFMx16();
15722   case MVT::f32:
15723     return Subtarget->useFPVFMx();
15724   case MVT::f64:
15725     return Subtarget->useFPVFMx64();
15726   default:
15727     break;
15728   }
15729 
15730   return false;
15731 }
15732 
15733 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
15734   if (V < 0)
15735     return false;
15736 
15737   unsigned Scale = 1;
15738   switch (VT.getSimpleVT().SimpleTy) {
15739   case MVT::i1:
15740   case MVT::i8:
15741     // Scale == 1;
15742     break;
15743   case MVT::i16:
15744     // Scale == 2;
15745     Scale = 2;
15746     break;
15747   default:
15748     // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
15749     // Scale == 4;
15750     Scale = 4;
15751     break;
15752   }
15753 
15754   if ((V & (Scale - 1)) != 0)
15755     return false;
15756   return isUInt<5>(V / Scale);
15757 }
15758 
15759 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
15760                                       const ARMSubtarget *Subtarget) {
15761   if (!VT.isInteger() && !VT.isFloatingPoint())
15762     return false;
15763   if (VT.isVector() && Subtarget->hasNEON())
15764     return false;
15765   if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
15766       !Subtarget->hasMVEFloatOps())
15767     return false;
15768 
15769   bool IsNeg = false;
15770   if (V < 0) {
15771     IsNeg = true;
15772     V = -V;
15773   }
15774 
15775   unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
15776 
15777   // MVE: size * imm7
15778   if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
15779     switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
15780     case MVT::i32:
15781     case MVT::f32:
15782       return isShiftedUInt<7,2>(V);
15783     case MVT::i16:
15784     case MVT::f16:
15785       return isShiftedUInt<7,1>(V);
15786     case MVT::i8:
15787       return isUInt<7>(V);
15788     default:
15789       return false;
15790     }
15791   }
15792 
15793   // half VLDR: 2 * imm8
15794   if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
15795     return isShiftedUInt<8, 1>(V);
15796   // VLDR and LDRD: 4 * imm8
15797   if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
15798     return isShiftedUInt<8, 2>(V);
15799 
15800   if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
15801     // + imm12 or - imm8
15802     if (IsNeg)
15803       return isUInt<8>(V);
15804     return isUInt<12>(V);
15805   }
15806 
15807   return false;
15808 }
15809 
15810 /// isLegalAddressImmediate - Return true if the integer value can be used
15811 /// as the offset of the target addressing mode for load / store of the
15812 /// given type.
15813 static bool isLegalAddressImmediate(int64_t V, EVT VT,
15814                                     const ARMSubtarget *Subtarget) {
15815   if (V == 0)
15816     return true;
15817 
15818   if (!VT.isSimple())
15819     return false;
15820 
15821   if (Subtarget->isThumb1Only())
15822     return isLegalT1AddressImmediate(V, VT);
15823   else if (Subtarget->isThumb2())
15824     return isLegalT2AddressImmediate(V, VT, Subtarget);
15825 
15826   // ARM mode.
15827   if (V < 0)
15828     V = - V;
15829   switch (VT.getSimpleVT().SimpleTy) {
15830   default: return false;
15831   case MVT::i1:
15832   case MVT::i8:
15833   case MVT::i32:
15834     // +- imm12
15835     return isUInt<12>(V);
15836   case MVT::i16:
15837     // +- imm8
15838     return isUInt<8>(V);
15839   case MVT::f32:
15840   case MVT::f64:
15841     if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
15842       return false;
15843     return isShiftedUInt<8, 2>(V);
15844   }
15845 }
15846 
15847 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
15848                                                       EVT VT) const {
15849   int Scale = AM.Scale;
15850   if (Scale < 0)
15851     return false;
15852 
15853   switch (VT.getSimpleVT().SimpleTy) {
15854   default: return false;
15855   case MVT::i1:
15856   case MVT::i8:
15857   case MVT::i16:
15858   case MVT::i32:
15859     if (Scale == 1)
15860       return true;
15861     // r + r << imm
15862     Scale = Scale & ~1;
15863     return Scale == 2 || Scale == 4 || Scale == 8;
15864   case MVT::i64:
15865     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
15866     // version in Thumb mode.
15867     // r + r
15868     if (Scale == 1)
15869       return true;
15870     // r * 2 (this can be lowered to r + r).
15871     if (!AM.HasBaseReg && Scale == 2)
15872       return true;
15873     return false;
15874   case MVT::isVoid:
15875     // Note, we allow "void" uses (basically, uses that aren't loads or
15876     // stores), because arm allows folding a scale into many arithmetic
15877     // operations.  This should be made more precise and revisited later.
15878 
15879     // Allow r << imm, but the imm has to be a multiple of two.
15880     if (Scale & 1) return false;
15881     return isPowerOf2_32(Scale);
15882   }
15883 }
15884 
15885 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
15886                                                       EVT VT) const {
15887   const int Scale = AM.Scale;
15888 
15889   // Negative scales are not supported in Thumb1.
15890   if (Scale < 0)
15891     return false;
15892 
15893   // Thumb1 addressing modes do not support register scaling excepting the
15894   // following cases:
15895   // 1. Scale == 1 means no scaling.
15896   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
15897   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
15898 }
15899 
15900 /// isLegalAddressingMode - Return true if the addressing mode represented
15901 /// by AM is legal for this target, for a load/store of the specified type.
15902 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15903                                               const AddrMode &AM, Type *Ty,
15904                                               unsigned AS, Instruction *I) const {
15905   EVT VT = getValueType(DL, Ty, true);
15906   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
15907     return false;
15908 
15909   // Can never fold addr of global into load/store.
15910   if (AM.BaseGV)
15911     return false;
15912 
15913   switch (AM.Scale) {
15914   case 0:  // no scale reg, must be "r+i" or "r", or "i".
15915     break;
15916   default:
15917     // ARM doesn't support any R+R*scale+imm addr modes.
15918     if (AM.BaseOffs)
15919       return false;
15920 
15921     if (!VT.isSimple())
15922       return false;
15923 
15924     if (Subtarget->isThumb1Only())
15925       return isLegalT1ScaledAddressingMode(AM, VT);
15926 
15927     if (Subtarget->isThumb2())
15928       return isLegalT2ScaledAddressingMode(AM, VT);
15929 
15930     int Scale = AM.Scale;
15931     switch (VT.getSimpleVT().SimpleTy) {
15932     default: return false;
15933     case MVT::i1:
15934     case MVT::i8:
15935     case MVT::i32:
15936       if (Scale < 0) Scale = -Scale;
15937       if (Scale == 1)
15938         return true;
15939       // r + r << imm
15940       return isPowerOf2_32(Scale & ~1);
15941     case MVT::i16:
15942     case MVT::i64:
15943       // r +/- r
15944       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
15945         return true;
15946       // r * 2 (this can be lowered to r + r).
15947       if (!AM.HasBaseReg && Scale == 2)
15948         return true;
15949       return false;
15950 
15951     case MVT::isVoid:
15952       // Note, we allow "void" uses (basically, uses that aren't loads or
15953       // stores), because arm allows folding a scale into many arithmetic
15954       // operations.  This should be made more precise and revisited later.
15955 
15956       // Allow r << imm, but the imm has to be a multiple of two.
15957       if (Scale & 1) return false;
15958       return isPowerOf2_32(Scale);
15959     }
15960   }
15961   return true;
15962 }
15963 
15964 /// isLegalICmpImmediate - Return true if the specified immediate is legal
15965 /// icmp immediate, that is the target has icmp instructions which can compare
15966 /// a register against the immediate without having to materialize the
15967 /// immediate into a register.
15968 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15969   // Thumb2 and ARM modes can use cmn for negative immediates.
15970   if (!Subtarget->isThumb())
15971     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
15972            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
15973   if (Subtarget->isThumb2())
15974     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
15975            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
15976   // Thumb1 doesn't have cmn, and only 8-bit immediates.
15977   return Imm >= 0 && Imm <= 255;
15978 }
15979 
15980 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
15981 /// *or sub* immediate, that is the target has add or sub instructions which can
15982 /// add a register with the immediate without having to materialize the
15983 /// immediate into a register.
15984 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15985   // Same encoding for add/sub, just flip the sign.
15986   int64_t AbsImm = std::abs(Imm);
15987   if (!Subtarget->isThumb())
15988     return ARM_AM::getSOImmVal(AbsImm) != -1;
15989   if (Subtarget->isThumb2())
15990     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
15991   // Thumb1 only has 8-bit unsigned immediate.
15992   return AbsImm >= 0 && AbsImm <= 255;
15993 }
15994 
15995 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
15996                                       bool isSEXTLoad, SDValue &Base,
15997                                       SDValue &Offset, bool &isInc,
15998                                       SelectionDAG &DAG) {
15999   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
16000     return false;
16001 
16002   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
16003     // AddressingMode 3
16004     Base = Ptr->getOperand(0);
16005     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
16006       int RHSC = (int)RHS->getZExtValue();
16007       if (RHSC < 0 && RHSC > -256) {
16008         assert(Ptr->getOpcode() == ISD::ADD);
16009         isInc = false;
16010         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16011         return true;
16012       }
16013     }
16014     isInc = (Ptr->getOpcode() == ISD::ADD);
16015     Offset = Ptr->getOperand(1);
16016     return true;
16017   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
16018     // AddressingMode 2
16019     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
16020       int RHSC = (int)RHS->getZExtValue();
16021       if (RHSC < 0 && RHSC > -0x1000) {
16022         assert(Ptr->getOpcode() == ISD::ADD);
16023         isInc = false;
16024         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16025         Base = Ptr->getOperand(0);
16026         return true;
16027       }
16028     }
16029 
16030     if (Ptr->getOpcode() == ISD::ADD) {
16031       isInc = true;
16032       ARM_AM::ShiftOpc ShOpcVal=
16033         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
16034       if (ShOpcVal != ARM_AM::no_shift) {
16035         Base = Ptr->getOperand(1);
16036         Offset = Ptr->getOperand(0);
16037       } else {
16038         Base = Ptr->getOperand(0);
16039         Offset = Ptr->getOperand(1);
16040       }
16041       return true;
16042     }
16043 
16044     isInc = (Ptr->getOpcode() == ISD::ADD);
16045     Base = Ptr->getOperand(0);
16046     Offset = Ptr->getOperand(1);
16047     return true;
16048   }
16049 
16050   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
16051   return false;
16052 }
16053 
16054 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
16055                                      bool isSEXTLoad, SDValue &Base,
16056                                      SDValue &Offset, bool &isInc,
16057                                      SelectionDAG &DAG) {
16058   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
16059     return false;
16060 
16061   Base = Ptr->getOperand(0);
16062   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
16063     int RHSC = (int)RHS->getZExtValue();
16064     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
16065       assert(Ptr->getOpcode() == ISD::ADD);
16066       isInc = false;
16067       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16068       return true;
16069     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
16070       isInc = Ptr->getOpcode() == ISD::ADD;
16071       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
16072       return true;
16073     }
16074   }
16075 
16076   return false;
16077 }
16078 
16079 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align,
16080                                       bool isSEXTLoad, bool IsMasked, bool isLE,
16081                                       SDValue &Base, SDValue &Offset,
16082                                       bool &isInc, SelectionDAG &DAG) {
16083   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
16084     return false;
16085   if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
16086     return false;
16087 
16088   // We allow LE non-masked loads to change the type (for example use a vldrb.8
16089   // as opposed to a vldrw.32). This can allow extra addressing modes or
16090   // alignments for what is otherwise an equivalent instruction.
16091   bool CanChangeType = isLE && !IsMasked;
16092 
16093   ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
16094   int RHSC = (int)RHS->getZExtValue();
16095 
16096   auto IsInRange = [&](int RHSC, int Limit, int Scale) {
16097     if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
16098       assert(Ptr->getOpcode() == ISD::ADD);
16099       isInc = false;
16100       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16101       return true;
16102     } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
16103       isInc = Ptr->getOpcode() == ISD::ADD;
16104       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
16105       return true;
16106     }
16107     return false;
16108   };
16109 
16110   // Try to find a matching instruction based on s/zext, Alignment, Offset and
16111   // (in BE/masked) type.
16112   Base = Ptr->getOperand(0);
16113   if (VT == MVT::v4i16) {
16114     if (Align >= 2 && IsInRange(RHSC, 0x80, 2))
16115       return true;
16116   } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
16117     if (IsInRange(RHSC, 0x80, 1))
16118       return true;
16119   } else if (Align >= 4 &&
16120              (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
16121              IsInRange(RHSC, 0x80, 4))
16122     return true;
16123   else if (Align >= 2 &&
16124            (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
16125            IsInRange(RHSC, 0x80, 2))
16126     return true;
16127   else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
16128     return true;
16129   return false;
16130 }
16131 
16132 /// getPreIndexedAddressParts - returns true by value, base pointer and
16133 /// offset pointer and addressing mode by reference if the node's address
16134 /// can be legally represented as pre-indexed load / store address.
16135 bool
16136 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
16137                                              SDValue &Offset,
16138                                              ISD::MemIndexedMode &AM,
16139                                              SelectionDAG &DAG) const {
16140   if (Subtarget->isThumb1Only())
16141     return false;
16142 
16143   EVT VT;
16144   SDValue Ptr;
16145   unsigned Align;
16146   bool isSEXTLoad = false;
16147   bool IsMasked = false;
16148   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
16149     Ptr = LD->getBasePtr();
16150     VT = LD->getMemoryVT();
16151     Align = LD->getAlignment();
16152     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
16153   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
16154     Ptr = ST->getBasePtr();
16155     VT = ST->getMemoryVT();
16156     Align = ST->getAlignment();
16157   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
16158     Ptr = LD->getBasePtr();
16159     VT = LD->getMemoryVT();
16160     Align = LD->getAlignment();
16161     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
16162     IsMasked = true;
16163   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
16164     Ptr = ST->getBasePtr();
16165     VT = ST->getMemoryVT();
16166     Align = ST->getAlignment();
16167     IsMasked = true;
16168   } else
16169     return false;
16170 
16171   bool isInc;
16172   bool isLegal = false;
16173   if (VT.isVector())
16174     isLegal = Subtarget->hasMVEIntegerOps() &&
16175               getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad,
16176                                         IsMasked, Subtarget->isLittle(), Base,
16177                                         Offset, isInc, DAG);
16178   else {
16179     if (Subtarget->isThumb2())
16180       isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
16181                                          Offset, isInc, DAG);
16182     else
16183       isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
16184                                           Offset, isInc, DAG);
16185   }
16186   if (!isLegal)
16187     return false;
16188 
16189   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
16190   return true;
16191 }
16192 
16193 /// getPostIndexedAddressParts - returns true by value, base pointer and
16194 /// offset pointer and addressing mode by reference if this node can be
16195 /// combined with a load / store to form a post-indexed load / store.
16196 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
16197                                                    SDValue &Base,
16198                                                    SDValue &Offset,
16199                                                    ISD::MemIndexedMode &AM,
16200                                                    SelectionDAG &DAG) const {
16201   EVT VT;
16202   SDValue Ptr;
16203   unsigned Align;
16204   bool isSEXTLoad = false, isNonExt;
16205   bool IsMasked = false;
16206   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
16207     VT = LD->getMemoryVT();
16208     Ptr = LD->getBasePtr();
16209     Align = LD->getAlignment();
16210     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
16211     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
16212   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
16213     VT = ST->getMemoryVT();
16214     Ptr = ST->getBasePtr();
16215     Align = ST->getAlignment();
16216     isNonExt = !ST->isTruncatingStore();
16217   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
16218     VT = LD->getMemoryVT();
16219     Ptr = LD->getBasePtr();
16220     Align = LD->getAlignment();
16221     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
16222     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
16223     IsMasked = true;
16224   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
16225     VT = ST->getMemoryVT();
16226     Ptr = ST->getBasePtr();
16227     Align = ST->getAlignment();
16228     isNonExt = !ST->isTruncatingStore();
16229     IsMasked = true;
16230   } else
16231     return false;
16232 
16233   if (Subtarget->isThumb1Only()) {
16234     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
16235     // must be non-extending/truncating, i32, with an offset of 4.
16236     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
16237     if (Op->getOpcode() != ISD::ADD || !isNonExt)
16238       return false;
16239     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
16240     if (!RHS || RHS->getZExtValue() != 4)
16241       return false;
16242 
16243     Offset = Op->getOperand(1);
16244     Base = Op->getOperand(0);
16245     AM = ISD::POST_INC;
16246     return true;
16247   }
16248 
16249   bool isInc;
16250   bool isLegal = false;
16251   if (VT.isVector())
16252     isLegal = Subtarget->hasMVEIntegerOps() &&
16253               getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad, IsMasked,
16254                                         Subtarget->isLittle(), Base, Offset,
16255                                         isInc, DAG);
16256   else {
16257     if (Subtarget->isThumb2())
16258       isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
16259                                          isInc, DAG);
16260     else
16261       isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
16262                                           isInc, DAG);
16263   }
16264   if (!isLegal)
16265     return false;
16266 
16267   if (Ptr != Base) {
16268     // Swap base ptr and offset to catch more post-index load / store when
16269     // it's legal. In Thumb2 mode, offset must be an immediate.
16270     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
16271         !Subtarget->isThumb2())
16272       std::swap(Base, Offset);
16273 
16274     // Post-indexed load / store update the base pointer.
16275     if (Ptr != Base)
16276       return false;
16277   }
16278 
16279   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
16280   return true;
16281 }
16282 
16283 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
16284                                                       KnownBits &Known,
16285                                                       const APInt &DemandedElts,
16286                                                       const SelectionDAG &DAG,
16287                                                       unsigned Depth) const {
16288   unsigned BitWidth = Known.getBitWidth();
16289   Known.resetAll();
16290   switch (Op.getOpcode()) {
16291   default: break;
16292   case ARMISD::ADDC:
16293   case ARMISD::ADDE:
16294   case ARMISD::SUBC:
16295   case ARMISD::SUBE:
16296     // Special cases when we convert a carry to a boolean.
16297     if (Op.getResNo() == 0) {
16298       SDValue LHS = Op.getOperand(0);
16299       SDValue RHS = Op.getOperand(1);
16300       // (ADDE 0, 0, C) will give us a single bit.
16301       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
16302           isNullConstant(RHS)) {
16303         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
16304         return;
16305       }
16306     }
16307     break;
16308   case ARMISD::CMOV: {
16309     // Bits are known zero/one if known on the LHS and RHS.
16310     Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
16311     if (Known.isUnknown())
16312       return;
16313 
16314     KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
16315     Known.Zero &= KnownRHS.Zero;
16316     Known.One  &= KnownRHS.One;
16317     return;
16318   }
16319   case ISD::INTRINSIC_W_CHAIN: {
16320     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
16321     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
16322     switch (IntID) {
16323     default: return;
16324     case Intrinsic::arm_ldaex:
16325     case Intrinsic::arm_ldrex: {
16326       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
16327       unsigned MemBits = VT.getScalarSizeInBits();
16328       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
16329       return;
16330     }
16331     }
16332   }
16333   case ARMISD::BFI: {
16334     // Conservatively, we can recurse down the first operand
16335     // and just mask out all affected bits.
16336     Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
16337 
16338     // The operand to BFI is already a mask suitable for removing the bits it
16339     // sets.
16340     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
16341     const APInt &Mask = CI->getAPIntValue();
16342     Known.Zero &= Mask;
16343     Known.One &= Mask;
16344     return;
16345   }
16346   case ARMISD::VGETLANEs:
16347   case ARMISD::VGETLANEu: {
16348     const SDValue &SrcSV = Op.getOperand(0);
16349     EVT VecVT = SrcSV.getValueType();
16350     assert(VecVT.isVector() && "VGETLANE expected a vector type");
16351     const unsigned NumSrcElts = VecVT.getVectorNumElements();
16352     ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
16353     assert(Pos->getAPIntValue().ult(NumSrcElts) &&
16354            "VGETLANE index out of bounds");
16355     unsigned Idx = Pos->getZExtValue();
16356     APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
16357     Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
16358 
16359     EVT VT = Op.getValueType();
16360     const unsigned DstSz = VT.getScalarSizeInBits();
16361     const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
16362     (void)SrcSz;
16363     assert(SrcSz == Known.getBitWidth());
16364     assert(DstSz > SrcSz);
16365     if (Op.getOpcode() == ARMISD::VGETLANEs)
16366       Known = Known.sext(DstSz);
16367     else {
16368       Known = Known.zext(DstSz);
16369     }
16370     assert(DstSz == Known.getBitWidth());
16371     break;
16372   }
16373   case ARMISD::VMOVrh: {
16374     KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
16375     assert(KnownOp.getBitWidth() == 16);
16376     Known = KnownOp.zext(32);
16377     break;
16378   }
16379   }
16380 }
16381 
16382 bool
16383 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
16384                                                 const APInt &DemandedAPInt,
16385                                                 TargetLoweringOpt &TLO) const {
16386   // Delay optimization, so we don't have to deal with illegal types, or block
16387   // optimizations.
16388   if (!TLO.LegalOps)
16389     return false;
16390 
16391   // Only optimize AND for now.
16392   if (Op.getOpcode() != ISD::AND)
16393     return false;
16394 
16395   EVT VT = Op.getValueType();
16396 
16397   // Ignore vectors.
16398   if (VT.isVector())
16399     return false;
16400 
16401   assert(VT == MVT::i32 && "Unexpected integer type");
16402 
16403   // Make sure the RHS really is a constant.
16404   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
16405   if (!C)
16406     return false;
16407 
16408   unsigned Mask = C->getZExtValue();
16409 
16410   unsigned Demanded = DemandedAPInt.getZExtValue();
16411   unsigned ShrunkMask = Mask & Demanded;
16412   unsigned ExpandedMask = Mask | ~Demanded;
16413 
16414   // If the mask is all zeros, let the target-independent code replace the
16415   // result with zero.
16416   if (ShrunkMask == 0)
16417     return false;
16418 
16419   // If the mask is all ones, erase the AND. (Currently, the target-independent
16420   // code won't do this, so we have to do it explicitly to avoid an infinite
16421   // loop in obscure cases.)
16422   if (ExpandedMask == ~0U)
16423     return TLO.CombineTo(Op, Op.getOperand(0));
16424 
16425   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
16426     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
16427   };
16428   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
16429     if (NewMask == Mask)
16430       return true;
16431     SDLoc DL(Op);
16432     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
16433     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
16434     return TLO.CombineTo(Op, NewOp);
16435   };
16436 
16437   // Prefer uxtb mask.
16438   if (IsLegalMask(0xFF))
16439     return UseMask(0xFF);
16440 
16441   // Prefer uxth mask.
16442   if (IsLegalMask(0xFFFF))
16443     return UseMask(0xFFFF);
16444 
16445   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
16446   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
16447   if (ShrunkMask < 256)
16448     return UseMask(ShrunkMask);
16449 
16450   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
16451   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
16452   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
16453     return UseMask(ExpandedMask);
16454 
16455   // Potential improvements:
16456   //
16457   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
16458   // We could try to prefer Thumb1 immediates which can be lowered to a
16459   // two-instruction sequence.
16460   // We could try to recognize more legal ARM/Thumb2 immediates here.
16461 
16462   return false;
16463 }
16464 
16465 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
16466     SDValue Op, const APInt &OriginalDemandedBits,
16467     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
16468     unsigned Depth) const {
16469   unsigned Opc = Op.getOpcode();
16470 
16471   switch (Opc) {
16472   case ARMISD::ASRL:
16473   case ARMISD::LSRL: {
16474     // If this is result 0 and the other result is unused, see if the demand
16475     // bits allow us to shrink this long shift into a standard small shift in
16476     // the opposite direction.
16477     if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
16478         isa<ConstantSDNode>(Op->getOperand(2))) {
16479       unsigned ShAmt = Op->getConstantOperandVal(2);
16480       if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(
16481                             APInt::getAllOnesValue(32) << (32 - ShAmt)))
16482         return TLO.CombineTo(
16483             Op, TLO.DAG.getNode(
16484                     ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
16485                     TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
16486     }
16487     break;
16488   }
16489   }
16490 
16491   return TargetLowering::SimplifyDemandedBitsForTargetNode(
16492       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
16493 }
16494 
16495 //===----------------------------------------------------------------------===//
16496 //                           ARM Inline Assembly Support
16497 //===----------------------------------------------------------------------===//
16498 
16499 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
16500   // Looking for "rev" which is V6+.
16501   if (!Subtarget->hasV6Ops())
16502     return false;
16503 
16504   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
16505   std::string AsmStr = IA->getAsmString();
16506   SmallVector<StringRef, 4> AsmPieces;
16507   SplitString(AsmStr, AsmPieces, ";\n");
16508 
16509   switch (AsmPieces.size()) {
16510   default: return false;
16511   case 1:
16512     AsmStr = std::string(AsmPieces[0]);
16513     AsmPieces.clear();
16514     SplitString(AsmStr, AsmPieces, " \t,");
16515 
16516     // rev $0, $1
16517     if (AsmPieces.size() == 3 &&
16518         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
16519         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
16520       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
16521       if (Ty && Ty->getBitWidth() == 32)
16522         return IntrinsicLowering::LowerToByteSwap(CI);
16523     }
16524     break;
16525   }
16526 
16527   return false;
16528 }
16529 
16530 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
16531   // At this point, we have to lower this constraint to something else, so we
16532   // lower it to an "r" or "w". However, by doing this we will force the result
16533   // to be in register, while the X constraint is much more permissive.
16534   //
16535   // Although we are correct (we are free to emit anything, without
16536   // constraints), we might break use cases that would expect us to be more
16537   // efficient and emit something else.
16538   if (!Subtarget->hasVFP2Base())
16539     return "r";
16540   if (ConstraintVT.isFloatingPoint())
16541     return "w";
16542   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
16543      (ConstraintVT.getSizeInBits() == 64 ||
16544       ConstraintVT.getSizeInBits() == 128))
16545     return "w";
16546 
16547   return "r";
16548 }
16549 
16550 /// getConstraintType - Given a constraint letter, return the type of
16551 /// constraint it is for this target.
16552 ARMTargetLowering::ConstraintType
16553 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
16554   unsigned S = Constraint.size();
16555   if (S == 1) {
16556     switch (Constraint[0]) {
16557     default:  break;
16558     case 'l': return C_RegisterClass;
16559     case 'w': return C_RegisterClass;
16560     case 'h': return C_RegisterClass;
16561     case 'x': return C_RegisterClass;
16562     case 't': return C_RegisterClass;
16563     case 'j': return C_Immediate; // Constant for movw.
16564     // An address with a single base register. Due to the way we
16565     // currently handle addresses it is the same as an 'r' memory constraint.
16566     case 'Q': return C_Memory;
16567     }
16568   } else if (S == 2) {
16569     switch (Constraint[0]) {
16570     default: break;
16571     case 'T': return C_RegisterClass;
16572     // All 'U+' constraints are addresses.
16573     case 'U': return C_Memory;
16574     }
16575   }
16576   return TargetLowering::getConstraintType(Constraint);
16577 }
16578 
16579 /// Examine constraint type and operand type and determine a weight value.
16580 /// This object must already have been set up with the operand type
16581 /// and the current alternative constraint selected.
16582 TargetLowering::ConstraintWeight
16583 ARMTargetLowering::getSingleConstraintMatchWeight(
16584     AsmOperandInfo &info, const char *constraint) const {
16585   ConstraintWeight weight = CW_Invalid;
16586   Value *CallOperandVal = info.CallOperandVal;
16587     // If we don't have a value, we can't do a match,
16588     // but allow it at the lowest weight.
16589   if (!CallOperandVal)
16590     return CW_Default;
16591   Type *type = CallOperandVal->getType();
16592   // Look at the constraint type.
16593   switch (*constraint) {
16594   default:
16595     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
16596     break;
16597   case 'l':
16598     if (type->isIntegerTy()) {
16599       if (Subtarget->isThumb())
16600         weight = CW_SpecificReg;
16601       else
16602         weight = CW_Register;
16603     }
16604     break;
16605   case 'w':
16606     if (type->isFloatingPointTy())
16607       weight = CW_Register;
16608     break;
16609   }
16610   return weight;
16611 }
16612 
16613 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
16614 
16615 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
16616     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
16617   switch (Constraint.size()) {
16618   case 1:
16619     // GCC ARM Constraint Letters
16620     switch (Constraint[0]) {
16621     case 'l': // Low regs or general regs.
16622       if (Subtarget->isThumb())
16623         return RCPair(0U, &ARM::tGPRRegClass);
16624       return RCPair(0U, &ARM::GPRRegClass);
16625     case 'h': // High regs or no regs.
16626       if (Subtarget->isThumb())
16627         return RCPair(0U, &ARM::hGPRRegClass);
16628       break;
16629     case 'r':
16630       if (Subtarget->isThumb1Only())
16631         return RCPair(0U, &ARM::tGPRRegClass);
16632       return RCPair(0U, &ARM::GPRRegClass);
16633     case 'w':
16634       if (VT == MVT::Other)
16635         break;
16636       if (VT == MVT::f32)
16637         return RCPair(0U, &ARM::SPRRegClass);
16638       if (VT.getSizeInBits() == 64)
16639         return RCPair(0U, &ARM::DPRRegClass);
16640       if (VT.getSizeInBits() == 128)
16641         return RCPair(0U, &ARM::QPRRegClass);
16642       break;
16643     case 'x':
16644       if (VT == MVT::Other)
16645         break;
16646       if (VT == MVT::f32)
16647         return RCPair(0U, &ARM::SPR_8RegClass);
16648       if (VT.getSizeInBits() == 64)
16649         return RCPair(0U, &ARM::DPR_8RegClass);
16650       if (VT.getSizeInBits() == 128)
16651         return RCPair(0U, &ARM::QPR_8RegClass);
16652       break;
16653     case 't':
16654       if (VT == MVT::Other)
16655         break;
16656       if (VT == MVT::f32 || VT == MVT::i32)
16657         return RCPair(0U, &ARM::SPRRegClass);
16658       if (VT.getSizeInBits() == 64)
16659         return RCPair(0U, &ARM::DPR_VFP2RegClass);
16660       if (VT.getSizeInBits() == 128)
16661         return RCPair(0U, &ARM::QPR_VFP2RegClass);
16662       break;
16663     }
16664     break;
16665 
16666   case 2:
16667     if (Constraint[0] == 'T') {
16668       switch (Constraint[1]) {
16669       default:
16670         break;
16671       case 'e':
16672         return RCPair(0U, &ARM::tGPREvenRegClass);
16673       case 'o':
16674         return RCPair(0U, &ARM::tGPROddRegClass);
16675       }
16676     }
16677     break;
16678 
16679   default:
16680     break;
16681   }
16682 
16683   if (StringRef("{cc}").equals_lower(Constraint))
16684     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
16685 
16686   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
16687 }
16688 
16689 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
16690 /// vector.  If it is invalid, don't add anything to Ops.
16691 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
16692                                                      std::string &Constraint,
16693                                                      std::vector<SDValue>&Ops,
16694                                                      SelectionDAG &DAG) const {
16695   SDValue Result;
16696 
16697   // Currently only support length 1 constraints.
16698   if (Constraint.length() != 1) return;
16699 
16700   char ConstraintLetter = Constraint[0];
16701   switch (ConstraintLetter) {
16702   default: break;
16703   case 'j':
16704   case 'I': case 'J': case 'K': case 'L':
16705   case 'M': case 'N': case 'O':
16706     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
16707     if (!C)
16708       return;
16709 
16710     int64_t CVal64 = C->getSExtValue();
16711     int CVal = (int) CVal64;
16712     // None of these constraints allow values larger than 32 bits.  Check
16713     // that the value fits in an int.
16714     if (CVal != CVal64)
16715       return;
16716 
16717     switch (ConstraintLetter) {
16718       case 'j':
16719         // Constant suitable for movw, must be between 0 and
16720         // 65535.
16721         if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
16722           if (CVal >= 0 && CVal <= 65535)
16723             break;
16724         return;
16725       case 'I':
16726         if (Subtarget->isThumb1Only()) {
16727           // This must be a constant between 0 and 255, for ADD
16728           // immediates.
16729           if (CVal >= 0 && CVal <= 255)
16730             break;
16731         } else if (Subtarget->isThumb2()) {
16732           // A constant that can be used as an immediate value in a
16733           // data-processing instruction.
16734           if (ARM_AM::getT2SOImmVal(CVal) != -1)
16735             break;
16736         } else {
16737           // A constant that can be used as an immediate value in a
16738           // data-processing instruction.
16739           if (ARM_AM::getSOImmVal(CVal) != -1)
16740             break;
16741         }
16742         return;
16743 
16744       case 'J':
16745         if (Subtarget->isThumb1Only()) {
16746           // This must be a constant between -255 and -1, for negated ADD
16747           // immediates. This can be used in GCC with an "n" modifier that
16748           // prints the negated value, for use with SUB instructions. It is
16749           // not useful otherwise but is implemented for compatibility.
16750           if (CVal >= -255 && CVal <= -1)
16751             break;
16752         } else {
16753           // This must be a constant between -4095 and 4095. It is not clear
16754           // what this constraint is intended for. Implemented for
16755           // compatibility with GCC.
16756           if (CVal >= -4095 && CVal <= 4095)
16757             break;
16758         }
16759         return;
16760 
16761       case 'K':
16762         if (Subtarget->isThumb1Only()) {
16763           // A 32-bit value where only one byte has a nonzero value. Exclude
16764           // zero to match GCC. This constraint is used by GCC internally for
16765           // constants that can be loaded with a move/shift combination.
16766           // It is not useful otherwise but is implemented for compatibility.
16767           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
16768             break;
16769         } else if (Subtarget->isThumb2()) {
16770           // A constant whose bitwise inverse can be used as an immediate
16771           // value in a data-processing instruction. This can be used in GCC
16772           // with a "B" modifier that prints the inverted value, for use with
16773           // BIC and MVN instructions. It is not useful otherwise but is
16774           // implemented for compatibility.
16775           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
16776             break;
16777         } else {
16778           // A constant whose bitwise inverse can be used as an immediate
16779           // value in a data-processing instruction. This can be used in GCC
16780           // with a "B" modifier that prints the inverted value, for use with
16781           // BIC and MVN instructions. It is not useful otherwise but is
16782           // implemented for compatibility.
16783           if (ARM_AM::getSOImmVal(~CVal) != -1)
16784             break;
16785         }
16786         return;
16787 
16788       case 'L':
16789         if (Subtarget->isThumb1Only()) {
16790           // This must be a constant between -7 and 7,
16791           // for 3-operand ADD/SUB immediate instructions.
16792           if (CVal >= -7 && CVal < 7)
16793             break;
16794         } else if (Subtarget->isThumb2()) {
16795           // A constant whose negation can be used as an immediate value in a
16796           // data-processing instruction. This can be used in GCC with an "n"
16797           // modifier that prints the negated value, for use with SUB
16798           // instructions. It is not useful otherwise but is implemented for
16799           // compatibility.
16800           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
16801             break;
16802         } else {
16803           // A constant whose negation can be used as an immediate value in a
16804           // data-processing instruction. This can be used in GCC with an "n"
16805           // modifier that prints the negated value, for use with SUB
16806           // instructions. It is not useful otherwise but is implemented for
16807           // compatibility.
16808           if (ARM_AM::getSOImmVal(-CVal) != -1)
16809             break;
16810         }
16811         return;
16812 
16813       case 'M':
16814         if (Subtarget->isThumb1Only()) {
16815           // This must be a multiple of 4 between 0 and 1020, for
16816           // ADD sp + immediate.
16817           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
16818             break;
16819         } else {
16820           // A power of two or a constant between 0 and 32.  This is used in
16821           // GCC for the shift amount on shifted register operands, but it is
16822           // useful in general for any shift amounts.
16823           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
16824             break;
16825         }
16826         return;
16827 
16828       case 'N':
16829         if (Subtarget->isThumb1Only()) {
16830           // This must be a constant between 0 and 31, for shift amounts.
16831           if (CVal >= 0 && CVal <= 31)
16832             break;
16833         }
16834         return;
16835 
16836       case 'O':
16837         if (Subtarget->isThumb1Only()) {
16838           // This must be a multiple of 4 between -508 and 508, for
16839           // ADD/SUB sp = sp + immediate.
16840           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
16841             break;
16842         }
16843         return;
16844     }
16845     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
16846     break;
16847   }
16848 
16849   if (Result.getNode()) {
16850     Ops.push_back(Result);
16851     return;
16852   }
16853   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16854 }
16855 
16856 static RTLIB::Libcall getDivRemLibcall(
16857     const SDNode *N, MVT::SimpleValueType SVT) {
16858   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
16859           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
16860          "Unhandled Opcode in getDivRemLibcall");
16861   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
16862                   N->getOpcode() == ISD::SREM;
16863   RTLIB::Libcall LC;
16864   switch (SVT) {
16865   default: llvm_unreachable("Unexpected request for libcall!");
16866   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
16867   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
16868   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
16869   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
16870   }
16871   return LC;
16872 }
16873 
16874 static TargetLowering::ArgListTy getDivRemArgList(
16875     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
16876   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
16877           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
16878          "Unhandled Opcode in getDivRemArgList");
16879   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
16880                   N->getOpcode() == ISD::SREM;
16881   TargetLowering::ArgListTy Args;
16882   TargetLowering::ArgListEntry Entry;
16883   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
16884     EVT ArgVT = N->getOperand(i).getValueType();
16885     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
16886     Entry.Node = N->getOperand(i);
16887     Entry.Ty = ArgTy;
16888     Entry.IsSExt = isSigned;
16889     Entry.IsZExt = !isSigned;
16890     Args.push_back(Entry);
16891   }
16892   if (Subtarget->isTargetWindows() && Args.size() >= 2)
16893     std::swap(Args[0], Args[1]);
16894   return Args;
16895 }
16896 
16897 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
16898   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
16899           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
16900           Subtarget->isTargetWindows()) &&
16901          "Register-based DivRem lowering only");
16902   unsigned Opcode = Op->getOpcode();
16903   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
16904          "Invalid opcode for Div/Rem lowering");
16905   bool isSigned = (Opcode == ISD::SDIVREM);
16906   EVT VT = Op->getValueType(0);
16907   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
16908   SDLoc dl(Op);
16909 
16910   // If the target has hardware divide, use divide + multiply + subtract:
16911   //     div = a / b
16912   //     rem = a - b * div
16913   //     return {div, rem}
16914   // This should be lowered into UDIV/SDIV + MLS later on.
16915   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
16916                                         : Subtarget->hasDivideInARMMode();
16917   if (hasDivide && Op->getValueType(0).isSimple() &&
16918       Op->getSimpleValueType(0) == MVT::i32) {
16919     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
16920     const SDValue Dividend = Op->getOperand(0);
16921     const SDValue Divisor = Op->getOperand(1);
16922     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
16923     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
16924     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
16925 
16926     SDValue Values[2] = {Div, Rem};
16927     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
16928   }
16929 
16930   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
16931                                        VT.getSimpleVT().SimpleTy);
16932   SDValue InChain = DAG.getEntryNode();
16933 
16934   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
16935                                                     DAG.getContext(),
16936                                                     Subtarget);
16937 
16938   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16939                                          getPointerTy(DAG.getDataLayout()));
16940 
16941   Type *RetTy = StructType::get(Ty, Ty);
16942 
16943   if (Subtarget->isTargetWindows())
16944     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
16945 
16946   TargetLowering::CallLoweringInfo CLI(DAG);
16947   CLI.setDebugLoc(dl).setChain(InChain)
16948     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
16949     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16950 
16951   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16952   return CallInfo.first;
16953 }
16954 
16955 // Lowers REM using divmod helpers
16956 // see RTABI section 4.2/4.3
16957 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
16958   // Build return types (div and rem)
16959   std::vector<Type*> RetTyParams;
16960   Type *RetTyElement;
16961 
16962   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
16963   default: llvm_unreachable("Unexpected request for libcall!");
16964   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
16965   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
16966   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
16967   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
16968   }
16969 
16970   RetTyParams.push_back(RetTyElement);
16971   RetTyParams.push_back(RetTyElement);
16972   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
16973   Type *RetTy = StructType::get(*DAG.getContext(), ret);
16974 
16975   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
16976                                                              SimpleTy);
16977   SDValue InChain = DAG.getEntryNode();
16978   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
16979                                                     Subtarget);
16980   bool isSigned = N->getOpcode() == ISD::SREM;
16981   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16982                                          getPointerTy(DAG.getDataLayout()));
16983 
16984   if (Subtarget->isTargetWindows())
16985     InChain = WinDBZCheckDenominator(DAG, N, InChain);
16986 
16987   // Lower call
16988   CallLoweringInfo CLI(DAG);
16989   CLI.setChain(InChain)
16990      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
16991      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
16992   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
16993 
16994   // Return second (rem) result operand (first contains div)
16995   SDNode *ResNode = CallResult.first.getNode();
16996   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
16997   return ResNode->getOperand(1);
16998 }
16999 
17000 SDValue
17001 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
17002   assert(Subtarget->isTargetWindows() && "unsupported target platform");
17003   SDLoc DL(Op);
17004 
17005   // Get the inputs.
17006   SDValue Chain = Op.getOperand(0);
17007   SDValue Size  = Op.getOperand(1);
17008 
17009   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
17010           "no-stack-arg-probe")) {
17011     unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
17012     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
17013     Chain = SP.getValue(1);
17014     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
17015     if (Align)
17016       SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
17017                        DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
17018     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
17019     SDValue Ops[2] = { SP, Chain };
17020     return DAG.getMergeValues(Ops, DL);
17021   }
17022 
17023   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
17024                               DAG.getConstant(2, DL, MVT::i32));
17025 
17026   SDValue Flag;
17027   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
17028   Flag = Chain.getValue(1);
17029 
17030   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
17031   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
17032 
17033   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
17034   Chain = NewSP.getValue(1);
17035 
17036   SDValue Ops[2] = { NewSP, Chain };
17037   return DAG.getMergeValues(Ops, DL);
17038 }
17039 
17040 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
17041   bool IsStrict = Op->isStrictFPOpcode();
17042   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
17043   const unsigned DstSz = Op.getValueType().getSizeInBits();
17044   const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
17045   assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
17046          "Unexpected type for custom-lowering FP_EXTEND");
17047 
17048   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
17049          "With both FP DP and 16, any FP conversion is legal!");
17050 
17051   assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
17052          "With FP16, 16 to 32 conversion is legal!");
17053 
17054   // Converting from 32 -> 64 is valid if we have FP64.
17055   if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
17056     // FIXME: Remove this when we have strict fp instruction selection patterns
17057     if (IsStrict) {
17058       SDLoc Loc(Op);
17059       SDValue Result = DAG.getNode(ISD::FP_EXTEND,
17060                                    Loc, Op.getValueType(), SrcVal);
17061       return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
17062     }
17063     return Op;
17064   }
17065 
17066   // Either we are converting from 16 -> 64, without FP16 and/or
17067   // FP.double-precision or without Armv8-fp. So we must do it in two
17068   // steps.
17069   // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
17070   // without FP16. So we must do a function call.
17071   SDLoc Loc(Op);
17072   RTLIB::Libcall LC;
17073   MakeLibCallOptions CallOptions;
17074   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
17075   for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
17076     bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
17077     MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
17078     MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
17079     if (Supported) {
17080       if (IsStrict) {
17081         SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
17082                              {DstVT, MVT::Other}, {Chain, SrcVal});
17083         Chain = SrcVal.getValue(1);
17084       } else {
17085         SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
17086       }
17087     } else {
17088       LC = RTLIB::getFPEXT(SrcVT, DstVT);
17089       assert(LC != RTLIB::UNKNOWN_LIBCALL &&
17090              "Unexpected type for custom-lowering FP_EXTEND");
17091       std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
17092                                             Loc, Chain);
17093     }
17094   }
17095 
17096   return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
17097 }
17098 
17099 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
17100   bool IsStrict = Op->isStrictFPOpcode();
17101 
17102   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
17103   EVT SrcVT = SrcVal.getValueType();
17104   EVT DstVT = Op.getValueType();
17105   const unsigned DstSz = Op.getValueType().getSizeInBits();
17106   const unsigned SrcSz = SrcVT.getSizeInBits();
17107   (void)DstSz;
17108   assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
17109          "Unexpected type for custom-lowering FP_ROUND");
17110 
17111   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
17112          "With both FP DP and 16, any FP conversion is legal!");
17113 
17114   SDLoc Loc(Op);
17115 
17116   // Instruction from 32 -> 16 if hasFP16 is valid
17117   if (SrcSz == 32 && Subtarget->hasFP16())
17118     return Op;
17119 
17120   // Lib call from 32 -> 16 / 64 -> [32, 16]
17121   RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
17122   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
17123          "Unexpected type for custom-lowering FP_ROUND");
17124   MakeLibCallOptions CallOptions;
17125   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
17126   SDValue Result;
17127   std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
17128                                         Loc, Chain);
17129   return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
17130 }
17131 
17132 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
17133                                  SelectionDAG &DAG) const {
17134   assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
17135   MVT HalfT = MVT::i32;
17136   SDLoc dl(N);
17137   SDValue Hi, Lo, Tmp;
17138 
17139   if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
17140       !isOperationLegalOrCustom(ISD::UADDO, HalfT))
17141     return ;
17142 
17143   unsigned OpTypeBits = HalfT.getScalarSizeInBits();
17144   SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
17145 
17146   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
17147                    DAG.getConstant(0, dl, HalfT));
17148   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
17149                    DAG.getConstant(1, dl, HalfT));
17150 
17151   Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
17152                     DAG.getConstant(OpTypeBits - 1, dl,
17153                     getShiftAmountTy(HalfT, DAG.getDataLayout())));
17154   Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
17155   Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
17156                    SDValue(Lo.getNode(), 1));
17157   Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
17158   Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
17159 
17160   Results.push_back(Lo);
17161   Results.push_back(Hi);
17162 }
17163 
17164 bool
17165 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
17166   // The ARM target isn't yet aware of offsets.
17167   return false;
17168 }
17169 
17170 bool ARM::isBitFieldInvertedMask(unsigned v) {
17171   if (v == 0xffffffff)
17172     return false;
17173 
17174   // there can be 1's on either or both "outsides", all the "inside"
17175   // bits must be 0's
17176   return isShiftedMask_32(~v);
17177 }
17178 
17179 /// isFPImmLegal - Returns true if the target can instruction select the
17180 /// specified FP immediate natively. If false, the legalizer will
17181 /// materialize the FP immediate as a load from a constant pool.
17182 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
17183                                      bool ForCodeSize) const {
17184   if (!Subtarget->hasVFP3Base())
17185     return false;
17186   if (VT == MVT::f16 && Subtarget->hasFullFP16())
17187     return ARM_AM::getFP16Imm(Imm) != -1;
17188   if (VT == MVT::f32)
17189     return ARM_AM::getFP32Imm(Imm) != -1;
17190   if (VT == MVT::f64 && Subtarget->hasFP64())
17191     return ARM_AM::getFP64Imm(Imm) != -1;
17192   return false;
17193 }
17194 
17195 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
17196 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
17197 /// specified in the intrinsic calls.
17198 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
17199                                            const CallInst &I,
17200                                            MachineFunction &MF,
17201                                            unsigned Intrinsic) const {
17202   switch (Intrinsic) {
17203   case Intrinsic::arm_neon_vld1:
17204   case Intrinsic::arm_neon_vld2:
17205   case Intrinsic::arm_neon_vld3:
17206   case Intrinsic::arm_neon_vld4:
17207   case Intrinsic::arm_neon_vld2lane:
17208   case Intrinsic::arm_neon_vld3lane:
17209   case Intrinsic::arm_neon_vld4lane:
17210   case Intrinsic::arm_neon_vld2dup:
17211   case Intrinsic::arm_neon_vld3dup:
17212   case Intrinsic::arm_neon_vld4dup: {
17213     Info.opc = ISD::INTRINSIC_W_CHAIN;
17214     // Conservatively set memVT to the entire set of vectors loaded.
17215     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17216     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
17217     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
17218     Info.ptrVal = I.getArgOperand(0);
17219     Info.offset = 0;
17220     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
17221     Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
17222     // volatile loads with NEON intrinsics not supported
17223     Info.flags = MachineMemOperand::MOLoad;
17224     return true;
17225   }
17226   case Intrinsic::arm_neon_vld1x2:
17227   case Intrinsic::arm_neon_vld1x3:
17228   case Intrinsic::arm_neon_vld1x4: {
17229     Info.opc = ISD::INTRINSIC_W_CHAIN;
17230     // Conservatively set memVT to the entire set of vectors loaded.
17231     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17232     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
17233     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
17234     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
17235     Info.offset = 0;
17236     Info.align.reset();
17237     // volatile loads with NEON intrinsics not supported
17238     Info.flags = MachineMemOperand::MOLoad;
17239     return true;
17240   }
17241   case Intrinsic::arm_neon_vst1:
17242   case Intrinsic::arm_neon_vst2:
17243   case Intrinsic::arm_neon_vst3:
17244   case Intrinsic::arm_neon_vst4:
17245   case Intrinsic::arm_neon_vst2lane:
17246   case Intrinsic::arm_neon_vst3lane:
17247   case Intrinsic::arm_neon_vst4lane: {
17248     Info.opc = ISD::INTRINSIC_VOID;
17249     // Conservatively set memVT to the entire set of vectors stored.
17250     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17251     unsigned NumElts = 0;
17252     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
17253       Type *ArgTy = I.getArgOperand(ArgI)->getType();
17254       if (!ArgTy->isVectorTy())
17255         break;
17256       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
17257     }
17258     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
17259     Info.ptrVal = I.getArgOperand(0);
17260     Info.offset = 0;
17261     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
17262     Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
17263     // volatile stores with NEON intrinsics not supported
17264     Info.flags = MachineMemOperand::MOStore;
17265     return true;
17266   }
17267   case Intrinsic::arm_neon_vst1x2:
17268   case Intrinsic::arm_neon_vst1x3:
17269   case Intrinsic::arm_neon_vst1x4: {
17270     Info.opc = ISD::INTRINSIC_VOID;
17271     // Conservatively set memVT to the entire set of vectors stored.
17272     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17273     unsigned NumElts = 0;
17274     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
17275       Type *ArgTy = I.getArgOperand(ArgI)->getType();
17276       if (!ArgTy->isVectorTy())
17277         break;
17278       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
17279     }
17280     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
17281     Info.ptrVal = I.getArgOperand(0);
17282     Info.offset = 0;
17283     Info.align.reset();
17284     // volatile stores with NEON intrinsics not supported
17285     Info.flags = MachineMemOperand::MOStore;
17286     return true;
17287   }
17288   case Intrinsic::arm_mve_vld2q:
17289   case Intrinsic::arm_mve_vld4q: {
17290     Info.opc = ISD::INTRINSIC_W_CHAIN;
17291     // Conservatively set memVT to the entire set of vectors loaded.
17292     Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
17293     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
17294     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
17295     Info.ptrVal = I.getArgOperand(0);
17296     Info.offset = 0;
17297     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
17298     // volatile loads with MVE intrinsics not supported
17299     Info.flags = MachineMemOperand::MOLoad;
17300     return true;
17301   }
17302   case Intrinsic::arm_mve_vst2q:
17303   case Intrinsic::arm_mve_vst4q: {
17304     Info.opc = ISD::INTRINSIC_VOID;
17305     // Conservatively set memVT to the entire set of vectors stored.
17306     Type *VecTy = I.getArgOperand(1)->getType();
17307     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
17308     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
17309     Info.ptrVal = I.getArgOperand(0);
17310     Info.offset = 0;
17311     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
17312     // volatile stores with MVE intrinsics not supported
17313     Info.flags = MachineMemOperand::MOStore;
17314     return true;
17315   }
17316   case Intrinsic::arm_ldaex:
17317   case Intrinsic::arm_ldrex: {
17318     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17319     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
17320     Info.opc = ISD::INTRINSIC_W_CHAIN;
17321     Info.memVT = MVT::getVT(PtrTy->getElementType());
17322     Info.ptrVal = I.getArgOperand(0);
17323     Info.offset = 0;
17324     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
17325     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
17326     return true;
17327   }
17328   case Intrinsic::arm_stlex:
17329   case Intrinsic::arm_strex: {
17330     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
17331     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
17332     Info.opc = ISD::INTRINSIC_W_CHAIN;
17333     Info.memVT = MVT::getVT(PtrTy->getElementType());
17334     Info.ptrVal = I.getArgOperand(1);
17335     Info.offset = 0;
17336     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
17337     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
17338     return true;
17339   }
17340   case Intrinsic::arm_stlexd:
17341   case Intrinsic::arm_strexd:
17342     Info.opc = ISD::INTRINSIC_W_CHAIN;
17343     Info.memVT = MVT::i64;
17344     Info.ptrVal = I.getArgOperand(2);
17345     Info.offset = 0;
17346     Info.align = Align(8);
17347     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
17348     return true;
17349 
17350   case Intrinsic::arm_ldaexd:
17351   case Intrinsic::arm_ldrexd:
17352     Info.opc = ISD::INTRINSIC_W_CHAIN;
17353     Info.memVT = MVT::i64;
17354     Info.ptrVal = I.getArgOperand(0);
17355     Info.offset = 0;
17356     Info.align = Align(8);
17357     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
17358     return true;
17359 
17360   default:
17361     break;
17362   }
17363 
17364   return false;
17365 }
17366 
17367 /// Returns true if it is beneficial to convert a load of a constant
17368 /// to just the constant itself.
17369 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
17370                                                           Type *Ty) const {
17371   assert(Ty->isIntegerTy());
17372 
17373   unsigned Bits = Ty->getPrimitiveSizeInBits();
17374   if (Bits == 0 || Bits > 32)
17375     return false;
17376   return true;
17377 }
17378 
17379 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
17380                                                 unsigned Index) const {
17381   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
17382     return false;
17383 
17384   return (Index == 0 || Index == ResVT.getVectorNumElements());
17385 }
17386 
17387 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
17388                                         ARM_MB::MemBOpt Domain) const {
17389   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17390 
17391   // First, if the target has no DMB, see what fallback we can use.
17392   if (!Subtarget->hasDataBarrier()) {
17393     // Some ARMv6 cpus can support data barriers with an mcr instruction.
17394     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
17395     // here.
17396     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
17397       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
17398       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
17399                         Builder.getInt32(0), Builder.getInt32(7),
17400                         Builder.getInt32(10), Builder.getInt32(5)};
17401       return Builder.CreateCall(MCR, args);
17402     } else {
17403       // Instead of using barriers, atomic accesses on these subtargets use
17404       // libcalls.
17405       llvm_unreachable("makeDMB on a target so old that it has no barriers");
17406     }
17407   } else {
17408     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
17409     // Only a full system barrier exists in the M-class architectures.
17410     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
17411     Constant *CDomain = Builder.getInt32(Domain);
17412     return Builder.CreateCall(DMB, CDomain);
17413   }
17414 }
17415 
17416 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
17417 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
17418                                                  Instruction *Inst,
17419                                                  AtomicOrdering Ord) const {
17420   switch (Ord) {
17421   case AtomicOrdering::NotAtomic:
17422   case AtomicOrdering::Unordered:
17423     llvm_unreachable("Invalid fence: unordered/non-atomic");
17424   case AtomicOrdering::Monotonic:
17425   case AtomicOrdering::Acquire:
17426     return nullptr; // Nothing to do
17427   case AtomicOrdering::SequentiallyConsistent:
17428     if (!Inst->hasAtomicStore())
17429       return nullptr; // Nothing to do
17430     LLVM_FALLTHROUGH;
17431   case AtomicOrdering::Release:
17432   case AtomicOrdering::AcquireRelease:
17433     if (Subtarget->preferISHSTBarriers())
17434       return makeDMB(Builder, ARM_MB::ISHST);
17435     // FIXME: add a comment with a link to documentation justifying this.
17436     else
17437       return makeDMB(Builder, ARM_MB::ISH);
17438   }
17439   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
17440 }
17441 
17442 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
17443                                                   Instruction *Inst,
17444                                                   AtomicOrdering Ord) const {
17445   switch (Ord) {
17446   case AtomicOrdering::NotAtomic:
17447   case AtomicOrdering::Unordered:
17448     llvm_unreachable("Invalid fence: unordered/not-atomic");
17449   case AtomicOrdering::Monotonic:
17450   case AtomicOrdering::Release:
17451     return nullptr; // Nothing to do
17452   case AtomicOrdering::Acquire:
17453   case AtomicOrdering::AcquireRelease:
17454   case AtomicOrdering::SequentiallyConsistent:
17455     return makeDMB(Builder, ARM_MB::ISH);
17456   }
17457   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
17458 }
17459 
17460 // Loads and stores less than 64-bits are already atomic; ones above that
17461 // are doomed anyway, so defer to the default libcall and blame the OS when
17462 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
17463 // anything for those.
17464 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17465   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
17466   return (Size == 64) && !Subtarget->isMClass();
17467 }
17468 
17469 // Loads and stores less than 64-bits are already atomic; ones above that
17470 // are doomed anyway, so defer to the default libcall and blame the OS when
17471 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
17472 // anything for those.
17473 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
17474 // guarantee, see DDI0406C ARM architecture reference manual,
17475 // sections A8.8.72-74 LDRD)
17476 TargetLowering::AtomicExpansionKind
17477 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17478   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
17479   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
17480                                                   : AtomicExpansionKind::None;
17481 }
17482 
17483 // For the real atomic operations, we have ldrex/strex up to 32 bits,
17484 // and up to 64 bits on the non-M profiles
17485 TargetLowering::AtomicExpansionKind
17486 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17487   if (AI->isFloatingPointOperation())
17488     return AtomicExpansionKind::CmpXChg;
17489 
17490   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
17491   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
17492   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
17493              ? AtomicExpansionKind::LLSC
17494              : AtomicExpansionKind::None;
17495 }
17496 
17497 TargetLowering::AtomicExpansionKind
17498 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
17499   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
17500   // implement cmpxchg without spilling. If the address being exchanged is also
17501   // on the stack and close enough to the spill slot, this can lead to a
17502   // situation where the monitor always gets cleared and the atomic operation
17503   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
17504   bool HasAtomicCmpXchg =
17505       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
17506   if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
17507     return AtomicExpansionKind::LLSC;
17508   return AtomicExpansionKind::None;
17509 }
17510 
17511 bool ARMTargetLowering::shouldInsertFencesForAtomic(
17512     const Instruction *I) const {
17513   return InsertFencesForAtomic;
17514 }
17515 
17516 // This has so far only been implemented for MachO.
17517 bool ARMTargetLowering::useLoadStackGuardNode() const {
17518   return Subtarget->isTargetMachO();
17519 }
17520 
17521 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
17522   if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
17523     return TargetLowering::insertSSPDeclarations(M);
17524 
17525   // MSVC CRT has a global variable holding security cookie.
17526   M.getOrInsertGlobal("__security_cookie",
17527                       Type::getInt8PtrTy(M.getContext()));
17528 
17529   // MSVC CRT has a function to validate security cookie.
17530   FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
17531       "__security_check_cookie", Type::getVoidTy(M.getContext()),
17532       Type::getInt8PtrTy(M.getContext()));
17533   if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
17534     F->addAttribute(1, Attribute::AttrKind::InReg);
17535 }
17536 
17537 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
17538   // MSVC CRT has a global variable holding security cookie.
17539   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
17540     return M.getGlobalVariable("__security_cookie");
17541   return TargetLowering::getSDagStackGuard(M);
17542 }
17543 
17544 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
17545   // MSVC CRT has a function to validate security cookie.
17546   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
17547     return M.getFunction("__security_check_cookie");
17548   return TargetLowering::getSSPStackGuardCheck(M);
17549 }
17550 
17551 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
17552                                                   unsigned &Cost) const {
17553   // If we do not have NEON, vector types are not natively supported.
17554   if (!Subtarget->hasNEON())
17555     return false;
17556 
17557   // Floating point values and vector values map to the same register file.
17558   // Therefore, although we could do a store extract of a vector type, this is
17559   // better to leave at float as we have more freedom in the addressing mode for
17560   // those.
17561   if (VectorTy->isFPOrFPVectorTy())
17562     return false;
17563 
17564   // If the index is unknown at compile time, this is very expensive to lower
17565   // and it is not possible to combine the store with the extract.
17566   if (!isa<ConstantInt>(Idx))
17567     return false;
17568 
17569   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
17570   unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize();
17571   // We can do a store + vector extract on any vector that fits perfectly in a D
17572   // or Q register.
17573   if (BitWidth == 64 || BitWidth == 128) {
17574     Cost = 0;
17575     return true;
17576   }
17577   return false;
17578 }
17579 
17580 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
17581   return Subtarget->hasV6T2Ops();
17582 }
17583 
17584 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
17585   return Subtarget->hasV6T2Ops();
17586 }
17587 
17588 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
17589   return !Subtarget->hasMinSize() || Subtarget->isTargetWindows();
17590 }
17591 
17592 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
17593                                          AtomicOrdering Ord) const {
17594   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17595   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
17596   bool IsAcquire = isAcquireOrStronger(Ord);
17597 
17598   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
17599   // intrinsic must return {i32, i32} and we have to recombine them into a
17600   // single i64 here.
17601   if (ValTy->getPrimitiveSizeInBits() == 64) {
17602     Intrinsic::ID Int =
17603         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
17604     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
17605 
17606     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
17607     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
17608 
17609     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
17610     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
17611     if (!Subtarget->isLittle())
17612       std::swap (Lo, Hi);
17613     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
17614     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
17615     return Builder.CreateOr(
17616         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
17617   }
17618 
17619   Type *Tys[] = { Addr->getType() };
17620   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
17621   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
17622 
17623   return Builder.CreateTruncOrBitCast(
17624       Builder.CreateCall(Ldrex, Addr),
17625       cast<PointerType>(Addr->getType())->getElementType());
17626 }
17627 
17628 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
17629     IRBuilder<> &Builder) const {
17630   if (!Subtarget->hasV7Ops())
17631     return;
17632   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17633   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
17634 }
17635 
17636 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
17637                                                Value *Addr,
17638                                                AtomicOrdering Ord) const {
17639   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17640   bool IsRelease = isReleaseOrStronger(Ord);
17641 
17642   // Since the intrinsics must have legal type, the i64 intrinsics take two
17643   // parameters: "i32, i32". We must marshal Val into the appropriate form
17644   // before the call.
17645   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
17646     Intrinsic::ID Int =
17647         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
17648     Function *Strex = Intrinsic::getDeclaration(M, Int);
17649     Type *Int32Ty = Type::getInt32Ty(M->getContext());
17650 
17651     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
17652     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
17653     if (!Subtarget->isLittle())
17654       std::swap(Lo, Hi);
17655     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
17656     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
17657   }
17658 
17659   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
17660   Type *Tys[] = { Addr->getType() };
17661   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
17662 
17663   return Builder.CreateCall(
17664       Strex, {Builder.CreateZExtOrBitCast(
17665                   Val, Strex->getFunctionType()->getParamType(0)),
17666               Addr});
17667 }
17668 
17669 
17670 bool ARMTargetLowering::alignLoopsWithOptSize() const {
17671   return Subtarget->isMClass();
17672 }
17673 
17674 /// A helper function for determining the number of interleaved accesses we
17675 /// will generate when lowering accesses of the given type.
17676 unsigned
17677 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
17678                                              const DataLayout &DL) const {
17679   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
17680 }
17681 
17682 bool ARMTargetLowering::isLegalInterleavedAccessType(
17683     unsigned Factor, VectorType *VecTy, const DataLayout &DL) const {
17684 
17685   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
17686   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
17687 
17688   if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
17689     return false;
17690 
17691   // Ensure the vector doesn't have f16 elements. Even though we could do an
17692   // i16 vldN, we can't hold the f16 vectors and will end up converting via
17693   // f32.
17694   if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
17695     return false;
17696   if (Subtarget->hasMVEIntegerOps() && Factor == 3)
17697     return false;
17698 
17699   // Ensure the number of vector elements is greater than 1.
17700   if (VecTy->getNumElements() < 2)
17701     return false;
17702 
17703   // Ensure the element type is legal.
17704   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
17705     return false;
17706 
17707   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
17708   // 128 will be split into multiple interleaved accesses.
17709   if (Subtarget->hasNEON() && VecSize == 64)
17710     return true;
17711   return VecSize % 128 == 0;
17712 }
17713 
17714 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
17715   if (Subtarget->hasNEON())
17716     return 4;
17717   if (Subtarget->hasMVEIntegerOps())
17718     return MVEMaxSupportedInterleaveFactor;
17719   return TargetLoweringBase::getMaxSupportedInterleaveFactor();
17720 }
17721 
17722 /// Lower an interleaved load into a vldN intrinsic.
17723 ///
17724 /// E.g. Lower an interleaved load (Factor = 2):
17725 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
17726 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
17727 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
17728 ///
17729 ///      Into:
17730 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
17731 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
17732 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
17733 bool ARMTargetLowering::lowerInterleavedLoad(
17734     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
17735     ArrayRef<unsigned> Indices, unsigned Factor) const {
17736   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
17737          "Invalid interleave factor");
17738   assert(!Shuffles.empty() && "Empty shufflevector input");
17739   assert(Shuffles.size() == Indices.size() &&
17740          "Unmatched number of shufflevectors and indices");
17741 
17742   VectorType *VecTy = Shuffles[0]->getType();
17743   Type *EltTy = VecTy->getElementType();
17744 
17745   const DataLayout &DL = LI->getModule()->getDataLayout();
17746 
17747   // Skip if we do not have NEON and skip illegal vector types. We can
17748   // "legalize" wide vector types into multiple interleaved accesses as long as
17749   // the vector types are divisible by 128.
17750   if (!isLegalInterleavedAccessType(Factor, VecTy, DL))
17751     return false;
17752 
17753   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
17754 
17755   // A pointer vector can not be the return type of the ldN intrinsics. Need to
17756   // load integer vectors first and then convert to pointer vectors.
17757   if (EltTy->isPointerTy())
17758     VecTy = VectorType::get(DL.getIntPtrType(EltTy), VecTy->getNumElements());
17759 
17760   IRBuilder<> Builder(LI);
17761 
17762   // The base address of the load.
17763   Value *BaseAddr = LI->getPointerOperand();
17764 
17765   if (NumLoads > 1) {
17766     // If we're going to generate more than one load, reset the sub-vector type
17767     // to something legal.
17768     VecTy = VectorType::get(VecTy->getElementType(),
17769                             VecTy->getNumElements() / NumLoads);
17770 
17771     // We will compute the pointer operand of each load from the original base
17772     // address using GEPs. Cast the base address to a pointer to the scalar
17773     // element type.
17774     BaseAddr = Builder.CreateBitCast(
17775         BaseAddr,
17776         VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
17777   }
17778 
17779   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
17780 
17781   auto createLoadIntrinsic = [&](Value *BaseAddr) {
17782     if (Subtarget->hasNEON()) {
17783       Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
17784       Type *Tys[] = {VecTy, Int8Ptr};
17785       static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
17786                                                 Intrinsic::arm_neon_vld3,
17787                                                 Intrinsic::arm_neon_vld4};
17788       Function *VldnFunc =
17789           Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
17790 
17791       SmallVector<Value *, 2> Ops;
17792       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
17793       Ops.push_back(Builder.getInt32(LI->getAlignment()));
17794 
17795       return Builder.CreateCall(VldnFunc, Ops, "vldN");
17796     } else {
17797       assert((Factor == 2 || Factor == 4) &&
17798              "expected interleave factor of 2 or 4 for MVE");
17799       Intrinsic::ID LoadInts =
17800           Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
17801       Type *VecEltTy =
17802           VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace());
17803       Type *Tys[] = {VecTy, VecEltTy};
17804       Function *VldnFunc =
17805           Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys);
17806 
17807       SmallVector<Value *, 2> Ops;
17808       Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy));
17809       return Builder.CreateCall(VldnFunc, Ops, "vldN");
17810     }
17811   };
17812 
17813   // Holds sub-vectors extracted from the load intrinsic return values. The
17814   // sub-vectors are associated with the shufflevector instructions they will
17815   // replace.
17816   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
17817 
17818   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
17819     // If we're generating more than one load, compute the base address of
17820     // subsequent loads as an offset from the previous.
17821     if (LoadCount > 0)
17822       BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
17823                                             VecTy->getNumElements() * Factor);
17824 
17825     CallInst *VldN = createLoadIntrinsic(BaseAddr);
17826 
17827     // Replace uses of each shufflevector with the corresponding vector loaded
17828     // by ldN.
17829     for (unsigned i = 0; i < Shuffles.size(); i++) {
17830       ShuffleVectorInst *SV = Shuffles[i];
17831       unsigned Index = Indices[i];
17832 
17833       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
17834 
17835       // Convert the integer vector to pointer vector if the element is pointer.
17836       if (EltTy->isPointerTy())
17837         SubVec = Builder.CreateIntToPtr(
17838             SubVec, VectorType::get(SV->getType()->getElementType(),
17839                                     VecTy->getNumElements()));
17840 
17841       SubVecs[SV].push_back(SubVec);
17842     }
17843   }
17844 
17845   // Replace uses of the shufflevector instructions with the sub-vectors
17846   // returned by the load intrinsic. If a shufflevector instruction is
17847   // associated with more than one sub-vector, those sub-vectors will be
17848   // concatenated into a single wide vector.
17849   for (ShuffleVectorInst *SVI : Shuffles) {
17850     auto &SubVec = SubVecs[SVI];
17851     auto *WideVec =
17852         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
17853     SVI->replaceAllUsesWith(WideVec);
17854   }
17855 
17856   return true;
17857 }
17858 
17859 /// Lower an interleaved store into a vstN intrinsic.
17860 ///
17861 /// E.g. Lower an interleaved store (Factor = 3):
17862 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
17863 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
17864 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
17865 ///
17866 ///      Into:
17867 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
17868 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
17869 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
17870 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
17871 ///
17872 /// Note that the new shufflevectors will be removed and we'll only generate one
17873 /// vst3 instruction in CodeGen.
17874 ///
17875 /// Example for a more general valid mask (Factor 3). Lower:
17876 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
17877 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
17878 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
17879 ///
17880 ///      Into:
17881 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
17882 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
17883 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
17884 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
17885 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
17886                                               ShuffleVectorInst *SVI,
17887                                               unsigned Factor) const {
17888   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
17889          "Invalid interleave factor");
17890 
17891   VectorType *VecTy = SVI->getType();
17892   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
17893 
17894   unsigned LaneLen = VecTy->getNumElements() / Factor;
17895   Type *EltTy = VecTy->getElementType();
17896   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
17897 
17898   const DataLayout &DL = SI->getModule()->getDataLayout();
17899 
17900   // Skip if we do not have NEON and skip illegal vector types. We can
17901   // "legalize" wide vector types into multiple interleaved accesses as long as
17902   // the vector types are divisible by 128.
17903   if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL))
17904     return false;
17905 
17906   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
17907 
17908   Value *Op0 = SVI->getOperand(0);
17909   Value *Op1 = SVI->getOperand(1);
17910   IRBuilder<> Builder(SI);
17911 
17912   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
17913   // vectors to integer vectors.
17914   if (EltTy->isPointerTy()) {
17915     Type *IntTy = DL.getIntPtrType(EltTy);
17916 
17917     // Convert to the corresponding integer vector.
17918     Type *IntVecTy = VectorType::get(
17919         IntTy, cast<VectorType>(Op0->getType())->getNumElements());
17920     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
17921     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
17922 
17923     SubVecTy = VectorType::get(IntTy, LaneLen);
17924   }
17925 
17926   // The base address of the store.
17927   Value *BaseAddr = SI->getPointerOperand();
17928 
17929   if (NumStores > 1) {
17930     // If we're going to generate more than one store, reset the lane length
17931     // and sub-vector type to something legal.
17932     LaneLen /= NumStores;
17933     SubVecTy = VectorType::get(SubVecTy->getElementType(), LaneLen);
17934 
17935     // We will compute the pointer operand of each store from the original base
17936     // address using GEPs. Cast the base address to a pointer to the scalar
17937     // element type.
17938     BaseAddr = Builder.CreateBitCast(
17939         BaseAddr,
17940         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
17941   }
17942 
17943   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
17944 
17945   auto Mask = SVI->getShuffleMask();
17946 
17947   auto createStoreIntrinsic = [&](Value *BaseAddr,
17948                                   SmallVectorImpl<Value *> &Shuffles) {
17949     if (Subtarget->hasNEON()) {
17950       static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
17951                                                  Intrinsic::arm_neon_vst3,
17952                                                  Intrinsic::arm_neon_vst4};
17953       Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
17954       Type *Tys[] = {Int8Ptr, SubVecTy};
17955 
17956       Function *VstNFunc = Intrinsic::getDeclaration(
17957           SI->getModule(), StoreInts[Factor - 2], Tys);
17958 
17959       SmallVector<Value *, 6> Ops;
17960       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
17961       for (auto S : Shuffles)
17962         Ops.push_back(S);
17963       Ops.push_back(Builder.getInt32(SI->getAlignment()));
17964       Builder.CreateCall(VstNFunc, Ops);
17965     } else {
17966       assert((Factor == 2 || Factor == 4) &&
17967              "expected interleave factor of 2 or 4 for MVE");
17968       Intrinsic::ID StoreInts =
17969           Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
17970       Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo(
17971           SI->getPointerAddressSpace());
17972       Type *Tys[] = {EltPtrTy, SubVecTy};
17973       Function *VstNFunc =
17974           Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys);
17975 
17976       SmallVector<Value *, 6> Ops;
17977       Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy));
17978       for (auto S : Shuffles)
17979         Ops.push_back(S);
17980       for (unsigned F = 0; F < Factor; F++) {
17981         Ops.push_back(Builder.getInt32(F));
17982         Builder.CreateCall(VstNFunc, Ops);
17983         Ops.pop_back();
17984       }
17985     }
17986   };
17987 
17988   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
17989     // If we generating more than one store, we compute the base address of
17990     // subsequent stores as an offset from the previous.
17991     if (StoreCount > 0)
17992       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
17993                                             BaseAddr, LaneLen * Factor);
17994 
17995     SmallVector<Value *, 4> Shuffles;
17996 
17997     // Split the shufflevector operands into sub vectors for the new vstN call.
17998     for (unsigned i = 0; i < Factor; i++) {
17999       unsigned IdxI = StoreCount * LaneLen * Factor + i;
18000       if (Mask[IdxI] >= 0) {
18001         Shuffles.push_back(Builder.CreateShuffleVector(
18002             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
18003       } else {
18004         unsigned StartMask = 0;
18005         for (unsigned j = 1; j < LaneLen; j++) {
18006           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
18007           if (Mask[IdxJ * Factor + IdxI] >= 0) {
18008             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
18009             break;
18010           }
18011         }
18012         // Note: If all elements in a chunk are undefs, StartMask=0!
18013         // Note: Filling undef gaps with random elements is ok, since
18014         // those elements were being written anyway (with undefs).
18015         // In the case of all undefs we're defaulting to using elems from 0
18016         // Note: StartMask cannot be negative, it's checked in
18017         // isReInterleaveMask
18018         Shuffles.push_back(Builder.CreateShuffleVector(
18019             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
18020       }
18021     }
18022 
18023     createStoreIntrinsic(BaseAddr, Shuffles);
18024   }
18025   return true;
18026 }
18027 
18028 enum HABaseType {
18029   HA_UNKNOWN = 0,
18030   HA_FLOAT,
18031   HA_DOUBLE,
18032   HA_VECT64,
18033   HA_VECT128
18034 };
18035 
18036 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
18037                                    uint64_t &Members) {
18038   if (auto *ST = dyn_cast<StructType>(Ty)) {
18039     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
18040       uint64_t SubMembers = 0;
18041       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
18042         return false;
18043       Members += SubMembers;
18044     }
18045   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
18046     uint64_t SubMembers = 0;
18047     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
18048       return false;
18049     Members += SubMembers * AT->getNumElements();
18050   } else if (Ty->isFloatTy()) {
18051     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
18052       return false;
18053     Members = 1;
18054     Base = HA_FLOAT;
18055   } else if (Ty->isDoubleTy()) {
18056     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
18057       return false;
18058     Members = 1;
18059     Base = HA_DOUBLE;
18060   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
18061     Members = 1;
18062     switch (Base) {
18063     case HA_FLOAT:
18064     case HA_DOUBLE:
18065       return false;
18066     case HA_VECT64:
18067       return VT->getPrimitiveSizeInBits().getFixedSize() == 64;
18068     case HA_VECT128:
18069       return VT->getPrimitiveSizeInBits().getFixedSize() == 128;
18070     case HA_UNKNOWN:
18071       switch (VT->getPrimitiveSizeInBits().getFixedSize()) {
18072       case 64:
18073         Base = HA_VECT64;
18074         return true;
18075       case 128:
18076         Base = HA_VECT128;
18077         return true;
18078       default:
18079         return false;
18080       }
18081     }
18082   }
18083 
18084   return (Members > 0 && Members <= 4);
18085 }
18086 
18087 /// Return the correct alignment for the current calling convention.
18088 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
18089                                                        DataLayout DL) const {
18090   const Align ABITypeAlign(DL.getABITypeAlignment(ArgTy));
18091   if (!ArgTy->isVectorTy())
18092     return ABITypeAlign;
18093 
18094   // Avoid over-aligning vector parameters. It would require realigning the
18095   // stack and waste space for no real benefit.
18096   return std::min(ABITypeAlign, DL.getStackAlignment());
18097 }
18098 
18099 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
18100 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
18101 /// passing according to AAPCS rules.
18102 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
18103     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
18104   if (getEffectiveCallingConv(CallConv, isVarArg) !=
18105       CallingConv::ARM_AAPCS_VFP)
18106     return false;
18107 
18108   HABaseType Base = HA_UNKNOWN;
18109   uint64_t Members = 0;
18110   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
18111   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
18112 
18113   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
18114   return IsHA || IsIntArray;
18115 }
18116 
18117 Register ARMTargetLowering::getExceptionPointerRegister(
18118     const Constant *PersonalityFn) const {
18119   // Platforms which do not use SjLj EH may return values in these registers
18120   // via the personality function.
18121   return Subtarget->useSjLjEH() ? Register() : ARM::R0;
18122 }
18123 
18124 Register ARMTargetLowering::getExceptionSelectorRegister(
18125     const Constant *PersonalityFn) const {
18126   // Platforms which do not use SjLj EH may return values in these registers
18127   // via the personality function.
18128   return Subtarget->useSjLjEH() ? Register() : ARM::R1;
18129 }
18130 
18131 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
18132   // Update IsSplitCSR in ARMFunctionInfo.
18133   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
18134   AFI->setIsSplitCSR(true);
18135 }
18136 
18137 void ARMTargetLowering::insertCopiesSplitCSR(
18138     MachineBasicBlock *Entry,
18139     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
18140   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
18141   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
18142   if (!IStart)
18143     return;
18144 
18145   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
18146   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
18147   MachineBasicBlock::iterator MBBI = Entry->begin();
18148   for (const MCPhysReg *I = IStart; *I; ++I) {
18149     const TargetRegisterClass *RC = nullptr;
18150     if (ARM::GPRRegClass.contains(*I))
18151       RC = &ARM::GPRRegClass;
18152     else if (ARM::DPRRegClass.contains(*I))
18153       RC = &ARM::DPRRegClass;
18154     else
18155       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
18156 
18157     Register NewVR = MRI->createVirtualRegister(RC);
18158     // Create copy from CSR to a virtual register.
18159     // FIXME: this currently does not emit CFI pseudo-instructions, it works
18160     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
18161     // nounwind. If we want to generalize this later, we may need to emit
18162     // CFI pseudo-instructions.
18163     assert(Entry->getParent()->getFunction().hasFnAttribute(
18164                Attribute::NoUnwind) &&
18165            "Function should be nounwind in insertCopiesSplitCSR!");
18166     Entry->addLiveIn(*I);
18167     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
18168         .addReg(*I);
18169 
18170     // Insert the copy-back instructions right before the terminator.
18171     for (auto *Exit : Exits)
18172       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
18173               TII->get(TargetOpcode::COPY), *I)
18174           .addReg(NewVR);
18175   }
18176 }
18177 
18178 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
18179   MF.getFrameInfo().computeMaxCallFrameSize(MF);
18180   TargetLoweringBase::finalizeLowering(MF);
18181 }
18182