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 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   setOperationAction(ISD::SDIVREM, VT, Expand);
214   setOperationAction(ISD::UDIVREM, VT, Expand);
215 
216   if (!VT.isFloatingPoint() &&
217       VT != MVT::v2i64 && VT != MVT::v1i64)
218     for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
219       setOperationAction(Opcode, VT, Legal);
220   if (!VT.isFloatingPoint())
221     for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
222       setOperationAction(Opcode, VT, Legal);
223 }
224 
225 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
226   addRegisterClass(VT, &ARM::DPRRegClass);
227   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
228 }
229 
230 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
231   addRegisterClass(VT, &ARM::DPairRegClass);
232   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
233 }
234 
235 void ARMTargetLowering::setAllExpand(MVT VT) {
236   for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
237     setOperationAction(Opc, VT, Expand);
238 
239   // We support these really simple operations even on types where all
240   // the actual arithmetic has to be broken down into simpler
241   // operations or turned into library calls.
242   setOperationAction(ISD::BITCAST, VT, Legal);
243   setOperationAction(ISD::LOAD, VT, Legal);
244   setOperationAction(ISD::STORE, VT, Legal);
245   setOperationAction(ISD::UNDEF, VT, Legal);
246 }
247 
248 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
249                                        LegalizeAction Action) {
250   setLoadExtAction(ISD::EXTLOAD,  From, To, Action);
251   setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
252   setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
253 }
254 
255 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
256   const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
257 
258   for (auto VT : IntTypes) {
259     addRegisterClass(VT, &ARM::MQPRRegClass);
260     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
261     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
262     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
263     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
264     setOperationAction(ISD::SHL, VT, Custom);
265     setOperationAction(ISD::SRA, VT, Custom);
266     setOperationAction(ISD::SRL, VT, Custom);
267     setOperationAction(ISD::SMIN, VT, Legal);
268     setOperationAction(ISD::SMAX, VT, Legal);
269     setOperationAction(ISD::UMIN, VT, Legal);
270     setOperationAction(ISD::UMAX, VT, Legal);
271     setOperationAction(ISD::ABS, VT, Legal);
272     setOperationAction(ISD::SETCC, VT, Custom);
273     setOperationAction(ISD::MLOAD, VT, Custom);
274     setOperationAction(ISD::MSTORE, VT, Legal);
275     setOperationAction(ISD::CTLZ, VT, Legal);
276     setOperationAction(ISD::CTTZ, VT, Custom);
277     setOperationAction(ISD::BITREVERSE, VT, Legal);
278     setOperationAction(ISD::BSWAP, VT, Legal);
279     setOperationAction(ISD::SADDSAT, VT, Legal);
280     setOperationAction(ISD::UADDSAT, VT, Legal);
281     setOperationAction(ISD::SSUBSAT, VT, Legal);
282     setOperationAction(ISD::USUBSAT, VT, Legal);
283 
284     // No native support for these.
285     setOperationAction(ISD::UDIV, VT, Expand);
286     setOperationAction(ISD::SDIV, VT, Expand);
287     setOperationAction(ISD::UREM, VT, Expand);
288     setOperationAction(ISD::SREM, VT, Expand);
289     setOperationAction(ISD::UDIVREM, VT, Expand);
290     setOperationAction(ISD::SDIVREM, VT, Expand);
291     setOperationAction(ISD::CTPOP, VT, Expand);
292 
293     // Vector reductions
294     setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
295     setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
296     setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
297     setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
298     setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
299     setOperationAction(ISD::VECREDUCE_MUL, VT, Custom);
300     setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
301     setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
302     setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
303 
304     if (!HasMVEFP) {
305       setOperationAction(ISD::SINT_TO_FP, VT, Expand);
306       setOperationAction(ISD::UINT_TO_FP, VT, Expand);
307       setOperationAction(ISD::FP_TO_SINT, VT, Expand);
308       setOperationAction(ISD::FP_TO_UINT, VT, Expand);
309     }
310 
311     // Pre and Post inc are supported on loads and stores
312     for (unsigned im = (unsigned)ISD::PRE_INC;
313          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
314       setIndexedLoadAction(im, VT, Legal);
315       setIndexedStoreAction(im, VT, Legal);
316       setIndexedMaskedLoadAction(im, VT, Legal);
317       setIndexedMaskedStoreAction(im, VT, Legal);
318     }
319   }
320 
321   const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
322   for (auto VT : FloatTypes) {
323     addRegisterClass(VT, &ARM::MQPRRegClass);
324     if (!HasMVEFP)
325       setAllExpand(VT);
326 
327     // These are legal or custom whether we have MVE.fp or not
328     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
329     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
330     setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
331     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
332     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
333     setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
334     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
335     setOperationAction(ISD::SETCC, VT, Custom);
336     setOperationAction(ISD::MLOAD, VT, Custom);
337     setOperationAction(ISD::MSTORE, VT, Legal);
338 
339     // Pre and Post inc are supported on loads and stores
340     for (unsigned im = (unsigned)ISD::PRE_INC;
341          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
342       setIndexedLoadAction(im, VT, Legal);
343       setIndexedStoreAction(im, VT, Legal);
344       setIndexedMaskedLoadAction(im, VT, Legal);
345       setIndexedMaskedStoreAction(im, VT, Legal);
346     }
347 
348     if (HasMVEFP) {
349       setOperationAction(ISD::FMINNUM, VT, Legal);
350       setOperationAction(ISD::FMAXNUM, VT, Legal);
351       setOperationAction(ISD::FROUND, VT, Legal);
352       setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
353       setOperationAction(ISD::VECREDUCE_FMUL, VT, Custom);
354       setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
355       setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
356 
357       // No native support for these.
358       setOperationAction(ISD::FDIV, VT, Expand);
359       setOperationAction(ISD::FREM, VT, Expand);
360       setOperationAction(ISD::FSQRT, VT, Expand);
361       setOperationAction(ISD::FSIN, VT, Expand);
362       setOperationAction(ISD::FCOS, VT, Expand);
363       setOperationAction(ISD::FPOW, VT, Expand);
364       setOperationAction(ISD::FLOG, VT, Expand);
365       setOperationAction(ISD::FLOG2, VT, Expand);
366       setOperationAction(ISD::FLOG10, VT, Expand);
367       setOperationAction(ISD::FEXP, VT, Expand);
368       setOperationAction(ISD::FEXP2, VT, Expand);
369       setOperationAction(ISD::FNEARBYINT, VT, Expand);
370     }
371   }
372 
373   // Custom Expand smaller than legal vector reductions to prevent false zero
374   // items being added.
375   setOperationAction(ISD::VECREDUCE_FADD, MVT::v4f16, Custom);
376   setOperationAction(ISD::VECREDUCE_FMUL, MVT::v4f16, Custom);
377   setOperationAction(ISD::VECREDUCE_FMIN, MVT::v4f16, Custom);
378   setOperationAction(ISD::VECREDUCE_FMAX, MVT::v4f16, Custom);
379   setOperationAction(ISD::VECREDUCE_FADD, MVT::v2f16, Custom);
380   setOperationAction(ISD::VECREDUCE_FMUL, MVT::v2f16, Custom);
381   setOperationAction(ISD::VECREDUCE_FMIN, MVT::v2f16, Custom);
382   setOperationAction(ISD::VECREDUCE_FMAX, MVT::v2f16, Custom);
383 
384   // We 'support' these types up to bitcast/load/store level, regardless of
385   // MVE integer-only / float support. Only doing FP data processing on the FP
386   // vector types is inhibited at integer-only level.
387   const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
388   for (auto VT : LongTypes) {
389     addRegisterClass(VT, &ARM::MQPRRegClass);
390     setAllExpand(VT);
391     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
392     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
393     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
394   }
395   // We can do bitwise operations on v2i64 vectors
396   setOperationAction(ISD::AND, MVT::v2i64, Legal);
397   setOperationAction(ISD::OR, MVT::v2i64, Legal);
398   setOperationAction(ISD::XOR, MVT::v2i64, Legal);
399 
400   // It is legal to extload from v4i8 to v4i16 or v4i32.
401   addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
402   addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
403   addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
404 
405   // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
406   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
408   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
409   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8,  Legal);
410   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal);
411 
412   // Some truncating stores are legal too.
413   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
414   setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
415   setTruncStoreAction(MVT::v8i16, MVT::v8i8,  Legal);
416 
417   // Pre and Post inc on these are legal, given the correct extends
418   for (unsigned im = (unsigned)ISD::PRE_INC;
419        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
420     for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
421       setIndexedLoadAction(im, VT, Legal);
422       setIndexedStoreAction(im, VT, Legal);
423       setIndexedMaskedLoadAction(im, VT, Legal);
424       setIndexedMaskedStoreAction(im, VT, Legal);
425     }
426   }
427 
428   // Predicate types
429   const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
430   for (auto VT : pTypes) {
431     addRegisterClass(VT, &ARM::VCCRRegClass);
432     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
433     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
434     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
435     setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
436     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
437     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
438     setOperationAction(ISD::SETCC, VT, Custom);
439     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
440     setOperationAction(ISD::LOAD, VT, Custom);
441     setOperationAction(ISD::STORE, VT, Custom);
442   }
443 }
444 
445 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
446                                      const ARMSubtarget &STI)
447     : TargetLowering(TM), Subtarget(&STI) {
448   RegInfo = Subtarget->getRegisterInfo();
449   Itins = Subtarget->getInstrItineraryData();
450 
451   setBooleanContents(ZeroOrOneBooleanContent);
452   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
453 
454   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
455       !Subtarget->isTargetWatchOS()) {
456     bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
457     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
458       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
459                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
460                                        : CallingConv::ARM_AAPCS);
461   }
462 
463   if (Subtarget->isTargetMachO()) {
464     // Uses VFP for Thumb libfuncs if available.
465     if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
466         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
467       static const struct {
468         const RTLIB::Libcall Op;
469         const char * const Name;
470         const ISD::CondCode Cond;
471       } LibraryCalls[] = {
472         // Single-precision floating-point arithmetic.
473         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
474         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
475         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
476         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
477 
478         // Double-precision floating-point arithmetic.
479         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
480         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
481         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
482         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
483 
484         // Single-precision comparisons.
485         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
486         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
487         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
488         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
489         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
490         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
491         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
492 
493         // Double-precision comparisons.
494         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
495         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
496         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
497         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
498         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
499         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
500         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
501 
502         // Floating-point to integer conversions.
503         // i64 conversions are done via library routines even when generating VFP
504         // instructions, so use the same ones.
505         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
506         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
507         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
508         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
509 
510         // Conversions between floating types.
511         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
512         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
513 
514         // Integer to floating-point conversions.
515         // i64 conversions are done via library routines even when generating VFP
516         // instructions, so use the same ones.
517         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
518         // e.g., __floatunsidf vs. __floatunssidfvfp.
519         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
520         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
521         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
522         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
523       };
524 
525       for (const auto &LC : LibraryCalls) {
526         setLibcallName(LC.Op, LC.Name);
527         if (LC.Cond != ISD::SETCC_INVALID)
528           setCmpLibcallCC(LC.Op, LC.Cond);
529       }
530     }
531   }
532 
533   // These libcalls are not available in 32-bit.
534   setLibcallName(RTLIB::SHL_I128, nullptr);
535   setLibcallName(RTLIB::SRL_I128, nullptr);
536   setLibcallName(RTLIB::SRA_I128, nullptr);
537 
538   // RTLIB
539   if (Subtarget->isAAPCS_ABI() &&
540       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
541        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
542     static const struct {
543       const RTLIB::Libcall Op;
544       const char * const Name;
545       const CallingConv::ID CC;
546       const ISD::CondCode Cond;
547     } LibraryCalls[] = {
548       // Double-precision floating-point arithmetic helper functions
549       // RTABI chapter 4.1.2, Table 2
550       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
551       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
552       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
553       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
554 
555       // Double-precision floating-point comparison helper functions
556       // RTABI chapter 4.1.2, Table 3
557       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
558       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
559       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
560       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
561       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
562       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
563       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
564 
565       // Single-precision floating-point arithmetic helper functions
566       // RTABI chapter 4.1.2, Table 4
567       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
568       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
569       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
570       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
571 
572       // Single-precision floating-point comparison helper functions
573       // RTABI chapter 4.1.2, Table 5
574       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
575       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
576       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
577       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
578       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
579       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
580       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
581 
582       // Floating-point to integer conversions.
583       // RTABI chapter 4.1.2, Table 6
584       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
585       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
586       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
587       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
588       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
589       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
590       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
591       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
592 
593       // Conversions between floating types.
594       // RTABI chapter 4.1.2, Table 7
595       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
596       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
597       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
598 
599       // Integer to floating-point conversions.
600       // RTABI chapter 4.1.2, Table 8
601       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
602       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
603       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
604       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
605       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
606       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
607       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
608       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
609 
610       // Long long helper functions
611       // RTABI chapter 4.2, Table 9
612       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
613       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
614       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
615       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
616 
617       // Integer division functions
618       // RTABI chapter 4.3.1
619       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
620       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
621       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
622       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
623       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
624       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
625       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
626       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
627     };
628 
629     for (const auto &LC : LibraryCalls) {
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     // EABI dependent RTLIB
637     if (TM.Options.EABIVersion == EABI::EABI4 ||
638         TM.Options.EABIVersion == EABI::EABI5) {
639       static const struct {
640         const RTLIB::Libcall Op;
641         const char *const Name;
642         const CallingConv::ID CC;
643         const ISD::CondCode Cond;
644       } MemOpsLibraryCalls[] = {
645         // Memory operations
646         // RTABI chapter 4.3.4
647         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
648         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
649         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
650       };
651 
652       for (const auto &LC : MemOpsLibraryCalls) {
653         setLibcallName(LC.Op, LC.Name);
654         setLibcallCallingConv(LC.Op, LC.CC);
655         if (LC.Cond != ISD::SETCC_INVALID)
656           setCmpLibcallCC(LC.Op, LC.Cond);
657       }
658     }
659   }
660 
661   if (Subtarget->isTargetWindows()) {
662     static const struct {
663       const RTLIB::Libcall Op;
664       const char * const Name;
665       const CallingConv::ID CC;
666     } LibraryCalls[] = {
667       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
668       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
669       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
670       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
671       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
672       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
673       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
674       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
675     };
676 
677     for (const auto &LC : LibraryCalls) {
678       setLibcallName(LC.Op, LC.Name);
679       setLibcallCallingConv(LC.Op, LC.CC);
680     }
681   }
682 
683   // Use divmod compiler-rt calls for iOS 5.0 and later.
684   if (Subtarget->isTargetMachO() &&
685       !(Subtarget->isTargetIOS() &&
686         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
687     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
688     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
689   }
690 
691   // The half <-> float conversion functions are always soft-float on
692   // non-watchos platforms, but are needed for some targets which use a
693   // hard-float calling convention by default.
694   if (!Subtarget->isTargetWatchABI()) {
695     if (Subtarget->isAAPCS_ABI()) {
696       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
697       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
698       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
699     } else {
700       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
701       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
702       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
703     }
704   }
705 
706   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
707   // a __gnu_ prefix (which is the default).
708   if (Subtarget->isTargetAEABI()) {
709     static const struct {
710       const RTLIB::Libcall Op;
711       const char * const Name;
712       const CallingConv::ID CC;
713     } LibraryCalls[] = {
714       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
715       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
716       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
717     };
718 
719     for (const auto &LC : LibraryCalls) {
720       setLibcallName(LC.Op, LC.Name);
721       setLibcallCallingConv(LC.Op, LC.CC);
722     }
723   }
724 
725   if (Subtarget->isThumb1Only())
726     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
727   else
728     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
729 
730   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
731       Subtarget->hasFPRegs()) {
732     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
733     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
734     if (!Subtarget->hasVFP2Base())
735       setAllExpand(MVT::f32);
736     if (!Subtarget->hasFP64())
737       setAllExpand(MVT::f64);
738   }
739 
740   if (Subtarget->hasFullFP16()) {
741     addRegisterClass(MVT::f16, &ARM::HPRRegClass);
742     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
743     setOperationAction(ISD::BITCAST, MVT::f16, Custom);
744 
745     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
746     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
747   }
748 
749   if (Subtarget->hasBF16()) {
750     addRegisterClass(MVT::bf16, &ARM::HPRRegClass);
751     setAllExpand(MVT::bf16);
752     if (!Subtarget->hasFullFP16())
753       setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
754   }
755 
756   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
757     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
758       setTruncStoreAction(VT, InnerVT, Expand);
759       addAllExtLoads(VT, InnerVT, Expand);
760     }
761 
762     setOperationAction(ISD::MULHS, VT, Expand);
763     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
764     setOperationAction(ISD::MULHU, VT, Expand);
765     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
766 
767     setOperationAction(ISD::BSWAP, VT, Expand);
768   }
769 
770   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
771   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
772 
773   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
774   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
775 
776   if (Subtarget->hasMVEIntegerOps())
777     addMVEVectorTypes(Subtarget->hasMVEFloatOps());
778 
779   // Combine low-overhead loop intrinsics so that we can lower i1 types.
780   if (Subtarget->hasLOB()) {
781     setTargetDAGCombine(ISD::BRCOND);
782     setTargetDAGCombine(ISD::BR_CC);
783   }
784 
785   if (Subtarget->hasNEON()) {
786     addDRTypeForNEON(MVT::v2f32);
787     addDRTypeForNEON(MVT::v8i8);
788     addDRTypeForNEON(MVT::v4i16);
789     addDRTypeForNEON(MVT::v2i32);
790     addDRTypeForNEON(MVT::v1i64);
791 
792     addQRTypeForNEON(MVT::v4f32);
793     addQRTypeForNEON(MVT::v2f64);
794     addQRTypeForNEON(MVT::v16i8);
795     addQRTypeForNEON(MVT::v8i16);
796     addQRTypeForNEON(MVT::v4i32);
797     addQRTypeForNEON(MVT::v2i64);
798 
799     if (Subtarget->hasFullFP16()) {
800       addQRTypeForNEON(MVT::v8f16);
801       addDRTypeForNEON(MVT::v4f16);
802     }
803 
804     if (Subtarget->hasBF16()) {
805       addQRTypeForNEON(MVT::v8bf16);
806       addDRTypeForNEON(MVT::v4bf16);
807     }
808   }
809 
810   if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
811     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
812     // none of Neon, MVE or VFP supports any arithmetic operations on it.
813     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
814     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
815     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
816     // FIXME: Code duplication: FDIV and FREM are expanded always, see
817     // ARMTargetLowering::addTypeForNEON method for details.
818     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
819     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
820     // FIXME: Create unittest.
821     // In another words, find a way when "copysign" appears in DAG with vector
822     // operands.
823     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
824     // FIXME: Code duplication: SETCC has custom operation action, see
825     // ARMTargetLowering::addTypeForNEON method for details.
826     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
827     // FIXME: Create unittest for FNEG and for FABS.
828     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
829     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
830     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
831     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
832     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
833     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
834     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
835     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
836     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
837     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
838     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
839     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
840     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
841     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
842     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
843     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
844     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
845     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
846   }
847 
848   if (Subtarget->hasNEON()) {
849     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
850     // supported for v4f32.
851     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
852     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
853     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
854     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
855     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
856     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
857     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
858     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
859     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
860     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
861     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
862     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
863     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
864     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
865 
866     // Mark v2f32 intrinsics.
867     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
868     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
869     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
870     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
871     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
872     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
873     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
874     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
875     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
876     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
877     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
878     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
879     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
880     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
881 
882     // Neon does not support some operations on v1i64 and v2i64 types.
883     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
884     // Custom handling for some quad-vector types to detect VMULL.
885     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
886     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
887     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
888     // Custom handling for some vector types to avoid expensive expansions
889     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
890     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
891     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
892     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
893     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
894     // a destination type that is wider than the source, and nor does
895     // it have a FP_TO_[SU]INT instruction with a narrower destination than
896     // source.
897     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
898     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
899     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
900     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
901     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
902     setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
903     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
904     setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
905 
906     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
907     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
908 
909     // NEON does not have single instruction CTPOP for vectors with element
910     // types wider than 8-bits.  However, custom lowering can leverage the
911     // v8i8/v16i8 vcnt instruction.
912     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
913     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
914     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
915     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
916     setOperationAction(ISD::CTPOP,      MVT::v1i64, Custom);
917     setOperationAction(ISD::CTPOP,      MVT::v2i64, Custom);
918 
919     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
920     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
921 
922     // NEON does not have single instruction CTTZ for vectors.
923     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
924     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
925     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
926     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
927 
928     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
929     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
930     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
931     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
932 
933     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
934     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
935     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
936     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
937 
938     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
939     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
940     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
941     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
942 
943     // NEON only has FMA instructions as of VFP4.
944     if (!Subtarget->hasVFP4Base()) {
945       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
946       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
947     }
948 
949     setTargetDAGCombine(ISD::SHL);
950     setTargetDAGCombine(ISD::SRL);
951     setTargetDAGCombine(ISD::SRA);
952     setTargetDAGCombine(ISD::FP_TO_SINT);
953     setTargetDAGCombine(ISD::FP_TO_UINT);
954     setTargetDAGCombine(ISD::FDIV);
955     setTargetDAGCombine(ISD::LOAD);
956 
957     // It is legal to extload from v4i8 to v4i16 or v4i32.
958     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
959                    MVT::v2i32}) {
960       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
961         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
962         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
963         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
964       }
965     }
966   }
967 
968   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
969     setTargetDAGCombine(ISD::BUILD_VECTOR);
970     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
971     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
972     setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
973     setTargetDAGCombine(ISD::STORE);
974     setTargetDAGCombine(ISD::SIGN_EXTEND);
975     setTargetDAGCombine(ISD::ZERO_EXTEND);
976     setTargetDAGCombine(ISD::ANY_EXTEND);
977     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
978     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
979     setTargetDAGCombine(ISD::INTRINSIC_VOID);
980     setTargetDAGCombine(ISD::VECREDUCE_ADD);
981     setTargetDAGCombine(ISD::ADD);
982     setTargetDAGCombine(ISD::BITCAST);
983   }
984   if (Subtarget->hasMVEIntegerOps()) {
985     setTargetDAGCombine(ISD::SMIN);
986     setTargetDAGCombine(ISD::UMIN);
987     setTargetDAGCombine(ISD::SMAX);
988     setTargetDAGCombine(ISD::UMAX);
989     setTargetDAGCombine(ISD::FP_EXTEND);
990   }
991 
992   if (!Subtarget->hasFP64()) {
993     // When targeting a floating-point unit with only single-precision
994     // operations, f64 is legal for the few double-precision instructions which
995     // are present However, no double-precision operations other than moves,
996     // loads and stores are provided by the hardware.
997     setOperationAction(ISD::FADD,       MVT::f64, Expand);
998     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
999     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
1000     setOperationAction(ISD::FMA,        MVT::f64, Expand);
1001     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
1002     setOperationAction(ISD::FREM,       MVT::f64, Expand);
1003     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
1004     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
1005     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
1006     setOperationAction(ISD::FABS,       MVT::f64, Expand);
1007     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
1008     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
1009     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
1010     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
1011     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
1012     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
1013     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
1014     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
1015     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
1016     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
1017     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
1018     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
1019     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
1020     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
1021     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1022     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
1023     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1024     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
1025     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
1026     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
1027     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
1028     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
1029     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
1030     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
1031     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
1032     setOperationAction(ISD::STRICT_FP_ROUND,   MVT::f32, Custom);
1033   }
1034 
1035   if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
1036     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
1037     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
1038     if (Subtarget->hasFullFP16()) {
1039       setOperationAction(ISD::FP_ROUND,  MVT::f16, Custom);
1040       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
1041     }
1042   }
1043 
1044   if (!Subtarget->hasFP16()) {
1045     setOperationAction(ISD::FP_EXTEND,  MVT::f32, Custom);
1046     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1047   }
1048 
1049   computeRegisterProperties(Subtarget->getRegisterInfo());
1050 
1051   // ARM does not have floating-point extending loads.
1052   for (MVT VT : MVT::fp_valuetypes()) {
1053     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1054     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1055   }
1056 
1057   // ... or truncating stores
1058   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1059   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1060   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1061 
1062   // ARM does not have i1 sign extending load.
1063   for (MVT VT : MVT::integer_valuetypes())
1064     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1065 
1066   // ARM supports all 4 flavors of integer indexed load / store.
1067   if (!Subtarget->isThumb1Only()) {
1068     for (unsigned im = (unsigned)ISD::PRE_INC;
1069          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1070       setIndexedLoadAction(im,  MVT::i1,  Legal);
1071       setIndexedLoadAction(im,  MVT::i8,  Legal);
1072       setIndexedLoadAction(im,  MVT::i16, Legal);
1073       setIndexedLoadAction(im,  MVT::i32, Legal);
1074       setIndexedStoreAction(im, MVT::i1,  Legal);
1075       setIndexedStoreAction(im, MVT::i8,  Legal);
1076       setIndexedStoreAction(im, MVT::i16, Legal);
1077       setIndexedStoreAction(im, MVT::i32, Legal);
1078     }
1079   } else {
1080     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1081     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
1082     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
1083   }
1084 
1085   setOperationAction(ISD::SADDO, MVT::i32, Custom);
1086   setOperationAction(ISD::UADDO, MVT::i32, Custom);
1087   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1088   setOperationAction(ISD::USUBO, MVT::i32, Custom);
1089 
1090   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1091   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1092   if (Subtarget->hasDSP()) {
1093     setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1094     setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1095     setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1096     setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1097   }
1098   if (Subtarget->hasBaseDSP()) {
1099     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1100     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1101   }
1102 
1103   // i64 operation support.
1104   setOperationAction(ISD::MUL,     MVT::i64, Expand);
1105   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
1106   if (Subtarget->isThumb1Only()) {
1107     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1108     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1109   }
1110   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1111       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1112     setOperationAction(ISD::MULHS, MVT::i32, Expand);
1113 
1114   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1115   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1116   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1117   setOperationAction(ISD::SRL,       MVT::i64, Custom);
1118   setOperationAction(ISD::SRA,       MVT::i64, Custom);
1119   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1120   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1121   setOperationAction(ISD::LOAD, MVT::i64, Custom);
1122   setOperationAction(ISD::STORE, MVT::i64, Custom);
1123 
1124   // MVE lowers 64 bit shifts to lsll and lsrl
1125   // assuming that ISD::SRL and SRA of i64 are already marked custom
1126   if (Subtarget->hasMVEIntegerOps())
1127     setOperationAction(ISD::SHL, MVT::i64, Custom);
1128 
1129   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1130   if (Subtarget->isThumb1Only()) {
1131     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1132     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1133     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1134   }
1135 
1136   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1137     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1138 
1139   // ARM does not have ROTL.
1140   setOperationAction(ISD::ROTL, MVT::i32, Expand);
1141   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1142     setOperationAction(ISD::ROTL, VT, Expand);
1143     setOperationAction(ISD::ROTR, VT, Expand);
1144   }
1145   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
1146   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1147   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1148     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1149     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1150   }
1151 
1152   // @llvm.readcyclecounter requires the Performance Monitors extension.
1153   // Default to the 0 expansion on unsupported platforms.
1154   // FIXME: Technically there are older ARM CPUs that have
1155   // implementation-specific ways of obtaining this information.
1156   if (Subtarget->hasPerfMon())
1157     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1158 
1159   // Only ARMv6 has BSWAP.
1160   if (!Subtarget->hasV6Ops())
1161     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1162 
1163   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1164                                         : Subtarget->hasDivideInARMMode();
1165   if (!hasDivide) {
1166     // These are expanded into libcalls if the cpu doesn't have HW divider.
1167     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
1168     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
1169   }
1170 
1171   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1172     setOperationAction(ISD::SDIV, MVT::i32, Custom);
1173     setOperationAction(ISD::UDIV, MVT::i32, Custom);
1174 
1175     setOperationAction(ISD::SDIV, MVT::i64, Custom);
1176     setOperationAction(ISD::UDIV, MVT::i64, Custom);
1177   }
1178 
1179   setOperationAction(ISD::SREM,  MVT::i32, Expand);
1180   setOperationAction(ISD::UREM,  MVT::i32, Expand);
1181 
1182   // Register based DivRem for AEABI (RTABI 4.2)
1183   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1184       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1185       Subtarget->isTargetWindows()) {
1186     setOperationAction(ISD::SREM, MVT::i64, Custom);
1187     setOperationAction(ISD::UREM, MVT::i64, Custom);
1188     HasStandaloneRem = false;
1189 
1190     if (Subtarget->isTargetWindows()) {
1191       const struct {
1192         const RTLIB::Libcall Op;
1193         const char * const Name;
1194         const CallingConv::ID CC;
1195       } LibraryCalls[] = {
1196         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1197         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1198         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1199         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1200 
1201         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1202         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1203         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1204         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1205       };
1206 
1207       for (const auto &LC : LibraryCalls) {
1208         setLibcallName(LC.Op, LC.Name);
1209         setLibcallCallingConv(LC.Op, LC.CC);
1210       }
1211     } else {
1212       const struct {
1213         const RTLIB::Libcall Op;
1214         const char * const Name;
1215         const CallingConv::ID CC;
1216       } LibraryCalls[] = {
1217         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1218         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1219         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1220         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1221 
1222         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1223         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1224         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1225         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1226       };
1227 
1228       for (const auto &LC : LibraryCalls) {
1229         setLibcallName(LC.Op, LC.Name);
1230         setLibcallCallingConv(LC.Op, LC.CC);
1231       }
1232     }
1233 
1234     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1235     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1236     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1237     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1238   } else {
1239     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1240     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1241   }
1242 
1243   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
1244     // MSVCRT doesn't have powi; fall back to pow
1245     setLibcallName(RTLIB::POWI_F32, nullptr);
1246     setLibcallName(RTLIB::POWI_F64, nullptr);
1247   }
1248 
1249   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
1250   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
1251   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1252   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1253 
1254   setOperationAction(ISD::TRAP, MVT::Other, Legal);
1255   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1256 
1257   // Use the default implementation.
1258   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
1259   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
1260   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
1261   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
1262   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
1263   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
1264 
1265   if (Subtarget->isTargetWindows())
1266     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1267   else
1268     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1269 
1270   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1271   // the default expansion.
1272   InsertFencesForAtomic = false;
1273   if (Subtarget->hasAnyDataBarrier() &&
1274       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1275     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1276     // to ldrex/strex loops already.
1277     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
1278     if (!Subtarget->isThumb() || !Subtarget->isMClass())
1279       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
1280 
1281     // On v8, we have particularly efficient implementations of atomic fences
1282     // if they can be combined with nearby atomic loads and stores.
1283     if (!Subtarget->hasAcquireRelease() ||
1284         getTargetMachine().getOptLevel() == 0) {
1285       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1286       InsertFencesForAtomic = true;
1287     }
1288   } else {
1289     // If there's anything we can use as a barrier, go through custom lowering
1290     // for ATOMIC_FENCE.
1291     // If target has DMB in thumb, Fences can be inserted.
1292     if (Subtarget->hasDataBarrier())
1293       InsertFencesForAtomic = true;
1294 
1295     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1296                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1297 
1298     // Set them all for expansion, which will force libcalls.
1299     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1300     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1301     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1302     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1303     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1304     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1305     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1306     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1307     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1308     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1309     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1310     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1311     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1312     // Unordered/Monotonic case.
1313     if (!InsertFencesForAtomic) {
1314       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1315       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1316     }
1317   }
1318 
1319   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1320 
1321   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1322   if (!Subtarget->hasV6Ops()) {
1323     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1324     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1325   }
1326   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1327 
1328   if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1329       !Subtarget->isThumb1Only()) {
1330     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1331     // iff target supports vfp2.
1332     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1333     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1334   }
1335 
1336   // We want to custom lower some of our intrinsics.
1337   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1338   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1339   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1340   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1341   if (Subtarget->useSjLjEH())
1342     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1343 
1344   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1345   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1346   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1347   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1348   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1349   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1350   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1351   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1352   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1353   if (Subtarget->hasFullFP16()) {
1354     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1355     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1356     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1357   }
1358 
1359   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1360 
1361   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1362   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1363   if (Subtarget->hasFullFP16())
1364       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1365   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1366   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1367   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1368 
1369   // We don't support sin/cos/fmod/copysign/pow
1370   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1371   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1372   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1373   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1374   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1375   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1376   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1377   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1378   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1379       !Subtarget->isThumb1Only()) {
1380     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1381     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1382   }
1383   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1384   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1385 
1386   if (!Subtarget->hasVFP4Base()) {
1387     setOperationAction(ISD::FMA, MVT::f64, Expand);
1388     setOperationAction(ISD::FMA, MVT::f32, Expand);
1389   }
1390 
1391   // Various VFP goodness
1392   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1393     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1394     if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1395       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1396       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1397     }
1398 
1399     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1400     if (!Subtarget->hasFP16()) {
1401       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1402       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1403     }
1404 
1405     // Strict floating-point comparisons need custom lowering.
1406     setOperationAction(ISD::STRICT_FSETCC,  MVT::f16, Custom);
1407     setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
1408     setOperationAction(ISD::STRICT_FSETCC,  MVT::f32, Custom);
1409     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
1410     setOperationAction(ISD::STRICT_FSETCC,  MVT::f64, Custom);
1411     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
1412   }
1413 
1414   // Use __sincos_stret if available.
1415   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1416       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1417     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1418     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1419   }
1420 
1421   // FP-ARMv8 implements a lot of rounding-like FP operations.
1422   if (Subtarget->hasFPARMv8Base()) {
1423     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1424     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1425     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1426     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1427     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1428     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1429     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1430     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1431     if (Subtarget->hasNEON()) {
1432       setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1433       setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1434       setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1435       setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1436     }
1437 
1438     if (Subtarget->hasFP64()) {
1439       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1440       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1441       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1442       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1443       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1444       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1445       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1446       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1447     }
1448   }
1449 
1450   // FP16 often need to be promoted to call lib functions
1451   if (Subtarget->hasFullFP16()) {
1452     setOperationAction(ISD::FREM, MVT::f16, Promote);
1453     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1454     setOperationAction(ISD::FSIN, MVT::f16, Promote);
1455     setOperationAction(ISD::FCOS, MVT::f16, Promote);
1456     setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1457     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1458     setOperationAction(ISD::FPOW, MVT::f16, Promote);
1459     setOperationAction(ISD::FEXP, MVT::f16, Promote);
1460     setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1461     setOperationAction(ISD::FLOG, MVT::f16, Promote);
1462     setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1463     setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1464 
1465     setOperationAction(ISD::FROUND, MVT::f16, Legal);
1466   }
1467 
1468   if (Subtarget->hasNEON()) {
1469     // vmin and vmax aren't available in a scalar form, so we can use
1470     // a NEON instruction with an undef lane instead.  This has a performance
1471     // penalty on some cores, so we don't do this unless we have been
1472     // asked to by the core tuning model.
1473     if (Subtarget->useNEONForSinglePrecisionFP()) {
1474       setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1475       setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1476       setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1477       setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1478     }
1479     setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1480     setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1481     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1482     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1483 
1484     if (Subtarget->hasFullFP16()) {
1485       setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1486       setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1487       setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1488       setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1489 
1490       setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1491       setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1492       setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1493       setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1494     }
1495   }
1496 
1497   // We have target-specific dag combine patterns for the following nodes:
1498   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1499   setTargetDAGCombine(ISD::ADD);
1500   setTargetDAGCombine(ISD::SUB);
1501   setTargetDAGCombine(ISD::MUL);
1502   setTargetDAGCombine(ISD::AND);
1503   setTargetDAGCombine(ISD::OR);
1504   setTargetDAGCombine(ISD::XOR);
1505 
1506   if (Subtarget->hasMVEIntegerOps())
1507     setTargetDAGCombine(ISD::VSELECT);
1508 
1509   if (Subtarget->hasV6Ops())
1510     setTargetDAGCombine(ISD::SRL);
1511   if (Subtarget->isThumb1Only())
1512     setTargetDAGCombine(ISD::SHL);
1513 
1514   setStackPointerRegisterToSaveRestore(ARM::SP);
1515 
1516   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1517       !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1518     setSchedulingPreference(Sched::RegPressure);
1519   else
1520     setSchedulingPreference(Sched::Hybrid);
1521 
1522   //// temporary - rewrite interface to use type
1523   MaxStoresPerMemset = 8;
1524   MaxStoresPerMemsetOptSize = 4;
1525   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1526   MaxStoresPerMemcpyOptSize = 2;
1527   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1528   MaxStoresPerMemmoveOptSize = 2;
1529 
1530   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1531   // are at least 4 bytes aligned.
1532   setMinStackArgumentAlignment(Align(4));
1533 
1534   // Prefer likely predicted branches to selects on out-of-order cores.
1535   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1536 
1537   setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1538 
1539   setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1540 
1541   if (Subtarget->isThumb() || Subtarget->isThumb2())
1542     setTargetDAGCombine(ISD::ABS);
1543 }
1544 
1545 bool ARMTargetLowering::useSoftFloat() const {
1546   return Subtarget->useSoftFloat();
1547 }
1548 
1549 // FIXME: It might make sense to define the representative register class as the
1550 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1551 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1552 // SPR's representative would be DPR_VFP2. This should work well if register
1553 // pressure tracking were modified such that a register use would increment the
1554 // pressure of the register class's representative and all of it's super
1555 // classes' representatives transitively. We have not implemented this because
1556 // of the difficulty prior to coalescing of modeling operand register classes
1557 // due to the common occurrence of cross class copies and subregister insertions
1558 // and extractions.
1559 std::pair<const TargetRegisterClass *, uint8_t>
1560 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1561                                            MVT VT) const {
1562   const TargetRegisterClass *RRC = nullptr;
1563   uint8_t Cost = 1;
1564   switch (VT.SimpleTy) {
1565   default:
1566     return TargetLowering::findRepresentativeClass(TRI, VT);
1567   // Use DPR as representative register class for all floating point
1568   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1569   // the cost is 1 for both f32 and f64.
1570   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1571   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1572     RRC = &ARM::DPRRegClass;
1573     // When NEON is used for SP, only half of the register file is available
1574     // because operations that define both SP and DP results will be constrained
1575     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1576     // coalescing by double-counting the SP regs. See the FIXME above.
1577     if (Subtarget->useNEONForSinglePrecisionFP())
1578       Cost = 2;
1579     break;
1580   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1581   case MVT::v4f32: case MVT::v2f64:
1582     RRC = &ARM::DPRRegClass;
1583     Cost = 2;
1584     break;
1585   case MVT::v4i64:
1586     RRC = &ARM::DPRRegClass;
1587     Cost = 4;
1588     break;
1589   case MVT::v8i64:
1590     RRC = &ARM::DPRRegClass;
1591     Cost = 8;
1592     break;
1593   }
1594   return std::make_pair(RRC, Cost);
1595 }
1596 
1597 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1598   switch ((ARMISD::NodeType)Opcode) {
1599   case ARMISD::FIRST_NUMBER:  break;
1600   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1601   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1602   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1603   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1604   case ARMISD::CALL:          return "ARMISD::CALL";
1605   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1606   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1607   case ARMISD::tSECALL:       return "ARMISD::tSECALL";
1608   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1609   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1610   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1611   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1612   case ARMISD::SERET_FLAG:    return "ARMISD::SERET_FLAG";
1613   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1614   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1615   case ARMISD::CMP:           return "ARMISD::CMP";
1616   case ARMISD::CMN:           return "ARMISD::CMN";
1617   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1618   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1619   case ARMISD::CMPFPE:        return "ARMISD::CMPFPE";
1620   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1621   case ARMISD::CMPFPEw0:      return "ARMISD::CMPFPEw0";
1622   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1623   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1624 
1625   case ARMISD::CMOV:          return "ARMISD::CMOV";
1626   case ARMISD::SUBS:          return "ARMISD::SUBS";
1627 
1628   case ARMISD::SSAT:          return "ARMISD::SSAT";
1629   case ARMISD::USAT:          return "ARMISD::USAT";
1630 
1631   case ARMISD::ASRL:          return "ARMISD::ASRL";
1632   case ARMISD::LSRL:          return "ARMISD::LSRL";
1633   case ARMISD::LSLL:          return "ARMISD::LSLL";
1634 
1635   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1636   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1637   case ARMISD::RRX:           return "ARMISD::RRX";
1638 
1639   case ARMISD::ADDC:          return "ARMISD::ADDC";
1640   case ARMISD::ADDE:          return "ARMISD::ADDE";
1641   case ARMISD::SUBC:          return "ARMISD::SUBC";
1642   case ARMISD::SUBE:          return "ARMISD::SUBE";
1643   case ARMISD::LSLS:          return "ARMISD::LSLS";
1644 
1645   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1646   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1647   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1648   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1649   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
1650 
1651   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1652   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1653   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1654 
1655   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1656 
1657   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1658 
1659   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1660 
1661   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1662 
1663   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1664 
1665   case ARMISD::LDRD:          return "ARMISD::LDRD";
1666   case ARMISD::STRD:          return "ARMISD::STRD";
1667 
1668   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1669   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1670 
1671   case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1672   case ARMISD::VECTOR_REG_CAST: return "ARMISD::VECTOR_REG_CAST";
1673   case ARMISD::VCMP:          return "ARMISD::VCMP";
1674   case ARMISD::VCMPZ:         return "ARMISD::VCMPZ";
1675   case ARMISD::VTST:          return "ARMISD::VTST";
1676 
1677   case ARMISD::VSHLs:         return "ARMISD::VSHLs";
1678   case ARMISD::VSHLu:         return "ARMISD::VSHLu";
1679   case ARMISD::VSHLIMM:       return "ARMISD::VSHLIMM";
1680   case ARMISD::VSHRsIMM:      return "ARMISD::VSHRsIMM";
1681   case ARMISD::VSHRuIMM:      return "ARMISD::VSHRuIMM";
1682   case ARMISD::VRSHRsIMM:     return "ARMISD::VRSHRsIMM";
1683   case ARMISD::VRSHRuIMM:     return "ARMISD::VRSHRuIMM";
1684   case ARMISD::VRSHRNIMM:     return "ARMISD::VRSHRNIMM";
1685   case ARMISD::VQSHLsIMM:     return "ARMISD::VQSHLsIMM";
1686   case ARMISD::VQSHLuIMM:     return "ARMISD::VQSHLuIMM";
1687   case ARMISD::VQSHLsuIMM:    return "ARMISD::VQSHLsuIMM";
1688   case ARMISD::VQSHRNsIMM:    return "ARMISD::VQSHRNsIMM";
1689   case ARMISD::VQSHRNuIMM:    return "ARMISD::VQSHRNuIMM";
1690   case ARMISD::VQSHRNsuIMM:   return "ARMISD::VQSHRNsuIMM";
1691   case ARMISD::VQRSHRNsIMM:   return "ARMISD::VQRSHRNsIMM";
1692   case ARMISD::VQRSHRNuIMM:   return "ARMISD::VQRSHRNuIMM";
1693   case ARMISD::VQRSHRNsuIMM:  return "ARMISD::VQRSHRNsuIMM";
1694   case ARMISD::VSLIIMM:       return "ARMISD::VSLIIMM";
1695   case ARMISD::VSRIIMM:       return "ARMISD::VSRIIMM";
1696   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1697   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1698   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1699   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1700   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1701   case ARMISD::VDUP:          return "ARMISD::VDUP";
1702   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1703   case ARMISD::VEXT:          return "ARMISD::VEXT";
1704   case ARMISD::VREV64:        return "ARMISD::VREV64";
1705   case ARMISD::VREV32:        return "ARMISD::VREV32";
1706   case ARMISD::VREV16:        return "ARMISD::VREV16";
1707   case ARMISD::VZIP:          return "ARMISD::VZIP";
1708   case ARMISD::VUZP:          return "ARMISD::VUZP";
1709   case ARMISD::VTRN:          return "ARMISD::VTRN";
1710   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1711   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1712   case ARMISD::VMOVN:         return "ARMISD::VMOVN";
1713   case ARMISD::VQMOVNs:       return "ARMISD::VQMOVNs";
1714   case ARMISD::VQMOVNu:       return "ARMISD::VQMOVNu";
1715   case ARMISD::VCVTN:         return "ARMISD::VCVTN";
1716   case ARMISD::VCVTL:         return "ARMISD::VCVTL";
1717   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1718   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1719   case ARMISD::VADDVs:        return "ARMISD::VADDVs";
1720   case ARMISD::VADDVu:        return "ARMISD::VADDVu";
1721   case ARMISD::VADDVps:       return "ARMISD::VADDVps";
1722   case ARMISD::VADDVpu:       return "ARMISD::VADDVpu";
1723   case ARMISD::VADDLVs:       return "ARMISD::VADDLVs";
1724   case ARMISD::VADDLVu:       return "ARMISD::VADDLVu";
1725   case ARMISD::VADDLVAs:      return "ARMISD::VADDLVAs";
1726   case ARMISD::VADDLVAu:      return "ARMISD::VADDLVAu";
1727   case ARMISD::VADDLVps:      return "ARMISD::VADDLVps";
1728   case ARMISD::VADDLVpu:      return "ARMISD::VADDLVpu";
1729   case ARMISD::VADDLVAps:     return "ARMISD::VADDLVAps";
1730   case ARMISD::VADDLVApu:     return "ARMISD::VADDLVApu";
1731   case ARMISD::VMLAVs:        return "ARMISD::VMLAVs";
1732   case ARMISD::VMLAVu:        return "ARMISD::VMLAVu";
1733   case ARMISD::VMLAVps:       return "ARMISD::VMLAVps";
1734   case ARMISD::VMLAVpu:       return "ARMISD::VMLAVpu";
1735   case ARMISD::VMLALVs:       return "ARMISD::VMLALVs";
1736   case ARMISD::VMLALVu:       return "ARMISD::VMLALVu";
1737   case ARMISD::VMLALVps:      return "ARMISD::VMLALVps";
1738   case ARMISD::VMLALVpu:      return "ARMISD::VMLALVpu";
1739   case ARMISD::VMLALVAs:      return "ARMISD::VMLALVAs";
1740   case ARMISD::VMLALVAu:      return "ARMISD::VMLALVAu";
1741   case ARMISD::VMLALVAps:     return "ARMISD::VMLALVAps";
1742   case ARMISD::VMLALVApu:     return "ARMISD::VMLALVApu";
1743   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1744   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1745   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1746   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1747   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1748   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1749   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1750   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1751   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1752   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1753   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1754   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1755   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1756   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1757   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1758   case ARMISD::QADD16b:       return "ARMISD::QADD16b";
1759   case ARMISD::QSUB16b:       return "ARMISD::QSUB16b";
1760   case ARMISD::QADD8b:        return "ARMISD::QADD8b";
1761   case ARMISD::QSUB8b:        return "ARMISD::QSUB8b";
1762   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1763   case ARMISD::BFI:           return "ARMISD::BFI";
1764   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1765   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1766   case ARMISD::VBSP:          return "ARMISD::VBSP";
1767   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1768   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1769   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1770   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1771   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1772   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1773   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1774   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1775   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1776   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1777   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1778   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1779   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1780   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1781   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1782   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1783   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1784   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1785   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1786   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1787   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1788   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1789   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1790   case ARMISD::WLS:           return "ARMISD::WLS";
1791   case ARMISD::LE:            return "ARMISD::LE";
1792   case ARMISD::LOOP_DEC:      return "ARMISD::LOOP_DEC";
1793   case ARMISD::CSINV:         return "ARMISD::CSINV";
1794   case ARMISD::CSNEG:         return "ARMISD::CSNEG";
1795   case ARMISD::CSINC:         return "ARMISD::CSINC";
1796   }
1797   return nullptr;
1798 }
1799 
1800 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1801                                           EVT VT) const {
1802   if (!VT.isVector())
1803     return getPointerTy(DL);
1804 
1805   // MVE has a predicate register.
1806   if (Subtarget->hasMVEIntegerOps() &&
1807       (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1808     return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1809   return VT.changeVectorElementTypeToInteger();
1810 }
1811 
1812 /// getRegClassFor - Return the register class that should be used for the
1813 /// specified value type.
1814 const TargetRegisterClass *
1815 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1816   (void)isDivergent;
1817   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1818   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1819   // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1820   // MVE Q registers.
1821   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1822     if (VT == MVT::v4i64)
1823       return &ARM::QQPRRegClass;
1824     if (VT == MVT::v8i64)
1825       return &ARM::QQQQPRRegClass;
1826   }
1827   return TargetLowering::getRegClassFor(VT);
1828 }
1829 
1830 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1831 // source/dest is aligned and the copy size is large enough. We therefore want
1832 // to align such objects passed to memory intrinsics.
1833 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1834                                                unsigned &PrefAlign) const {
1835   if (!isa<MemIntrinsic>(CI))
1836     return false;
1837   MinSize = 8;
1838   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1839   // cycle faster than 4-byte aligned LDM.
1840   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1841   return true;
1842 }
1843 
1844 // Create a fast isel object.
1845 FastISel *
1846 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1847                                   const TargetLibraryInfo *libInfo) const {
1848   return ARM::createFastISel(funcInfo, libInfo);
1849 }
1850 
1851 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1852   unsigned NumVals = N->getNumValues();
1853   if (!NumVals)
1854     return Sched::RegPressure;
1855 
1856   for (unsigned i = 0; i != NumVals; ++i) {
1857     EVT VT = N->getValueType(i);
1858     if (VT == MVT::Glue || VT == MVT::Other)
1859       continue;
1860     if (VT.isFloatingPoint() || VT.isVector())
1861       return Sched::ILP;
1862   }
1863 
1864   if (!N->isMachineOpcode())
1865     return Sched::RegPressure;
1866 
1867   // Load are scheduled for latency even if there instruction itinerary
1868   // is not available.
1869   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1870   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1871 
1872   if (MCID.getNumDefs() == 0)
1873     return Sched::RegPressure;
1874   if (!Itins->isEmpty() &&
1875       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1876     return Sched::ILP;
1877 
1878   return Sched::RegPressure;
1879 }
1880 
1881 //===----------------------------------------------------------------------===//
1882 // Lowering Code
1883 //===----------------------------------------------------------------------===//
1884 
1885 static bool isSRL16(const SDValue &Op) {
1886   if (Op.getOpcode() != ISD::SRL)
1887     return false;
1888   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1889     return Const->getZExtValue() == 16;
1890   return false;
1891 }
1892 
1893 static bool isSRA16(const SDValue &Op) {
1894   if (Op.getOpcode() != ISD::SRA)
1895     return false;
1896   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1897     return Const->getZExtValue() == 16;
1898   return false;
1899 }
1900 
1901 static bool isSHL16(const SDValue &Op) {
1902   if (Op.getOpcode() != ISD::SHL)
1903     return false;
1904   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1905     return Const->getZExtValue() == 16;
1906   return false;
1907 }
1908 
1909 // Check for a signed 16-bit value. We special case SRA because it makes it
1910 // more simple when also looking for SRAs that aren't sign extending a
1911 // smaller value. Without the check, we'd need to take extra care with
1912 // checking order for some operations.
1913 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1914   if (isSRA16(Op))
1915     return isSHL16(Op.getOperand(0));
1916   return DAG.ComputeNumSignBits(Op) == 17;
1917 }
1918 
1919 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1920 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1921   switch (CC) {
1922   default: llvm_unreachable("Unknown condition code!");
1923   case ISD::SETNE:  return ARMCC::NE;
1924   case ISD::SETEQ:  return ARMCC::EQ;
1925   case ISD::SETGT:  return ARMCC::GT;
1926   case ISD::SETGE:  return ARMCC::GE;
1927   case ISD::SETLT:  return ARMCC::LT;
1928   case ISD::SETLE:  return ARMCC::LE;
1929   case ISD::SETUGT: return ARMCC::HI;
1930   case ISD::SETUGE: return ARMCC::HS;
1931   case ISD::SETULT: return ARMCC::LO;
1932   case ISD::SETULE: return ARMCC::LS;
1933   }
1934 }
1935 
1936 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1937 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1938                         ARMCC::CondCodes &CondCode2) {
1939   CondCode2 = ARMCC::AL;
1940   switch (CC) {
1941   default: llvm_unreachable("Unknown FP condition!");
1942   case ISD::SETEQ:
1943   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1944   case ISD::SETGT:
1945   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1946   case ISD::SETGE:
1947   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1948   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1949   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1950   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1951   case ISD::SETO:   CondCode = ARMCC::VC; break;
1952   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1953   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1954   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1955   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1956   case ISD::SETLT:
1957   case ISD::SETULT: CondCode = ARMCC::LT; break;
1958   case ISD::SETLE:
1959   case ISD::SETULE: CondCode = ARMCC::LE; break;
1960   case ISD::SETNE:
1961   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1962   }
1963 }
1964 
1965 //===----------------------------------------------------------------------===//
1966 //                      Calling Convention Implementation
1967 //===----------------------------------------------------------------------===//
1968 
1969 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1970 /// account presence of floating point hardware and calling convention
1971 /// limitations, such as support for variadic functions.
1972 CallingConv::ID
1973 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1974                                            bool isVarArg) const {
1975   switch (CC) {
1976   default:
1977     report_fatal_error("Unsupported calling convention");
1978   case CallingConv::ARM_AAPCS:
1979   case CallingConv::ARM_APCS:
1980   case CallingConv::GHC:
1981   case CallingConv::CFGuard_Check:
1982     return CC;
1983   case CallingConv::PreserveMost:
1984     return CallingConv::PreserveMost;
1985   case CallingConv::ARM_AAPCS_VFP:
1986   case CallingConv::Swift:
1987     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1988   case CallingConv::C:
1989     if (!Subtarget->isAAPCS_ABI())
1990       return CallingConv::ARM_APCS;
1991     else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1992              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1993              !isVarArg)
1994       return CallingConv::ARM_AAPCS_VFP;
1995     else
1996       return CallingConv::ARM_AAPCS;
1997   case CallingConv::Fast:
1998   case CallingConv::CXX_FAST_TLS:
1999     if (!Subtarget->isAAPCS_ABI()) {
2000       if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
2001         return CallingConv::Fast;
2002       return CallingConv::ARM_APCS;
2003     } else if (Subtarget->hasVFP2Base() &&
2004                !Subtarget->isThumb1Only() && !isVarArg)
2005       return CallingConv::ARM_AAPCS_VFP;
2006     else
2007       return CallingConv::ARM_AAPCS;
2008   }
2009 }
2010 
2011 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2012                                                  bool isVarArg) const {
2013   return CCAssignFnForNode(CC, false, isVarArg);
2014 }
2015 
2016 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
2017                                                    bool isVarArg) const {
2018   return CCAssignFnForNode(CC, true, isVarArg);
2019 }
2020 
2021 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
2022 /// CallingConvention.
2023 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
2024                                                  bool Return,
2025                                                  bool isVarArg) const {
2026   switch (getEffectiveCallingConv(CC, isVarArg)) {
2027   default:
2028     report_fatal_error("Unsupported calling convention");
2029   case CallingConv::ARM_APCS:
2030     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
2031   case CallingConv::ARM_AAPCS:
2032     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2033   case CallingConv::ARM_AAPCS_VFP:
2034     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
2035   case CallingConv::Fast:
2036     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
2037   case CallingConv::GHC:
2038     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
2039   case CallingConv::PreserveMost:
2040     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
2041   case CallingConv::CFGuard_Check:
2042     return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
2043   }
2044 }
2045 
2046 SDValue ARMTargetLowering::MoveToHPR(const SDLoc &dl, SelectionDAG &DAG,
2047                                      MVT LocVT, MVT ValVT, SDValue Val) const {
2048   Val = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocVT.getSizeInBits()),
2049                     Val);
2050   if (Subtarget->hasFullFP16()) {
2051     Val = DAG.getNode(ARMISD::VMOVhr, dl, ValVT, Val);
2052   } else {
2053     Val = DAG.getNode(ISD::TRUNCATE, dl,
2054                       MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2055     Val = DAG.getNode(ISD::BITCAST, dl, ValVT, Val);
2056   }
2057   return Val;
2058 }
2059 
2060 SDValue ARMTargetLowering::MoveFromHPR(const SDLoc &dl, SelectionDAG &DAG,
2061                                        MVT LocVT, MVT ValVT,
2062                                        SDValue Val) const {
2063   if (Subtarget->hasFullFP16()) {
2064     Val = DAG.getNode(ARMISD::VMOVrh, dl,
2065                       MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2066   } else {
2067     Val = DAG.getNode(ISD::BITCAST, dl,
2068                       MVT::getIntegerVT(ValVT.getSizeInBits()), Val);
2069     Val = DAG.getNode(ISD::ZERO_EXTEND, dl,
2070                       MVT::getIntegerVT(LocVT.getSizeInBits()), Val);
2071   }
2072   return DAG.getNode(ISD::BITCAST, dl, LocVT, Val);
2073 }
2074 
2075 /// LowerCallResult - Lower the result values of a call into the
2076 /// appropriate copies out of appropriate physical registers.
2077 SDValue ARMTargetLowering::LowerCallResult(
2078     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2079     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2080     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2081     SDValue ThisVal) const {
2082   // Assign locations to each value returned by this call.
2083   SmallVector<CCValAssign, 16> RVLocs;
2084   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2085                  *DAG.getContext());
2086   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
2087 
2088   // Copy all of the result registers out of their specified physreg.
2089   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2090     CCValAssign VA = RVLocs[i];
2091 
2092     // Pass 'this' value directly from the argument to return value, to avoid
2093     // reg unit interference
2094     if (i == 0 && isThisReturn) {
2095       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
2096              "unexpected return calling convention register assignment");
2097       InVals.push_back(ThisVal);
2098       continue;
2099     }
2100 
2101     SDValue Val;
2102     if (VA.needsCustom() &&
2103         (VA.getLocVT() == MVT::f64 || VA.getLocVT() == MVT::v2f64)) {
2104       // Handle f64 or half of a v2f64.
2105       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2106                                       InFlag);
2107       Chain = Lo.getValue(1);
2108       InFlag = Lo.getValue(2);
2109       VA = RVLocs[++i]; // skip ahead to next loc
2110       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
2111                                       InFlag);
2112       Chain = Hi.getValue(1);
2113       InFlag = Hi.getValue(2);
2114       if (!Subtarget->isLittle())
2115         std::swap (Lo, Hi);
2116       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2117 
2118       if (VA.getLocVT() == MVT::v2f64) {
2119         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
2120         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2121                           DAG.getConstant(0, dl, MVT::i32));
2122 
2123         VA = RVLocs[++i]; // skip ahead to next loc
2124         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2125         Chain = Lo.getValue(1);
2126         InFlag = Lo.getValue(2);
2127         VA = RVLocs[++i]; // skip ahead to next loc
2128         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2129         Chain = Hi.getValue(1);
2130         InFlag = Hi.getValue(2);
2131         if (!Subtarget->isLittle())
2132           std::swap (Lo, Hi);
2133         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2134         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2135                           DAG.getConstant(1, dl, MVT::i32));
2136       }
2137     } else {
2138       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2139                                InFlag);
2140       Chain = Val.getValue(1);
2141       InFlag = Val.getValue(2);
2142     }
2143 
2144     switch (VA.getLocInfo()) {
2145     default: llvm_unreachable("Unknown loc info!");
2146     case CCValAssign::Full: break;
2147     case CCValAssign::BCvt:
2148       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2149       break;
2150     }
2151 
2152     // f16 arguments have their size extended to 4 bytes and passed as if they
2153     // had been copied to the LSBs of a 32-bit register.
2154     // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2155     if (VA.needsCustom() &&
2156         (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
2157       Val = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Val);
2158 
2159     InVals.push_back(Val);
2160   }
2161 
2162   return Chain;
2163 }
2164 
2165 /// LowerMemOpCallTo - Store the argument to the stack.
2166 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
2167                                             SDValue Arg, const SDLoc &dl,
2168                                             SelectionDAG &DAG,
2169                                             const CCValAssign &VA,
2170                                             ISD::ArgFlagsTy Flags) const {
2171   unsigned LocMemOffset = VA.getLocMemOffset();
2172   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2173   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2174                        StackPtr, PtrOff);
2175   return DAG.getStore(
2176       Chain, dl, Arg, PtrOff,
2177       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2178 }
2179 
2180 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2181                                          SDValue Chain, SDValue &Arg,
2182                                          RegsToPassVector &RegsToPass,
2183                                          CCValAssign &VA, CCValAssign &NextVA,
2184                                          SDValue &StackPtr,
2185                                          SmallVectorImpl<SDValue> &MemOpChains,
2186                                          ISD::ArgFlagsTy Flags) const {
2187   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2188                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
2189   unsigned id = Subtarget->isLittle() ? 0 : 1;
2190   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2191 
2192   if (NextVA.isRegLoc())
2193     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2194   else {
2195     assert(NextVA.isMemLoc());
2196     if (!StackPtr.getNode())
2197       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2198                                     getPointerTy(DAG.getDataLayout()));
2199 
2200     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2201                                            dl, DAG, NextVA,
2202                                            Flags));
2203   }
2204 }
2205 
2206 /// LowerCall - Lowering a call into a callseq_start <-
2207 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2208 /// nodes.
2209 SDValue
2210 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2211                              SmallVectorImpl<SDValue> &InVals) const {
2212   SelectionDAG &DAG                     = CLI.DAG;
2213   SDLoc &dl                             = CLI.DL;
2214   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2215   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2216   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2217   SDValue Chain                         = CLI.Chain;
2218   SDValue Callee                        = CLI.Callee;
2219   bool &isTailCall                      = CLI.IsTailCall;
2220   CallingConv::ID CallConv              = CLI.CallConv;
2221   bool doesNotRet                       = CLI.DoesNotReturn;
2222   bool isVarArg                         = CLI.IsVarArg;
2223 
2224   MachineFunction &MF = DAG.getMachineFunction();
2225   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2226   MachineFunction::CallSiteInfo CSInfo;
2227   bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2228   bool isThisReturn = false;
2229   bool isCmseNSCall   = false;
2230   bool PreferIndirect = false;
2231 
2232   // Determine whether this is a non-secure function call.
2233   if (CLI.CB && CLI.CB->getAttributes().hasFnAttribute("cmse_nonsecure_call"))
2234     isCmseNSCall = true;
2235 
2236   // Disable tail calls if they're not supported.
2237   if (!Subtarget->supportsTailCall())
2238     isTailCall = false;
2239 
2240   // For both the non-secure calls and the returns from a CMSE entry function,
2241   // the function needs to do some extra work afte r the call, or before the
2242   // return, respectively, thus it cannot end with atail call
2243   if (isCmseNSCall || AFI->isCmseNSEntryFunction())
2244     isTailCall = false;
2245 
2246   if (isa<GlobalAddressSDNode>(Callee)) {
2247     // If we're optimizing for minimum size and the function is called three or
2248     // more times in this block, we can improve codesize by calling indirectly
2249     // as BLXr has a 16-bit encoding.
2250     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2251     if (CLI.CB) {
2252       auto *BB = CLI.CB->getParent();
2253       PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2254                        count_if(GV->users(), [&BB](const User *U) {
2255                          return isa<Instruction>(U) &&
2256                                 cast<Instruction>(U)->getParent() == BB;
2257                        }) > 2;
2258     }
2259   }
2260   if (isTailCall) {
2261     // Check if it's really possible to do a tail call.
2262     isTailCall = IsEligibleForTailCallOptimization(
2263         Callee, CallConv, isVarArg, isStructRet,
2264         MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2265         PreferIndirect);
2266     if (!isTailCall && CLI.CB && CLI.CB->isMustTailCall())
2267       report_fatal_error("failed to perform tail call elimination on a call "
2268                          "site marked musttail");
2269     // We don't support GuaranteedTailCallOpt for ARM, only automatically
2270     // detected sibcalls.
2271     if (isTailCall)
2272       ++NumTailCalls;
2273   }
2274 
2275   // Analyze operands of the call, assigning locations to each operand.
2276   SmallVector<CCValAssign, 16> ArgLocs;
2277   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2278                  *DAG.getContext());
2279   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2280 
2281   // Get a count of how many bytes are to be pushed on the stack.
2282   unsigned NumBytes = CCInfo.getNextStackOffset();
2283 
2284   if (isTailCall) {
2285     // For tail calls, memory operands are available in our caller's stack.
2286     NumBytes = 0;
2287   } else {
2288     // Adjust the stack pointer for the new arguments...
2289     // These operations are automatically eliminated by the prolog/epilog pass
2290     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2291   }
2292 
2293   SDValue StackPtr =
2294       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2295 
2296   RegsToPassVector RegsToPass;
2297   SmallVector<SDValue, 8> MemOpChains;
2298 
2299   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2300   // of tail call optimization, arguments are handled later.
2301   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2302        i != e;
2303        ++i, ++realArgIdx) {
2304     CCValAssign &VA = ArgLocs[i];
2305     SDValue Arg = OutVals[realArgIdx];
2306     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2307     bool isByVal = Flags.isByVal();
2308 
2309     // Promote the value if needed.
2310     switch (VA.getLocInfo()) {
2311     default: llvm_unreachable("Unknown loc info!");
2312     case CCValAssign::Full: break;
2313     case CCValAssign::SExt:
2314       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2315       break;
2316     case CCValAssign::ZExt:
2317       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2318       break;
2319     case CCValAssign::AExt:
2320       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2321       break;
2322     case CCValAssign::BCvt:
2323       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2324       break;
2325     }
2326 
2327     // f16 arguments have their size extended to 4 bytes and passed as if they
2328     // had been copied to the LSBs of a 32-bit register.
2329     // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
2330     if (VA.needsCustom() &&
2331         (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16)) {
2332       Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
2333     } else {
2334       // f16 arguments could have been extended prior to argument lowering.
2335       // Mask them arguments if this is a CMSE nonsecure call.
2336       auto ArgVT = Outs[realArgIdx].ArgVT;
2337       if (isCmseNSCall && (ArgVT == MVT::f16)) {
2338         auto LocBits = VA.getLocVT().getSizeInBits();
2339         auto MaskValue = APInt::getLowBitsSet(LocBits, ArgVT.getSizeInBits());
2340         SDValue Mask =
2341             DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
2342         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
2343         Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
2344         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2345       }
2346     }
2347 
2348     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2349     if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
2350       SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2351                                 DAG.getConstant(0, dl, MVT::i32));
2352       SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2353                                 DAG.getConstant(1, dl, MVT::i32));
2354 
2355       PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass, VA, ArgLocs[++i],
2356                        StackPtr, MemOpChains, Flags);
2357 
2358       VA = ArgLocs[++i]; // skip ahead to next loc
2359       if (VA.isRegLoc()) {
2360         PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass, VA, ArgLocs[++i],
2361                          StackPtr, MemOpChains, Flags);
2362       } else {
2363         assert(VA.isMemLoc());
2364 
2365         MemOpChains.push_back(
2366             LowerMemOpCallTo(Chain, StackPtr, Op1, dl, DAG, VA, Flags));
2367       }
2368     } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
2369       PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2370                        StackPtr, MemOpChains, Flags);
2371     } else if (VA.isRegLoc()) {
2372       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2373           Outs[0].VT == MVT::i32) {
2374         assert(VA.getLocVT() == MVT::i32 &&
2375                "unexpected calling convention register assignment");
2376         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2377                "unexpected use of 'returned'");
2378         isThisReturn = true;
2379       }
2380       const TargetOptions &Options = DAG.getTarget().Options;
2381       if (Options.EmitCallSiteInfo)
2382         CSInfo.emplace_back(VA.getLocReg(), i);
2383       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2384     } else if (isByVal) {
2385       assert(VA.isMemLoc());
2386       unsigned offset = 0;
2387 
2388       // True if this byval aggregate will be split between registers
2389       // and memory.
2390       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2391       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2392 
2393       if (CurByValIdx < ByValArgsCount) {
2394 
2395         unsigned RegBegin, RegEnd;
2396         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2397 
2398         EVT PtrVT =
2399             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2400         unsigned int i, j;
2401         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2402           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2403           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2404           SDValue Load =
2405               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo(),
2406                           DAG.InferPtrAlign(AddArg));
2407           MemOpChains.push_back(Load.getValue(1));
2408           RegsToPass.push_back(std::make_pair(j, Load));
2409         }
2410 
2411         // If parameter size outsides register area, "offset" value
2412         // helps us to calculate stack slot for remained part properly.
2413         offset = RegEnd - RegBegin;
2414 
2415         CCInfo.nextInRegsParam();
2416       }
2417 
2418       if (Flags.getByValSize() > 4*offset) {
2419         auto PtrVT = getPointerTy(DAG.getDataLayout());
2420         unsigned LocMemOffset = VA.getLocMemOffset();
2421         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2422         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2423         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2424         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2425         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2426                                            MVT::i32);
2427         SDValue AlignNode =
2428             DAG.getConstant(Flags.getNonZeroByValAlign().value(), dl, MVT::i32);
2429 
2430         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2431         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2432         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2433                                           Ops));
2434       }
2435     } else if (!isTailCall) {
2436       assert(VA.isMemLoc());
2437 
2438       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2439                                              dl, DAG, VA, Flags));
2440     }
2441   }
2442 
2443   if (!MemOpChains.empty())
2444     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2445 
2446   // Build a sequence of copy-to-reg nodes chained together with token chain
2447   // and flag operands which copy the outgoing args into the appropriate regs.
2448   SDValue InFlag;
2449   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2450     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2451                              RegsToPass[i].second, InFlag);
2452     InFlag = Chain.getValue(1);
2453   }
2454 
2455   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2456   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2457   // node so that legalize doesn't hack it.
2458   bool isDirect = false;
2459 
2460   const TargetMachine &TM = getTargetMachine();
2461   const Module *Mod = MF.getFunction().getParent();
2462   const GlobalValue *GV = nullptr;
2463   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2464     GV = G->getGlobal();
2465   bool isStub =
2466       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2467 
2468   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2469   bool isLocalARMFunc = false;
2470   auto PtrVt = getPointerTy(DAG.getDataLayout());
2471 
2472   if (Subtarget->genLongCalls()) {
2473     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2474            "long-calls codegen is not position independent!");
2475     // Handle a global address or an external symbol. If it's not one of
2476     // those, the target's already in a register, so we don't need to do
2477     // anything extra.
2478     if (isa<GlobalAddressSDNode>(Callee)) {
2479       // Create a constant pool entry for the callee address
2480       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2481       ARMConstantPoolValue *CPV =
2482         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2483 
2484       // Get the address of the callee into a register
2485       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2486       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2487       Callee = DAG.getLoad(
2488           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2489           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2490     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2491       const char *Sym = S->getSymbol();
2492 
2493       // Create a constant pool entry for the callee address
2494       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2495       ARMConstantPoolValue *CPV =
2496         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2497                                       ARMPCLabelIndex, 0);
2498       // Get the address of the callee into a register
2499       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2500       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2501       Callee = DAG.getLoad(
2502           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2503           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2504     }
2505   } else if (isa<GlobalAddressSDNode>(Callee)) {
2506     if (!PreferIndirect) {
2507       isDirect = true;
2508       bool isDef = GV->isStrongDefinitionForLinker();
2509 
2510       // ARM call to a local ARM function is predicable.
2511       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2512       // tBX takes a register source operand.
2513       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2514         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2515         Callee = DAG.getNode(
2516             ARMISD::WrapperPIC, dl, PtrVt,
2517             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2518         Callee = DAG.getLoad(
2519             PtrVt, dl, DAG.getEntryNode(), Callee,
2520             MachinePointerInfo::getGOT(DAG.getMachineFunction()), MaybeAlign(),
2521             MachineMemOperand::MODereferenceable |
2522                 MachineMemOperand::MOInvariant);
2523       } else if (Subtarget->isTargetCOFF()) {
2524         assert(Subtarget->isTargetWindows() &&
2525                "Windows is the only supported COFF target");
2526         unsigned TargetFlags = ARMII::MO_NO_FLAG;
2527         if (GV->hasDLLImportStorageClass())
2528           TargetFlags = ARMII::MO_DLLIMPORT;
2529         else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
2530           TargetFlags = ARMII::MO_COFFSTUB;
2531         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2532                                             TargetFlags);
2533         if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2534           Callee =
2535               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2536                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2537                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2538       } else {
2539         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2540       }
2541     }
2542   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2543     isDirect = true;
2544     // tBX takes a register source operand.
2545     const char *Sym = S->getSymbol();
2546     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2547       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2548       ARMConstantPoolValue *CPV =
2549         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2550                                       ARMPCLabelIndex, 4);
2551       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, Align(4));
2552       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2553       Callee = DAG.getLoad(
2554           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2555           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2556       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2557       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2558     } else {
2559       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2560     }
2561   }
2562 
2563   if (isCmseNSCall) {
2564     assert(!isARMFunc && !isDirect &&
2565            "Cannot handle call to ARM function or direct call");
2566     if (NumBytes > 0) {
2567       DiagnosticInfoUnsupported Diag(DAG.getMachineFunction().getFunction(),
2568                                      "call to non-secure function would "
2569                                      "require passing arguments on stack",
2570                                      dl.getDebugLoc());
2571       DAG.getContext()->diagnose(Diag);
2572     }
2573     if (isStructRet) {
2574       DiagnosticInfoUnsupported Diag(
2575           DAG.getMachineFunction().getFunction(),
2576           "call to non-secure function would return value through pointer",
2577           dl.getDebugLoc());
2578       DAG.getContext()->diagnose(Diag);
2579     }
2580   }
2581 
2582   // FIXME: handle tail calls differently.
2583   unsigned CallOpc;
2584   if (Subtarget->isThumb()) {
2585     if (isCmseNSCall)
2586       CallOpc = ARMISD::tSECALL;
2587     else if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2588       CallOpc = ARMISD::CALL_NOLINK;
2589     else
2590       CallOpc = ARMISD::CALL;
2591   } else {
2592     if (!isDirect && !Subtarget->hasV5TOps())
2593       CallOpc = ARMISD::CALL_NOLINK;
2594     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2595              // Emit regular call when code size is the priority
2596              !Subtarget->hasMinSize())
2597       // "mov lr, pc; b _foo" to avoid confusing the RSP
2598       CallOpc = ARMISD::CALL_NOLINK;
2599     else
2600       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2601   }
2602 
2603   std::vector<SDValue> Ops;
2604   Ops.push_back(Chain);
2605   Ops.push_back(Callee);
2606 
2607   // Add argument registers to the end of the list so that they are known live
2608   // into the call.
2609   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2610     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2611                                   RegsToPass[i].second.getValueType()));
2612 
2613   // Add a register mask operand representing the call-preserved registers.
2614   if (!isTailCall) {
2615     const uint32_t *Mask;
2616     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2617     if (isThisReturn) {
2618       // For 'this' returns, use the R0-preserving mask if applicable
2619       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2620       if (!Mask) {
2621         // Set isThisReturn to false if the calling convention is not one that
2622         // allows 'returned' to be modeled in this way, so LowerCallResult does
2623         // not try to pass 'this' straight through
2624         isThisReturn = false;
2625         Mask = ARI->getCallPreservedMask(MF, CallConv);
2626       }
2627     } else
2628       Mask = ARI->getCallPreservedMask(MF, CallConv);
2629 
2630     assert(Mask && "Missing call preserved mask for calling convention");
2631     Ops.push_back(DAG.getRegisterMask(Mask));
2632   }
2633 
2634   if (InFlag.getNode())
2635     Ops.push_back(InFlag);
2636 
2637   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2638   if (isTailCall) {
2639     MF.getFrameInfo().setHasTailCall();
2640     SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2641     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2642     return Ret;
2643   }
2644 
2645   // Returns a chain and a flag for retval copy to use.
2646   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2647   DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
2648   InFlag = Chain.getValue(1);
2649   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2650 
2651   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2652                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2653   if (!Ins.empty())
2654     InFlag = Chain.getValue(1);
2655 
2656   // Handle result values, copying them out of physregs into vregs that we
2657   // return.
2658   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2659                          InVals, isThisReturn,
2660                          isThisReturn ? OutVals[0] : SDValue());
2661 }
2662 
2663 /// HandleByVal - Every parameter *after* a byval parameter is passed
2664 /// on the stack.  Remember the next parameter register to allocate,
2665 /// and then confiscate the rest of the parameter registers to insure
2666 /// this.
2667 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2668                                     Align Alignment) const {
2669   // Byval (as with any stack) slots are always at least 4 byte aligned.
2670   Alignment = std::max(Alignment, Align(4));
2671 
2672   unsigned Reg = State->AllocateReg(GPRArgRegs);
2673   if (!Reg)
2674     return;
2675 
2676   unsigned AlignInRegs = Alignment.value() / 4;
2677   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2678   for (unsigned i = 0; i < Waste; ++i)
2679     Reg = State->AllocateReg(GPRArgRegs);
2680 
2681   if (!Reg)
2682     return;
2683 
2684   unsigned Excess = 4 * (ARM::R4 - Reg);
2685 
2686   // Special case when NSAA != SP and parameter size greater than size of
2687   // all remained GPR regs. In that case we can't split parameter, we must
2688   // send it to stack. We also must set NCRN to R4, so waste all
2689   // remained registers.
2690   const unsigned NSAAOffset = State->getNextStackOffset();
2691   if (NSAAOffset != 0 && Size > Excess) {
2692     while (State->AllocateReg(GPRArgRegs))
2693       ;
2694     return;
2695   }
2696 
2697   // First register for byval parameter is the first register that wasn't
2698   // allocated before this method call, so it would be "reg".
2699   // If parameter is small enough to be saved in range [reg, r4), then
2700   // the end (first after last) register would be reg + param-size-in-regs,
2701   // else parameter would be splitted between registers and stack,
2702   // end register would be r4 in this case.
2703   unsigned ByValRegBegin = Reg;
2704   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2705   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2706   // Note, first register is allocated in the beginning of function already,
2707   // allocate remained amount of registers we need.
2708   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2709     State->AllocateReg(GPRArgRegs);
2710   // A byval parameter that is split between registers and memory needs its
2711   // size truncated here.
2712   // In the case where the entire structure fits in registers, we set the
2713   // size in memory to zero.
2714   Size = std::max<int>(Size - Excess, 0);
2715 }
2716 
2717 /// MatchingStackOffset - Return true if the given stack call argument is
2718 /// already available in the same position (relatively) of the caller's
2719 /// incoming argument stack.
2720 static
2721 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2722                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2723                          const TargetInstrInfo *TII) {
2724   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2725   int FI = std::numeric_limits<int>::max();
2726   if (Arg.getOpcode() == ISD::CopyFromReg) {
2727     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2728     if (!Register::isVirtualRegister(VR))
2729       return false;
2730     MachineInstr *Def = MRI->getVRegDef(VR);
2731     if (!Def)
2732       return false;
2733     if (!Flags.isByVal()) {
2734       if (!TII->isLoadFromStackSlot(*Def, FI))
2735         return false;
2736     } else {
2737       return false;
2738     }
2739   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2740     if (Flags.isByVal())
2741       // ByVal argument is passed in as a pointer but it's now being
2742       // dereferenced. e.g.
2743       // define @foo(%struct.X* %A) {
2744       //   tail call @bar(%struct.X* byval %A)
2745       // }
2746       return false;
2747     SDValue Ptr = Ld->getBasePtr();
2748     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2749     if (!FINode)
2750       return false;
2751     FI = FINode->getIndex();
2752   } else
2753     return false;
2754 
2755   assert(FI != std::numeric_limits<int>::max());
2756   if (!MFI.isFixedObjectIndex(FI))
2757     return false;
2758   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2759 }
2760 
2761 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2762 /// for tail call optimization. Targets which want to do tail call
2763 /// optimization should implement this function.
2764 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2765     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2766     bool isCalleeStructRet, bool isCallerStructRet,
2767     const SmallVectorImpl<ISD::OutputArg> &Outs,
2768     const SmallVectorImpl<SDValue> &OutVals,
2769     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2770     const bool isIndirect) const {
2771   MachineFunction &MF = DAG.getMachineFunction();
2772   const Function &CallerF = MF.getFunction();
2773   CallingConv::ID CallerCC = CallerF.getCallingConv();
2774 
2775   assert(Subtarget->supportsTailCall());
2776 
2777   // Indirect tail calls cannot be optimized for Thumb1 if the args
2778   // to the call take up r0-r3. The reason is that there are no legal registers
2779   // left to hold the pointer to the function to be called.
2780   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2781       (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2782     return false;
2783 
2784   // Look for obvious safe cases to perform tail call optimization that do not
2785   // require ABI changes. This is what gcc calls sibcall.
2786 
2787   // Exception-handling functions need a special set of instructions to indicate
2788   // a return to the hardware. Tail-calling another function would probably
2789   // break this.
2790   if (CallerF.hasFnAttribute("interrupt"))
2791     return false;
2792 
2793   // Also avoid sibcall optimization if either caller or callee uses struct
2794   // return semantics.
2795   if (isCalleeStructRet || isCallerStructRet)
2796     return false;
2797 
2798   // Externally-defined functions with weak linkage should not be
2799   // tail-called on ARM when the OS does not support dynamic
2800   // pre-emption of symbols, as the AAELF spec requires normal calls
2801   // to undefined weak functions to be replaced with a NOP or jump to the
2802   // next instruction. The behaviour of branch instructions in this
2803   // situation (as used for tail calls) is implementation-defined, so we
2804   // cannot rely on the linker replacing the tail call with a return.
2805   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2806     const GlobalValue *GV = G->getGlobal();
2807     const Triple &TT = getTargetMachine().getTargetTriple();
2808     if (GV->hasExternalWeakLinkage() &&
2809         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2810       return false;
2811   }
2812 
2813   // Check that the call results are passed in the same way.
2814   LLVMContext &C = *DAG.getContext();
2815   if (!CCState::resultsCompatible(
2816           getEffectiveCallingConv(CalleeCC, isVarArg),
2817           getEffectiveCallingConv(CallerCC, CallerF.isVarArg()), MF, C, Ins,
2818           CCAssignFnForReturn(CalleeCC, isVarArg),
2819           CCAssignFnForReturn(CallerCC, CallerF.isVarArg())))
2820     return false;
2821   // The callee has to preserve all registers the caller needs to preserve.
2822   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2823   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2824   if (CalleeCC != CallerCC) {
2825     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2826     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2827       return false;
2828   }
2829 
2830   // If Caller's vararg or byval argument has been split between registers and
2831   // stack, do not perform tail call, since part of the argument is in caller's
2832   // local frame.
2833   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2834   if (AFI_Caller->getArgRegsSaveSize())
2835     return false;
2836 
2837   // If the callee takes no arguments then go on to check the results of the
2838   // call.
2839   if (!Outs.empty()) {
2840     // Check if stack adjustment is needed. For now, do not do this if any
2841     // argument is passed on the stack.
2842     SmallVector<CCValAssign, 16> ArgLocs;
2843     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2844     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2845     if (CCInfo.getNextStackOffset()) {
2846       // Check if the arguments are already laid out in the right way as
2847       // the caller's fixed stack objects.
2848       MachineFrameInfo &MFI = MF.getFrameInfo();
2849       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2850       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2851       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2852            i != e;
2853            ++i, ++realArgIdx) {
2854         CCValAssign &VA = ArgLocs[i];
2855         EVT RegVT = VA.getLocVT();
2856         SDValue Arg = OutVals[realArgIdx];
2857         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2858         if (VA.getLocInfo() == CCValAssign::Indirect)
2859           return false;
2860         if (VA.needsCustom() && (RegVT == MVT::f64 || RegVT == MVT::v2f64)) {
2861           // f64 and vector types are split into multiple registers or
2862           // register/stack-slot combinations.  The types will not match
2863           // the registers; give up on memory f64 refs until we figure
2864           // out what to do about this.
2865           if (!VA.isRegLoc())
2866             return false;
2867           if (!ArgLocs[++i].isRegLoc())
2868             return false;
2869           if (RegVT == MVT::v2f64) {
2870             if (!ArgLocs[++i].isRegLoc())
2871               return false;
2872             if (!ArgLocs[++i].isRegLoc())
2873               return false;
2874           }
2875         } else if (!VA.isRegLoc()) {
2876           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2877                                    MFI, MRI, TII))
2878             return false;
2879         }
2880       }
2881     }
2882 
2883     const MachineRegisterInfo &MRI = MF.getRegInfo();
2884     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2885       return false;
2886   }
2887 
2888   return true;
2889 }
2890 
2891 bool
2892 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2893                                   MachineFunction &MF, bool isVarArg,
2894                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2895                                   LLVMContext &Context) const {
2896   SmallVector<CCValAssign, 16> RVLocs;
2897   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2898   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2899 }
2900 
2901 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2902                                     const SDLoc &DL, SelectionDAG &DAG) {
2903   const MachineFunction &MF = DAG.getMachineFunction();
2904   const Function &F = MF.getFunction();
2905 
2906   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2907 
2908   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2909   // version of the "preferred return address". These offsets affect the return
2910   // instruction if this is a return from PL1 without hypervisor extensions.
2911   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2912   //    SWI:     0      "subs pc, lr, #0"
2913   //    ABORT:   +4     "subs pc, lr, #4"
2914   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2915   // UNDEF varies depending on where the exception came from ARM or Thumb
2916   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2917 
2918   int64_t LROffset;
2919   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2920       IntKind == "ABORT")
2921     LROffset = 4;
2922   else if (IntKind == "SWI" || IntKind == "UNDEF")
2923     LROffset = 0;
2924   else
2925     report_fatal_error("Unsupported interrupt attribute. If present, value "
2926                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2927 
2928   RetOps.insert(RetOps.begin() + 1,
2929                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2930 
2931   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2932 }
2933 
2934 SDValue
2935 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2936                                bool isVarArg,
2937                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2938                                const SmallVectorImpl<SDValue> &OutVals,
2939                                const SDLoc &dl, SelectionDAG &DAG) const {
2940   // CCValAssign - represent the assignment of the return value to a location.
2941   SmallVector<CCValAssign, 16> RVLocs;
2942 
2943   // CCState - Info about the registers and stack slots.
2944   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2945                  *DAG.getContext());
2946 
2947   // Analyze outgoing return values.
2948   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2949 
2950   SDValue Flag;
2951   SmallVector<SDValue, 4> RetOps;
2952   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2953   bool isLittleEndian = Subtarget->isLittle();
2954 
2955   MachineFunction &MF = DAG.getMachineFunction();
2956   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2957   AFI->setReturnRegsCount(RVLocs.size());
2958 
2959  // Report error if cmse entry function returns structure through first ptr arg.
2960   if (AFI->isCmseNSEntryFunction() && MF.getFunction().hasStructRetAttr()) {
2961     // Note: using an empty SDLoc(), as the first line of the function is a
2962     // better place to report than the last line.
2963     DiagnosticInfoUnsupported Diag(
2964         DAG.getMachineFunction().getFunction(),
2965         "secure entry function would return value through pointer",
2966         SDLoc().getDebugLoc());
2967     DAG.getContext()->diagnose(Diag);
2968   }
2969 
2970   // Copy the result values into the output registers.
2971   for (unsigned i = 0, realRVLocIdx = 0;
2972        i != RVLocs.size();
2973        ++i, ++realRVLocIdx) {
2974     CCValAssign &VA = RVLocs[i];
2975     assert(VA.isRegLoc() && "Can only return in registers!");
2976 
2977     SDValue Arg = OutVals[realRVLocIdx];
2978     bool ReturnF16 = false;
2979 
2980     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2981       // Half-precision return values can be returned like this:
2982       //
2983       // t11 f16 = fadd ...
2984       // t12: i16 = bitcast t11
2985       //   t13: i32 = zero_extend t12
2986       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2987       //
2988       // to avoid code generation for bitcasts, we simply set Arg to the node
2989       // that produces the f16 value, t11 in this case.
2990       //
2991       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2992         SDValue ZE = Arg.getOperand(0);
2993         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2994           SDValue BC = ZE.getOperand(0);
2995           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2996             Arg = BC.getOperand(0);
2997             ReturnF16 = true;
2998           }
2999         }
3000       }
3001     }
3002 
3003     switch (VA.getLocInfo()) {
3004     default: llvm_unreachable("Unknown loc info!");
3005     case CCValAssign::Full: break;
3006     case CCValAssign::BCvt:
3007       if (!ReturnF16)
3008         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3009       break;
3010     }
3011 
3012     // Mask f16 arguments if this is a CMSE nonsecure entry.
3013     auto RetVT = Outs[realRVLocIdx].ArgVT;
3014     if (AFI->isCmseNSEntryFunction() && (RetVT == MVT::f16)) {
3015       if (VA.needsCustom() && VA.getValVT() == MVT::f16) {
3016         Arg = MoveFromHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), Arg);
3017       } else {
3018         auto LocBits = VA.getLocVT().getSizeInBits();
3019         auto MaskValue = APInt::getLowBitsSet(LocBits, RetVT.getSizeInBits());
3020         SDValue Mask =
3021             DAG.getConstant(MaskValue, dl, MVT::getIntegerVT(LocBits));
3022         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::getIntegerVT(LocBits), Arg);
3023         Arg = DAG.getNode(ISD::AND, dl, MVT::getIntegerVT(LocBits), Arg, Mask);
3024         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
3025       }
3026     }
3027 
3028     if (VA.needsCustom() &&
3029         (VA.getLocVT() == MVT::v2f64 || VA.getLocVT() == MVT::f64)) {
3030       if (VA.getLocVT() == MVT::v2f64) {
3031         // Extract the first half and return it in two registers.
3032         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3033                                    DAG.getConstant(0, dl, MVT::i32));
3034         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
3035                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
3036 
3037         Chain =
3038             DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3039                              HalfGPRs.getValue(isLittleEndian ? 0 : 1), Flag);
3040         Flag = Chain.getValue(1);
3041         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3042         VA = RVLocs[++i]; // skip ahead to next loc
3043         Chain =
3044             DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3045                              HalfGPRs.getValue(isLittleEndian ? 1 : 0), Flag);
3046         Flag = Chain.getValue(1);
3047         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3048         VA = RVLocs[++i]; // skip ahead to next loc
3049 
3050         // Extract the 2nd half and fall through to handle it as an f64 value.
3051         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
3052                           DAG.getConstant(1, dl, MVT::i32));
3053       }
3054       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
3055       // available.
3056       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
3057                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
3058       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3059                                fmrrd.getValue(isLittleEndian ? 0 : 1), Flag);
3060       Flag = Chain.getValue(1);
3061       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3062       VA = RVLocs[++i]; // skip ahead to next loc
3063       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3064                                fmrrd.getValue(isLittleEndian ? 1 : 0), Flag);
3065     } else
3066       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
3067 
3068     // Guarantee that all emitted copies are
3069     // stuck together, avoiding something bad.
3070     Flag = Chain.getValue(1);
3071     RetOps.push_back(DAG.getRegister(
3072         VA.getLocReg(), ReturnF16 ? Arg.getValueType() : VA.getLocVT()));
3073   }
3074   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
3075   const MCPhysReg *I =
3076       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3077   if (I) {
3078     for (; *I; ++I) {
3079       if (ARM::GPRRegClass.contains(*I))
3080         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
3081       else if (ARM::DPRRegClass.contains(*I))
3082         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3083       else
3084         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3085     }
3086   }
3087 
3088   // Update chain and glue.
3089   RetOps[0] = Chain;
3090   if (Flag.getNode())
3091     RetOps.push_back(Flag);
3092 
3093   // CPUs which aren't M-class use a special sequence to return from
3094   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
3095   // though we use "subs pc, lr, #N").
3096   //
3097   // M-class CPUs actually use a normal return sequence with a special
3098   // (hardware-provided) value in LR, so the normal code path works.
3099   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
3100       !Subtarget->isMClass()) {
3101     if (Subtarget->isThumb1Only())
3102       report_fatal_error("interrupt attribute is not supported in Thumb1");
3103     return LowerInterruptReturn(RetOps, dl, DAG);
3104   }
3105 
3106   ARMISD::NodeType RetNode = AFI->isCmseNSEntryFunction() ? ARMISD::SERET_FLAG :
3107                                                             ARMISD::RET_FLAG;
3108   return DAG.getNode(RetNode, dl, MVT::Other, RetOps);
3109 }
3110 
3111 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
3112   if (N->getNumValues() != 1)
3113     return false;
3114   if (!N->hasNUsesOfValue(1, 0))
3115     return false;
3116 
3117   SDValue TCChain = Chain;
3118   SDNode *Copy = *N->use_begin();
3119   if (Copy->getOpcode() == ISD::CopyToReg) {
3120     // If the copy has a glue operand, we conservatively assume it isn't safe to
3121     // perform a tail call.
3122     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3123       return false;
3124     TCChain = Copy->getOperand(0);
3125   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
3126     SDNode *VMov = Copy;
3127     // f64 returned in a pair of GPRs.
3128     SmallPtrSet<SDNode*, 2> Copies;
3129     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3130          UI != UE; ++UI) {
3131       if (UI->getOpcode() != ISD::CopyToReg)
3132         return false;
3133       Copies.insert(*UI);
3134     }
3135     if (Copies.size() > 2)
3136       return false;
3137 
3138     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
3139          UI != UE; ++UI) {
3140       SDValue UseChain = UI->getOperand(0);
3141       if (Copies.count(UseChain.getNode()))
3142         // Second CopyToReg
3143         Copy = *UI;
3144       else {
3145         // We are at the top of this chain.
3146         // If the copy has a glue operand, we conservatively assume it
3147         // isn't safe to perform a tail call.
3148         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
3149           return false;
3150         // First CopyToReg
3151         TCChain = UseChain;
3152       }
3153     }
3154   } else if (Copy->getOpcode() == ISD::BITCAST) {
3155     // f32 returned in a single GPR.
3156     if (!Copy->hasOneUse())
3157       return false;
3158     Copy = *Copy->use_begin();
3159     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
3160       return false;
3161     // If the copy has a glue operand, we conservatively assume it isn't safe to
3162     // perform a tail call.
3163     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
3164       return false;
3165     TCChain = Copy->getOperand(0);
3166   } else {
3167     return false;
3168   }
3169 
3170   bool HasRet = false;
3171   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
3172        UI != UE; ++UI) {
3173     if (UI->getOpcode() != ARMISD::RET_FLAG &&
3174         UI->getOpcode() != ARMISD::INTRET_FLAG)
3175       return false;
3176     HasRet = true;
3177   }
3178 
3179   if (!HasRet)
3180     return false;
3181 
3182   Chain = TCChain;
3183   return true;
3184 }
3185 
3186 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
3187   if (!Subtarget->supportsTailCall())
3188     return false;
3189 
3190   if (!CI->isTailCall())
3191     return false;
3192 
3193   return true;
3194 }
3195 
3196 // Trying to write a 64 bit value so need to split into two 32 bit values first,
3197 // and pass the lower and high parts through.
3198 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
3199   SDLoc DL(Op);
3200   SDValue WriteValue = Op->getOperand(2);
3201 
3202   // This function is only supposed to be called for i64 type argument.
3203   assert(WriteValue.getValueType() == MVT::i64
3204           && "LowerWRITE_REGISTER called for non-i64 type argument.");
3205 
3206   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3207                            DAG.getConstant(0, DL, MVT::i32));
3208   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
3209                            DAG.getConstant(1, DL, MVT::i32));
3210   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
3211   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
3212 }
3213 
3214 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3215 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
3216 // one of the above mentioned nodes. It has to be wrapped because otherwise
3217 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3218 // be used to form addressing mode. These wrapped nodes will be selected
3219 // into MOVi.
3220 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3221                                              SelectionDAG &DAG) const {
3222   EVT PtrVT = Op.getValueType();
3223   // FIXME there is no actual debug info here
3224   SDLoc dl(Op);
3225   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3226   SDValue Res;
3227 
3228   // When generating execute-only code Constant Pools must be promoted to the
3229   // global data section. It's a bit ugly that we can't share them across basic
3230   // blocks, but this way we guarantee that execute-only behaves correct with
3231   // position-independent addressing modes.
3232   if (Subtarget->genExecuteOnly()) {
3233     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3234     auto T = const_cast<Type*>(CP->getType());
3235     auto C = const_cast<Constant*>(CP->getConstVal());
3236     auto M = const_cast<Module*>(DAG.getMachineFunction().
3237                                  getFunction().getParent());
3238     auto GV = new GlobalVariable(
3239                     *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3240                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3241                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3242                     Twine(AFI->createPICLabelUId())
3243                   );
3244     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3245                                             dl, PtrVT);
3246     return LowerGlobalAddress(GA, DAG);
3247   }
3248 
3249   if (CP->isMachineConstantPoolEntry())
3250     Res =
3251         DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT, CP->getAlign());
3252   else
3253     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlign());
3254   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3255 }
3256 
3257 unsigned ARMTargetLowering::getJumpTableEncoding() const {
3258   return MachineJumpTableInfo::EK_Inline;
3259 }
3260 
3261 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3262                                              SelectionDAG &DAG) const {
3263   MachineFunction &MF = DAG.getMachineFunction();
3264   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3265   unsigned ARMPCLabelIndex = 0;
3266   SDLoc DL(Op);
3267   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3268   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3269   SDValue CPAddr;
3270   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3271   if (!IsPositionIndependent) {
3272     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, Align(4));
3273   } else {
3274     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3275     ARMPCLabelIndex = AFI->createPICLabelUId();
3276     ARMConstantPoolValue *CPV =
3277       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3278                                       ARMCP::CPBlockAddress, PCAdj);
3279     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3280   }
3281   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3282   SDValue Result = DAG.getLoad(
3283       PtrVT, DL, DAG.getEntryNode(), CPAddr,
3284       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3285   if (!IsPositionIndependent)
3286     return Result;
3287   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3288   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3289 }
3290 
3291 /// Convert a TLS address reference into the correct sequence of loads
3292 /// and calls to compute the variable's address for Darwin, and return an
3293 /// SDValue containing the final node.
3294 
3295 /// Darwin only has one TLS scheme which must be capable of dealing with the
3296 /// fully general situation, in the worst case. This means:
3297 ///     + "extern __thread" declaration.
3298 ///     + Defined in a possibly unknown dynamic library.
3299 ///
3300 /// The general system is that each __thread variable has a [3 x i32] descriptor
3301 /// which contains information used by the runtime to calculate the address. The
3302 /// only part of this the compiler needs to know about is the first word, which
3303 /// contains a function pointer that must be called with the address of the
3304 /// entire descriptor in "r0".
3305 ///
3306 /// Since this descriptor may be in a different unit, in general access must
3307 /// proceed along the usual ARM rules. A common sequence to produce is:
3308 ///
3309 ///     movw rT1, :lower16:_var$non_lazy_ptr
3310 ///     movt rT1, :upper16:_var$non_lazy_ptr
3311 ///     ldr r0, [rT1]
3312 ///     ldr rT2, [r0]
3313 ///     blx rT2
3314 ///     [...address now in r0...]
3315 SDValue
3316 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3317                                                SelectionDAG &DAG) const {
3318   assert(Subtarget->isTargetDarwin() &&
3319          "This function expects a Darwin target");
3320   SDLoc DL(Op);
3321 
3322   // First step is to get the address of the actua global symbol. This is where
3323   // the TLS descriptor lives.
3324   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3325 
3326   // The first entry in the descriptor is a function pointer that we must call
3327   // to obtain the address of the variable.
3328   SDValue Chain = DAG.getEntryNode();
3329   SDValue FuncTLVGet = DAG.getLoad(
3330       MVT::i32, DL, Chain, DescAddr,
3331       MachinePointerInfo::getGOT(DAG.getMachineFunction()), Align(4),
3332       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3333           MachineMemOperand::MOInvariant);
3334   Chain = FuncTLVGet.getValue(1);
3335 
3336   MachineFunction &F = DAG.getMachineFunction();
3337   MachineFrameInfo &MFI = F.getFrameInfo();
3338   MFI.setAdjustsStack(true);
3339 
3340   // TLS calls preserve all registers except those that absolutely must be
3341   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3342   // silly).
3343   auto TRI =
3344       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3345   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3346   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3347 
3348   // Finally, we can make the call. This is just a degenerate version of a
3349   // normal AArch64 call node: r0 takes the address of the descriptor, and
3350   // returns the address of the variable in this thread.
3351   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3352   Chain =
3353       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3354                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3355                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3356   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3357 }
3358 
3359 SDValue
3360 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3361                                                 SelectionDAG &DAG) const {
3362   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3363 
3364   SDValue Chain = DAG.getEntryNode();
3365   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3366   SDLoc DL(Op);
3367 
3368   // Load the current TEB (thread environment block)
3369   SDValue Ops[] = {Chain,
3370                    DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3371                    DAG.getTargetConstant(15, DL, MVT::i32),
3372                    DAG.getTargetConstant(0, DL, MVT::i32),
3373                    DAG.getTargetConstant(13, DL, MVT::i32),
3374                    DAG.getTargetConstant(0, DL, MVT::i32),
3375                    DAG.getTargetConstant(2, DL, MVT::i32)};
3376   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3377                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
3378 
3379   SDValue TEB = CurrentTEB.getValue(0);
3380   Chain = CurrentTEB.getValue(1);
3381 
3382   // Load the ThreadLocalStoragePointer from the TEB
3383   // A pointer to the TLS array is located at offset 0x2c from the TEB.
3384   SDValue TLSArray =
3385       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3386   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3387 
3388   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3389   // offset into the TLSArray.
3390 
3391   // Load the TLS index from the C runtime
3392   SDValue TLSIndex =
3393       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3394   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3395   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3396 
3397   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3398                               DAG.getConstant(2, DL, MVT::i32));
3399   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3400                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3401                             MachinePointerInfo());
3402 
3403   // Get the offset of the start of the .tls section (section base)
3404   const auto *GA = cast<GlobalAddressSDNode>(Op);
3405   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3406   SDValue Offset = DAG.getLoad(
3407       PtrVT, DL, Chain,
3408       DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3409                   DAG.getTargetConstantPool(CPV, PtrVT, Align(4))),
3410       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3411 
3412   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3413 }
3414 
3415 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3416 SDValue
3417 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3418                                                  SelectionDAG &DAG) const {
3419   SDLoc dl(GA);
3420   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3421   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3422   MachineFunction &MF = DAG.getMachineFunction();
3423   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3424   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3425   ARMConstantPoolValue *CPV =
3426     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3427                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3428   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3429   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3430   Argument = DAG.getLoad(
3431       PtrVT, dl, DAG.getEntryNode(), Argument,
3432       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3433   SDValue Chain = Argument.getValue(1);
3434 
3435   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3436   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3437 
3438   // call __tls_get_addr.
3439   ArgListTy Args;
3440   ArgListEntry Entry;
3441   Entry.Node = Argument;
3442   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3443   Args.push_back(Entry);
3444 
3445   // FIXME: is there useful debug info available here?
3446   TargetLowering::CallLoweringInfo CLI(DAG);
3447   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3448       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3449       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3450 
3451   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3452   return CallResult.first;
3453 }
3454 
3455 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3456 // "local exec" model.
3457 SDValue
3458 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3459                                         SelectionDAG &DAG,
3460                                         TLSModel::Model model) const {
3461   const GlobalValue *GV = GA->getGlobal();
3462   SDLoc dl(GA);
3463   SDValue Offset;
3464   SDValue Chain = DAG.getEntryNode();
3465   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3466   // Get the Thread Pointer
3467   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3468 
3469   if (model == TLSModel::InitialExec) {
3470     MachineFunction &MF = DAG.getMachineFunction();
3471     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3472     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3473     // Initial exec model.
3474     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3475     ARMConstantPoolValue *CPV =
3476       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3477                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3478                                       true);
3479     Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3480     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3481     Offset = DAG.getLoad(
3482         PtrVT, dl, Chain, Offset,
3483         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3484     Chain = Offset.getValue(1);
3485 
3486     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3487     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3488 
3489     Offset = DAG.getLoad(
3490         PtrVT, dl, Chain, Offset,
3491         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3492   } else {
3493     // local exec model
3494     assert(model == TLSModel::LocalExec);
3495     ARMConstantPoolValue *CPV =
3496       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3497     Offset = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3498     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3499     Offset = DAG.getLoad(
3500         PtrVT, dl, Chain, Offset,
3501         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3502   }
3503 
3504   // The address of the thread local variable is the add of the thread
3505   // pointer with the offset of the variable.
3506   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3507 }
3508 
3509 SDValue
3510 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3511   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3512   if (DAG.getTarget().useEmulatedTLS())
3513     return LowerToTLSEmulatedModel(GA, DAG);
3514 
3515   if (Subtarget->isTargetDarwin())
3516     return LowerGlobalTLSAddressDarwin(Op, DAG);
3517 
3518   if (Subtarget->isTargetWindows())
3519     return LowerGlobalTLSAddressWindows(Op, DAG);
3520 
3521   // TODO: implement the "local dynamic" model
3522   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3523   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3524 
3525   switch (model) {
3526     case TLSModel::GeneralDynamic:
3527     case TLSModel::LocalDynamic:
3528       return LowerToTLSGeneralDynamicModel(GA, DAG);
3529     case TLSModel::InitialExec:
3530     case TLSModel::LocalExec:
3531       return LowerToTLSExecModels(GA, DAG, model);
3532   }
3533   llvm_unreachable("bogus TLS model");
3534 }
3535 
3536 /// Return true if all users of V are within function F, looking through
3537 /// ConstantExprs.
3538 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3539   SmallVector<const User*,4> Worklist;
3540   for (auto *U : V->users())
3541     Worklist.push_back(U);
3542   while (!Worklist.empty()) {
3543     auto *U = Worklist.pop_back_val();
3544     if (isa<ConstantExpr>(U)) {
3545       for (auto *UU : U->users())
3546         Worklist.push_back(UU);
3547       continue;
3548     }
3549 
3550     auto *I = dyn_cast<Instruction>(U);
3551     if (!I || I->getParent()->getParent() != F)
3552       return false;
3553   }
3554   return true;
3555 }
3556 
3557 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3558                                      const GlobalValue *GV, SelectionDAG &DAG,
3559                                      EVT PtrVT, const SDLoc &dl) {
3560   // If we're creating a pool entry for a constant global with unnamed address,
3561   // and the global is small enough, we can emit it inline into the constant pool
3562   // to save ourselves an indirection.
3563   //
3564   // This is a win if the constant is only used in one function (so it doesn't
3565   // need to be duplicated) or duplicating the constant wouldn't increase code
3566   // size (implying the constant is no larger than 4 bytes).
3567   const Function &F = DAG.getMachineFunction().getFunction();
3568 
3569   // We rely on this decision to inline being idemopotent and unrelated to the
3570   // use-site. We know that if we inline a variable at one use site, we'll
3571   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3572   // doesn't know about this optimization, so bail out if it's enabled else
3573   // we could decide to inline here (and thus never emit the GV) but require
3574   // the GV from fast-isel generated code.
3575   if (!EnableConstpoolPromotion ||
3576       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3577       return SDValue();
3578 
3579   auto *GVar = dyn_cast<GlobalVariable>(GV);
3580   if (!GVar || !GVar->hasInitializer() ||
3581       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3582       !GVar->hasLocalLinkage())
3583     return SDValue();
3584 
3585   // If we inline a value that contains relocations, we move the relocations
3586   // from .data to .text. This is not allowed in position-independent code.
3587   auto *Init = GVar->getInitializer();
3588   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3589       Init->needsRelocation())
3590     return SDValue();
3591 
3592   // The constant islands pass can only really deal with alignment requests
3593   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3594   // any type wanting greater alignment requirements than 4 bytes. We also
3595   // can only promote constants that are multiples of 4 bytes in size or
3596   // are paddable to a multiple of 4. Currently we only try and pad constants
3597   // that are strings for simplicity.
3598   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3599   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3600   Align PrefAlign = DAG.getDataLayout().getPreferredAlign(GVar);
3601   unsigned RequiredPadding = 4 - (Size % 4);
3602   bool PaddingPossible =
3603     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3604   if (!PaddingPossible || PrefAlign > 4 || Size > ConstpoolPromotionMaxSize ||
3605       Size == 0)
3606     return SDValue();
3607 
3608   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3609   MachineFunction &MF = DAG.getMachineFunction();
3610   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3611 
3612   // We can't bloat the constant pool too much, else the ConstantIslands pass
3613   // may fail to converge. If we haven't promoted this global yet (it may have
3614   // multiple uses), and promoting it would increase the constant pool size (Sz
3615   // > 4), ensure we have space to do so up to MaxTotal.
3616   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3617     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3618         ConstpoolPromotionMaxTotal)
3619       return SDValue();
3620 
3621   // This is only valid if all users are in a single function; we can't clone
3622   // the constant in general. The LLVM IR unnamed_addr allows merging
3623   // constants, but not cloning them.
3624   //
3625   // We could potentially allow cloning if we could prove all uses of the
3626   // constant in the current function don't care about the address, like
3627   // printf format strings. But that isn't implemented for now.
3628   if (!allUsersAreInFunction(GVar, &F))
3629     return SDValue();
3630 
3631   // We're going to inline this global. Pad it out if needed.
3632   if (RequiredPadding != 4) {
3633     StringRef S = CDAInit->getAsString();
3634 
3635     SmallVector<uint8_t,16> V(S.size());
3636     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3637     while (RequiredPadding--)
3638       V.push_back(0);
3639     Init = ConstantDataArray::get(*DAG.getContext(), V);
3640   }
3641 
3642   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3643   SDValue CPAddr = DAG.getTargetConstantPool(CPVal, PtrVT, Align(4));
3644   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3645     AFI->markGlobalAsPromotedToConstantPool(GVar);
3646     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3647                                       PaddedSize - 4);
3648   }
3649   ++NumConstpoolPromoted;
3650   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3651 }
3652 
3653 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3654   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3655     if (!(GV = GA->getBaseObject()))
3656       return false;
3657   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3658     return V->isConstant();
3659   return isa<Function>(GV);
3660 }
3661 
3662 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3663                                               SelectionDAG &DAG) const {
3664   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3665   default: llvm_unreachable("unknown object format");
3666   case Triple::COFF:
3667     return LowerGlobalAddressWindows(Op, DAG);
3668   case Triple::ELF:
3669     return LowerGlobalAddressELF(Op, DAG);
3670   case Triple::MachO:
3671     return LowerGlobalAddressDarwin(Op, DAG);
3672   }
3673 }
3674 
3675 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3676                                                  SelectionDAG &DAG) const {
3677   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3678   SDLoc dl(Op);
3679   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3680   const TargetMachine &TM = getTargetMachine();
3681   bool IsRO = isReadOnly(GV);
3682 
3683   // promoteToConstantPool only if not generating XO text section
3684   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3685     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3686       return V;
3687 
3688   if (isPositionIndependent()) {
3689     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3690     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3691                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3692     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3693     if (UseGOT_PREL)
3694       Result =
3695           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3696                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3697     return Result;
3698   } else if (Subtarget->isROPI() && IsRO) {
3699     // PC-relative.
3700     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3701     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3702     return Result;
3703   } else if (Subtarget->isRWPI() && !IsRO) {
3704     // SB-relative.
3705     SDValue RelAddr;
3706     if (Subtarget->useMovt()) {
3707       ++NumMovwMovt;
3708       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3709       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3710     } else { // use literal pool for address constant
3711       ARMConstantPoolValue *CPV =
3712         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3713       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3714       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3715       RelAddr = DAG.getLoad(
3716           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3717           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3718     }
3719     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3720     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3721     return Result;
3722   }
3723 
3724   // If we have T2 ops, we can materialize the address directly via movt/movw
3725   // pair. This is always cheaper.
3726   if (Subtarget->useMovt()) {
3727     ++NumMovwMovt;
3728     // FIXME: Once remat is capable of dealing with instructions with register
3729     // operands, expand this into two nodes.
3730     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3731                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3732   } else {
3733     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, Align(4));
3734     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3735     return DAG.getLoad(
3736         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3737         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3738   }
3739 }
3740 
3741 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3742                                                     SelectionDAG &DAG) const {
3743   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3744          "ROPI/RWPI not currently supported for Darwin");
3745   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3746   SDLoc dl(Op);
3747   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3748 
3749   if (Subtarget->useMovt())
3750     ++NumMovwMovt;
3751 
3752   // FIXME: Once remat is capable of dealing with instructions with register
3753   // operands, expand this into multiple nodes
3754   unsigned Wrapper =
3755       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3756 
3757   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3758   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3759 
3760   if (Subtarget->isGVIndirectSymbol(GV))
3761     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3762                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3763   return Result;
3764 }
3765 
3766 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3767                                                      SelectionDAG &DAG) const {
3768   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3769   assert(Subtarget->useMovt() &&
3770          "Windows on ARM expects to use movw/movt");
3771   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3772          "ROPI/RWPI not currently supported for Windows");
3773 
3774   const TargetMachine &TM = getTargetMachine();
3775   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3776   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3777   if (GV->hasDLLImportStorageClass())
3778     TargetFlags = ARMII::MO_DLLIMPORT;
3779   else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3780     TargetFlags = ARMII::MO_COFFSTUB;
3781   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3782   SDValue Result;
3783   SDLoc DL(Op);
3784 
3785   ++NumMovwMovt;
3786 
3787   // FIXME: Once remat is capable of dealing with instructions with register
3788   // operands, expand this into two nodes.
3789   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3790                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3791                                                   TargetFlags));
3792   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3793     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3794                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3795   return Result;
3796 }
3797 
3798 SDValue
3799 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3800   SDLoc dl(Op);
3801   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3802   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3803                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3804                      Op.getOperand(1), Val);
3805 }
3806 
3807 SDValue
3808 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3809   SDLoc dl(Op);
3810   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3811                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3812 }
3813 
3814 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3815                                                       SelectionDAG &DAG) const {
3816   SDLoc dl(Op);
3817   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3818                      Op.getOperand(0));
3819 }
3820 
3821 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3822     SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3823   unsigned IntNo =
3824       cast<ConstantSDNode>(
3825           Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3826           ->getZExtValue();
3827   switch (IntNo) {
3828     default:
3829       return SDValue();  // Don't custom lower most intrinsics.
3830     case Intrinsic::arm_gnu_eabi_mcount: {
3831       MachineFunction &MF = DAG.getMachineFunction();
3832       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3833       SDLoc dl(Op);
3834       SDValue Chain = Op.getOperand(0);
3835       // call "\01__gnu_mcount_nc"
3836       const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3837       const uint32_t *Mask =
3838           ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3839       assert(Mask && "Missing call preserved mask for calling convention");
3840       // Mark LR an implicit live-in.
3841       unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3842       SDValue ReturnAddress =
3843           DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3844       constexpr EVT ResultTys[] = {MVT::Other, MVT::Glue};
3845       SDValue Callee =
3846           DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3847       SDValue RegisterMask = DAG.getRegisterMask(Mask);
3848       if (Subtarget->isThumb())
3849         return SDValue(
3850             DAG.getMachineNode(
3851                 ARM::tBL_PUSHLR, dl, ResultTys,
3852                 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3853                  DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3854             0);
3855       return SDValue(
3856           DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3857                              {ReturnAddress, Callee, RegisterMask, Chain}),
3858           0);
3859     }
3860   }
3861 }
3862 
3863 SDValue
3864 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3865                                           const ARMSubtarget *Subtarget) const {
3866   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3867   SDLoc dl(Op);
3868   switch (IntNo) {
3869   default: return SDValue();    // Don't custom lower most intrinsics.
3870   case Intrinsic::thread_pointer: {
3871     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3872     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3873   }
3874   case Intrinsic::arm_cls: {
3875     const SDValue &Operand = Op.getOperand(1);
3876     const EVT VTy = Op.getValueType();
3877     SDValue SRA =
3878         DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
3879     SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
3880     SDValue SHL =
3881         DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
3882     SDValue OR =
3883         DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
3884     SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
3885     return Result;
3886   }
3887   case Intrinsic::arm_cls64: {
3888     // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
3889     //          else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
3890     const SDValue &Operand = Op.getOperand(1);
3891     const EVT VTy = Op.getValueType();
3892 
3893     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3894                              DAG.getConstant(1, dl, VTy));
3895     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3896                              DAG.getConstant(0, dl, VTy));
3897     SDValue Constant0 = DAG.getConstant(0, dl, VTy);
3898     SDValue Constant1 = DAG.getConstant(1, dl, VTy);
3899     SDValue Constant31 = DAG.getConstant(31, dl, VTy);
3900     SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
3901     SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
3902     SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
3903     SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
3904     SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
3905     SDValue CheckLo =
3906         DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
3907     SDValue HiIsZero =
3908         DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
3909     SDValue AdjustedLo =
3910         DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
3911     SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
3912     SDValue Result =
3913         DAG.getSelect(dl, VTy, CheckLo,
3914                       DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
3915     return Result;
3916   }
3917   case Intrinsic::eh_sjlj_lsda: {
3918     MachineFunction &MF = DAG.getMachineFunction();
3919     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3920     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3921     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3922     SDValue CPAddr;
3923     bool IsPositionIndependent = isPositionIndependent();
3924     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3925     ARMConstantPoolValue *CPV =
3926       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3927                                       ARMCP::CPLSDA, PCAdj);
3928     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, Align(4));
3929     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3930     SDValue Result = DAG.getLoad(
3931         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3932         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3933 
3934     if (IsPositionIndependent) {
3935       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3936       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3937     }
3938     return Result;
3939   }
3940   case Intrinsic::arm_neon_vabs:
3941     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3942                         Op.getOperand(1));
3943   case Intrinsic::arm_neon_vmulls:
3944   case Intrinsic::arm_neon_vmullu: {
3945     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3946       ? ARMISD::VMULLs : ARMISD::VMULLu;
3947     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3948                        Op.getOperand(1), Op.getOperand(2));
3949   }
3950   case Intrinsic::arm_neon_vminnm:
3951   case Intrinsic::arm_neon_vmaxnm: {
3952     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3953       ? ISD::FMINNUM : ISD::FMAXNUM;
3954     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3955                        Op.getOperand(1), Op.getOperand(2));
3956   }
3957   case Intrinsic::arm_neon_vminu:
3958   case Intrinsic::arm_neon_vmaxu: {
3959     if (Op.getValueType().isFloatingPoint())
3960       return SDValue();
3961     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3962       ? ISD::UMIN : ISD::UMAX;
3963     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3964                          Op.getOperand(1), Op.getOperand(2));
3965   }
3966   case Intrinsic::arm_neon_vmins:
3967   case Intrinsic::arm_neon_vmaxs: {
3968     // v{min,max}s is overloaded between signed integers and floats.
3969     if (!Op.getValueType().isFloatingPoint()) {
3970       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3971         ? ISD::SMIN : ISD::SMAX;
3972       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3973                          Op.getOperand(1), Op.getOperand(2));
3974     }
3975     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3976       ? ISD::FMINIMUM : ISD::FMAXIMUM;
3977     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3978                        Op.getOperand(1), Op.getOperand(2));
3979   }
3980   case Intrinsic::arm_neon_vtbl1:
3981     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3982                        Op.getOperand(1), Op.getOperand(2));
3983   case Intrinsic::arm_neon_vtbl2:
3984     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3985                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3986   case Intrinsic::arm_mve_pred_i2v:
3987   case Intrinsic::arm_mve_pred_v2i:
3988     return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
3989                        Op.getOperand(1));
3990   case Intrinsic::arm_mve_vreinterpretq:
3991     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(Op), Op.getValueType(),
3992                        Op.getOperand(1));
3993   case Intrinsic::arm_mve_lsll:
3994     return DAG.getNode(ARMISD::LSLL, SDLoc(Op), Op->getVTList(),
3995                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3996   case Intrinsic::arm_mve_asrl:
3997     return DAG.getNode(ARMISD::ASRL, SDLoc(Op), Op->getVTList(),
3998                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3999   }
4000 }
4001 
4002 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
4003                                  const ARMSubtarget *Subtarget) {
4004   SDLoc dl(Op);
4005   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
4006   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
4007   if (SSID == SyncScope::SingleThread)
4008     return Op;
4009 
4010   if (!Subtarget->hasDataBarrier()) {
4011     // Some ARMv6 cpus can support data barriers with an mcr instruction.
4012     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
4013     // here.
4014     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
4015            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
4016     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
4017                        DAG.getConstant(0, dl, MVT::i32));
4018   }
4019 
4020   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
4021   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
4022   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
4023   if (Subtarget->isMClass()) {
4024     // Only a full system barrier exists in the M-class architectures.
4025     Domain = ARM_MB::SY;
4026   } else if (Subtarget->preferISHSTBarriers() &&
4027              Ord == AtomicOrdering::Release) {
4028     // Swift happens to implement ISHST barriers in a way that's compatible with
4029     // Release semantics but weaker than ISH so we'd be fools not to use
4030     // it. Beware: other processors probably don't!
4031     Domain = ARM_MB::ISHST;
4032   }
4033 
4034   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
4035                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
4036                      DAG.getConstant(Domain, dl, MVT::i32));
4037 }
4038 
4039 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
4040                              const ARMSubtarget *Subtarget) {
4041   // ARM pre v5TE and Thumb1 does not have preload instructions.
4042   if (!(Subtarget->isThumb2() ||
4043         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
4044     // Just preserve the chain.
4045     return Op.getOperand(0);
4046 
4047   SDLoc dl(Op);
4048   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
4049   if (!isRead &&
4050       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
4051     // ARMv7 with MP extension has PLDW.
4052     return Op.getOperand(0);
4053 
4054   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
4055   if (Subtarget->isThumb()) {
4056     // Invert the bits.
4057     isRead = ~isRead & 1;
4058     isData = ~isData & 1;
4059   }
4060 
4061   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
4062                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
4063                      DAG.getConstant(isData, dl, MVT::i32));
4064 }
4065 
4066 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
4067   MachineFunction &MF = DAG.getMachineFunction();
4068   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
4069 
4070   // vastart just stores the address of the VarArgsFrameIndex slot into the
4071   // memory location argument.
4072   SDLoc dl(Op);
4073   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4074   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4075   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4076   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
4077                       MachinePointerInfo(SV));
4078 }
4079 
4080 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
4081                                                 CCValAssign &NextVA,
4082                                                 SDValue &Root,
4083                                                 SelectionDAG &DAG,
4084                                                 const SDLoc &dl) const {
4085   MachineFunction &MF = DAG.getMachineFunction();
4086   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4087 
4088   const TargetRegisterClass *RC;
4089   if (AFI->isThumb1OnlyFunction())
4090     RC = &ARM::tGPRRegClass;
4091   else
4092     RC = &ARM::GPRRegClass;
4093 
4094   // Transform the arguments stored in physical registers into virtual ones.
4095   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4096   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4097 
4098   SDValue ArgValue2;
4099   if (NextVA.isMemLoc()) {
4100     MachineFrameInfo &MFI = MF.getFrameInfo();
4101     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
4102 
4103     // Create load node to retrieve arguments from the stack.
4104     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4105     ArgValue2 = DAG.getLoad(
4106         MVT::i32, dl, Root, FIN,
4107         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4108   } else {
4109     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
4110     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
4111   }
4112   if (!Subtarget->isLittle())
4113     std::swap (ArgValue, ArgValue2);
4114   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
4115 }
4116 
4117 // The remaining GPRs hold either the beginning of variable-argument
4118 // data, or the beginning of an aggregate passed by value (usually
4119 // byval).  Either way, we allocate stack slots adjacent to the data
4120 // provided by our caller, and store the unallocated registers there.
4121 // If this is a variadic function, the va_list pointer will begin with
4122 // these values; otherwise, this reassembles a (byval) structure that
4123 // was split between registers and memory.
4124 // Return: The frame index registers were stored into.
4125 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
4126                                       const SDLoc &dl, SDValue &Chain,
4127                                       const Value *OrigArg,
4128                                       unsigned InRegsParamRecordIdx,
4129                                       int ArgOffset, unsigned ArgSize) const {
4130   // Currently, two use-cases possible:
4131   // Case #1. Non-var-args function, and we meet first byval parameter.
4132   //          Setup first unallocated register as first byval register;
4133   //          eat all remained registers
4134   //          (these two actions are performed by HandleByVal method).
4135   //          Then, here, we initialize stack frame with
4136   //          "store-reg" instructions.
4137   // Case #2. Var-args function, that doesn't contain byval parameters.
4138   //          The same: eat all remained unallocated registers,
4139   //          initialize stack frame.
4140 
4141   MachineFunction &MF = DAG.getMachineFunction();
4142   MachineFrameInfo &MFI = MF.getFrameInfo();
4143   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4144   unsigned RBegin, REnd;
4145   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
4146     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
4147   } else {
4148     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4149     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
4150     REnd = ARM::R4;
4151   }
4152 
4153   if (REnd != RBegin)
4154     ArgOffset = -4 * (ARM::R4 - RBegin);
4155 
4156   auto PtrVT = getPointerTy(DAG.getDataLayout());
4157   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
4158   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
4159 
4160   SmallVector<SDValue, 4> MemOps;
4161   const TargetRegisterClass *RC =
4162       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
4163 
4164   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
4165     unsigned VReg = MF.addLiveIn(Reg, RC);
4166     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4167     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4168                                  MachinePointerInfo(OrigArg, 4 * i));
4169     MemOps.push_back(Store);
4170     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
4171   }
4172 
4173   if (!MemOps.empty())
4174     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4175   return FrameIndex;
4176 }
4177 
4178 // Setup stack frame, the va_list pointer will start from.
4179 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
4180                                              const SDLoc &dl, SDValue &Chain,
4181                                              unsigned ArgOffset,
4182                                              unsigned TotalArgRegsSaveSize,
4183                                              bool ForceMutable) const {
4184   MachineFunction &MF = DAG.getMachineFunction();
4185   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4186 
4187   // Try to store any remaining integer argument regs
4188   // to their spots on the stack so that they may be loaded by dereferencing
4189   // the result of va_next.
4190   // If there is no regs to be stored, just point address after last
4191   // argument passed via stack.
4192   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
4193                                   CCInfo.getInRegsParamsCount(),
4194                                   CCInfo.getNextStackOffset(),
4195                                   std::max(4U, TotalArgRegsSaveSize));
4196   AFI->setVarArgsFrameIndex(FrameIndex);
4197 }
4198 
4199 bool ARMTargetLowering::splitValueIntoRegisterParts(
4200     SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
4201     unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const {
4202   bool IsABIRegCopy = CC.hasValue();
4203   EVT ValueVT = Val.getValueType();
4204   if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4205       PartVT == MVT::f32) {
4206     unsigned ValueBits = ValueVT.getSizeInBits();
4207     unsigned PartBits = PartVT.getSizeInBits();
4208     Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(ValueBits), Val);
4209     Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::getIntegerVT(PartBits), Val);
4210     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
4211     Parts[0] = Val;
4212     return true;
4213   }
4214   return false;
4215 }
4216 
4217 SDValue ARMTargetLowering::joinRegisterPartsIntoValue(
4218     SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
4219     MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const {
4220   bool IsABIRegCopy = CC.hasValue();
4221   if (IsABIRegCopy && (ValueVT == MVT::f16 || ValueVT == MVT::bf16) &&
4222       PartVT == MVT::f32) {
4223     unsigned ValueBits = ValueVT.getSizeInBits();
4224     unsigned PartBits = PartVT.getSizeInBits();
4225     SDValue Val = Parts[0];
4226 
4227     Val = DAG.getNode(ISD::BITCAST, DL, MVT::getIntegerVT(PartBits), Val);
4228     Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::getIntegerVT(ValueBits), Val);
4229     Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
4230     return Val;
4231   }
4232   return SDValue();
4233 }
4234 
4235 SDValue ARMTargetLowering::LowerFormalArguments(
4236     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4237     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4238     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4239   MachineFunction &MF = DAG.getMachineFunction();
4240   MachineFrameInfo &MFI = MF.getFrameInfo();
4241 
4242   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
4243 
4244   // Assign locations to all of the incoming arguments.
4245   SmallVector<CCValAssign, 16> ArgLocs;
4246   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4247                  *DAG.getContext());
4248   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
4249 
4250   SmallVector<SDValue, 16> ArgValues;
4251   SDValue ArgValue;
4252   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
4253   unsigned CurArgIdx = 0;
4254 
4255   // Initially ArgRegsSaveSize is zero.
4256   // Then we increase this value each time we meet byval parameter.
4257   // We also increase this value in case of varargs function.
4258   AFI->setArgRegsSaveSize(0);
4259 
4260   // Calculate the amount of stack space that we need to allocate to store
4261   // byval and variadic arguments that are passed in registers.
4262   // We need to know this before we allocate the first byval or variadic
4263   // argument, as they will be allocated a stack slot below the CFA (Canonical
4264   // Frame Address, the stack pointer at entry to the function).
4265   unsigned ArgRegBegin = ARM::R4;
4266   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4267     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4268       break;
4269 
4270     CCValAssign &VA = ArgLocs[i];
4271     unsigned Index = VA.getValNo();
4272     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4273     if (!Flags.isByVal())
4274       continue;
4275 
4276     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4277     unsigned RBegin, REnd;
4278     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4279     ArgRegBegin = std::min(ArgRegBegin, RBegin);
4280 
4281     CCInfo.nextInRegsParam();
4282   }
4283   CCInfo.rewindByValRegsInfo();
4284 
4285   int lastInsIndex = -1;
4286   if (isVarArg && MFI.hasVAStart()) {
4287     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4288     if (RegIdx != array_lengthof(GPRArgRegs))
4289       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4290   }
4291 
4292   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4293   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4294   auto PtrVT = getPointerTy(DAG.getDataLayout());
4295 
4296   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4297     CCValAssign &VA = ArgLocs[i];
4298     if (Ins[VA.getValNo()].isOrigArg()) {
4299       std::advance(CurOrigArg,
4300                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4301       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4302     }
4303     // Arguments stored in registers.
4304     if (VA.isRegLoc()) {
4305       EVT RegVT = VA.getLocVT();
4306 
4307       if (VA.needsCustom() && VA.getLocVT() == MVT::v2f64) {
4308         // f64 and vector types are split up into multiple registers or
4309         // combinations of registers and stack slots.
4310         SDValue ArgValue1 =
4311             GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4312         VA = ArgLocs[++i]; // skip ahead to next loc
4313         SDValue ArgValue2;
4314         if (VA.isMemLoc()) {
4315           int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4316           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4317           ArgValue2 = DAG.getLoad(
4318               MVT::f64, dl, Chain, FIN,
4319               MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
4320         } else {
4321           ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4322         }
4323         ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4324         ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4325                                ArgValue1, DAG.getIntPtrConstant(0, dl));
4326         ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, ArgValue,
4327                                ArgValue2, DAG.getIntPtrConstant(1, dl));
4328       } else if (VA.needsCustom() && VA.getLocVT() == MVT::f64) {
4329         ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4330       } else {
4331         const TargetRegisterClass *RC;
4332 
4333         if (RegVT == MVT::f16 || RegVT == MVT::bf16)
4334           RC = &ARM::HPRRegClass;
4335         else if (RegVT == MVT::f32)
4336           RC = &ARM::SPRRegClass;
4337         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16 ||
4338                  RegVT == MVT::v4bf16)
4339           RC = &ARM::DPRRegClass;
4340         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16 ||
4341                  RegVT == MVT::v8bf16)
4342           RC = &ARM::QPRRegClass;
4343         else if (RegVT == MVT::i32)
4344           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4345                                            : &ARM::GPRRegClass;
4346         else
4347           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4348 
4349         // Transform the arguments in physical registers into virtual ones.
4350         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4351         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4352 
4353         // If this value is passed in r0 and has the returned attribute (e.g.
4354         // C++ 'structors), record this fact for later use.
4355         if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4356           AFI->setPreservesR0();
4357         }
4358       }
4359 
4360       // If this is an 8 or 16-bit value, it is really passed promoted
4361       // to 32 bits.  Insert an assert[sz]ext to capture this, then
4362       // truncate to the right size.
4363       switch (VA.getLocInfo()) {
4364       default: llvm_unreachable("Unknown loc info!");
4365       case CCValAssign::Full: break;
4366       case CCValAssign::BCvt:
4367         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4368         break;
4369       case CCValAssign::SExt:
4370         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4371                                DAG.getValueType(VA.getValVT()));
4372         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4373         break;
4374       case CCValAssign::ZExt:
4375         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4376                                DAG.getValueType(VA.getValVT()));
4377         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4378         break;
4379       }
4380 
4381       // f16 arguments have their size extended to 4 bytes and passed as if they
4382       // had been copied to the LSBs of a 32-bit register.
4383       // For that, it's passed extended to i32 (soft ABI) or to f32 (hard ABI)
4384       if (VA.needsCustom() &&
4385           (VA.getValVT() == MVT::f16 || VA.getValVT() == MVT::bf16))
4386         ArgValue = MoveToHPR(dl, DAG, VA.getLocVT(), VA.getValVT(), ArgValue);
4387 
4388       InVals.push_back(ArgValue);
4389     } else { // VA.isRegLoc()
4390       // sanity check
4391       assert(VA.isMemLoc());
4392       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4393 
4394       int index = VA.getValNo();
4395 
4396       // Some Ins[] entries become multiple ArgLoc[] entries.
4397       // Process them only once.
4398       if (index != lastInsIndex)
4399         {
4400           ISD::ArgFlagsTy Flags = Ins[index].Flags;
4401           // FIXME: For now, all byval parameter objects are marked mutable.
4402           // This can be changed with more analysis.
4403           // In case of tail call optimization mark all arguments mutable.
4404           // Since they could be overwritten by lowering of arguments in case of
4405           // a tail call.
4406           if (Flags.isByVal()) {
4407             assert(Ins[index].isOrigArg() &&
4408                    "Byval arguments cannot be implicit");
4409             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4410 
4411             int FrameIndex = StoreByValRegs(
4412                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4413                 VA.getLocMemOffset(), Flags.getByValSize());
4414             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4415             CCInfo.nextInRegsParam();
4416           } else {
4417             unsigned FIOffset = VA.getLocMemOffset();
4418             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4419                                            FIOffset, true);
4420 
4421             // Create load nodes to retrieve arguments from the stack.
4422             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4423             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4424                                          MachinePointerInfo::getFixedStack(
4425                                              DAG.getMachineFunction(), FI)));
4426           }
4427           lastInsIndex = index;
4428         }
4429     }
4430   }
4431 
4432   // varargs
4433   if (isVarArg && MFI.hasVAStart()) {
4434     VarArgStyleRegisters(CCInfo, DAG, dl, Chain, CCInfo.getNextStackOffset(),
4435                          TotalArgRegsSaveSize);
4436     if (AFI->isCmseNSEntryFunction()) {
4437       DiagnosticInfoUnsupported Diag(
4438           DAG.getMachineFunction().getFunction(),
4439           "secure entry function must not be variadic", dl.getDebugLoc());
4440       DAG.getContext()->diagnose(Diag);
4441     }
4442   }
4443 
4444   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4445 
4446   if (CCInfo.getNextStackOffset() > 0 && AFI->isCmseNSEntryFunction()) {
4447     DiagnosticInfoUnsupported Diag(
4448         DAG.getMachineFunction().getFunction(),
4449         "secure entry function requires arguments on stack", dl.getDebugLoc());
4450     DAG.getContext()->diagnose(Diag);
4451   }
4452 
4453   return Chain;
4454 }
4455 
4456 /// isFloatingPointZero - Return true if this is +0.0.
4457 static bool isFloatingPointZero(SDValue Op) {
4458   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4459     return CFP->getValueAPF().isPosZero();
4460   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4461     // Maybe this has already been legalized into the constant pool?
4462     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4463       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4464       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4465         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4466           return CFP->getValueAPF().isPosZero();
4467     }
4468   } else if (Op->getOpcode() == ISD::BITCAST &&
4469              Op->getValueType(0) == MVT::f64) {
4470     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4471     // created by LowerConstantFP().
4472     SDValue BitcastOp = Op->getOperand(0);
4473     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4474         isNullConstant(BitcastOp->getOperand(0)))
4475       return true;
4476   }
4477   return false;
4478 }
4479 
4480 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4481 /// the given operands.
4482 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4483                                      SDValue &ARMcc, SelectionDAG &DAG,
4484                                      const SDLoc &dl) const {
4485   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4486     unsigned C = RHSC->getZExtValue();
4487     if (!isLegalICmpImmediate((int32_t)C)) {
4488       // Constant does not fit, try adjusting it by one.
4489       switch (CC) {
4490       default: break;
4491       case ISD::SETLT:
4492       case ISD::SETGE:
4493         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4494           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4495           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4496         }
4497         break;
4498       case ISD::SETULT:
4499       case ISD::SETUGE:
4500         if (C != 0 && isLegalICmpImmediate(C-1)) {
4501           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4502           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4503         }
4504         break;
4505       case ISD::SETLE:
4506       case ISD::SETGT:
4507         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4508           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4509           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4510         }
4511         break;
4512       case ISD::SETULE:
4513       case ISD::SETUGT:
4514         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4515           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4516           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4517         }
4518         break;
4519       }
4520     }
4521   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4522              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4523     // In ARM and Thumb-2, the compare instructions can shift their second
4524     // operand.
4525     CC = ISD::getSetCCSwappedOperands(CC);
4526     std::swap(LHS, RHS);
4527   }
4528 
4529   // Thumb1 has very limited immediate modes, so turning an "and" into a
4530   // shift can save multiple instructions.
4531   //
4532   // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4533   // into "((x << n) >> n)".  But that isn't necessarily profitable on its
4534   // own. If it's the operand to an unsigned comparison with an immediate,
4535   // we can eliminate one of the shifts: we transform
4536   // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4537   //
4538   // We avoid transforming cases which aren't profitable due to encoding
4539   // details:
4540   //
4541   // 1. C2 fits into the immediate field of a cmp, and the transformed version
4542   // would not; in that case, we're essentially trading one immediate load for
4543   // another.
4544   // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4545   // 3. C2 is zero; we have other code for this special case.
4546   //
4547   // FIXME: Figure out profitability for Thumb2; we usually can't save an
4548   // instruction, since the AND is always one instruction anyway, but we could
4549   // use narrow instructions in some cases.
4550   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4551       LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4552       LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4553       !isSignedIntSetCC(CC)) {
4554     unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4555     auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4556     uint64_t RHSV = RHSC->getZExtValue();
4557     if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4558       unsigned ShiftBits = countLeadingZeros(Mask);
4559       if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4560         SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4561         LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4562         RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4563       }
4564     }
4565   }
4566 
4567   // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4568   // single "lsls x, c+1".  The shift sets the "C" and "Z" flags the same
4569   // way a cmp would.
4570   // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4571   // some tweaks to the heuristics for the previous and->shift transform.
4572   // FIXME: Optimize cases where the LHS isn't a shift.
4573   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4574       isa<ConstantSDNode>(RHS) &&
4575       cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4576       CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4577       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4578     unsigned ShiftAmt =
4579       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4580     SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4581                                 DAG.getVTList(MVT::i32, MVT::i32),
4582                                 LHS.getOperand(0),
4583                                 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4584     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4585                                      Shift.getValue(1), SDValue());
4586     ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4587     return Chain.getValue(1);
4588   }
4589 
4590   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4591 
4592   // If the RHS is a constant zero then the V (overflow) flag will never be
4593   // set. This can allow us to simplify GE to PL or LT to MI, which can be
4594   // simpler for other passes (like the peephole optimiser) to deal with.
4595   if (isNullConstant(RHS)) {
4596     switch (CondCode) {
4597       default: break;
4598       case ARMCC::GE:
4599         CondCode = ARMCC::PL;
4600         break;
4601       case ARMCC::LT:
4602         CondCode = ARMCC::MI;
4603         break;
4604     }
4605   }
4606 
4607   ARMISD::NodeType CompareType;
4608   switch (CondCode) {
4609   default:
4610     CompareType = ARMISD::CMP;
4611     break;
4612   case ARMCC::EQ:
4613   case ARMCC::NE:
4614     // Uses only Z Flag
4615     CompareType = ARMISD::CMPZ;
4616     break;
4617   }
4618   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4619   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4620 }
4621 
4622 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4623 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4624                                      SelectionDAG &DAG, const SDLoc &dl,
4625                                      bool Signaling) const {
4626   assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4627   SDValue Cmp;
4628   if (!isFloatingPointZero(RHS))
4629     Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPE : ARMISD::CMPFP,
4630                       dl, MVT::Glue, LHS, RHS);
4631   else
4632     Cmp = DAG.getNode(Signaling ? ARMISD::CMPFPEw0 : ARMISD::CMPFPw0,
4633                       dl, MVT::Glue, LHS);
4634   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4635 }
4636 
4637 /// duplicateCmp - Glue values can have only one use, so this function
4638 /// duplicates a comparison node.
4639 SDValue
4640 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4641   unsigned Opc = Cmp.getOpcode();
4642   SDLoc DL(Cmp);
4643   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4644     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4645 
4646   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4647   Cmp = Cmp.getOperand(0);
4648   Opc = Cmp.getOpcode();
4649   if (Opc == ARMISD::CMPFP)
4650     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4651   else {
4652     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4653     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4654   }
4655   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4656 }
4657 
4658 // This function returns three things: the arithmetic computation itself
4659 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
4660 // comparison and the condition code define the case in which the arithmetic
4661 // computation *does not* overflow.
4662 std::pair<SDValue, SDValue>
4663 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4664                                  SDValue &ARMcc) const {
4665   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
4666 
4667   SDValue Value, OverflowCmp;
4668   SDValue LHS = Op.getOperand(0);
4669   SDValue RHS = Op.getOperand(1);
4670   SDLoc dl(Op);
4671 
4672   // FIXME: We are currently always generating CMPs because we don't support
4673   // generating CMN through the backend. This is not as good as the natural
4674   // CMP case because it causes a register dependency and cannot be folded
4675   // later.
4676 
4677   switch (Op.getOpcode()) {
4678   default:
4679     llvm_unreachable("Unknown overflow instruction!");
4680   case ISD::SADDO:
4681     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4682     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4683     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4684     break;
4685   case ISD::UADDO:
4686     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4687     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4688     // We do not use it in the USUBO case as Value may not be used.
4689     Value = DAG.getNode(ARMISD::ADDC, dl,
4690                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4691                 .getValue(0);
4692     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4693     break;
4694   case ISD::SSUBO:
4695     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4696     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4697     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4698     break;
4699   case ISD::USUBO:
4700     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4701     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4702     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4703     break;
4704   case ISD::UMULO:
4705     // We generate a UMUL_LOHI and then check if the high word is 0.
4706     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4707     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4708                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4709                         LHS, RHS);
4710     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4711                               DAG.getConstant(0, dl, MVT::i32));
4712     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4713     break;
4714   case ISD::SMULO:
4715     // We generate a SMUL_LOHI and then check if all the bits of the high word
4716     // are the same as the sign bit of the low word.
4717     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4718     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4719                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4720                         LHS, RHS);
4721     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4722                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4723                                           Value.getValue(0),
4724                                           DAG.getConstant(31, dl, MVT::i32)));
4725     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4726     break;
4727   } // switch (...)
4728 
4729   return std::make_pair(Value, OverflowCmp);
4730 }
4731 
4732 SDValue
4733 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4734   // Let legalize expand this if it isn't a legal type yet.
4735   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4736     return SDValue();
4737 
4738   SDValue Value, OverflowCmp;
4739   SDValue ARMcc;
4740   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4741   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4742   SDLoc dl(Op);
4743   // We use 0 and 1 as false and true values.
4744   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4745   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4746   EVT VT = Op.getValueType();
4747 
4748   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4749                                  ARMcc, CCR, OverflowCmp);
4750 
4751   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4752   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4753 }
4754 
4755 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4756                                               SelectionDAG &DAG) {
4757   SDLoc DL(BoolCarry);
4758   EVT CarryVT = BoolCarry.getValueType();
4759 
4760   // This converts the boolean value carry into the carry flag by doing
4761   // ARMISD::SUBC Carry, 1
4762   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4763                               DAG.getVTList(CarryVT, MVT::i32),
4764                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
4765   return Carry.getValue(1);
4766 }
4767 
4768 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4769                                               SelectionDAG &DAG) {
4770   SDLoc DL(Flags);
4771 
4772   // Now convert the carry flag into a boolean carry. We do this
4773   // using ARMISD:ADDE 0, 0, Carry
4774   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4775                      DAG.getConstant(0, DL, MVT::i32),
4776                      DAG.getConstant(0, DL, MVT::i32), Flags);
4777 }
4778 
4779 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4780                                              SelectionDAG &DAG) const {
4781   // Let legalize expand this if it isn't a legal type yet.
4782   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4783     return SDValue();
4784 
4785   SDValue LHS = Op.getOperand(0);
4786   SDValue RHS = Op.getOperand(1);
4787   SDLoc dl(Op);
4788 
4789   EVT VT = Op.getValueType();
4790   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4791   SDValue Value;
4792   SDValue Overflow;
4793   switch (Op.getOpcode()) {
4794   default:
4795     llvm_unreachable("Unknown overflow instruction!");
4796   case ISD::UADDO:
4797     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4798     // Convert the carry flag into a boolean value.
4799     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4800     break;
4801   case ISD::USUBO: {
4802     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4803     // Convert the carry flag into a boolean value.
4804     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4805     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4806     // value. So compute 1 - C.
4807     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4808                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4809     break;
4810   }
4811   }
4812 
4813   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4814 }
4815 
4816 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4817                                const ARMSubtarget *Subtarget) {
4818   EVT VT = Op.getValueType();
4819   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
4820     return SDValue();
4821   if (!VT.isSimple())
4822     return SDValue();
4823 
4824   unsigned NewOpcode;
4825   bool IsAdd = Op->getOpcode() == ISD::SADDSAT;
4826   switch (VT.getSimpleVT().SimpleTy) {
4827   default:
4828     return SDValue();
4829   case MVT::i8:
4830     NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b;
4831     break;
4832   case MVT::i16:
4833     NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b;
4834     break;
4835   }
4836 
4837   SDLoc dl(Op);
4838   SDValue Add =
4839       DAG.getNode(NewOpcode, dl, MVT::i32,
4840                   DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
4841                   DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
4842   return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
4843 }
4844 
4845 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4846   SDValue Cond = Op.getOperand(0);
4847   SDValue SelectTrue = Op.getOperand(1);
4848   SDValue SelectFalse = Op.getOperand(2);
4849   SDLoc dl(Op);
4850   unsigned Opc = Cond.getOpcode();
4851 
4852   if (Cond.getResNo() == 1 &&
4853       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4854        Opc == ISD::USUBO)) {
4855     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4856       return SDValue();
4857 
4858     SDValue Value, OverflowCmp;
4859     SDValue ARMcc;
4860     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4861     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4862     EVT VT = Op.getValueType();
4863 
4864     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4865                    OverflowCmp, DAG);
4866   }
4867 
4868   // Convert:
4869   //
4870   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4871   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4872   //
4873   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4874     const ConstantSDNode *CMOVTrue =
4875       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4876     const ConstantSDNode *CMOVFalse =
4877       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4878 
4879     if (CMOVTrue && CMOVFalse) {
4880       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4881       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4882 
4883       SDValue True;
4884       SDValue False;
4885       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4886         True = SelectTrue;
4887         False = SelectFalse;
4888       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4889         True = SelectFalse;
4890         False = SelectTrue;
4891       }
4892 
4893       if (True.getNode() && False.getNode()) {
4894         EVT VT = Op.getValueType();
4895         SDValue ARMcc = Cond.getOperand(2);
4896         SDValue CCR = Cond.getOperand(3);
4897         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4898         assert(True.getValueType() == VT);
4899         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4900       }
4901     }
4902   }
4903 
4904   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4905   // undefined bits before doing a full-word comparison with zero.
4906   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4907                      DAG.getConstant(1, dl, Cond.getValueType()));
4908 
4909   return DAG.getSelectCC(dl, Cond,
4910                          DAG.getConstant(0, dl, Cond.getValueType()),
4911                          SelectTrue, SelectFalse, ISD::SETNE);
4912 }
4913 
4914 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4915                                  bool &swpCmpOps, bool &swpVselOps) {
4916   // Start by selecting the GE condition code for opcodes that return true for
4917   // 'equality'
4918   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4919       CC == ISD::SETULE || CC == ISD::SETGE  || CC == ISD::SETLE)
4920     CondCode = ARMCC::GE;
4921 
4922   // and GT for opcodes that return false for 'equality'.
4923   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4924            CC == ISD::SETULT || CC == ISD::SETGT  || CC == ISD::SETLT)
4925     CondCode = ARMCC::GT;
4926 
4927   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4928   // to swap the compare operands.
4929   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4930       CC == ISD::SETULT || CC == ISD::SETLE  || CC == ISD::SETLT)
4931     swpCmpOps = true;
4932 
4933   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4934   // If we have an unordered opcode, we need to swap the operands to the VSEL
4935   // instruction (effectively negating the condition).
4936   //
4937   // This also has the effect of swapping which one of 'less' or 'greater'
4938   // returns true, so we also swap the compare operands. It also switches
4939   // whether we return true for 'equality', so we compensate by picking the
4940   // opposite condition code to our original choice.
4941   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4942       CC == ISD::SETUGT) {
4943     swpCmpOps = !swpCmpOps;
4944     swpVselOps = !swpVselOps;
4945     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4946   }
4947 
4948   // 'ordered' is 'anything but unordered', so use the VS condition code and
4949   // swap the VSEL operands.
4950   if (CC == ISD::SETO) {
4951     CondCode = ARMCC::VS;
4952     swpVselOps = true;
4953   }
4954 
4955   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4956   // code and swap the VSEL operands. Also do this if we don't care about the
4957   // unordered case.
4958   if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4959     CondCode = ARMCC::EQ;
4960     swpVselOps = true;
4961   }
4962 }
4963 
4964 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4965                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4966                                    SDValue Cmp, SelectionDAG &DAG) const {
4967   if (!Subtarget->hasFP64() && VT == MVT::f64) {
4968     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4969                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4970     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4971                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4972 
4973     SDValue TrueLow = TrueVal.getValue(0);
4974     SDValue TrueHigh = TrueVal.getValue(1);
4975     SDValue FalseLow = FalseVal.getValue(0);
4976     SDValue FalseHigh = FalseVal.getValue(1);
4977 
4978     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4979                               ARMcc, CCR, Cmp);
4980     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4981                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4982 
4983     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4984   } else {
4985     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4986                        Cmp);
4987   }
4988 }
4989 
4990 static bool isGTorGE(ISD::CondCode CC) {
4991   return CC == ISD::SETGT || CC == ISD::SETGE;
4992 }
4993 
4994 static bool isLTorLE(ISD::CondCode CC) {
4995   return CC == ISD::SETLT || CC == ISD::SETLE;
4996 }
4997 
4998 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4999 // All of these conditions (and their <= and >= counterparts) will do:
5000 //          x < k ? k : x
5001 //          x > k ? x : k
5002 //          k < x ? x : k
5003 //          k > x ? k : x
5004 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
5005                             const SDValue TrueVal, const SDValue FalseVal,
5006                             const ISD::CondCode CC, const SDValue K) {
5007   return (isGTorGE(CC) &&
5008           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
5009          (isLTorLE(CC) &&
5010           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
5011 }
5012 
5013 // Check if two chained conditionals could be converted into SSAT or USAT.
5014 //
5015 // SSAT can replace a set of two conditional selectors that bound a number to an
5016 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
5017 //
5018 //     x < -k ? -k : (x > k ? k : x)
5019 //     x < -k ? -k : (x < k ? x : k)
5020 //     x > -k ? (x > k ? k : x) : -k
5021 //     x < k ? (x < -k ? -k : x) : k
5022 //     etc.
5023 //
5024 // LLVM canonicalizes these to either a min(max()) or a max(min())
5025 // pattern. This function tries to match one of these and will return true
5026 // if successful.
5027 //
5028 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
5029 // a power of 2.
5030 //
5031 // It returns true if the conversion can be done, false otherwise.
5032 // Additionally, the variable is returned in parameter V, the constant in K and
5033 // usat is set to true if the conditional represents an unsigned saturation
5034 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
5035                                     uint64_t &K, bool &Usat) {
5036   SDValue V1 = Op.getOperand(0);
5037   SDValue K1 = Op.getOperand(1);
5038   SDValue TrueVal1 = Op.getOperand(2);
5039   SDValue FalseVal1 = Op.getOperand(3);
5040   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5041 
5042   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
5043   if (Op2.getOpcode() != ISD::SELECT_CC)
5044     return false;
5045 
5046   SDValue V2 = Op2.getOperand(0);
5047   SDValue K2 = Op2.getOperand(1);
5048   SDValue TrueVal2 = Op2.getOperand(2);
5049   SDValue FalseVal2 = Op2.getOperand(3);
5050   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
5051 
5052   SDValue V1Tmp = V1;
5053   SDValue V2Tmp = V2;
5054 
5055   if (V1.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5056       V2.getOpcode() == ISD::SIGN_EXTEND_INREG) {
5057     V1Tmp = V1.getOperand(0);
5058     V2Tmp = V2.getOperand(0);
5059   }
5060 
5061   // Check that the registers and the constants match a max(min()) or min(max())
5062   // pattern
5063   if (V1Tmp == TrueVal1 && V2Tmp == TrueVal2 && K1 == FalseVal1 &&
5064       K2 == FalseVal2 &&
5065       ((isGTorGE(CC1) && isLTorLE(CC2)) || (isLTorLE(CC1) && isGTorGE(CC2)))) {
5066 
5067     // Check that the constant in the lower-bound check is
5068     // the opposite of the constant in the upper-bound check
5069     // in 1's complement.
5070     if (!isa<ConstantSDNode>(K1) || !isa<ConstantSDNode>(K2))
5071       return false;
5072 
5073     int64_t Val1 = cast<ConstantSDNode>(K1)->getSExtValue();
5074     int64_t Val2 = cast<ConstantSDNode>(K2)->getSExtValue();
5075     int64_t PosVal = std::max(Val1, Val2);
5076     int64_t NegVal = std::min(Val1, Val2);
5077 
5078     if (!((Val1 > Val2 && isLTorLE(CC1)) || (Val1 < Val2 && isLTorLE(CC2))) ||
5079         !isPowerOf2_64(PosVal + 1))
5080       return false;
5081 
5082     // Handle the difference between USAT (unsigned) and SSAT (signed)
5083     // saturation
5084     if (Val1 == ~Val2)
5085       Usat = false;
5086     else if (NegVal == 0)
5087       Usat = true;
5088     else
5089       return false;
5090 
5091     V = V2Tmp;
5092     // At this point, PosVal is guaranteed to be positive
5093     K = (uint64_t) PosVal;
5094 
5095     return true;
5096   }
5097   return false;
5098 }
5099 
5100 // Check if a condition of the type x < k ? k : x can be converted into a
5101 // bit operation instead of conditional moves.
5102 // Currently this is allowed given:
5103 // - The conditions and values match up
5104 // - k is 0 or -1 (all ones)
5105 // This function will not check the last condition, thats up to the caller
5106 // It returns true if the transformation can be made, and in such case
5107 // returns x in V, and k in SatK.
5108 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
5109                                          SDValue &SatK)
5110 {
5111   SDValue LHS = Op.getOperand(0);
5112   SDValue RHS = Op.getOperand(1);
5113   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5114   SDValue TrueVal = Op.getOperand(2);
5115   SDValue FalseVal = Op.getOperand(3);
5116 
5117   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
5118                                                ? &RHS
5119                                                : nullptr;
5120 
5121   // No constant operation in comparison, early out
5122   if (!K)
5123     return false;
5124 
5125   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
5126   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
5127   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
5128 
5129   // If the constant on left and right side, or variable on left and right,
5130   // does not match, early out
5131   if (*K != KTmp || V != VTmp)
5132     return false;
5133 
5134   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
5135     SatK = *K;
5136     return true;
5137   }
5138 
5139   return false;
5140 }
5141 
5142 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
5143   if (VT == MVT::f32)
5144     return !Subtarget->hasVFP2Base();
5145   if (VT == MVT::f64)
5146     return !Subtarget->hasFP64();
5147   if (VT == MVT::f16)
5148     return !Subtarget->hasFullFP16();
5149   return false;
5150 }
5151 
5152 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5153   EVT VT = Op.getValueType();
5154   SDLoc dl(Op);
5155 
5156   // Try to convert two saturating conditional selects into a single SSAT
5157   SDValue SatValue;
5158   uint64_t SatConstant;
5159   bool SatUSat;
5160   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
5161       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
5162     if (SatUSat)
5163       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
5164                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
5165     else
5166       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
5167                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
5168   }
5169 
5170   // Try to convert expressions of the form x < k ? k : x (and similar forms)
5171   // into more efficient bit operations, which is possible when k is 0 or -1
5172   // On ARM and Thumb-2 which have flexible operand 2 this will result in
5173   // single instructions. On Thumb the shift and the bit operation will be two
5174   // instructions.
5175   // Only allow this transformation on full-width (32-bit) operations
5176   SDValue LowerSatConstant;
5177   if (VT == MVT::i32 &&
5178       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
5179     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
5180                                  DAG.getConstant(31, dl, VT));
5181     if (isNullConstant(LowerSatConstant)) {
5182       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
5183                                       DAG.getAllOnesConstant(dl, VT));
5184       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
5185     } else if (isAllOnesConstant(LowerSatConstant))
5186       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
5187   }
5188 
5189   SDValue LHS = Op.getOperand(0);
5190   SDValue RHS = Op.getOperand(1);
5191   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5192   SDValue TrueVal = Op.getOperand(2);
5193   SDValue FalseVal = Op.getOperand(3);
5194   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
5195   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
5196 
5197   if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
5198       LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
5199     unsigned TVal = CTVal->getZExtValue();
5200     unsigned FVal = CFVal->getZExtValue();
5201     unsigned Opcode = 0;
5202 
5203     if (TVal == ~FVal) {
5204       Opcode = ARMISD::CSINV;
5205     } else if (TVal == ~FVal + 1) {
5206       Opcode = ARMISD::CSNEG;
5207     } else if (TVal + 1 == FVal) {
5208       Opcode = ARMISD::CSINC;
5209     } else if (TVal == FVal + 1) {
5210       Opcode = ARMISD::CSINC;
5211       std::swap(TrueVal, FalseVal);
5212       std::swap(TVal, FVal);
5213       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5214     }
5215 
5216     if (Opcode) {
5217       // If one of the constants is cheaper than another, materialise the
5218       // cheaper one and let the csel generate the other.
5219       if (Opcode != ARMISD::CSINC &&
5220           HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
5221         std::swap(TrueVal, FalseVal);
5222         std::swap(TVal, FVal);
5223         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5224       }
5225 
5226       // Attempt to use ZR checking TVal is 0, possibly inverting the condition
5227       // to get there. CSINC not is invertable like the other two (~(~a) == a,
5228       // -(-a) == a, but (a+1)+1 != a).
5229       if (FVal == 0 && Opcode != ARMISD::CSINC) {
5230         std::swap(TrueVal, FalseVal);
5231         std::swap(TVal, FVal);
5232         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5233       }
5234       if (TVal == 0)
5235         TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
5236 
5237       // Drops F's value because we can get it by inverting/negating TVal.
5238       FalseVal = TrueVal;
5239 
5240       SDValue ARMcc;
5241       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5242       EVT VT = TrueVal.getValueType();
5243       return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
5244     }
5245   }
5246 
5247   if (isUnsupportedFloatingType(LHS.getValueType())) {
5248     DAG.getTargetLoweringInfo().softenSetCCOperands(
5249         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5250 
5251     // If softenSetCCOperands only returned one value, we should compare it to
5252     // zero.
5253     if (!RHS.getNode()) {
5254       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5255       CC = ISD::SETNE;
5256     }
5257   }
5258 
5259   if (LHS.getValueType() == MVT::i32) {
5260     // Try to generate VSEL on ARMv8.
5261     // The VSEL instruction can't use all the usual ARM condition
5262     // codes: it only has two bits to select the condition code, so it's
5263     // constrained to use only GE, GT, VS and EQ.
5264     //
5265     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5266     // swap the operands of the previous compare instruction (effectively
5267     // inverting the compare condition, swapping 'less' and 'greater') and
5268     // sometimes need to swap the operands to the VSEL (which inverts the
5269     // condition in the sense of firing whenever the previous condition didn't)
5270     if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5271                                         TrueVal.getValueType() == MVT::f32 ||
5272                                         TrueVal.getValueType() == MVT::f64)) {
5273       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5274       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5275           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5276         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5277         std::swap(TrueVal, FalseVal);
5278       }
5279     }
5280 
5281     SDValue ARMcc;
5282     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5283     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5284     // Choose GE over PL, which vsel does now support
5285     if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
5286       ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5287     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5288   }
5289 
5290   ARMCC::CondCodes CondCode, CondCode2;
5291   FPCCToARMCC(CC, CondCode, CondCode2);
5292 
5293   // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5294   // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5295   // must use VSEL (limited condition codes), due to not having conditional f16
5296   // moves.
5297   if (Subtarget->hasFPARMv8Base() &&
5298       !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5299       (TrueVal.getValueType() == MVT::f16 ||
5300        TrueVal.getValueType() == MVT::f32 ||
5301        TrueVal.getValueType() == MVT::f64)) {
5302     bool swpCmpOps = false;
5303     bool swpVselOps = false;
5304     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5305 
5306     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5307         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5308       if (swpCmpOps)
5309         std::swap(LHS, RHS);
5310       if (swpVselOps)
5311         std::swap(TrueVal, FalseVal);
5312     }
5313   }
5314 
5315   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5316   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5317   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5318   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5319   if (CondCode2 != ARMCC::AL) {
5320     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5321     // FIXME: Needs another CMP because flag can have but one use.
5322     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5323     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5324   }
5325   return Result;
5326 }
5327 
5328 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
5329 /// to morph to an integer compare sequence.
5330 static bool canChangeToInt(SDValue Op, bool &SeenZero,
5331                            const ARMSubtarget *Subtarget) {
5332   SDNode *N = Op.getNode();
5333   if (!N->hasOneUse())
5334     // Otherwise it requires moving the value from fp to integer registers.
5335     return false;
5336   if (!N->getNumValues())
5337     return false;
5338   EVT VT = Op.getValueType();
5339   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5340     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5341     // vmrs are very slow, e.g. cortex-a8.
5342     return false;
5343 
5344   if (isFloatingPointZero(Op)) {
5345     SeenZero = true;
5346     return true;
5347   }
5348   return ISD::isNormalLoad(N);
5349 }
5350 
5351 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5352   if (isFloatingPointZero(Op))
5353     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5354 
5355   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5356     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5357                        Ld->getPointerInfo(), Ld->getAlignment(),
5358                        Ld->getMemOperand()->getFlags());
5359 
5360   llvm_unreachable("Unknown VFP cmp argument!");
5361 }
5362 
5363 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5364                            SDValue &RetVal1, SDValue &RetVal2) {
5365   SDLoc dl(Op);
5366 
5367   if (isFloatingPointZero(Op)) {
5368     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5369     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5370     return;
5371   }
5372 
5373   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5374     SDValue Ptr = Ld->getBasePtr();
5375     RetVal1 =
5376         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5377                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5378 
5379     EVT PtrType = Ptr.getValueType();
5380     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5381     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5382                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5383     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5384                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
5385                           Ld->getMemOperand()->getFlags());
5386     return;
5387   }
5388 
5389   llvm_unreachable("Unknown VFP cmp argument!");
5390 }
5391 
5392 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5393 /// f32 and even f64 comparisons to integer ones.
5394 SDValue
5395 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5396   SDValue Chain = Op.getOperand(0);
5397   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5398   SDValue LHS = Op.getOperand(2);
5399   SDValue RHS = Op.getOperand(3);
5400   SDValue Dest = Op.getOperand(4);
5401   SDLoc dl(Op);
5402 
5403   bool LHSSeenZero = false;
5404   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5405   bool RHSSeenZero = false;
5406   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5407   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5408     // If unsafe fp math optimization is enabled and there are no other uses of
5409     // the CMP operands, and the condition code is EQ or NE, we can optimize it
5410     // to an integer comparison.
5411     if (CC == ISD::SETOEQ)
5412       CC = ISD::SETEQ;
5413     else if (CC == ISD::SETUNE)
5414       CC = ISD::SETNE;
5415 
5416     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5417     SDValue ARMcc;
5418     if (LHS.getValueType() == MVT::f32) {
5419       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5420                         bitcastf32Toi32(LHS, DAG), Mask);
5421       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5422                         bitcastf32Toi32(RHS, DAG), Mask);
5423       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5424       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5425       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5426                          Chain, Dest, ARMcc, CCR, Cmp);
5427     }
5428 
5429     SDValue LHS1, LHS2;
5430     SDValue RHS1, RHS2;
5431     expandf64Toi32(LHS, DAG, LHS1, LHS2);
5432     expandf64Toi32(RHS, DAG, RHS1, RHS2);
5433     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5434     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5435     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5436     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5437     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5438     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5439     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5440   }
5441 
5442   return SDValue();
5443 }
5444 
5445 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5446   SDValue Chain = Op.getOperand(0);
5447   SDValue Cond = Op.getOperand(1);
5448   SDValue Dest = Op.getOperand(2);
5449   SDLoc dl(Op);
5450 
5451   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5452   // instruction.
5453   unsigned Opc = Cond.getOpcode();
5454   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5455                       !Subtarget->isThumb1Only();
5456   if (Cond.getResNo() == 1 &&
5457       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5458        Opc == ISD::USUBO || OptimizeMul)) {
5459     // Only lower legal XALUO ops.
5460     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5461       return SDValue();
5462 
5463     // The actual operation with overflow check.
5464     SDValue Value, OverflowCmp;
5465     SDValue ARMcc;
5466     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5467 
5468     // Reverse the condition code.
5469     ARMCC::CondCodes CondCode =
5470         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5471     CondCode = ARMCC::getOppositeCondition(CondCode);
5472     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5473     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5474 
5475     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5476                        OverflowCmp);
5477   }
5478 
5479   return SDValue();
5480 }
5481 
5482 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5483   SDValue Chain = Op.getOperand(0);
5484   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5485   SDValue LHS = Op.getOperand(2);
5486   SDValue RHS = Op.getOperand(3);
5487   SDValue Dest = Op.getOperand(4);
5488   SDLoc dl(Op);
5489 
5490   if (isUnsupportedFloatingType(LHS.getValueType())) {
5491     DAG.getTargetLoweringInfo().softenSetCCOperands(
5492         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5493 
5494     // If softenSetCCOperands only returned one value, we should compare it to
5495     // zero.
5496     if (!RHS.getNode()) {
5497       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5498       CC = ISD::SETNE;
5499     }
5500   }
5501 
5502   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5503   // instruction.
5504   unsigned Opc = LHS.getOpcode();
5505   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5506                       !Subtarget->isThumb1Only();
5507   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5508       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5509        Opc == ISD::USUBO || OptimizeMul) &&
5510       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5511     // Only lower legal XALUO ops.
5512     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5513       return SDValue();
5514 
5515     // The actual operation with overflow check.
5516     SDValue Value, OverflowCmp;
5517     SDValue ARMcc;
5518     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5519 
5520     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5521       // Reverse the condition code.
5522       ARMCC::CondCodes CondCode =
5523           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5524       CondCode = ARMCC::getOppositeCondition(CondCode);
5525       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5526     }
5527     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5528 
5529     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5530                        OverflowCmp);
5531   }
5532 
5533   if (LHS.getValueType() == MVT::i32) {
5534     SDValue ARMcc;
5535     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5536     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5537     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5538                        Chain, Dest, ARMcc, CCR, Cmp);
5539   }
5540 
5541   if (getTargetMachine().Options.UnsafeFPMath &&
5542       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5543        CC == ISD::SETNE || CC == ISD::SETUNE)) {
5544     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5545       return Result;
5546   }
5547 
5548   ARMCC::CondCodes CondCode, CondCode2;
5549   FPCCToARMCC(CC, CondCode, CondCode2);
5550 
5551   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5552   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5553   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5554   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5555   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5556   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5557   if (CondCode2 != ARMCC::AL) {
5558     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5559     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5560     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5561   }
5562   return Res;
5563 }
5564 
5565 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5566   SDValue Chain = Op.getOperand(0);
5567   SDValue Table = Op.getOperand(1);
5568   SDValue Index = Op.getOperand(2);
5569   SDLoc dl(Op);
5570 
5571   EVT PTy = getPointerTy(DAG.getDataLayout());
5572   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5573   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5574   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5575   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5576   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5577   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5578     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5579     // which does another jump to the destination. This also makes it easier
5580     // to translate it to TBB / TBH later (Thumb2 only).
5581     // FIXME: This might not work if the function is extremely large.
5582     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5583                        Addr, Op.getOperand(2), JTI);
5584   }
5585   if (isPositionIndependent() || Subtarget->isROPI()) {
5586     Addr =
5587         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5588                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5589     Chain = Addr.getValue(1);
5590     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5591     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5592   } else {
5593     Addr =
5594         DAG.getLoad(PTy, dl, Chain, Addr,
5595                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5596     Chain = Addr.getValue(1);
5597     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5598   }
5599 }
5600 
5601 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5602   EVT VT = Op.getValueType();
5603   SDLoc dl(Op);
5604 
5605   if (Op.getValueType().getVectorElementType() == MVT::i32) {
5606     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5607       return Op;
5608     return DAG.UnrollVectorOp(Op.getNode());
5609   }
5610 
5611   const bool HasFullFP16 =
5612     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5613 
5614   EVT NewTy;
5615   const EVT OpTy = Op.getOperand(0).getValueType();
5616   if (OpTy == MVT::v4f32)
5617     NewTy = MVT::v4i32;
5618   else if (OpTy == MVT::v4f16 && HasFullFP16)
5619     NewTy = MVT::v4i16;
5620   else if (OpTy == MVT::v8f16 && HasFullFP16)
5621     NewTy = MVT::v8i16;
5622   else
5623     llvm_unreachable("Invalid type for custom lowering!");
5624 
5625   if (VT != MVT::v4i16 && VT != MVT::v8i16)
5626     return DAG.UnrollVectorOp(Op.getNode());
5627 
5628   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5629   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5630 }
5631 
5632 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5633   EVT VT = Op.getValueType();
5634   if (VT.isVector())
5635     return LowerVectorFP_TO_INT(Op, DAG);
5636 
5637   bool IsStrict = Op->isStrictFPOpcode();
5638   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5639 
5640   if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5641     RTLIB::Libcall LC;
5642     if (Op.getOpcode() == ISD::FP_TO_SINT ||
5643         Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5644       LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5645                               Op.getValueType());
5646     else
5647       LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5648                               Op.getValueType());
5649     SDLoc Loc(Op);
5650     MakeLibCallOptions CallOptions;
5651     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5652     SDValue Result;
5653     std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5654                                           CallOptions, Loc, Chain);
5655     return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5656   }
5657 
5658   // FIXME: Remove this when we have strict fp instruction selection patterns
5659   if (IsStrict) {
5660     SDLoc Loc(Op);
5661     SDValue Result =
5662         DAG.getNode(Op.getOpcode() == ISD::STRICT_FP_TO_SINT ? ISD::FP_TO_SINT
5663                                                              : ISD::FP_TO_UINT,
5664                     Loc, Op.getValueType(), SrcVal);
5665     return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
5666   }
5667 
5668   return Op;
5669 }
5670 
5671 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5672   EVT VT = Op.getValueType();
5673   SDLoc dl(Op);
5674 
5675   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5676     if (VT.getVectorElementType() == MVT::f32)
5677       return Op;
5678     return DAG.UnrollVectorOp(Op.getNode());
5679   }
5680 
5681   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5682           Op.getOperand(0).getValueType() == MVT::v8i16) &&
5683          "Invalid type for custom lowering!");
5684 
5685   const bool HasFullFP16 =
5686     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5687 
5688   EVT DestVecType;
5689   if (VT == MVT::v4f32)
5690     DestVecType = MVT::v4i32;
5691   else if (VT == MVT::v4f16 && HasFullFP16)
5692     DestVecType = MVT::v4i16;
5693   else if (VT == MVT::v8f16 && HasFullFP16)
5694     DestVecType = MVT::v8i16;
5695   else
5696     return DAG.UnrollVectorOp(Op.getNode());
5697 
5698   unsigned CastOpc;
5699   unsigned Opc;
5700   switch (Op.getOpcode()) {
5701   default: llvm_unreachable("Invalid opcode!");
5702   case ISD::SINT_TO_FP:
5703     CastOpc = ISD::SIGN_EXTEND;
5704     Opc = ISD::SINT_TO_FP;
5705     break;
5706   case ISD::UINT_TO_FP:
5707     CastOpc = ISD::ZERO_EXTEND;
5708     Opc = ISD::UINT_TO_FP;
5709     break;
5710   }
5711 
5712   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5713   return DAG.getNode(Opc, dl, VT, Op);
5714 }
5715 
5716 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5717   EVT VT = Op.getValueType();
5718   if (VT.isVector())
5719     return LowerVectorINT_TO_FP(Op, DAG);
5720   if (isUnsupportedFloatingType(VT)) {
5721     RTLIB::Libcall LC;
5722     if (Op.getOpcode() == ISD::SINT_TO_FP)
5723       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5724                               Op.getValueType());
5725     else
5726       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5727                               Op.getValueType());
5728     MakeLibCallOptions CallOptions;
5729     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5730                        CallOptions, SDLoc(Op)).first;
5731   }
5732 
5733   return Op;
5734 }
5735 
5736 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5737   // Implement fcopysign with a fabs and a conditional fneg.
5738   SDValue Tmp0 = Op.getOperand(0);
5739   SDValue Tmp1 = Op.getOperand(1);
5740   SDLoc dl(Op);
5741   EVT VT = Op.getValueType();
5742   EVT SrcVT = Tmp1.getValueType();
5743   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5744     Tmp0.getOpcode() == ARMISD::VMOVDRR;
5745   bool UseNEON = !InGPR && Subtarget->hasNEON();
5746 
5747   if (UseNEON) {
5748     // Use VBSL to copy the sign bit.
5749     unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5750     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5751                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5752     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5753     if (VT == MVT::f64)
5754       Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5755                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5756                          DAG.getConstant(32, dl, MVT::i32));
5757     else /*if (VT == MVT::f32)*/
5758       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5759     if (SrcVT == MVT::f32) {
5760       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5761       if (VT == MVT::f64)
5762         Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5763                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5764                            DAG.getConstant(32, dl, MVT::i32));
5765     } else if (VT == MVT::f32)
5766       Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5767                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5768                          DAG.getConstant(32, dl, MVT::i32));
5769     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5770     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5771 
5772     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5773                                             dl, MVT::i32);
5774     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5775     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5776                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5777 
5778     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5779                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5780                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5781     if (VT == MVT::f32) {
5782       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5783       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5784                         DAG.getConstant(0, dl, MVT::i32));
5785     } else {
5786       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5787     }
5788 
5789     return Res;
5790   }
5791 
5792   // Bitcast operand 1 to i32.
5793   if (SrcVT == MVT::f64)
5794     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5795                        Tmp1).getValue(1);
5796   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5797 
5798   // Or in the signbit with integer operations.
5799   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5800   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5801   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5802   if (VT == MVT::f32) {
5803     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5804                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5805     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5806                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5807   }
5808 
5809   // f64: Or the high part with signbit and then combine two parts.
5810   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5811                      Tmp0);
5812   SDValue Lo = Tmp0.getValue(0);
5813   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5814   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5815   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5816 }
5817 
5818 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5819   MachineFunction &MF = DAG.getMachineFunction();
5820   MachineFrameInfo &MFI = MF.getFrameInfo();
5821   MFI.setReturnAddressIsTaken(true);
5822 
5823   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5824     return SDValue();
5825 
5826   EVT VT = Op.getValueType();
5827   SDLoc dl(Op);
5828   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5829   if (Depth) {
5830     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5831     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5832     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5833                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5834                        MachinePointerInfo());
5835   }
5836 
5837   // Return LR, which contains the return address. Mark it an implicit live-in.
5838   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5839   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5840 }
5841 
5842 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5843   const ARMBaseRegisterInfo &ARI =
5844     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5845   MachineFunction &MF = DAG.getMachineFunction();
5846   MachineFrameInfo &MFI = MF.getFrameInfo();
5847   MFI.setFrameAddressIsTaken(true);
5848 
5849   EVT VT = Op.getValueType();
5850   SDLoc dl(Op);  // FIXME probably not meaningful
5851   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5852   Register FrameReg = ARI.getFrameRegister(MF);
5853   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5854   while (Depth--)
5855     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5856                             MachinePointerInfo());
5857   return FrameAddr;
5858 }
5859 
5860 // FIXME? Maybe this could be a TableGen attribute on some registers and
5861 // this table could be generated automatically from RegInfo.
5862 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
5863                                               const MachineFunction &MF) const {
5864   Register Reg = StringSwitch<unsigned>(RegName)
5865                        .Case("sp", ARM::SP)
5866                        .Default(0);
5867   if (Reg)
5868     return Reg;
5869   report_fatal_error(Twine("Invalid register name \""
5870                               + StringRef(RegName)  + "\"."));
5871 }
5872 
5873 // Result is 64 bit value so split into two 32 bit values and return as a
5874 // pair of values.
5875 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5876                                 SelectionDAG &DAG) {
5877   SDLoc DL(N);
5878 
5879   // This function is only supposed to be called for i64 type destination.
5880   assert(N->getValueType(0) == MVT::i64
5881           && "ExpandREAD_REGISTER called for non-i64 type result.");
5882 
5883   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5884                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5885                              N->getOperand(0),
5886                              N->getOperand(1));
5887 
5888   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5889                     Read.getValue(1)));
5890   Results.push_back(Read.getOperand(0));
5891 }
5892 
5893 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5894 /// When \p DstVT, the destination type of \p BC, is on the vector
5895 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5896 /// it might be possible to combine them, such that everything stays on the
5897 /// vector register bank.
5898 /// \p return The node that would replace \p BT, if the combine
5899 /// is possible.
5900 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5901                                                 SelectionDAG &DAG) {
5902   SDValue Op = BC->getOperand(0);
5903   EVT DstVT = BC->getValueType(0);
5904 
5905   // The only vector instruction that can produce a scalar (remember,
5906   // since the bitcast was about to be turned into VMOVDRR, the source
5907   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5908   // Moreover, we can do this combine only if there is one use.
5909   // Finally, if the destination type is not a vector, there is not
5910   // much point on forcing everything on the vector bank.
5911   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5912       !Op.hasOneUse())
5913     return SDValue();
5914 
5915   // If the index is not constant, we will introduce an additional
5916   // multiply that will stick.
5917   // Give up in that case.
5918   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5919   if (!Index)
5920     return SDValue();
5921   unsigned DstNumElt = DstVT.getVectorNumElements();
5922 
5923   // Compute the new index.
5924   const APInt &APIntIndex = Index->getAPIntValue();
5925   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5926   NewIndex *= APIntIndex;
5927   // Check if the new constant index fits into i32.
5928   if (NewIndex.getBitWidth() > 32)
5929     return SDValue();
5930 
5931   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5932   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5933   SDLoc dl(Op);
5934   SDValue ExtractSrc = Op.getOperand(0);
5935   EVT VecVT = EVT::getVectorVT(
5936       *DAG.getContext(), DstVT.getScalarType(),
5937       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5938   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5939   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5940                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5941 }
5942 
5943 /// ExpandBITCAST - If the target supports VFP, this function is called to
5944 /// expand a bit convert where either the source or destination type is i64 to
5945 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5946 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5947 /// vectors), since the legalizer won't know what to do with that.
5948 SDValue ARMTargetLowering::ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5949                                          const ARMSubtarget *Subtarget) const {
5950   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5951   SDLoc dl(N);
5952   SDValue Op = N->getOperand(0);
5953 
5954   // This function is only supposed to be called for i16 and i64 types, either
5955   // as the source or destination of the bit convert.
5956   EVT SrcVT = Op.getValueType();
5957   EVT DstVT = N->getValueType(0);
5958 
5959   if ((SrcVT == MVT::i16 || SrcVT == MVT::i32) &&
5960       (DstVT == MVT::f16 || DstVT == MVT::bf16))
5961     return MoveToHPR(SDLoc(N), DAG, MVT::i32, DstVT.getSimpleVT(),
5962                      DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), MVT::i32, Op));
5963 
5964   if ((DstVT == MVT::i16 || DstVT == MVT::i32) &&
5965       (SrcVT == MVT::f16 || SrcVT == MVT::bf16))
5966     return DAG.getNode(
5967         ISD::TRUNCATE, SDLoc(N), DstVT,
5968         MoveFromHPR(SDLoc(N), DAG, MVT::i32, SrcVT.getSimpleVT(), Op));
5969 
5970   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5971     return SDValue();
5972 
5973   // Turn i64->f64 into VMOVDRR.
5974   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5975     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5976     // if we can combine the bitcast with its source.
5977     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5978       return Val;
5979 
5980     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5981                              DAG.getConstant(0, dl, MVT::i32));
5982     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5983                              DAG.getConstant(1, dl, MVT::i32));
5984     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5985                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5986   }
5987 
5988   // Turn f64->i64 into VMOVRRD.
5989   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5990     SDValue Cvt;
5991     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5992         SrcVT.getVectorNumElements() > 1)
5993       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5994                         DAG.getVTList(MVT::i32, MVT::i32),
5995                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5996     else
5997       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5998                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5999     // Merge the pieces into a single i64 value.
6000     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
6001   }
6002 
6003   return SDValue();
6004 }
6005 
6006 /// getZeroVector - Returns a vector of specified type with all zero elements.
6007 /// Zero vectors are used to represent vector negation and in those cases
6008 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
6009 /// not support i64 elements, so sometimes the zero vectors will need to be
6010 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
6011 /// zero vector.
6012 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
6013   assert(VT.isVector() && "Expected a vector type");
6014   // The canonical modified immediate encoding of a zero vector is....0!
6015   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
6016   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
6017   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
6018   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6019 }
6020 
6021 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
6022 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
6023 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
6024                                                 SelectionDAG &DAG) const {
6025   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6026   EVT VT = Op.getValueType();
6027   unsigned VTBits = VT.getSizeInBits();
6028   SDLoc dl(Op);
6029   SDValue ShOpLo = Op.getOperand(0);
6030   SDValue ShOpHi = Op.getOperand(1);
6031   SDValue ShAmt  = Op.getOperand(2);
6032   SDValue ARMcc;
6033   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6034   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
6035 
6036   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
6037 
6038   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6039                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6040   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
6041   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6042                                    DAG.getConstant(VTBits, dl, MVT::i32));
6043   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
6044   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6045   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
6046   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6047                             ISD::SETGE, ARMcc, DAG, dl);
6048   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
6049                            ARMcc, CCR, CmpLo);
6050 
6051   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
6052   SDValue HiBigShift = Opc == ISD::SRA
6053                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
6054                                          DAG.getConstant(VTBits - 1, dl, VT))
6055                            : DAG.getConstant(0, dl, VT);
6056   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6057                             ISD::SETGE, ARMcc, DAG, dl);
6058   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6059                            ARMcc, CCR, CmpHi);
6060 
6061   SDValue Ops[2] = { Lo, Hi };
6062   return DAG.getMergeValues(Ops, dl);
6063 }
6064 
6065 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
6066 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
6067 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
6068                                                SelectionDAG &DAG) const {
6069   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6070   EVT VT = Op.getValueType();
6071   unsigned VTBits = VT.getSizeInBits();
6072   SDLoc dl(Op);
6073   SDValue ShOpLo = Op.getOperand(0);
6074   SDValue ShOpHi = Op.getOperand(1);
6075   SDValue ShAmt  = Op.getOperand(2);
6076   SDValue ARMcc;
6077   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6078 
6079   assert(Op.getOpcode() == ISD::SHL_PARTS);
6080   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6081                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
6082   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
6083   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
6084   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
6085 
6086   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
6087                                    DAG.getConstant(VTBits, dl, MVT::i32));
6088   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
6089   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6090                             ISD::SETGE, ARMcc, DAG, dl);
6091   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
6092                            ARMcc, CCR, CmpHi);
6093 
6094   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
6095                           ISD::SETGE, ARMcc, DAG, dl);
6096   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6097   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
6098                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
6099 
6100   SDValue Ops[2] = { Lo, Hi };
6101   return DAG.getMergeValues(Ops, dl);
6102 }
6103 
6104 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
6105                                             SelectionDAG &DAG) const {
6106   // The rounding mode is in bits 23:22 of the FPSCR.
6107   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
6108   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
6109   // so that the shift + and get folded into a bitfield extract.
6110   SDLoc dl(Op);
6111   SDValue Chain = Op.getOperand(0);
6112   SDValue Ops[] = {Chain,
6113                    DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32)};
6114 
6115   SDValue FPSCR =
6116       DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, {MVT::i32, MVT::Other}, Ops);
6117   Chain = FPSCR.getValue(1);
6118   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
6119                                   DAG.getConstant(1U << 22, dl, MVT::i32));
6120   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
6121                               DAG.getConstant(22, dl, MVT::i32));
6122   SDValue And = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
6123                             DAG.getConstant(3, dl, MVT::i32));
6124   return DAG.getMergeValues({And, Chain}, dl);
6125 }
6126 
6127 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
6128                          const ARMSubtarget *ST) {
6129   SDLoc dl(N);
6130   EVT VT = N->getValueType(0);
6131   if (VT.isVector() && ST->hasNEON()) {
6132 
6133     // Compute the least significant set bit: LSB = X & -X
6134     SDValue X = N->getOperand(0);
6135     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
6136     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
6137 
6138     EVT ElemTy = VT.getVectorElementType();
6139 
6140     if (ElemTy == MVT::i8) {
6141       // Compute with: cttz(x) = ctpop(lsb - 1)
6142       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6143                                 DAG.getTargetConstant(1, dl, ElemTy));
6144       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6145       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6146     }
6147 
6148     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
6149         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
6150       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
6151       unsigned NumBits = ElemTy.getSizeInBits();
6152       SDValue WidthMinus1 =
6153           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6154                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
6155       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
6156       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
6157     }
6158 
6159     // Compute with: cttz(x) = ctpop(lsb - 1)
6160 
6161     // Compute LSB - 1.
6162     SDValue Bits;
6163     if (ElemTy == MVT::i64) {
6164       // Load constant 0xffff'ffff'ffff'ffff to register.
6165       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6166                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
6167       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
6168     } else {
6169       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
6170                                 DAG.getTargetConstant(1, dl, ElemTy));
6171       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
6172     }
6173     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
6174   }
6175 
6176   if (!ST->hasV6T2Ops())
6177     return SDValue();
6178 
6179   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
6180   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
6181 }
6182 
6183 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
6184                           const ARMSubtarget *ST) {
6185   EVT VT = N->getValueType(0);
6186   SDLoc DL(N);
6187 
6188   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
6189   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
6190           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
6191          "Unexpected type for custom ctpop lowering");
6192 
6193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6194   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
6195   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
6196   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
6197 
6198   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
6199   unsigned EltSize = 8;
6200   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6201   while (EltSize != VT.getScalarSizeInBits()) {
6202     SmallVector<SDValue, 8> Ops;
6203     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6204                                   TLI.getPointerTy(DAG.getDataLayout())));
6205     Ops.push_back(Res);
6206 
6207     EltSize *= 2;
6208     NumElts /= 2;
6209     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6210     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6211   }
6212 
6213   return Res;
6214 }
6215 
6216 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
6217 /// operand of a vector shift operation, where all the elements of the
6218 /// build_vector must have the same constant integer value.
6219 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6220   // Ignore bit_converts.
6221   while (Op.getOpcode() == ISD::BITCAST)
6222     Op = Op.getOperand(0);
6223   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6224   APInt SplatBits, SplatUndef;
6225   unsigned SplatBitSize;
6226   bool HasAnyUndefs;
6227   if (!BVN ||
6228       !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6229                             ElementBits) ||
6230       SplatBitSize > ElementBits)
6231     return false;
6232   Cnt = SplatBits.getSExtValue();
6233   return true;
6234 }
6235 
6236 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6237 /// operand of a vector shift left operation.  That value must be in the range:
6238 ///   0 <= Value < ElementBits for a left shift; or
6239 ///   0 <= Value <= ElementBits for a long left shift.
6240 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6241   assert(VT.isVector() && "vector shift count is not a vector type");
6242   int64_t ElementBits = VT.getScalarSizeInBits();
6243   if (!getVShiftImm(Op, ElementBits, Cnt))
6244     return false;
6245   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6246 }
6247 
6248 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6249 /// operand of a vector shift right operation.  For a shift opcode, the value
6250 /// is positive, but for an intrinsic the value count must be negative. The
6251 /// absolute value must be in the range:
6252 ///   1 <= |Value| <= ElementBits for a right shift; or
6253 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6254 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6255                          int64_t &Cnt) {
6256   assert(VT.isVector() && "vector shift count is not a vector type");
6257   int64_t ElementBits = VT.getScalarSizeInBits();
6258   if (!getVShiftImm(Op, ElementBits, Cnt))
6259     return false;
6260   if (!isIntrinsic)
6261     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6262   if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6263     Cnt = -Cnt;
6264     return true;
6265   }
6266   return false;
6267 }
6268 
6269 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6270                           const ARMSubtarget *ST) {
6271   EVT VT = N->getValueType(0);
6272   SDLoc dl(N);
6273   int64_t Cnt;
6274 
6275   if (!VT.isVector())
6276     return SDValue();
6277 
6278   // We essentially have two forms here. Shift by an immediate and shift by a
6279   // vector register (there are also shift by a gpr, but that is just handled
6280   // with a tablegen pattern). We cannot easily match shift by an immediate in
6281   // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6282   // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6283   // signed or unsigned, and a negative shift indicates a shift right).
6284   if (N->getOpcode() == ISD::SHL) {
6285     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6286       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6287                          DAG.getConstant(Cnt, dl, MVT::i32));
6288     return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6289                        N->getOperand(1));
6290   }
6291 
6292   assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6293          "unexpected vector shift opcode");
6294 
6295   if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6296     unsigned VShiftOpc =
6297         (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6298     return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6299                        DAG.getConstant(Cnt, dl, MVT::i32));
6300   }
6301 
6302   // Other right shifts we don't have operations for (we use a shift left by a
6303   // negative number).
6304   EVT ShiftVT = N->getOperand(1).getValueType();
6305   SDValue NegatedCount = DAG.getNode(
6306       ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6307   unsigned VShiftOpc =
6308       (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6309   return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6310 }
6311 
6312 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6313                                 const ARMSubtarget *ST) {
6314   EVT VT = N->getValueType(0);
6315   SDLoc dl(N);
6316 
6317   // We can get here for a node like i32 = ISD::SHL i32, i64
6318   if (VT != MVT::i64)
6319     return SDValue();
6320 
6321   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6322           N->getOpcode() == ISD::SHL) &&
6323          "Unknown shift to lower!");
6324 
6325   unsigned ShOpc = N->getOpcode();
6326   if (ST->hasMVEIntegerOps()) {
6327     SDValue ShAmt = N->getOperand(1);
6328     unsigned ShPartsOpc = ARMISD::LSLL;
6329     ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6330 
6331     // If the shift amount is greater than 32 or has a greater bitwidth than 64
6332     // then do the default optimisation
6333     if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6334         (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6335       return SDValue();
6336 
6337     // Extract the lower 32 bits of the shift amount if it's not an i32
6338     if (ShAmt->getValueType(0) != MVT::i32)
6339       ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6340 
6341     if (ShOpc == ISD::SRL) {
6342       if (!Con)
6343         // There is no t2LSRLr instruction so negate and perform an lsll if the
6344         // shift amount is in a register, emulating a right shift.
6345         ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6346                             DAG.getConstant(0, dl, MVT::i32), ShAmt);
6347       else
6348         // Else generate an lsrl on the immediate shift amount
6349         ShPartsOpc = ARMISD::LSRL;
6350     } else if (ShOpc == ISD::SRA)
6351       ShPartsOpc = ARMISD::ASRL;
6352 
6353     // Lower 32 bits of the destination/source
6354     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6355                              DAG.getConstant(0, dl, MVT::i32));
6356     // Upper 32 bits of the destination/source
6357     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6358                              DAG.getConstant(1, dl, MVT::i32));
6359 
6360     // Generate the shift operation as computed above
6361     Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6362                      ShAmt);
6363     // The upper 32 bits come from the second return value of lsll
6364     Hi = SDValue(Lo.getNode(), 1);
6365     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6366   }
6367 
6368   // We only lower SRA, SRL of 1 here, all others use generic lowering.
6369   if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6370     return SDValue();
6371 
6372   // If we are in thumb mode, we don't have RRX.
6373   if (ST->isThumb1Only())
6374     return SDValue();
6375 
6376   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
6377   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6378                            DAG.getConstant(0, dl, MVT::i32));
6379   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6380                            DAG.getConstant(1, dl, MVT::i32));
6381 
6382   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6383   // captures the result into a carry flag.
6384   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6385   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6386 
6387   // The low part is an ARMISD::RRX operand, which shifts the carry in.
6388   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6389 
6390   // Merge the pieces into a single i64 value.
6391  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6392 }
6393 
6394 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6395                            const ARMSubtarget *ST) {
6396   bool Invert = false;
6397   bool Swap = false;
6398   unsigned Opc = ARMCC::AL;
6399 
6400   SDValue Op0 = Op.getOperand(0);
6401   SDValue Op1 = Op.getOperand(1);
6402   SDValue CC = Op.getOperand(2);
6403   EVT VT = Op.getValueType();
6404   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6405   SDLoc dl(Op);
6406 
6407   EVT CmpVT;
6408   if (ST->hasNEON())
6409     CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6410   else {
6411     assert(ST->hasMVEIntegerOps() &&
6412            "No hardware support for integer vector comparison!");
6413 
6414     if (Op.getValueType().getVectorElementType() != MVT::i1)
6415       return SDValue();
6416 
6417     // Make sure we expand floating point setcc to scalar if we do not have
6418     // mve.fp, so that we can handle them from there.
6419     if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6420       return SDValue();
6421 
6422     CmpVT = VT;
6423   }
6424 
6425   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6426       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6427     // Special-case integer 64-bit equality comparisons. They aren't legal,
6428     // but they can be lowered with a few vector instructions.
6429     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6430     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6431     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6432     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6433     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6434                               DAG.getCondCode(ISD::SETEQ));
6435     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6436     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6437     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6438     if (SetCCOpcode == ISD::SETNE)
6439       Merged = DAG.getNOT(dl, Merged, CmpVT);
6440     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6441     return Merged;
6442   }
6443 
6444   if (CmpVT.getVectorElementType() == MVT::i64)
6445     // 64-bit comparisons are not legal in general.
6446     return SDValue();
6447 
6448   if (Op1.getValueType().isFloatingPoint()) {
6449     switch (SetCCOpcode) {
6450     default: llvm_unreachable("Illegal FP comparison");
6451     case ISD::SETUNE:
6452     case ISD::SETNE:
6453       if (ST->hasMVEFloatOps()) {
6454         Opc = ARMCC::NE; break;
6455       } else {
6456         Invert = true; LLVM_FALLTHROUGH;
6457       }
6458     case ISD::SETOEQ:
6459     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6460     case ISD::SETOLT:
6461     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6462     case ISD::SETOGT:
6463     case ISD::SETGT:  Opc = ARMCC::GT; break;
6464     case ISD::SETOLE:
6465     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6466     case ISD::SETOGE:
6467     case ISD::SETGE: Opc = ARMCC::GE; break;
6468     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6469     case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6470     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6471     case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6472     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6473     case ISD::SETONE: {
6474       // Expand this to (OLT | OGT).
6475       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6476                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6477       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6478                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6479       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6480       if (Invert)
6481         Result = DAG.getNOT(dl, Result, VT);
6482       return Result;
6483     }
6484     case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6485     case ISD::SETO: {
6486       // Expand this to (OLT | OGE).
6487       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6488                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6489       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6490                                    DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6491       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6492       if (Invert)
6493         Result = DAG.getNOT(dl, Result, VT);
6494       return Result;
6495     }
6496     }
6497   } else {
6498     // Integer comparisons.
6499     switch (SetCCOpcode) {
6500     default: llvm_unreachable("Illegal integer comparison");
6501     case ISD::SETNE:
6502       if (ST->hasMVEIntegerOps()) {
6503         Opc = ARMCC::NE; break;
6504       } else {
6505         Invert = true; LLVM_FALLTHROUGH;
6506       }
6507     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6508     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
6509     case ISD::SETGT:  Opc = ARMCC::GT; break;
6510     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6511     case ISD::SETGE:  Opc = ARMCC::GE; break;
6512     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6513     case ISD::SETUGT: Opc = ARMCC::HI; break;
6514     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6515     case ISD::SETUGE: Opc = ARMCC::HS; break;
6516     }
6517 
6518     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6519     if (ST->hasNEON() && Opc == ARMCC::EQ) {
6520       SDValue AndOp;
6521       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6522         AndOp = Op0;
6523       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6524         AndOp = Op1;
6525 
6526       // Ignore bitconvert.
6527       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6528         AndOp = AndOp.getOperand(0);
6529 
6530       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6531         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6532         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6533         SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6534         if (!Invert)
6535           Result = DAG.getNOT(dl, Result, VT);
6536         return Result;
6537       }
6538     }
6539   }
6540 
6541   if (Swap)
6542     std::swap(Op0, Op1);
6543 
6544   // If one of the operands is a constant vector zero, attempt to fold the
6545   // comparison to a specialized compare-against-zero form.
6546   SDValue SingleOp;
6547   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6548     SingleOp = Op0;
6549   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6550     if (Opc == ARMCC::GE)
6551       Opc = ARMCC::LE;
6552     else if (Opc == ARMCC::GT)
6553       Opc = ARMCC::LT;
6554     SingleOp = Op1;
6555   }
6556 
6557   SDValue Result;
6558   if (SingleOp.getNode()) {
6559     Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6560                          DAG.getConstant(Opc, dl, MVT::i32));
6561   } else {
6562     Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6563                          DAG.getConstant(Opc, dl, MVT::i32));
6564   }
6565 
6566   Result = DAG.getSExtOrTrunc(Result, dl, VT);
6567 
6568   if (Invert)
6569     Result = DAG.getNOT(dl, Result, VT);
6570 
6571   return Result;
6572 }
6573 
6574 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6575   SDValue LHS = Op.getOperand(0);
6576   SDValue RHS = Op.getOperand(1);
6577   SDValue Carry = Op.getOperand(2);
6578   SDValue Cond = Op.getOperand(3);
6579   SDLoc DL(Op);
6580 
6581   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6582 
6583   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6584   // have to invert the carry first.
6585   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6586                       DAG.getConstant(1, DL, MVT::i32), Carry);
6587   // This converts the boolean value carry into the carry flag.
6588   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6589 
6590   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6591   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6592 
6593   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6594   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6595   SDValue ARMcc = DAG.getConstant(
6596       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6597   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6598   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6599                                    Cmp.getValue(1), SDValue());
6600   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6601                      CCR, Chain.getValue(1));
6602 }
6603 
6604 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6605 /// valid vector constant for a NEON or MVE instruction with a "modified
6606 /// immediate" operand (e.g., VMOV).  If so, return the encoded value.
6607 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6608                                  unsigned SplatBitSize, SelectionDAG &DAG,
6609                                  const SDLoc &dl, EVT &VT, EVT VectorVT,
6610                                  VMOVModImmType type) {
6611   unsigned OpCmode, Imm;
6612   bool is128Bits = VectorVT.is128BitVector();
6613 
6614   // SplatBitSize is set to the smallest size that splats the vector, so a
6615   // zero vector will always have SplatBitSize == 8.  However, NEON modified
6616   // immediate instructions others than VMOV do not support the 8-bit encoding
6617   // of a zero vector, and the default encoding of zero is supposed to be the
6618   // 32-bit version.
6619   if (SplatBits == 0)
6620     SplatBitSize = 32;
6621 
6622   switch (SplatBitSize) {
6623   case 8:
6624     if (type != VMOVModImm)
6625       return SDValue();
6626     // Any 1-byte value is OK.  Op=0, Cmode=1110.
6627     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6628     OpCmode = 0xe;
6629     Imm = SplatBits;
6630     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6631     break;
6632 
6633   case 16:
6634     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6635     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6636     if ((SplatBits & ~0xff) == 0) {
6637       // Value = 0x00nn: Op=x, Cmode=100x.
6638       OpCmode = 0x8;
6639       Imm = SplatBits;
6640       break;
6641     }
6642     if ((SplatBits & ~0xff00) == 0) {
6643       // Value = 0xnn00: Op=x, Cmode=101x.
6644       OpCmode = 0xa;
6645       Imm = SplatBits >> 8;
6646       break;
6647     }
6648     return SDValue();
6649 
6650   case 32:
6651     // NEON's 32-bit VMOV supports splat values where:
6652     // * only one byte is nonzero, or
6653     // * the least significant byte is 0xff and the second byte is nonzero, or
6654     // * the least significant 2 bytes are 0xff and the third is nonzero.
6655     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6656     if ((SplatBits & ~0xff) == 0) {
6657       // Value = 0x000000nn: Op=x, Cmode=000x.
6658       OpCmode = 0;
6659       Imm = SplatBits;
6660       break;
6661     }
6662     if ((SplatBits & ~0xff00) == 0) {
6663       // Value = 0x0000nn00: Op=x, Cmode=001x.
6664       OpCmode = 0x2;
6665       Imm = SplatBits >> 8;
6666       break;
6667     }
6668     if ((SplatBits & ~0xff0000) == 0) {
6669       // Value = 0x00nn0000: Op=x, Cmode=010x.
6670       OpCmode = 0x4;
6671       Imm = SplatBits >> 16;
6672       break;
6673     }
6674     if ((SplatBits & ~0xff000000) == 0) {
6675       // Value = 0xnn000000: Op=x, Cmode=011x.
6676       OpCmode = 0x6;
6677       Imm = SplatBits >> 24;
6678       break;
6679     }
6680 
6681     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6682     if (type == OtherModImm) return SDValue();
6683 
6684     if ((SplatBits & ~0xffff) == 0 &&
6685         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6686       // Value = 0x0000nnff: Op=x, Cmode=1100.
6687       OpCmode = 0xc;
6688       Imm = SplatBits >> 8;
6689       break;
6690     }
6691 
6692     // cmode == 0b1101 is not supported for MVE VMVN
6693     if (type == MVEVMVNModImm)
6694       return SDValue();
6695 
6696     if ((SplatBits & ~0xffffff) == 0 &&
6697         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6698       // Value = 0x00nnffff: Op=x, Cmode=1101.
6699       OpCmode = 0xd;
6700       Imm = SplatBits >> 16;
6701       break;
6702     }
6703 
6704     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6705     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6706     // VMOV.I32.  A (very) minor optimization would be to replicate the value
6707     // and fall through here to test for a valid 64-bit splat.  But, then the
6708     // caller would also need to check and handle the change in size.
6709     return SDValue();
6710 
6711   case 64: {
6712     if (type != VMOVModImm)
6713       return SDValue();
6714     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6715     uint64_t BitMask = 0xff;
6716     uint64_t Val = 0;
6717     unsigned ImmMask = 1;
6718     Imm = 0;
6719     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6720       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6721         Val |= BitMask;
6722         Imm |= ImmMask;
6723       } else if ((SplatBits & BitMask) != 0) {
6724         return SDValue();
6725       }
6726       BitMask <<= 8;
6727       ImmMask <<= 1;
6728     }
6729 
6730     if (DAG.getDataLayout().isBigEndian()) {
6731       // Reverse the order of elements within the vector.
6732       unsigned BytesPerElem = VectorVT.getScalarSizeInBits() / 8;
6733       unsigned Mask = (1 << BytesPerElem) - 1;
6734       unsigned NumElems = 8 / BytesPerElem;
6735       unsigned NewImm = 0;
6736       for (unsigned ElemNum = 0; ElemNum < NumElems; ++ElemNum) {
6737         unsigned Elem = ((Imm >> ElemNum * BytesPerElem) & Mask);
6738         NewImm |= Elem << (NumElems - ElemNum - 1) * BytesPerElem;
6739       }
6740       Imm = NewImm;
6741     }
6742 
6743     // Op=1, Cmode=1110.
6744     OpCmode = 0x1e;
6745     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6746     break;
6747   }
6748 
6749   default:
6750     llvm_unreachable("unexpected size for isVMOVModifiedImm");
6751   }
6752 
6753   unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6754   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6755 }
6756 
6757 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6758                                            const ARMSubtarget *ST) const {
6759   EVT VT = Op.getValueType();
6760   bool IsDouble = (VT == MVT::f64);
6761   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6762   const APFloat &FPVal = CFP->getValueAPF();
6763 
6764   // Prevent floating-point constants from using literal loads
6765   // when execute-only is enabled.
6766   if (ST->genExecuteOnly()) {
6767     // If we can represent the constant as an immediate, don't lower it
6768     if (isFPImmLegal(FPVal, VT))
6769       return Op;
6770     // Otherwise, construct as integer, and move to float register
6771     APInt INTVal = FPVal.bitcastToAPInt();
6772     SDLoc DL(CFP);
6773     switch (VT.getSimpleVT().SimpleTy) {
6774       default:
6775         llvm_unreachable("Unknown floating point type!");
6776         break;
6777       case MVT::f64: {
6778         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6779         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6780         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6781       }
6782       case MVT::f32:
6783           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6784               DAG.getConstant(INTVal, DL, MVT::i32));
6785     }
6786   }
6787 
6788   if (!ST->hasVFP3Base())
6789     return SDValue();
6790 
6791   // Use the default (constant pool) lowering for double constants when we have
6792   // an SP-only FPU
6793   if (IsDouble && !Subtarget->hasFP64())
6794     return SDValue();
6795 
6796   // Try splatting with a VMOV.f32...
6797   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6798 
6799   if (ImmVal != -1) {
6800     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6801       // We have code in place to select a valid ConstantFP already, no need to
6802       // do any mangling.
6803       return Op;
6804     }
6805 
6806     // It's a float and we are trying to use NEON operations where
6807     // possible. Lower it to a splat followed by an extract.
6808     SDLoc DL(Op);
6809     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6810     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6811                                       NewVal);
6812     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6813                        DAG.getConstant(0, DL, MVT::i32));
6814   }
6815 
6816   // The rest of our options are NEON only, make sure that's allowed before
6817   // proceeding..
6818   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6819     return SDValue();
6820 
6821   EVT VMovVT;
6822   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6823 
6824   // It wouldn't really be worth bothering for doubles except for one very
6825   // important value, which does happen to match: 0.0. So make sure we don't do
6826   // anything stupid.
6827   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6828     return SDValue();
6829 
6830   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6831   SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6832                                      VMovVT, VT, VMOVModImm);
6833   if (NewVal != SDValue()) {
6834     SDLoc DL(Op);
6835     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6836                                       NewVal);
6837     if (IsDouble)
6838       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6839 
6840     // It's a float: cast and extract a vector element.
6841     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6842                                        VecConstant);
6843     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6844                        DAG.getConstant(0, DL, MVT::i32));
6845   }
6846 
6847   // Finally, try a VMVN.i32
6848   NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6849                              VT, VMVNModImm);
6850   if (NewVal != SDValue()) {
6851     SDLoc DL(Op);
6852     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6853 
6854     if (IsDouble)
6855       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6856 
6857     // It's a float: cast and extract a vector element.
6858     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6859                                        VecConstant);
6860     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6861                        DAG.getConstant(0, DL, MVT::i32));
6862   }
6863 
6864   return SDValue();
6865 }
6866 
6867 // check if an VEXT instruction can handle the shuffle mask when the
6868 // vector sources of the shuffle are the same.
6869 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6870   unsigned NumElts = VT.getVectorNumElements();
6871 
6872   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6873   if (M[0] < 0)
6874     return false;
6875 
6876   Imm = M[0];
6877 
6878   // If this is a VEXT shuffle, the immediate value is the index of the first
6879   // element.  The other shuffle indices must be the successive elements after
6880   // the first one.
6881   unsigned ExpectedElt = Imm;
6882   for (unsigned i = 1; i < NumElts; ++i) {
6883     // Increment the expected index.  If it wraps around, just follow it
6884     // back to index zero and keep going.
6885     ++ExpectedElt;
6886     if (ExpectedElt == NumElts)
6887       ExpectedElt = 0;
6888 
6889     if (M[i] < 0) continue; // ignore UNDEF indices
6890     if (ExpectedElt != static_cast<unsigned>(M[i]))
6891       return false;
6892   }
6893 
6894   return true;
6895 }
6896 
6897 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6898                        bool &ReverseVEXT, unsigned &Imm) {
6899   unsigned NumElts = VT.getVectorNumElements();
6900   ReverseVEXT = false;
6901 
6902   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6903   if (M[0] < 0)
6904     return false;
6905 
6906   Imm = M[0];
6907 
6908   // If this is a VEXT shuffle, the immediate value is the index of the first
6909   // element.  The other shuffle indices must be the successive elements after
6910   // the first one.
6911   unsigned ExpectedElt = Imm;
6912   for (unsigned i = 1; i < NumElts; ++i) {
6913     // Increment the expected index.  If it wraps around, it may still be
6914     // a VEXT but the source vectors must be swapped.
6915     ExpectedElt += 1;
6916     if (ExpectedElt == NumElts * 2) {
6917       ExpectedElt = 0;
6918       ReverseVEXT = true;
6919     }
6920 
6921     if (M[i] < 0) continue; // ignore UNDEF indices
6922     if (ExpectedElt != static_cast<unsigned>(M[i]))
6923       return false;
6924   }
6925 
6926   // Adjust the index value if the source operands will be swapped.
6927   if (ReverseVEXT)
6928     Imm -= NumElts;
6929 
6930   return true;
6931 }
6932 
6933 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6934 /// instruction with the specified blocksize.  (The order of the elements
6935 /// within each block of the vector is reversed.)
6936 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6937   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6938          "Only possible block sizes for VREV are: 16, 32, 64");
6939 
6940   unsigned EltSz = VT.getScalarSizeInBits();
6941   if (EltSz == 64)
6942     return false;
6943 
6944   unsigned NumElts = VT.getVectorNumElements();
6945   unsigned BlockElts = M[0] + 1;
6946   // If the first shuffle index is UNDEF, be optimistic.
6947   if (M[0] < 0)
6948     BlockElts = BlockSize / EltSz;
6949 
6950   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6951     return false;
6952 
6953   for (unsigned i = 0; i < NumElts; ++i) {
6954     if (M[i] < 0) continue; // ignore UNDEF indices
6955     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6956       return false;
6957   }
6958 
6959   return true;
6960 }
6961 
6962 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6963   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6964   // range, then 0 is placed into the resulting vector. So pretty much any mask
6965   // of 8 elements can work here.
6966   return VT == MVT::v8i8 && M.size() == 8;
6967 }
6968 
6969 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6970                                unsigned Index) {
6971   if (Mask.size() == Elements * 2)
6972     return Index / Elements;
6973   return Mask[Index] == 0 ? 0 : 1;
6974 }
6975 
6976 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6977 // checking that pairs of elements in the shuffle mask represent the same index
6978 // in each vector, incrementing the expected index by 2 at each step.
6979 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6980 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6981 //  v2={e,f,g,h}
6982 // WhichResult gives the offset for each element in the mask based on which
6983 // of the two results it belongs to.
6984 //
6985 // The transpose can be represented either as:
6986 // result1 = shufflevector v1, v2, result1_shuffle_mask
6987 // result2 = shufflevector v1, v2, result2_shuffle_mask
6988 // where v1/v2 and the shuffle masks have the same number of elements
6989 // (here WhichResult (see below) indicates which result is being checked)
6990 //
6991 // or as:
6992 // results = shufflevector v1, v2, shuffle_mask
6993 // where both results are returned in one vector and the shuffle mask has twice
6994 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6995 // want to check the low half and high half of the shuffle mask as if it were
6996 // the other case
6997 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6998   unsigned EltSz = VT.getScalarSizeInBits();
6999   if (EltSz == 64)
7000     return false;
7001 
7002   unsigned NumElts = VT.getVectorNumElements();
7003   if (M.size() != NumElts && M.size() != NumElts*2)
7004     return false;
7005 
7006   // If the mask is twice as long as the input vector then we need to check the
7007   // upper and lower parts of the mask with a matching value for WhichResult
7008   // FIXME: A mask with only even values will be rejected in case the first
7009   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
7010   // M[0] is used to determine WhichResult
7011   for (unsigned i = 0; i < M.size(); i += NumElts) {
7012     WhichResult = SelectPairHalf(NumElts, M, i);
7013     for (unsigned j = 0; j < NumElts; j += 2) {
7014       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7015           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
7016         return false;
7017     }
7018   }
7019 
7020   if (M.size() == NumElts*2)
7021     WhichResult = 0;
7022 
7023   return true;
7024 }
7025 
7026 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
7027 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7028 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
7029 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7030   unsigned EltSz = VT.getScalarSizeInBits();
7031   if (EltSz == 64)
7032     return false;
7033 
7034   unsigned NumElts = VT.getVectorNumElements();
7035   if (M.size() != NumElts && M.size() != NumElts*2)
7036     return false;
7037 
7038   for (unsigned i = 0; i < M.size(); i += NumElts) {
7039     WhichResult = SelectPairHalf(NumElts, M, i);
7040     for (unsigned j = 0; j < NumElts; j += 2) {
7041       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
7042           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
7043         return false;
7044     }
7045   }
7046 
7047   if (M.size() == NumElts*2)
7048     WhichResult = 0;
7049 
7050   return true;
7051 }
7052 
7053 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
7054 // that the mask elements are either all even and in steps of size 2 or all odd
7055 // and in steps of size 2.
7056 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
7057 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
7058 //  v2={e,f,g,h}
7059 // Requires similar checks to that of isVTRNMask with
7060 // respect the how results are returned.
7061 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7062   unsigned EltSz = VT.getScalarSizeInBits();
7063   if (EltSz == 64)
7064     return false;
7065 
7066   unsigned NumElts = VT.getVectorNumElements();
7067   if (M.size() != NumElts && M.size() != NumElts*2)
7068     return false;
7069 
7070   for (unsigned i = 0; i < M.size(); i += NumElts) {
7071     WhichResult = SelectPairHalf(NumElts, M, i);
7072     for (unsigned j = 0; j < NumElts; ++j) {
7073       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
7074         return false;
7075     }
7076   }
7077 
7078   if (M.size() == NumElts*2)
7079     WhichResult = 0;
7080 
7081   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7082   if (VT.is64BitVector() && EltSz == 32)
7083     return false;
7084 
7085   return true;
7086 }
7087 
7088 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
7089 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7090 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
7091 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7092   unsigned EltSz = VT.getScalarSizeInBits();
7093   if (EltSz == 64)
7094     return false;
7095 
7096   unsigned NumElts = VT.getVectorNumElements();
7097   if (M.size() != NumElts && M.size() != NumElts*2)
7098     return false;
7099 
7100   unsigned Half = NumElts / 2;
7101   for (unsigned i = 0; i < M.size(); i += NumElts) {
7102     WhichResult = SelectPairHalf(NumElts, M, i);
7103     for (unsigned j = 0; j < NumElts; j += Half) {
7104       unsigned Idx = WhichResult;
7105       for (unsigned k = 0; k < Half; ++k) {
7106         int MIdx = M[i + j + k];
7107         if (MIdx >= 0 && (unsigned) MIdx != Idx)
7108           return false;
7109         Idx += 2;
7110       }
7111     }
7112   }
7113 
7114   if (M.size() == NumElts*2)
7115     WhichResult = 0;
7116 
7117   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7118   if (VT.is64BitVector() && EltSz == 32)
7119     return false;
7120 
7121   return true;
7122 }
7123 
7124 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
7125 // that pairs of elements of the shufflemask represent the same index in each
7126 // vector incrementing sequentially through the vectors.
7127 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
7128 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
7129 //  v2={e,f,g,h}
7130 // Requires similar checks to that of isVTRNMask with respect the how results
7131 // are returned.
7132 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
7133   unsigned EltSz = VT.getScalarSizeInBits();
7134   if (EltSz == 64)
7135     return false;
7136 
7137   unsigned NumElts = VT.getVectorNumElements();
7138   if (M.size() != NumElts && M.size() != NumElts*2)
7139     return false;
7140 
7141   for (unsigned i = 0; i < M.size(); i += NumElts) {
7142     WhichResult = SelectPairHalf(NumElts, M, i);
7143     unsigned Idx = WhichResult * NumElts / 2;
7144     for (unsigned j = 0; j < NumElts; j += 2) {
7145       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7146           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
7147         return false;
7148       Idx += 1;
7149     }
7150   }
7151 
7152   if (M.size() == NumElts*2)
7153     WhichResult = 0;
7154 
7155   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7156   if (VT.is64BitVector() && EltSz == 32)
7157     return false;
7158 
7159   return true;
7160 }
7161 
7162 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
7163 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
7164 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
7165 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
7166   unsigned EltSz = VT.getScalarSizeInBits();
7167   if (EltSz == 64)
7168     return false;
7169 
7170   unsigned NumElts = VT.getVectorNumElements();
7171   if (M.size() != NumElts && M.size() != NumElts*2)
7172     return false;
7173 
7174   for (unsigned i = 0; i < M.size(); i += NumElts) {
7175     WhichResult = SelectPairHalf(NumElts, M, i);
7176     unsigned Idx = WhichResult * NumElts / 2;
7177     for (unsigned j = 0; j < NumElts; j += 2) {
7178       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
7179           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
7180         return false;
7181       Idx += 1;
7182     }
7183   }
7184 
7185   if (M.size() == NumElts*2)
7186     WhichResult = 0;
7187 
7188   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
7189   if (VT.is64BitVector() && EltSz == 32)
7190     return false;
7191 
7192   return true;
7193 }
7194 
7195 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
7196 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
7197 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
7198                                            unsigned &WhichResult,
7199                                            bool &isV_UNDEF) {
7200   isV_UNDEF = false;
7201   if (isVTRNMask(ShuffleMask, VT, WhichResult))
7202     return ARMISD::VTRN;
7203   if (isVUZPMask(ShuffleMask, VT, WhichResult))
7204     return ARMISD::VUZP;
7205   if (isVZIPMask(ShuffleMask, VT, WhichResult))
7206     return ARMISD::VZIP;
7207 
7208   isV_UNDEF = true;
7209   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7210     return ARMISD::VTRN;
7211   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7212     return ARMISD::VUZP;
7213   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7214     return ARMISD::VZIP;
7215 
7216   return 0;
7217 }
7218 
7219 /// \return true if this is a reverse operation on an vector.
7220 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7221   unsigned NumElts = VT.getVectorNumElements();
7222   // Make sure the mask has the right size.
7223   if (NumElts != M.size())
7224       return false;
7225 
7226   // Look for <15, ..., 3, -1, 1, 0>.
7227   for (unsigned i = 0; i != NumElts; ++i)
7228     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7229       return false;
7230 
7231   return true;
7232 }
7233 
7234 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) {
7235   unsigned NumElts = VT.getVectorNumElements();
7236   // Make sure the mask has the right size.
7237   if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7238       return false;
7239 
7240   // If Top
7241   //   Look for <0, N, 2, N+2, 4, N+4, ..>.
7242   //   This inserts Input2 into Input1
7243   // else if not Top
7244   //   Look for <0, N+1, 2, N+3, 4, N+5, ..>
7245   //   This inserts Input1 into Input2
7246   unsigned Offset = Top ? 0 : 1;
7247   for (unsigned i = 0; i < NumElts; i+=2) {
7248     if (M[i] >= 0 && M[i] != (int)i)
7249       return false;
7250     if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset))
7251       return false;
7252   }
7253 
7254   return true;
7255 }
7256 
7257 // Reconstruct an MVE VCVT from a BuildVector of scalar fptrunc, all extracted
7258 // from a pair of inputs. For example:
7259 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7260 //             FP_ROUND(EXTRACT_ELT(Y, 0),
7261 //             FP_ROUND(EXTRACT_ELT(X, 1),
7262 //             FP_ROUND(EXTRACT_ELT(Y, 1), ...)
7263 static SDValue LowerBuildVectorOfFPTrunc(SDValue BV, SelectionDAG &DAG,
7264                                          const ARMSubtarget *ST) {
7265   assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7266   if (!ST->hasMVEFloatOps())
7267     return SDValue();
7268 
7269   SDLoc dl(BV);
7270   EVT VT = BV.getValueType();
7271   if (VT != MVT::v8f16)
7272     return SDValue();
7273 
7274   // We are looking for a buildvector of fptrunc elements, where all the
7275   // elements are interleavingly extracted from two sources. Check the first two
7276   // items are valid enough and extract some info from them (they are checked
7277   // properly in the loop below).
7278   if (BV.getOperand(0).getOpcode() != ISD::FP_ROUND ||
7279       BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7280       BV.getOperand(0).getOperand(0).getConstantOperandVal(1) != 0)
7281     return SDValue();
7282   if (BV.getOperand(1).getOpcode() != ISD::FP_ROUND ||
7283       BV.getOperand(1).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
7284       BV.getOperand(1).getOperand(0).getConstantOperandVal(1) != 0)
7285     return SDValue();
7286   SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7287   SDValue Op1 = BV.getOperand(1).getOperand(0).getOperand(0);
7288   if (Op0.getValueType() != MVT::v4f32 || Op1.getValueType() != MVT::v4f32)
7289     return SDValue();
7290 
7291   // Check all the values in the BuildVector line up with our expectations.
7292   for (unsigned i = 1; i < 4; i++) {
7293     auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7294       return Trunc.getOpcode() == ISD::FP_ROUND &&
7295              Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7296              Trunc.getOperand(0).getOperand(0) == Op &&
7297              Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7298     };
7299     if (!Check(BV.getOperand(i * 2 + 0), Op0, i))
7300       return SDValue();
7301     if (!Check(BV.getOperand(i * 2 + 1), Op1, i))
7302       return SDValue();
7303   }
7304 
7305   SDValue N1 = DAG.getNode(ARMISD::VCVTN, dl, VT, DAG.getUNDEF(VT), Op0,
7306                            DAG.getConstant(0, dl, MVT::i32));
7307   return DAG.getNode(ARMISD::VCVTN, dl, VT, N1, Op1,
7308                      DAG.getConstant(1, dl, MVT::i32));
7309 }
7310 
7311 // Reconstruct an MVE VCVT from a BuildVector of scalar fpext, all extracted
7312 // from a single input on alternating lanes. For example:
7313 // BUILDVECTOR(FP_ROUND(EXTRACT_ELT(X, 0),
7314 //             FP_ROUND(EXTRACT_ELT(X, 2),
7315 //             FP_ROUND(EXTRACT_ELT(X, 4), ...)
7316 static SDValue LowerBuildVectorOfFPExt(SDValue BV, SelectionDAG &DAG,
7317                                        const ARMSubtarget *ST) {
7318   assert(BV.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7319   if (!ST->hasMVEFloatOps())
7320     return SDValue();
7321 
7322   SDLoc dl(BV);
7323   EVT VT = BV.getValueType();
7324   if (VT != MVT::v4f32)
7325     return SDValue();
7326 
7327   // We are looking for a buildvector of fptext elements, where all the
7328   // elements are alternating lanes from a single source. For example <0,2,4,6>
7329   // or <1,3,5,7>. Check the first two items are valid enough and extract some
7330   // info from them (they are checked properly in the loop below).
7331   if (BV.getOperand(0).getOpcode() != ISD::FP_EXTEND ||
7332       BV.getOperand(0).getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT)
7333     return SDValue();
7334   SDValue Op0 = BV.getOperand(0).getOperand(0).getOperand(0);
7335   int Offset = BV.getOperand(0).getOperand(0).getConstantOperandVal(1);
7336   if (Op0.getValueType() != MVT::v8f16 || (Offset != 0 && Offset != 1))
7337     return SDValue();
7338 
7339   // Check all the values in the BuildVector line up with our expectations.
7340   for (unsigned i = 1; i < 4; i++) {
7341     auto Check = [](SDValue Trunc, SDValue Op, unsigned Idx) {
7342       return Trunc.getOpcode() == ISD::FP_EXTEND &&
7343              Trunc.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7344              Trunc.getOperand(0).getOperand(0) == Op &&
7345              Trunc.getOperand(0).getConstantOperandVal(1) == Idx;
7346     };
7347     if (!Check(BV.getOperand(i), Op0, 2 * i + Offset))
7348       return SDValue();
7349   }
7350 
7351   return DAG.getNode(ARMISD::VCVTL, dl, VT, Op0,
7352                      DAG.getConstant(Offset, dl, MVT::i32));
7353 }
7354 
7355 // If N is an integer constant that can be moved into a register in one
7356 // instruction, return an SDValue of such a constant (will become a MOV
7357 // instruction).  Otherwise return null.
7358 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7359                                      const ARMSubtarget *ST, const SDLoc &dl) {
7360   uint64_t Val;
7361   if (!isa<ConstantSDNode>(N))
7362     return SDValue();
7363   Val = cast<ConstantSDNode>(N)->getZExtValue();
7364 
7365   if (ST->isThumb1Only()) {
7366     if (Val <= 255 || ~Val <= 255)
7367       return DAG.getConstant(Val, dl, MVT::i32);
7368   } else {
7369     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7370       return DAG.getConstant(Val, dl, MVT::i32);
7371   }
7372   return SDValue();
7373 }
7374 
7375 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7376                                     const ARMSubtarget *ST) {
7377   SDLoc dl(Op);
7378   EVT VT = Op.getValueType();
7379 
7380   assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7381 
7382   unsigned NumElts = VT.getVectorNumElements();
7383   unsigned BoolMask;
7384   unsigned BitsPerBool;
7385   if (NumElts == 4) {
7386     BitsPerBool = 4;
7387     BoolMask = 0xf;
7388   } else if (NumElts == 8) {
7389     BitsPerBool = 2;
7390     BoolMask = 0x3;
7391   } else if (NumElts == 16) {
7392     BitsPerBool = 1;
7393     BoolMask = 0x1;
7394   } else
7395     return SDValue();
7396 
7397   // If this is a single value copied into all lanes (a splat), we can just sign
7398   // extend that single value
7399   SDValue FirstOp = Op.getOperand(0);
7400   if (!isa<ConstantSDNode>(FirstOp) &&
7401       std::all_of(std::next(Op->op_begin()), Op->op_end(),
7402                   [&FirstOp](SDUse &U) {
7403                     return U.get().isUndef() || U.get() == FirstOp;
7404                   })) {
7405     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7406                               DAG.getValueType(MVT::i1));
7407     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7408   }
7409 
7410   // First create base with bits set where known
7411   unsigned Bits32 = 0;
7412   for (unsigned i = 0; i < NumElts; ++i) {
7413     SDValue V = Op.getOperand(i);
7414     if (!isa<ConstantSDNode>(V) && !V.isUndef())
7415       continue;
7416     bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7417     if (BitSet)
7418       Bits32 |= BoolMask << (i * BitsPerBool);
7419   }
7420 
7421   // Add in unknown nodes
7422   SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7423                              DAG.getConstant(Bits32, dl, MVT::i32));
7424   for (unsigned i = 0; i < NumElts; ++i) {
7425     SDValue V = Op.getOperand(i);
7426     if (isa<ConstantSDNode>(V) || V.isUndef())
7427       continue;
7428     Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7429                        DAG.getConstant(i, dl, MVT::i32));
7430   }
7431 
7432   return Base;
7433 }
7434 
7435 // If this is a case we can't handle, return null and let the default
7436 // expansion code take care of it.
7437 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7438                                              const ARMSubtarget *ST) const {
7439   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7440   SDLoc dl(Op);
7441   EVT VT = Op.getValueType();
7442 
7443   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7444     return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7445 
7446   APInt SplatBits, SplatUndef;
7447   unsigned SplatBitSize;
7448   bool HasAnyUndefs;
7449   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7450     if (SplatUndef.isAllOnesValue())
7451       return DAG.getUNDEF(VT);
7452 
7453     if ((ST->hasNEON() && SplatBitSize <= 64) ||
7454         (ST->hasMVEIntegerOps() && SplatBitSize <= 64)) {
7455       // Check if an immediate VMOV works.
7456       EVT VmovVT;
7457       SDValue Val =
7458           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
7459                             SplatBitSize, DAG, dl, VmovVT, VT, VMOVModImm);
7460 
7461       if (Val.getNode()) {
7462         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7463         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7464       }
7465 
7466       // Try an immediate VMVN.
7467       uint64_t NegatedImm = (~SplatBits).getZExtValue();
7468       Val = isVMOVModifiedImm(
7469           NegatedImm, SplatUndef.getZExtValue(), SplatBitSize, DAG, dl, VmovVT,
7470           VT, ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7471       if (Val.getNode()) {
7472         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7473         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7474       }
7475 
7476       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7477       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7478         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7479         if (ImmVal != -1) {
7480           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7481           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7482         }
7483       }
7484     }
7485   }
7486 
7487   // Scan through the operands to see if only one value is used.
7488   //
7489   // As an optimisation, even if more than one value is used it may be more
7490   // profitable to splat with one value then change some lanes.
7491   //
7492   // Heuristically we decide to do this if the vector has a "dominant" value,
7493   // defined as splatted to more than half of the lanes.
7494   unsigned NumElts = VT.getVectorNumElements();
7495   bool isOnlyLowElement = true;
7496   bool usesOnlyOneValue = true;
7497   bool hasDominantValue = false;
7498   bool isConstant = true;
7499 
7500   // Map of the number of times a particular SDValue appears in the
7501   // element list.
7502   DenseMap<SDValue, unsigned> ValueCounts;
7503   SDValue Value;
7504   for (unsigned i = 0; i < NumElts; ++i) {
7505     SDValue V = Op.getOperand(i);
7506     if (V.isUndef())
7507       continue;
7508     if (i > 0)
7509       isOnlyLowElement = false;
7510     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7511       isConstant = false;
7512 
7513     ValueCounts.insert(std::make_pair(V, 0));
7514     unsigned &Count = ValueCounts[V];
7515 
7516     // Is this value dominant? (takes up more than half of the lanes)
7517     if (++Count > (NumElts / 2)) {
7518       hasDominantValue = true;
7519       Value = V;
7520     }
7521   }
7522   if (ValueCounts.size() != 1)
7523     usesOnlyOneValue = false;
7524   if (!Value.getNode() && !ValueCounts.empty())
7525     Value = ValueCounts.begin()->first;
7526 
7527   if (ValueCounts.empty())
7528     return DAG.getUNDEF(VT);
7529 
7530   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7531   // Keep going if we are hitting this case.
7532   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7533     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7534 
7535   unsigned EltSize = VT.getScalarSizeInBits();
7536 
7537   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
7538   // i32 and try again.
7539   if (hasDominantValue && EltSize <= 32) {
7540     if (!isConstant) {
7541       SDValue N;
7542 
7543       // If we are VDUPing a value that comes directly from a vector, that will
7544       // cause an unnecessary move to and from a GPR, where instead we could
7545       // just use VDUPLANE. We can only do this if the lane being extracted
7546       // is at a constant index, as the VDUP from lane instructions only have
7547       // constant-index forms.
7548       ConstantSDNode *constIndex;
7549       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7550           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7551         // We need to create a new undef vector to use for the VDUPLANE if the
7552         // size of the vector from which we get the value is different than the
7553         // size of the vector that we need to create. We will insert the element
7554         // such that the register coalescer will remove unnecessary copies.
7555         if (VT != Value->getOperand(0).getValueType()) {
7556           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7557                              VT.getVectorNumElements();
7558           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7559                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7560                         Value, DAG.getConstant(index, dl, MVT::i32)),
7561                            DAG.getConstant(index, dl, MVT::i32));
7562         } else
7563           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7564                         Value->getOperand(0), Value->getOperand(1));
7565       } else
7566         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7567 
7568       if (!usesOnlyOneValue) {
7569         // The dominant value was splatted as 'N', but we now have to insert
7570         // all differing elements.
7571         for (unsigned I = 0; I < NumElts; ++I) {
7572           if (Op.getOperand(I) == Value)
7573             continue;
7574           SmallVector<SDValue, 3> Ops;
7575           Ops.push_back(N);
7576           Ops.push_back(Op.getOperand(I));
7577           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7578           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7579         }
7580       }
7581       return N;
7582     }
7583     if (VT.getVectorElementType().isFloatingPoint()) {
7584       SmallVector<SDValue, 8> Ops;
7585       MVT FVT = VT.getVectorElementType().getSimpleVT();
7586       assert(FVT == MVT::f32 || FVT == MVT::f16);
7587       MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7588       for (unsigned i = 0; i < NumElts; ++i)
7589         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7590                                   Op.getOperand(i)));
7591       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7592       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7593       Val = LowerBUILD_VECTOR(Val, DAG, ST);
7594       if (Val.getNode())
7595         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7596     }
7597     if (usesOnlyOneValue) {
7598       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7599       if (isConstant && Val.getNode())
7600         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7601     }
7602   }
7603 
7604   // If all elements are constants and the case above didn't get hit, fall back
7605   // to the default expansion, which will generate a load from the constant
7606   // pool.
7607   if (isConstant)
7608     return SDValue();
7609 
7610   // Reconstruct the BUILDVECTOR to one of the legal shuffles (such as vext and
7611   // vmovn). Empirical tests suggest this is rarely worth it for vectors of
7612   // length <= 2.
7613   if (NumElts >= 4)
7614     if (SDValue shuffle = ReconstructShuffle(Op, DAG))
7615       return shuffle;
7616 
7617   // Attempt to turn a buildvector of scalar fptrunc's or fpext's back into
7618   // VCVT's
7619   if (SDValue VCVT = LowerBuildVectorOfFPTrunc(Op, DAG, Subtarget))
7620     return VCVT;
7621   if (SDValue VCVT = LowerBuildVectorOfFPExt(Op, DAG, Subtarget))
7622     return VCVT;
7623 
7624   if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7625     // If we haven't found an efficient lowering, try splitting a 128-bit vector
7626     // into two 64-bit vectors; we might discover a better way to lower it.
7627     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7628     EVT ExtVT = VT.getVectorElementType();
7629     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7630     SDValue Lower =
7631         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7632     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7633       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7634     SDValue Upper = DAG.getBuildVector(
7635         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7636     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7637       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7638     if (Lower && Upper)
7639       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7640   }
7641 
7642   // Vectors with 32- or 64-bit elements can be built by directly assigning
7643   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
7644   // will be legalized.
7645   if (EltSize >= 32) {
7646     // Do the expansion with floating-point types, since that is what the VFP
7647     // registers are defined to use, and since i64 is not legal.
7648     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7649     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7650     SmallVector<SDValue, 8> Ops;
7651     for (unsigned i = 0; i < NumElts; ++i)
7652       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7653     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7654     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7655   }
7656 
7657   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7658   // know the default expansion would otherwise fall back on something even
7659   // worse. For a vector with one or two non-undef values, that's
7660   // scalar_to_vector for the elements followed by a shuffle (provided the
7661   // shuffle is valid for the target) and materialization element by element
7662   // on the stack followed by a load for everything else.
7663   if (!isConstant && !usesOnlyOneValue) {
7664     SDValue Vec = DAG.getUNDEF(VT);
7665     for (unsigned i = 0 ; i < NumElts; ++i) {
7666       SDValue V = Op.getOperand(i);
7667       if (V.isUndef())
7668         continue;
7669       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7670       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7671     }
7672     return Vec;
7673   }
7674 
7675   return SDValue();
7676 }
7677 
7678 // Gather data to see if the operation can be modelled as a
7679 // shuffle in combination with VEXTs.
7680 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7681                                               SelectionDAG &DAG) const {
7682   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7683   SDLoc dl(Op);
7684   EVT VT = Op.getValueType();
7685   unsigned NumElts = VT.getVectorNumElements();
7686 
7687   struct ShuffleSourceInfo {
7688     SDValue Vec;
7689     unsigned MinElt = std::numeric_limits<unsigned>::max();
7690     unsigned MaxElt = 0;
7691 
7692     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7693     // be compatible with the shuffle we intend to construct. As a result
7694     // ShuffleVec will be some sliding window into the original Vec.
7695     SDValue ShuffleVec;
7696 
7697     // Code should guarantee that element i in Vec starts at element "WindowBase
7698     // + i * WindowScale in ShuffleVec".
7699     int WindowBase = 0;
7700     int WindowScale = 1;
7701 
7702     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7703 
7704     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7705   };
7706 
7707   // First gather all vectors used as an immediate source for this BUILD_VECTOR
7708   // node.
7709   SmallVector<ShuffleSourceInfo, 2> Sources;
7710   for (unsigned i = 0; i < NumElts; ++i) {
7711     SDValue V = Op.getOperand(i);
7712     if (V.isUndef())
7713       continue;
7714     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7715       // A shuffle can only come from building a vector from various
7716       // elements of other vectors.
7717       return SDValue();
7718     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7719       // Furthermore, shuffles require a constant mask, whereas extractelts
7720       // accept variable indices.
7721       return SDValue();
7722     }
7723 
7724     // Add this element source to the list if it's not already there.
7725     SDValue SourceVec = V.getOperand(0);
7726     auto Source = llvm::find(Sources, SourceVec);
7727     if (Source == Sources.end())
7728       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7729 
7730     // Update the minimum and maximum lane number seen.
7731     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7732     Source->MinElt = std::min(Source->MinElt, EltNo);
7733     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7734   }
7735 
7736   // Currently only do something sane when at most two source vectors
7737   // are involved.
7738   if (Sources.size() > 2)
7739     return SDValue();
7740 
7741   // Find out the smallest element size among result and two sources, and use
7742   // it as element size to build the shuffle_vector.
7743   EVT SmallestEltTy = VT.getVectorElementType();
7744   for (auto &Source : Sources) {
7745     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7746     if (SrcEltTy.bitsLT(SmallestEltTy))
7747       SmallestEltTy = SrcEltTy;
7748   }
7749   unsigned ResMultiplier =
7750       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7751   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7752   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7753 
7754   // If the source vector is too wide or too narrow, we may nevertheless be able
7755   // to construct a compatible shuffle either by concatenating it with UNDEF or
7756   // extracting a suitable range of elements.
7757   for (auto &Src : Sources) {
7758     EVT SrcVT = Src.ShuffleVec.getValueType();
7759 
7760     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7761       continue;
7762 
7763     // This stage of the search produces a source with the same element type as
7764     // the original, but with a total width matching the BUILD_VECTOR output.
7765     EVT EltVT = SrcVT.getVectorElementType();
7766     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7767     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7768 
7769     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7770       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7771         return SDValue();
7772       // We can pad out the smaller vector for free, so if it's part of a
7773       // shuffle...
7774       Src.ShuffleVec =
7775           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7776                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7777       continue;
7778     }
7779 
7780     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7781       return SDValue();
7782 
7783     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7784       // Span too large for a VEXT to cope
7785       return SDValue();
7786     }
7787 
7788     if (Src.MinElt >= NumSrcElts) {
7789       // The extraction can just take the second half
7790       Src.ShuffleVec =
7791           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7792                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7793       Src.WindowBase = -NumSrcElts;
7794     } else if (Src.MaxElt < NumSrcElts) {
7795       // The extraction can just take the first half
7796       Src.ShuffleVec =
7797           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7798                       DAG.getConstant(0, dl, MVT::i32));
7799     } else {
7800       // An actual VEXT is needed
7801       SDValue VEXTSrc1 =
7802           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7803                       DAG.getConstant(0, dl, MVT::i32));
7804       SDValue VEXTSrc2 =
7805           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7806                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7807 
7808       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7809                                    VEXTSrc2,
7810                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
7811       Src.WindowBase = -Src.MinElt;
7812     }
7813   }
7814 
7815   // Another possible incompatibility occurs from the vector element types. We
7816   // can fix this by bitcasting the source vectors to the same type we intend
7817   // for the shuffle.
7818   for (auto &Src : Sources) {
7819     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7820     if (SrcEltTy == SmallestEltTy)
7821       continue;
7822     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7823     Src.ShuffleVec = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, ShuffleVT, Src.ShuffleVec);
7824     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7825     Src.WindowBase *= Src.WindowScale;
7826   }
7827 
7828   // Final sanity check before we try to actually produce a shuffle.
7829   LLVM_DEBUG(for (auto Src
7830                   : Sources)
7831                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7832 
7833   // The stars all align, our next step is to produce the mask for the shuffle.
7834   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7835   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7836   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7837     SDValue Entry = Op.getOperand(i);
7838     if (Entry.isUndef())
7839       continue;
7840 
7841     auto Src = llvm::find(Sources, Entry.getOperand(0));
7842     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7843 
7844     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7845     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7846     // segment.
7847     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7848     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7849                                VT.getScalarSizeInBits());
7850     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7851 
7852     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7853     // starting at the appropriate offset.
7854     int *LaneMask = &Mask[i * ResMultiplier];
7855 
7856     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7857     ExtractBase += NumElts * (Src - Sources.begin());
7858     for (int j = 0; j < LanesDefined; ++j)
7859       LaneMask[j] = ExtractBase + j;
7860   }
7861 
7862 
7863   // We can't handle more than two sources. This should have already
7864   // been checked before this point.
7865   assert(Sources.size() <= 2 && "Too many sources!");
7866 
7867   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7868   for (unsigned i = 0; i < Sources.size(); ++i)
7869     ShuffleOps[i] = Sources[i].ShuffleVec;
7870 
7871   SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7872                                             ShuffleOps[1], Mask, DAG);
7873   if (!Shuffle)
7874     return SDValue();
7875   return DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Shuffle);
7876 }
7877 
7878 enum ShuffleOpCodes {
7879   OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7880   OP_VREV,
7881   OP_VDUP0,
7882   OP_VDUP1,
7883   OP_VDUP2,
7884   OP_VDUP3,
7885   OP_VEXT1,
7886   OP_VEXT2,
7887   OP_VEXT3,
7888   OP_VUZPL, // VUZP, left result
7889   OP_VUZPR, // VUZP, right result
7890   OP_VZIPL, // VZIP, left result
7891   OP_VZIPR, // VZIP, right result
7892   OP_VTRNL, // VTRN, left result
7893   OP_VTRNR  // VTRN, right result
7894 };
7895 
7896 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7897   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7898   switch (OpNum) {
7899   case OP_COPY:
7900   case OP_VREV:
7901   case OP_VDUP0:
7902   case OP_VDUP1:
7903   case OP_VDUP2:
7904   case OP_VDUP3:
7905     return true;
7906   }
7907   return false;
7908 }
7909 
7910 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7911 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7912 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7913 /// are assumed to be legal.
7914 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7915   if (VT.getVectorNumElements() == 4 &&
7916       (VT.is128BitVector() || VT.is64BitVector())) {
7917     unsigned PFIndexes[4];
7918     for (unsigned i = 0; i != 4; ++i) {
7919       if (M[i] < 0)
7920         PFIndexes[i] = 8;
7921       else
7922         PFIndexes[i] = M[i];
7923     }
7924 
7925     // Compute the index in the perfect shuffle table.
7926     unsigned PFTableIndex =
7927       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7928     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7929     unsigned Cost = (PFEntry >> 30);
7930 
7931     if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7932       return true;
7933   }
7934 
7935   bool ReverseVEXT, isV_UNDEF;
7936   unsigned Imm, WhichResult;
7937 
7938   unsigned EltSize = VT.getScalarSizeInBits();
7939   if (EltSize >= 32 ||
7940       ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7941       ShuffleVectorInst::isIdentityMask(M) ||
7942       isVREVMask(M, VT, 64) ||
7943       isVREVMask(M, VT, 32) ||
7944       isVREVMask(M, VT, 16))
7945     return true;
7946   else if (Subtarget->hasNEON() &&
7947            (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7948             isVTBLMask(M, VT) ||
7949             isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7950     return true;
7951   else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7952            isReverseMask(M, VT))
7953     return true;
7954   else if (Subtarget->hasMVEIntegerOps() &&
7955            (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1)))
7956     return true;
7957   else
7958     return false;
7959 }
7960 
7961 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7962 /// the specified operations to build the shuffle.
7963 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7964                                       SDValue RHS, SelectionDAG &DAG,
7965                                       const SDLoc &dl) {
7966   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7967   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7968   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7969 
7970   if (OpNum == OP_COPY) {
7971     if (LHSID == (1*9+2)*9+3) return LHS;
7972     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7973     return RHS;
7974   }
7975 
7976   SDValue OpLHS, OpRHS;
7977   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7978   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7979   EVT VT = OpLHS.getValueType();
7980 
7981   switch (OpNum) {
7982   default: llvm_unreachable("Unknown shuffle opcode!");
7983   case OP_VREV:
7984     // VREV divides the vector in half and swaps within the half.
7985     if (VT.getVectorElementType() == MVT::i32 ||
7986         VT.getVectorElementType() == MVT::f32)
7987       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7988     // vrev <4 x i16> -> VREV32
7989     if (VT.getVectorElementType() == MVT::i16)
7990       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7991     // vrev <4 x i8> -> VREV16
7992     assert(VT.getVectorElementType() == MVT::i8);
7993     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7994   case OP_VDUP0:
7995   case OP_VDUP1:
7996   case OP_VDUP2:
7997   case OP_VDUP3:
7998     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7999                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
8000   case OP_VEXT1:
8001   case OP_VEXT2:
8002   case OP_VEXT3:
8003     return DAG.getNode(ARMISD::VEXT, dl, VT,
8004                        OpLHS, OpRHS,
8005                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
8006   case OP_VUZPL:
8007   case OP_VUZPR:
8008     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
8009                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
8010   case OP_VZIPL:
8011   case OP_VZIPR:
8012     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
8013                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
8014   case OP_VTRNL:
8015   case OP_VTRNR:
8016     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
8017                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
8018   }
8019 }
8020 
8021 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
8022                                        ArrayRef<int> ShuffleMask,
8023                                        SelectionDAG &DAG) {
8024   // Check to see if we can use the VTBL instruction.
8025   SDValue V1 = Op.getOperand(0);
8026   SDValue V2 = Op.getOperand(1);
8027   SDLoc DL(Op);
8028 
8029   SmallVector<SDValue, 8> VTBLMask;
8030   for (ArrayRef<int>::iterator
8031          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
8032     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
8033 
8034   if (V2.getNode()->isUndef())
8035     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
8036                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8037 
8038   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
8039                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
8040 }
8041 
8042 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
8043                                                       SelectionDAG &DAG) {
8044   SDLoc DL(Op);
8045   SDValue OpLHS = Op.getOperand(0);
8046   EVT VT = OpLHS.getValueType();
8047 
8048   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
8049          "Expect an v8i16/v16i8 type");
8050   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
8051   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
8052   // extract the first 8 bytes into the top double word and the last 8 bytes
8053   // into the bottom double word. The v8i16 case is similar.
8054   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
8055   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
8056                      DAG.getConstant(ExtractNum, DL, MVT::i32));
8057 }
8058 
8059 static EVT getVectorTyFromPredicateVector(EVT VT) {
8060   switch (VT.getSimpleVT().SimpleTy) {
8061   case MVT::v4i1:
8062     return MVT::v4i32;
8063   case MVT::v8i1:
8064     return MVT::v8i16;
8065   case MVT::v16i1:
8066     return MVT::v16i8;
8067   default:
8068     llvm_unreachable("Unexpected vector predicate type");
8069   }
8070 }
8071 
8072 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
8073                                     SelectionDAG &DAG) {
8074   // Converting from boolean predicates to integers involves creating a vector
8075   // of all ones or all zeroes and selecting the lanes based upon the real
8076   // predicate.
8077   SDValue AllOnes =
8078       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
8079   AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
8080 
8081   SDValue AllZeroes =
8082       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
8083   AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
8084 
8085   // Get full vector type from predicate type
8086   EVT NewVT = getVectorTyFromPredicateVector(VT);
8087 
8088   SDValue RecastV1;
8089   // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
8090   // this to a v16i1. This cannot be done with an ordinary bitcast because the
8091   // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
8092   // since we know in hardware the sizes are really the same.
8093   if (VT != MVT::v16i1)
8094     RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
8095   else
8096     RecastV1 = Pred;
8097 
8098   // Select either all ones or zeroes depending upon the real predicate bits.
8099   SDValue PredAsVector =
8100       DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
8101 
8102   // Recast our new predicate-as-integer v16i8 vector into something
8103   // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
8104   return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
8105 }
8106 
8107 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
8108                                       const ARMSubtarget *ST) {
8109   EVT VT = Op.getValueType();
8110   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8111   ArrayRef<int> ShuffleMask = SVN->getMask();
8112 
8113   assert(ST->hasMVEIntegerOps() &&
8114          "No support for vector shuffle of boolean predicates");
8115 
8116   SDValue V1 = Op.getOperand(0);
8117   SDLoc dl(Op);
8118   if (isReverseMask(ShuffleMask, VT)) {
8119     SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
8120     SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
8121     SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
8122                               DAG.getConstant(16, dl, MVT::i32));
8123     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
8124   }
8125 
8126   // Until we can come up with optimised cases for every single vector
8127   // shuffle in existence we have chosen the least painful strategy. This is
8128   // to essentially promote the boolean predicate to a 8-bit integer, where
8129   // each predicate represents a byte. Then we fall back on a normal integer
8130   // vector shuffle and convert the result back into a predicate vector. In
8131   // many cases the generated code might be even better than scalar code
8132   // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
8133   // fields in a register into 8 other arbitrary 2-bit fields!
8134   SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
8135   EVT NewVT = PredAsVector.getValueType();
8136 
8137   // Do the shuffle!
8138   SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
8139                                           DAG.getUNDEF(NewVT), ShuffleMask);
8140 
8141   // Now return the result of comparing the shuffled vector with zero,
8142   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8143   return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
8144                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8145 }
8146 
8147 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
8148                                             ArrayRef<int> ShuffleMask,
8149                                             SelectionDAG &DAG) {
8150   // Attempt to lower the vector shuffle using as many whole register movs as
8151   // possible. This is useful for types smaller than 32bits, which would
8152   // often otherwise become a series for grp movs.
8153   SDLoc dl(Op);
8154   EVT VT = Op.getValueType();
8155   if (VT.getScalarSizeInBits() >= 32)
8156     return SDValue();
8157 
8158   assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
8159          "Unexpected vector type");
8160   int NumElts = VT.getVectorNumElements();
8161   int QuarterSize = NumElts / 4;
8162   // The four final parts of the vector, as i32's
8163   SDValue Parts[4];
8164 
8165   // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
8166   // <u,u,u,u>), returning the vmov lane index
8167   auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
8168     // Detect which mov lane this would be from the first non-undef element.
8169     int MovIdx = -1;
8170     for (int i = 0; i < Length; i++) {
8171       if (ShuffleMask[Start + i] >= 0) {
8172         if (ShuffleMask[Start + i] % Length != i)
8173           return -1;
8174         MovIdx = ShuffleMask[Start + i] / Length;
8175         break;
8176       }
8177     }
8178     // If all items are undef, leave this for other combines
8179     if (MovIdx == -1)
8180       return -1;
8181     // Check the remaining values are the correct part of the same mov
8182     for (int i = 1; i < Length; i++) {
8183       if (ShuffleMask[Start + i] >= 0 &&
8184           (ShuffleMask[Start + i] / Length != MovIdx ||
8185            ShuffleMask[Start + i] % Length != i))
8186         return -1;
8187     }
8188     return MovIdx;
8189   };
8190 
8191   for (int Part = 0; Part < 4; ++Part) {
8192     // Does this part look like a mov
8193     int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
8194     if (Elt != -1) {
8195       SDValue Input = Op->getOperand(0);
8196       if (Elt >= 4) {
8197         Input = Op->getOperand(1);
8198         Elt -= 4;
8199       }
8200       SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input);
8201       Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast,
8202                                 DAG.getConstant(Elt, dl, MVT::i32));
8203     }
8204   }
8205 
8206   // Nothing interesting found, just return
8207   if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
8208     return SDValue();
8209 
8210   // The other parts need to be built with the old shuffle vector, cast to a
8211   // v4i32 and extract_vector_elts
8212   if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
8213     SmallVector<int, 16> NewShuffleMask;
8214     for (int Part = 0; Part < 4; ++Part)
8215       for (int i = 0; i < QuarterSize; i++)
8216         NewShuffleMask.push_back(
8217             Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
8218     SDValue NewShuffle = DAG.getVectorShuffle(
8219         VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
8220     SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle);
8221 
8222     for (int Part = 0; Part < 4; ++Part)
8223       if (!Parts[Part])
8224         Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8225                                   BitCast, DAG.getConstant(Part, dl, MVT::i32));
8226   }
8227   // Build a vector out of the various parts and bitcast it back to the original
8228   // type.
8229   SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts);
8230   return DAG.getBitcast(VT, NewVec);
8231 }
8232 
8233 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
8234                                    const ARMSubtarget *ST) {
8235   SDValue V1 = Op.getOperand(0);
8236   SDValue V2 = Op.getOperand(1);
8237   SDLoc dl(Op);
8238   EVT VT = Op.getValueType();
8239   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
8240   unsigned EltSize = VT.getScalarSizeInBits();
8241 
8242   if (ST->hasMVEIntegerOps() && EltSize == 1)
8243     return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
8244 
8245   // Convert shuffles that are directly supported on NEON to target-specific
8246   // DAG nodes, instead of keeping them as shuffles and matching them again
8247   // during code selection.  This is more efficient and avoids the possibility
8248   // of inconsistencies between legalization and selection.
8249   // FIXME: floating-point vectors should be canonicalized to integer vectors
8250   // of the same time so that they get CSEd properly.
8251   ArrayRef<int> ShuffleMask = SVN->getMask();
8252 
8253   if (EltSize <= 32) {
8254     if (SVN->isSplat()) {
8255       int Lane = SVN->getSplatIndex();
8256       // If this is undef splat, generate it via "just" vdup, if possible.
8257       if (Lane == -1) Lane = 0;
8258 
8259       // Test if V1 is a SCALAR_TO_VECTOR.
8260       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8261         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8262       }
8263       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
8264       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
8265       // reaches it).
8266       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
8267           !isa<ConstantSDNode>(V1.getOperand(0))) {
8268         bool IsScalarToVector = true;
8269         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
8270           if (!V1.getOperand(i).isUndef()) {
8271             IsScalarToVector = false;
8272             break;
8273           }
8274         if (IsScalarToVector)
8275           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
8276       }
8277       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
8278                          DAG.getConstant(Lane, dl, MVT::i32));
8279     }
8280 
8281     bool ReverseVEXT = false;
8282     unsigned Imm = 0;
8283     if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
8284       if (ReverseVEXT)
8285         std::swap(V1, V2);
8286       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
8287                          DAG.getConstant(Imm, dl, MVT::i32));
8288     }
8289 
8290     if (isVREVMask(ShuffleMask, VT, 64))
8291       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
8292     if (isVREVMask(ShuffleMask, VT, 32))
8293       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
8294     if (isVREVMask(ShuffleMask, VT, 16))
8295       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
8296 
8297     if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
8298       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
8299                          DAG.getConstant(Imm, dl, MVT::i32));
8300     }
8301 
8302     // Check for Neon shuffles that modify both input vectors in place.
8303     // If both results are used, i.e., if there are two shuffles with the same
8304     // source operands and with masks corresponding to both results of one of
8305     // these operations, DAG memoization will ensure that a single node is
8306     // used for both shuffles.
8307     unsigned WhichResult = 0;
8308     bool isV_UNDEF = false;
8309     if (ST->hasNEON()) {
8310       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8311               ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8312         if (isV_UNDEF)
8313           V2 = V1;
8314         return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8315             .getValue(WhichResult);
8316       }
8317     }
8318     if (ST->hasMVEIntegerOps()) {
8319       if (isVMOVNMask(ShuffleMask, VT, 0))
8320         return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8321                            DAG.getConstant(0, dl, MVT::i32));
8322       if (isVMOVNMask(ShuffleMask, VT, 1))
8323         return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8324                            DAG.getConstant(1, dl, MVT::i32));
8325     }
8326 
8327     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8328     // shuffles that produce a result larger than their operands with:
8329     //   shuffle(concat(v1, undef), concat(v2, undef))
8330     // ->
8331     //   shuffle(concat(v1, v2), undef)
8332     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8333     //
8334     // This is useful in the general case, but there are special cases where
8335     // native shuffles produce larger results: the two-result ops.
8336     //
8337     // Look through the concat when lowering them:
8338     //   shuffle(concat(v1, v2), undef)
8339     // ->
8340     //   concat(VZIP(v1, v2):0, :1)
8341     //
8342     if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8343       SDValue SubV1 = V1->getOperand(0);
8344       SDValue SubV2 = V1->getOperand(1);
8345       EVT SubVT = SubV1.getValueType();
8346 
8347       // We expect these to have been canonicalized to -1.
8348       assert(llvm::all_of(ShuffleMask, [&](int i) {
8349         return i < (int)VT.getVectorNumElements();
8350       }) && "Unexpected shuffle index into UNDEF operand!");
8351 
8352       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8353               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8354         if (isV_UNDEF)
8355           SubV2 = SubV1;
8356         assert((WhichResult == 0) &&
8357                "In-place shuffle of concat can only have one result!");
8358         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8359                                   SubV1, SubV2);
8360         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8361                            Res.getValue(1));
8362       }
8363     }
8364   }
8365 
8366   // If the shuffle is not directly supported and it has 4 elements, use
8367   // the PerfectShuffle-generated table to synthesize it from other shuffles.
8368   unsigned NumElts = VT.getVectorNumElements();
8369   if (NumElts == 4) {
8370     unsigned PFIndexes[4];
8371     for (unsigned i = 0; i != 4; ++i) {
8372       if (ShuffleMask[i] < 0)
8373         PFIndexes[i] = 8;
8374       else
8375         PFIndexes[i] = ShuffleMask[i];
8376     }
8377 
8378     // Compute the index in the perfect shuffle table.
8379     unsigned PFTableIndex =
8380       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8381     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8382     unsigned Cost = (PFEntry >> 30);
8383 
8384     if (Cost <= 4) {
8385       if (ST->hasNEON())
8386         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8387       else if (isLegalMVEShuffleOp(PFEntry)) {
8388         unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8389         unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8390         unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8391         unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8392         if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8393           return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8394       }
8395     }
8396   }
8397 
8398   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8399   if (EltSize >= 32) {
8400     // Do the expansion with floating-point types, since that is what the VFP
8401     // registers are defined to use, and since i64 is not legal.
8402     EVT EltVT = EVT::getFloatingPointVT(EltSize);
8403     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8404     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8405     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8406     SmallVector<SDValue, 8> Ops;
8407     for (unsigned i = 0; i < NumElts; ++i) {
8408       if (ShuffleMask[i] < 0)
8409         Ops.push_back(DAG.getUNDEF(EltVT));
8410       else
8411         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8412                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
8413                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8414                                                   dl, MVT::i32)));
8415     }
8416     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8417     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8418   }
8419 
8420   if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
8421     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
8422 
8423   if (ST->hasNEON() && VT == MVT::v8i8)
8424     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8425       return NewOp;
8426 
8427   if (ST->hasMVEIntegerOps())
8428     if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8429       return NewOp;
8430 
8431   return SDValue();
8432 }
8433 
8434 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8435                                          const ARMSubtarget *ST) {
8436   EVT VecVT = Op.getOperand(0).getValueType();
8437   SDLoc dl(Op);
8438 
8439   assert(ST->hasMVEIntegerOps() &&
8440          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8441 
8442   SDValue Conv =
8443       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8444   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8445   unsigned LaneWidth =
8446       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8447   unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8448   SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8449                             Op.getOperand(1), DAG.getValueType(MVT::i1));
8450   SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8451                             DAG.getConstant(~Mask, dl, MVT::i32));
8452   return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8453 }
8454 
8455 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8456                                                   SelectionDAG &DAG) const {
8457   // INSERT_VECTOR_ELT is legal only for immediate indexes.
8458   SDValue Lane = Op.getOperand(2);
8459   if (!isa<ConstantSDNode>(Lane))
8460     return SDValue();
8461 
8462   SDValue Elt = Op.getOperand(1);
8463   EVT EltVT = Elt.getValueType();
8464 
8465   if (Subtarget->hasMVEIntegerOps() &&
8466       Op.getValueType().getScalarSizeInBits() == 1)
8467     return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8468 
8469   if (getTypeAction(*DAG.getContext(), EltVT) ==
8470       TargetLowering::TypePromoteFloat) {
8471     // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8472     // but the type system will try to do that if we don't intervene.
8473     // Reinterpret any such vector-element insertion as one with the
8474     // corresponding integer types.
8475 
8476     SDLoc dl(Op);
8477 
8478     EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8479     assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8480            TargetLowering::TypePromoteFloat);
8481 
8482     SDValue VecIn = Op.getOperand(0);
8483     EVT VecVT = VecIn.getValueType();
8484     EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8485                                   VecVT.getVectorNumElements());
8486 
8487     SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8488     SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8489     SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8490                                   IVecIn, IElt, Lane);
8491     return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8492   }
8493 
8494   return Op;
8495 }
8496 
8497 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8498                                           const ARMSubtarget *ST) {
8499   EVT VecVT = Op.getOperand(0).getValueType();
8500   SDLoc dl(Op);
8501 
8502   assert(ST->hasMVEIntegerOps() &&
8503          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8504 
8505   SDValue Conv =
8506       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8507   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8508   unsigned LaneWidth =
8509       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8510   SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8511                               DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8512   return Shift;
8513 }
8514 
8515 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8516                                        const ARMSubtarget *ST) {
8517   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8518   SDValue Lane = Op.getOperand(1);
8519   if (!isa<ConstantSDNode>(Lane))
8520     return SDValue();
8521 
8522   SDValue Vec = Op.getOperand(0);
8523   EVT VT = Vec.getValueType();
8524 
8525   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8526     return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8527 
8528   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8529     SDLoc dl(Op);
8530     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8531   }
8532 
8533   return Op;
8534 }
8535 
8536 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8537                                       const ARMSubtarget *ST) {
8538   SDValue V1 = Op.getOperand(0);
8539   SDValue V2 = Op.getOperand(1);
8540   SDLoc dl(Op);
8541   EVT VT = Op.getValueType();
8542   EVT Op1VT = V1.getValueType();
8543   EVT Op2VT = V2.getValueType();
8544   unsigned NumElts = VT.getVectorNumElements();
8545 
8546   assert(Op1VT == Op2VT && "Operand types don't match!");
8547   assert(VT.getScalarSizeInBits() == 1 &&
8548          "Unexpected custom CONCAT_VECTORS lowering");
8549   assert(ST->hasMVEIntegerOps() &&
8550          "CONCAT_VECTORS lowering only supported for MVE");
8551 
8552   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8553   SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8554 
8555   // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8556   // promoted to v8i16, etc.
8557 
8558   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8559 
8560   // Extract the vector elements from Op1 and Op2 one by one and truncate them
8561   // to be the right size for the destination. For example, if Op1 is v4i1 then
8562   // the promoted vector is v4i32. The result of concatentation gives a v8i1,
8563   // which when promoted is v8i16. That means each i32 element from Op1 needs
8564   // truncating to i16 and inserting in the result.
8565   EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8566   SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8567   auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8568     EVT NewVT = NewV.getValueType();
8569     EVT ConcatVT = ConVec.getValueType();
8570     for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8571       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8572                                 DAG.getIntPtrConstant(i, dl));
8573       ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8574                            DAG.getConstant(j, dl, MVT::i32));
8575     }
8576     return ConVec;
8577   };
8578   unsigned j = 0;
8579   ConVec = ExractInto(NewV1, ConVec, j);
8580   ConVec = ExractInto(NewV2, ConVec, j);
8581 
8582   // Now return the result of comparing the subvector with zero,
8583   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8584   return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8585                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8586 }
8587 
8588 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8589                                    const ARMSubtarget *ST) {
8590   EVT VT = Op->getValueType(0);
8591   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8592     return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8593 
8594   // The only time a CONCAT_VECTORS operation can have legal types is when
8595   // two 64-bit vectors are concatenated to a 128-bit vector.
8596   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8597          "unexpected CONCAT_VECTORS");
8598   SDLoc dl(Op);
8599   SDValue Val = DAG.getUNDEF(MVT::v2f64);
8600   SDValue Op0 = Op.getOperand(0);
8601   SDValue Op1 = Op.getOperand(1);
8602   if (!Op0.isUndef())
8603     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8604                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8605                       DAG.getIntPtrConstant(0, dl));
8606   if (!Op1.isUndef())
8607     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8608                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8609                       DAG.getIntPtrConstant(1, dl));
8610   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8611 }
8612 
8613 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8614                                       const ARMSubtarget *ST) {
8615   SDValue V1 = Op.getOperand(0);
8616   SDValue V2 = Op.getOperand(1);
8617   SDLoc dl(Op);
8618   EVT VT = Op.getValueType();
8619   EVT Op1VT = V1.getValueType();
8620   unsigned NumElts = VT.getVectorNumElements();
8621   unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8622 
8623   assert(VT.getScalarSizeInBits() == 1 &&
8624          "Unexpected custom EXTRACT_SUBVECTOR lowering");
8625   assert(ST->hasMVEIntegerOps() &&
8626          "EXTRACT_SUBVECTOR lowering only supported for MVE");
8627 
8628   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8629 
8630   // We now have Op1 promoted to a vector of integers, where v8i1 gets
8631   // promoted to v8i16, etc.
8632 
8633   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8634 
8635   EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8636   SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8637   for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8638     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8639                               DAG.getIntPtrConstant(i, dl));
8640     SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8641                          DAG.getConstant(j, dl, MVT::i32));
8642   }
8643 
8644   // Now return the result of comparing the subvector with zero,
8645   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8646   return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8647                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8648 }
8649 
8650 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8651 /// element has been zero/sign-extended, depending on the isSigned parameter,
8652 /// from an integer type half its size.
8653 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8654                                    bool isSigned) {
8655   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8656   EVT VT = N->getValueType(0);
8657   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8658     SDNode *BVN = N->getOperand(0).getNode();
8659     if (BVN->getValueType(0) != MVT::v4i32 ||
8660         BVN->getOpcode() != ISD::BUILD_VECTOR)
8661       return false;
8662     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8663     unsigned HiElt = 1 - LoElt;
8664     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8665     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8666     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8667     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8668     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8669       return false;
8670     if (isSigned) {
8671       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8672           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8673         return true;
8674     } else {
8675       if (Hi0->isNullValue() && Hi1->isNullValue())
8676         return true;
8677     }
8678     return false;
8679   }
8680 
8681   if (N->getOpcode() != ISD::BUILD_VECTOR)
8682     return false;
8683 
8684   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8685     SDNode *Elt = N->getOperand(i).getNode();
8686     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8687       unsigned EltSize = VT.getScalarSizeInBits();
8688       unsigned HalfSize = EltSize / 2;
8689       if (isSigned) {
8690         if (!isIntN(HalfSize, C->getSExtValue()))
8691           return false;
8692       } else {
8693         if (!isUIntN(HalfSize, C->getZExtValue()))
8694           return false;
8695       }
8696       continue;
8697     }
8698     return false;
8699   }
8700 
8701   return true;
8702 }
8703 
8704 /// isSignExtended - Check if a node is a vector value that is sign-extended
8705 /// or a constant BUILD_VECTOR with sign-extended elements.
8706 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8707   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8708     return true;
8709   if (isExtendedBUILD_VECTOR(N, DAG, true))
8710     return true;
8711   return false;
8712 }
8713 
8714 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8715 /// or a constant BUILD_VECTOR with zero-extended elements.
8716 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8717   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8718     return true;
8719   if (isExtendedBUILD_VECTOR(N, DAG, false))
8720     return true;
8721   return false;
8722 }
8723 
8724 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8725   if (OrigVT.getSizeInBits() >= 64)
8726     return OrigVT;
8727 
8728   assert(OrigVT.isSimple() && "Expecting a simple value type");
8729 
8730   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8731   switch (OrigSimpleTy) {
8732   default: llvm_unreachable("Unexpected Vector Type");
8733   case MVT::v2i8:
8734   case MVT::v2i16:
8735      return MVT::v2i32;
8736   case MVT::v4i8:
8737     return  MVT::v4i16;
8738   }
8739 }
8740 
8741 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8742 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8743 /// We insert the required extension here to get the vector to fill a D register.
8744 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8745                                             const EVT &OrigTy,
8746                                             const EVT &ExtTy,
8747                                             unsigned ExtOpcode) {
8748   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8749   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8750   // 64-bits we need to insert a new extension so that it will be 64-bits.
8751   assert(ExtTy.is128BitVector() && "Unexpected extension size");
8752   if (OrigTy.getSizeInBits() >= 64)
8753     return N;
8754 
8755   // Must extend size to at least 64 bits to be used as an operand for VMULL.
8756   EVT NewVT = getExtensionTo64Bits(OrigTy);
8757 
8758   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8759 }
8760 
8761 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8762 /// does not do any sign/zero extension. If the original vector is less
8763 /// than 64 bits, an appropriate extension will be added after the load to
8764 /// reach a total size of 64 bits. We have to add the extension separately
8765 /// because ARM does not have a sign/zero extending load for vectors.
8766 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8767   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8768 
8769   // The load already has the right type.
8770   if (ExtendedTy == LD->getMemoryVT())
8771     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8772                        LD->getBasePtr(), LD->getPointerInfo(),
8773                        LD->getAlignment(), LD->getMemOperand()->getFlags());
8774 
8775   // We need to create a zextload/sextload. We cannot just create a load
8776   // followed by a zext/zext node because LowerMUL is also run during normal
8777   // operation legalization where we can't create illegal types.
8778   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8779                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8780                         LD->getMemoryVT(), LD->getAlignment(),
8781                         LD->getMemOperand()->getFlags());
8782 }
8783 
8784 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8785 /// extending load, or BUILD_VECTOR with extended elements, return the
8786 /// unextended value. The unextended vector should be 64 bits so that it can
8787 /// be used as an operand to a VMULL instruction. If the original vector size
8788 /// before extension is less than 64 bits we add a an extension to resize
8789 /// the vector to 64 bits.
8790 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8791   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8792     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8793                                         N->getOperand(0)->getValueType(0),
8794                                         N->getValueType(0),
8795                                         N->getOpcode());
8796 
8797   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8798     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8799            "Expected extending load");
8800 
8801     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8802     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8803     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8804     SDValue extLoad =
8805         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8806     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8807 
8808     return newLoad;
8809   }
8810 
8811   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
8812   // have been legalized as a BITCAST from v4i32.
8813   if (N->getOpcode() == ISD::BITCAST) {
8814     SDNode *BVN = N->getOperand(0).getNode();
8815     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8816            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8817     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8818     return DAG.getBuildVector(
8819         MVT::v2i32, SDLoc(N),
8820         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8821   }
8822   // Construct a new BUILD_VECTOR with elements truncated to half the size.
8823   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8824   EVT VT = N->getValueType(0);
8825   unsigned EltSize = VT.getScalarSizeInBits() / 2;
8826   unsigned NumElts = VT.getVectorNumElements();
8827   MVT TruncVT = MVT::getIntegerVT(EltSize);
8828   SmallVector<SDValue, 8> Ops;
8829   SDLoc dl(N);
8830   for (unsigned i = 0; i != NumElts; ++i) {
8831     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8832     const APInt &CInt = C->getAPIntValue();
8833     // Element types smaller than 32 bits are not legal, so use i32 elements.
8834     // The values are implicitly truncated so sext vs. zext doesn't matter.
8835     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8836   }
8837   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8838 }
8839 
8840 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8841   unsigned Opcode = N->getOpcode();
8842   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8843     SDNode *N0 = N->getOperand(0).getNode();
8844     SDNode *N1 = N->getOperand(1).getNode();
8845     return N0->hasOneUse() && N1->hasOneUse() &&
8846       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8847   }
8848   return false;
8849 }
8850 
8851 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8852   unsigned Opcode = N->getOpcode();
8853   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8854     SDNode *N0 = N->getOperand(0).getNode();
8855     SDNode *N1 = N->getOperand(1).getNode();
8856     return N0->hasOneUse() && N1->hasOneUse() &&
8857       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8858   }
8859   return false;
8860 }
8861 
8862 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8863   // Multiplications are only custom-lowered for 128-bit vectors so that
8864   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
8865   EVT VT = Op.getValueType();
8866   assert(VT.is128BitVector() && VT.isInteger() &&
8867          "unexpected type for custom-lowering ISD::MUL");
8868   SDNode *N0 = Op.getOperand(0).getNode();
8869   SDNode *N1 = Op.getOperand(1).getNode();
8870   unsigned NewOpc = 0;
8871   bool isMLA = false;
8872   bool isN0SExt = isSignExtended(N0, DAG);
8873   bool isN1SExt = isSignExtended(N1, DAG);
8874   if (isN0SExt && isN1SExt)
8875     NewOpc = ARMISD::VMULLs;
8876   else {
8877     bool isN0ZExt = isZeroExtended(N0, DAG);
8878     bool isN1ZExt = isZeroExtended(N1, DAG);
8879     if (isN0ZExt && isN1ZExt)
8880       NewOpc = ARMISD::VMULLu;
8881     else if (isN1SExt || isN1ZExt) {
8882       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8883       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8884       if (isN1SExt && isAddSubSExt(N0, DAG)) {
8885         NewOpc = ARMISD::VMULLs;
8886         isMLA = true;
8887       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8888         NewOpc = ARMISD::VMULLu;
8889         isMLA = true;
8890       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8891         std::swap(N0, N1);
8892         NewOpc = ARMISD::VMULLu;
8893         isMLA = true;
8894       }
8895     }
8896 
8897     if (!NewOpc) {
8898       if (VT == MVT::v2i64)
8899         // Fall through to expand this.  It is not legal.
8900         return SDValue();
8901       else
8902         // Other vector multiplications are legal.
8903         return Op;
8904     }
8905   }
8906 
8907   // Legalize to a VMULL instruction.
8908   SDLoc DL(Op);
8909   SDValue Op0;
8910   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8911   if (!isMLA) {
8912     Op0 = SkipExtensionForVMULL(N0, DAG);
8913     assert(Op0.getValueType().is64BitVector() &&
8914            Op1.getValueType().is64BitVector() &&
8915            "unexpected types for extended operands to VMULL");
8916     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8917   }
8918 
8919   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8920   // isel lowering to take advantage of no-stall back to back vmul + vmla.
8921   //   vmull q0, d4, d6
8922   //   vmlal q0, d5, d6
8923   // is faster than
8924   //   vaddl q0, d4, d5
8925   //   vmovl q1, d6
8926   //   vmul  q0, q0, q1
8927   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8928   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8929   EVT Op1VT = Op1.getValueType();
8930   return DAG.getNode(N0->getOpcode(), DL, VT,
8931                      DAG.getNode(NewOpc, DL, VT,
8932                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8933                      DAG.getNode(NewOpc, DL, VT,
8934                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8935 }
8936 
8937 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8938                               SelectionDAG &DAG) {
8939   // TODO: Should this propagate fast-math-flags?
8940 
8941   // Convert to float
8942   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8943   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8944   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8945   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8946   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8947   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8948   // Get reciprocal estimate.
8949   // float4 recip = vrecpeq_f32(yf);
8950   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8951                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8952                    Y);
8953   // Because char has a smaller range than uchar, we can actually get away
8954   // without any newton steps.  This requires that we use a weird bias
8955   // of 0xb000, however (again, this has been exhaustively tested).
8956   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8957   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8958   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8959   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8960   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8961   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8962   // Convert back to short.
8963   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8964   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8965   return X;
8966 }
8967 
8968 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8969                                SelectionDAG &DAG) {
8970   // TODO: Should this propagate fast-math-flags?
8971 
8972   SDValue N2;
8973   // Convert to float.
8974   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8975   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8976   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8977   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8978   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8979   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8980 
8981   // Use reciprocal estimate and one refinement step.
8982   // float4 recip = vrecpeq_f32(yf);
8983   // recip *= vrecpsq_f32(yf, recip);
8984   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8985                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8986                    N1);
8987   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8988                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8989                    N1, N2);
8990   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8991   // Because short has a smaller range than ushort, we can actually get away
8992   // with only a single newton step.  This requires that we use a weird bias
8993   // of 89, however (again, this has been exhaustively tested).
8994   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8995   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8996   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8997   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8998   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8999   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9000   // Convert back to integer and return.
9001   // return vmovn_s32(vcvt_s32_f32(result));
9002   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9003   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9004   return N0;
9005 }
9006 
9007 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
9008                          const ARMSubtarget *ST) {
9009   EVT VT = Op.getValueType();
9010   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9011          "unexpected type for custom-lowering ISD::SDIV");
9012 
9013   SDLoc dl(Op);
9014   SDValue N0 = Op.getOperand(0);
9015   SDValue N1 = Op.getOperand(1);
9016   SDValue N2, N3;
9017 
9018   if (VT == MVT::v8i8) {
9019     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
9020     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
9021 
9022     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9023                      DAG.getIntPtrConstant(4, dl));
9024     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9025                      DAG.getIntPtrConstant(4, dl));
9026     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9027                      DAG.getIntPtrConstant(0, dl));
9028     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9029                      DAG.getIntPtrConstant(0, dl));
9030 
9031     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
9032     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
9033 
9034     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9035     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9036 
9037     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
9038     return N0;
9039   }
9040   return LowerSDIV_v4i16(N0, N1, dl, DAG);
9041 }
9042 
9043 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
9044                          const ARMSubtarget *ST) {
9045   // TODO: Should this propagate fast-math-flags?
9046   EVT VT = Op.getValueType();
9047   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
9048          "unexpected type for custom-lowering ISD::UDIV");
9049 
9050   SDLoc dl(Op);
9051   SDValue N0 = Op.getOperand(0);
9052   SDValue N1 = Op.getOperand(1);
9053   SDValue N2, N3;
9054 
9055   if (VT == MVT::v8i8) {
9056     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
9057     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
9058 
9059     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9060                      DAG.getIntPtrConstant(4, dl));
9061     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9062                      DAG.getIntPtrConstant(4, dl));
9063     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
9064                      DAG.getIntPtrConstant(0, dl));
9065     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
9066                      DAG.getIntPtrConstant(0, dl));
9067 
9068     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
9069     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
9070 
9071     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
9072     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
9073 
9074     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
9075                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
9076                                      MVT::i32),
9077                      N0);
9078     return N0;
9079   }
9080 
9081   // v4i16 sdiv ... Convert to float.
9082   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
9083   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
9084   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
9085   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
9086   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
9087   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
9088 
9089   // Use reciprocal estimate and two refinement steps.
9090   // float4 recip = vrecpeq_f32(yf);
9091   // recip *= vrecpsq_f32(yf, recip);
9092   // recip *= vrecpsq_f32(yf, recip);
9093   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9094                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
9095                    BN1);
9096   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9097                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9098                    BN1, N2);
9099   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9100   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
9101                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
9102                    BN1, N2);
9103   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
9104   // Simply multiplying by the reciprocal estimate can leave us a few ulps
9105   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
9106   // and that it will never cause us to return an answer too large).
9107   // float4 result = as_float4(as_int4(xf*recip) + 2);
9108   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
9109   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
9110   N1 = DAG.getConstant(2, dl, MVT::v4i32);
9111   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
9112   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
9113   // Convert back to integer and return.
9114   // return vmovn_u32(vcvt_s32_f32(result));
9115   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
9116   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
9117   return N0;
9118 }
9119 
9120 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
9121   SDNode *N = Op.getNode();
9122   EVT VT = N->getValueType(0);
9123   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
9124 
9125   SDValue Carry = Op.getOperand(2);
9126 
9127   SDLoc DL(Op);
9128 
9129   SDValue Result;
9130   if (Op.getOpcode() == ISD::ADDCARRY) {
9131     // This converts the boolean value carry into the carry flag.
9132     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9133 
9134     // Do the addition proper using the carry flag we wanted.
9135     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
9136                          Op.getOperand(1), Carry);
9137 
9138     // Now convert the carry flag into a boolean value.
9139     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9140   } else {
9141     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
9142     // have to invert the carry first.
9143     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9144                         DAG.getConstant(1, DL, MVT::i32), Carry);
9145     // This converts the boolean value carry into the carry flag.
9146     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
9147 
9148     // Do the subtraction proper using the carry flag we wanted.
9149     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
9150                          Op.getOperand(1), Carry);
9151 
9152     // Now convert the carry flag into a boolean value.
9153     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
9154     // But the carry returned by ARMISD::SUBE is not a borrow as expected
9155     // by ISD::SUBCARRY, so compute 1 - C.
9156     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
9157                         DAG.getConstant(1, DL, MVT::i32), Carry);
9158   }
9159 
9160   // Return both values.
9161   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
9162 }
9163 
9164 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
9165   assert(Subtarget->isTargetDarwin());
9166 
9167   // For iOS, we want to call an alternative entry point: __sincos_stret,
9168   // return values are passed via sret.
9169   SDLoc dl(Op);
9170   SDValue Arg = Op.getOperand(0);
9171   EVT ArgVT = Arg.getValueType();
9172   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
9173   auto PtrVT = getPointerTy(DAG.getDataLayout());
9174 
9175   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9177 
9178   // Pair of floats / doubles used to pass the result.
9179   Type *RetTy = StructType::get(ArgTy, ArgTy);
9180   auto &DL = DAG.getDataLayout();
9181 
9182   ArgListTy Args;
9183   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
9184   SDValue SRet;
9185   if (ShouldUseSRet) {
9186     // Create stack object for sret.
9187     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
9188     const Align StackAlign = DL.getPrefTypeAlign(RetTy);
9189     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
9190     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
9191 
9192     ArgListEntry Entry;
9193     Entry.Node = SRet;
9194     Entry.Ty = RetTy->getPointerTo();
9195     Entry.IsSExt = false;
9196     Entry.IsZExt = false;
9197     Entry.IsSRet = true;
9198     Args.push_back(Entry);
9199     RetTy = Type::getVoidTy(*DAG.getContext());
9200   }
9201 
9202   ArgListEntry Entry;
9203   Entry.Node = Arg;
9204   Entry.Ty = ArgTy;
9205   Entry.IsSExt = false;
9206   Entry.IsZExt = false;
9207   Args.push_back(Entry);
9208 
9209   RTLIB::Libcall LC =
9210       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
9211   const char *LibcallName = getLibcallName(LC);
9212   CallingConv::ID CC = getLibcallCallingConv(LC);
9213   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
9214 
9215   TargetLowering::CallLoweringInfo CLI(DAG);
9216   CLI.setDebugLoc(dl)
9217       .setChain(DAG.getEntryNode())
9218       .setCallee(CC, RetTy, Callee, std::move(Args))
9219       .setDiscardResult(ShouldUseSRet);
9220   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
9221 
9222   if (!ShouldUseSRet)
9223     return CallResult.first;
9224 
9225   SDValue LoadSin =
9226       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
9227 
9228   // Address of cos field.
9229   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
9230                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
9231   SDValue LoadCos =
9232       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
9233 
9234   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
9235   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
9236                      LoadSin.getValue(0), LoadCos.getValue(0));
9237 }
9238 
9239 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
9240                                                   bool Signed,
9241                                                   SDValue &Chain) const {
9242   EVT VT = Op.getValueType();
9243   assert((VT == MVT::i32 || VT == MVT::i64) &&
9244          "unexpected type for custom lowering DIV");
9245   SDLoc dl(Op);
9246 
9247   const auto &DL = DAG.getDataLayout();
9248   const auto &TLI = DAG.getTargetLoweringInfo();
9249 
9250   const char *Name = nullptr;
9251   if (Signed)
9252     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
9253   else
9254     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
9255 
9256   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
9257 
9258   ARMTargetLowering::ArgListTy Args;
9259 
9260   for (auto AI : {1, 0}) {
9261     ArgListEntry Arg;
9262     Arg.Node = Op.getOperand(AI);
9263     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
9264     Args.push_back(Arg);
9265   }
9266 
9267   CallLoweringInfo CLI(DAG);
9268   CLI.setDebugLoc(dl)
9269     .setChain(Chain)
9270     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
9271                ES, std::move(Args));
9272 
9273   return LowerCallTo(CLI).first;
9274 }
9275 
9276 // This is a code size optimisation: return the original SDIV node to
9277 // DAGCombiner when we don't want to expand SDIV into a sequence of
9278 // instructions, and an empty node otherwise which will cause the
9279 // SDIV to be expanded in DAGCombine.
9280 SDValue
9281 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9282                                  SelectionDAG &DAG,
9283                                  SmallVectorImpl<SDNode *> &Created) const {
9284   // TODO: Support SREM
9285   if (N->getOpcode() != ISD::SDIV)
9286     return SDValue();
9287 
9288   const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
9289   const bool MinSize = ST.hasMinSize();
9290   const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
9291                                       : ST.hasDivideInARMMode();
9292 
9293   // Don't touch vector types; rewriting this may lead to scalarizing
9294   // the int divs.
9295   if (N->getOperand(0).getValueType().isVector())
9296     return SDValue();
9297 
9298   // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
9299   // hwdiv support for this to be really profitable.
9300   if (!(MinSize && HasDivide))
9301     return SDValue();
9302 
9303   // ARM mode is a bit simpler than Thumb: we can handle large power
9304   // of 2 immediates with 1 mov instruction; no further checks required,
9305   // just return the sdiv node.
9306   if (!ST.isThumb())
9307     return SDValue(N, 0);
9308 
9309   // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
9310   // and thus lose the code size benefits of a MOVS that requires only 2.
9311   // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9312   // but as it's doing exactly this, it's not worth the trouble to get TTI.
9313   if (Divisor.sgt(128))
9314     return SDValue();
9315 
9316   return SDValue(N, 0);
9317 }
9318 
9319 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9320                                             bool Signed) const {
9321   assert(Op.getValueType() == MVT::i32 &&
9322          "unexpected type for custom lowering DIV");
9323   SDLoc dl(Op);
9324 
9325   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9326                                DAG.getEntryNode(), Op.getOperand(1));
9327 
9328   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9329 }
9330 
9331 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9332   SDLoc DL(N);
9333   SDValue Op = N->getOperand(1);
9334   if (N->getValueType(0) == MVT::i32)
9335     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9336   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9337                            DAG.getConstant(0, DL, MVT::i32));
9338   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9339                            DAG.getConstant(1, DL, MVT::i32));
9340   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9341                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9342 }
9343 
9344 void ARMTargetLowering::ExpandDIV_Windows(
9345     SDValue Op, SelectionDAG &DAG, bool Signed,
9346     SmallVectorImpl<SDValue> &Results) const {
9347   const auto &DL = DAG.getDataLayout();
9348   const auto &TLI = DAG.getTargetLoweringInfo();
9349 
9350   assert(Op.getValueType() == MVT::i64 &&
9351          "unexpected type for custom lowering DIV");
9352   SDLoc dl(Op);
9353 
9354   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9355 
9356   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9357 
9358   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9359   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9360                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
9361   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9362 
9363   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lower, Upper));
9364 }
9365 
9366 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9367   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9368   EVT MemVT = LD->getMemoryVT();
9369   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9370          "Expected a predicate type!");
9371   assert(MemVT == Op.getValueType());
9372   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9373          "Expected a non-extending load");
9374   assert(LD->isUnindexed() && "Expected a unindexed load");
9375 
9376   // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
9377   // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9378   // need to make sure that 8/4 bits are actually loaded into the correct
9379   // place, which means loading the value and then shuffling the values into
9380   // the bottom bits of the predicate.
9381   // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9382   // for BE).
9383 
9384   SDLoc dl(Op);
9385   SDValue Load = DAG.getExtLoad(
9386       ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9387       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9388       LD->getMemOperand());
9389   SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load);
9390   if (MemVT != MVT::v16i1)
9391     Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9392                        DAG.getConstant(0, dl, MVT::i32));
9393   return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9394 }
9395 
9396 void ARMTargetLowering::LowerLOAD(SDNode *N, SmallVectorImpl<SDValue> &Results,
9397                                   SelectionDAG &DAG) const {
9398   LoadSDNode *LD = cast<LoadSDNode>(N);
9399   EVT MemVT = LD->getMemoryVT();
9400   assert(LD->isUnindexed() && "Loads should be unindexed at this point.");
9401 
9402   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9403       !Subtarget->isThumb1Only() && LD->isVolatile()) {
9404     SDLoc dl(N);
9405     SDValue Result = DAG.getMemIntrinsicNode(
9406         ARMISD::LDRD, dl, DAG.getVTList({MVT::i32, MVT::i32, MVT::Other}),
9407         {LD->getChain(), LD->getBasePtr()}, MemVT, LD->getMemOperand());
9408     SDValue Lo = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 0 : 1);
9409     SDValue Hi = Result.getValue(DAG.getDataLayout().isLittleEndian() ? 1 : 0);
9410     SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
9411     Results.append({Pair, Result.getValue(2)});
9412   }
9413 }
9414 
9415 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
9416   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9417   EVT MemVT = ST->getMemoryVT();
9418   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9419          "Expected a predicate type!");
9420   assert(MemVT == ST->getValue().getValueType());
9421   assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9422   assert(ST->isUnindexed() && "Expected a unindexed store");
9423 
9424   // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
9425   // unset and a scalar store.
9426   SDLoc dl(Op);
9427   SDValue Build = ST->getValue();
9428   if (MemVT != MVT::v16i1) {
9429     SmallVector<SDValue, 16> Ops;
9430     for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++)
9431       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9432                                 DAG.getConstant(I, dl, MVT::i32)));
9433     for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9434       Ops.push_back(DAG.getUNDEF(MVT::i32));
9435     Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9436   }
9437   SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9438   return DAG.getTruncStore(
9439       ST->getChain(), dl, GRP, ST->getBasePtr(),
9440       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9441       ST->getMemOperand());
9442 }
9443 
9444 static SDValue LowerSTORE(SDValue Op, SelectionDAG &DAG,
9445                           const ARMSubtarget *Subtarget) {
9446   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9447   EVT MemVT = ST->getMemoryVT();
9448   assert(ST->isUnindexed() && "Stores should be unindexed at this point.");
9449 
9450   if (MemVT == MVT::i64 && Subtarget->hasV5TEOps() &&
9451       !Subtarget->isThumb1Only() && ST->isVolatile()) {
9452     SDNode *N = Op.getNode();
9453     SDLoc dl(N);
9454 
9455     SDValue Lo = DAG.getNode(
9456         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9457         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 0 : 1, dl,
9458                               MVT::i32));
9459     SDValue Hi = DAG.getNode(
9460         ISD::EXTRACT_ELEMENT, dl, MVT::i32, ST->getValue(),
9461         DAG.getTargetConstant(DAG.getDataLayout().isLittleEndian() ? 1 : 0, dl,
9462                               MVT::i32));
9463 
9464     return DAG.getMemIntrinsicNode(ARMISD::STRD, dl, DAG.getVTList(MVT::Other),
9465                                    {ST->getChain(), Lo, Hi, ST->getBasePtr()},
9466                                    MemVT, ST->getMemOperand());
9467   } else if (Subtarget->hasMVEIntegerOps() &&
9468              ((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 ||
9469                MemVT == MVT::v16i1))) {
9470     return LowerPredicateStore(Op, DAG);
9471   }
9472 
9473   return SDValue();
9474 }
9475 
9476 static bool isZeroVector(SDValue N) {
9477   return (ISD::isBuildVectorAllZeros(N.getNode()) ||
9478           (N->getOpcode() == ARMISD::VMOVIMM &&
9479            isNullConstant(N->getOperand(0))));
9480 }
9481 
9482 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
9483   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
9484   MVT VT = Op.getSimpleValueType();
9485   SDValue Mask = N->getMask();
9486   SDValue PassThru = N->getPassThru();
9487   SDLoc dl(Op);
9488 
9489   if (isZeroVector(PassThru))
9490     return Op;
9491 
9492   // MVE Masked loads use zero as the passthru value. Here we convert undef to
9493   // zero too, and other values are lowered to a select.
9494   SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
9495                                 DAG.getTargetConstant(0, dl, MVT::i32));
9496   SDValue NewLoad = DAG.getMaskedLoad(
9497       VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
9498       N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
9499       N->getExtensionType(), N->isExpandingLoad());
9500   SDValue Combo = NewLoad;
9501   bool PassThruIsCastZero = (PassThru.getOpcode() == ISD::BITCAST ||
9502                              PassThru.getOpcode() == ARMISD::VECTOR_REG_CAST) &&
9503                             isZeroVector(PassThru->getOperand(0));
9504   if (!PassThru.isUndef() && !PassThruIsCastZero)
9505     Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
9506   return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
9507 }
9508 
9509 static SDValue LowerVecReduce(SDValue Op, SelectionDAG &DAG,
9510                               const ARMSubtarget *ST) {
9511   if (!ST->hasMVEIntegerOps())
9512     return SDValue();
9513 
9514   SDLoc dl(Op);
9515   unsigned BaseOpcode = 0;
9516   switch (Op->getOpcode()) {
9517   default: llvm_unreachable("Expected VECREDUCE opcode");
9518   case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
9519   case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
9520   case ISD::VECREDUCE_MUL:  BaseOpcode = ISD::MUL; break;
9521   case ISD::VECREDUCE_AND:  BaseOpcode = ISD::AND; break;
9522   case ISD::VECREDUCE_OR:   BaseOpcode = ISD::OR; break;
9523   case ISD::VECREDUCE_XOR:  BaseOpcode = ISD::XOR; break;
9524   case ISD::VECREDUCE_FMAX: BaseOpcode = ISD::FMAXNUM; break;
9525   case ISD::VECREDUCE_FMIN: BaseOpcode = ISD::FMINNUM; break;
9526   }
9527 
9528   SDValue Op0 = Op->getOperand(0);
9529   EVT VT = Op0.getValueType();
9530   EVT EltVT = VT.getVectorElementType();
9531   unsigned NumElts = VT.getVectorNumElements();
9532   unsigned NumActiveLanes = NumElts;
9533 
9534   assert((NumActiveLanes == 16 || NumActiveLanes == 8 || NumActiveLanes == 4 ||
9535           NumActiveLanes == 2) &&
9536          "Only expected a power 2 vector size");
9537 
9538   // Use Mul(X, Rev(X)) until 4 items remain. Going down to 4 vector elements
9539   // allows us to easily extract vector elements from the lanes.
9540   while (NumActiveLanes > 4) {
9541     unsigned RevOpcode = NumActiveLanes == 16 ? ARMISD::VREV16 : ARMISD::VREV32;
9542     SDValue Rev = DAG.getNode(RevOpcode, dl, VT, Op0);
9543     Op0 = DAG.getNode(BaseOpcode, dl, VT, Op0, Rev);
9544     NumActiveLanes /= 2;
9545   }
9546 
9547   SDValue Res;
9548   if (NumActiveLanes == 4) {
9549     // The remaining 4 elements are summed sequentially
9550     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9551                               DAG.getConstant(0 * NumElts / 4, dl, MVT::i32));
9552     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9553                               DAG.getConstant(1 * NumElts / 4, dl, MVT::i32));
9554     SDValue Ext2 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9555                               DAG.getConstant(2 * NumElts / 4, dl, MVT::i32));
9556     SDValue Ext3 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9557                               DAG.getConstant(3 * NumElts / 4, dl, MVT::i32));
9558     SDValue Res0 = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
9559     SDValue Res1 = DAG.getNode(BaseOpcode, dl, EltVT, Ext2, Ext3, Op->getFlags());
9560     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res0, Res1, Op->getFlags());
9561   } else {
9562     SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9563                               DAG.getConstant(0, dl, MVT::i32));
9564     SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Op0,
9565                               DAG.getConstant(1, dl, MVT::i32));
9566     Res = DAG.getNode(BaseOpcode, dl, EltVT, Ext0, Ext1, Op->getFlags());
9567   }
9568 
9569   // Result type may be wider than element type.
9570   if (EltVT != Op->getValueType(0))
9571     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Op->getValueType(0), Res);
9572   return Res;
9573 }
9574 
9575 static SDValue LowerVecReduceF(SDValue Op, SelectionDAG &DAG,
9576                                const ARMSubtarget *ST) {
9577   if (!ST->hasMVEFloatOps())
9578     return SDValue();
9579   return LowerVecReduce(Op, DAG, ST);
9580 }
9581 
9582 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
9583   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
9584     // Acquire/Release load/store is not legal for targets without a dmb or
9585     // equivalent available.
9586     return SDValue();
9587 
9588   // Monotonic load/store is legal for all targets.
9589   return Op;
9590 }
9591 
9592 static void ReplaceREADCYCLECOUNTER(SDNode *N,
9593                                     SmallVectorImpl<SDValue> &Results,
9594                                     SelectionDAG &DAG,
9595                                     const ARMSubtarget *Subtarget) {
9596   SDLoc DL(N);
9597   // Under Power Management extensions, the cycle-count is:
9598   //    mrc p15, #0, <Rt>, c9, c13, #0
9599   SDValue Ops[] = { N->getOperand(0), // Chain
9600                     DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
9601                     DAG.getTargetConstant(15, DL, MVT::i32),
9602                     DAG.getTargetConstant(0, DL, MVT::i32),
9603                     DAG.getTargetConstant(9, DL, MVT::i32),
9604                     DAG.getTargetConstant(13, DL, MVT::i32),
9605                     DAG.getTargetConstant(0, DL, MVT::i32)
9606   };
9607 
9608   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
9609                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
9610   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
9611                                 DAG.getConstant(0, DL, MVT::i32)));
9612   Results.push_back(Cycles32.getValue(1));
9613 }
9614 
9615 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
9616   SDLoc dl(V.getNode());
9617   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
9618   SDValue VHi = DAG.getAnyExtOrTrunc(
9619       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
9620       dl, MVT::i32);
9621   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9622   if (isBigEndian)
9623     std::swap (VLo, VHi);
9624   SDValue RegClass =
9625       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
9626   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
9627   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
9628   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
9629   return SDValue(
9630       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
9631 }
9632 
9633 static void ReplaceCMP_SWAP_64Results(SDNode *N,
9634                                        SmallVectorImpl<SDValue> & Results,
9635                                        SelectionDAG &DAG) {
9636   assert(N->getValueType(0) == MVT::i64 &&
9637          "AtomicCmpSwap on types less than 64 should be legal");
9638   SDValue Ops[] = {N->getOperand(1),
9639                    createGPRPairNode(DAG, N->getOperand(2)),
9640                    createGPRPairNode(DAG, N->getOperand(3)),
9641                    N->getOperand(0)};
9642   SDNode *CmpSwap = DAG.getMachineNode(
9643       ARM::CMP_SWAP_64, SDLoc(N),
9644       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
9645 
9646   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
9647   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
9648 
9649   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9650 
9651   SDValue Lo =
9652       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
9653                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9654   SDValue Hi =
9655       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
9656                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0));
9657   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i64, Lo, Hi));
9658   Results.push_back(SDValue(CmpSwap, 2));
9659 }
9660 
9661 SDValue ARMTargetLowering::LowerFSETCC(SDValue Op, SelectionDAG &DAG) const {
9662   SDLoc dl(Op);
9663   EVT VT = Op.getValueType();
9664   SDValue Chain = Op.getOperand(0);
9665   SDValue LHS = Op.getOperand(1);
9666   SDValue RHS = Op.getOperand(2);
9667   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(3))->get();
9668   bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
9669 
9670   // If we don't have instructions of this float type then soften to a libcall
9671   // and use SETCC instead.
9672   if (isUnsupportedFloatingType(LHS.getValueType())) {
9673     DAG.getTargetLoweringInfo().softenSetCCOperands(
9674       DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS, Chain, IsSignaling);
9675     if (!RHS.getNode()) {
9676       RHS = DAG.getConstant(0, dl, LHS.getValueType());
9677       CC = ISD::SETNE;
9678     }
9679     SDValue Result = DAG.getNode(ISD::SETCC, dl, VT, LHS, RHS,
9680                                  DAG.getCondCode(CC));
9681     return DAG.getMergeValues({Result, Chain}, dl);
9682   }
9683 
9684   ARMCC::CondCodes CondCode, CondCode2;
9685   FPCCToARMCC(CC, CondCode, CondCode2);
9686 
9687   // FIXME: Chain is not handled correctly here. Currently the FPSCR is implicit
9688   // in CMPFP and CMPFPE, but instead it should be made explicit by these
9689   // instructions using a chain instead of glue. This would also fix the problem
9690   // here (and also in LowerSELECT_CC) where we generate two comparisons when
9691   // CondCode2 != AL.
9692   SDValue True = DAG.getConstant(1, dl, VT);
9693   SDValue False =  DAG.getConstant(0, dl, VT);
9694   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
9695   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
9696   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9697   SDValue Result = getCMOV(dl, VT, False, True, ARMcc, CCR, Cmp, DAG);
9698   if (CondCode2 != ARMCC::AL) {
9699     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
9700     Cmp = getVFPCmp(LHS, RHS, DAG, dl, IsSignaling);
9701     Result = getCMOV(dl, VT, Result, True, ARMcc, CCR, Cmp, DAG);
9702   }
9703   return DAG.getMergeValues({Result, Chain}, dl);
9704 }
9705 
9706 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9707   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
9708   switch (Op.getOpcode()) {
9709   default: llvm_unreachable("Don't know how to custom lower this!");
9710   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
9711   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9712   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
9713   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9714   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9715   case ISD::SELECT:        return LowerSELECT(Op, DAG);
9716   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
9717   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
9718   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
9719   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
9720   case ISD::VASTART:       return LowerVASTART(Op, DAG);
9721   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
9722   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
9723   case ISD::SINT_TO_FP:
9724   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
9725   case ISD::STRICT_FP_TO_SINT:
9726   case ISD::STRICT_FP_TO_UINT:
9727   case ISD::FP_TO_SINT:
9728   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
9729   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
9730   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
9731   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
9732   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
9733   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
9734   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
9735   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
9736   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
9737                                                                Subtarget);
9738   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
9739   case ISD::SHL:
9740   case ISD::SRL:
9741   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
9742   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
9743   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
9744   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
9745   case ISD::SRL_PARTS:
9746   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
9747   case ISD::CTTZ:
9748   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
9749   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
9750   case ISD::SETCC:         return LowerVSETCC(Op, DAG, Subtarget);
9751   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
9752   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
9753   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
9754   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
9755   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
9756   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9757   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
9758   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
9759   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
9760   case ISD::MUL:           return LowerMUL(Op, DAG);
9761   case ISD::SDIV:
9762     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9763       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
9764     return LowerSDIV(Op, DAG, Subtarget);
9765   case ISD::UDIV:
9766     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9767       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
9768     return LowerUDIV(Op, DAG, Subtarget);
9769   case ISD::ADDCARRY:
9770   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
9771   case ISD::SADDO:
9772   case ISD::SSUBO:
9773     return LowerSignedALUO(Op, DAG);
9774   case ISD::UADDO:
9775   case ISD::USUBO:
9776     return LowerUnsignedALUO(Op, DAG);
9777   case ISD::SADDSAT:
9778   case ISD::SSUBSAT:
9779     return LowerSADDSUBSAT(Op, DAG, Subtarget);
9780   case ISD::LOAD:
9781     return LowerPredicateLoad(Op, DAG);
9782   case ISD::STORE:
9783     return LowerSTORE(Op, DAG, Subtarget);
9784   case ISD::MLOAD:
9785     return LowerMLOAD(Op, DAG);
9786   case ISD::VECREDUCE_MUL:
9787   case ISD::VECREDUCE_AND:
9788   case ISD::VECREDUCE_OR:
9789   case ISD::VECREDUCE_XOR:
9790     return LowerVecReduce(Op, DAG, Subtarget);
9791   case ISD::VECREDUCE_FADD:
9792   case ISD::VECREDUCE_FMUL:
9793   case ISD::VECREDUCE_FMIN:
9794   case ISD::VECREDUCE_FMAX:
9795     return LowerVecReduceF(Op, DAG, Subtarget);
9796   case ISD::ATOMIC_LOAD:
9797   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
9798   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
9799   case ISD::SDIVREM:
9800   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
9801   case ISD::DYNAMIC_STACKALLOC:
9802     if (Subtarget->isTargetWindows())
9803       return LowerDYNAMIC_STACKALLOC(Op, DAG);
9804     llvm_unreachable("Don't know how to custom lower this!");
9805   case ISD::STRICT_FP_ROUND:
9806   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
9807   case ISD::STRICT_FP_EXTEND:
9808   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9809   case ISD::STRICT_FSETCC:
9810   case ISD::STRICT_FSETCCS: return LowerFSETCC(Op, DAG);
9811   case ARMISD::WIN__DBZCHK: return SDValue();
9812   }
9813 }
9814 
9815 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9816                                  SelectionDAG &DAG) {
9817   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9818   unsigned Opc = 0;
9819   if (IntNo == Intrinsic::arm_smlald)
9820     Opc = ARMISD::SMLALD;
9821   else if (IntNo == Intrinsic::arm_smlaldx)
9822     Opc = ARMISD::SMLALDX;
9823   else if (IntNo == Intrinsic::arm_smlsld)
9824     Opc = ARMISD::SMLSLD;
9825   else if (IntNo == Intrinsic::arm_smlsldx)
9826     Opc = ARMISD::SMLSLDX;
9827   else
9828     return;
9829 
9830   SDLoc dl(N);
9831   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9832                            N->getOperand(3),
9833                            DAG.getConstant(0, dl, MVT::i32));
9834   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9835                            N->getOperand(3),
9836                            DAG.getConstant(1, dl, MVT::i32));
9837 
9838   SDValue LongMul = DAG.getNode(Opc, dl,
9839                                 DAG.getVTList(MVT::i32, MVT::i32),
9840                                 N->getOperand(1), N->getOperand(2),
9841                                 Lo, Hi);
9842   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64,
9843                                 LongMul.getValue(0), LongMul.getValue(1)));
9844 }
9845 
9846 /// ReplaceNodeResults - Replace the results of node with an illegal result
9847 /// type with new values built out of custom code.
9848 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9849                                            SmallVectorImpl<SDValue> &Results,
9850                                            SelectionDAG &DAG) const {
9851   SDValue Res;
9852   switch (N->getOpcode()) {
9853   default:
9854     llvm_unreachable("Don't know how to custom expand this!");
9855   case ISD::READ_REGISTER:
9856     ExpandREAD_REGISTER(N, Results, DAG);
9857     break;
9858   case ISD::BITCAST:
9859     Res = ExpandBITCAST(N, DAG, Subtarget);
9860     break;
9861   case ISD::SRL:
9862   case ISD::SRA:
9863   case ISD::SHL:
9864     Res = Expand64BitShift(N, DAG, Subtarget);
9865     break;
9866   case ISD::SREM:
9867   case ISD::UREM:
9868     Res = LowerREM(N, DAG);
9869     break;
9870   case ISD::SDIVREM:
9871   case ISD::UDIVREM:
9872     Res = LowerDivRem(SDValue(N, 0), DAG);
9873     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9874     Results.push_back(Res.getValue(0));
9875     Results.push_back(Res.getValue(1));
9876     return;
9877   case ISD::SADDSAT:
9878   case ISD::SSUBSAT:
9879     Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
9880     break;
9881   case ISD::READCYCLECOUNTER:
9882     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9883     return;
9884   case ISD::UDIV:
9885   case ISD::SDIV:
9886     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9887     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9888                              Results);
9889   case ISD::ATOMIC_CMP_SWAP:
9890     ReplaceCMP_SWAP_64Results(N, Results, DAG);
9891     return;
9892   case ISD::INTRINSIC_WO_CHAIN:
9893     return ReplaceLongIntrinsic(N, Results, DAG);
9894   case ISD::ABS:
9895      lowerABS(N, Results, DAG);
9896      return ;
9897   case ISD::LOAD:
9898     LowerLOAD(N, Results, DAG);
9899     break;
9900   }
9901   if (Res.getNode())
9902     Results.push_back(Res);
9903 }
9904 
9905 //===----------------------------------------------------------------------===//
9906 //                           ARM Scheduler Hooks
9907 //===----------------------------------------------------------------------===//
9908 
9909 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9910 /// registers the function context.
9911 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9912                                                MachineBasicBlock *MBB,
9913                                                MachineBasicBlock *DispatchBB,
9914                                                int FI) const {
9915   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9916          "ROPI/RWPI not currently supported with SjLj");
9917   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9918   DebugLoc dl = MI.getDebugLoc();
9919   MachineFunction *MF = MBB->getParent();
9920   MachineRegisterInfo *MRI = &MF->getRegInfo();
9921   MachineConstantPool *MCP = MF->getConstantPool();
9922   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9923   const Function &F = MF->getFunction();
9924 
9925   bool isThumb = Subtarget->isThumb();
9926   bool isThumb2 = Subtarget->isThumb2();
9927 
9928   unsigned PCLabelId = AFI->createPICLabelUId();
9929   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9930   ARMConstantPoolValue *CPV =
9931     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9932   unsigned CPI = MCP->getConstantPoolIndex(CPV, Align(4));
9933 
9934   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9935                                            : &ARM::GPRRegClass;
9936 
9937   // Grab constant pool and fixed stack memory operands.
9938   MachineMemOperand *CPMMO =
9939       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9940                                MachineMemOperand::MOLoad, 4, Align(4));
9941 
9942   MachineMemOperand *FIMMOSt =
9943       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9944                                MachineMemOperand::MOStore, 4, Align(4));
9945 
9946   // Load the address of the dispatch MBB into the jump buffer.
9947   if (isThumb2) {
9948     // Incoming value: jbuf
9949     //   ldr.n  r5, LCPI1_1
9950     //   orr    r5, r5, #1
9951     //   add    r5, pc
9952     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
9953     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9954     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9955         .addConstantPoolIndex(CPI)
9956         .addMemOperand(CPMMO)
9957         .add(predOps(ARMCC::AL));
9958     // Set the low bit because of thumb mode.
9959     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9960     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9961         .addReg(NewVReg1, RegState::Kill)
9962         .addImm(0x01)
9963         .add(predOps(ARMCC::AL))
9964         .add(condCodeOp());
9965     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9966     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9967       .addReg(NewVReg2, RegState::Kill)
9968       .addImm(PCLabelId);
9969     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9970         .addReg(NewVReg3, RegState::Kill)
9971         .addFrameIndex(FI)
9972         .addImm(36) // &jbuf[1] :: pc
9973         .addMemOperand(FIMMOSt)
9974         .add(predOps(ARMCC::AL));
9975   } else if (isThumb) {
9976     // Incoming value: jbuf
9977     //   ldr.n  r1, LCPI1_4
9978     //   add    r1, pc
9979     //   mov    r2, #1
9980     //   orrs   r1, r2
9981     //   add    r2, $jbuf, #+4 ; &jbuf[1]
9982     //   str    r1, [r2]
9983     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9984     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9985         .addConstantPoolIndex(CPI)
9986         .addMemOperand(CPMMO)
9987         .add(predOps(ARMCC::AL));
9988     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9989     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9990       .addReg(NewVReg1, RegState::Kill)
9991       .addImm(PCLabelId);
9992     // Set the low bit because of thumb mode.
9993     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9994     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9995         .addReg(ARM::CPSR, RegState::Define)
9996         .addImm(1)
9997         .add(predOps(ARMCC::AL));
9998     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9999     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
10000         .addReg(ARM::CPSR, RegState::Define)
10001         .addReg(NewVReg2, RegState::Kill)
10002         .addReg(NewVReg3, RegState::Kill)
10003         .add(predOps(ARMCC::AL));
10004     Register NewVReg5 = MRI->createVirtualRegister(TRC);
10005     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
10006             .addFrameIndex(FI)
10007             .addImm(36); // &jbuf[1] :: pc
10008     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
10009         .addReg(NewVReg4, RegState::Kill)
10010         .addReg(NewVReg5, RegState::Kill)
10011         .addImm(0)
10012         .addMemOperand(FIMMOSt)
10013         .add(predOps(ARMCC::AL));
10014   } else {
10015     // Incoming value: jbuf
10016     //   ldr  r1, LCPI1_1
10017     //   add  r1, pc, r1
10018     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
10019     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10020     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
10021         .addConstantPoolIndex(CPI)
10022         .addImm(0)
10023         .addMemOperand(CPMMO)
10024         .add(predOps(ARMCC::AL));
10025     Register NewVReg2 = MRI->createVirtualRegister(TRC);
10026     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
10027         .addReg(NewVReg1, RegState::Kill)
10028         .addImm(PCLabelId)
10029         .add(predOps(ARMCC::AL));
10030     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
10031         .addReg(NewVReg2, RegState::Kill)
10032         .addFrameIndex(FI)
10033         .addImm(36) // &jbuf[1] :: pc
10034         .addMemOperand(FIMMOSt)
10035         .add(predOps(ARMCC::AL));
10036   }
10037 }
10038 
10039 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
10040                                               MachineBasicBlock *MBB) const {
10041   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10042   DebugLoc dl = MI.getDebugLoc();
10043   MachineFunction *MF = MBB->getParent();
10044   MachineRegisterInfo *MRI = &MF->getRegInfo();
10045   MachineFrameInfo &MFI = MF->getFrameInfo();
10046   int FI = MFI.getFunctionContextIndex();
10047 
10048   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
10049                                                         : &ARM::GPRnopcRegClass;
10050 
10051   // Get a mapping of the call site numbers to all of the landing pads they're
10052   // associated with.
10053   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
10054   unsigned MaxCSNum = 0;
10055   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
10056        ++BB) {
10057     if (!BB->isEHPad()) continue;
10058 
10059     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
10060     // pad.
10061     for (MachineBasicBlock::iterator
10062            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
10063       if (!II->isEHLabel()) continue;
10064 
10065       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
10066       if (!MF->hasCallSiteLandingPad(Sym)) continue;
10067 
10068       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
10069       for (SmallVectorImpl<unsigned>::iterator
10070              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
10071            CSI != CSE; ++CSI) {
10072         CallSiteNumToLPad[*CSI].push_back(&*BB);
10073         MaxCSNum = std::max(MaxCSNum, *CSI);
10074       }
10075       break;
10076     }
10077   }
10078 
10079   // Get an ordered list of the machine basic blocks for the jump table.
10080   std::vector<MachineBasicBlock*> LPadList;
10081   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
10082   LPadList.reserve(CallSiteNumToLPad.size());
10083   for (unsigned I = 1; I <= MaxCSNum; ++I) {
10084     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
10085     for (SmallVectorImpl<MachineBasicBlock*>::iterator
10086            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
10087       LPadList.push_back(*II);
10088       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
10089     }
10090   }
10091 
10092   assert(!LPadList.empty() &&
10093          "No landing pad destinations for the dispatch jump table!");
10094 
10095   // Create the jump table and associated information.
10096   MachineJumpTableInfo *JTI =
10097     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
10098   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
10099 
10100   // Create the MBBs for the dispatch code.
10101 
10102   // Shove the dispatch's address into the return slot in the function context.
10103   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
10104   DispatchBB->setIsEHPad();
10105 
10106   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10107   unsigned trap_opcode;
10108   if (Subtarget->isThumb())
10109     trap_opcode = ARM::tTRAP;
10110   else
10111     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
10112 
10113   BuildMI(TrapBB, dl, TII->get(trap_opcode));
10114   DispatchBB->addSuccessor(TrapBB);
10115 
10116   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
10117   DispatchBB->addSuccessor(DispContBB);
10118 
10119   // Insert and MBBs.
10120   MF->insert(MF->end(), DispatchBB);
10121   MF->insert(MF->end(), DispContBB);
10122   MF->insert(MF->end(), TrapBB);
10123 
10124   // Insert code into the entry block that creates and registers the function
10125   // context.
10126   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
10127 
10128   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
10129       MachinePointerInfo::getFixedStack(*MF, FI),
10130       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, Align(4));
10131 
10132   MachineInstrBuilder MIB;
10133   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
10134 
10135   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
10136   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
10137 
10138   // Add a register mask with no preserved registers.  This results in all
10139   // registers being marked as clobbered. This can't work if the dispatch block
10140   // is in a Thumb1 function and is linked with ARM code which uses the FP
10141   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
10142   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
10143 
10144   bool IsPositionIndependent = isPositionIndependent();
10145   unsigned NumLPads = LPadList.size();
10146   if (Subtarget->isThumb2()) {
10147     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10148     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
10149         .addFrameIndex(FI)
10150         .addImm(4)
10151         .addMemOperand(FIMMOLd)
10152         .add(predOps(ARMCC::AL));
10153 
10154     if (NumLPads < 256) {
10155       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
10156           .addReg(NewVReg1)
10157           .addImm(LPadList.size())
10158           .add(predOps(ARMCC::AL));
10159     } else {
10160       Register VReg1 = MRI->createVirtualRegister(TRC);
10161       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
10162           .addImm(NumLPads & 0xFFFF)
10163           .add(predOps(ARMCC::AL));
10164 
10165       unsigned VReg2 = VReg1;
10166       if ((NumLPads & 0xFFFF0000) != 0) {
10167         VReg2 = MRI->createVirtualRegister(TRC);
10168         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
10169             .addReg(VReg1)
10170             .addImm(NumLPads >> 16)
10171             .add(predOps(ARMCC::AL));
10172       }
10173 
10174       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
10175           .addReg(NewVReg1)
10176           .addReg(VReg2)
10177           .add(predOps(ARMCC::AL));
10178     }
10179 
10180     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
10181       .addMBB(TrapBB)
10182       .addImm(ARMCC::HI)
10183       .addReg(ARM::CPSR);
10184 
10185     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10186     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
10187         .addJumpTableIndex(MJTI)
10188         .add(predOps(ARMCC::AL));
10189 
10190     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10191     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
10192         .addReg(NewVReg3, RegState::Kill)
10193         .addReg(NewVReg1)
10194         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10195         .add(predOps(ARMCC::AL))
10196         .add(condCodeOp());
10197 
10198     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
10199       .addReg(NewVReg4, RegState::Kill)
10200       .addReg(NewVReg1)
10201       .addJumpTableIndex(MJTI);
10202   } else if (Subtarget->isThumb()) {
10203     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10204     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
10205         .addFrameIndex(FI)
10206         .addImm(1)
10207         .addMemOperand(FIMMOLd)
10208         .add(predOps(ARMCC::AL));
10209 
10210     if (NumLPads < 256) {
10211       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
10212           .addReg(NewVReg1)
10213           .addImm(NumLPads)
10214           .add(predOps(ARMCC::AL));
10215     } else {
10216       MachineConstantPool *ConstantPool = MF->getConstantPool();
10217       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10218       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10219 
10220       // MachineConstantPool wants an explicit alignment.
10221       Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10222       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10223 
10224       Register VReg1 = MRI->createVirtualRegister(TRC);
10225       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
10226           .addReg(VReg1, RegState::Define)
10227           .addConstantPoolIndex(Idx)
10228           .add(predOps(ARMCC::AL));
10229       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
10230           .addReg(NewVReg1)
10231           .addReg(VReg1)
10232           .add(predOps(ARMCC::AL));
10233     }
10234 
10235     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
10236       .addMBB(TrapBB)
10237       .addImm(ARMCC::HI)
10238       .addReg(ARM::CPSR);
10239 
10240     Register NewVReg2 = MRI->createVirtualRegister(TRC);
10241     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
10242         .addReg(ARM::CPSR, RegState::Define)
10243         .addReg(NewVReg1)
10244         .addImm(2)
10245         .add(predOps(ARMCC::AL));
10246 
10247     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10248     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
10249         .addJumpTableIndex(MJTI)
10250         .add(predOps(ARMCC::AL));
10251 
10252     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10253     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
10254         .addReg(ARM::CPSR, RegState::Define)
10255         .addReg(NewVReg2, RegState::Kill)
10256         .addReg(NewVReg3)
10257         .add(predOps(ARMCC::AL));
10258 
10259     MachineMemOperand *JTMMOLd =
10260         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10261                                  MachineMemOperand::MOLoad, 4, Align(4));
10262 
10263     Register NewVReg5 = MRI->createVirtualRegister(TRC);
10264     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
10265         .addReg(NewVReg4, RegState::Kill)
10266         .addImm(0)
10267         .addMemOperand(JTMMOLd)
10268         .add(predOps(ARMCC::AL));
10269 
10270     unsigned NewVReg6 = NewVReg5;
10271     if (IsPositionIndependent) {
10272       NewVReg6 = MRI->createVirtualRegister(TRC);
10273       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
10274           .addReg(ARM::CPSR, RegState::Define)
10275           .addReg(NewVReg5, RegState::Kill)
10276           .addReg(NewVReg3)
10277           .add(predOps(ARMCC::AL));
10278     }
10279 
10280     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
10281       .addReg(NewVReg6, RegState::Kill)
10282       .addJumpTableIndex(MJTI);
10283   } else {
10284     Register NewVReg1 = MRI->createVirtualRegister(TRC);
10285     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
10286         .addFrameIndex(FI)
10287         .addImm(4)
10288         .addMemOperand(FIMMOLd)
10289         .add(predOps(ARMCC::AL));
10290 
10291     if (NumLPads < 256) {
10292       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
10293           .addReg(NewVReg1)
10294           .addImm(NumLPads)
10295           .add(predOps(ARMCC::AL));
10296     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
10297       Register VReg1 = MRI->createVirtualRegister(TRC);
10298       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
10299           .addImm(NumLPads & 0xFFFF)
10300           .add(predOps(ARMCC::AL));
10301 
10302       unsigned VReg2 = VReg1;
10303       if ((NumLPads & 0xFFFF0000) != 0) {
10304         VReg2 = MRI->createVirtualRegister(TRC);
10305         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
10306             .addReg(VReg1)
10307             .addImm(NumLPads >> 16)
10308             .add(predOps(ARMCC::AL));
10309       }
10310 
10311       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10312           .addReg(NewVReg1)
10313           .addReg(VReg2)
10314           .add(predOps(ARMCC::AL));
10315     } else {
10316       MachineConstantPool *ConstantPool = MF->getConstantPool();
10317       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10318       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
10319 
10320       // MachineConstantPool wants an explicit alignment.
10321       Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10322       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10323 
10324       Register VReg1 = MRI->createVirtualRegister(TRC);
10325       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
10326           .addReg(VReg1, RegState::Define)
10327           .addConstantPoolIndex(Idx)
10328           .addImm(0)
10329           .add(predOps(ARMCC::AL));
10330       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
10331           .addReg(NewVReg1)
10332           .addReg(VReg1, RegState::Kill)
10333           .add(predOps(ARMCC::AL));
10334     }
10335 
10336     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
10337       .addMBB(TrapBB)
10338       .addImm(ARMCC::HI)
10339       .addReg(ARM::CPSR);
10340 
10341     Register NewVReg3 = MRI->createVirtualRegister(TRC);
10342     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
10343         .addReg(NewVReg1)
10344         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
10345         .add(predOps(ARMCC::AL))
10346         .add(condCodeOp());
10347     Register NewVReg4 = MRI->createVirtualRegister(TRC);
10348     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
10349         .addJumpTableIndex(MJTI)
10350         .add(predOps(ARMCC::AL));
10351 
10352     MachineMemOperand *JTMMOLd =
10353         MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(*MF),
10354                                  MachineMemOperand::MOLoad, 4, Align(4));
10355     Register NewVReg5 = MRI->createVirtualRegister(TRC);
10356     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
10357         .addReg(NewVReg3, RegState::Kill)
10358         .addReg(NewVReg4)
10359         .addImm(0)
10360         .addMemOperand(JTMMOLd)
10361         .add(predOps(ARMCC::AL));
10362 
10363     if (IsPositionIndependent) {
10364       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
10365         .addReg(NewVReg5, RegState::Kill)
10366         .addReg(NewVReg4)
10367         .addJumpTableIndex(MJTI);
10368     } else {
10369       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
10370         .addReg(NewVReg5, RegState::Kill)
10371         .addJumpTableIndex(MJTI);
10372     }
10373   }
10374 
10375   // Add the jump table entries as successors to the MBB.
10376   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
10377   for (std::vector<MachineBasicBlock*>::iterator
10378          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
10379     MachineBasicBlock *CurMBB = *I;
10380     if (SeenMBBs.insert(CurMBB).second)
10381       DispContBB->addSuccessor(CurMBB);
10382   }
10383 
10384   // N.B. the order the invoke BBs are processed in doesn't matter here.
10385   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
10386   SmallVector<MachineBasicBlock*, 64> MBBLPads;
10387   for (MachineBasicBlock *BB : InvokeBBs) {
10388 
10389     // Remove the landing pad successor from the invoke block and replace it
10390     // with the new dispatch block.
10391     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
10392                                                   BB->succ_end());
10393     while (!Successors.empty()) {
10394       MachineBasicBlock *SMBB = Successors.pop_back_val();
10395       if (SMBB->isEHPad()) {
10396         BB->removeSuccessor(SMBB);
10397         MBBLPads.push_back(SMBB);
10398       }
10399     }
10400 
10401     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
10402     BB->normalizeSuccProbs();
10403 
10404     // Find the invoke call and mark all of the callee-saved registers as
10405     // 'implicit defined' so that they're spilled. This prevents code from
10406     // moving instructions to before the EH block, where they will never be
10407     // executed.
10408     for (MachineBasicBlock::reverse_iterator
10409            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
10410       if (!II->isCall()) continue;
10411 
10412       DenseMap<unsigned, bool> DefRegs;
10413       for (MachineInstr::mop_iterator
10414              OI = II->operands_begin(), OE = II->operands_end();
10415            OI != OE; ++OI) {
10416         if (!OI->isReg()) continue;
10417         DefRegs[OI->getReg()] = true;
10418       }
10419 
10420       MachineInstrBuilder MIB(*MF, &*II);
10421 
10422       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
10423         unsigned Reg = SavedRegs[i];
10424         if (Subtarget->isThumb2() &&
10425             !ARM::tGPRRegClass.contains(Reg) &&
10426             !ARM::hGPRRegClass.contains(Reg))
10427           continue;
10428         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
10429           continue;
10430         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
10431           continue;
10432         if (!DefRegs[Reg])
10433           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
10434       }
10435 
10436       break;
10437     }
10438   }
10439 
10440   // Mark all former landing pads as non-landing pads. The dispatch is the only
10441   // landing pad now.
10442   for (SmallVectorImpl<MachineBasicBlock*>::iterator
10443          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
10444     (*I)->setIsEHPad(false);
10445 
10446   // The instruction is gone now.
10447   MI.eraseFromParent();
10448 }
10449 
10450 static
10451 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
10452   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
10453        E = MBB->succ_end(); I != E; ++I)
10454     if (*I != Succ)
10455       return *I;
10456   llvm_unreachable("Expecting a BB with two successors!");
10457 }
10458 
10459 /// Return the load opcode for a given load size. If load size >= 8,
10460 /// neon opcode will be returned.
10461 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
10462   if (LdSize >= 8)
10463     return LdSize == 16 ? ARM::VLD1q32wb_fixed
10464                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
10465   if (IsThumb1)
10466     return LdSize == 4 ? ARM::tLDRi
10467                        : LdSize == 2 ? ARM::tLDRHi
10468                                      : LdSize == 1 ? ARM::tLDRBi : 0;
10469   if (IsThumb2)
10470     return LdSize == 4 ? ARM::t2LDR_POST
10471                        : LdSize == 2 ? ARM::t2LDRH_POST
10472                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
10473   return LdSize == 4 ? ARM::LDR_POST_IMM
10474                      : LdSize == 2 ? ARM::LDRH_POST
10475                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
10476 }
10477 
10478 /// Return the store opcode for a given store size. If store size >= 8,
10479 /// neon opcode will be returned.
10480 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
10481   if (StSize >= 8)
10482     return StSize == 16 ? ARM::VST1q32wb_fixed
10483                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
10484   if (IsThumb1)
10485     return StSize == 4 ? ARM::tSTRi
10486                        : StSize == 2 ? ARM::tSTRHi
10487                                      : StSize == 1 ? ARM::tSTRBi : 0;
10488   if (IsThumb2)
10489     return StSize == 4 ? ARM::t2STR_POST
10490                        : StSize == 2 ? ARM::t2STRH_POST
10491                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
10492   return StSize == 4 ? ARM::STR_POST_IMM
10493                      : StSize == 2 ? ARM::STRH_POST
10494                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
10495 }
10496 
10497 /// Emit a post-increment load operation with given size. The instructions
10498 /// will be added to BB at Pos.
10499 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10500                        const TargetInstrInfo *TII, const DebugLoc &dl,
10501                        unsigned LdSize, unsigned Data, unsigned AddrIn,
10502                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10503   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
10504   assert(LdOpc != 0 && "Should have a load opcode");
10505   if (LdSize >= 8) {
10506     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10507         .addReg(AddrOut, RegState::Define)
10508         .addReg(AddrIn)
10509         .addImm(0)
10510         .add(predOps(ARMCC::AL));
10511   } else if (IsThumb1) {
10512     // load + update AddrIn
10513     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10514         .addReg(AddrIn)
10515         .addImm(0)
10516         .add(predOps(ARMCC::AL));
10517     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10518         .add(t1CondCodeOp())
10519         .addReg(AddrIn)
10520         .addImm(LdSize)
10521         .add(predOps(ARMCC::AL));
10522   } else if (IsThumb2) {
10523     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10524         .addReg(AddrOut, RegState::Define)
10525         .addReg(AddrIn)
10526         .addImm(LdSize)
10527         .add(predOps(ARMCC::AL));
10528   } else { // arm
10529     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10530         .addReg(AddrOut, RegState::Define)
10531         .addReg(AddrIn)
10532         .addReg(0)
10533         .addImm(LdSize)
10534         .add(predOps(ARMCC::AL));
10535   }
10536 }
10537 
10538 /// Emit a post-increment store operation with given size. The instructions
10539 /// will be added to BB at Pos.
10540 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10541                        const TargetInstrInfo *TII, const DebugLoc &dl,
10542                        unsigned StSize, unsigned Data, unsigned AddrIn,
10543                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10544   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
10545   assert(StOpc != 0 && "Should have a store opcode");
10546   if (StSize >= 8) {
10547     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10548         .addReg(AddrIn)
10549         .addImm(0)
10550         .addReg(Data)
10551         .add(predOps(ARMCC::AL));
10552   } else if (IsThumb1) {
10553     // store + update AddrIn
10554     BuildMI(*BB, Pos, dl, TII->get(StOpc))
10555         .addReg(Data)
10556         .addReg(AddrIn)
10557         .addImm(0)
10558         .add(predOps(ARMCC::AL));
10559     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10560         .add(t1CondCodeOp())
10561         .addReg(AddrIn)
10562         .addImm(StSize)
10563         .add(predOps(ARMCC::AL));
10564   } else if (IsThumb2) {
10565     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10566         .addReg(Data)
10567         .addReg(AddrIn)
10568         .addImm(StSize)
10569         .add(predOps(ARMCC::AL));
10570   } else { // arm
10571     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10572         .addReg(Data)
10573         .addReg(AddrIn)
10574         .addReg(0)
10575         .addImm(StSize)
10576         .add(predOps(ARMCC::AL));
10577   }
10578 }
10579 
10580 MachineBasicBlock *
10581 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
10582                                    MachineBasicBlock *BB) const {
10583   // This pseudo instruction has 3 operands: dst, src, size
10584   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
10585   // Otherwise, we will generate unrolled scalar copies.
10586   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10587   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10588   MachineFunction::iterator It = ++BB->getIterator();
10589 
10590   Register dest = MI.getOperand(0).getReg();
10591   Register src = MI.getOperand(1).getReg();
10592   unsigned SizeVal = MI.getOperand(2).getImm();
10593   unsigned Alignment = MI.getOperand(3).getImm();
10594   DebugLoc dl = MI.getDebugLoc();
10595 
10596   MachineFunction *MF = BB->getParent();
10597   MachineRegisterInfo &MRI = MF->getRegInfo();
10598   unsigned UnitSize = 0;
10599   const TargetRegisterClass *TRC = nullptr;
10600   const TargetRegisterClass *VecTRC = nullptr;
10601 
10602   bool IsThumb1 = Subtarget->isThumb1Only();
10603   bool IsThumb2 = Subtarget->isThumb2();
10604   bool IsThumb = Subtarget->isThumb();
10605 
10606   if (Alignment & 1) {
10607     UnitSize = 1;
10608   } else if (Alignment & 2) {
10609     UnitSize = 2;
10610   } else {
10611     // Check whether we can use NEON instructions.
10612     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
10613         Subtarget->hasNEON()) {
10614       if ((Alignment % 16 == 0) && SizeVal >= 16)
10615         UnitSize = 16;
10616       else if ((Alignment % 8 == 0) && SizeVal >= 8)
10617         UnitSize = 8;
10618     }
10619     // Can't use NEON instructions.
10620     if (UnitSize == 0)
10621       UnitSize = 4;
10622   }
10623 
10624   // Select the correct opcode and register class for unit size load/store
10625   bool IsNeon = UnitSize >= 8;
10626   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
10627   if (IsNeon)
10628     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
10629                             : UnitSize == 8 ? &ARM::DPRRegClass
10630                                             : nullptr;
10631 
10632   unsigned BytesLeft = SizeVal % UnitSize;
10633   unsigned LoopSize = SizeVal - BytesLeft;
10634 
10635   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
10636     // Use LDR and STR to copy.
10637     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
10638     // [destOut] = STR_POST(scratch, destIn, UnitSize)
10639     unsigned srcIn = src;
10640     unsigned destIn = dest;
10641     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
10642       Register srcOut = MRI.createVirtualRegister(TRC);
10643       Register destOut = MRI.createVirtualRegister(TRC);
10644       Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10645       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
10646                  IsThumb1, IsThumb2);
10647       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
10648                  IsThumb1, IsThumb2);
10649       srcIn = srcOut;
10650       destIn = destOut;
10651     }
10652 
10653     // Handle the leftover bytes with LDRB and STRB.
10654     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
10655     // [destOut] = STRB_POST(scratch, destIn, 1)
10656     for (unsigned i = 0; i < BytesLeft; i++) {
10657       Register srcOut = MRI.createVirtualRegister(TRC);
10658       Register destOut = MRI.createVirtualRegister(TRC);
10659       Register scratch = MRI.createVirtualRegister(TRC);
10660       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
10661                  IsThumb1, IsThumb2);
10662       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
10663                  IsThumb1, IsThumb2);
10664       srcIn = srcOut;
10665       destIn = destOut;
10666     }
10667     MI.eraseFromParent(); // The instruction is gone now.
10668     return BB;
10669   }
10670 
10671   // Expand the pseudo op to a loop.
10672   // thisMBB:
10673   //   ...
10674   //   movw varEnd, # --> with thumb2
10675   //   movt varEnd, #
10676   //   ldrcp varEnd, idx --> without thumb2
10677   //   fallthrough --> loopMBB
10678   // loopMBB:
10679   //   PHI varPhi, varEnd, varLoop
10680   //   PHI srcPhi, src, srcLoop
10681   //   PHI destPhi, dst, destLoop
10682   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10683   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
10684   //   subs varLoop, varPhi, #UnitSize
10685   //   bne loopMBB
10686   //   fallthrough --> exitMBB
10687   // exitMBB:
10688   //   epilogue to handle left-over bytes
10689   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10690   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10691   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10692   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10693   MF->insert(It, loopMBB);
10694   MF->insert(It, exitMBB);
10695 
10696   // Transfer the remainder of BB and its successor edges to exitMBB.
10697   exitMBB->splice(exitMBB->begin(), BB,
10698                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10699   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10700 
10701   // Load an immediate to varEnd.
10702   Register varEnd = MRI.createVirtualRegister(TRC);
10703   if (Subtarget->useMovt()) {
10704     unsigned Vtmp = varEnd;
10705     if ((LoopSize & 0xFFFF0000) != 0)
10706       Vtmp = MRI.createVirtualRegister(TRC);
10707     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
10708         .addImm(LoopSize & 0xFFFF)
10709         .add(predOps(ARMCC::AL));
10710 
10711     if ((LoopSize & 0xFFFF0000) != 0)
10712       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
10713           .addReg(Vtmp)
10714           .addImm(LoopSize >> 16)
10715           .add(predOps(ARMCC::AL));
10716   } else {
10717     MachineConstantPool *ConstantPool = MF->getConstantPool();
10718     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10719     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
10720 
10721     // MachineConstantPool wants an explicit alignment.
10722     Align Alignment = MF->getDataLayout().getPrefTypeAlign(Int32Ty);
10723     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Alignment);
10724     MachineMemOperand *CPMMO =
10725         MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10726                                  MachineMemOperand::MOLoad, 4, Align(4));
10727 
10728     if (IsThumb)
10729       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
10730           .addReg(varEnd, RegState::Define)
10731           .addConstantPoolIndex(Idx)
10732           .add(predOps(ARMCC::AL))
10733           .addMemOperand(CPMMO);
10734     else
10735       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
10736           .addReg(varEnd, RegState::Define)
10737           .addConstantPoolIndex(Idx)
10738           .addImm(0)
10739           .add(predOps(ARMCC::AL))
10740           .addMemOperand(CPMMO);
10741   }
10742   BB->addSuccessor(loopMBB);
10743 
10744   // Generate the loop body:
10745   //   varPhi = PHI(varLoop, varEnd)
10746   //   srcPhi = PHI(srcLoop, src)
10747   //   destPhi = PHI(destLoop, dst)
10748   MachineBasicBlock *entryBB = BB;
10749   BB = loopMBB;
10750   Register varLoop = MRI.createVirtualRegister(TRC);
10751   Register varPhi = MRI.createVirtualRegister(TRC);
10752   Register srcLoop = MRI.createVirtualRegister(TRC);
10753   Register srcPhi = MRI.createVirtualRegister(TRC);
10754   Register destLoop = MRI.createVirtualRegister(TRC);
10755   Register destPhi = MRI.createVirtualRegister(TRC);
10756 
10757   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
10758     .addReg(varLoop).addMBB(loopMBB)
10759     .addReg(varEnd).addMBB(entryBB);
10760   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
10761     .addReg(srcLoop).addMBB(loopMBB)
10762     .addReg(src).addMBB(entryBB);
10763   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
10764     .addReg(destLoop).addMBB(loopMBB)
10765     .addReg(dest).addMBB(entryBB);
10766 
10767   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10768   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
10769   Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10770   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
10771              IsThumb1, IsThumb2);
10772   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
10773              IsThumb1, IsThumb2);
10774 
10775   // Decrement loop variable by UnitSize.
10776   if (IsThumb1) {
10777     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
10778         .add(t1CondCodeOp())
10779         .addReg(varPhi)
10780         .addImm(UnitSize)
10781         .add(predOps(ARMCC::AL));
10782   } else {
10783     MachineInstrBuilder MIB =
10784         BuildMI(*BB, BB->end(), dl,
10785                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
10786     MIB.addReg(varPhi)
10787         .addImm(UnitSize)
10788         .add(predOps(ARMCC::AL))
10789         .add(condCodeOp());
10790     MIB->getOperand(5).setReg(ARM::CPSR);
10791     MIB->getOperand(5).setIsDef(true);
10792   }
10793   BuildMI(*BB, BB->end(), dl,
10794           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
10795       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
10796 
10797   // loopMBB can loop back to loopMBB or fall through to exitMBB.
10798   BB->addSuccessor(loopMBB);
10799   BB->addSuccessor(exitMBB);
10800 
10801   // Add epilogue to handle BytesLeft.
10802   BB = exitMBB;
10803   auto StartOfExit = exitMBB->begin();
10804 
10805   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10806   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10807   unsigned srcIn = srcLoop;
10808   unsigned destIn = destLoop;
10809   for (unsigned i = 0; i < BytesLeft; i++) {
10810     Register srcOut = MRI.createVirtualRegister(TRC);
10811     Register destOut = MRI.createVirtualRegister(TRC);
10812     Register scratch = MRI.createVirtualRegister(TRC);
10813     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
10814                IsThumb1, IsThumb2);
10815     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10816                IsThumb1, IsThumb2);
10817     srcIn = srcOut;
10818     destIn = destOut;
10819   }
10820 
10821   MI.eraseFromParent(); // The instruction is gone now.
10822   return BB;
10823 }
10824 
10825 MachineBasicBlock *
10826 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10827                                        MachineBasicBlock *MBB) const {
10828   const TargetMachine &TM = getTargetMachine();
10829   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10830   DebugLoc DL = MI.getDebugLoc();
10831 
10832   assert(Subtarget->isTargetWindows() &&
10833          "__chkstk is only supported on Windows");
10834   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10835 
10836   // __chkstk takes the number of words to allocate on the stack in R4, and
10837   // returns the stack adjustment in number of bytes in R4.  This will not
10838   // clober any other registers (other than the obvious lr).
10839   //
10840   // Although, technically, IP should be considered a register which may be
10841   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
10842   // thumb-2 environment, so there is no interworking required.  As a result, we
10843   // do not expect a veneer to be emitted by the linker, clobbering IP.
10844   //
10845   // Each module receives its own copy of __chkstk, so no import thunk is
10846   // required, again, ensuring that IP is not clobbered.
10847   //
10848   // Finally, although some linkers may theoretically provide a trampoline for
10849   // out of range calls (which is quite common due to a 32M range limitation of
10850   // branches for Thumb), we can generate the long-call version via
10851   // -mcmodel=large, alleviating the need for the trampoline which may clobber
10852   // IP.
10853 
10854   switch (TM.getCodeModel()) {
10855   case CodeModel::Tiny:
10856     llvm_unreachable("Tiny code model not available on ARM.");
10857   case CodeModel::Small:
10858   case CodeModel::Medium:
10859   case CodeModel::Kernel:
10860     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10861         .add(predOps(ARMCC::AL))
10862         .addExternalSymbol("__chkstk")
10863         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10864         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10865         .addReg(ARM::R12,
10866                 RegState::Implicit | RegState::Define | RegState::Dead)
10867         .addReg(ARM::CPSR,
10868                 RegState::Implicit | RegState::Define | RegState::Dead);
10869     break;
10870   case CodeModel::Large: {
10871     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10872     Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10873 
10874     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10875       .addExternalSymbol("__chkstk");
10876     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10877         .add(predOps(ARMCC::AL))
10878         .addReg(Reg, RegState::Kill)
10879         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10880         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10881         .addReg(ARM::R12,
10882                 RegState::Implicit | RegState::Define | RegState::Dead)
10883         .addReg(ARM::CPSR,
10884                 RegState::Implicit | RegState::Define | RegState::Dead);
10885     break;
10886   }
10887   }
10888 
10889   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10890       .addReg(ARM::SP, RegState::Kill)
10891       .addReg(ARM::R4, RegState::Kill)
10892       .setMIFlags(MachineInstr::FrameSetup)
10893       .add(predOps(ARMCC::AL))
10894       .add(condCodeOp());
10895 
10896   MI.eraseFromParent();
10897   return MBB;
10898 }
10899 
10900 MachineBasicBlock *
10901 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10902                                        MachineBasicBlock *MBB) const {
10903   DebugLoc DL = MI.getDebugLoc();
10904   MachineFunction *MF = MBB->getParent();
10905   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10906 
10907   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10908   MF->insert(++MBB->getIterator(), ContBB);
10909   ContBB->splice(ContBB->begin(), MBB,
10910                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10911   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10912   MBB->addSuccessor(ContBB);
10913 
10914   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10915   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10916   MF->push_back(TrapBB);
10917   MBB->addSuccessor(TrapBB);
10918 
10919   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10920       .addReg(MI.getOperand(0).getReg())
10921       .addImm(0)
10922       .add(predOps(ARMCC::AL));
10923   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10924       .addMBB(TrapBB)
10925       .addImm(ARMCC::EQ)
10926       .addReg(ARM::CPSR);
10927 
10928   MI.eraseFromParent();
10929   return ContBB;
10930 }
10931 
10932 // The CPSR operand of SelectItr might be missing a kill marker
10933 // because there were multiple uses of CPSR, and ISel didn't know
10934 // which to mark. Figure out whether SelectItr should have had a
10935 // kill marker, and set it if it should. Returns the correct kill
10936 // marker value.
10937 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10938                                    MachineBasicBlock* BB,
10939                                    const TargetRegisterInfo* TRI) {
10940   // Scan forward through BB for a use/def of CPSR.
10941   MachineBasicBlock::iterator miI(std::next(SelectItr));
10942   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10943     const MachineInstr& mi = *miI;
10944     if (mi.readsRegister(ARM::CPSR))
10945       return false;
10946     if (mi.definesRegister(ARM::CPSR))
10947       break; // Should have kill-flag - update below.
10948   }
10949 
10950   // If we hit the end of the block, check whether CPSR is live into a
10951   // successor.
10952   if (miI == BB->end()) {
10953     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10954                                           sEnd = BB->succ_end();
10955          sItr != sEnd; ++sItr) {
10956       MachineBasicBlock* succ = *sItr;
10957       if (succ->isLiveIn(ARM::CPSR))
10958         return false;
10959     }
10960   }
10961 
10962   // We found a def, or hit the end of the basic block and CPSR wasn't live
10963   // out. SelectMI should have a kill flag on CPSR.
10964   SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10965   return true;
10966 }
10967 
10968 MachineBasicBlock *
10969 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10970                                                MachineBasicBlock *BB) const {
10971   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10972   DebugLoc dl = MI.getDebugLoc();
10973   bool isThumb2 = Subtarget->isThumb2();
10974   switch (MI.getOpcode()) {
10975   default: {
10976     MI.print(errs());
10977     llvm_unreachable("Unexpected instr type to insert");
10978   }
10979 
10980   // Thumb1 post-indexed loads are really just single-register LDMs.
10981   case ARM::tLDR_postidx: {
10982     MachineOperand Def(MI.getOperand(1));
10983     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10984         .add(Def)  // Rn_wb
10985         .add(MI.getOperand(2))  // Rn
10986         .add(MI.getOperand(3))  // PredImm
10987         .add(MI.getOperand(4))  // PredReg
10988         .add(MI.getOperand(0))  // Rt
10989         .cloneMemRefs(MI);
10990     MI.eraseFromParent();
10991     return BB;
10992   }
10993 
10994   // The Thumb2 pre-indexed stores have the same MI operands, they just
10995   // define them differently in the .td files from the isel patterns, so
10996   // they need pseudos.
10997   case ARM::t2STR_preidx:
10998     MI.setDesc(TII->get(ARM::t2STR_PRE));
10999     return BB;
11000   case ARM::t2STRB_preidx:
11001     MI.setDesc(TII->get(ARM::t2STRB_PRE));
11002     return BB;
11003   case ARM::t2STRH_preidx:
11004     MI.setDesc(TII->get(ARM::t2STRH_PRE));
11005     return BB;
11006 
11007   case ARM::STRi_preidx:
11008   case ARM::STRBi_preidx: {
11009     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
11010                                                          : ARM::STRB_PRE_IMM;
11011     // Decode the offset.
11012     unsigned Offset = MI.getOperand(4).getImm();
11013     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
11014     Offset = ARM_AM::getAM2Offset(Offset);
11015     if (isSub)
11016       Offset = -Offset;
11017 
11018     MachineMemOperand *MMO = *MI.memoperands_begin();
11019     BuildMI(*BB, MI, dl, TII->get(NewOpc))
11020         .add(MI.getOperand(0)) // Rn_wb
11021         .add(MI.getOperand(1)) // Rt
11022         .add(MI.getOperand(2)) // Rn
11023         .addImm(Offset)        // offset (skip GPR==zero_reg)
11024         .add(MI.getOperand(5)) // pred
11025         .add(MI.getOperand(6))
11026         .addMemOperand(MMO);
11027     MI.eraseFromParent();
11028     return BB;
11029   }
11030   case ARM::STRr_preidx:
11031   case ARM::STRBr_preidx:
11032   case ARM::STRH_preidx: {
11033     unsigned NewOpc;
11034     switch (MI.getOpcode()) {
11035     default: llvm_unreachable("unexpected opcode!");
11036     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
11037     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
11038     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
11039     }
11040     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
11041     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
11042       MIB.add(MI.getOperand(i));
11043     MI.eraseFromParent();
11044     return BB;
11045   }
11046 
11047   case ARM::tMOVCCr_pseudo: {
11048     // To "insert" a SELECT_CC instruction, we actually have to insert the
11049     // diamond control-flow pattern.  The incoming instruction knows the
11050     // destination vreg to set, the condition code register to branch on, the
11051     // true/false values to select between, and a branch opcode to use.
11052     const BasicBlock *LLVM_BB = BB->getBasicBlock();
11053     MachineFunction::iterator It = ++BB->getIterator();
11054 
11055     //  thisMBB:
11056     //  ...
11057     //   TrueVal = ...
11058     //   cmpTY ccX, r1, r2
11059     //   bCC copy1MBB
11060     //   fallthrough --> copy0MBB
11061     MachineBasicBlock *thisMBB  = BB;
11062     MachineFunction *F = BB->getParent();
11063     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11064     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
11065     F->insert(It, copy0MBB);
11066     F->insert(It, sinkMBB);
11067 
11068     // Check whether CPSR is live past the tMOVCCr_pseudo.
11069     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
11070     if (!MI.killsRegister(ARM::CPSR) &&
11071         !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
11072       copy0MBB->addLiveIn(ARM::CPSR);
11073       sinkMBB->addLiveIn(ARM::CPSR);
11074     }
11075 
11076     // Transfer the remainder of BB and its successor edges to sinkMBB.
11077     sinkMBB->splice(sinkMBB->begin(), BB,
11078                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11079     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11080 
11081     BB->addSuccessor(copy0MBB);
11082     BB->addSuccessor(sinkMBB);
11083 
11084     BuildMI(BB, dl, TII->get(ARM::tBcc))
11085         .addMBB(sinkMBB)
11086         .addImm(MI.getOperand(3).getImm())
11087         .addReg(MI.getOperand(4).getReg());
11088 
11089     //  copy0MBB:
11090     //   %FalseValue = ...
11091     //   # fallthrough to sinkMBB
11092     BB = copy0MBB;
11093 
11094     // Update machine-CFG edges
11095     BB->addSuccessor(sinkMBB);
11096 
11097     //  sinkMBB:
11098     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11099     //  ...
11100     BB = sinkMBB;
11101     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
11102         .addReg(MI.getOperand(1).getReg())
11103         .addMBB(copy0MBB)
11104         .addReg(MI.getOperand(2).getReg())
11105         .addMBB(thisMBB);
11106 
11107     MI.eraseFromParent(); // The pseudo instruction is gone now.
11108     return BB;
11109   }
11110 
11111   case ARM::BCCi64:
11112   case ARM::BCCZi64: {
11113     // If there is an unconditional branch to the other successor, remove it.
11114     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
11115 
11116     // Compare both parts that make up the double comparison separately for
11117     // equality.
11118     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
11119 
11120     Register LHS1 = MI.getOperand(1).getReg();
11121     Register LHS2 = MI.getOperand(2).getReg();
11122     if (RHSisZero) {
11123       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11124           .addReg(LHS1)
11125           .addImm(0)
11126           .add(predOps(ARMCC::AL));
11127       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11128         .addReg(LHS2).addImm(0)
11129         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
11130     } else {
11131       Register RHS1 = MI.getOperand(3).getReg();
11132       Register RHS2 = MI.getOperand(4).getReg();
11133       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
11134           .addReg(LHS1)
11135           .addReg(RHS1)
11136           .add(predOps(ARMCC::AL));
11137       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
11138         .addReg(LHS2).addReg(RHS2)
11139         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
11140     }
11141 
11142     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
11143     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
11144     if (MI.getOperand(0).getImm() == ARMCC::NE)
11145       std::swap(destMBB, exitMBB);
11146 
11147     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
11148       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
11149     if (isThumb2)
11150       BuildMI(BB, dl, TII->get(ARM::t2B))
11151           .addMBB(exitMBB)
11152           .add(predOps(ARMCC::AL));
11153     else
11154       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
11155 
11156     MI.eraseFromParent(); // The pseudo instruction is gone now.
11157     return BB;
11158   }
11159 
11160   case ARM::Int_eh_sjlj_setjmp:
11161   case ARM::Int_eh_sjlj_setjmp_nofp:
11162   case ARM::tInt_eh_sjlj_setjmp:
11163   case ARM::t2Int_eh_sjlj_setjmp:
11164   case ARM::t2Int_eh_sjlj_setjmp_nofp:
11165     return BB;
11166 
11167   case ARM::Int_eh_sjlj_setup_dispatch:
11168     EmitSjLjDispatchBlock(MI, BB);
11169     return BB;
11170 
11171   case ARM::ABS:
11172   case ARM::t2ABS: {
11173     // To insert an ABS instruction, we have to insert the
11174     // diamond control-flow pattern.  The incoming instruction knows the
11175     // source vreg to test against 0, the destination vreg to set,
11176     // the condition code register to branch on, the
11177     // true/false values to select between, and a branch opcode to use.
11178     // It transforms
11179     //     V1 = ABS V0
11180     // into
11181     //     V2 = MOVS V0
11182     //     BCC                      (branch to SinkBB if V0 >= 0)
11183     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
11184     //     SinkBB: V1 = PHI(V2, V3)
11185     const BasicBlock *LLVM_BB = BB->getBasicBlock();
11186     MachineFunction::iterator BBI = ++BB->getIterator();
11187     MachineFunction *Fn = BB->getParent();
11188     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
11189     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
11190     Fn->insert(BBI, RSBBB);
11191     Fn->insert(BBI, SinkBB);
11192 
11193     Register ABSSrcReg = MI.getOperand(1).getReg();
11194     Register ABSDstReg = MI.getOperand(0).getReg();
11195     bool ABSSrcKIll = MI.getOperand(1).isKill();
11196     bool isThumb2 = Subtarget->isThumb2();
11197     MachineRegisterInfo &MRI = Fn->getRegInfo();
11198     // In Thumb mode S must not be specified if source register is the SP or
11199     // PC and if destination register is the SP, so restrict register class
11200     Register NewRsbDstReg = MRI.createVirtualRegister(
11201         isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
11202 
11203     // Transfer the remainder of BB and its successor edges to sinkMBB.
11204     SinkBB->splice(SinkBB->begin(), BB,
11205                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
11206     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
11207 
11208     BB->addSuccessor(RSBBB);
11209     BB->addSuccessor(SinkBB);
11210 
11211     // fall through to SinkMBB
11212     RSBBB->addSuccessor(SinkBB);
11213 
11214     // insert a cmp at the end of BB
11215     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
11216         .addReg(ABSSrcReg)
11217         .addImm(0)
11218         .add(predOps(ARMCC::AL));
11219 
11220     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
11221     BuildMI(BB, dl,
11222       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
11223       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
11224 
11225     // insert rsbri in RSBBB
11226     // Note: BCC and rsbri will be converted into predicated rsbmi
11227     // by if-conversion pass
11228     BuildMI(*RSBBB, RSBBB->begin(), dl,
11229             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
11230         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
11231         .addImm(0)
11232         .add(predOps(ARMCC::AL))
11233         .add(condCodeOp());
11234 
11235     // insert PHI in SinkBB,
11236     // reuse ABSDstReg to not change uses of ABS instruction
11237     BuildMI(*SinkBB, SinkBB->begin(), dl,
11238       TII->get(ARM::PHI), ABSDstReg)
11239       .addReg(NewRsbDstReg).addMBB(RSBBB)
11240       .addReg(ABSSrcReg).addMBB(BB);
11241 
11242     // remove ABS instruction
11243     MI.eraseFromParent();
11244 
11245     // return last added BB
11246     return SinkBB;
11247   }
11248   case ARM::COPY_STRUCT_BYVAL_I32:
11249     ++NumLoopByVals;
11250     return EmitStructByval(MI, BB);
11251   case ARM::WIN__CHKSTK:
11252     return EmitLowered__chkstk(MI, BB);
11253   case ARM::WIN__DBZCHK:
11254     return EmitLowered__dbzchk(MI, BB);
11255   }
11256 }
11257 
11258 /// Attaches vregs to MEMCPY that it will use as scratch registers
11259 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
11260 /// instead of as a custom inserter because we need the use list from the SDNode.
11261 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
11262                                     MachineInstr &MI, const SDNode *Node) {
11263   bool isThumb1 = Subtarget->isThumb1Only();
11264 
11265   DebugLoc DL = MI.getDebugLoc();
11266   MachineFunction *MF = MI.getParent()->getParent();
11267   MachineRegisterInfo &MRI = MF->getRegInfo();
11268   MachineInstrBuilder MIB(*MF, MI);
11269 
11270   // If the new dst/src is unused mark it as dead.
11271   if (!Node->hasAnyUseOfValue(0)) {
11272     MI.getOperand(0).setIsDead(true);
11273   }
11274   if (!Node->hasAnyUseOfValue(1)) {
11275     MI.getOperand(1).setIsDead(true);
11276   }
11277 
11278   // The MEMCPY both defines and kills the scratch registers.
11279   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
11280     Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
11281                                                          : &ARM::GPRRegClass);
11282     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
11283   }
11284 }
11285 
11286 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11287                                                       SDNode *Node) const {
11288   if (MI.getOpcode() == ARM::MEMCPY) {
11289     attachMEMCPYScratchRegs(Subtarget, MI, Node);
11290     return;
11291   }
11292 
11293   const MCInstrDesc *MCID = &MI.getDesc();
11294   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
11295   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
11296   // operand is still set to noreg. If needed, set the optional operand's
11297   // register to CPSR, and remove the redundant implicit def.
11298   //
11299   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
11300 
11301   // Rename pseudo opcodes.
11302   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
11303   unsigned ccOutIdx;
11304   if (NewOpc) {
11305     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
11306     MCID = &TII->get(NewOpc);
11307 
11308     assert(MCID->getNumOperands() ==
11309            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
11310         && "converted opcode should be the same except for cc_out"
11311            " (and, on Thumb1, pred)");
11312 
11313     MI.setDesc(*MCID);
11314 
11315     // Add the optional cc_out operand
11316     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
11317 
11318     // On Thumb1, move all input operands to the end, then add the predicate
11319     if (Subtarget->isThumb1Only()) {
11320       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
11321         MI.addOperand(MI.getOperand(1));
11322         MI.RemoveOperand(1);
11323       }
11324 
11325       // Restore the ties
11326       for (unsigned i = MI.getNumOperands(); i--;) {
11327         const MachineOperand& op = MI.getOperand(i);
11328         if (op.isReg() && op.isUse()) {
11329           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
11330           if (DefIdx != -1)
11331             MI.tieOperands(DefIdx, i);
11332         }
11333       }
11334 
11335       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
11336       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
11337       ccOutIdx = 1;
11338     } else
11339       ccOutIdx = MCID->getNumOperands() - 1;
11340   } else
11341     ccOutIdx = MCID->getNumOperands() - 1;
11342 
11343   // Any ARM instruction that sets the 's' bit should specify an optional
11344   // "cc_out" operand in the last operand position.
11345   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
11346     assert(!NewOpc && "Optional cc_out operand required");
11347     return;
11348   }
11349   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
11350   // since we already have an optional CPSR def.
11351   bool definesCPSR = false;
11352   bool deadCPSR = false;
11353   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
11354        ++i) {
11355     const MachineOperand &MO = MI.getOperand(i);
11356     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
11357       definesCPSR = true;
11358       if (MO.isDead())
11359         deadCPSR = true;
11360       MI.RemoveOperand(i);
11361       break;
11362     }
11363   }
11364   if (!definesCPSR) {
11365     assert(!NewOpc && "Optional cc_out operand required");
11366     return;
11367   }
11368   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
11369   if (deadCPSR) {
11370     assert(!MI.getOperand(ccOutIdx).getReg() &&
11371            "expect uninitialized optional cc_out operand");
11372     // Thumb1 instructions must have the S bit even if the CPSR is dead.
11373     if (!Subtarget->isThumb1Only())
11374       return;
11375   }
11376 
11377   // If this instruction was defined with an optional CPSR def and its dag node
11378   // had a live implicit CPSR def, then activate the optional CPSR def.
11379   MachineOperand &MO = MI.getOperand(ccOutIdx);
11380   MO.setReg(ARM::CPSR);
11381   MO.setIsDef(true);
11382 }
11383 
11384 //===----------------------------------------------------------------------===//
11385 //                           ARM Optimization Hooks
11386 //===----------------------------------------------------------------------===//
11387 
11388 // Helper function that checks if N is a null or all ones constant.
11389 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
11390   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
11391 }
11392 
11393 // Return true if N is conditionally 0 or all ones.
11394 // Detects these expressions where cc is an i1 value:
11395 //
11396 //   (select cc 0, y)   [AllOnes=0]
11397 //   (select cc y, 0)   [AllOnes=0]
11398 //   (zext cc)          [AllOnes=0]
11399 //   (sext cc)          [AllOnes=0/1]
11400 //   (select cc -1, y)  [AllOnes=1]
11401 //   (select cc y, -1)  [AllOnes=1]
11402 //
11403 // Invert is set when N is the null/all ones constant when CC is false.
11404 // OtherOp is set to the alternative value of N.
11405 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
11406                                        SDValue &CC, bool &Invert,
11407                                        SDValue &OtherOp,
11408                                        SelectionDAG &DAG) {
11409   switch (N->getOpcode()) {
11410   default: return false;
11411   case ISD::SELECT: {
11412     CC = N->getOperand(0);
11413     SDValue N1 = N->getOperand(1);
11414     SDValue N2 = N->getOperand(2);
11415     if (isZeroOrAllOnes(N1, AllOnes)) {
11416       Invert = false;
11417       OtherOp = N2;
11418       return true;
11419     }
11420     if (isZeroOrAllOnes(N2, AllOnes)) {
11421       Invert = true;
11422       OtherOp = N1;
11423       return true;
11424     }
11425     return false;
11426   }
11427   case ISD::ZERO_EXTEND:
11428     // (zext cc) can never be the all ones value.
11429     if (AllOnes)
11430       return false;
11431     LLVM_FALLTHROUGH;
11432   case ISD::SIGN_EXTEND: {
11433     SDLoc dl(N);
11434     EVT VT = N->getValueType(0);
11435     CC = N->getOperand(0);
11436     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
11437       return false;
11438     Invert = !AllOnes;
11439     if (AllOnes)
11440       // When looking for an AllOnes constant, N is an sext, and the 'other'
11441       // value is 0.
11442       OtherOp = DAG.getConstant(0, dl, VT);
11443     else if (N->getOpcode() == ISD::ZERO_EXTEND)
11444       // When looking for a 0 constant, N can be zext or sext.
11445       OtherOp = DAG.getConstant(1, dl, VT);
11446     else
11447       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
11448                                 VT);
11449     return true;
11450   }
11451   }
11452 }
11453 
11454 // Combine a constant select operand into its use:
11455 //
11456 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
11457 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
11458 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
11459 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
11460 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
11461 //
11462 // The transform is rejected if the select doesn't have a constant operand that
11463 // is null, or all ones when AllOnes is set.
11464 //
11465 // Also recognize sext/zext from i1:
11466 //
11467 //   (add (zext cc), x) -> (select cc (add x, 1), x)
11468 //   (add (sext cc), x) -> (select cc (add x, -1), x)
11469 //
11470 // These transformations eventually create predicated instructions.
11471 //
11472 // @param N       The node to transform.
11473 // @param Slct    The N operand that is a select.
11474 // @param OtherOp The other N operand (x above).
11475 // @param DCI     Context.
11476 // @param AllOnes Require the select constant to be all ones instead of null.
11477 // @returns The new node, or SDValue() on failure.
11478 static
11479 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
11480                             TargetLowering::DAGCombinerInfo &DCI,
11481                             bool AllOnes = false) {
11482   SelectionDAG &DAG = DCI.DAG;
11483   EVT VT = N->getValueType(0);
11484   SDValue NonConstantVal;
11485   SDValue CCOp;
11486   bool SwapSelectOps;
11487   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
11488                                   NonConstantVal, DAG))
11489     return SDValue();
11490 
11491   // Slct is now know to be the desired identity constant when CC is true.
11492   SDValue TrueVal = OtherOp;
11493   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11494                                  OtherOp, NonConstantVal);
11495   // Unless SwapSelectOps says CC should be false.
11496   if (SwapSelectOps)
11497     std::swap(TrueVal, FalseVal);
11498 
11499   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
11500                      CCOp, TrueVal, FalseVal);
11501 }
11502 
11503 // Attempt combineSelectAndUse on each operand of a commutative operator N.
11504 static
11505 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
11506                                        TargetLowering::DAGCombinerInfo &DCI) {
11507   SDValue N0 = N->getOperand(0);
11508   SDValue N1 = N->getOperand(1);
11509   if (N0.getNode()->hasOneUse())
11510     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
11511       return Result;
11512   if (N1.getNode()->hasOneUse())
11513     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
11514       return Result;
11515   return SDValue();
11516 }
11517 
11518 static bool IsVUZPShuffleNode(SDNode *N) {
11519   // VUZP shuffle node.
11520   if (N->getOpcode() == ARMISD::VUZP)
11521     return true;
11522 
11523   // "VUZP" on i32 is an alias for VTRN.
11524   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
11525     return true;
11526 
11527   return false;
11528 }
11529 
11530 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
11531                                  TargetLowering::DAGCombinerInfo &DCI,
11532                                  const ARMSubtarget *Subtarget) {
11533   // Look for ADD(VUZP.0, VUZP.1).
11534   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
11535       N0 == N1)
11536    return SDValue();
11537 
11538   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
11539   if (!N->getValueType(0).is64BitVector())
11540     return SDValue();
11541 
11542   // Generate vpadd.
11543   SelectionDAG &DAG = DCI.DAG;
11544   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11545   SDLoc dl(N);
11546   SDNode *Unzip = N0.getNode();
11547   EVT VT = N->getValueType(0);
11548 
11549   SmallVector<SDValue, 8> Ops;
11550   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
11551                                 TLI.getPointerTy(DAG.getDataLayout())));
11552   Ops.push_back(Unzip->getOperand(0));
11553   Ops.push_back(Unzip->getOperand(1));
11554 
11555   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11556 }
11557 
11558 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11559                                       TargetLowering::DAGCombinerInfo &DCI,
11560                                       const ARMSubtarget *Subtarget) {
11561   // Check for two extended operands.
11562   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
11563         N1.getOpcode() == ISD::SIGN_EXTEND) &&
11564       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
11565         N1.getOpcode() == ISD::ZERO_EXTEND))
11566     return SDValue();
11567 
11568   SDValue N00 = N0.getOperand(0);
11569   SDValue N10 = N1.getOperand(0);
11570 
11571   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
11572   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
11573       N00 == N10)
11574     return SDValue();
11575 
11576   // We only recognize Q register paddl here; this can't be reached until
11577   // after type legalization.
11578   if (!N00.getValueType().is64BitVector() ||
11579       !N0.getValueType().is128BitVector())
11580     return SDValue();
11581 
11582   // Generate vpaddl.
11583   SelectionDAG &DAG = DCI.DAG;
11584   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11585   SDLoc dl(N);
11586   EVT VT = N->getValueType(0);
11587 
11588   SmallVector<SDValue, 8> Ops;
11589   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
11590   unsigned Opcode;
11591   if (N0.getOpcode() == ISD::SIGN_EXTEND)
11592     Opcode = Intrinsic::arm_neon_vpaddls;
11593   else
11594     Opcode = Intrinsic::arm_neon_vpaddlu;
11595   Ops.push_back(DAG.getConstant(Opcode, dl,
11596                                 TLI.getPointerTy(DAG.getDataLayout())));
11597   EVT ElemTy = N00.getValueType().getVectorElementType();
11598   unsigned NumElts = VT.getVectorNumElements();
11599   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
11600   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
11601                                N00.getOperand(0), N00.getOperand(1));
11602   Ops.push_back(Concat);
11603 
11604   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11605 }
11606 
11607 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
11608 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
11609 // much easier to match.
11610 static SDValue
11611 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11612                                TargetLowering::DAGCombinerInfo &DCI,
11613                                const ARMSubtarget *Subtarget) {
11614   // Only perform optimization if after legalize, and if NEON is available. We
11615   // also expected both operands to be BUILD_VECTORs.
11616   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
11617       || N0.getOpcode() != ISD::BUILD_VECTOR
11618       || N1.getOpcode() != ISD::BUILD_VECTOR)
11619     return SDValue();
11620 
11621   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
11622   EVT VT = N->getValueType(0);
11623   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
11624     return SDValue();
11625 
11626   // Check that the vector operands are of the right form.
11627   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
11628   // operands, where N is the size of the formed vector.
11629   // Each EXTRACT_VECTOR should have the same input vector and odd or even
11630   // index such that we have a pair wise add pattern.
11631 
11632   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
11633   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11634     return SDValue();
11635   SDValue Vec = N0->getOperand(0)->getOperand(0);
11636   SDNode *V = Vec.getNode();
11637   unsigned nextIndex = 0;
11638 
11639   // For each operands to the ADD which are BUILD_VECTORs,
11640   // check to see if each of their operands are an EXTRACT_VECTOR with
11641   // the same vector and appropriate index.
11642   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
11643     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
11644         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11645 
11646       SDValue ExtVec0 = N0->getOperand(i);
11647       SDValue ExtVec1 = N1->getOperand(i);
11648 
11649       // First operand is the vector, verify its the same.
11650       if (V != ExtVec0->getOperand(0).getNode() ||
11651           V != ExtVec1->getOperand(0).getNode())
11652         return SDValue();
11653 
11654       // Second is the constant, verify its correct.
11655       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
11656       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
11657 
11658       // For the constant, we want to see all the even or all the odd.
11659       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
11660           || C1->getZExtValue() != nextIndex+1)
11661         return SDValue();
11662 
11663       // Increment index.
11664       nextIndex+=2;
11665     } else
11666       return SDValue();
11667   }
11668 
11669   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
11670   // we're using the entire input vector, otherwise there's a size/legality
11671   // mismatch somewhere.
11672   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
11673       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
11674     return SDValue();
11675 
11676   // Create VPADDL node.
11677   SelectionDAG &DAG = DCI.DAG;
11678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11679 
11680   SDLoc dl(N);
11681 
11682   // Build operand list.
11683   SmallVector<SDValue, 8> Ops;
11684   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
11685                                 TLI.getPointerTy(DAG.getDataLayout())));
11686 
11687   // Input is the vector.
11688   Ops.push_back(Vec);
11689 
11690   // Get widened type and narrowed type.
11691   MVT widenType;
11692   unsigned numElem = VT.getVectorNumElements();
11693 
11694   EVT inputLaneType = Vec.getValueType().getVectorElementType();
11695   switch (inputLaneType.getSimpleVT().SimpleTy) {
11696     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
11697     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
11698     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
11699     default:
11700       llvm_unreachable("Invalid vector element type for padd optimization.");
11701   }
11702 
11703   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
11704   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
11705   return DAG.getNode(ExtOp, dl, VT, tmp);
11706 }
11707 
11708 static SDValue findMUL_LOHI(SDValue V) {
11709   if (V->getOpcode() == ISD::UMUL_LOHI ||
11710       V->getOpcode() == ISD::SMUL_LOHI)
11711     return V;
11712   return SDValue();
11713 }
11714 
11715 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
11716                                         TargetLowering::DAGCombinerInfo &DCI,
11717                                         const ARMSubtarget *Subtarget) {
11718   if (!Subtarget->hasBaseDSP())
11719     return SDValue();
11720 
11721   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
11722   // accumulates the product into a 64-bit value. The 16-bit values will
11723   // be sign extended somehow or SRA'd into 32-bit values
11724   // (addc (adde (mul 16bit, 16bit), lo), hi)
11725   SDValue Mul = AddcNode->getOperand(0);
11726   SDValue Lo = AddcNode->getOperand(1);
11727   if (Mul.getOpcode() != ISD::MUL) {
11728     Lo = AddcNode->getOperand(0);
11729     Mul = AddcNode->getOperand(1);
11730     if (Mul.getOpcode() != ISD::MUL)
11731       return SDValue();
11732   }
11733 
11734   SDValue SRA = AddeNode->getOperand(0);
11735   SDValue Hi = AddeNode->getOperand(1);
11736   if (SRA.getOpcode() != ISD::SRA) {
11737     SRA = AddeNode->getOperand(1);
11738     Hi = AddeNode->getOperand(0);
11739     if (SRA.getOpcode() != ISD::SRA)
11740       return SDValue();
11741   }
11742   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
11743     if (Const->getZExtValue() != 31)
11744       return SDValue();
11745   } else
11746     return SDValue();
11747 
11748   if (SRA.getOperand(0) != Mul)
11749     return SDValue();
11750 
11751   SelectionDAG &DAG = DCI.DAG;
11752   SDLoc dl(AddcNode);
11753   unsigned Opcode = 0;
11754   SDValue Op0;
11755   SDValue Op1;
11756 
11757   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
11758     Opcode = ARMISD::SMLALBB;
11759     Op0 = Mul.getOperand(0);
11760     Op1 = Mul.getOperand(1);
11761   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
11762     Opcode = ARMISD::SMLALBT;
11763     Op0 = Mul.getOperand(0);
11764     Op1 = Mul.getOperand(1).getOperand(0);
11765   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
11766     Opcode = ARMISD::SMLALTB;
11767     Op0 = Mul.getOperand(0).getOperand(0);
11768     Op1 = Mul.getOperand(1);
11769   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
11770     Opcode = ARMISD::SMLALTT;
11771     Op0 = Mul->getOperand(0).getOperand(0);
11772     Op1 = Mul->getOperand(1).getOperand(0);
11773   }
11774 
11775   if (!Op0 || !Op1)
11776     return SDValue();
11777 
11778   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
11779                               Op0, Op1, Lo, Hi);
11780   // Replace the ADDs' nodes uses by the MLA node's values.
11781   SDValue HiMLALResult(SMLAL.getNode(), 1);
11782   SDValue LoMLALResult(SMLAL.getNode(), 0);
11783 
11784   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
11785   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
11786 
11787   // Return original node to notify the driver to stop replacing.
11788   SDValue resNode(AddcNode, 0);
11789   return resNode;
11790 }
11791 
11792 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
11793                                      TargetLowering::DAGCombinerInfo &DCI,
11794                                      const ARMSubtarget *Subtarget) {
11795   // Look for multiply add opportunities.
11796   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
11797   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
11798   // a glue link from the first add to the second add.
11799   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
11800   // a S/UMLAL instruction.
11801   //                  UMUL_LOHI
11802   //                 / :lo    \ :hi
11803   //                V          \          [no multiline comment]
11804   //    loAdd ->  ADDC         |
11805   //                 \ :carry /
11806   //                  V      V
11807   //                    ADDE   <- hiAdd
11808   //
11809   // In the special case where only the higher part of a signed result is used
11810   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
11811   // a constant with the exact value of 0x80000000, we recognize we are dealing
11812   // with a "rounded multiply and add" (or subtract) and transform it into
11813   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11814 
11815   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11816           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11817          "Expect an ADDE or SUBE");
11818 
11819   assert(AddeSubeNode->getNumOperands() == 3 &&
11820          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11821          "ADDE node has the wrong inputs");
11822 
11823   // Check that we are chained to the right ADDC or SUBC node.
11824   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11825   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11826        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11827       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11828        AddcSubcNode->getOpcode() != ARMISD::SUBC))
11829     return SDValue();
11830 
11831   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11832   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11833 
11834   // Check if the two operands are from the same mul_lohi node.
11835   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11836     return SDValue();
11837 
11838   assert(AddcSubcNode->getNumValues() == 2 &&
11839          AddcSubcNode->getValueType(0) == MVT::i32 &&
11840          "Expect ADDC with two result values. First: i32");
11841 
11842   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11843   // maybe a SMLAL which multiplies two 16-bit values.
11844   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11845       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11846       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11847       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11848       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11849     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11850 
11851   // Check for the triangle shape.
11852   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11853   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11854 
11855   // Make sure that the ADDE/SUBE operands are not coming from the same node.
11856   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11857     return SDValue();
11858 
11859   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11860   bool IsLeftOperandMUL = false;
11861   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11862   if (MULOp == SDValue())
11863     MULOp = findMUL_LOHI(AddeSubeOp1);
11864   else
11865     IsLeftOperandMUL = true;
11866   if (MULOp == SDValue())
11867     return SDValue();
11868 
11869   // Figure out the right opcode.
11870   unsigned Opc = MULOp->getOpcode();
11871   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11872 
11873   // Figure out the high and low input values to the MLAL node.
11874   SDValue *HiAddSub = nullptr;
11875   SDValue *LoMul = nullptr;
11876   SDValue *LowAddSub = nullptr;
11877 
11878   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11879   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11880     return SDValue();
11881 
11882   if (IsLeftOperandMUL)
11883     HiAddSub = &AddeSubeOp1;
11884   else
11885     HiAddSub = &AddeSubeOp0;
11886 
11887   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11888   // whose low result is fed to the ADDC/SUBC we are checking.
11889 
11890   if (AddcSubcOp0 == MULOp.getValue(0)) {
11891     LoMul = &AddcSubcOp0;
11892     LowAddSub = &AddcSubcOp1;
11893   }
11894   if (AddcSubcOp1 == MULOp.getValue(0)) {
11895     LoMul = &AddcSubcOp1;
11896     LowAddSub = &AddcSubcOp0;
11897   }
11898 
11899   if (!LoMul)
11900     return SDValue();
11901 
11902   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11903   // the replacement below will create a cycle.
11904   if (AddcSubcNode == HiAddSub->getNode() ||
11905       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11906     return SDValue();
11907 
11908   // Create the merged node.
11909   SelectionDAG &DAG = DCI.DAG;
11910 
11911   // Start building operand list.
11912   SmallVector<SDValue, 8> Ops;
11913   Ops.push_back(LoMul->getOperand(0));
11914   Ops.push_back(LoMul->getOperand(1));
11915 
11916   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
11917   // the case, we must be doing signed multiplication and only use the higher
11918   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11919   // addition or subtraction with the value of 0x800000.
11920   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11921       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11922       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11923       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11924           0x80000000) {
11925     Ops.push_back(*HiAddSub);
11926     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11927       FinalOpc = ARMISD::SMMLSR;
11928     } else {
11929       FinalOpc = ARMISD::SMMLAR;
11930     }
11931     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11932     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11933 
11934     return SDValue(AddeSubeNode, 0);
11935   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11936     // SMMLS is generated during instruction selection and the rest of this
11937     // function can not handle the case where AddcSubcNode is a SUBC.
11938     return SDValue();
11939 
11940   // Finish building the operand list for {U/S}MLAL
11941   Ops.push_back(*LowAddSub);
11942   Ops.push_back(*HiAddSub);
11943 
11944   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11945                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
11946 
11947   // Replace the ADDs' nodes uses by the MLA node's values.
11948   SDValue HiMLALResult(MLALNode.getNode(), 1);
11949   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11950 
11951   SDValue LoMLALResult(MLALNode.getNode(), 0);
11952   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11953 
11954   // Return original node to notify the driver to stop replacing.
11955   return SDValue(AddeSubeNode, 0);
11956 }
11957 
11958 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11959                                       TargetLowering::DAGCombinerInfo &DCI,
11960                                       const ARMSubtarget *Subtarget) {
11961   // UMAAL is similar to UMLAL except that it adds two unsigned values.
11962   // While trying to combine for the other MLAL nodes, first search for the
11963   // chance to use UMAAL. Check if Addc uses a node which has already
11964   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11965   // as the addend, and it's handled in PerformUMLALCombine.
11966 
11967   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11968     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11969 
11970   // Check that we have a glued ADDC node.
11971   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11972   if (AddcNode->getOpcode() != ARMISD::ADDC)
11973     return SDValue();
11974 
11975   // Find the converted UMAAL or quit if it doesn't exist.
11976   SDNode *UmlalNode = nullptr;
11977   SDValue AddHi;
11978   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11979     UmlalNode = AddcNode->getOperand(0).getNode();
11980     AddHi = AddcNode->getOperand(1);
11981   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11982     UmlalNode = AddcNode->getOperand(1).getNode();
11983     AddHi = AddcNode->getOperand(0);
11984   } else {
11985     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11986   }
11987 
11988   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11989   // the ADDC as well as Zero.
11990   if (!isNullConstant(UmlalNode->getOperand(3)))
11991     return SDValue();
11992 
11993   if ((isNullConstant(AddeNode->getOperand(0)) &&
11994        AddeNode->getOperand(1).getNode() == UmlalNode) ||
11995       (AddeNode->getOperand(0).getNode() == UmlalNode &&
11996        isNullConstant(AddeNode->getOperand(1)))) {
11997     SelectionDAG &DAG = DCI.DAG;
11998     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11999                       UmlalNode->getOperand(2), AddHi };
12000     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
12001                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
12002 
12003     // Replace the ADDs' nodes uses by the UMAAL node's values.
12004     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
12005     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
12006 
12007     // Return original node to notify the driver to stop replacing.
12008     return SDValue(AddeNode, 0);
12009   }
12010   return SDValue();
12011 }
12012 
12013 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
12014                                    const ARMSubtarget *Subtarget) {
12015   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
12016     return SDValue();
12017 
12018   // Check that we have a pair of ADDC and ADDE as operands.
12019   // Both addends of the ADDE must be zero.
12020   SDNode* AddcNode = N->getOperand(2).getNode();
12021   SDNode* AddeNode = N->getOperand(3).getNode();
12022   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
12023       (AddeNode->getOpcode() == ARMISD::ADDE) &&
12024       isNullConstant(AddeNode->getOperand(0)) &&
12025       isNullConstant(AddeNode->getOperand(1)) &&
12026       (AddeNode->getOperand(2).getNode() == AddcNode))
12027     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
12028                        DAG.getVTList(MVT::i32, MVT::i32),
12029                        {N->getOperand(0), N->getOperand(1),
12030                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
12031   else
12032     return SDValue();
12033 }
12034 
12035 static SDValue PerformAddcSubcCombine(SDNode *N,
12036                                       TargetLowering::DAGCombinerInfo &DCI,
12037                                       const ARMSubtarget *Subtarget) {
12038   SelectionDAG &DAG(DCI.DAG);
12039 
12040   if (N->getOpcode() == ARMISD::SUBC) {
12041     // (SUBC (ADDE 0, 0, C), 1) -> C
12042     SDValue LHS = N->getOperand(0);
12043     SDValue RHS = N->getOperand(1);
12044     if (LHS->getOpcode() == ARMISD::ADDE &&
12045         isNullConstant(LHS->getOperand(0)) &&
12046         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
12047       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
12048     }
12049   }
12050 
12051   if (Subtarget->isThumb1Only()) {
12052     SDValue RHS = N->getOperand(1);
12053     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12054       int32_t imm = C->getSExtValue();
12055       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
12056         SDLoc DL(N);
12057         RHS = DAG.getConstant(-imm, DL, MVT::i32);
12058         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
12059                                                            : ARMISD::ADDC;
12060         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
12061       }
12062     }
12063   }
12064 
12065   return SDValue();
12066 }
12067 
12068 static SDValue PerformAddeSubeCombine(SDNode *N,
12069                                       TargetLowering::DAGCombinerInfo &DCI,
12070                                       const ARMSubtarget *Subtarget) {
12071   if (Subtarget->isThumb1Only()) {
12072     SelectionDAG &DAG = DCI.DAG;
12073     SDValue RHS = N->getOperand(1);
12074     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
12075       int64_t imm = C->getSExtValue();
12076       if (imm < 0) {
12077         SDLoc DL(N);
12078 
12079         // The with-carry-in form matches bitwise not instead of the negation.
12080         // Effectively, the inverse interpretation of the carry flag already
12081         // accounts for part of the negation.
12082         RHS = DAG.getConstant(~imm, DL, MVT::i32);
12083 
12084         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
12085                                                            : ARMISD::ADDE;
12086         return DAG.getNode(Opcode, DL, N->getVTList(),
12087                            N->getOperand(0), RHS, N->getOperand(2));
12088       }
12089     }
12090   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
12091     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
12092   }
12093   return SDValue();
12094 }
12095 
12096 static SDValue PerformVSELECTCombine(SDNode *N,
12097                                      TargetLowering::DAGCombinerInfo &DCI,
12098                                      const ARMSubtarget *Subtarget) {
12099   // Transforms vselect(not(cond), lhs, rhs) into vselect(cond, rhs, lhs).
12100   //
12101   // We need to re-implement this optimization here as the implementation in the
12102   // Target-Independent DAGCombiner does not handle the kind of constant we make
12103   // (it calls isConstOrConstSplat with AllowTruncation set to false - and for
12104   // good reason, allowing truncation there would break other targets).
12105   //
12106   // Currently, this is only done for MVE, as it's the only target that benefits
12107   // from this transformation (e.g. VPNOT+VPSEL becomes a single VPSEL).
12108   if (!Subtarget->hasMVEIntegerOps())
12109     return SDValue();
12110 
12111   if (N->getOperand(0).getOpcode() != ISD::XOR)
12112     return SDValue();
12113   SDValue XOR = N->getOperand(0);
12114 
12115   // Check if the XOR's RHS is either a 1, or a BUILD_VECTOR of 1s.
12116   // It is important to check with truncation allowed as the BUILD_VECTORs we
12117   // generate in those situations will truncate their operands.
12118   ConstantSDNode *Const =
12119       isConstOrConstSplat(XOR->getOperand(1), /*AllowUndefs*/ false,
12120                           /*AllowTruncation*/ true);
12121   if (!Const || !Const->isOne())
12122     return SDValue();
12123 
12124   // Rewrite into vselect(cond, rhs, lhs).
12125   SDValue Cond = XOR->getOperand(0);
12126   SDValue LHS = N->getOperand(1);
12127   SDValue RHS = N->getOperand(2);
12128   EVT Type = N->getValueType(0);
12129   return DCI.DAG.getNode(ISD::VSELECT, SDLoc(N), Type, Cond, RHS, LHS);
12130 }
12131 
12132 static SDValue PerformABSCombine(SDNode *N,
12133                                   TargetLowering::DAGCombinerInfo &DCI,
12134                                   const ARMSubtarget *Subtarget) {
12135   SDValue res;
12136   SelectionDAG &DAG = DCI.DAG;
12137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12138 
12139   if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
12140     return SDValue();
12141 
12142   if (!TLI.expandABS(N, res, DAG))
12143       return SDValue();
12144 
12145   return res;
12146 }
12147 
12148 /// PerformADDECombine - Target-specific dag combine transform from
12149 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
12150 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
12151 static SDValue PerformADDECombine(SDNode *N,
12152                                   TargetLowering::DAGCombinerInfo &DCI,
12153                                   const ARMSubtarget *Subtarget) {
12154   // Only ARM and Thumb2 support UMLAL/SMLAL.
12155   if (Subtarget->isThumb1Only())
12156     return PerformAddeSubeCombine(N, DCI, Subtarget);
12157 
12158   // Only perform the checks after legalize when the pattern is available.
12159   if (DCI.isBeforeLegalize()) return SDValue();
12160 
12161   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
12162 }
12163 
12164 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
12165 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
12166 /// called with the default operands, and if that fails, with commuted
12167 /// operands.
12168 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
12169                                           TargetLowering::DAGCombinerInfo &DCI,
12170                                           const ARMSubtarget *Subtarget){
12171   // Attempt to create vpadd for this add.
12172   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
12173     return Result;
12174 
12175   // Attempt to create vpaddl for this add.
12176   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
12177     return Result;
12178   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
12179                                                       Subtarget))
12180     return Result;
12181 
12182   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
12183   if (N0.getNode()->hasOneUse())
12184     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
12185       return Result;
12186   return SDValue();
12187 }
12188 
12189 static SDValue PerformADDVecReduce(SDNode *N,
12190                                    TargetLowering::DAGCombinerInfo &DCI,
12191                                    const ARMSubtarget *Subtarget) {
12192   if (!Subtarget->hasMVEIntegerOps() || N->getValueType(0) != MVT::i64)
12193     return SDValue();
12194 
12195   SDValue N0 = N->getOperand(0);
12196   SDValue N1 = N->getOperand(1);
12197 
12198   // We are looking for a i64 add of a VADDLVx. Due to these being i64's, this
12199   // will look like:
12200   //   t1: i32,i32 = ARMISD::VADDLVs x
12201   //   t2: i64 = build_pair t1, t1:1
12202   //   t3: i64 = add t2, y
12203   // We also need to check for sext / zext and commutitive adds.
12204   auto MakeVecReduce = [&](unsigned Opcode, unsigned OpcodeA, SDValue NA,
12205                            SDValue NB) {
12206     if (NB->getOpcode() != ISD::BUILD_PAIR)
12207       return SDValue();
12208     SDValue VecRed = NB->getOperand(0);
12209     if (VecRed->getOpcode() != Opcode || VecRed.getResNo() != 0 ||
12210         NB->getOperand(1) != SDValue(VecRed.getNode(), 1))
12211       return SDValue();
12212 
12213     SDLoc dl(N);
12214     SmallVector<SDValue, 4> Ops;
12215     Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
12216                                   DCI.DAG.getConstant(0, dl, MVT::i32)));
12217     Ops.push_back(DCI.DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, NA,
12218                                   DCI.DAG.getConstant(1, dl, MVT::i32)));
12219     for (unsigned i = 0, e = VecRed.getNumOperands(); i < e; i++)
12220       Ops.push_back(VecRed->getOperand(i));
12221     SDValue Red = DCI.DAG.getNode(OpcodeA, dl,
12222                                   DCI.DAG.getVTList({MVT::i32, MVT::i32}), Ops);
12223     return DCI.DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Red,
12224                            SDValue(Red.getNode(), 1));
12225   };
12226 
12227   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N0, N1))
12228     return M;
12229   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N0, N1))
12230     return M;
12231   if (SDValue M = MakeVecReduce(ARMISD::VADDLVs, ARMISD::VADDLVAs, N1, N0))
12232     return M;
12233   if (SDValue M = MakeVecReduce(ARMISD::VADDLVu, ARMISD::VADDLVAu, N1, N0))
12234     return M;
12235   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N0, N1))
12236     return M;
12237   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N0, N1))
12238     return M;
12239   if (SDValue M = MakeVecReduce(ARMISD::VADDLVps, ARMISD::VADDLVAps, N1, N0))
12240     return M;
12241   if (SDValue M = MakeVecReduce(ARMISD::VADDLVpu, ARMISD::VADDLVApu, N1, N0))
12242     return M;
12243   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N0, N1))
12244     return M;
12245   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N0, N1))
12246     return M;
12247   if (SDValue M = MakeVecReduce(ARMISD::VMLALVs, ARMISD::VMLALVAs, N1, N0))
12248     return M;
12249   if (SDValue M = MakeVecReduce(ARMISD::VMLALVu, ARMISD::VMLALVAu, N1, N0))
12250     return M;
12251   if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N0, N1))
12252     return M;
12253   if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N0, N1))
12254     return M;
12255   if (SDValue M = MakeVecReduce(ARMISD::VMLALVps, ARMISD::VMLALVAps, N1, N0))
12256     return M;
12257   if (SDValue M = MakeVecReduce(ARMISD::VMLALVpu, ARMISD::VMLALVApu, N1, N0))
12258     return M;
12259   return SDValue();
12260 }
12261 
12262 bool
12263 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
12264                                                  CombineLevel Level) const {
12265   if (Level == BeforeLegalizeTypes)
12266     return true;
12267 
12268   if (N->getOpcode() != ISD::SHL)
12269     return true;
12270 
12271   if (Subtarget->isThumb1Only()) {
12272     // Avoid making expensive immediates by commuting shifts. (This logic
12273     // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
12274     // for free.)
12275     if (N->getOpcode() != ISD::SHL)
12276       return true;
12277     SDValue N1 = N->getOperand(0);
12278     if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
12279         N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
12280       return true;
12281     if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
12282       if (Const->getAPIntValue().ult(256))
12283         return false;
12284       if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
12285           Const->getAPIntValue().sgt(-256))
12286         return false;
12287     }
12288     return true;
12289   }
12290 
12291   // Turn off commute-with-shift transform after legalization, so it doesn't
12292   // conflict with PerformSHLSimplify.  (We could try to detect when
12293   // PerformSHLSimplify would trigger more precisely, but it isn't
12294   // really necessary.)
12295   return false;
12296 }
12297 
12298 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
12299     const SDNode *N, CombineLevel Level) const {
12300   if (!Subtarget->isThumb1Only())
12301     return true;
12302 
12303   if (Level == BeforeLegalizeTypes)
12304     return true;
12305 
12306   return false;
12307 }
12308 
12309 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
12310   if (!Subtarget->hasNEON()) {
12311     if (Subtarget->isThumb1Only())
12312       return VT.getScalarSizeInBits() <= 32;
12313     return true;
12314   }
12315   return VT.isScalarInteger();
12316 }
12317 
12318 static SDValue PerformSHLSimplify(SDNode *N,
12319                                 TargetLowering::DAGCombinerInfo &DCI,
12320                                 const ARMSubtarget *ST) {
12321   // Allow the generic combiner to identify potential bswaps.
12322   if (DCI.isBeforeLegalize())
12323     return SDValue();
12324 
12325   // DAG combiner will fold:
12326   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
12327   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
12328   // Other code patterns that can be also be modified have the following form:
12329   // b + ((a << 1) | 510)
12330   // b + ((a << 1) & 510)
12331   // b + ((a << 1) ^ 510)
12332   // b + ((a << 1) + 510)
12333 
12334   // Many instructions can  perform the shift for free, but it requires both
12335   // the operands to be registers. If c1 << c2 is too large, a mov immediate
12336   // instruction will needed. So, unfold back to the original pattern if:
12337   // - if c1 and c2 are small enough that they don't require mov imms.
12338   // - the user(s) of the node can perform an shl
12339 
12340   // No shifted operands for 16-bit instructions.
12341   if (ST->isThumb() && ST->isThumb1Only())
12342     return SDValue();
12343 
12344   // Check that all the users could perform the shl themselves.
12345   for (auto U : N->uses()) {
12346     switch(U->getOpcode()) {
12347     default:
12348       return SDValue();
12349     case ISD::SUB:
12350     case ISD::ADD:
12351     case ISD::AND:
12352     case ISD::OR:
12353     case ISD::XOR:
12354     case ISD::SETCC:
12355     case ARMISD::CMP:
12356       // Check that the user isn't already using a constant because there
12357       // aren't any instructions that support an immediate operand and a
12358       // shifted operand.
12359       if (isa<ConstantSDNode>(U->getOperand(0)) ||
12360           isa<ConstantSDNode>(U->getOperand(1)))
12361         return SDValue();
12362 
12363       // Check that it's not already using a shift.
12364       if (U->getOperand(0).getOpcode() == ISD::SHL ||
12365           U->getOperand(1).getOpcode() == ISD::SHL)
12366         return SDValue();
12367       break;
12368     }
12369   }
12370 
12371   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
12372       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
12373     return SDValue();
12374 
12375   if (N->getOperand(0).getOpcode() != ISD::SHL)
12376     return SDValue();
12377 
12378   SDValue SHL = N->getOperand(0);
12379 
12380   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
12381   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
12382   if (!C1ShlC2 || !C2)
12383     return SDValue();
12384 
12385   APInt C2Int = C2->getAPIntValue();
12386   APInt C1Int = C1ShlC2->getAPIntValue();
12387 
12388   // Check that performing a lshr will not lose any information.
12389   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
12390                                      C2Int.getBitWidth() - C2->getZExtValue());
12391   if ((C1Int & Mask) != C1Int)
12392     return SDValue();
12393 
12394   // Shift the first constant.
12395   C1Int.lshrInPlace(C2Int);
12396 
12397   // The immediates are encoded as an 8-bit value that can be rotated.
12398   auto LargeImm = [](const APInt &Imm) {
12399     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
12400     return Imm.getBitWidth() - Zeros > 8;
12401   };
12402 
12403   if (LargeImm(C1Int) || LargeImm(C2Int))
12404     return SDValue();
12405 
12406   SelectionDAG &DAG = DCI.DAG;
12407   SDLoc dl(N);
12408   SDValue X = SHL.getOperand(0);
12409   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
12410                               DAG.getConstant(C1Int, dl, MVT::i32));
12411   // Shift left to compensate for the lshr of C1Int.
12412   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
12413 
12414   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
12415              SHL.dump(); N->dump());
12416   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
12417   return Res;
12418 }
12419 
12420 
12421 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
12422 ///
12423 static SDValue PerformADDCombine(SDNode *N,
12424                                  TargetLowering::DAGCombinerInfo &DCI,
12425                                  const ARMSubtarget *Subtarget) {
12426   SDValue N0 = N->getOperand(0);
12427   SDValue N1 = N->getOperand(1);
12428 
12429   // Only works one way, because it needs an immediate operand.
12430   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12431     return Result;
12432 
12433   if (SDValue Result = PerformADDVecReduce(N, DCI, Subtarget))
12434     return Result;
12435 
12436   // First try with the default operand order.
12437   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
12438     return Result;
12439 
12440   // If that didn't work, try again with the operands commuted.
12441   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
12442 }
12443 
12444 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
12445 ///
12446 static SDValue PerformSUBCombine(SDNode *N,
12447                                  TargetLowering::DAGCombinerInfo &DCI,
12448                                  const ARMSubtarget *Subtarget) {
12449   SDValue N0 = N->getOperand(0);
12450   SDValue N1 = N->getOperand(1);
12451 
12452   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
12453   if (N1.getNode()->hasOneUse())
12454     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
12455       return Result;
12456 
12457   if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
12458     return SDValue();
12459 
12460   // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
12461   // so that we can readily pattern match more mve instructions which can use
12462   // a scalar operand.
12463   SDValue VDup = N->getOperand(1);
12464   if (VDup->getOpcode() != ARMISD::VDUP)
12465     return SDValue();
12466 
12467   SDValue VMov = N->getOperand(0);
12468   if (VMov->getOpcode() == ISD::BITCAST)
12469     VMov = VMov->getOperand(0);
12470 
12471   if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
12472     return SDValue();
12473 
12474   SDLoc dl(N);
12475   SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
12476                                    DCI.DAG.getConstant(0, dl, MVT::i32),
12477                                    VDup->getOperand(0));
12478   return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
12479 }
12480 
12481 /// PerformVMULCombine
12482 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
12483 /// special multiplier accumulator forwarding.
12484 ///   vmul d3, d0, d2
12485 ///   vmla d3, d1, d2
12486 /// is faster than
12487 ///   vadd d3, d0, d1
12488 ///   vmul d3, d3, d2
12489 //  However, for (A + B) * (A + B),
12490 //    vadd d2, d0, d1
12491 //    vmul d3, d0, d2
12492 //    vmla d3, d1, d2
12493 //  is slower than
12494 //    vadd d2, d0, d1
12495 //    vmul d3, d2, d2
12496 static SDValue PerformVMULCombine(SDNode *N,
12497                                   TargetLowering::DAGCombinerInfo &DCI,
12498                                   const ARMSubtarget *Subtarget) {
12499   if (!Subtarget->hasVMLxForwarding())
12500     return SDValue();
12501 
12502   SelectionDAG &DAG = DCI.DAG;
12503   SDValue N0 = N->getOperand(0);
12504   SDValue N1 = N->getOperand(1);
12505   unsigned Opcode = N0.getOpcode();
12506   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12507       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
12508     Opcode = N1.getOpcode();
12509     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
12510         Opcode != ISD::FADD && Opcode != ISD::FSUB)
12511       return SDValue();
12512     std::swap(N0, N1);
12513   }
12514 
12515   if (N0 == N1)
12516     return SDValue();
12517 
12518   EVT VT = N->getValueType(0);
12519   SDLoc DL(N);
12520   SDValue N00 = N0->getOperand(0);
12521   SDValue N01 = N0->getOperand(1);
12522   return DAG.getNode(Opcode, DL, VT,
12523                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
12524                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
12525 }
12526 
12527 static SDValue PerformMVEVMULLCombine(SDNode *N, SelectionDAG &DAG,
12528                                       const ARMSubtarget *Subtarget) {
12529   EVT VT = N->getValueType(0);
12530   if (VT != MVT::v2i64)
12531     return SDValue();
12532 
12533   SDValue N0 = N->getOperand(0);
12534   SDValue N1 = N->getOperand(1);
12535 
12536   auto IsSignExt = [&](SDValue Op) {
12537     if (Op->getOpcode() != ISD::SIGN_EXTEND_INREG)
12538       return SDValue();
12539     EVT VT = cast<VTSDNode>(Op->getOperand(1))->getVT();
12540     if (VT.getScalarSizeInBits() == 32)
12541       return Op->getOperand(0);
12542     return SDValue();
12543   };
12544   auto IsZeroExt = [&](SDValue Op) {
12545     // Zero extends are a little more awkward. At the point we are matching
12546     // this, we are looking for an AND with a (-1, 0, -1, 0) buildvector mask.
12547     // That might be before of after a bitcast depending on how the and is
12548     // placed. Because this has to look through bitcasts, it is currently only
12549     // supported on LE.
12550     if (!Subtarget->isLittle())
12551       return SDValue();
12552 
12553     SDValue And = Op;
12554     if (And->getOpcode() == ISD::BITCAST)
12555       And = And->getOperand(0);
12556     if (And->getOpcode() != ISD::AND)
12557       return SDValue();
12558     SDValue Mask = And->getOperand(1);
12559     if (Mask->getOpcode() == ISD::BITCAST)
12560       Mask = Mask->getOperand(0);
12561 
12562     if (Mask->getOpcode() != ISD::BUILD_VECTOR ||
12563         Mask.getValueType() != MVT::v4i32)
12564       return SDValue();
12565     if (isAllOnesConstant(Mask->getOperand(0)) &&
12566         isNullConstant(Mask->getOperand(1)) &&
12567         isAllOnesConstant(Mask->getOperand(2)) &&
12568         isNullConstant(Mask->getOperand(3)))
12569       return And->getOperand(0);
12570     return SDValue();
12571   };
12572 
12573   SDLoc dl(N);
12574   if (SDValue Op0 = IsSignExt(N0)) {
12575     if (SDValue Op1 = IsSignExt(N1)) {
12576       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12577       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12578       return DAG.getNode(ARMISD::VMULLs, dl, VT, New0a, New1a);
12579     }
12580   }
12581   if (SDValue Op0 = IsZeroExt(N0)) {
12582     if (SDValue Op1 = IsZeroExt(N1)) {
12583       SDValue New0a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op0);
12584       SDValue New1a = DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, MVT::v4i32, Op1);
12585       return DAG.getNode(ARMISD::VMULLu, dl, VT, New0a, New1a);
12586     }
12587   }
12588 
12589   return SDValue();
12590 }
12591 
12592 static SDValue PerformMULCombine(SDNode *N,
12593                                  TargetLowering::DAGCombinerInfo &DCI,
12594                                  const ARMSubtarget *Subtarget) {
12595   SelectionDAG &DAG = DCI.DAG;
12596 
12597   EVT VT = N->getValueType(0);
12598   if (Subtarget->hasMVEIntegerOps() && VT == MVT::v2i64)
12599     return PerformMVEVMULLCombine(N, DAG, Subtarget);
12600 
12601   if (Subtarget->isThumb1Only())
12602     return SDValue();
12603 
12604   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12605     return SDValue();
12606 
12607   if (VT.is64BitVector() || VT.is128BitVector())
12608     return PerformVMULCombine(N, DCI, Subtarget);
12609   if (VT != MVT::i32)
12610     return SDValue();
12611 
12612   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12613   if (!C)
12614     return SDValue();
12615 
12616   int64_t MulAmt = C->getSExtValue();
12617   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
12618 
12619   ShiftAmt = ShiftAmt & (32 - 1);
12620   SDValue V = N->getOperand(0);
12621   SDLoc DL(N);
12622 
12623   SDValue Res;
12624   MulAmt >>= ShiftAmt;
12625 
12626   if (MulAmt >= 0) {
12627     if (isPowerOf2_32(MulAmt - 1)) {
12628       // (mul x, 2^N + 1) => (add (shl x, N), x)
12629       Res = DAG.getNode(ISD::ADD, DL, VT,
12630                         V,
12631                         DAG.getNode(ISD::SHL, DL, VT,
12632                                     V,
12633                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
12634                                                     MVT::i32)));
12635     } else if (isPowerOf2_32(MulAmt + 1)) {
12636       // (mul x, 2^N - 1) => (sub (shl x, N), x)
12637       Res = DAG.getNode(ISD::SUB, DL, VT,
12638                         DAG.getNode(ISD::SHL, DL, VT,
12639                                     V,
12640                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
12641                                                     MVT::i32)),
12642                         V);
12643     } else
12644       return SDValue();
12645   } else {
12646     uint64_t MulAmtAbs = -MulAmt;
12647     if (isPowerOf2_32(MulAmtAbs + 1)) {
12648       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
12649       Res = DAG.getNode(ISD::SUB, DL, VT,
12650                         V,
12651                         DAG.getNode(ISD::SHL, DL, VT,
12652                                     V,
12653                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
12654                                                     MVT::i32)));
12655     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
12656       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
12657       Res = DAG.getNode(ISD::ADD, DL, VT,
12658                         V,
12659                         DAG.getNode(ISD::SHL, DL, VT,
12660                                     V,
12661                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
12662                                                     MVT::i32)));
12663       Res = DAG.getNode(ISD::SUB, DL, VT,
12664                         DAG.getConstant(0, DL, MVT::i32), Res);
12665     } else
12666       return SDValue();
12667   }
12668 
12669   if (ShiftAmt != 0)
12670     Res = DAG.getNode(ISD::SHL, DL, VT,
12671                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
12672 
12673   // Do not add new nodes to DAG combiner worklist.
12674   DCI.CombineTo(N, Res, false);
12675   return SDValue();
12676 }
12677 
12678 static SDValue CombineANDShift(SDNode *N,
12679                                TargetLowering::DAGCombinerInfo &DCI,
12680                                const ARMSubtarget *Subtarget) {
12681   // Allow DAGCombine to pattern-match before we touch the canonical form.
12682   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12683     return SDValue();
12684 
12685   if (N->getValueType(0) != MVT::i32)
12686     return SDValue();
12687 
12688   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12689   if (!N1C)
12690     return SDValue();
12691 
12692   uint32_t C1 = (uint32_t)N1C->getZExtValue();
12693   // Don't transform uxtb/uxth.
12694   if (C1 == 255 || C1 == 65535)
12695     return SDValue();
12696 
12697   SDNode *N0 = N->getOperand(0).getNode();
12698   if (!N0->hasOneUse())
12699     return SDValue();
12700 
12701   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
12702     return SDValue();
12703 
12704   bool LeftShift = N0->getOpcode() == ISD::SHL;
12705 
12706   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12707   if (!N01C)
12708     return SDValue();
12709 
12710   uint32_t C2 = (uint32_t)N01C->getZExtValue();
12711   if (!C2 || C2 >= 32)
12712     return SDValue();
12713 
12714   // Clear irrelevant bits in the mask.
12715   if (LeftShift)
12716     C1 &= (-1U << C2);
12717   else
12718     C1 &= (-1U >> C2);
12719 
12720   SelectionDAG &DAG = DCI.DAG;
12721   SDLoc DL(N);
12722 
12723   // We have a pattern of the form "(and (shl x, c2) c1)" or
12724   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
12725   // transform to a pair of shifts, to save materializing c1.
12726 
12727   // First pattern: right shift, then mask off leading bits.
12728   // FIXME: Use demanded bits?
12729   if (!LeftShift && isMask_32(C1)) {
12730     uint32_t C3 = countLeadingZeros(C1);
12731     if (C2 < C3) {
12732       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12733                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12734       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12735                          DAG.getConstant(C3, DL, MVT::i32));
12736     }
12737   }
12738 
12739   // First pattern, reversed: left shift, then mask off trailing bits.
12740   if (LeftShift && isMask_32(~C1)) {
12741     uint32_t C3 = countTrailingZeros(C1);
12742     if (C2 < C3) {
12743       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12744                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12745       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12746                          DAG.getConstant(C3, DL, MVT::i32));
12747     }
12748   }
12749 
12750   // Second pattern: left shift, then mask off leading bits.
12751   // FIXME: Use demanded bits?
12752   if (LeftShift && isShiftedMask_32(C1)) {
12753     uint32_t Trailing = countTrailingZeros(C1);
12754     uint32_t C3 = countLeadingZeros(C1);
12755     if (Trailing == C2 && C2 + C3 < 32) {
12756       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12757                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12758       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12759                         DAG.getConstant(C3, DL, MVT::i32));
12760     }
12761   }
12762 
12763   // Second pattern, reversed: right shift, then mask off trailing bits.
12764   // FIXME: Handle other patterns of known/demanded bits.
12765   if (!LeftShift && isShiftedMask_32(C1)) {
12766     uint32_t Leading = countLeadingZeros(C1);
12767     uint32_t C3 = countTrailingZeros(C1);
12768     if (Leading == C2 && C2 + C3 < 32) {
12769       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12770                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12771       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12772                          DAG.getConstant(C3, DL, MVT::i32));
12773     }
12774   }
12775 
12776   // FIXME: Transform "(and (shl x, c2) c1)" ->
12777   // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
12778   // c1.
12779   return SDValue();
12780 }
12781 
12782 static SDValue PerformANDCombine(SDNode *N,
12783                                  TargetLowering::DAGCombinerInfo &DCI,
12784                                  const ARMSubtarget *Subtarget) {
12785   // Attempt to use immediate-form VBIC
12786   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12787   SDLoc dl(N);
12788   EVT VT = N->getValueType(0);
12789   SelectionDAG &DAG = DCI.DAG;
12790 
12791   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT) || VT == MVT::v4i1 ||
12792       VT == MVT::v8i1 || VT == MVT::v16i1)
12793     return SDValue();
12794 
12795   APInt SplatBits, SplatUndef;
12796   unsigned SplatBitSize;
12797   bool HasAnyUndefs;
12798   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
12799       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12800     if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
12801         SplatBitSize == 64) {
12802       EVT VbicVT;
12803       SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
12804                                       SplatUndef.getZExtValue(), SplatBitSize,
12805                                       DAG, dl, VbicVT, VT, OtherModImm);
12806       if (Val.getNode()) {
12807         SDValue Input =
12808           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
12809         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
12810         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
12811       }
12812     }
12813   }
12814 
12815   if (!Subtarget->isThumb1Only()) {
12816     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
12817     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
12818       return Result;
12819 
12820     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12821       return Result;
12822   }
12823 
12824   if (Subtarget->isThumb1Only())
12825     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
12826       return Result;
12827 
12828   return SDValue();
12829 }
12830 
12831 // Try combining OR nodes to SMULWB, SMULWT.
12832 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
12833                                          TargetLowering::DAGCombinerInfo &DCI,
12834                                          const ARMSubtarget *Subtarget) {
12835   if (!Subtarget->hasV6Ops() ||
12836       (Subtarget->isThumb() &&
12837        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
12838     return SDValue();
12839 
12840   SDValue SRL = OR->getOperand(0);
12841   SDValue SHL = OR->getOperand(1);
12842 
12843   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
12844     SRL = OR->getOperand(1);
12845     SHL = OR->getOperand(0);
12846   }
12847   if (!isSRL16(SRL) || !isSHL16(SHL))
12848     return SDValue();
12849 
12850   // The first operands to the shifts need to be the two results from the
12851   // same smul_lohi node.
12852   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
12853        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
12854     return SDValue();
12855 
12856   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
12857   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
12858       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
12859     return SDValue();
12860 
12861   // Now we have:
12862   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
12863   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
12864   // For SMUWB the 16-bit value will signed extended somehow.
12865   // For SMULWT only the SRA is required.
12866   // Check both sides of SMUL_LOHI
12867   SDValue OpS16 = SMULLOHI->getOperand(0);
12868   SDValue OpS32 = SMULLOHI->getOperand(1);
12869 
12870   SelectionDAG &DAG = DCI.DAG;
12871   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
12872     OpS16 = OpS32;
12873     OpS32 = SMULLOHI->getOperand(0);
12874   }
12875 
12876   SDLoc dl(OR);
12877   unsigned Opcode = 0;
12878   if (isS16(OpS16, DAG))
12879     Opcode = ARMISD::SMULWB;
12880   else if (isSRA16(OpS16)) {
12881     Opcode = ARMISD::SMULWT;
12882     OpS16 = OpS16->getOperand(0);
12883   }
12884   else
12885     return SDValue();
12886 
12887   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
12888   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
12889   return SDValue(OR, 0);
12890 }
12891 
12892 static SDValue PerformORCombineToBFI(SDNode *N,
12893                                      TargetLowering::DAGCombinerInfo &DCI,
12894                                      const ARMSubtarget *Subtarget) {
12895   // BFI is only available on V6T2+
12896   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
12897     return SDValue();
12898 
12899   EVT VT = N->getValueType(0);
12900   SDValue N0 = N->getOperand(0);
12901   SDValue N1 = N->getOperand(1);
12902   SelectionDAG &DAG = DCI.DAG;
12903   SDLoc DL(N);
12904   // 1) or (and A, mask), val => ARMbfi A, val, mask
12905   //      iff (val & mask) == val
12906   //
12907   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12908   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
12909   //          && mask == ~mask2
12910   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
12911   //          && ~mask == mask2
12912   //  (i.e., copy a bitfield value into another bitfield of the same width)
12913 
12914   if (VT != MVT::i32)
12915     return SDValue();
12916 
12917   SDValue N00 = N0.getOperand(0);
12918 
12919   // The value and the mask need to be constants so we can verify this is
12920   // actually a bitfield set. If the mask is 0xffff, we can do better
12921   // via a movt instruction, so don't use BFI in that case.
12922   SDValue MaskOp = N0.getOperand(1);
12923   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
12924   if (!MaskC)
12925     return SDValue();
12926   unsigned Mask = MaskC->getZExtValue();
12927   if (Mask == 0xffff)
12928     return SDValue();
12929   SDValue Res;
12930   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
12931   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12932   if (N1C) {
12933     unsigned Val = N1C->getZExtValue();
12934     if ((Val & ~Mask) != Val)
12935       return SDValue();
12936 
12937     if (ARM::isBitFieldInvertedMask(Mask)) {
12938       Val >>= countTrailingZeros(~Mask);
12939 
12940       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
12941                         DAG.getConstant(Val, DL, MVT::i32),
12942                         DAG.getConstant(Mask, DL, MVT::i32));
12943 
12944       DCI.CombineTo(N, Res, false);
12945       // Return value from the original node to inform the combiner than N is
12946       // now dead.
12947       return SDValue(N, 0);
12948     }
12949   } else if (N1.getOpcode() == ISD::AND) {
12950     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12951     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12952     if (!N11C)
12953       return SDValue();
12954     unsigned Mask2 = N11C->getZExtValue();
12955 
12956     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
12957     // as is to match.
12958     if (ARM::isBitFieldInvertedMask(Mask) &&
12959         (Mask == ~Mask2)) {
12960       // The pack halfword instruction works better for masks that fit it,
12961       // so use that when it's available.
12962       if (Subtarget->hasDSP() &&
12963           (Mask == 0xffff || Mask == 0xffff0000))
12964         return SDValue();
12965       // 2a
12966       unsigned amt = countTrailingZeros(Mask2);
12967       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
12968                         DAG.getConstant(amt, DL, MVT::i32));
12969       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
12970                         DAG.getConstant(Mask, DL, MVT::i32));
12971       DCI.CombineTo(N, Res, false);
12972       // Return value from the original node to inform the combiner than N is
12973       // now dead.
12974       return SDValue(N, 0);
12975     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
12976                (~Mask == Mask2)) {
12977       // The pack halfword instruction works better for masks that fit it,
12978       // so use that when it's available.
12979       if (Subtarget->hasDSP() &&
12980           (Mask2 == 0xffff || Mask2 == 0xffff0000))
12981         return SDValue();
12982       // 2b
12983       unsigned lsb = countTrailingZeros(Mask);
12984       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
12985                         DAG.getConstant(lsb, DL, MVT::i32));
12986       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
12987                         DAG.getConstant(Mask2, DL, MVT::i32));
12988       DCI.CombineTo(N, Res, false);
12989       // Return value from the original node to inform the combiner than N is
12990       // now dead.
12991       return SDValue(N, 0);
12992     }
12993   }
12994 
12995   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
12996       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
12997       ARM::isBitFieldInvertedMask(~Mask)) {
12998     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
12999     // where lsb(mask) == #shamt and masked bits of B are known zero.
13000     SDValue ShAmt = N00.getOperand(1);
13001     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
13002     unsigned LSB = countTrailingZeros(Mask);
13003     if (ShAmtC != LSB)
13004       return SDValue();
13005 
13006     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
13007                       DAG.getConstant(~Mask, DL, MVT::i32));
13008 
13009     DCI.CombineTo(N, Res, false);
13010     // Return value from the original node to inform the combiner than N is
13011     // now dead.
13012     return SDValue(N, 0);
13013   }
13014 
13015   return SDValue();
13016 }
13017 
13018 static bool isValidMVECond(unsigned CC, bool IsFloat) {
13019   switch (CC) {
13020   case ARMCC::EQ:
13021   case ARMCC::NE:
13022   case ARMCC::LE:
13023   case ARMCC::GT:
13024   case ARMCC::GE:
13025   case ARMCC::LT:
13026     return true;
13027   case ARMCC::HS:
13028   case ARMCC::HI:
13029     return !IsFloat;
13030   default:
13031     return false;
13032   };
13033 }
13034 
13035 static ARMCC::CondCodes getVCMPCondCode(SDValue N) {
13036   if (N->getOpcode() == ARMISD::VCMP)
13037     return (ARMCC::CondCodes)N->getConstantOperandVal(2);
13038   else if (N->getOpcode() == ARMISD::VCMPZ)
13039     return (ARMCC::CondCodes)N->getConstantOperandVal(1);
13040   else
13041     llvm_unreachable("Not a VCMP/VCMPZ!");
13042 }
13043 
13044 static bool CanInvertMVEVCMP(SDValue N) {
13045   ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N));
13046   return isValidMVECond(CC, N->getOperand(0).getValueType().isFloatingPoint());
13047 }
13048 
13049 static SDValue PerformORCombine_i1(SDNode *N,
13050                                    TargetLowering::DAGCombinerInfo &DCI,
13051                                    const ARMSubtarget *Subtarget) {
13052   // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
13053   // together with predicates
13054   EVT VT = N->getValueType(0);
13055   SDLoc DL(N);
13056   SDValue N0 = N->getOperand(0);
13057   SDValue N1 = N->getOperand(1);
13058 
13059   auto IsFreelyInvertable = [&](SDValue V) {
13060     if (V->getOpcode() == ARMISD::VCMP || V->getOpcode() == ARMISD::VCMPZ)
13061       return CanInvertMVEVCMP(V);
13062     return false;
13063   };
13064 
13065   // At least one operand must be freely invertable.
13066   if (!(IsFreelyInvertable(N0) || IsFreelyInvertable(N1)))
13067     return SDValue();
13068 
13069   SDValue NewN0 = DCI.DAG.getLogicalNOT(DL, N0, VT);
13070   SDValue NewN1 = DCI.DAG.getLogicalNOT(DL, N1, VT);
13071   SDValue And = DCI.DAG.getNode(ISD::AND, DL, VT, NewN0, NewN1);
13072   return DCI.DAG.getLogicalNOT(DL, And, VT);
13073 }
13074 
13075 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
13076 static SDValue PerformORCombine(SDNode *N,
13077                                 TargetLowering::DAGCombinerInfo &DCI,
13078                                 const ARMSubtarget *Subtarget) {
13079   // Attempt to use immediate-form VORR
13080   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
13081   SDLoc dl(N);
13082   EVT VT = N->getValueType(0);
13083   SelectionDAG &DAG = DCI.DAG;
13084 
13085   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13086     return SDValue();
13087 
13088   if (Subtarget->hasMVEIntegerOps() &&
13089       (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
13090     return PerformORCombine_i1(N, DCI, Subtarget);
13091 
13092   APInt SplatBits, SplatUndef;
13093   unsigned SplatBitSize;
13094   bool HasAnyUndefs;
13095   if (BVN && (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) &&
13096       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
13097     if (SplatBitSize == 8 || SplatBitSize == 16 || SplatBitSize == 32 ||
13098         SplatBitSize == 64) {
13099       EVT VorrVT;
13100       SDValue Val =
13101           isVMOVModifiedImm(SplatBits.getZExtValue(), SplatUndef.getZExtValue(),
13102                             SplatBitSize, DAG, dl, VorrVT, VT, OtherModImm);
13103       if (Val.getNode()) {
13104         SDValue Input =
13105           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
13106         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
13107         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
13108       }
13109     }
13110   }
13111 
13112   if (!Subtarget->isThumb1Only()) {
13113     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
13114     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
13115       return Result;
13116     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
13117       return Result;
13118   }
13119 
13120   SDValue N0 = N->getOperand(0);
13121   SDValue N1 = N->getOperand(1);
13122 
13123   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
13124   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
13125       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
13126 
13127     // The code below optimizes (or (and X, Y), Z).
13128     // The AND operand needs to have a single user to make these optimizations
13129     // profitable.
13130     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
13131       return SDValue();
13132 
13133     APInt SplatUndef;
13134     unsigned SplatBitSize;
13135     bool HasAnyUndefs;
13136 
13137     APInt SplatBits0, SplatBits1;
13138     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
13139     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
13140     // Ensure that the second operand of both ands are constants
13141     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
13142                                       HasAnyUndefs) && !HasAnyUndefs) {
13143         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
13144                                           HasAnyUndefs) && !HasAnyUndefs) {
13145             // Ensure that the bit width of the constants are the same and that
13146             // the splat arguments are logical inverses as per the pattern we
13147             // are trying to simplify.
13148             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
13149                 SplatBits0 == ~SplatBits1) {
13150                 // Canonicalize the vector type to make instruction selection
13151                 // simpler.
13152                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
13153                 SDValue Result = DAG.getNode(ARMISD::VBSP, dl, CanonicalVT,
13154                                              N0->getOperand(1),
13155                                              N0->getOperand(0),
13156                                              N1->getOperand(0));
13157                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13158             }
13159         }
13160     }
13161   }
13162 
13163   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
13164   // reasonable.
13165   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
13166     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
13167       return Res;
13168   }
13169 
13170   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13171     return Result;
13172 
13173   return SDValue();
13174 }
13175 
13176 static SDValue PerformXORCombine(SDNode *N,
13177                                  TargetLowering::DAGCombinerInfo &DCI,
13178                                  const ARMSubtarget *Subtarget) {
13179   EVT VT = N->getValueType(0);
13180   SelectionDAG &DAG = DCI.DAG;
13181 
13182   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
13183     return SDValue();
13184 
13185   if (!Subtarget->isThumb1Only()) {
13186     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
13187     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
13188       return Result;
13189 
13190     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
13191       return Result;
13192   }
13193 
13194   if (Subtarget->hasMVEIntegerOps()) {
13195     // fold (xor(vcmp/z, 1)) into a vcmp with the opposite condition.
13196     SDValue N0 = N->getOperand(0);
13197     SDValue N1 = N->getOperand(1);
13198     const TargetLowering *TLI = Subtarget->getTargetLowering();
13199     if (TLI->isConstTrueVal(N1.getNode()) &&
13200         (N0->getOpcode() == ARMISD::VCMP || N0->getOpcode() == ARMISD::VCMPZ)) {
13201       if (CanInvertMVEVCMP(N0)) {
13202         SDLoc DL(N0);
13203         ARMCC::CondCodes CC = ARMCC::getOppositeCondition(getVCMPCondCode(N0));
13204 
13205         SmallVector<SDValue, 4> Ops;
13206         Ops.push_back(N0->getOperand(0));
13207         if (N0->getOpcode() == ARMISD::VCMP)
13208           Ops.push_back(N0->getOperand(1));
13209         Ops.push_back(DCI.DAG.getConstant(CC, DL, MVT::i32));
13210         return DCI.DAG.getNode(N0->getOpcode(), DL, N0->getValueType(0), Ops);
13211       }
13212     }
13213   }
13214 
13215   return SDValue();
13216 }
13217 
13218 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
13219 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
13220 // their position in "to" (Rd).
13221 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
13222   assert(N->getOpcode() == ARMISD::BFI);
13223 
13224   SDValue From = N->getOperand(1);
13225   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
13226   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
13227 
13228   // If the Base came from a SHR #C, we can deduce that it is really testing bit
13229   // #C in the base of the SHR.
13230   if (From->getOpcode() == ISD::SRL &&
13231       isa<ConstantSDNode>(From->getOperand(1))) {
13232     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
13233     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
13234     FromMask <<= Shift.getLimitedValue(31);
13235     From = From->getOperand(0);
13236   }
13237 
13238   return From;
13239 }
13240 
13241 // If A and B contain one contiguous set of bits, does A | B == A . B?
13242 //
13243 // Neither A nor B must be zero.
13244 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
13245   unsigned LastActiveBitInA =  A.countTrailingZeros();
13246   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
13247   return LastActiveBitInA - 1 == FirstActiveBitInB;
13248 }
13249 
13250 static SDValue FindBFIToCombineWith(SDNode *N) {
13251   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
13252   // if one exists.
13253   APInt ToMask, FromMask;
13254   SDValue From = ParseBFI(N, ToMask, FromMask);
13255   SDValue To = N->getOperand(0);
13256 
13257   // Now check for a compatible BFI to merge with. We can pass through BFIs that
13258   // aren't compatible, but not if they set the same bit in their destination as
13259   // we do (or that of any BFI we're going to combine with).
13260   SDValue V = To;
13261   APInt CombinedToMask = ToMask;
13262   while (V.getOpcode() == ARMISD::BFI) {
13263     APInt NewToMask, NewFromMask;
13264     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
13265     if (NewFrom != From) {
13266       // This BFI has a different base. Keep going.
13267       CombinedToMask |= NewToMask;
13268       V = V.getOperand(0);
13269       continue;
13270     }
13271 
13272     // Do the written bits conflict with any we've seen so far?
13273     if ((NewToMask & CombinedToMask).getBoolValue())
13274       // Conflicting bits - bail out because going further is unsafe.
13275       return SDValue();
13276 
13277     // Are the new bits contiguous when combined with the old bits?
13278     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
13279         BitsProperlyConcatenate(FromMask, NewFromMask))
13280       return V;
13281     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
13282         BitsProperlyConcatenate(NewFromMask, FromMask))
13283       return V;
13284 
13285     // We've seen a write to some bits, so track it.
13286     CombinedToMask |= NewToMask;
13287     // Keep going...
13288     V = V.getOperand(0);
13289   }
13290 
13291   return SDValue();
13292 }
13293 
13294 static SDValue PerformBFICombine(SDNode *N,
13295                                  TargetLowering::DAGCombinerInfo &DCI) {
13296   SDValue N1 = N->getOperand(1);
13297   if (N1.getOpcode() == ISD::AND) {
13298     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
13299     // the bits being cleared by the AND are not demanded by the BFI.
13300     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
13301     if (!N11C)
13302       return SDValue();
13303     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13304     unsigned LSB = countTrailingZeros(~InvMask);
13305     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
13306     assert(Width <
13307                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
13308            "undefined behavior");
13309     unsigned Mask = (1u << Width) - 1;
13310     unsigned Mask2 = N11C->getZExtValue();
13311     if ((Mask & (~Mask2)) == 0)
13312       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
13313                              N->getOperand(0), N1.getOperand(0),
13314                              N->getOperand(2));
13315   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
13316     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
13317     // Keep track of any consecutive bits set that all come from the same base
13318     // value. We can combine these together into a single BFI.
13319     SDValue CombineBFI = FindBFIToCombineWith(N);
13320     if (CombineBFI == SDValue())
13321       return SDValue();
13322 
13323     // We've found a BFI.
13324     APInt ToMask1, FromMask1;
13325     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
13326 
13327     APInt ToMask2, FromMask2;
13328     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
13329     assert(From1 == From2);
13330     (void)From2;
13331 
13332     // First, unlink CombineBFI.
13333     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
13334     // Then create a new BFI, combining the two together.
13335     APInt NewFromMask = FromMask1 | FromMask2;
13336     APInt NewToMask = ToMask1 | ToMask2;
13337 
13338     EVT VT = N->getValueType(0);
13339     SDLoc dl(N);
13340 
13341     if (NewFromMask[0] == 0)
13342       From1 = DCI.DAG.getNode(
13343         ISD::SRL, dl, VT, From1,
13344         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
13345     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
13346                            DCI.DAG.getConstant(~NewToMask, dl, VT));
13347   }
13348   return SDValue();
13349 }
13350 
13351 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
13352 /// ARMISD::VMOVRRD.
13353 static SDValue PerformVMOVRRDCombine(SDNode *N,
13354                                      TargetLowering::DAGCombinerInfo &DCI,
13355                                      const ARMSubtarget *Subtarget) {
13356   // vmovrrd(vmovdrr x, y) -> x,y
13357   SDValue InDouble = N->getOperand(0);
13358   if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
13359     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
13360 
13361   // vmovrrd(load f64) -> (load i32), (load i32)
13362   SDNode *InNode = InDouble.getNode();
13363   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
13364       InNode->getValueType(0) == MVT::f64 &&
13365       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
13366       !cast<LoadSDNode>(InNode)->isVolatile()) {
13367     // TODO: Should this be done for non-FrameIndex operands?
13368     LoadSDNode *LD = cast<LoadSDNode>(InNode);
13369 
13370     SelectionDAG &DAG = DCI.DAG;
13371     SDLoc DL(LD);
13372     SDValue BasePtr = LD->getBasePtr();
13373     SDValue NewLD1 =
13374         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
13375                     LD->getAlignment(), LD->getMemOperand()->getFlags());
13376 
13377     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13378                                     DAG.getConstant(4, DL, MVT::i32));
13379 
13380     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
13381                                  LD->getPointerInfo().getWithOffset(4),
13382                                  std::min(4U, LD->getAlignment()),
13383                                  LD->getMemOperand()->getFlags());
13384 
13385     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
13386     if (DCI.DAG.getDataLayout().isBigEndian())
13387       std::swap (NewLD1, NewLD2);
13388     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
13389     return Result;
13390   }
13391 
13392   return SDValue();
13393 }
13394 
13395 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
13396 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
13397 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
13398   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
13399   SDValue Op0 = N->getOperand(0);
13400   SDValue Op1 = N->getOperand(1);
13401   if (Op0.getOpcode() == ISD::BITCAST)
13402     Op0 = Op0.getOperand(0);
13403   if (Op1.getOpcode() == ISD::BITCAST)
13404     Op1 = Op1.getOperand(0);
13405   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
13406       Op0.getNode() == Op1.getNode() &&
13407       Op0.getResNo() == 0 && Op1.getResNo() == 1)
13408     return DAG.getNode(ISD::BITCAST, SDLoc(N),
13409                        N->getValueType(0), Op0.getOperand(0));
13410   return SDValue();
13411 }
13412 
13413 static SDValue PerformVMOVhrCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13414   SDValue Op0 = N->getOperand(0);
13415 
13416   // VMOVhr (VMOVrh (X)) -> X
13417   if (Op0->getOpcode() == ARMISD::VMOVrh)
13418     return Op0->getOperand(0);
13419 
13420   // FullFP16: half values are passed in S-registers, and we don't
13421   // need any of the bitcast and moves:
13422   //
13423   //     t2: f32,ch = CopyFromReg t0, Register:f32 %0
13424   //   t5: i32 = bitcast t2
13425   // t18: f16 = ARMISD::VMOVhr t5
13426   if (Op0->getOpcode() == ISD::BITCAST) {
13427     SDValue Copy = Op0->getOperand(0);
13428     if (Copy.getValueType() == MVT::f32 &&
13429         Copy->getOpcode() == ISD::CopyFromReg) {
13430       SDValue Ops[] = {Copy->getOperand(0), Copy->getOperand(1)};
13431       SDValue NewCopy =
13432           DCI.DAG.getNode(ISD::CopyFromReg, SDLoc(N), N->getValueType(0), Ops);
13433       return NewCopy;
13434     }
13435   }
13436 
13437   // fold (VMOVhr (load x)) -> (load (f16*)x)
13438   if (LoadSDNode *LN0 = dyn_cast<LoadSDNode>(Op0)) {
13439     if (LN0->hasOneUse() && LN0->isUnindexed() &&
13440         LN0->getMemoryVT() == MVT::i16) {
13441       SDValue Load =
13442           DCI.DAG.getLoad(N->getValueType(0), SDLoc(N), LN0->getChain(),
13443                           LN0->getBasePtr(), LN0->getMemOperand());
13444       DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13445       DCI.DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), Load.getValue(1));
13446       return Load;
13447     }
13448   }
13449 
13450   // Only the bottom 16 bits of the source register are used.
13451   APInt DemandedMask = APInt::getLowBitsSet(32, 16);
13452   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
13453   if (TLI.SimplifyDemandedBits(Op0, DemandedMask, DCI))
13454     return SDValue(N, 0);
13455 
13456   return SDValue();
13457 }
13458 
13459 static SDValue PerformVMOVrhCombine(SDNode *N,
13460                                     TargetLowering::DAGCombinerInfo &DCI) {
13461   SDValue N0 = N->getOperand(0);
13462   EVT VT = N->getValueType(0);
13463 
13464   // fold (VMOVrh (fpconst x)) -> const x
13465   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N0)) {
13466     APFloat V = C->getValueAPF();
13467     return DCI.DAG.getConstant(V.bitcastToAPInt().getZExtValue(), SDLoc(N), VT);
13468   }
13469 
13470   // fold (VMOVrh (load x)) -> (zextload (i16*)x)
13471   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
13472     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
13473 
13474     SDValue Load =
13475         DCI.DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT, LN0->getChain(),
13476                            LN0->getBasePtr(), MVT::i16, LN0->getMemOperand());
13477     DCI.DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Load.getValue(0));
13478     DCI.DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
13479     return Load;
13480   }
13481 
13482   // Fold VMOVrh(extract(x, n)) -> vgetlaneu(x, n)
13483   if (N0->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
13484       isa<ConstantSDNode>(N0->getOperand(1)))
13485     return DCI.DAG.getNode(ARMISD::VGETLANEu, SDLoc(N), VT, N0->getOperand(0),
13486                            N0->getOperand(1));
13487 
13488   return SDValue();
13489 }
13490 
13491 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
13492 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
13493 /// i64 vector to have f64 elements, since the value can then be loaded
13494 /// directly into a VFP register.
13495 static bool hasNormalLoadOperand(SDNode *N) {
13496   unsigned NumElts = N->getValueType(0).getVectorNumElements();
13497   for (unsigned i = 0; i < NumElts; ++i) {
13498     SDNode *Elt = N->getOperand(i).getNode();
13499     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
13500       return true;
13501   }
13502   return false;
13503 }
13504 
13505 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
13506 /// ISD::BUILD_VECTOR.
13507 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
13508                                           TargetLowering::DAGCombinerInfo &DCI,
13509                                           const ARMSubtarget *Subtarget) {
13510   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
13511   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
13512   // into a pair of GPRs, which is fine when the value is used as a scalar,
13513   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
13514   SelectionDAG &DAG = DCI.DAG;
13515   if (N->getNumOperands() == 2)
13516     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
13517       return RV;
13518 
13519   // Load i64 elements as f64 values so that type legalization does not split
13520   // them up into i32 values.
13521   EVT VT = N->getValueType(0);
13522   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
13523     return SDValue();
13524   SDLoc dl(N);
13525   SmallVector<SDValue, 8> Ops;
13526   unsigned NumElts = VT.getVectorNumElements();
13527   for (unsigned i = 0; i < NumElts; ++i) {
13528     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
13529     Ops.push_back(V);
13530     // Make the DAGCombiner fold the bitcast.
13531     DCI.AddToWorklist(V.getNode());
13532   }
13533   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
13534   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
13535   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
13536 }
13537 
13538 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
13539 static SDValue
13540 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13541   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
13542   // At that time, we may have inserted bitcasts from integer to float.
13543   // If these bitcasts have survived DAGCombine, change the lowering of this
13544   // BUILD_VECTOR in something more vector friendly, i.e., that does not
13545   // force to use floating point types.
13546 
13547   // Make sure we can change the type of the vector.
13548   // This is possible iff:
13549   // 1. The vector is only used in a bitcast to a integer type. I.e.,
13550   //    1.1. Vector is used only once.
13551   //    1.2. Use is a bit convert to an integer type.
13552   // 2. The size of its operands are 32-bits (64-bits are not legal).
13553   EVT VT = N->getValueType(0);
13554   EVT EltVT = VT.getVectorElementType();
13555 
13556   // Check 1.1. and 2.
13557   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
13558     return SDValue();
13559 
13560   // By construction, the input type must be float.
13561   assert(EltVT == MVT::f32 && "Unexpected type!");
13562 
13563   // Check 1.2.
13564   SDNode *Use = *N->use_begin();
13565   if (Use->getOpcode() != ISD::BITCAST ||
13566       Use->getValueType(0).isFloatingPoint())
13567     return SDValue();
13568 
13569   // Check profitability.
13570   // Model is, if more than half of the relevant operands are bitcast from
13571   // i32, turn the build_vector into a sequence of insert_vector_elt.
13572   // Relevant operands are everything that is not statically
13573   // (i.e., at compile time) bitcasted.
13574   unsigned NumOfBitCastedElts = 0;
13575   unsigned NumElts = VT.getVectorNumElements();
13576   unsigned NumOfRelevantElts = NumElts;
13577   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
13578     SDValue Elt = N->getOperand(Idx);
13579     if (Elt->getOpcode() == ISD::BITCAST) {
13580       // Assume only bit cast to i32 will go away.
13581       if (Elt->getOperand(0).getValueType() == MVT::i32)
13582         ++NumOfBitCastedElts;
13583     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
13584       // Constants are statically casted, thus do not count them as
13585       // relevant operands.
13586       --NumOfRelevantElts;
13587   }
13588 
13589   // Check if more than half of the elements require a non-free bitcast.
13590   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
13591     return SDValue();
13592 
13593   SelectionDAG &DAG = DCI.DAG;
13594   // Create the new vector type.
13595   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
13596   // Check if the type is legal.
13597   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13598   if (!TLI.isTypeLegal(VecVT))
13599     return SDValue();
13600 
13601   // Combine:
13602   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
13603   // => BITCAST INSERT_VECTOR_ELT
13604   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
13605   //                      (BITCAST EN), N.
13606   SDValue Vec = DAG.getUNDEF(VecVT);
13607   SDLoc dl(N);
13608   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
13609     SDValue V = N->getOperand(Idx);
13610     if (V.isUndef())
13611       continue;
13612     if (V.getOpcode() == ISD::BITCAST &&
13613         V->getOperand(0).getValueType() == MVT::i32)
13614       // Fold obvious case.
13615       V = V.getOperand(0);
13616     else {
13617       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
13618       // Make the DAGCombiner fold the bitcasts.
13619       DCI.AddToWorklist(V.getNode());
13620     }
13621     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
13622     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
13623   }
13624   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
13625   // Make the DAGCombiner fold the bitcasts.
13626   DCI.AddToWorklist(Vec.getNode());
13627   return Vec;
13628 }
13629 
13630 static SDValue
13631 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13632   EVT VT = N->getValueType(0);
13633   SDValue Op = N->getOperand(0);
13634   SDLoc dl(N);
13635 
13636   // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
13637   if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
13638     // If the valuetypes are the same, we can remove the cast entirely.
13639     if (Op->getOperand(0).getValueType() == VT)
13640       return Op->getOperand(0);
13641     return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, Op->getOperand(0));
13642   }
13643 
13644   return SDValue();
13645 }
13646 
13647 static SDValue
13648 PerformVECTOR_REG_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
13649                               const ARMSubtarget *ST) {
13650   EVT VT = N->getValueType(0);
13651   SDValue Op = N->getOperand(0);
13652   SDLoc dl(N);
13653 
13654   // Under Little endian, a VECTOR_REG_CAST is equivalent to a BITCAST
13655   if (ST->isLittle())
13656     return DCI.DAG.getNode(ISD::BITCAST, dl, VT, Op);
13657 
13658   // VECTOR_REG_CAST(VECTOR_REG_CAST(x)) == VECTOR_REG_CAST(x)
13659   if (Op->getOpcode() == ARMISD::VECTOR_REG_CAST) {
13660     // If the valuetypes are the same, we can remove the cast entirely.
13661     if (Op->getOperand(0).getValueType() == VT)
13662       return Op->getOperand(0);
13663     return DCI.DAG.getNode(ARMISD::VECTOR_REG_CAST, dl, VT, Op->getOperand(0));
13664   }
13665 
13666   return SDValue();
13667 }
13668 
13669 static SDValue PerformVCMPCombine(SDNode *N,
13670                                   TargetLowering::DAGCombinerInfo &DCI,
13671                                   const ARMSubtarget *Subtarget) {
13672   if (!Subtarget->hasMVEIntegerOps())
13673     return SDValue();
13674 
13675   EVT VT = N->getValueType(0);
13676   SDValue Op0 = N->getOperand(0);
13677   SDValue Op1 = N->getOperand(1);
13678   ARMCC::CondCodes Cond =
13679       (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
13680   SDLoc dl(N);
13681 
13682   // vcmp X, 0, cc -> vcmpz X, cc
13683   if (isZeroVector(Op1))
13684     return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0,
13685                            N->getOperand(2));
13686 
13687   unsigned SwappedCond = getSwappedCondition(Cond);
13688   if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
13689     // vcmp 0, X, cc -> vcmpz X, reversed(cc)
13690     if (isZeroVector(Op0))
13691       return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
13692                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13693     // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
13694     if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
13695       return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
13696                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
13697   }
13698 
13699   return SDValue();
13700 }
13701 
13702 /// PerformInsertEltCombine - Target-specific dag combine xforms for
13703 /// ISD::INSERT_VECTOR_ELT.
13704 static SDValue PerformInsertEltCombine(SDNode *N,
13705                                        TargetLowering::DAGCombinerInfo &DCI) {
13706   // Bitcast an i64 load inserted into a vector to f64.
13707   // Otherwise, the i64 value will be legalized to a pair of i32 values.
13708   EVT VT = N->getValueType(0);
13709   SDNode *Elt = N->getOperand(1).getNode();
13710   if (VT.getVectorElementType() != MVT::i64 ||
13711       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
13712     return SDValue();
13713 
13714   SelectionDAG &DAG = DCI.DAG;
13715   SDLoc dl(N);
13716   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13717                                  VT.getVectorNumElements());
13718   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
13719   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
13720   // Make the DAGCombiner fold the bitcasts.
13721   DCI.AddToWorklist(Vec.getNode());
13722   DCI.AddToWorklist(V.getNode());
13723   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
13724                                Vec, V, N->getOperand(2));
13725   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
13726 }
13727 
13728 static SDValue PerformExtractEltCombine(SDNode *N,
13729                                         TargetLowering::DAGCombinerInfo &DCI) {
13730   SDValue Op0 = N->getOperand(0);
13731   EVT VT = N->getValueType(0);
13732   SDLoc dl(N);
13733 
13734   // extract (vdup x) -> x
13735   if (Op0->getOpcode() == ARMISD::VDUP) {
13736     SDValue X = Op0->getOperand(0);
13737     if (VT == MVT::f16 && X.getValueType() == MVT::i32)
13738       return DCI.DAG.getNode(ARMISD::VMOVhr, dl, VT, X);
13739     if (VT == MVT::i32 && X.getValueType() == MVT::f16)
13740       return DCI.DAG.getNode(ARMISD::VMOVrh, dl, VT, X);
13741 
13742     while (X.getValueType() != VT && X->getOpcode() == ISD::BITCAST)
13743       X = X->getOperand(0);
13744     if (X.getValueType() == VT)
13745       return X;
13746   }
13747 
13748   return SDValue();
13749 }
13750 
13751 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
13752 /// ISD::VECTOR_SHUFFLE.
13753 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
13754   // The LLVM shufflevector instruction does not require the shuffle mask
13755   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
13756   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
13757   // operands do not match the mask length, they are extended by concatenating
13758   // them with undef vectors.  That is probably the right thing for other
13759   // targets, but for NEON it is better to concatenate two double-register
13760   // size vector operands into a single quad-register size vector.  Do that
13761   // transformation here:
13762   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
13763   //   shuffle(concat(v1, v2), undef)
13764   SDValue Op0 = N->getOperand(0);
13765   SDValue Op1 = N->getOperand(1);
13766   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
13767       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
13768       Op0.getNumOperands() != 2 ||
13769       Op1.getNumOperands() != 2)
13770     return SDValue();
13771   SDValue Concat0Op1 = Op0.getOperand(1);
13772   SDValue Concat1Op1 = Op1.getOperand(1);
13773   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
13774     return SDValue();
13775   // Skip the transformation if any of the types are illegal.
13776   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13777   EVT VT = N->getValueType(0);
13778   if (!TLI.isTypeLegal(VT) ||
13779       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
13780       !TLI.isTypeLegal(Concat1Op1.getValueType()))
13781     return SDValue();
13782 
13783   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13784                                   Op0.getOperand(0), Op1.getOperand(0));
13785   // Translate the shuffle mask.
13786   SmallVector<int, 16> NewMask;
13787   unsigned NumElts = VT.getVectorNumElements();
13788   unsigned HalfElts = NumElts/2;
13789   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
13790   for (unsigned n = 0; n < NumElts; ++n) {
13791     int MaskElt = SVN->getMaskElt(n);
13792     int NewElt = -1;
13793     if (MaskElt < (int)HalfElts)
13794       NewElt = MaskElt;
13795     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
13796       NewElt = HalfElts + MaskElt - NumElts;
13797     NewMask.push_back(NewElt);
13798   }
13799   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
13800                               DAG.getUNDEF(VT), NewMask);
13801 }
13802 
13803 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
13804 /// NEON load/store intrinsics, and generic vector load/stores, to merge
13805 /// base address updates.
13806 /// For generic load/stores, the memory type is assumed to be a vector.
13807 /// The caller is assumed to have checked legality.
13808 static SDValue CombineBaseUpdate(SDNode *N,
13809                                  TargetLowering::DAGCombinerInfo &DCI) {
13810   SelectionDAG &DAG = DCI.DAG;
13811   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
13812                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
13813   const bool isStore = N->getOpcode() == ISD::STORE;
13814   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
13815   SDValue Addr = N->getOperand(AddrOpIdx);
13816   MemSDNode *MemN = cast<MemSDNode>(N);
13817   SDLoc dl(N);
13818 
13819   // Search for a use of the address operand that is an increment.
13820   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
13821          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
13822     SDNode *User = *UI;
13823     if (User->getOpcode() != ISD::ADD ||
13824         UI.getUse().getResNo() != Addr.getResNo())
13825       continue;
13826 
13827     // Check that the add is independent of the load/store.  Otherwise, folding
13828     // it would create a cycle. We can avoid searching through Addr as it's a
13829     // predecessor to both.
13830     SmallPtrSet<const SDNode *, 32> Visited;
13831     SmallVector<const SDNode *, 16> Worklist;
13832     Visited.insert(Addr.getNode());
13833     Worklist.push_back(N);
13834     Worklist.push_back(User);
13835     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
13836         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13837       continue;
13838 
13839     // Find the new opcode for the updating load/store.
13840     bool isLoadOp = true;
13841     bool isLaneOp = false;
13842     unsigned NewOpc = 0;
13843     unsigned NumVecs = 0;
13844     if (isIntrinsic) {
13845       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
13846       switch (IntNo) {
13847       default: llvm_unreachable("unexpected intrinsic for Neon base update");
13848       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
13849         NumVecs = 1; break;
13850       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
13851         NumVecs = 2; break;
13852       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
13853         NumVecs = 3; break;
13854       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
13855         NumVecs = 4; break;
13856       case Intrinsic::arm_neon_vld1x2:
13857       case Intrinsic::arm_neon_vld1x3:
13858       case Intrinsic::arm_neon_vld1x4:
13859       case Intrinsic::arm_neon_vld2dup:
13860       case Intrinsic::arm_neon_vld3dup:
13861       case Intrinsic::arm_neon_vld4dup:
13862         // TODO: Support updating VLD1x and VLDxDUP nodes. For now, we just skip
13863         // combining base updates for such intrinsics.
13864         continue;
13865       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
13866         NumVecs = 2; isLaneOp = true; break;
13867       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
13868         NumVecs = 3; isLaneOp = true; break;
13869       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
13870         NumVecs = 4; isLaneOp = true; break;
13871       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
13872         NumVecs = 1; isLoadOp = false; break;
13873       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
13874         NumVecs = 2; isLoadOp = false; break;
13875       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
13876         NumVecs = 3; isLoadOp = false; break;
13877       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
13878         NumVecs = 4; isLoadOp = false; break;
13879       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
13880         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
13881       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
13882         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
13883       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
13884         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
13885       }
13886     } else {
13887       isLaneOp = true;
13888       switch (N->getOpcode()) {
13889       default: llvm_unreachable("unexpected opcode for Neon base update");
13890       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
13891       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
13892       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
13893       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
13894       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
13895         NumVecs = 1; isLaneOp = false; break;
13896       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
13897         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
13898       }
13899     }
13900 
13901     // Find the size of memory referenced by the load/store.
13902     EVT VecTy;
13903     if (isLoadOp) {
13904       VecTy = N->getValueType(0);
13905     } else if (isIntrinsic) {
13906       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
13907     } else {
13908       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
13909       VecTy = N->getOperand(1).getValueType();
13910     }
13911 
13912     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
13913     if (isLaneOp)
13914       NumBytes /= VecTy.getVectorNumElements();
13915 
13916     // If the increment is a constant, it must match the memory ref size.
13917     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13918     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
13919     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
13920       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
13921       // separate instructions that make it harder to use a non-constant update.
13922       continue;
13923     }
13924 
13925     // OK, we found an ADD we can fold into the base update.
13926     // Now, create a _UPD node, taking care of not breaking alignment.
13927 
13928     EVT AlignedVecTy = VecTy;
13929     unsigned Alignment = MemN->getAlignment();
13930 
13931     // If this is a less-than-standard-aligned load/store, change the type to
13932     // match the standard alignment.
13933     // The alignment is overlooked when selecting _UPD variants; and it's
13934     // easier to introduce bitcasts here than fix that.
13935     // There are 3 ways to get to this base-update combine:
13936     // - intrinsics: they are assumed to be properly aligned (to the standard
13937     //   alignment of the memory type), so we don't need to do anything.
13938     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
13939     //   intrinsics, so, likewise, there's nothing to do.
13940     // - generic load/store instructions: the alignment is specified as an
13941     //   explicit operand, rather than implicitly as the standard alignment
13942     //   of the memory type (like the intrisics).  We need to change the
13943     //   memory type to match the explicit alignment.  That way, we don't
13944     //   generate non-standard-aligned ARMISD::VLDx nodes.
13945     if (isa<LSBaseSDNode>(N)) {
13946       if (Alignment == 0)
13947         Alignment = 1;
13948       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
13949         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
13950         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
13951         assert(!isLaneOp && "Unexpected generic load/store lane.");
13952         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
13953         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
13954       }
13955       // Don't set an explicit alignment on regular load/stores that we want
13956       // to transform to VLD/VST 1_UPD nodes.
13957       // This matches the behavior of regular load/stores, which only get an
13958       // explicit alignment if the MMO alignment is larger than the standard
13959       // alignment of the memory type.
13960       // Intrinsics, however, always get an explicit alignment, set to the
13961       // alignment of the MMO.
13962       Alignment = 1;
13963     }
13964 
13965     // Create the new updating load/store node.
13966     // First, create an SDVTList for the new updating node's results.
13967     EVT Tys[6];
13968     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
13969     unsigned n;
13970     for (n = 0; n < NumResultVecs; ++n)
13971       Tys[n] = AlignedVecTy;
13972     Tys[n++] = MVT::i32;
13973     Tys[n] = MVT::Other;
13974     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
13975 
13976     // Then, gather the new node's operands.
13977     SmallVector<SDValue, 8> Ops;
13978     Ops.push_back(N->getOperand(0)); // incoming chain
13979     Ops.push_back(N->getOperand(AddrOpIdx));
13980     Ops.push_back(Inc);
13981 
13982     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
13983       // Try to match the intrinsic's signature
13984       Ops.push_back(StN->getValue());
13985     } else {
13986       // Loads (and of course intrinsics) match the intrinsics' signature,
13987       // so just add all but the alignment operand.
13988       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
13989         Ops.push_back(N->getOperand(i));
13990     }
13991 
13992     // For all node types, the alignment operand is always the last one.
13993     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
13994 
13995     // If this is a non-standard-aligned STORE, the penultimate operand is the
13996     // stored value.  Bitcast it to the aligned type.
13997     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
13998       SDValue &StVal = Ops[Ops.size()-2];
13999       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
14000     }
14001 
14002     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
14003     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
14004                                            MemN->getMemOperand());
14005 
14006     // Update the uses.
14007     SmallVector<SDValue, 5> NewResults;
14008     for (unsigned i = 0; i < NumResultVecs; ++i)
14009       NewResults.push_back(SDValue(UpdN.getNode(), i));
14010 
14011     // If this is an non-standard-aligned LOAD, the first result is the loaded
14012     // value.  Bitcast it to the expected result type.
14013     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
14014       SDValue &LdVal = NewResults[0];
14015       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
14016     }
14017 
14018     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
14019     DCI.CombineTo(N, NewResults);
14020     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
14021 
14022     break;
14023   }
14024   return SDValue();
14025 }
14026 
14027 static SDValue PerformVLDCombine(SDNode *N,
14028                                  TargetLowering::DAGCombinerInfo &DCI) {
14029   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14030     return SDValue();
14031 
14032   return CombineBaseUpdate(N, DCI);
14033 }
14034 
14035 static SDValue PerformMVEVLDCombine(SDNode *N,
14036                                     TargetLowering::DAGCombinerInfo &DCI) {
14037   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
14038     return SDValue();
14039 
14040   SelectionDAG &DAG = DCI.DAG;
14041   SDValue Addr = N->getOperand(2);
14042   MemSDNode *MemN = cast<MemSDNode>(N);
14043   SDLoc dl(N);
14044 
14045   // For the stores, where there are multiple intrinsics we only actually want
14046   // to post-inc the last of the them.
14047   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14048   if (IntNo == Intrinsic::arm_mve_vst2q &&
14049       cast<ConstantSDNode>(N->getOperand(5))->getZExtValue() != 1)
14050     return SDValue();
14051   if (IntNo == Intrinsic::arm_mve_vst4q &&
14052       cast<ConstantSDNode>(N->getOperand(7))->getZExtValue() != 3)
14053     return SDValue();
14054 
14055   // Search for a use of the address operand that is an increment.
14056   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
14057                             UE = Addr.getNode()->use_end();
14058        UI != UE; ++UI) {
14059     SDNode *User = *UI;
14060     if (User->getOpcode() != ISD::ADD ||
14061         UI.getUse().getResNo() != Addr.getResNo())
14062       continue;
14063 
14064     // Check that the add is independent of the load/store.  Otherwise, folding
14065     // it would create a cycle. We can avoid searching through Addr as it's a
14066     // predecessor to both.
14067     SmallPtrSet<const SDNode *, 32> Visited;
14068     SmallVector<const SDNode *, 16> Worklist;
14069     Visited.insert(Addr.getNode());
14070     Worklist.push_back(N);
14071     Worklist.push_back(User);
14072     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
14073         SDNode::hasPredecessorHelper(User, Visited, Worklist))
14074       continue;
14075 
14076     // Find the new opcode for the updating load/store.
14077     bool isLoadOp = true;
14078     unsigned NewOpc = 0;
14079     unsigned NumVecs = 0;
14080     switch (IntNo) {
14081     default:
14082       llvm_unreachable("unexpected intrinsic for MVE VLDn combine");
14083     case Intrinsic::arm_mve_vld2q:
14084       NewOpc = ARMISD::VLD2_UPD;
14085       NumVecs = 2;
14086       break;
14087     case Intrinsic::arm_mve_vld4q:
14088       NewOpc = ARMISD::VLD4_UPD;
14089       NumVecs = 4;
14090       break;
14091     case Intrinsic::arm_mve_vst2q:
14092       NewOpc = ARMISD::VST2_UPD;
14093       NumVecs = 2;
14094       isLoadOp = false;
14095       break;
14096     case Intrinsic::arm_mve_vst4q:
14097       NewOpc = ARMISD::VST4_UPD;
14098       NumVecs = 4;
14099       isLoadOp = false;
14100       break;
14101     }
14102 
14103     // Find the size of memory referenced by the load/store.
14104     EVT VecTy;
14105     if (isLoadOp) {
14106       VecTy = N->getValueType(0);
14107     } else {
14108       VecTy = N->getOperand(3).getValueType();
14109     }
14110 
14111     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
14112 
14113     // If the increment is a constant, it must match the memory ref size.
14114     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
14115     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
14116     if (!CInc || CInc->getZExtValue() != NumBytes)
14117       continue;
14118 
14119     // Create the new updating load/store node.
14120     // First, create an SDVTList for the new updating node's results.
14121     EVT Tys[6];
14122     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
14123     unsigned n;
14124     for (n = 0; n < NumResultVecs; ++n)
14125       Tys[n] = VecTy;
14126     Tys[n++] = MVT::i32;
14127     Tys[n] = MVT::Other;
14128     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
14129 
14130     // Then, gather the new node's operands.
14131     SmallVector<SDValue, 8> Ops;
14132     Ops.push_back(N->getOperand(0)); // incoming chain
14133     Ops.push_back(N->getOperand(2)); // ptr
14134     Ops.push_back(Inc);
14135 
14136     for (unsigned i = 3; i < N->getNumOperands(); ++i)
14137       Ops.push_back(N->getOperand(i));
14138 
14139     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, VecTy,
14140                                            MemN->getMemOperand());
14141 
14142     // Update the uses.
14143     SmallVector<SDValue, 5> NewResults;
14144     for (unsigned i = 0; i < NumResultVecs; ++i)
14145       NewResults.push_back(SDValue(UpdN.getNode(), i));
14146 
14147     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1)); // chain
14148     DCI.CombineTo(N, NewResults);
14149     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
14150 
14151     break;
14152   }
14153 
14154   return SDValue();
14155 }
14156 
14157 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
14158 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
14159 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
14160 /// return true.
14161 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
14162   SelectionDAG &DAG = DCI.DAG;
14163   EVT VT = N->getValueType(0);
14164   // vldN-dup instructions only support 64-bit vectors for N > 1.
14165   if (!VT.is64BitVector())
14166     return false;
14167 
14168   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
14169   SDNode *VLD = N->getOperand(0).getNode();
14170   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
14171     return false;
14172   unsigned NumVecs = 0;
14173   unsigned NewOpc = 0;
14174   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
14175   if (IntNo == Intrinsic::arm_neon_vld2lane) {
14176     NumVecs = 2;
14177     NewOpc = ARMISD::VLD2DUP;
14178   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
14179     NumVecs = 3;
14180     NewOpc = ARMISD::VLD3DUP;
14181   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
14182     NumVecs = 4;
14183     NewOpc = ARMISD::VLD4DUP;
14184   } else {
14185     return false;
14186   }
14187 
14188   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
14189   // numbers match the load.
14190   unsigned VLDLaneNo =
14191     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
14192   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
14193        UI != UE; ++UI) {
14194     // Ignore uses of the chain result.
14195     if (UI.getUse().getResNo() == NumVecs)
14196       continue;
14197     SDNode *User = *UI;
14198     if (User->getOpcode() != ARMISD::VDUPLANE ||
14199         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
14200       return false;
14201   }
14202 
14203   // Create the vldN-dup node.
14204   EVT Tys[5];
14205   unsigned n;
14206   for (n = 0; n < NumVecs; ++n)
14207     Tys[n] = VT;
14208   Tys[n] = MVT::Other;
14209   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
14210   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
14211   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
14212   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
14213                                            Ops, VLDMemInt->getMemoryVT(),
14214                                            VLDMemInt->getMemOperand());
14215 
14216   // Update the uses.
14217   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
14218        UI != UE; ++UI) {
14219     unsigned ResNo = UI.getUse().getResNo();
14220     // Ignore uses of the chain result.
14221     if (ResNo == NumVecs)
14222       continue;
14223     SDNode *User = *UI;
14224     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
14225   }
14226 
14227   // Now the vldN-lane intrinsic is dead except for its chain result.
14228   // Update uses of the chain.
14229   std::vector<SDValue> VLDDupResults;
14230   for (unsigned n = 0; n < NumVecs; ++n)
14231     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
14232   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
14233   DCI.CombineTo(VLD, VLDDupResults);
14234 
14235   return true;
14236 }
14237 
14238 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
14239 /// ARMISD::VDUPLANE.
14240 static SDValue PerformVDUPLANECombine(SDNode *N,
14241                                       TargetLowering::DAGCombinerInfo &DCI,
14242                                       const ARMSubtarget *Subtarget) {
14243   SDValue Op = N->getOperand(0);
14244   EVT VT = N->getValueType(0);
14245 
14246   // On MVE, we just convert the VDUPLANE to a VDUP with an extract.
14247   if (Subtarget->hasMVEIntegerOps()) {
14248     EVT ExtractVT = VT.getVectorElementType();
14249     // We need to ensure we are creating a legal type.
14250     if (!DCI.DAG.getTargetLoweringInfo().isTypeLegal(ExtractVT))
14251       ExtractVT = MVT::i32;
14252     SDValue Extract = DCI.DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), ExtractVT,
14253                               N->getOperand(0), N->getOperand(1));
14254     return DCI.DAG.getNode(ARMISD::VDUP, SDLoc(N), VT, Extract);
14255   }
14256 
14257   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
14258   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
14259   if (CombineVLDDUP(N, DCI))
14260     return SDValue(N, 0);
14261 
14262   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
14263   // redundant.  Ignore bit_converts for now; element sizes are checked below.
14264   while (Op.getOpcode() == ISD::BITCAST)
14265     Op = Op.getOperand(0);
14266   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
14267     return SDValue();
14268 
14269   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
14270   unsigned EltSize = Op.getScalarValueSizeInBits();
14271   // The canonical VMOV for a zero vector uses a 32-bit element size.
14272   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14273   unsigned EltBits;
14274   if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
14275     EltSize = 8;
14276   if (EltSize > VT.getScalarSizeInBits())
14277     return SDValue();
14278 
14279   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
14280 }
14281 
14282 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
14283 static SDValue PerformVDUPCombine(SDNode *N,
14284                                   TargetLowering::DAGCombinerInfo &DCI,
14285                                   const ARMSubtarget *Subtarget) {
14286   SelectionDAG &DAG = DCI.DAG;
14287   SDValue Op = N->getOperand(0);
14288   SDLoc dl(N);
14289 
14290   if (Subtarget->hasMVEIntegerOps()) {
14291     // Convert VDUP f32 -> VDUP BITCAST i32 under MVE, as we know the value will
14292     // need to come from a GPR.
14293     if (Op.getValueType() == MVT::f32)
14294       return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
14295                              DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op));
14296     else if (Op.getValueType() == MVT::f16)
14297       return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0),
14298                              DAG.getNode(ARMISD::VMOVrh, dl, MVT::i32, Op));
14299   }
14300 
14301   if (!Subtarget->hasNEON())
14302     return SDValue();
14303 
14304   // Match VDUP(LOAD) -> VLD1DUP.
14305   // We match this pattern here rather than waiting for isel because the
14306   // transform is only legal for unindexed loads.
14307   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
14308   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
14309       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
14310     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
14311                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
14312     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
14313     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
14314                                              Ops, LD->getMemoryVT(),
14315                                              LD->getMemOperand());
14316     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
14317     return VLDDup;
14318   }
14319 
14320   return SDValue();
14321 }
14322 
14323 static SDValue PerformLOADCombine(SDNode *N,
14324                                   TargetLowering::DAGCombinerInfo &DCI) {
14325   EVT VT = N->getValueType(0);
14326 
14327   // If this is a legal vector load, try to combine it into a VLD1_UPD.
14328   if (ISD::isNormalLoad(N) && VT.isVector() &&
14329       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
14330     return CombineBaseUpdate(N, DCI);
14331 
14332   return SDValue();
14333 }
14334 
14335 // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
14336 // pack all of the elements in one place.  Next, store to memory in fewer
14337 // chunks.
14338 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
14339                                              SelectionDAG &DAG) {
14340   SDValue StVal = St->getValue();
14341   EVT VT = StVal.getValueType();
14342   if (!St->isTruncatingStore() || !VT.isVector())
14343     return SDValue();
14344   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14345   EVT StVT = St->getMemoryVT();
14346   unsigned NumElems = VT.getVectorNumElements();
14347   assert(StVT != VT && "Cannot truncate to the same type");
14348   unsigned FromEltSz = VT.getScalarSizeInBits();
14349   unsigned ToEltSz = StVT.getScalarSizeInBits();
14350 
14351   // From, To sizes and ElemCount must be pow of two
14352   if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
14353     return SDValue();
14354 
14355   // We are going to use the original vector elt for storing.
14356   // Accumulated smaller vector elements must be a multiple of the store size.
14357   if (0 != (NumElems * FromEltSz) % ToEltSz)
14358     return SDValue();
14359 
14360   unsigned SizeRatio = FromEltSz / ToEltSz;
14361   assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
14362 
14363   // Create a type on which we perform the shuffle.
14364   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
14365                                    NumElems * SizeRatio);
14366   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
14367 
14368   SDLoc DL(St);
14369   SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
14370   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
14371   for (unsigned i = 0; i < NumElems; ++i)
14372     ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
14373                                                       : i * SizeRatio;
14374 
14375   // Can't shuffle using an illegal type.
14376   if (!TLI.isTypeLegal(WideVecVT))
14377     return SDValue();
14378 
14379   SDValue Shuff = DAG.getVectorShuffle(
14380       WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
14381   // At this point all of the data is stored at the bottom of the
14382   // register. We now need to save it to mem.
14383 
14384   // Find the largest store unit
14385   MVT StoreType = MVT::i8;
14386   for (MVT Tp : MVT::integer_valuetypes()) {
14387     if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
14388       StoreType = Tp;
14389   }
14390   // Didn't find a legal store type.
14391   if (!TLI.isTypeLegal(StoreType))
14392     return SDValue();
14393 
14394   // Bitcast the original vector into a vector of store-size units
14395   EVT StoreVecVT =
14396       EVT::getVectorVT(*DAG.getContext(), StoreType,
14397                        VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
14398   assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
14399   SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
14400   SmallVector<SDValue, 8> Chains;
14401   SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
14402                                       TLI.getPointerTy(DAG.getDataLayout()));
14403   SDValue BasePtr = St->getBasePtr();
14404 
14405   // Perform one or more big stores into memory.
14406   unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
14407   for (unsigned I = 0; I < E; I++) {
14408     SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
14409                                  ShuffWide, DAG.getIntPtrConstant(I, DL));
14410     SDValue Ch =
14411         DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
14412                      St->getAlignment(), St->getMemOperand()->getFlags());
14413     BasePtr =
14414         DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
14415     Chains.push_back(Ch);
14416   }
14417   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
14418 }
14419 
14420 // Try taking a single vector store from an truncate (which would otherwise turn
14421 // into an expensive buildvector) and splitting it into a series of narrowing
14422 // stores.
14423 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
14424                                                  SelectionDAG &DAG) {
14425   if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
14426     return SDValue();
14427   SDValue Trunc = St->getValue();
14428   if (Trunc->getOpcode() != ISD::TRUNCATE && Trunc->getOpcode() != ISD::FP_ROUND)
14429     return SDValue();
14430   EVT FromVT = Trunc->getOperand(0).getValueType();
14431   EVT ToVT = Trunc.getValueType();
14432   if (!ToVT.isVector())
14433     return SDValue();
14434   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
14435   EVT ToEltVT = ToVT.getVectorElementType();
14436   EVT FromEltVT = FromVT.getVectorElementType();
14437 
14438   unsigned NumElements = 0;
14439   if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8))
14440     NumElements = 4;
14441   if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8)
14442     NumElements = 8;
14443   if (FromEltVT == MVT::f32 && ToEltVT == MVT::f16)
14444     NumElements = 4;
14445   if (NumElements == 0 ||
14446       (FromEltVT != MVT::f32 && FromVT.getVectorNumElements() == NumElements) ||
14447       FromVT.getVectorNumElements() % NumElements != 0)
14448     return SDValue();
14449 
14450   // Test if the Trunc will be convertable to a VMOVN with a shuffle, and if so
14451   // use the VMOVN over splitting the store. We are looking for patterns of:
14452   // !rev: 0 N 1 N+1 2 N+2 ...
14453   //  rev: N 0 N+1 1 N+2 2 ...
14454   auto isVMOVNOriginalMask = [&](ArrayRef<int> M, bool rev) {
14455     unsigned NumElts = ToVT.getVectorNumElements();
14456     if (NumElts != M.size())
14457       return false;
14458 
14459     unsigned Off0 = rev ? NumElts : 0;
14460     unsigned Off1 = rev ? 0 : NumElts;
14461 
14462     for (unsigned i = 0; i < NumElts; i += 2) {
14463       if (M[i] >= 0 && M[i] != (int)(Off0 + i / 2))
14464         return false;
14465       if (M[i + 1] >= 0 && M[i + 1] != (int)(Off1 + i / 2))
14466         return false;
14467     }
14468 
14469     return true;
14470   };
14471 
14472   if (auto *Shuffle = dyn_cast<ShuffleVectorSDNode>(Trunc->getOperand(0)))
14473     if (isVMOVNOriginalMask(Shuffle->getMask(), false) ||
14474         isVMOVNOriginalMask(Shuffle->getMask(), true))
14475       return SDValue();
14476 
14477   LLVMContext &C = *DAG.getContext();
14478   SDLoc DL(St);
14479   // Details about the old store
14480   SDValue Ch = St->getChain();
14481   SDValue BasePtr = St->getBasePtr();
14482   Align Alignment = St->getOriginalAlign();
14483   MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
14484   AAMDNodes AAInfo = St->getAAInfo();
14485 
14486   // We split the store into slices of NumElements. fp16 trunc stores are vcvt
14487   // and then stored as truncating integer stores.
14488   EVT NewFromVT = EVT::getVectorVT(C, FromEltVT, NumElements);
14489   EVT NewToVT = EVT::getVectorVT(
14490       C, EVT::getIntegerVT(C, ToEltVT.getSizeInBits()), NumElements);
14491 
14492   SmallVector<SDValue, 4> Stores;
14493   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
14494     unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
14495     SDValue NewPtr =
14496         DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
14497 
14498     SDValue Extract =
14499         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
14500                     DAG.getConstant(i * NumElements, DL, MVT::i32));
14501 
14502     if (ToEltVT == MVT::f16) {
14503       SDValue FPTrunc =
14504           DAG.getNode(ARMISD::VCVTN, DL, MVT::v8f16, DAG.getUNDEF(MVT::v8f16),
14505                       Extract, DAG.getConstant(0, DL, MVT::i32));
14506       Extract = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v4i32, FPTrunc);
14507     }
14508 
14509     SDValue Store = DAG.getTruncStore(
14510         Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
14511         NewToVT, Alignment.value(), MMOFlags, AAInfo);
14512     Stores.push_back(Store);
14513   }
14514   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
14515 }
14516 
14517 /// PerformSTORECombine - Target-specific dag combine xforms for
14518 /// ISD::STORE.
14519 static SDValue PerformSTORECombine(SDNode *N,
14520                                    TargetLowering::DAGCombinerInfo &DCI,
14521                                    const ARMSubtarget *Subtarget) {
14522   StoreSDNode *St = cast<StoreSDNode>(N);
14523   if (St->isVolatile())
14524     return SDValue();
14525   SDValue StVal = St->getValue();
14526   EVT VT = StVal.getValueType();
14527 
14528   if (Subtarget->hasNEON())
14529     if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
14530       return Store;
14531 
14532   if (Subtarget->hasMVEIntegerOps())
14533     if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
14534       return NewToken;
14535 
14536   if (!ISD::isNormalStore(St))
14537     return SDValue();
14538 
14539   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
14540   // ARM stores of arguments in the same cache line.
14541   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
14542       StVal.getNode()->hasOneUse()) {
14543     SelectionDAG  &DAG = DCI.DAG;
14544     bool isBigEndian = DAG.getDataLayout().isBigEndian();
14545     SDLoc DL(St);
14546     SDValue BasePtr = St->getBasePtr();
14547     SDValue NewST1 = DAG.getStore(
14548         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
14549         BasePtr, St->getPointerInfo(), St->getAlignment(),
14550         St->getMemOperand()->getFlags());
14551 
14552     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
14553                                     DAG.getConstant(4, DL, MVT::i32));
14554     return DAG.getStore(NewST1.getValue(0), DL,
14555                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
14556                         OffsetPtr, St->getPointerInfo(),
14557                         std::min(4U, St->getAlignment() / 2),
14558                         St->getMemOperand()->getFlags());
14559   }
14560 
14561   if (StVal.getValueType() == MVT::i64 &&
14562       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14563 
14564     // Bitcast an i64 store extracted from a vector to f64.
14565     // Otherwise, the i64 value will be legalized to a pair of i32 values.
14566     SelectionDAG &DAG = DCI.DAG;
14567     SDLoc dl(StVal);
14568     SDValue IntVec = StVal.getOperand(0);
14569     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
14570                                    IntVec.getValueType().getVectorNumElements());
14571     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
14572     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
14573                                  Vec, StVal.getOperand(1));
14574     dl = SDLoc(N);
14575     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
14576     // Make the DAGCombiner fold the bitcasts.
14577     DCI.AddToWorklist(Vec.getNode());
14578     DCI.AddToWorklist(ExtElt.getNode());
14579     DCI.AddToWorklist(V.getNode());
14580     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
14581                         St->getPointerInfo(), St->getAlignment(),
14582                         St->getMemOperand()->getFlags(), St->getAAInfo());
14583   }
14584 
14585   // If this is a legal vector store, try to combine it into a VST1_UPD.
14586   if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
14587       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
14588     return CombineBaseUpdate(N, DCI);
14589 
14590   return SDValue();
14591 }
14592 
14593 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
14594 /// can replace combinations of VMUL and VCVT (floating-point to integer)
14595 /// when the VMUL has a constant operand that is a power of 2.
14596 ///
14597 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14598 ///  vmul.f32        d16, d17, d16
14599 ///  vcvt.s32.f32    d16, d16
14600 /// becomes:
14601 ///  vcvt.s32.f32    d16, d16, #3
14602 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
14603                                   const ARMSubtarget *Subtarget) {
14604   if (!Subtarget->hasNEON())
14605     return SDValue();
14606 
14607   SDValue Op = N->getOperand(0);
14608   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
14609       Op.getOpcode() != ISD::FMUL)
14610     return SDValue();
14611 
14612   SDValue ConstVec = Op->getOperand(1);
14613   if (!isa<BuildVectorSDNode>(ConstVec))
14614     return SDValue();
14615 
14616   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
14617   uint32_t FloatBits = FloatTy.getSizeInBits();
14618   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
14619   uint32_t IntBits = IntTy.getSizeInBits();
14620   unsigned NumLanes = Op.getValueType().getVectorNumElements();
14621   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14622     // These instructions only exist converting from f32 to i32. We can handle
14623     // smaller integers by generating an extra truncate, but larger ones would
14624     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14625     // these intructions only support v2i32/v4i32 types.
14626     return SDValue();
14627   }
14628 
14629   BitVector UndefElements;
14630   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14631   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14632   if (C == -1 || C == 0 || C > 32)
14633     return SDValue();
14634 
14635   SDLoc dl(N);
14636   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
14637   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
14638     Intrinsic::arm_neon_vcvtfp2fxu;
14639   SDValue FixConv = DAG.getNode(
14640       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14641       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
14642       DAG.getConstant(C, dl, MVT::i32));
14643 
14644   if (IntBits < FloatBits)
14645     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
14646 
14647   return FixConv;
14648 }
14649 
14650 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
14651 /// can replace combinations of VCVT (integer to floating-point) and VDIV
14652 /// when the VDIV has a constant operand that is a power of 2.
14653 ///
14654 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
14655 ///  vcvt.f32.s32    d16, d16
14656 ///  vdiv.f32        d16, d17, d16
14657 /// becomes:
14658 ///  vcvt.f32.s32    d16, d16, #3
14659 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
14660                                   const ARMSubtarget *Subtarget) {
14661   if (!Subtarget->hasNEON())
14662     return SDValue();
14663 
14664   SDValue Op = N->getOperand(0);
14665   unsigned OpOpcode = Op.getNode()->getOpcode();
14666   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
14667       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
14668     return SDValue();
14669 
14670   SDValue ConstVec = N->getOperand(1);
14671   if (!isa<BuildVectorSDNode>(ConstVec))
14672     return SDValue();
14673 
14674   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
14675   uint32_t FloatBits = FloatTy.getSizeInBits();
14676   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
14677   uint32_t IntBits = IntTy.getSizeInBits();
14678   unsigned NumLanes = Op.getValueType().getVectorNumElements();
14679   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
14680     // These instructions only exist converting from i32 to f32. We can handle
14681     // smaller integers by generating an extra extend, but larger ones would
14682     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
14683     // these intructions only support v2i32/v4i32 types.
14684     return SDValue();
14685   }
14686 
14687   BitVector UndefElements;
14688   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
14689   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
14690   if (C == -1 || C == 0 || C > 32)
14691     return SDValue();
14692 
14693   SDLoc dl(N);
14694   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
14695   SDValue ConvInput = Op.getOperand(0);
14696   if (IntBits < FloatBits)
14697     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
14698                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
14699                             ConvInput);
14700 
14701   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
14702     Intrinsic::arm_neon_vcvtfxu2fp;
14703   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
14704                      Op.getValueType(),
14705                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
14706                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
14707 }
14708 
14709 static SDValue PerformVECREDUCE_ADDCombine(SDNode *N, SelectionDAG &DAG,
14710                                            const ARMSubtarget *ST) {
14711   if (!ST->hasMVEIntegerOps())
14712     return SDValue();
14713 
14714   assert(N->getOpcode() == ISD::VECREDUCE_ADD);
14715   EVT ResVT = N->getValueType(0);
14716   SDValue N0 = N->getOperand(0);
14717   SDLoc dl(N);
14718 
14719   // We are looking for something that will have illegal types if left alone,
14720   // but that we can convert to a single instruction undef MVE. For example
14721   // vecreduce_add(sext(A, v8i32)) => VADDV.s16 A
14722   // or
14723   // vecreduce_add(mul(zext(A, v16i32), zext(B, v16i32))) => VMLADAV.u8 A, B
14724 
14725   // Cases:
14726   //   VADDV u/s 8/16/32
14727   //   VMLAV u/s 8/16/32
14728   //   VADDLV u/s 32
14729   //   VMLALV u/s 16/32
14730 
14731   auto IsVADDV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes) {
14732     if (ResVT != RetTy || N0->getOpcode() != ExtendCode)
14733       return SDValue();
14734     SDValue A = N0->getOperand(0);
14735     if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14736       return A;
14737     return SDValue();
14738   };
14739   auto IsPredVADDV = [&](MVT RetTy, unsigned ExtendCode,
14740                          ArrayRef<MVT> ExtTypes, SDValue &Mask) {
14741     if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
14742         !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
14743       return SDValue();
14744     Mask = N0->getOperand(0);
14745     SDValue Ext = N0->getOperand(1);
14746     if (Ext->getOpcode() != ExtendCode)
14747       return SDValue();
14748     SDValue A = Ext->getOperand(0);
14749     if (llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14750       return A;
14751     return SDValue();
14752   };
14753   auto IsVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
14754                      SDValue &A, SDValue &B) {
14755     // For a vmla we are trying to match a larger pattern:
14756     // ExtA = sext/zext A
14757     // ExtB = sext/zext B
14758     // Mul = mul ExtA, ExtB
14759     // vecreduce.add Mul
14760     // There might also be en extra extend between the mul and the addreduce, so
14761     // long as the bitwidth is high enough to make them equivalent (for example
14762     // original v8i16 might be mul at v8i32 and the reduce happens at v8i64).
14763     if (ResVT != RetTy)
14764       return false;
14765     SDValue Mul = N0;
14766     if (Mul->getOpcode() == ExtendCode &&
14767         Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
14768             ResVT.getScalarSizeInBits())
14769       Mul = Mul->getOperand(0);
14770     if (Mul->getOpcode() != ISD::MUL)
14771       return false;
14772     SDValue ExtA = Mul->getOperand(0);
14773     SDValue ExtB = Mul->getOperand(1);
14774     if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode)
14775       return false;
14776     A = ExtA->getOperand(0);
14777     B = ExtB->getOperand(0);
14778     if (A.getValueType() == B.getValueType() &&
14779         llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14780       return true;
14781     return false;
14782   };
14783   auto IsPredVMLAV = [&](MVT RetTy, unsigned ExtendCode, ArrayRef<MVT> ExtTypes,
14784                      SDValue &A, SDValue &B, SDValue &Mask) {
14785     // Same as the pattern above with a select for the zero predicated lanes
14786     // ExtA = sext/zext A
14787     // ExtB = sext/zext B
14788     // Mul = mul ExtA, ExtB
14789     // N0 = select Mask, Mul, 0
14790     // vecreduce.add N0
14791     if (ResVT != RetTy || N0->getOpcode() != ISD::VSELECT ||
14792         !ISD::isBuildVectorAllZeros(N0->getOperand(2).getNode()))
14793       return false;
14794     Mask = N0->getOperand(0);
14795     SDValue Mul = N0->getOperand(1);
14796     if (Mul->getOpcode() == ExtendCode &&
14797         Mul->getOperand(0).getScalarValueSizeInBits() * 2 >=
14798             ResVT.getScalarSizeInBits())
14799       Mul = Mul->getOperand(0);
14800     if (Mul->getOpcode() != ISD::MUL)
14801       return false;
14802     SDValue ExtA = Mul->getOperand(0);
14803     SDValue ExtB = Mul->getOperand(1);
14804     if (ExtA->getOpcode() != ExtendCode && ExtB->getOpcode() != ExtendCode)
14805       return false;
14806     A = ExtA->getOperand(0);
14807     B = ExtB->getOperand(0);
14808     if (A.getValueType() == B.getValueType() &&
14809         llvm::any_of(ExtTypes, [&A](MVT Ty) { return A.getValueType() == Ty; }))
14810       return true;
14811     return false;
14812   };
14813   auto Create64bitNode = [&](unsigned Opcode, ArrayRef<SDValue> Ops) {
14814     SDValue Node = DAG.getNode(Opcode, dl, {MVT::i32, MVT::i32}, Ops);
14815     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Node,
14816                        SDValue(Node.getNode(), 1));
14817   };
14818 
14819   if (SDValue A = IsVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}))
14820     return DAG.getNode(ARMISD::VADDVs, dl, ResVT, A);
14821   if (SDValue A = IsVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}))
14822     return DAG.getNode(ARMISD::VADDVu, dl, ResVT, A);
14823   if (SDValue A = IsVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}))
14824     return Create64bitNode(ARMISD::VADDLVs, {A});
14825   if (SDValue A = IsVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}))
14826     return Create64bitNode(ARMISD::VADDLVu, {A});
14827   if (SDValue A = IsVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}))
14828     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
14829                        DAG.getNode(ARMISD::VADDVs, dl, MVT::i32, A));
14830   if (SDValue A = IsVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}))
14831     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
14832                        DAG.getNode(ARMISD::VADDVu, dl, MVT::i32, A));
14833 
14834   SDValue Mask;
14835   if (SDValue A = IsPredVADDV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
14836     return DAG.getNode(ARMISD::VADDVps, dl, ResVT, A, Mask);
14837   if (SDValue A = IsPredVADDV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, Mask))
14838     return DAG.getNode(ARMISD::VADDVpu, dl, ResVT, A, Mask);
14839   if (SDValue A = IsPredVADDV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v4i32}, Mask))
14840     return Create64bitNode(ARMISD::VADDLVps, {A, Mask});
14841   if (SDValue A = IsPredVADDV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v4i32}, Mask))
14842     return Create64bitNode(ARMISD::VADDLVpu, {A, Mask});
14843   if (SDValue A = IsPredVADDV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, Mask))
14844     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
14845                        DAG.getNode(ARMISD::VADDVps, dl, MVT::i32, A, Mask));
14846   if (SDValue A = IsPredVADDV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, Mask))
14847     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
14848                        DAG.getNode(ARMISD::VADDVpu, dl, MVT::i32, A, Mask));
14849 
14850   SDValue A, B;
14851   if (IsVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
14852     return DAG.getNode(ARMISD::VMLAVs, dl, ResVT, A, B);
14853   if (IsVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B))
14854     return DAG.getNode(ARMISD::VMLAVu, dl, ResVT, A, B);
14855   if (IsVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B))
14856     return Create64bitNode(ARMISD::VMLALVs, {A, B});
14857   if (IsVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B))
14858     return Create64bitNode(ARMISD::VMLALVu, {A, B});
14859   if (IsVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B))
14860     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
14861                        DAG.getNode(ARMISD::VMLAVs, dl, MVT::i32, A, B));
14862   if (IsVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B))
14863     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
14864                        DAG.getNode(ARMISD::VMLAVu, dl, MVT::i32, A, B));
14865 
14866   if (IsPredVMLAV(MVT::i32, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask))
14867     return DAG.getNode(ARMISD::VMLAVps, dl, ResVT, A, B, Mask);
14868   if (IsPredVMLAV(MVT::i32, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v16i8}, A, B, Mask))
14869     return DAG.getNode(ARMISD::VMLAVpu, dl, ResVT, A, B, Mask);
14870   if (IsPredVMLAV(MVT::i64, ISD::SIGN_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask))
14871     return Create64bitNode(ARMISD::VMLALVps, {A, B, Mask});
14872   if (IsPredVMLAV(MVT::i64, ISD::ZERO_EXTEND, {MVT::v8i16, MVT::v4i32}, A, B, Mask))
14873     return Create64bitNode(ARMISD::VMLALVpu, {A, B, Mask});
14874   if (IsPredVMLAV(MVT::i16, ISD::SIGN_EXTEND, {MVT::v16i8}, A, B, Mask))
14875     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
14876                        DAG.getNode(ARMISD::VMLAVps, dl, MVT::i32, A, B, Mask));
14877   if (IsPredVMLAV(MVT::i16, ISD::ZERO_EXTEND, {MVT::v16i8}, A, B, Mask))
14878     return DAG.getNode(ISD::TRUNCATE, dl, ResVT,
14879                        DAG.getNode(ARMISD::VMLAVpu, dl, MVT::i32, A, B, Mask));
14880 
14881   // Some complications. We can get a case where the two inputs of the mul are
14882   // the same, then the output sext will have been helpfully converted to a
14883   // zext. Turn it back.
14884   SDValue Op = N0;
14885   if (Op->getOpcode() == ISD::VSELECT)
14886     Op = Op->getOperand(1);
14887   if (Op->getOpcode() == ISD::ZERO_EXTEND &&
14888       Op->getOperand(0)->getOpcode() == ISD::MUL) {
14889     SDValue Mul = Op->getOperand(0);
14890     if (Mul->getOperand(0) == Mul->getOperand(1) &&
14891         Mul->getOperand(0)->getOpcode() == ISD::SIGN_EXTEND) {
14892       SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, dl, N0->getValueType(0), Mul);
14893       if (Op != N0)
14894         Ext = DAG.getNode(ISD::VSELECT, dl, N0->getValueType(0),
14895                           N0->getOperand(0), Ext, N0->getOperand(2));
14896       return DAG.getNode(ISD::VECREDUCE_ADD, dl, ResVT, Ext);
14897     }
14898   }
14899 
14900   return SDValue();
14901 }
14902 
14903 static SDValue PerformVMOVNCombine(SDNode *N,
14904                                    TargetLowering::DAGCombinerInfo &DCI) {
14905   SDValue Op0 = N->getOperand(0);
14906   SDValue Op1 = N->getOperand(1);
14907   unsigned IsTop = N->getConstantOperandVal(2);
14908 
14909   // VMOVNt(c, VQMOVNb(a, b)) => VQMOVNt(c, b)
14910   // VMOVNb(c, VQMOVNb(a, b)) => VQMOVNb(c, b)
14911   if ((Op1->getOpcode() == ARMISD::VQMOVNs ||
14912        Op1->getOpcode() == ARMISD::VQMOVNu) &&
14913       Op1->getConstantOperandVal(2) == 0)
14914     return DCI.DAG.getNode(Op1->getOpcode(), SDLoc(Op1), N->getValueType(0),
14915                            Op0, Op1->getOperand(1), N->getOperand(2));
14916 
14917   // Only the bottom lanes from Qm (Op1) and either the top or bottom lanes from
14918   // Qd (Op0) are demanded from a VMOVN, depending on whether we are inserting
14919   // into the top or bottom lanes.
14920   unsigned NumElts = N->getValueType(0).getVectorNumElements();
14921   APInt Op1DemandedElts = APInt::getSplat(NumElts, APInt::getLowBitsSet(2, 1));
14922   APInt Op0DemandedElts =
14923       IsTop ? Op1DemandedElts
14924             : APInt::getSplat(NumElts, APInt::getHighBitsSet(2, 1));
14925 
14926   APInt KnownUndef, KnownZero;
14927   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
14928   if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
14929                                      KnownZero, DCI))
14930     return SDValue(N, 0);
14931   if (TLI.SimplifyDemandedVectorElts(Op1, Op1DemandedElts, KnownUndef,
14932                                      KnownZero, DCI))
14933     return SDValue(N, 0);
14934 
14935   return SDValue();
14936 }
14937 
14938 static SDValue PerformVQMOVNCombine(SDNode *N,
14939                                     TargetLowering::DAGCombinerInfo &DCI) {
14940   SDValue Op0 = N->getOperand(0);
14941   unsigned IsTop = N->getConstantOperandVal(2);
14942 
14943   unsigned NumElts = N->getValueType(0).getVectorNumElements();
14944   APInt Op0DemandedElts =
14945       APInt::getSplat(NumElts, IsTop ? APInt::getLowBitsSet(2, 1)
14946                                      : APInt::getHighBitsSet(2, 1));
14947 
14948   APInt KnownUndef, KnownZero;
14949   const TargetLowering &TLI = DCI.DAG.getTargetLoweringInfo();
14950   if (TLI.SimplifyDemandedVectorElts(Op0, Op0DemandedElts, KnownUndef,
14951                                      KnownZero, DCI))
14952     return SDValue(N, 0);
14953   return SDValue();
14954 }
14955 
14956 static SDValue PerformLongShiftCombine(SDNode *N, SelectionDAG &DAG) {
14957   SDLoc DL(N);
14958   SDValue Op0 = N->getOperand(0);
14959   SDValue Op1 = N->getOperand(1);
14960 
14961   // Turn X << -C -> X >> C and viceversa. The negative shifts can come up from
14962   // uses of the intrinsics.
14963   if (auto C = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
14964     int ShiftAmt = C->getSExtValue();
14965     if (ShiftAmt == 0) {
14966       SDValue Merge = DAG.getMergeValues({Op0, Op1}, DL);
14967       DAG.ReplaceAllUsesWith(N, Merge.getNode());
14968       return SDValue();
14969     }
14970 
14971     if (ShiftAmt >= -32 && ShiftAmt < 0) {
14972       unsigned NewOpcode =
14973           N->getOpcode() == ARMISD::LSLL ? ARMISD::LSRL : ARMISD::LSLL;
14974       SDValue NewShift = DAG.getNode(NewOpcode, DL, N->getVTList(), Op0, Op1,
14975                                      DAG.getConstant(-ShiftAmt, DL, MVT::i32));
14976       DAG.ReplaceAllUsesWith(N, NewShift.getNode());
14977       return NewShift;
14978     }
14979   }
14980 
14981   return SDValue();
14982 }
14983 
14984 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
14985 SDValue ARMTargetLowering::PerformIntrinsicCombine(SDNode *N,
14986                                                    DAGCombinerInfo &DCI) const {
14987   SelectionDAG &DAG = DCI.DAG;
14988   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14989   switch (IntNo) {
14990   default:
14991     // Don't do anything for most intrinsics.
14992     break;
14993 
14994   // Vector shifts: check for immediate versions and lower them.
14995   // Note: This is done during DAG combining instead of DAG legalizing because
14996   // the build_vectors for 64-bit vector element shift counts are generally
14997   // not legal, and it is hard to see their values after they get legalized to
14998   // loads from a constant pool.
14999   case Intrinsic::arm_neon_vshifts:
15000   case Intrinsic::arm_neon_vshiftu:
15001   case Intrinsic::arm_neon_vrshifts:
15002   case Intrinsic::arm_neon_vrshiftu:
15003   case Intrinsic::arm_neon_vrshiftn:
15004   case Intrinsic::arm_neon_vqshifts:
15005   case Intrinsic::arm_neon_vqshiftu:
15006   case Intrinsic::arm_neon_vqshiftsu:
15007   case Intrinsic::arm_neon_vqshiftns:
15008   case Intrinsic::arm_neon_vqshiftnu:
15009   case Intrinsic::arm_neon_vqshiftnsu:
15010   case Intrinsic::arm_neon_vqrshiftns:
15011   case Intrinsic::arm_neon_vqrshiftnu:
15012   case Intrinsic::arm_neon_vqrshiftnsu: {
15013     EVT VT = N->getOperand(1).getValueType();
15014     int64_t Cnt;
15015     unsigned VShiftOpc = 0;
15016 
15017     switch (IntNo) {
15018     case Intrinsic::arm_neon_vshifts:
15019     case Intrinsic::arm_neon_vshiftu:
15020       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
15021         VShiftOpc = ARMISD::VSHLIMM;
15022         break;
15023       }
15024       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
15025         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
15026                                                           : ARMISD::VSHRuIMM);
15027         break;
15028       }
15029       return SDValue();
15030 
15031     case Intrinsic::arm_neon_vrshifts:
15032     case Intrinsic::arm_neon_vrshiftu:
15033       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
15034         break;
15035       return SDValue();
15036 
15037     case Intrinsic::arm_neon_vqshifts:
15038     case Intrinsic::arm_neon_vqshiftu:
15039       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
15040         break;
15041       return SDValue();
15042 
15043     case Intrinsic::arm_neon_vqshiftsu:
15044       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
15045         break;
15046       llvm_unreachable("invalid shift count for vqshlu intrinsic");
15047 
15048     case Intrinsic::arm_neon_vrshiftn:
15049     case Intrinsic::arm_neon_vqshiftns:
15050     case Intrinsic::arm_neon_vqshiftnu:
15051     case Intrinsic::arm_neon_vqshiftnsu:
15052     case Intrinsic::arm_neon_vqrshiftns:
15053     case Intrinsic::arm_neon_vqrshiftnu:
15054     case Intrinsic::arm_neon_vqrshiftnsu:
15055       // Narrowing shifts require an immediate right shift.
15056       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
15057         break;
15058       llvm_unreachable("invalid shift count for narrowing vector shift "
15059                        "intrinsic");
15060 
15061     default:
15062       llvm_unreachable("unhandled vector shift");
15063     }
15064 
15065     switch (IntNo) {
15066     case Intrinsic::arm_neon_vshifts:
15067     case Intrinsic::arm_neon_vshiftu:
15068       // Opcode already set above.
15069       break;
15070     case Intrinsic::arm_neon_vrshifts:
15071       VShiftOpc = ARMISD::VRSHRsIMM;
15072       break;
15073     case Intrinsic::arm_neon_vrshiftu:
15074       VShiftOpc = ARMISD::VRSHRuIMM;
15075       break;
15076     case Intrinsic::arm_neon_vrshiftn:
15077       VShiftOpc = ARMISD::VRSHRNIMM;
15078       break;
15079     case Intrinsic::arm_neon_vqshifts:
15080       VShiftOpc = ARMISD::VQSHLsIMM;
15081       break;
15082     case Intrinsic::arm_neon_vqshiftu:
15083       VShiftOpc = ARMISD::VQSHLuIMM;
15084       break;
15085     case Intrinsic::arm_neon_vqshiftsu:
15086       VShiftOpc = ARMISD::VQSHLsuIMM;
15087       break;
15088     case Intrinsic::arm_neon_vqshiftns:
15089       VShiftOpc = ARMISD::VQSHRNsIMM;
15090       break;
15091     case Intrinsic::arm_neon_vqshiftnu:
15092       VShiftOpc = ARMISD::VQSHRNuIMM;
15093       break;
15094     case Intrinsic::arm_neon_vqshiftnsu:
15095       VShiftOpc = ARMISD::VQSHRNsuIMM;
15096       break;
15097     case Intrinsic::arm_neon_vqrshiftns:
15098       VShiftOpc = ARMISD::VQRSHRNsIMM;
15099       break;
15100     case Intrinsic::arm_neon_vqrshiftnu:
15101       VShiftOpc = ARMISD::VQRSHRNuIMM;
15102       break;
15103     case Intrinsic::arm_neon_vqrshiftnsu:
15104       VShiftOpc = ARMISD::VQRSHRNsuIMM;
15105       break;
15106     }
15107 
15108     SDLoc dl(N);
15109     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
15110                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
15111   }
15112 
15113   case Intrinsic::arm_neon_vshiftins: {
15114     EVT VT = N->getOperand(1).getValueType();
15115     int64_t Cnt;
15116     unsigned VShiftOpc = 0;
15117 
15118     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
15119       VShiftOpc = ARMISD::VSLIIMM;
15120     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
15121       VShiftOpc = ARMISD::VSRIIMM;
15122     else {
15123       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
15124     }
15125 
15126     SDLoc dl(N);
15127     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
15128                        N->getOperand(1), N->getOperand(2),
15129                        DAG.getConstant(Cnt, dl, MVT::i32));
15130   }
15131 
15132   case Intrinsic::arm_neon_vqrshifts:
15133   case Intrinsic::arm_neon_vqrshiftu:
15134     // No immediate versions of these to check for.
15135     break;
15136 
15137   case Intrinsic::arm_mve_vqdmlah:
15138   case Intrinsic::arm_mve_vqdmlash:
15139   case Intrinsic::arm_mve_vqrdmlah:
15140   case Intrinsic::arm_mve_vqrdmlash:
15141   case Intrinsic::arm_mve_vmla_n_predicated:
15142   case Intrinsic::arm_mve_vmlas_n_predicated:
15143   case Intrinsic::arm_mve_vqdmlah_predicated:
15144   case Intrinsic::arm_mve_vqdmlash_predicated:
15145   case Intrinsic::arm_mve_vqrdmlah_predicated:
15146   case Intrinsic::arm_mve_vqrdmlash_predicated: {
15147     // These intrinsics all take an i32 scalar operand which is narrowed to the
15148     // size of a single lane of the vector type they return. So we don't need
15149     // any bits of that operand above that point, which allows us to eliminate
15150     // uxth/sxth.
15151     unsigned BitWidth = N->getValueType(0).getScalarSizeInBits();
15152     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
15153     if (SimplifyDemandedBits(N->getOperand(3), DemandedMask, DCI))
15154       return SDValue();
15155     break;
15156   }
15157 
15158   case Intrinsic::arm_mve_minv:
15159   case Intrinsic::arm_mve_maxv:
15160   case Intrinsic::arm_mve_minav:
15161   case Intrinsic::arm_mve_maxav:
15162   case Intrinsic::arm_mve_minv_predicated:
15163   case Intrinsic::arm_mve_maxv_predicated:
15164   case Intrinsic::arm_mve_minav_predicated:
15165   case Intrinsic::arm_mve_maxav_predicated: {
15166     // These intrinsics all take an i32 scalar operand which is narrowed to the
15167     // size of a single lane of the vector type they take as the other input.
15168     unsigned BitWidth = N->getOperand(2)->getValueType(0).getScalarSizeInBits();
15169     APInt DemandedMask = APInt::getLowBitsSet(32, BitWidth);
15170     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
15171       return SDValue();
15172     break;
15173   }
15174 
15175   case Intrinsic::arm_mve_addv: {
15176     // Turn this intrinsic straight into the appropriate ARMISD::VADDV node,
15177     // which allow PerformADDVecReduce to turn it into VADDLV when possible.
15178     bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
15179     unsigned Opc = Unsigned ? ARMISD::VADDVu : ARMISD::VADDVs;
15180     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), N->getOperand(1));
15181   }
15182 
15183   case Intrinsic::arm_mve_addlv:
15184   case Intrinsic::arm_mve_addlv_predicated: {
15185     // Same for these, but ARMISD::VADDLV has to be followed by a BUILD_PAIR
15186     // which recombines the two outputs into an i64
15187     bool Unsigned = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
15188     unsigned Opc = IntNo == Intrinsic::arm_mve_addlv ?
15189                     (Unsigned ? ARMISD::VADDLVu : ARMISD::VADDLVs) :
15190                     (Unsigned ? ARMISD::VADDLVpu : ARMISD::VADDLVps);
15191 
15192     SmallVector<SDValue, 4> Ops;
15193     for (unsigned i = 1, e = N->getNumOperands(); i < e; i++)
15194       if (i != 2)                      // skip the unsigned flag
15195         Ops.push_back(N->getOperand(i));
15196 
15197     SDLoc dl(N);
15198     SDValue val = DAG.getNode(Opc, dl, {MVT::i32, MVT::i32}, Ops);
15199     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, val.getValue(0),
15200                        val.getValue(1));
15201   }
15202   }
15203 
15204   return SDValue();
15205 }
15206 
15207 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
15208 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
15209 /// combining instead of DAG legalizing because the build_vectors for 64-bit
15210 /// vector element shift counts are generally not legal, and it is hard to see
15211 /// their values after they get legalized to loads from a constant pool.
15212 static SDValue PerformShiftCombine(SDNode *N,
15213                                    TargetLowering::DAGCombinerInfo &DCI,
15214                                    const ARMSubtarget *ST) {
15215   SelectionDAG &DAG = DCI.DAG;
15216   EVT VT = N->getValueType(0);
15217   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
15218     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
15219     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
15220     SDValue N1 = N->getOperand(1);
15221     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
15222       SDValue N0 = N->getOperand(0);
15223       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
15224           DAG.MaskedValueIsZero(N0.getOperand(0),
15225                                 APInt::getHighBitsSet(32, 16)))
15226         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
15227     }
15228   }
15229 
15230   if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
15231       N->getOperand(0)->getOpcode() == ISD::AND &&
15232       N->getOperand(0)->hasOneUse()) {
15233     if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
15234       return SDValue();
15235     // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
15236     // usually show up because instcombine prefers to canonicalize it to
15237     // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
15238     // out of GEP lowering in some cases.
15239     SDValue N0 = N->getOperand(0);
15240     ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
15241     if (!ShiftAmtNode)
15242       return SDValue();
15243     uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
15244     ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
15245     if (!AndMaskNode)
15246       return SDValue();
15247     uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
15248     // Don't transform uxtb/uxth.
15249     if (AndMask == 255 || AndMask == 65535)
15250       return SDValue();
15251     if (isMask_32(AndMask)) {
15252       uint32_t MaskedBits = countLeadingZeros(AndMask);
15253       if (MaskedBits > ShiftAmt) {
15254         SDLoc DL(N);
15255         SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
15256                                   DAG.getConstant(MaskedBits, DL, MVT::i32));
15257         return DAG.getNode(
15258             ISD::SRL, DL, MVT::i32, SHL,
15259             DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
15260       }
15261     }
15262   }
15263 
15264   // Nothing to be done for scalar shifts.
15265   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15266   if (!VT.isVector() || !TLI.isTypeLegal(VT))
15267     return SDValue();
15268   if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
15269     return SDValue();
15270 
15271   int64_t Cnt;
15272 
15273   switch (N->getOpcode()) {
15274   default: llvm_unreachable("unexpected shift opcode");
15275 
15276   case ISD::SHL:
15277     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
15278       SDLoc dl(N);
15279       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
15280                          DAG.getConstant(Cnt, dl, MVT::i32));
15281     }
15282     break;
15283 
15284   case ISD::SRA:
15285   case ISD::SRL:
15286     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
15287       unsigned VShiftOpc =
15288           (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
15289       SDLoc dl(N);
15290       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
15291                          DAG.getConstant(Cnt, dl, MVT::i32));
15292     }
15293   }
15294   return SDValue();
15295 }
15296 
15297 // Look for a sign/zero/fpextend extend of a larger than legal load. This can be
15298 // split into multiple extending loads, which are simpler to deal with than an
15299 // arbitrary extend. For fp extends we use an integer extending load and a VCVTL
15300 // to convert the type to an f32.
15301 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
15302   SDValue N0 = N->getOperand(0);
15303   if (N0.getOpcode() != ISD::LOAD)
15304     return SDValue();
15305   LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
15306   if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
15307       LD->getExtensionType() != ISD::NON_EXTLOAD)
15308     return SDValue();
15309   EVT FromVT = LD->getValueType(0);
15310   EVT ToVT = N->getValueType(0);
15311   if (!ToVT.isVector())
15312     return SDValue();
15313   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
15314   EVT ToEltVT = ToVT.getVectorElementType();
15315   EVT FromEltVT = FromVT.getVectorElementType();
15316 
15317   unsigned NumElements = 0;
15318   if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
15319     NumElements = 4;
15320   if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
15321     NumElements = 8;
15322   if (ToEltVT == MVT::f32 && FromEltVT == MVT::f16)
15323     NumElements = 4;
15324   if (NumElements == 0 ||
15325       (FromEltVT != MVT::f16 && FromVT.getVectorNumElements() == NumElements) ||
15326       FromVT.getVectorNumElements() % NumElements != 0 ||
15327       !isPowerOf2_32(NumElements))
15328     return SDValue();
15329 
15330   LLVMContext &C = *DAG.getContext();
15331   SDLoc DL(LD);
15332   // Details about the old load
15333   SDValue Ch = LD->getChain();
15334   SDValue BasePtr = LD->getBasePtr();
15335   Align Alignment = LD->getOriginalAlign();
15336   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
15337   AAMDNodes AAInfo = LD->getAAInfo();
15338 
15339   ISD::LoadExtType NewExtType =
15340       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
15341   SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
15342   EVT NewFromVT = EVT::getVectorVT(
15343       C, EVT::getIntegerVT(C, FromEltVT.getScalarSizeInBits()), NumElements);
15344   EVT NewToVT = EVT::getVectorVT(
15345       C, EVT::getIntegerVT(C, ToEltVT.getScalarSizeInBits()), NumElements);
15346 
15347   SmallVector<SDValue, 4> Loads;
15348   SmallVector<SDValue, 4> Chains;
15349   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
15350     unsigned NewOffset = (i * NewFromVT.getSizeInBits()) / 8;
15351     SDValue NewPtr =
15352         DAG.getObjectPtrOffset(DL, BasePtr, TypeSize::Fixed(NewOffset));
15353 
15354     SDValue NewLoad =
15355         DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
15356                     LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
15357                     Alignment, MMOFlags, AAInfo);
15358     Loads.push_back(NewLoad);
15359     Chains.push_back(SDValue(NewLoad.getNode(), 1));
15360   }
15361 
15362   // Float truncs need to extended with VCVTB's into their floating point types.
15363   if (FromEltVT == MVT::f16) {
15364     SmallVector<SDValue, 4> Extends;
15365 
15366     for (unsigned i = 0; i < Loads.size(); i++) {
15367       SDValue LoadBC =
15368           DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, MVT::v8f16, Loads[i]);
15369       SDValue FPExt = DAG.getNode(ARMISD::VCVTL, DL, MVT::v4f32, LoadBC,
15370                                   DAG.getConstant(0, DL, MVT::i32));
15371       Extends.push_back(FPExt);
15372     }
15373 
15374     Loads = Extends;
15375   }
15376 
15377   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
15378   DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
15379   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, Loads);
15380 }
15381 
15382 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
15383 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
15384 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
15385                                     const ARMSubtarget *ST) {
15386   SDValue N0 = N->getOperand(0);
15387 
15388   // Check for sign- and zero-extensions of vector extract operations of 8- and
15389   // 16-bit vector elements. NEON and MVE support these directly. They are
15390   // handled during DAG combining because type legalization will promote them
15391   // to 32-bit types and it is messy to recognize the operations after that.
15392   if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
15393       N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
15394     SDValue Vec = N0.getOperand(0);
15395     SDValue Lane = N0.getOperand(1);
15396     EVT VT = N->getValueType(0);
15397     EVT EltVT = N0.getValueType();
15398     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15399 
15400     if (VT == MVT::i32 &&
15401         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
15402         TLI.isTypeLegal(Vec.getValueType()) &&
15403         isa<ConstantSDNode>(Lane)) {
15404 
15405       unsigned Opc = 0;
15406       switch (N->getOpcode()) {
15407       default: llvm_unreachable("unexpected opcode");
15408       case ISD::SIGN_EXTEND:
15409         Opc = ARMISD::VGETLANEs;
15410         break;
15411       case ISD::ZERO_EXTEND:
15412       case ISD::ANY_EXTEND:
15413         Opc = ARMISD::VGETLANEu;
15414         break;
15415       }
15416       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
15417     }
15418   }
15419 
15420   if (ST->hasMVEIntegerOps())
15421     if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
15422       return NewLoad;
15423 
15424   return SDValue();
15425 }
15426 
15427 static SDValue PerformFPExtendCombine(SDNode *N, SelectionDAG &DAG,
15428                                       const ARMSubtarget *ST) {
15429   if (ST->hasMVEFloatOps())
15430     if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
15431       return NewLoad;
15432 
15433   return SDValue();
15434 }
15435 
15436 /// PerformMinMaxCombine - Target-specific DAG combining for creating truncating
15437 /// saturates.
15438 static SDValue PerformMinMaxCombine(SDNode *N, SelectionDAG &DAG,
15439                                     const ARMSubtarget *ST) {
15440   EVT VT = N->getValueType(0);
15441   SDValue N0 = N->getOperand(0);
15442   if (!ST->hasMVEIntegerOps())
15443     return SDValue();
15444 
15445   if (VT != MVT::v4i32 && VT != MVT::v8i16)
15446     return SDValue();
15447 
15448   auto IsSignedSaturate = [&](SDNode *Min, SDNode *Max) {
15449     // Check one is a smin and the other is a smax
15450     if (Min->getOpcode() != ISD::SMIN)
15451       std::swap(Min, Max);
15452     if (Min->getOpcode() != ISD::SMIN || Max->getOpcode() != ISD::SMAX)
15453       return false;
15454 
15455     APInt SaturateC;
15456     if (VT == MVT::v4i32)
15457       SaturateC = APInt(32, (1 << 15) - 1, true);
15458     else //if (VT == MVT::v8i16)
15459       SaturateC = APInt(16, (1 << 7) - 1, true);
15460 
15461     APInt MinC, MaxC;
15462     if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
15463         MinC != SaturateC)
15464       return false;
15465     if (!ISD::isConstantSplatVector(Max->getOperand(1).getNode(), MaxC) ||
15466         MaxC != ~SaturateC)
15467       return false;
15468     return true;
15469   };
15470 
15471   if (IsSignedSaturate(N, N0.getNode())) {
15472     SDLoc DL(N);
15473     MVT ExtVT, HalfVT;
15474     if (VT == MVT::v4i32) {
15475       HalfVT = MVT::v8i16;
15476       ExtVT = MVT::v4i16;
15477     } else { // if (VT == MVT::v8i16)
15478       HalfVT = MVT::v16i8;
15479       ExtVT = MVT::v8i8;
15480     }
15481 
15482     // Create a VQMOVNB with undef top lanes, then signed extended into the top
15483     // half. That extend will hopefully be removed if only the bottom bits are
15484     // demanded (though a truncating store, for example).
15485     SDValue VQMOVN =
15486         DAG.getNode(ARMISD::VQMOVNs, DL, HalfVT, DAG.getUNDEF(HalfVT),
15487                     N0->getOperand(0), DAG.getConstant(0, DL, MVT::i32));
15488     SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
15489     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Bitcast,
15490                        DAG.getValueType(ExtVT));
15491   }
15492 
15493   auto IsUnsignedSaturate = [&](SDNode *Min) {
15494     // For unsigned, we just need to check for <= 0xffff
15495     if (Min->getOpcode() != ISD::UMIN)
15496       return false;
15497 
15498     APInt SaturateC;
15499     if (VT == MVT::v4i32)
15500       SaturateC = APInt(32, (1 << 16) - 1, true);
15501     else //if (VT == MVT::v8i16)
15502       SaturateC = APInt(16, (1 << 8) - 1, true);
15503 
15504     APInt MinC;
15505     if (!ISD::isConstantSplatVector(Min->getOperand(1).getNode(), MinC) ||
15506         MinC != SaturateC)
15507       return false;
15508     return true;
15509   };
15510 
15511   if (IsUnsignedSaturate(N)) {
15512     SDLoc DL(N);
15513     MVT HalfVT;
15514     unsigned ExtConst;
15515     if (VT == MVT::v4i32) {
15516       HalfVT = MVT::v8i16;
15517       ExtConst = 0x0000FFFF;
15518     } else { //if (VT == MVT::v8i16)
15519       HalfVT = MVT::v16i8;
15520       ExtConst = 0x00FF;
15521     }
15522 
15523     // Create a VQMOVNB with undef top lanes, then ZExt into the top half with
15524     // an AND. That extend will hopefully be removed if only the bottom bits are
15525     // demanded (though a truncating store, for example).
15526     SDValue VQMOVN =
15527         DAG.getNode(ARMISD::VQMOVNu, DL, HalfVT, DAG.getUNDEF(HalfVT), N0,
15528                     DAG.getConstant(0, DL, MVT::i32));
15529     SDValue Bitcast = DAG.getNode(ARMISD::VECTOR_REG_CAST, DL, VT, VQMOVN);
15530     return DAG.getNode(ISD::AND, DL, VT, Bitcast,
15531                        DAG.getConstant(ExtConst, DL, VT));
15532   }
15533 
15534   return SDValue();
15535 }
15536 
15537 static const APInt *isPowerOf2Constant(SDValue V) {
15538   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
15539   if (!C)
15540     return nullptr;
15541   const APInt *CV = &C->getAPIntValue();
15542   return CV->isPowerOf2() ? CV : nullptr;
15543 }
15544 
15545 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
15546   // If we have a CMOV, OR and AND combination such as:
15547   //   if (x & CN)
15548   //     y |= CM;
15549   //
15550   // And:
15551   //   * CN is a single bit;
15552   //   * All bits covered by CM are known zero in y
15553   //
15554   // Then we can convert this into a sequence of BFI instructions. This will
15555   // always be a win if CM is a single bit, will always be no worse than the
15556   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
15557   // three bits (due to the extra IT instruction).
15558 
15559   SDValue Op0 = CMOV->getOperand(0);
15560   SDValue Op1 = CMOV->getOperand(1);
15561   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
15562   auto CC = CCNode->getAPIntValue().getLimitedValue();
15563   SDValue CmpZ = CMOV->getOperand(4);
15564 
15565   // The compare must be against zero.
15566   if (!isNullConstant(CmpZ->getOperand(1)))
15567     return SDValue();
15568 
15569   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
15570   SDValue And = CmpZ->getOperand(0);
15571   if (And->getOpcode() != ISD::AND)
15572     return SDValue();
15573   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
15574   if (!AndC)
15575     return SDValue();
15576   SDValue X = And->getOperand(0);
15577 
15578   if (CC == ARMCC::EQ) {
15579     // We're performing an "equal to zero" compare. Swap the operands so we
15580     // canonicalize on a "not equal to zero" compare.
15581     std::swap(Op0, Op1);
15582   } else {
15583     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
15584   }
15585 
15586   if (Op1->getOpcode() != ISD::OR)
15587     return SDValue();
15588 
15589   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
15590   if (!OrC)
15591     return SDValue();
15592   SDValue Y = Op1->getOperand(0);
15593 
15594   if (Op0 != Y)
15595     return SDValue();
15596 
15597   // Now, is it profitable to continue?
15598   APInt OrCI = OrC->getAPIntValue();
15599   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
15600   if (OrCI.countPopulation() > Heuristic)
15601     return SDValue();
15602 
15603   // Lastly, can we determine that the bits defined by OrCI
15604   // are zero in Y?
15605   KnownBits Known = DAG.computeKnownBits(Y);
15606   if ((OrCI & Known.Zero) != OrCI)
15607     return SDValue();
15608 
15609   // OK, we can do the combine.
15610   SDValue V = Y;
15611   SDLoc dl(X);
15612   EVT VT = X.getValueType();
15613   unsigned BitInX = AndC->logBase2();
15614 
15615   if (BitInX != 0) {
15616     // We must shift X first.
15617     X = DAG.getNode(ISD::SRL, dl, VT, X,
15618                     DAG.getConstant(BitInX, dl, VT));
15619   }
15620 
15621   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
15622        BitInY < NumActiveBits; ++BitInY) {
15623     if (OrCI[BitInY] == 0)
15624       continue;
15625     APInt Mask(VT.getSizeInBits(), 0);
15626     Mask.setBit(BitInY);
15627     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
15628                     // Confusingly, the operand is an *inverted* mask.
15629                     DAG.getConstant(~Mask, dl, VT));
15630   }
15631 
15632   return V;
15633 }
15634 
15635 // Given N, the value controlling the conditional branch, search for the loop
15636 // intrinsic, returning it, along with how the value is used. We need to handle
15637 // patterns such as the following:
15638 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
15639 // (brcond (setcc (loop.decrement), 0, eq), exit)
15640 // (brcond (setcc (loop.decrement), 0, ne), header)
15641 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
15642                                    bool &Negate) {
15643   switch (N->getOpcode()) {
15644   default:
15645     break;
15646   case ISD::XOR: {
15647     if (!isa<ConstantSDNode>(N.getOperand(1)))
15648       return SDValue();
15649     if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
15650       return SDValue();
15651     Negate = !Negate;
15652     return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
15653   }
15654   case ISD::SETCC: {
15655     auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
15656     if (!Const)
15657       return SDValue();
15658     if (Const->isNullValue())
15659       Imm = 0;
15660     else if (Const->isOne())
15661       Imm = 1;
15662     else
15663       return SDValue();
15664     CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
15665     return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
15666   }
15667   case ISD::INTRINSIC_W_CHAIN: {
15668     unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
15669     if (IntOp != Intrinsic::test_set_loop_iterations &&
15670         IntOp != Intrinsic::loop_decrement_reg)
15671       return SDValue();
15672     return N;
15673   }
15674   }
15675   return SDValue();
15676 }
15677 
15678 static SDValue PerformHWLoopCombine(SDNode *N,
15679                                     TargetLowering::DAGCombinerInfo &DCI,
15680                                     const ARMSubtarget *ST) {
15681 
15682   // The hwloop intrinsics that we're interested are used for control-flow,
15683   // either for entering or exiting the loop:
15684   // - test.set.loop.iterations will test whether its operand is zero. If it
15685   //   is zero, the proceeding branch should not enter the loop.
15686   // - loop.decrement.reg also tests whether its operand is zero. If it is
15687   //   zero, the proceeding branch should not branch back to the beginning of
15688   //   the loop.
15689   // So here, we need to check that how the brcond is using the result of each
15690   // of the intrinsics to ensure that we're branching to the right place at the
15691   // right time.
15692 
15693   ISD::CondCode CC;
15694   SDValue Cond;
15695   int Imm = 1;
15696   bool Negate = false;
15697   SDValue Chain = N->getOperand(0);
15698   SDValue Dest;
15699 
15700   if (N->getOpcode() == ISD::BRCOND) {
15701     CC = ISD::SETEQ;
15702     Cond = N->getOperand(1);
15703     Dest = N->getOperand(2);
15704   } else {
15705     assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
15706     CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
15707     Cond = N->getOperand(2);
15708     Dest = N->getOperand(4);
15709     if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
15710       if (!Const->isOne() && !Const->isNullValue())
15711         return SDValue();
15712       Imm = Const->getZExtValue();
15713     } else
15714       return SDValue();
15715   }
15716 
15717   SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
15718   if (!Int)
15719     return SDValue();
15720 
15721   if (Negate)
15722     CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
15723 
15724   auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
15725     return (CC == ISD::SETEQ && Imm == 0) ||
15726            (CC == ISD::SETNE && Imm == 1) ||
15727            (CC == ISD::SETLT && Imm == 1) ||
15728            (CC == ISD::SETULT && Imm == 1);
15729   };
15730 
15731   auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
15732     return (CC == ISD::SETEQ && Imm == 1) ||
15733            (CC == ISD::SETNE && Imm == 0) ||
15734            (CC == ISD::SETGT && Imm == 0) ||
15735            (CC == ISD::SETUGT && Imm == 0) ||
15736            (CC == ISD::SETGE && Imm == 1) ||
15737            (CC == ISD::SETUGE && Imm == 1);
15738   };
15739 
15740   assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
15741          "unsupported condition");
15742 
15743   SDLoc dl(Int);
15744   SelectionDAG &DAG = DCI.DAG;
15745   SDValue Elements = Int.getOperand(2);
15746   unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
15747   assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
15748           && "expected single br user");
15749   SDNode *Br = *N->use_begin();
15750   SDValue OtherTarget = Br->getOperand(1);
15751 
15752   // Update the unconditional branch to branch to the given Dest.
15753   auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
15754     SDValue NewBrOps[] = { Br->getOperand(0), Dest };
15755     SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
15756     DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
15757   };
15758 
15759   if (IntOp == Intrinsic::test_set_loop_iterations) {
15760     SDValue Res;
15761     // We expect this 'instruction' to branch when the counter is zero.
15762     if (IsTrueIfZero(CC, Imm)) {
15763       SDValue Ops[] = { Chain, Elements, Dest };
15764       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
15765     } else {
15766       // The logic is the reverse of what we need for WLS, so find the other
15767       // basic block target: the target of the proceeding br.
15768       UpdateUncondBr(Br, Dest, DAG);
15769 
15770       SDValue Ops[] = { Chain, Elements, OtherTarget };
15771       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
15772     }
15773     DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
15774     return Res;
15775   } else {
15776     SDValue Size = DAG.getTargetConstant(
15777       cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
15778     SDValue Args[] = { Int.getOperand(0), Elements, Size, };
15779     SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
15780                                   DAG.getVTList(MVT::i32, MVT::Other), Args);
15781     DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
15782 
15783     // We expect this instruction to branch when the count is not zero.
15784     SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
15785 
15786     // Update the unconditional branch to target the loop preheader if we've
15787     // found the condition has been reversed.
15788     if (Target == OtherTarget)
15789       UpdateUncondBr(Br, Dest, DAG);
15790 
15791     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
15792                         SDValue(LoopDec.getNode(), 1), Chain);
15793 
15794     SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
15795     return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
15796   }
15797   return SDValue();
15798 }
15799 
15800 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
15801 SDValue
15802 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
15803   SDValue Cmp = N->getOperand(4);
15804   if (Cmp.getOpcode() != ARMISD::CMPZ)
15805     // Only looking at NE cases.
15806     return SDValue();
15807 
15808   EVT VT = N->getValueType(0);
15809   SDLoc dl(N);
15810   SDValue LHS = Cmp.getOperand(0);
15811   SDValue RHS = Cmp.getOperand(1);
15812   SDValue Chain = N->getOperand(0);
15813   SDValue BB = N->getOperand(1);
15814   SDValue ARMcc = N->getOperand(2);
15815   ARMCC::CondCodes CC =
15816     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
15817 
15818   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
15819   // -> (brcond Chain BB CC CPSR Cmp)
15820   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
15821       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
15822       LHS->getOperand(0)->hasOneUse()) {
15823     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
15824     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
15825     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
15826     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
15827     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
15828         (LHS01C && LHS01C->getZExtValue() == 1) &&
15829         (LHS1C && LHS1C->getZExtValue() == 1) &&
15830         (RHSC && RHSC->getZExtValue() == 0)) {
15831       return DAG.getNode(
15832           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
15833           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
15834     }
15835   }
15836 
15837   return SDValue();
15838 }
15839 
15840 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
15841 SDValue
15842 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
15843   SDValue Cmp = N->getOperand(4);
15844   if (Cmp.getOpcode() != ARMISD::CMPZ)
15845     // Only looking at EQ and NE cases.
15846     return SDValue();
15847 
15848   EVT VT = N->getValueType(0);
15849   SDLoc dl(N);
15850   SDValue LHS = Cmp.getOperand(0);
15851   SDValue RHS = Cmp.getOperand(1);
15852   SDValue FalseVal = N->getOperand(0);
15853   SDValue TrueVal = N->getOperand(1);
15854   SDValue ARMcc = N->getOperand(2);
15855   ARMCC::CondCodes CC =
15856     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
15857 
15858   // BFI is only available on V6T2+.
15859   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
15860     SDValue R = PerformCMOVToBFICombine(N, DAG);
15861     if (R)
15862       return R;
15863   }
15864 
15865   // Simplify
15866   //   mov     r1, r0
15867   //   cmp     r1, x
15868   //   mov     r0, y
15869   //   moveq   r0, x
15870   // to
15871   //   cmp     r0, x
15872   //   movne   r0, y
15873   //
15874   //   mov     r1, r0
15875   //   cmp     r1, x
15876   //   mov     r0, x
15877   //   movne   r0, y
15878   // to
15879   //   cmp     r0, x
15880   //   movne   r0, y
15881   /// FIXME: Turn this into a target neutral optimization?
15882   SDValue Res;
15883   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
15884     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
15885                       N->getOperand(3), Cmp);
15886   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
15887     SDValue ARMcc;
15888     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
15889     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
15890                       N->getOperand(3), NewCmp);
15891   }
15892 
15893   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
15894   // -> (cmov F T CC CPSR Cmp)
15895   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
15896     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
15897     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
15898     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
15899     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
15900         (LHS1C && LHS1C->getZExtValue() == 1) &&
15901         (RHSC && RHSC->getZExtValue() == 0)) {
15902       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
15903                          LHS->getOperand(2), LHS->getOperand(3),
15904                          LHS->getOperand(4));
15905     }
15906   }
15907 
15908   if (!VT.isInteger())
15909       return SDValue();
15910 
15911   // Materialize a boolean comparison for integers so we can avoid branching.
15912   if (isNullConstant(FalseVal)) {
15913     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
15914       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
15915         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
15916         // right 5 bits will make that 32 be 1, otherwise it will be 0.
15917         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
15918         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
15919         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
15920                           DAG.getConstant(5, dl, MVT::i32));
15921       } else {
15922         // CMOV 0, 1, ==, (CMPZ x, y) ->
15923         //     (ADDCARRY (SUB x, y), t:0, t:1)
15924         // where t = (SUBCARRY 0, (SUB x, y), 0)
15925         //
15926         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
15927         // x != y. In other words, a carry C == 1 when x == y, C == 0
15928         // otherwise.
15929         // The final ADDCARRY computes
15930         //     x - y + (0 - (x - y)) + C == C
15931         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
15932         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15933         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
15934         // ISD::SUBCARRY returns a borrow but we want the carry here
15935         // actually.
15936         SDValue Carry =
15937             DAG.getNode(ISD::SUB, dl, MVT::i32,
15938                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
15939         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
15940       }
15941     } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
15942                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
15943       // This seems pointless but will allow us to combine it further below.
15944       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
15945       SDValue Sub =
15946           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
15947       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
15948                                           Sub.getValue(1), SDValue());
15949       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
15950                         N->getOperand(3), CPSRGlue.getValue(1));
15951       FalseVal = Sub;
15952     }
15953   } else if (isNullConstant(TrueVal)) {
15954     if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
15955         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
15956       // This seems pointless but will allow us to combine it further below
15957       // Note that we change == for != as this is the dual for the case above.
15958       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
15959       SDValue Sub =
15960           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
15961       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
15962                                           Sub.getValue(1), SDValue());
15963       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
15964                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
15965                         N->getOperand(3), CPSRGlue.getValue(1));
15966       FalseVal = Sub;
15967     }
15968   }
15969 
15970   // On Thumb1, the DAG above may be further combined if z is a power of 2
15971   // (z == 2 ^ K).
15972   // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
15973   // t1 = (USUBO (SUB x, y), 1)
15974   // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
15975   // Result = if K != 0 then (SHL t2:0, K) else t2:0
15976   //
15977   // This also handles the special case of comparing against zero; it's
15978   // essentially, the same pattern, except there's no SUBS:
15979   // CMOV x, z, !=, (CMPZ x, 0) ->
15980   // t1 = (USUBO x, 1)
15981   // t2 = (SUBCARRY x, t1:0, t1:1)
15982   // Result = if K != 0 then (SHL t2:0, K) else t2:0
15983   const APInt *TrueConst;
15984   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
15985       ((FalseVal.getOpcode() == ARMISD::SUBS &&
15986         FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
15987        (FalseVal == LHS && isNullConstant(RHS))) &&
15988       (TrueConst = isPowerOf2Constant(TrueVal))) {
15989     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15990     unsigned ShiftAmount = TrueConst->logBase2();
15991     if (ShiftAmount)
15992       TrueVal = DAG.getConstant(1, dl, VT);
15993     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
15994     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
15995 
15996     if (ShiftAmount)
15997       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
15998                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
15999   }
16000 
16001   if (Res.getNode()) {
16002     KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
16003     // Capture demanded bits information that would be otherwise lost.
16004     if (Known.Zero == 0xfffffffe)
16005       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
16006                         DAG.getValueType(MVT::i1));
16007     else if (Known.Zero == 0xffffff00)
16008       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
16009                         DAG.getValueType(MVT::i8));
16010     else if (Known.Zero == 0xffff0000)
16011       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
16012                         DAG.getValueType(MVT::i16));
16013   }
16014 
16015   return Res;
16016 }
16017 
16018 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG,
16019                                     const ARMSubtarget *ST) {
16020   SDValue Src = N->getOperand(0);
16021   EVT DstVT = N->getValueType(0);
16022 
16023   // Convert v4f32 bitcast (v4i32 vdup (i32)) -> v4f32 vdup (i32) under MVE.
16024   if (ST->hasMVEIntegerOps() && Src.getOpcode() == ARMISD::VDUP) {
16025     EVT SrcVT = Src.getValueType();
16026     if (SrcVT.getScalarSizeInBits() == DstVT.getScalarSizeInBits())
16027       return DAG.getNode(ARMISD::VDUP, SDLoc(N), DstVT, Src.getOperand(0));
16028   }
16029 
16030   // We may have a bitcast of something that has already had this bitcast
16031   // combine performed on it, so skip past any VECTOR_REG_CASTs.
16032   while (Src.getOpcode() == ARMISD::VECTOR_REG_CAST)
16033     Src = Src.getOperand(0);
16034 
16035   // Bitcast from element-wise VMOV or VMVN doesn't need VREV if the VREV that
16036   // would be generated is at least the width of the element type.
16037   EVT SrcVT = Src.getValueType();
16038   if ((Src.getOpcode() == ARMISD::VMOVIMM ||
16039        Src.getOpcode() == ARMISD::VMVNIMM ||
16040        Src.getOpcode() == ARMISD::VMOVFPIMM) &&
16041       SrcVT.getScalarSizeInBits() <= DstVT.getScalarSizeInBits() &&
16042       DAG.getDataLayout().isBigEndian())
16043     return DAG.getNode(ARMISD::VECTOR_REG_CAST, SDLoc(N), DstVT, Src);
16044 
16045   return SDValue();
16046 }
16047 
16048 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
16049                                              DAGCombinerInfo &DCI) const {
16050   switch (N->getOpcode()) {
16051   default: break;
16052   case ISD::VSELECT:    return PerformVSELECTCombine(N, DCI, Subtarget);
16053   case ISD::ABS:        return PerformABSCombine(N, DCI, Subtarget);
16054   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
16055   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
16056   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
16057   case ISD::SUB:        return PerformSUBCombine(N, DCI, Subtarget);
16058   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
16059   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
16060   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
16061   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
16062   case ISD::BRCOND:
16063   case ISD::BR_CC:      return PerformHWLoopCombine(N, DCI, Subtarget);
16064   case ARMISD::ADDC:
16065   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
16066   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
16067   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
16068   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
16069   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
16070   case ARMISD::VMOVhr:  return PerformVMOVhrCombine(N, DCI);
16071   case ARMISD::VMOVrh:  return PerformVMOVrhCombine(N, DCI);
16072   case ISD::STORE:      return PerformSTORECombine(N, DCI, Subtarget);
16073   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
16074   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
16075   case ISD::EXTRACT_VECTOR_ELT: return PerformExtractEltCombine(N, DCI);
16076   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
16077   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI, Subtarget);
16078   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
16079   case ISD::FP_TO_SINT:
16080   case ISD::FP_TO_UINT:
16081     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
16082   case ISD::FDIV:
16083     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
16084   case ISD::INTRINSIC_WO_CHAIN:
16085     return PerformIntrinsicCombine(N, DCI);
16086   case ISD::SHL:
16087   case ISD::SRA:
16088   case ISD::SRL:
16089     return PerformShiftCombine(N, DCI, Subtarget);
16090   case ISD::SIGN_EXTEND:
16091   case ISD::ZERO_EXTEND:
16092   case ISD::ANY_EXTEND:
16093     return PerformExtendCombine(N, DCI.DAG, Subtarget);
16094   case ISD::FP_EXTEND:
16095     return PerformFPExtendCombine(N, DCI.DAG, Subtarget);
16096   case ISD::SMIN:
16097   case ISD::UMIN:
16098   case ISD::SMAX:
16099   case ISD::UMAX:
16100     return PerformMinMaxCombine(N, DCI.DAG, Subtarget);
16101   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
16102   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
16103   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
16104   case ARMISD::VLD1DUP:
16105   case ARMISD::VLD2DUP:
16106   case ARMISD::VLD3DUP:
16107   case ARMISD::VLD4DUP:
16108     return PerformVLDCombine(N, DCI);
16109   case ARMISD::BUILD_VECTOR:
16110     return PerformARMBUILD_VECTORCombine(N, DCI);
16111   case ISD::BITCAST:
16112     return PerformBITCASTCombine(N, DCI.DAG, Subtarget);
16113   case ARMISD::PREDICATE_CAST:
16114     return PerformPREDICATE_CASTCombine(N, DCI);
16115   case ARMISD::VECTOR_REG_CAST:
16116     return PerformVECTOR_REG_CASTCombine(N, DCI, Subtarget);
16117   case ARMISD::VCMP:
16118     return PerformVCMPCombine(N, DCI, Subtarget);
16119   case ISD::VECREDUCE_ADD:
16120     return PerformVECREDUCE_ADDCombine(N, DCI.DAG, Subtarget);
16121   case ARMISD::VMOVN:
16122     return PerformVMOVNCombine(N, DCI);
16123   case ARMISD::VQMOVNs:
16124   case ARMISD::VQMOVNu:
16125     return PerformVQMOVNCombine(N, DCI);
16126   case ARMISD::ASRL:
16127   case ARMISD::LSRL:
16128   case ARMISD::LSLL:
16129     return PerformLongShiftCombine(N, DCI.DAG);
16130   case ARMISD::SMULWB: {
16131     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16132     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
16133     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
16134       return SDValue();
16135     break;
16136   }
16137   case ARMISD::SMULWT: {
16138     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16139     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
16140     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
16141       return SDValue();
16142     break;
16143   }
16144   case ARMISD::SMLALBB:
16145   case ARMISD::QADD16b:
16146   case ARMISD::QSUB16b: {
16147     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16148     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
16149     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
16150         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
16151       return SDValue();
16152     break;
16153   }
16154   case ARMISD::SMLALBT: {
16155     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
16156     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
16157     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
16158     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
16159     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
16160         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
16161       return SDValue();
16162     break;
16163   }
16164   case ARMISD::SMLALTB: {
16165     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
16166     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
16167     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
16168     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
16169     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
16170         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
16171       return SDValue();
16172     break;
16173   }
16174   case ARMISD::SMLALTT: {
16175     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16176     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
16177     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
16178         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
16179       return SDValue();
16180     break;
16181   }
16182   case ARMISD::QADD8b:
16183   case ARMISD::QSUB8b: {
16184     unsigned BitWidth = N->getValueType(0).getSizeInBits();
16185     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
16186     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
16187         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
16188       return SDValue();
16189     break;
16190   }
16191   case ISD::INTRINSIC_VOID:
16192   case ISD::INTRINSIC_W_CHAIN:
16193     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
16194     case Intrinsic::arm_neon_vld1:
16195     case Intrinsic::arm_neon_vld1x2:
16196     case Intrinsic::arm_neon_vld1x3:
16197     case Intrinsic::arm_neon_vld1x4:
16198     case Intrinsic::arm_neon_vld2:
16199     case Intrinsic::arm_neon_vld3:
16200     case Intrinsic::arm_neon_vld4:
16201     case Intrinsic::arm_neon_vld2lane:
16202     case Intrinsic::arm_neon_vld3lane:
16203     case Intrinsic::arm_neon_vld4lane:
16204     case Intrinsic::arm_neon_vld2dup:
16205     case Intrinsic::arm_neon_vld3dup:
16206     case Intrinsic::arm_neon_vld4dup:
16207     case Intrinsic::arm_neon_vst1:
16208     case Intrinsic::arm_neon_vst1x2:
16209     case Intrinsic::arm_neon_vst1x3:
16210     case Intrinsic::arm_neon_vst1x4:
16211     case Intrinsic::arm_neon_vst2:
16212     case Intrinsic::arm_neon_vst3:
16213     case Intrinsic::arm_neon_vst4:
16214     case Intrinsic::arm_neon_vst2lane:
16215     case Intrinsic::arm_neon_vst3lane:
16216     case Intrinsic::arm_neon_vst4lane:
16217       return PerformVLDCombine(N, DCI);
16218     case Intrinsic::arm_mve_vld2q:
16219     case Intrinsic::arm_mve_vld4q:
16220     case Intrinsic::arm_mve_vst2q:
16221     case Intrinsic::arm_mve_vst4q:
16222       return PerformMVEVLDCombine(N, DCI);
16223     default: break;
16224     }
16225     break;
16226   }
16227   return SDValue();
16228 }
16229 
16230 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
16231                                                           EVT VT) const {
16232   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
16233 }
16234 
16235 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
16236                                                        unsigned Alignment,
16237                                                        MachineMemOperand::Flags,
16238                                                        bool *Fast) const {
16239   // Depends what it gets converted into if the type is weird.
16240   if (!VT.isSimple())
16241     return false;
16242 
16243   // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
16244   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
16245   auto Ty = VT.getSimpleVT().SimpleTy;
16246 
16247   if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
16248     // Unaligned access can use (for example) LRDB, LRDH, LDR
16249     if (AllowsUnaligned) {
16250       if (Fast)
16251         *Fast = Subtarget->hasV7Ops();
16252       return true;
16253     }
16254   }
16255 
16256   if (Ty == MVT::f64 || Ty == MVT::v2f64) {
16257     // For any little-endian targets with neon, we can support unaligned ld/st
16258     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
16259     // A big-endian target may also explicitly support unaligned accesses
16260     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
16261       if (Fast)
16262         *Fast = true;
16263       return true;
16264     }
16265   }
16266 
16267   if (!Subtarget->hasMVEIntegerOps())
16268     return false;
16269 
16270   // These are for predicates
16271   if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
16272     if (Fast)
16273       *Fast = true;
16274     return true;
16275   }
16276 
16277   // These are for truncated stores/narrowing loads. They are fine so long as
16278   // the alignment is at least the size of the item being loaded
16279   if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
16280       Alignment >= VT.getScalarSizeInBits() / 8) {
16281     if (Fast)
16282       *Fast = true;
16283     return true;
16284   }
16285 
16286   // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
16287   // VSTRW.U32 all store the vector register in exactly the same format, and
16288   // differ only in the range of their immediate offset field and the required
16289   // alignment. So there is always a store that can be used, regardless of
16290   // actual type.
16291   //
16292   // For big endian, that is not the case. But can still emit a (VSTRB.U8;
16293   // VREV64.8) pair and get the same effect. This will likely be better than
16294   // aligning the vector through the stack.
16295   if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
16296       Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
16297       Ty == MVT::v2f64) {
16298     if (Fast)
16299       *Fast = true;
16300     return true;
16301   }
16302 
16303   return false;
16304 }
16305 
16306 
16307 EVT ARMTargetLowering::getOptimalMemOpType(
16308     const MemOp &Op, const AttributeList &FuncAttributes) const {
16309   // See if we can use NEON instructions for this...
16310   if ((Op.isMemcpy() || Op.isZeroMemset()) && Subtarget->hasNEON() &&
16311       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
16312     bool Fast;
16313     if (Op.size() >= 16 &&
16314         (Op.isAligned(Align(16)) ||
16315          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
16316                                          MachineMemOperand::MONone, &Fast) &&
16317           Fast))) {
16318       return MVT::v2f64;
16319     } else if (Op.size() >= 8 &&
16320                (Op.isAligned(Align(8)) ||
16321                 (allowsMisalignedMemoryAccesses(
16322                      MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
16323                  Fast))) {
16324       return MVT::f64;
16325     }
16326   }
16327 
16328   // Let the target-independent logic figure it out.
16329   return MVT::Other;
16330 }
16331 
16332 // 64-bit integers are split into their high and low parts and held in two
16333 // different registers, so the trunc is free since the low register can just
16334 // be used.
16335 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
16336   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
16337     return false;
16338   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
16339   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
16340   return (SrcBits == 64 && DestBits == 32);
16341 }
16342 
16343 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
16344   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
16345       !DstVT.isInteger())
16346     return false;
16347   unsigned SrcBits = SrcVT.getSizeInBits();
16348   unsigned DestBits = DstVT.getSizeInBits();
16349   return (SrcBits == 64 && DestBits == 32);
16350 }
16351 
16352 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16353   if (Val.getOpcode() != ISD::LOAD)
16354     return false;
16355 
16356   EVT VT1 = Val.getValueType();
16357   if (!VT1.isSimple() || !VT1.isInteger() ||
16358       !VT2.isSimple() || !VT2.isInteger())
16359     return false;
16360 
16361   switch (VT1.getSimpleVT().SimpleTy) {
16362   default: break;
16363   case MVT::i1:
16364   case MVT::i8:
16365   case MVT::i16:
16366     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
16367     return true;
16368   }
16369 
16370   return false;
16371 }
16372 
16373 bool ARMTargetLowering::isFNegFree(EVT VT) const {
16374   if (!VT.isSimple())
16375     return false;
16376 
16377   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
16378   // negate values directly (fneg is free). So, we don't want to let the DAG
16379   // combiner rewrite fneg into xors and some other instructions.  For f16 and
16380   // FullFP16 argument passing, some bitcast nodes may be introduced,
16381   // triggering this DAG combine rewrite, so we are avoiding that with this.
16382   switch (VT.getSimpleVT().SimpleTy) {
16383   default: break;
16384   case MVT::f16:
16385     return Subtarget->hasFullFP16();
16386   }
16387 
16388   return false;
16389 }
16390 
16391 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
16392 /// of the vector elements.
16393 static bool areExtractExts(Value *Ext1, Value *Ext2) {
16394   auto areExtDoubled = [](Instruction *Ext) {
16395     return Ext->getType()->getScalarSizeInBits() ==
16396            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
16397   };
16398 
16399   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
16400       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
16401       !areExtDoubled(cast<Instruction>(Ext1)) ||
16402       !areExtDoubled(cast<Instruction>(Ext2)))
16403     return false;
16404 
16405   return true;
16406 }
16407 
16408 /// Check if sinking \p I's operands to I's basic block is profitable, because
16409 /// the operands can be folded into a target instruction, e.g.
16410 /// sext/zext can be folded into vsubl.
16411 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
16412                                            SmallVectorImpl<Use *> &Ops) const {
16413   if (!I->getType()->isVectorTy())
16414     return false;
16415 
16416   if (Subtarget->hasNEON()) {
16417     switch (I->getOpcode()) {
16418     case Instruction::Sub:
16419     case Instruction::Add: {
16420       if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
16421         return false;
16422       Ops.push_back(&I->getOperandUse(0));
16423       Ops.push_back(&I->getOperandUse(1));
16424       return true;
16425     }
16426     default:
16427       return false;
16428     }
16429   }
16430 
16431   if (!Subtarget->hasMVEIntegerOps())
16432     return false;
16433 
16434   auto IsFMSMul = [&](Instruction *I) {
16435     if (!I->hasOneUse())
16436       return false;
16437     auto *Sub = cast<Instruction>(*I->users().begin());
16438     return Sub->getOpcode() == Instruction::FSub && Sub->getOperand(1) == I;
16439   };
16440   auto IsFMS = [&](Instruction *I) {
16441     if (match(I->getOperand(0), m_FNeg(m_Value())) ||
16442         match(I->getOperand(1), m_FNeg(m_Value())))
16443       return true;
16444     return false;
16445   };
16446 
16447   auto IsSinker = [&](Instruction *I, int Operand) {
16448     switch (I->getOpcode()) {
16449     case Instruction::Add:
16450     case Instruction::Mul:
16451     case Instruction::FAdd:
16452     case Instruction::ICmp:
16453     case Instruction::FCmp:
16454       return true;
16455     case Instruction::FMul:
16456       return !IsFMSMul(I);
16457     case Instruction::Sub:
16458     case Instruction::FSub:
16459     case Instruction::Shl:
16460     case Instruction::LShr:
16461     case Instruction::AShr:
16462       return Operand == 1;
16463     case Instruction::Call:
16464       if (auto *II = dyn_cast<IntrinsicInst>(I)) {
16465         switch (II->getIntrinsicID()) {
16466         case Intrinsic::fma:
16467           return !IsFMS(I);
16468         case Intrinsic::arm_mve_add_predicated:
16469         case Intrinsic::arm_mve_mul_predicated:
16470         case Intrinsic::arm_mve_qadd_predicated:
16471         case Intrinsic::arm_mve_hadd_predicated:
16472         case Intrinsic::arm_mve_vqdmull_predicated:
16473         case Intrinsic::arm_mve_qdmulh_predicated:
16474         case Intrinsic::arm_mve_qrdmulh_predicated:
16475         case Intrinsic::arm_mve_fma_predicated:
16476           return true;
16477         case Intrinsic::arm_mve_sub_predicated:
16478         case Intrinsic::arm_mve_qsub_predicated:
16479         case Intrinsic::arm_mve_hsub_predicated:
16480           return Operand == 1;
16481         default:
16482           return false;
16483         }
16484       }
16485       return false;
16486     default:
16487       return false;
16488     }
16489   };
16490 
16491   for (auto OpIdx : enumerate(I->operands())) {
16492     Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
16493     // Make sure we are not already sinking this operand
16494     if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
16495       continue;
16496 
16497     Instruction *Shuffle = Op;
16498     if (Shuffle->getOpcode() == Instruction::BitCast)
16499       Shuffle = dyn_cast<Instruction>(Shuffle->getOperand(0));
16500     // We are looking for a splat that can be sunk.
16501     if (!Shuffle ||
16502         !match(Shuffle, m_Shuffle(
16503                             m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
16504                             m_Undef(), m_ZeroMask())))
16505       continue;
16506     if (!IsSinker(I, OpIdx.index()))
16507       continue;
16508 
16509     // All uses of the shuffle should be sunk to avoid duplicating it across gpr
16510     // and vector registers
16511     for (Use &U : Op->uses()) {
16512       Instruction *Insn = cast<Instruction>(U.getUser());
16513       if (!IsSinker(Insn, U.getOperandNo()))
16514         return false;
16515     }
16516 
16517     Ops.push_back(&Shuffle->getOperandUse(0));
16518     if (Shuffle != Op)
16519       Ops.push_back(&Op->getOperandUse(0));
16520     Ops.push_back(&OpIdx.value());
16521   }
16522   return true;
16523 }
16524 
16525 Type *ARMTargetLowering::shouldConvertSplatType(ShuffleVectorInst *SVI) const {
16526   if (!Subtarget->hasMVEIntegerOps())
16527     return nullptr;
16528   Type *SVIType = SVI->getType();
16529   Type *ScalarType = SVIType->getScalarType();
16530 
16531   if (ScalarType->isFloatTy())
16532     return Type::getInt32Ty(SVIType->getContext());
16533   if (ScalarType->isHalfTy())
16534     return Type::getInt16Ty(SVIType->getContext());
16535   return nullptr;
16536 }
16537 
16538 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
16539   EVT VT = ExtVal.getValueType();
16540 
16541   if (!isTypeLegal(VT))
16542     return false;
16543 
16544   if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
16545     if (Ld->isExpandingLoad())
16546       return false;
16547   }
16548 
16549   if (Subtarget->hasMVEIntegerOps())
16550     return true;
16551 
16552   // Don't create a loadext if we can fold the extension into a wide/long
16553   // instruction.
16554   // If there's more than one user instruction, the loadext is desirable no
16555   // matter what.  There can be two uses by the same instruction.
16556   if (ExtVal->use_empty() ||
16557       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
16558     return true;
16559 
16560   SDNode *U = *ExtVal->use_begin();
16561   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
16562        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
16563     return false;
16564 
16565   return true;
16566 }
16567 
16568 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16569   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16570     return false;
16571 
16572   if (!isTypeLegal(EVT::getEVT(Ty1)))
16573     return false;
16574 
16575   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16576 
16577   // Assuming the caller doesn't have a zeroext or signext return parameter,
16578   // truncation all the way down to i1 is valid.
16579   return true;
16580 }
16581 
16582 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
16583                                                 const AddrMode &AM, Type *Ty,
16584                                                 unsigned AS) const {
16585   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
16586     if (Subtarget->hasFPAO())
16587       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
16588     return 0;
16589   }
16590   return -1;
16591 }
16592 
16593 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
16594 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
16595 /// expanded to FMAs when this method returns true, otherwise fmuladd is
16596 /// expanded to fmul + fadd.
16597 ///
16598 /// ARM supports both fused and unfused multiply-add operations; we already
16599 /// lower a pair of fmul and fadd to the latter so it's not clear that there
16600 /// would be a gain or that the gain would be worthwhile enough to risk
16601 /// correctness bugs.
16602 ///
16603 /// For MVE, we set this to true as it helps simplify the need for some
16604 /// patterns (and we don't have the non-fused floating point instruction).
16605 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
16606                                                    EVT VT) const {
16607   if (!VT.isSimple())
16608     return false;
16609 
16610   switch (VT.getSimpleVT().SimpleTy) {
16611   case MVT::v4f32:
16612   case MVT::v8f16:
16613     return Subtarget->hasMVEFloatOps();
16614   case MVT::f16:
16615     return Subtarget->useFPVFMx16();
16616   case MVT::f32:
16617     return Subtarget->useFPVFMx();
16618   case MVT::f64:
16619     return Subtarget->useFPVFMx64();
16620   default:
16621     break;
16622   }
16623 
16624   return false;
16625 }
16626 
16627 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
16628   if (V < 0)
16629     return false;
16630 
16631   unsigned Scale = 1;
16632   switch (VT.getSimpleVT().SimpleTy) {
16633   case MVT::i1:
16634   case MVT::i8:
16635     // Scale == 1;
16636     break;
16637   case MVT::i16:
16638     // Scale == 2;
16639     Scale = 2;
16640     break;
16641   default:
16642     // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
16643     // Scale == 4;
16644     Scale = 4;
16645     break;
16646   }
16647 
16648   if ((V & (Scale - 1)) != 0)
16649     return false;
16650   return isUInt<5>(V / Scale);
16651 }
16652 
16653 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
16654                                       const ARMSubtarget *Subtarget) {
16655   if (!VT.isInteger() && !VT.isFloatingPoint())
16656     return false;
16657   if (VT.isVector() && Subtarget->hasNEON())
16658     return false;
16659   if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
16660       !Subtarget->hasMVEFloatOps())
16661     return false;
16662 
16663   bool IsNeg = false;
16664   if (V < 0) {
16665     IsNeg = true;
16666     V = -V;
16667   }
16668 
16669   unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
16670 
16671   // MVE: size * imm7
16672   if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
16673     switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
16674     case MVT::i32:
16675     case MVT::f32:
16676       return isShiftedUInt<7,2>(V);
16677     case MVT::i16:
16678     case MVT::f16:
16679       return isShiftedUInt<7,1>(V);
16680     case MVT::i8:
16681       return isUInt<7>(V);
16682     default:
16683       return false;
16684     }
16685   }
16686 
16687   // half VLDR: 2 * imm8
16688   if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
16689     return isShiftedUInt<8, 1>(V);
16690   // VLDR and LDRD: 4 * imm8
16691   if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
16692     return isShiftedUInt<8, 2>(V);
16693 
16694   if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
16695     // + imm12 or - imm8
16696     if (IsNeg)
16697       return isUInt<8>(V);
16698     return isUInt<12>(V);
16699   }
16700 
16701   return false;
16702 }
16703 
16704 /// isLegalAddressImmediate - Return true if the integer value can be used
16705 /// as the offset of the target addressing mode for load / store of the
16706 /// given type.
16707 static bool isLegalAddressImmediate(int64_t V, EVT VT,
16708                                     const ARMSubtarget *Subtarget) {
16709   if (V == 0)
16710     return true;
16711 
16712   if (!VT.isSimple())
16713     return false;
16714 
16715   if (Subtarget->isThumb1Only())
16716     return isLegalT1AddressImmediate(V, VT);
16717   else if (Subtarget->isThumb2())
16718     return isLegalT2AddressImmediate(V, VT, Subtarget);
16719 
16720   // ARM mode.
16721   if (V < 0)
16722     V = - V;
16723   switch (VT.getSimpleVT().SimpleTy) {
16724   default: return false;
16725   case MVT::i1:
16726   case MVT::i8:
16727   case MVT::i32:
16728     // +- imm12
16729     return isUInt<12>(V);
16730   case MVT::i16:
16731     // +- imm8
16732     return isUInt<8>(V);
16733   case MVT::f32:
16734   case MVT::f64:
16735     if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
16736       return false;
16737     return isShiftedUInt<8, 2>(V);
16738   }
16739 }
16740 
16741 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
16742                                                       EVT VT) const {
16743   int Scale = AM.Scale;
16744   if (Scale < 0)
16745     return false;
16746 
16747   switch (VT.getSimpleVT().SimpleTy) {
16748   default: return false;
16749   case MVT::i1:
16750   case MVT::i8:
16751   case MVT::i16:
16752   case MVT::i32:
16753     if (Scale == 1)
16754       return true;
16755     // r + r << imm
16756     Scale = Scale & ~1;
16757     return Scale == 2 || Scale == 4 || Scale == 8;
16758   case MVT::i64:
16759     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
16760     // version in Thumb mode.
16761     // r + r
16762     if (Scale == 1)
16763       return true;
16764     // r * 2 (this can be lowered to r + r).
16765     if (!AM.HasBaseReg && Scale == 2)
16766       return true;
16767     return false;
16768   case MVT::isVoid:
16769     // Note, we allow "void" uses (basically, uses that aren't loads or
16770     // stores), because arm allows folding a scale into many arithmetic
16771     // operations.  This should be made more precise and revisited later.
16772 
16773     // Allow r << imm, but the imm has to be a multiple of two.
16774     if (Scale & 1) return false;
16775     return isPowerOf2_32(Scale);
16776   }
16777 }
16778 
16779 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
16780                                                       EVT VT) const {
16781   const int Scale = AM.Scale;
16782 
16783   // Negative scales are not supported in Thumb1.
16784   if (Scale < 0)
16785     return false;
16786 
16787   // Thumb1 addressing modes do not support register scaling excepting the
16788   // following cases:
16789   // 1. Scale == 1 means no scaling.
16790   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
16791   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
16792 }
16793 
16794 /// isLegalAddressingMode - Return true if the addressing mode represented
16795 /// by AM is legal for this target, for a load/store of the specified type.
16796 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
16797                                               const AddrMode &AM, Type *Ty,
16798                                               unsigned AS, Instruction *I) const {
16799   EVT VT = getValueType(DL, Ty, true);
16800   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
16801     return false;
16802 
16803   // Can never fold addr of global into load/store.
16804   if (AM.BaseGV)
16805     return false;
16806 
16807   switch (AM.Scale) {
16808   case 0:  // no scale reg, must be "r+i" or "r", or "i".
16809     break;
16810   default:
16811     // ARM doesn't support any R+R*scale+imm addr modes.
16812     if (AM.BaseOffs)
16813       return false;
16814 
16815     if (!VT.isSimple())
16816       return false;
16817 
16818     if (Subtarget->isThumb1Only())
16819       return isLegalT1ScaledAddressingMode(AM, VT);
16820 
16821     if (Subtarget->isThumb2())
16822       return isLegalT2ScaledAddressingMode(AM, VT);
16823 
16824     int Scale = AM.Scale;
16825     switch (VT.getSimpleVT().SimpleTy) {
16826     default: return false;
16827     case MVT::i1:
16828     case MVT::i8:
16829     case MVT::i32:
16830       if (Scale < 0) Scale = -Scale;
16831       if (Scale == 1)
16832         return true;
16833       // r + r << imm
16834       return isPowerOf2_32(Scale & ~1);
16835     case MVT::i16:
16836     case MVT::i64:
16837       // r +/- r
16838       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
16839         return true;
16840       // r * 2 (this can be lowered to r + r).
16841       if (!AM.HasBaseReg && Scale == 2)
16842         return true;
16843       return false;
16844 
16845     case MVT::isVoid:
16846       // Note, we allow "void" uses (basically, uses that aren't loads or
16847       // stores), because arm allows folding a scale into many arithmetic
16848       // operations.  This should be made more precise and revisited later.
16849 
16850       // Allow r << imm, but the imm has to be a multiple of two.
16851       if (Scale & 1) return false;
16852       return isPowerOf2_32(Scale);
16853     }
16854   }
16855   return true;
16856 }
16857 
16858 /// isLegalICmpImmediate - Return true if the specified immediate is legal
16859 /// icmp immediate, that is the target has icmp instructions which can compare
16860 /// a register against the immediate without having to materialize the
16861 /// immediate into a register.
16862 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16863   // Thumb2 and ARM modes can use cmn for negative immediates.
16864   if (!Subtarget->isThumb())
16865     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
16866            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
16867   if (Subtarget->isThumb2())
16868     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
16869            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
16870   // Thumb1 doesn't have cmn, and only 8-bit immediates.
16871   return Imm >= 0 && Imm <= 255;
16872 }
16873 
16874 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
16875 /// *or sub* immediate, that is the target has add or sub instructions which can
16876 /// add a register with the immediate without having to materialize the
16877 /// immediate into a register.
16878 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
16879   // Same encoding for add/sub, just flip the sign.
16880   int64_t AbsImm = std::abs(Imm);
16881   if (!Subtarget->isThumb())
16882     return ARM_AM::getSOImmVal(AbsImm) != -1;
16883   if (Subtarget->isThumb2())
16884     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
16885   // Thumb1 only has 8-bit unsigned immediate.
16886   return AbsImm >= 0 && AbsImm <= 255;
16887 }
16888 
16889 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
16890                                       bool isSEXTLoad, SDValue &Base,
16891                                       SDValue &Offset, bool &isInc,
16892                                       SelectionDAG &DAG) {
16893   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
16894     return false;
16895 
16896   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
16897     // AddressingMode 3
16898     Base = Ptr->getOperand(0);
16899     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
16900       int RHSC = (int)RHS->getZExtValue();
16901       if (RHSC < 0 && RHSC > -256) {
16902         assert(Ptr->getOpcode() == ISD::ADD);
16903         isInc = false;
16904         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16905         return true;
16906       }
16907     }
16908     isInc = (Ptr->getOpcode() == ISD::ADD);
16909     Offset = Ptr->getOperand(1);
16910     return true;
16911   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
16912     // AddressingMode 2
16913     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
16914       int RHSC = (int)RHS->getZExtValue();
16915       if (RHSC < 0 && RHSC > -0x1000) {
16916         assert(Ptr->getOpcode() == ISD::ADD);
16917         isInc = false;
16918         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16919         Base = Ptr->getOperand(0);
16920         return true;
16921       }
16922     }
16923 
16924     if (Ptr->getOpcode() == ISD::ADD) {
16925       isInc = true;
16926       ARM_AM::ShiftOpc ShOpcVal=
16927         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
16928       if (ShOpcVal != ARM_AM::no_shift) {
16929         Base = Ptr->getOperand(1);
16930         Offset = Ptr->getOperand(0);
16931       } else {
16932         Base = Ptr->getOperand(0);
16933         Offset = Ptr->getOperand(1);
16934       }
16935       return true;
16936     }
16937 
16938     isInc = (Ptr->getOpcode() == ISD::ADD);
16939     Base = Ptr->getOperand(0);
16940     Offset = Ptr->getOperand(1);
16941     return true;
16942   }
16943 
16944   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
16945   return false;
16946 }
16947 
16948 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
16949                                      bool isSEXTLoad, SDValue &Base,
16950                                      SDValue &Offset, bool &isInc,
16951                                      SelectionDAG &DAG) {
16952   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
16953     return false;
16954 
16955   Base = Ptr->getOperand(0);
16956   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
16957     int RHSC = (int)RHS->getZExtValue();
16958     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
16959       assert(Ptr->getOpcode() == ISD::ADD);
16960       isInc = false;
16961       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16962       return true;
16963     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
16964       isInc = Ptr->getOpcode() == ISD::ADD;
16965       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
16966       return true;
16967     }
16968   }
16969 
16970   return false;
16971 }
16972 
16973 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, Align Alignment,
16974                                       bool isSEXTLoad, bool IsMasked, bool isLE,
16975                                       SDValue &Base, SDValue &Offset,
16976                                       bool &isInc, SelectionDAG &DAG) {
16977   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
16978     return false;
16979   if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
16980     return false;
16981 
16982   // We allow LE non-masked loads to change the type (for example use a vldrb.8
16983   // as opposed to a vldrw.32). This can allow extra addressing modes or
16984   // alignments for what is otherwise an equivalent instruction.
16985   bool CanChangeType = isLE && !IsMasked;
16986 
16987   ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
16988   int RHSC = (int)RHS->getZExtValue();
16989 
16990   auto IsInRange = [&](int RHSC, int Limit, int Scale) {
16991     if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
16992       assert(Ptr->getOpcode() == ISD::ADD);
16993       isInc = false;
16994       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
16995       return true;
16996     } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
16997       isInc = Ptr->getOpcode() == ISD::ADD;
16998       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
16999       return true;
17000     }
17001     return false;
17002   };
17003 
17004   // Try to find a matching instruction based on s/zext, Alignment, Offset and
17005   // (in BE/masked) type.
17006   Base = Ptr->getOperand(0);
17007   if (VT == MVT::v4i16) {
17008     if (Alignment >= 2 && IsInRange(RHSC, 0x80, 2))
17009       return true;
17010   } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
17011     if (IsInRange(RHSC, 0x80, 1))
17012       return true;
17013   } else if (Alignment >= 4 &&
17014              (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
17015              IsInRange(RHSC, 0x80, 4))
17016     return true;
17017   else if (Alignment >= 2 &&
17018            (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
17019            IsInRange(RHSC, 0x80, 2))
17020     return true;
17021   else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
17022     return true;
17023   return false;
17024 }
17025 
17026 /// getPreIndexedAddressParts - returns true by value, base pointer and
17027 /// offset pointer and addressing mode by reference if the node's address
17028 /// can be legally represented as pre-indexed load / store address.
17029 bool
17030 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
17031                                              SDValue &Offset,
17032                                              ISD::MemIndexedMode &AM,
17033                                              SelectionDAG &DAG) const {
17034   if (Subtarget->isThumb1Only())
17035     return false;
17036 
17037   EVT VT;
17038   SDValue Ptr;
17039   Align Alignment;
17040   bool isSEXTLoad = false;
17041   bool IsMasked = false;
17042   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
17043     Ptr = LD->getBasePtr();
17044     VT = LD->getMemoryVT();
17045     Alignment = LD->getAlign();
17046     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17047   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
17048     Ptr = ST->getBasePtr();
17049     VT = ST->getMemoryVT();
17050     Alignment = ST->getAlign();
17051   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
17052     Ptr = LD->getBasePtr();
17053     VT = LD->getMemoryVT();
17054     Alignment = LD->getAlign();
17055     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17056     IsMasked = true;
17057   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
17058     Ptr = ST->getBasePtr();
17059     VT = ST->getMemoryVT();
17060     Alignment = ST->getAlign();
17061     IsMasked = true;
17062   } else
17063     return false;
17064 
17065   bool isInc;
17066   bool isLegal = false;
17067   if (VT.isVector())
17068     isLegal = Subtarget->hasMVEIntegerOps() &&
17069               getMVEIndexedAddressParts(
17070                   Ptr.getNode(), VT, Alignment, isSEXTLoad, IsMasked,
17071                   Subtarget->isLittle(), Base, Offset, isInc, DAG);
17072   else {
17073     if (Subtarget->isThumb2())
17074       isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
17075                                          Offset, isInc, DAG);
17076     else
17077       isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
17078                                           Offset, isInc, DAG);
17079   }
17080   if (!isLegal)
17081     return false;
17082 
17083   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
17084   return true;
17085 }
17086 
17087 /// getPostIndexedAddressParts - returns true by value, base pointer and
17088 /// offset pointer and addressing mode by reference if this node can be
17089 /// combined with a load / store to form a post-indexed load / store.
17090 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
17091                                                    SDValue &Base,
17092                                                    SDValue &Offset,
17093                                                    ISD::MemIndexedMode &AM,
17094                                                    SelectionDAG &DAG) const {
17095   EVT VT;
17096   SDValue Ptr;
17097   Align Alignment;
17098   bool isSEXTLoad = false, isNonExt;
17099   bool IsMasked = false;
17100   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
17101     VT = LD->getMemoryVT();
17102     Ptr = LD->getBasePtr();
17103     Alignment = LD->getAlign();
17104     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17105     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
17106   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
17107     VT = ST->getMemoryVT();
17108     Ptr = ST->getBasePtr();
17109     Alignment = ST->getAlign();
17110     isNonExt = !ST->isTruncatingStore();
17111   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
17112     VT = LD->getMemoryVT();
17113     Ptr = LD->getBasePtr();
17114     Alignment = LD->getAlign();
17115     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
17116     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
17117     IsMasked = true;
17118   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
17119     VT = ST->getMemoryVT();
17120     Ptr = ST->getBasePtr();
17121     Alignment = ST->getAlign();
17122     isNonExt = !ST->isTruncatingStore();
17123     IsMasked = true;
17124   } else
17125     return false;
17126 
17127   if (Subtarget->isThumb1Only()) {
17128     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
17129     // must be non-extending/truncating, i32, with an offset of 4.
17130     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
17131     if (Op->getOpcode() != ISD::ADD || !isNonExt)
17132       return false;
17133     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
17134     if (!RHS || RHS->getZExtValue() != 4)
17135       return false;
17136 
17137     Offset = Op->getOperand(1);
17138     Base = Op->getOperand(0);
17139     AM = ISD::POST_INC;
17140     return true;
17141   }
17142 
17143   bool isInc;
17144   bool isLegal = false;
17145   if (VT.isVector())
17146     isLegal = Subtarget->hasMVEIntegerOps() &&
17147               getMVEIndexedAddressParts(Op, VT, Alignment, isSEXTLoad, IsMasked,
17148                                         Subtarget->isLittle(), Base, Offset,
17149                                         isInc, DAG);
17150   else {
17151     if (Subtarget->isThumb2())
17152       isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
17153                                          isInc, DAG);
17154     else
17155       isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
17156                                           isInc, DAG);
17157   }
17158   if (!isLegal)
17159     return false;
17160 
17161   if (Ptr != Base) {
17162     // Swap base ptr and offset to catch more post-index load / store when
17163     // it's legal. In Thumb2 mode, offset must be an immediate.
17164     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
17165         !Subtarget->isThumb2())
17166       std::swap(Base, Offset);
17167 
17168     // Post-indexed load / store update the base pointer.
17169     if (Ptr != Base)
17170       return false;
17171   }
17172 
17173   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
17174   return true;
17175 }
17176 
17177 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17178                                                       KnownBits &Known,
17179                                                       const APInt &DemandedElts,
17180                                                       const SelectionDAG &DAG,
17181                                                       unsigned Depth) const {
17182   unsigned BitWidth = Known.getBitWidth();
17183   Known.resetAll();
17184   switch (Op.getOpcode()) {
17185   default: break;
17186   case ARMISD::ADDC:
17187   case ARMISD::ADDE:
17188   case ARMISD::SUBC:
17189   case ARMISD::SUBE:
17190     // Special cases when we convert a carry to a boolean.
17191     if (Op.getResNo() == 0) {
17192       SDValue LHS = Op.getOperand(0);
17193       SDValue RHS = Op.getOperand(1);
17194       // (ADDE 0, 0, C) will give us a single bit.
17195       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
17196           isNullConstant(RHS)) {
17197         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17198         return;
17199       }
17200     }
17201     break;
17202   case ARMISD::CMOV: {
17203     // Bits are known zero/one if known on the LHS and RHS.
17204     Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
17205     if (Known.isUnknown())
17206       return;
17207 
17208     KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
17209     Known.Zero &= KnownRHS.Zero;
17210     Known.One  &= KnownRHS.One;
17211     return;
17212   }
17213   case ISD::INTRINSIC_W_CHAIN: {
17214     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
17215     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
17216     switch (IntID) {
17217     default: return;
17218     case Intrinsic::arm_ldaex:
17219     case Intrinsic::arm_ldrex: {
17220       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
17221       unsigned MemBits = VT.getScalarSizeInBits();
17222       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
17223       return;
17224     }
17225     }
17226   }
17227   case ARMISD::BFI: {
17228     // Conservatively, we can recurse down the first operand
17229     // and just mask out all affected bits.
17230     Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
17231 
17232     // The operand to BFI is already a mask suitable for removing the bits it
17233     // sets.
17234     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
17235     const APInt &Mask = CI->getAPIntValue();
17236     Known.Zero &= Mask;
17237     Known.One &= Mask;
17238     return;
17239   }
17240   case ARMISD::VGETLANEs:
17241   case ARMISD::VGETLANEu: {
17242     const SDValue &SrcSV = Op.getOperand(0);
17243     EVT VecVT = SrcSV.getValueType();
17244     assert(VecVT.isVector() && "VGETLANE expected a vector type");
17245     const unsigned NumSrcElts = VecVT.getVectorNumElements();
17246     ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
17247     assert(Pos->getAPIntValue().ult(NumSrcElts) &&
17248            "VGETLANE index out of bounds");
17249     unsigned Idx = Pos->getZExtValue();
17250     APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
17251     Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
17252 
17253     EVT VT = Op.getValueType();
17254     const unsigned DstSz = VT.getScalarSizeInBits();
17255     const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
17256     (void)SrcSz;
17257     assert(SrcSz == Known.getBitWidth());
17258     assert(DstSz > SrcSz);
17259     if (Op.getOpcode() == ARMISD::VGETLANEs)
17260       Known = Known.sext(DstSz);
17261     else {
17262       Known = Known.zext(DstSz);
17263     }
17264     assert(DstSz == Known.getBitWidth());
17265     break;
17266   }
17267   case ARMISD::VMOVrh: {
17268     KnownBits KnownOp = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
17269     assert(KnownOp.getBitWidth() == 16);
17270     Known = KnownOp.zext(32);
17271     break;
17272   }
17273   }
17274 }
17275 
17276 bool ARMTargetLowering::targetShrinkDemandedConstant(
17277     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
17278     TargetLoweringOpt &TLO) const {
17279   // Delay optimization, so we don't have to deal with illegal types, or block
17280   // optimizations.
17281   if (!TLO.LegalOps)
17282     return false;
17283 
17284   // Only optimize AND for now.
17285   if (Op.getOpcode() != ISD::AND)
17286     return false;
17287 
17288   EVT VT = Op.getValueType();
17289 
17290   // Ignore vectors.
17291   if (VT.isVector())
17292     return false;
17293 
17294   assert(VT == MVT::i32 && "Unexpected integer type");
17295 
17296   // Make sure the RHS really is a constant.
17297   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
17298   if (!C)
17299     return false;
17300 
17301   unsigned Mask = C->getZExtValue();
17302 
17303   unsigned Demanded = DemandedBits.getZExtValue();
17304   unsigned ShrunkMask = Mask & Demanded;
17305   unsigned ExpandedMask = Mask | ~Demanded;
17306 
17307   // If the mask is all zeros, let the target-independent code replace the
17308   // result with zero.
17309   if (ShrunkMask == 0)
17310     return false;
17311 
17312   // If the mask is all ones, erase the AND. (Currently, the target-independent
17313   // code won't do this, so we have to do it explicitly to avoid an infinite
17314   // loop in obscure cases.)
17315   if (ExpandedMask == ~0U)
17316     return TLO.CombineTo(Op, Op.getOperand(0));
17317 
17318   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
17319     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
17320   };
17321   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
17322     if (NewMask == Mask)
17323       return true;
17324     SDLoc DL(Op);
17325     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
17326     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
17327     return TLO.CombineTo(Op, NewOp);
17328   };
17329 
17330   // Prefer uxtb mask.
17331   if (IsLegalMask(0xFF))
17332     return UseMask(0xFF);
17333 
17334   // Prefer uxth mask.
17335   if (IsLegalMask(0xFFFF))
17336     return UseMask(0xFFFF);
17337 
17338   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
17339   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
17340   if (ShrunkMask < 256)
17341     return UseMask(ShrunkMask);
17342 
17343   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
17344   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
17345   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
17346     return UseMask(ExpandedMask);
17347 
17348   // Potential improvements:
17349   //
17350   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
17351   // We could try to prefer Thumb1 immediates which can be lowered to a
17352   // two-instruction sequence.
17353   // We could try to recognize more legal ARM/Thumb2 immediates here.
17354 
17355   return false;
17356 }
17357 
17358 bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
17359     SDValue Op, const APInt &OriginalDemandedBits,
17360     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
17361     unsigned Depth) const {
17362   unsigned Opc = Op.getOpcode();
17363 
17364   switch (Opc) {
17365   case ARMISD::ASRL:
17366   case ARMISD::LSRL: {
17367     // If this is result 0 and the other result is unused, see if the demand
17368     // bits allow us to shrink this long shift into a standard small shift in
17369     // the opposite direction.
17370     if (Op.getResNo() == 0 && !Op->hasAnyUseOfValue(1) &&
17371         isa<ConstantSDNode>(Op->getOperand(2))) {
17372       unsigned ShAmt = Op->getConstantOperandVal(2);
17373       if (ShAmt < 32 && OriginalDemandedBits.isSubsetOf(
17374                             APInt::getAllOnesValue(32) << (32 - ShAmt)))
17375         return TLO.CombineTo(
17376             Op, TLO.DAG.getNode(
17377                     ISD::SHL, SDLoc(Op), MVT::i32, Op.getOperand(1),
17378                     TLO.DAG.getConstant(32 - ShAmt, SDLoc(Op), MVT::i32)));
17379     }
17380     break;
17381   }
17382   }
17383 
17384   return TargetLowering::SimplifyDemandedBitsForTargetNode(
17385       Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
17386 }
17387 
17388 //===----------------------------------------------------------------------===//
17389 //                           ARM Inline Assembly Support
17390 //===----------------------------------------------------------------------===//
17391 
17392 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
17393   // Looking for "rev" which is V6+.
17394   if (!Subtarget->hasV6Ops())
17395     return false;
17396 
17397   InlineAsm *IA = cast<InlineAsm>(CI->getCalledOperand());
17398   std::string AsmStr = IA->getAsmString();
17399   SmallVector<StringRef, 4> AsmPieces;
17400   SplitString(AsmStr, AsmPieces, ";\n");
17401 
17402   switch (AsmPieces.size()) {
17403   default: return false;
17404   case 1:
17405     AsmStr = std::string(AsmPieces[0]);
17406     AsmPieces.clear();
17407     SplitString(AsmStr, AsmPieces, " \t,");
17408 
17409     // rev $0, $1
17410     if (AsmPieces.size() == 3 &&
17411         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
17412         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
17413       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
17414       if (Ty && Ty->getBitWidth() == 32)
17415         return IntrinsicLowering::LowerToByteSwap(CI);
17416     }
17417     break;
17418   }
17419 
17420   return false;
17421 }
17422 
17423 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
17424   // At this point, we have to lower this constraint to something else, so we
17425   // lower it to an "r" or "w". However, by doing this we will force the result
17426   // to be in register, while the X constraint is much more permissive.
17427   //
17428   // Although we are correct (we are free to emit anything, without
17429   // constraints), we might break use cases that would expect us to be more
17430   // efficient and emit something else.
17431   if (!Subtarget->hasVFP2Base())
17432     return "r";
17433   if (ConstraintVT.isFloatingPoint())
17434     return "w";
17435   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
17436      (ConstraintVT.getSizeInBits() == 64 ||
17437       ConstraintVT.getSizeInBits() == 128))
17438     return "w";
17439 
17440   return "r";
17441 }
17442 
17443 /// getConstraintType - Given a constraint letter, return the type of
17444 /// constraint it is for this target.
17445 ARMTargetLowering::ConstraintType
17446 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
17447   unsigned S = Constraint.size();
17448   if (S == 1) {
17449     switch (Constraint[0]) {
17450     default:  break;
17451     case 'l': return C_RegisterClass;
17452     case 'w': return C_RegisterClass;
17453     case 'h': return C_RegisterClass;
17454     case 'x': return C_RegisterClass;
17455     case 't': return C_RegisterClass;
17456     case 'j': return C_Immediate; // Constant for movw.
17457     // An address with a single base register. Due to the way we
17458     // currently handle addresses it is the same as an 'r' memory constraint.
17459     case 'Q': return C_Memory;
17460     }
17461   } else if (S == 2) {
17462     switch (Constraint[0]) {
17463     default: break;
17464     case 'T': return C_RegisterClass;
17465     // All 'U+' constraints are addresses.
17466     case 'U': return C_Memory;
17467     }
17468   }
17469   return TargetLowering::getConstraintType(Constraint);
17470 }
17471 
17472 /// Examine constraint type and operand type and determine a weight value.
17473 /// This object must already have been set up with the operand type
17474 /// and the current alternative constraint selected.
17475 TargetLowering::ConstraintWeight
17476 ARMTargetLowering::getSingleConstraintMatchWeight(
17477     AsmOperandInfo &info, const char *constraint) const {
17478   ConstraintWeight weight = CW_Invalid;
17479   Value *CallOperandVal = info.CallOperandVal;
17480     // If we don't have a value, we can't do a match,
17481     // but allow it at the lowest weight.
17482   if (!CallOperandVal)
17483     return CW_Default;
17484   Type *type = CallOperandVal->getType();
17485   // Look at the constraint type.
17486   switch (*constraint) {
17487   default:
17488     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
17489     break;
17490   case 'l':
17491     if (type->isIntegerTy()) {
17492       if (Subtarget->isThumb())
17493         weight = CW_SpecificReg;
17494       else
17495         weight = CW_Register;
17496     }
17497     break;
17498   case 'w':
17499     if (type->isFloatingPointTy())
17500       weight = CW_Register;
17501     break;
17502   }
17503   return weight;
17504 }
17505 
17506 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
17507 
17508 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
17509     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
17510   switch (Constraint.size()) {
17511   case 1:
17512     // GCC ARM Constraint Letters
17513     switch (Constraint[0]) {
17514     case 'l': // Low regs or general regs.
17515       if (Subtarget->isThumb())
17516         return RCPair(0U, &ARM::tGPRRegClass);
17517       return RCPair(0U, &ARM::GPRRegClass);
17518     case 'h': // High regs or no regs.
17519       if (Subtarget->isThumb())
17520         return RCPair(0U, &ARM::hGPRRegClass);
17521       break;
17522     case 'r':
17523       if (Subtarget->isThumb1Only())
17524         return RCPair(0U, &ARM::tGPRRegClass);
17525       return RCPair(0U, &ARM::GPRRegClass);
17526     case 'w':
17527       if (VT == MVT::Other)
17528         break;
17529       if (VT == MVT::f32)
17530         return RCPair(0U, &ARM::SPRRegClass);
17531       if (VT.getSizeInBits() == 64)
17532         return RCPair(0U, &ARM::DPRRegClass);
17533       if (VT.getSizeInBits() == 128)
17534         return RCPair(0U, &ARM::QPRRegClass);
17535       break;
17536     case 'x':
17537       if (VT == MVT::Other)
17538         break;
17539       if (VT == MVT::f32)
17540         return RCPair(0U, &ARM::SPR_8RegClass);
17541       if (VT.getSizeInBits() == 64)
17542         return RCPair(0U, &ARM::DPR_8RegClass);
17543       if (VT.getSizeInBits() == 128)
17544         return RCPair(0U, &ARM::QPR_8RegClass);
17545       break;
17546     case 't':
17547       if (VT == MVT::Other)
17548         break;
17549       if (VT == MVT::f32 || VT == MVT::i32)
17550         return RCPair(0U, &ARM::SPRRegClass);
17551       if (VT.getSizeInBits() == 64)
17552         return RCPair(0U, &ARM::DPR_VFP2RegClass);
17553       if (VT.getSizeInBits() == 128)
17554         return RCPair(0U, &ARM::QPR_VFP2RegClass);
17555       break;
17556     }
17557     break;
17558 
17559   case 2:
17560     if (Constraint[0] == 'T') {
17561       switch (Constraint[1]) {
17562       default:
17563         break;
17564       case 'e':
17565         return RCPair(0U, &ARM::tGPREvenRegClass);
17566       case 'o':
17567         return RCPair(0U, &ARM::tGPROddRegClass);
17568       }
17569     }
17570     break;
17571 
17572   default:
17573     break;
17574   }
17575 
17576   if (StringRef("{cc}").equals_lower(Constraint))
17577     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
17578 
17579   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
17580 }
17581 
17582 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
17583 /// vector.  If it is invalid, don't add anything to Ops.
17584 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
17585                                                      std::string &Constraint,
17586                                                      std::vector<SDValue>&Ops,
17587                                                      SelectionDAG &DAG) const {
17588   SDValue Result;
17589 
17590   // Currently only support length 1 constraints.
17591   if (Constraint.length() != 1) return;
17592 
17593   char ConstraintLetter = Constraint[0];
17594   switch (ConstraintLetter) {
17595   default: break;
17596   case 'j':
17597   case 'I': case 'J': case 'K': case 'L':
17598   case 'M': case 'N': case 'O':
17599     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
17600     if (!C)
17601       return;
17602 
17603     int64_t CVal64 = C->getSExtValue();
17604     int CVal = (int) CVal64;
17605     // None of these constraints allow values larger than 32 bits.  Check
17606     // that the value fits in an int.
17607     if (CVal != CVal64)
17608       return;
17609 
17610     switch (ConstraintLetter) {
17611       case 'j':
17612         // Constant suitable for movw, must be between 0 and
17613         // 65535.
17614         if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
17615           if (CVal >= 0 && CVal <= 65535)
17616             break;
17617         return;
17618       case 'I':
17619         if (Subtarget->isThumb1Only()) {
17620           // This must be a constant between 0 and 255, for ADD
17621           // immediates.
17622           if (CVal >= 0 && CVal <= 255)
17623             break;
17624         } else if (Subtarget->isThumb2()) {
17625           // A constant that can be used as an immediate value in a
17626           // data-processing instruction.
17627           if (ARM_AM::getT2SOImmVal(CVal) != -1)
17628             break;
17629         } else {
17630           // A constant that can be used as an immediate value in a
17631           // data-processing instruction.
17632           if (ARM_AM::getSOImmVal(CVal) != -1)
17633             break;
17634         }
17635         return;
17636 
17637       case 'J':
17638         if (Subtarget->isThumb1Only()) {
17639           // This must be a constant between -255 and -1, for negated ADD
17640           // immediates. This can be used in GCC with an "n" modifier that
17641           // prints the negated value, for use with SUB instructions. It is
17642           // not useful otherwise but is implemented for compatibility.
17643           if (CVal >= -255 && CVal <= -1)
17644             break;
17645         } else {
17646           // This must be a constant between -4095 and 4095. It is not clear
17647           // what this constraint is intended for. Implemented for
17648           // compatibility with GCC.
17649           if (CVal >= -4095 && CVal <= 4095)
17650             break;
17651         }
17652         return;
17653 
17654       case 'K':
17655         if (Subtarget->isThumb1Only()) {
17656           // A 32-bit value where only one byte has a nonzero value. Exclude
17657           // zero to match GCC. This constraint is used by GCC internally for
17658           // constants that can be loaded with a move/shift combination.
17659           // It is not useful otherwise but is implemented for compatibility.
17660           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
17661             break;
17662         } else if (Subtarget->isThumb2()) {
17663           // A constant whose bitwise inverse can be used as an immediate
17664           // value in a data-processing instruction. This can be used in GCC
17665           // with a "B" modifier that prints the inverted value, for use with
17666           // BIC and MVN instructions. It is not useful otherwise but is
17667           // implemented for compatibility.
17668           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
17669             break;
17670         } else {
17671           // A constant whose bitwise inverse can be used as an immediate
17672           // value in a data-processing instruction. This can be used in GCC
17673           // with a "B" modifier that prints the inverted value, for use with
17674           // BIC and MVN instructions. It is not useful otherwise but is
17675           // implemented for compatibility.
17676           if (ARM_AM::getSOImmVal(~CVal) != -1)
17677             break;
17678         }
17679         return;
17680 
17681       case 'L':
17682         if (Subtarget->isThumb1Only()) {
17683           // This must be a constant between -7 and 7,
17684           // for 3-operand ADD/SUB immediate instructions.
17685           if (CVal >= -7 && CVal < 7)
17686             break;
17687         } else if (Subtarget->isThumb2()) {
17688           // A constant whose negation can be used as an immediate value in a
17689           // data-processing instruction. This can be used in GCC with an "n"
17690           // modifier that prints the negated value, for use with SUB
17691           // instructions. It is not useful otherwise but is implemented for
17692           // compatibility.
17693           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
17694             break;
17695         } else {
17696           // A constant whose negation can be used as an immediate value in a
17697           // data-processing instruction. This can be used in GCC with an "n"
17698           // modifier that prints the negated value, for use with SUB
17699           // instructions. It is not useful otherwise but is implemented for
17700           // compatibility.
17701           if (ARM_AM::getSOImmVal(-CVal) != -1)
17702             break;
17703         }
17704         return;
17705 
17706       case 'M':
17707         if (Subtarget->isThumb1Only()) {
17708           // This must be a multiple of 4 between 0 and 1020, for
17709           // ADD sp + immediate.
17710           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
17711             break;
17712         } else {
17713           // A power of two or a constant between 0 and 32.  This is used in
17714           // GCC for the shift amount on shifted register operands, but it is
17715           // useful in general for any shift amounts.
17716           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
17717             break;
17718         }
17719         return;
17720 
17721       case 'N':
17722         if (Subtarget->isThumb1Only()) {
17723           // This must be a constant between 0 and 31, for shift amounts.
17724           if (CVal >= 0 && CVal <= 31)
17725             break;
17726         }
17727         return;
17728 
17729       case 'O':
17730         if (Subtarget->isThumb1Only()) {
17731           // This must be a multiple of 4 between -508 and 508, for
17732           // ADD/SUB sp = sp + immediate.
17733           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
17734             break;
17735         }
17736         return;
17737     }
17738     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
17739     break;
17740   }
17741 
17742   if (Result.getNode()) {
17743     Ops.push_back(Result);
17744     return;
17745   }
17746   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
17747 }
17748 
17749 static RTLIB::Libcall getDivRemLibcall(
17750     const SDNode *N, MVT::SimpleValueType SVT) {
17751   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
17752           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
17753          "Unhandled Opcode in getDivRemLibcall");
17754   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
17755                   N->getOpcode() == ISD::SREM;
17756   RTLIB::Libcall LC;
17757   switch (SVT) {
17758   default: llvm_unreachable("Unexpected request for libcall!");
17759   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
17760   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
17761   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
17762   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
17763   }
17764   return LC;
17765 }
17766 
17767 static TargetLowering::ArgListTy getDivRemArgList(
17768     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
17769   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
17770           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
17771          "Unhandled Opcode in getDivRemArgList");
17772   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
17773                   N->getOpcode() == ISD::SREM;
17774   TargetLowering::ArgListTy Args;
17775   TargetLowering::ArgListEntry Entry;
17776   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
17777     EVT ArgVT = N->getOperand(i).getValueType();
17778     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
17779     Entry.Node = N->getOperand(i);
17780     Entry.Ty = ArgTy;
17781     Entry.IsSExt = isSigned;
17782     Entry.IsZExt = !isSigned;
17783     Args.push_back(Entry);
17784   }
17785   if (Subtarget->isTargetWindows() && Args.size() >= 2)
17786     std::swap(Args[0], Args[1]);
17787   return Args;
17788 }
17789 
17790 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
17791   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
17792           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
17793           Subtarget->isTargetWindows()) &&
17794          "Register-based DivRem lowering only");
17795   unsigned Opcode = Op->getOpcode();
17796   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
17797          "Invalid opcode for Div/Rem lowering");
17798   bool isSigned = (Opcode == ISD::SDIVREM);
17799   EVT VT = Op->getValueType(0);
17800   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
17801   SDLoc dl(Op);
17802 
17803   // If the target has hardware divide, use divide + multiply + subtract:
17804   //     div = a / b
17805   //     rem = a - b * div
17806   //     return {div, rem}
17807   // This should be lowered into UDIV/SDIV + MLS later on.
17808   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
17809                                         : Subtarget->hasDivideInARMMode();
17810   if (hasDivide && Op->getValueType(0).isSimple() &&
17811       Op->getSimpleValueType(0) == MVT::i32) {
17812     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
17813     const SDValue Dividend = Op->getOperand(0);
17814     const SDValue Divisor = Op->getOperand(1);
17815     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
17816     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
17817     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
17818 
17819     SDValue Values[2] = {Div, Rem};
17820     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
17821   }
17822 
17823   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
17824                                        VT.getSimpleVT().SimpleTy);
17825   SDValue InChain = DAG.getEntryNode();
17826 
17827   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
17828                                                     DAG.getContext(),
17829                                                     Subtarget);
17830 
17831   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17832                                          getPointerTy(DAG.getDataLayout()));
17833 
17834   Type *RetTy = StructType::get(Ty, Ty);
17835 
17836   if (Subtarget->isTargetWindows())
17837     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
17838 
17839   TargetLowering::CallLoweringInfo CLI(DAG);
17840   CLI.setDebugLoc(dl).setChain(InChain)
17841     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
17842     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17843 
17844   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17845   return CallInfo.first;
17846 }
17847 
17848 // Lowers REM using divmod helpers
17849 // see RTABI section 4.2/4.3
17850 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
17851   // Build return types (div and rem)
17852   std::vector<Type*> RetTyParams;
17853   Type *RetTyElement;
17854 
17855   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
17856   default: llvm_unreachable("Unexpected request for libcall!");
17857   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
17858   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
17859   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
17860   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
17861   }
17862 
17863   RetTyParams.push_back(RetTyElement);
17864   RetTyParams.push_back(RetTyElement);
17865   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
17866   Type *RetTy = StructType::get(*DAG.getContext(), ret);
17867 
17868   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
17869                                                              SimpleTy);
17870   SDValue InChain = DAG.getEntryNode();
17871   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
17872                                                     Subtarget);
17873   bool isSigned = N->getOpcode() == ISD::SREM;
17874   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17875                                          getPointerTy(DAG.getDataLayout()));
17876 
17877   if (Subtarget->isTargetWindows())
17878     InChain = WinDBZCheckDenominator(DAG, N, InChain);
17879 
17880   // Lower call
17881   CallLoweringInfo CLI(DAG);
17882   CLI.setChain(InChain)
17883      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
17884      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
17885   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
17886 
17887   // Return second (rem) result operand (first contains div)
17888   SDNode *ResNode = CallResult.first.getNode();
17889   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
17890   return ResNode->getOperand(1);
17891 }
17892 
17893 SDValue
17894 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
17895   assert(Subtarget->isTargetWindows() && "unsupported target platform");
17896   SDLoc DL(Op);
17897 
17898   // Get the inputs.
17899   SDValue Chain = Op.getOperand(0);
17900   SDValue Size  = Op.getOperand(1);
17901 
17902   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
17903           "no-stack-arg-probe")) {
17904     MaybeAlign Align =
17905         cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
17906     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
17907     Chain = SP.getValue(1);
17908     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
17909     if (Align)
17910       SP =
17911           DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
17912                       DAG.getConstant(-(uint64_t)Align->value(), DL, MVT::i32));
17913     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
17914     SDValue Ops[2] = { SP, Chain };
17915     return DAG.getMergeValues(Ops, DL);
17916   }
17917 
17918   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
17919                               DAG.getConstant(2, DL, MVT::i32));
17920 
17921   SDValue Flag;
17922   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
17923   Flag = Chain.getValue(1);
17924 
17925   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
17926   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
17927 
17928   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
17929   Chain = NewSP.getValue(1);
17930 
17931   SDValue Ops[2] = { NewSP, Chain };
17932   return DAG.getMergeValues(Ops, DL);
17933 }
17934 
17935 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
17936   bool IsStrict = Op->isStrictFPOpcode();
17937   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
17938   const unsigned DstSz = Op.getValueType().getSizeInBits();
17939   const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
17940   assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
17941          "Unexpected type for custom-lowering FP_EXTEND");
17942 
17943   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
17944          "With both FP DP and 16, any FP conversion is legal!");
17945 
17946   assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
17947          "With FP16, 16 to 32 conversion is legal!");
17948 
17949   // Converting from 32 -> 64 is valid if we have FP64.
17950   if (SrcSz == 32 && DstSz == 64 && Subtarget->hasFP64()) {
17951     // FIXME: Remove this when we have strict fp instruction selection patterns
17952     if (IsStrict) {
17953       SDLoc Loc(Op);
17954       SDValue Result = DAG.getNode(ISD::FP_EXTEND,
17955                                    Loc, Op.getValueType(), SrcVal);
17956       return DAG.getMergeValues({Result, Op.getOperand(0)}, Loc);
17957     }
17958     return Op;
17959   }
17960 
17961   // Either we are converting from 16 -> 64, without FP16 and/or
17962   // FP.double-precision or without Armv8-fp. So we must do it in two
17963   // steps.
17964   // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
17965   // without FP16. So we must do a function call.
17966   SDLoc Loc(Op);
17967   RTLIB::Libcall LC;
17968   MakeLibCallOptions CallOptions;
17969   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
17970   for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
17971     bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
17972     MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
17973     MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
17974     if (Supported) {
17975       if (IsStrict) {
17976         SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
17977                              {DstVT, MVT::Other}, {Chain, SrcVal});
17978         Chain = SrcVal.getValue(1);
17979       } else {
17980         SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
17981       }
17982     } else {
17983       LC = RTLIB::getFPEXT(SrcVT, DstVT);
17984       assert(LC != RTLIB::UNKNOWN_LIBCALL &&
17985              "Unexpected type for custom-lowering FP_EXTEND");
17986       std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
17987                                             Loc, Chain);
17988     }
17989   }
17990 
17991   return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
17992 }
17993 
17994 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
17995   bool IsStrict = Op->isStrictFPOpcode();
17996 
17997   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
17998   EVT SrcVT = SrcVal.getValueType();
17999   EVT DstVT = Op.getValueType();
18000   const unsigned DstSz = Op.getValueType().getSizeInBits();
18001   const unsigned SrcSz = SrcVT.getSizeInBits();
18002   (void)DstSz;
18003   assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
18004          "Unexpected type for custom-lowering FP_ROUND");
18005 
18006   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
18007          "With both FP DP and 16, any FP conversion is legal!");
18008 
18009   SDLoc Loc(Op);
18010 
18011   // Instruction from 32 -> 16 if hasFP16 is valid
18012   if (SrcSz == 32 && Subtarget->hasFP16())
18013     return Op;
18014 
18015   // Lib call from 32 -> 16 / 64 -> [32, 16]
18016   RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
18017   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
18018          "Unexpected type for custom-lowering FP_ROUND");
18019   MakeLibCallOptions CallOptions;
18020   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
18021   SDValue Result;
18022   std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
18023                                         Loc, Chain);
18024   return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
18025 }
18026 
18027 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
18028                                  SelectionDAG &DAG) const {
18029   assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
18030   MVT HalfT = MVT::i32;
18031   SDLoc dl(N);
18032   SDValue Hi, Lo, Tmp;
18033 
18034   if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
18035       !isOperationLegalOrCustom(ISD::UADDO, HalfT))
18036     return ;
18037 
18038   unsigned OpTypeBits = HalfT.getScalarSizeInBits();
18039   SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
18040 
18041   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
18042                    DAG.getConstant(0, dl, HalfT));
18043   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
18044                    DAG.getConstant(1, dl, HalfT));
18045 
18046   Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
18047                     DAG.getConstant(OpTypeBits - 1, dl,
18048                     getShiftAmountTy(HalfT, DAG.getDataLayout())));
18049   Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
18050   Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
18051                    SDValue(Lo.getNode(), 1));
18052   Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
18053   Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
18054 
18055   Results.push_back(Lo);
18056   Results.push_back(Hi);
18057 }
18058 
18059 bool
18060 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
18061   // The ARM target isn't yet aware of offsets.
18062   return false;
18063 }
18064 
18065 bool ARM::isBitFieldInvertedMask(unsigned v) {
18066   if (v == 0xffffffff)
18067     return false;
18068 
18069   // there can be 1's on either or both "outsides", all the "inside"
18070   // bits must be 0's
18071   return isShiftedMask_32(~v);
18072 }
18073 
18074 /// isFPImmLegal - Returns true if the target can instruction select the
18075 /// specified FP immediate natively. If false, the legalizer will
18076 /// materialize the FP immediate as a load from a constant pool.
18077 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
18078                                      bool ForCodeSize) const {
18079   if (!Subtarget->hasVFP3Base())
18080     return false;
18081   if (VT == MVT::f16 && Subtarget->hasFullFP16())
18082     return ARM_AM::getFP16Imm(Imm) != -1;
18083   if (VT == MVT::f32 && Subtarget->hasFullFP16() &&
18084       ARM_AM::getFP32FP16Imm(Imm) != -1)
18085     return true;
18086   if (VT == MVT::f32)
18087     return ARM_AM::getFP32Imm(Imm) != -1;
18088   if (VT == MVT::f64 && Subtarget->hasFP64())
18089     return ARM_AM::getFP64Imm(Imm) != -1;
18090   return false;
18091 }
18092 
18093 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
18094 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
18095 /// specified in the intrinsic calls.
18096 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
18097                                            const CallInst &I,
18098                                            MachineFunction &MF,
18099                                            unsigned Intrinsic) const {
18100   switch (Intrinsic) {
18101   case Intrinsic::arm_neon_vld1:
18102   case Intrinsic::arm_neon_vld2:
18103   case Intrinsic::arm_neon_vld3:
18104   case Intrinsic::arm_neon_vld4:
18105   case Intrinsic::arm_neon_vld2lane:
18106   case Intrinsic::arm_neon_vld3lane:
18107   case Intrinsic::arm_neon_vld4lane:
18108   case Intrinsic::arm_neon_vld2dup:
18109   case Intrinsic::arm_neon_vld3dup:
18110   case Intrinsic::arm_neon_vld4dup: {
18111     Info.opc = ISD::INTRINSIC_W_CHAIN;
18112     // Conservatively set memVT to the entire set of vectors loaded.
18113     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18114     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
18115     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18116     Info.ptrVal = I.getArgOperand(0);
18117     Info.offset = 0;
18118     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
18119     Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
18120     // volatile loads with NEON intrinsics not supported
18121     Info.flags = MachineMemOperand::MOLoad;
18122     return true;
18123   }
18124   case Intrinsic::arm_neon_vld1x2:
18125   case Intrinsic::arm_neon_vld1x3:
18126   case Intrinsic::arm_neon_vld1x4: {
18127     Info.opc = ISD::INTRINSIC_W_CHAIN;
18128     // Conservatively set memVT to the entire set of vectors loaded.
18129     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18130     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
18131     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18132     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
18133     Info.offset = 0;
18134     Info.align.reset();
18135     // volatile loads with NEON intrinsics not supported
18136     Info.flags = MachineMemOperand::MOLoad;
18137     return true;
18138   }
18139   case Intrinsic::arm_neon_vst1:
18140   case Intrinsic::arm_neon_vst2:
18141   case Intrinsic::arm_neon_vst3:
18142   case Intrinsic::arm_neon_vst4:
18143   case Intrinsic::arm_neon_vst2lane:
18144   case Intrinsic::arm_neon_vst3lane:
18145   case Intrinsic::arm_neon_vst4lane: {
18146     Info.opc = ISD::INTRINSIC_VOID;
18147     // Conservatively set memVT to the entire set of vectors stored.
18148     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18149     unsigned NumElts = 0;
18150     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
18151       Type *ArgTy = I.getArgOperand(ArgI)->getType();
18152       if (!ArgTy->isVectorTy())
18153         break;
18154       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
18155     }
18156     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18157     Info.ptrVal = I.getArgOperand(0);
18158     Info.offset = 0;
18159     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
18160     Info.align = cast<ConstantInt>(AlignArg)->getMaybeAlignValue();
18161     // volatile stores with NEON intrinsics not supported
18162     Info.flags = MachineMemOperand::MOStore;
18163     return true;
18164   }
18165   case Intrinsic::arm_neon_vst1x2:
18166   case Intrinsic::arm_neon_vst1x3:
18167   case Intrinsic::arm_neon_vst1x4: {
18168     Info.opc = ISD::INTRINSIC_VOID;
18169     // Conservatively set memVT to the entire set of vectors stored.
18170     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18171     unsigned NumElts = 0;
18172     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
18173       Type *ArgTy = I.getArgOperand(ArgI)->getType();
18174       if (!ArgTy->isVectorTy())
18175         break;
18176       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
18177     }
18178     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
18179     Info.ptrVal = I.getArgOperand(0);
18180     Info.offset = 0;
18181     Info.align.reset();
18182     // volatile stores with NEON intrinsics not supported
18183     Info.flags = MachineMemOperand::MOStore;
18184     return true;
18185   }
18186   case Intrinsic::arm_mve_vld2q:
18187   case Intrinsic::arm_mve_vld4q: {
18188     Info.opc = ISD::INTRINSIC_W_CHAIN;
18189     // Conservatively set memVT to the entire set of vectors loaded.
18190     Type *VecTy = cast<StructType>(I.getType())->getElementType(1);
18191     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vld2q ? 2 : 4;
18192     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
18193     Info.ptrVal = I.getArgOperand(0);
18194     Info.offset = 0;
18195     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
18196     // volatile loads with MVE intrinsics not supported
18197     Info.flags = MachineMemOperand::MOLoad;
18198     return true;
18199   }
18200   case Intrinsic::arm_mve_vst2q:
18201   case Intrinsic::arm_mve_vst4q: {
18202     Info.opc = ISD::INTRINSIC_VOID;
18203     // Conservatively set memVT to the entire set of vectors stored.
18204     Type *VecTy = I.getArgOperand(1)->getType();
18205     unsigned Factor = Intrinsic == Intrinsic::arm_mve_vst2q ? 2 : 4;
18206     Info.memVT = EVT::getVectorVT(VecTy->getContext(), MVT::i64, Factor * 2);
18207     Info.ptrVal = I.getArgOperand(0);
18208     Info.offset = 0;
18209     Info.align = Align(VecTy->getScalarSizeInBits() / 8);
18210     // volatile stores with MVE intrinsics not supported
18211     Info.flags = MachineMemOperand::MOStore;
18212     return true;
18213   }
18214   case Intrinsic::arm_ldaex:
18215   case Intrinsic::arm_ldrex: {
18216     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18217     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
18218     Info.opc = ISD::INTRINSIC_W_CHAIN;
18219     Info.memVT = MVT::getVT(PtrTy->getElementType());
18220     Info.ptrVal = I.getArgOperand(0);
18221     Info.offset = 0;
18222     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
18223     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
18224     return true;
18225   }
18226   case Intrinsic::arm_stlex:
18227   case Intrinsic::arm_strex: {
18228     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
18229     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
18230     Info.opc = ISD::INTRINSIC_W_CHAIN;
18231     Info.memVT = MVT::getVT(PtrTy->getElementType());
18232     Info.ptrVal = I.getArgOperand(1);
18233     Info.offset = 0;
18234     Info.align = DL.getABITypeAlign(PtrTy->getElementType());
18235     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
18236     return true;
18237   }
18238   case Intrinsic::arm_stlexd:
18239   case Intrinsic::arm_strexd:
18240     Info.opc = ISD::INTRINSIC_W_CHAIN;
18241     Info.memVT = MVT::i64;
18242     Info.ptrVal = I.getArgOperand(2);
18243     Info.offset = 0;
18244     Info.align = Align(8);
18245     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
18246     return true;
18247 
18248   case Intrinsic::arm_ldaexd:
18249   case Intrinsic::arm_ldrexd:
18250     Info.opc = ISD::INTRINSIC_W_CHAIN;
18251     Info.memVT = MVT::i64;
18252     Info.ptrVal = I.getArgOperand(0);
18253     Info.offset = 0;
18254     Info.align = Align(8);
18255     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
18256     return true;
18257 
18258   default:
18259     break;
18260   }
18261 
18262   return false;
18263 }
18264 
18265 /// Returns true if it is beneficial to convert a load of a constant
18266 /// to just the constant itself.
18267 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
18268                                                           Type *Ty) const {
18269   assert(Ty->isIntegerTy());
18270 
18271   unsigned Bits = Ty->getPrimitiveSizeInBits();
18272   if (Bits == 0 || Bits > 32)
18273     return false;
18274   return true;
18275 }
18276 
18277 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
18278                                                 unsigned Index) const {
18279   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
18280     return false;
18281 
18282   return (Index == 0 || Index == ResVT.getVectorNumElements());
18283 }
18284 
18285 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
18286                                         ARM_MB::MemBOpt Domain) const {
18287   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18288 
18289   // First, if the target has no DMB, see what fallback we can use.
18290   if (!Subtarget->hasDataBarrier()) {
18291     // Some ARMv6 cpus can support data barriers with an mcr instruction.
18292     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
18293     // here.
18294     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
18295       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
18296       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
18297                         Builder.getInt32(0), Builder.getInt32(7),
18298                         Builder.getInt32(10), Builder.getInt32(5)};
18299       return Builder.CreateCall(MCR, args);
18300     } else {
18301       // Instead of using barriers, atomic accesses on these subtargets use
18302       // libcalls.
18303       llvm_unreachable("makeDMB on a target so old that it has no barriers");
18304     }
18305   } else {
18306     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
18307     // Only a full system barrier exists in the M-class architectures.
18308     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
18309     Constant *CDomain = Builder.getInt32(Domain);
18310     return Builder.CreateCall(DMB, CDomain);
18311   }
18312 }
18313 
18314 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
18315 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
18316                                                  Instruction *Inst,
18317                                                  AtomicOrdering Ord) const {
18318   switch (Ord) {
18319   case AtomicOrdering::NotAtomic:
18320   case AtomicOrdering::Unordered:
18321     llvm_unreachable("Invalid fence: unordered/non-atomic");
18322   case AtomicOrdering::Monotonic:
18323   case AtomicOrdering::Acquire:
18324     return nullptr; // Nothing to do
18325   case AtomicOrdering::SequentiallyConsistent:
18326     if (!Inst->hasAtomicStore())
18327       return nullptr; // Nothing to do
18328     LLVM_FALLTHROUGH;
18329   case AtomicOrdering::Release:
18330   case AtomicOrdering::AcquireRelease:
18331     if (Subtarget->preferISHSTBarriers())
18332       return makeDMB(Builder, ARM_MB::ISHST);
18333     // FIXME: add a comment with a link to documentation justifying this.
18334     else
18335       return makeDMB(Builder, ARM_MB::ISH);
18336   }
18337   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
18338 }
18339 
18340 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
18341                                                   Instruction *Inst,
18342                                                   AtomicOrdering Ord) const {
18343   switch (Ord) {
18344   case AtomicOrdering::NotAtomic:
18345   case AtomicOrdering::Unordered:
18346     llvm_unreachable("Invalid fence: unordered/not-atomic");
18347   case AtomicOrdering::Monotonic:
18348   case AtomicOrdering::Release:
18349     return nullptr; // Nothing to do
18350   case AtomicOrdering::Acquire:
18351   case AtomicOrdering::AcquireRelease:
18352   case AtomicOrdering::SequentiallyConsistent:
18353     return makeDMB(Builder, ARM_MB::ISH);
18354   }
18355   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
18356 }
18357 
18358 // Loads and stores less than 64-bits are already atomic; ones above that
18359 // are doomed anyway, so defer to the default libcall and blame the OS when
18360 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
18361 // anything for those.
18362 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
18363   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
18364   return (Size == 64) && !Subtarget->isMClass();
18365 }
18366 
18367 // Loads and stores less than 64-bits are already atomic; ones above that
18368 // are doomed anyway, so defer to the default libcall and blame the OS when
18369 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
18370 // anything for those.
18371 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
18372 // guarantee, see DDI0406C ARM architecture reference manual,
18373 // sections A8.8.72-74 LDRD)
18374 TargetLowering::AtomicExpansionKind
18375 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
18376   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
18377   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
18378                                                   : AtomicExpansionKind::None;
18379 }
18380 
18381 // For the real atomic operations, we have ldrex/strex up to 32 bits,
18382 // and up to 64 bits on the non-M profiles
18383 TargetLowering::AtomicExpansionKind
18384 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
18385   if (AI->isFloatingPointOperation())
18386     return AtomicExpansionKind::CmpXChg;
18387 
18388   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
18389   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
18390   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
18391              ? AtomicExpansionKind::LLSC
18392              : AtomicExpansionKind::None;
18393 }
18394 
18395 TargetLowering::AtomicExpansionKind
18396 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
18397   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
18398   // implement cmpxchg without spilling. If the address being exchanged is also
18399   // on the stack and close enough to the spill slot, this can lead to a
18400   // situation where the monitor always gets cleared and the atomic operation
18401   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
18402   bool HasAtomicCmpXchg =
18403       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
18404   if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
18405     return AtomicExpansionKind::LLSC;
18406   return AtomicExpansionKind::None;
18407 }
18408 
18409 bool ARMTargetLowering::shouldInsertFencesForAtomic(
18410     const Instruction *I) const {
18411   return InsertFencesForAtomic;
18412 }
18413 
18414 // This has so far only been implemented for MachO.
18415 bool ARMTargetLowering::useLoadStackGuardNode() const {
18416   return Subtarget->isTargetMachO();
18417 }
18418 
18419 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
18420   if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18421     return TargetLowering::insertSSPDeclarations(M);
18422 
18423   // MSVC CRT has a global variable holding security cookie.
18424   M.getOrInsertGlobal("__security_cookie",
18425                       Type::getInt8PtrTy(M.getContext()));
18426 
18427   // MSVC CRT has a function to validate security cookie.
18428   FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
18429       "__security_check_cookie", Type::getVoidTy(M.getContext()),
18430       Type::getInt8PtrTy(M.getContext()));
18431   if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
18432     F->addAttribute(1, Attribute::AttrKind::InReg);
18433 }
18434 
18435 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
18436   // MSVC CRT has a global variable holding security cookie.
18437   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18438     return M.getGlobalVariable("__security_cookie");
18439   return TargetLowering::getSDagStackGuard(M);
18440 }
18441 
18442 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
18443   // MSVC CRT has a function to validate security cookie.
18444   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
18445     return M.getFunction("__security_check_cookie");
18446   return TargetLowering::getSSPStackGuardCheck(M);
18447 }
18448 
18449 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
18450                                                   unsigned &Cost) const {
18451   // If we do not have NEON, vector types are not natively supported.
18452   if (!Subtarget->hasNEON())
18453     return false;
18454 
18455   // Floating point values and vector values map to the same register file.
18456   // Therefore, although we could do a store extract of a vector type, this is
18457   // better to leave at float as we have more freedom in the addressing mode for
18458   // those.
18459   if (VectorTy->isFPOrFPVectorTy())
18460     return false;
18461 
18462   // If the index is unknown at compile time, this is very expensive to lower
18463   // and it is not possible to combine the store with the extract.
18464   if (!isa<ConstantInt>(Idx))
18465     return false;
18466 
18467   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
18468   unsigned BitWidth = VectorTy->getPrimitiveSizeInBits().getFixedSize();
18469   // We can do a store + vector extract on any vector that fits perfectly in a D
18470   // or Q register.
18471   if (BitWidth == 64 || BitWidth == 128) {
18472     Cost = 0;
18473     return true;
18474   }
18475   return false;
18476 }
18477 
18478 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
18479   return Subtarget->hasV6T2Ops();
18480 }
18481 
18482 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
18483   return Subtarget->hasV6T2Ops();
18484 }
18485 
18486 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
18487   return !Subtarget->hasMinSize() || Subtarget->isTargetWindows();
18488 }
18489 
18490 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
18491                                          AtomicOrdering Ord) const {
18492   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18493   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
18494   bool IsAcquire = isAcquireOrStronger(Ord);
18495 
18496   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
18497   // intrinsic must return {i32, i32} and we have to recombine them into a
18498   // single i64 here.
18499   if (ValTy->getPrimitiveSizeInBits() == 64) {
18500     Intrinsic::ID Int =
18501         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
18502     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
18503 
18504     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
18505     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
18506 
18507     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
18508     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
18509     if (!Subtarget->isLittle())
18510       std::swap (Lo, Hi);
18511     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
18512     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
18513     return Builder.CreateOr(
18514         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
18515   }
18516 
18517   Type *Tys[] = { Addr->getType() };
18518   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
18519   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
18520 
18521   return Builder.CreateTruncOrBitCast(
18522       Builder.CreateCall(Ldrex, Addr),
18523       cast<PointerType>(Addr->getType())->getElementType());
18524 }
18525 
18526 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
18527     IRBuilder<> &Builder) const {
18528   if (!Subtarget->hasV7Ops())
18529     return;
18530   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18531   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
18532 }
18533 
18534 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
18535                                                Value *Addr,
18536                                                AtomicOrdering Ord) const {
18537   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18538   bool IsRelease = isReleaseOrStronger(Ord);
18539 
18540   // Since the intrinsics must have legal type, the i64 intrinsics take two
18541   // parameters: "i32, i32". We must marshal Val into the appropriate form
18542   // before the call.
18543   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
18544     Intrinsic::ID Int =
18545         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
18546     Function *Strex = Intrinsic::getDeclaration(M, Int);
18547     Type *Int32Ty = Type::getInt32Ty(M->getContext());
18548 
18549     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
18550     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
18551     if (!Subtarget->isLittle())
18552       std::swap(Lo, Hi);
18553     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
18554     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
18555   }
18556 
18557   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
18558   Type *Tys[] = { Addr->getType() };
18559   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
18560 
18561   return Builder.CreateCall(
18562       Strex, {Builder.CreateZExtOrBitCast(
18563                   Val, Strex->getFunctionType()->getParamType(0)),
18564               Addr});
18565 }
18566 
18567 
18568 bool ARMTargetLowering::alignLoopsWithOptSize() const {
18569   return Subtarget->isMClass();
18570 }
18571 
18572 /// A helper function for determining the number of interleaved accesses we
18573 /// will generate when lowering accesses of the given type.
18574 unsigned
18575 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
18576                                              const DataLayout &DL) const {
18577   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
18578 }
18579 
18580 bool ARMTargetLowering::isLegalInterleavedAccessType(
18581     unsigned Factor, FixedVectorType *VecTy, const DataLayout &DL) const {
18582 
18583   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
18584   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
18585 
18586   if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
18587     return false;
18588 
18589   // Ensure the vector doesn't have f16 elements. Even though we could do an
18590   // i16 vldN, we can't hold the f16 vectors and will end up converting via
18591   // f32.
18592   if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
18593     return false;
18594   if (Subtarget->hasMVEIntegerOps() && Factor == 3)
18595     return false;
18596 
18597   // Ensure the number of vector elements is greater than 1.
18598   if (VecTy->getNumElements() < 2)
18599     return false;
18600 
18601   // Ensure the element type is legal.
18602   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
18603     return false;
18604 
18605   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
18606   // 128 will be split into multiple interleaved accesses.
18607   if (Subtarget->hasNEON() && VecSize == 64)
18608     return true;
18609   return VecSize % 128 == 0;
18610 }
18611 
18612 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
18613   if (Subtarget->hasNEON())
18614     return 4;
18615   if (Subtarget->hasMVEIntegerOps())
18616     return MVEMaxSupportedInterleaveFactor;
18617   return TargetLoweringBase::getMaxSupportedInterleaveFactor();
18618 }
18619 
18620 /// Lower an interleaved load into a vldN intrinsic.
18621 ///
18622 /// E.g. Lower an interleaved load (Factor = 2):
18623 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
18624 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
18625 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
18626 ///
18627 ///      Into:
18628 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
18629 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
18630 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
18631 bool ARMTargetLowering::lowerInterleavedLoad(
18632     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
18633     ArrayRef<unsigned> Indices, unsigned Factor) const {
18634   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
18635          "Invalid interleave factor");
18636   assert(!Shuffles.empty() && "Empty shufflevector input");
18637   assert(Shuffles.size() == Indices.size() &&
18638          "Unmatched number of shufflevectors and indices");
18639 
18640   auto *VecTy = cast<FixedVectorType>(Shuffles[0]->getType());
18641   Type *EltTy = VecTy->getElementType();
18642 
18643   const DataLayout &DL = LI->getModule()->getDataLayout();
18644 
18645   // Skip if we do not have NEON and skip illegal vector types. We can
18646   // "legalize" wide vector types into multiple interleaved accesses as long as
18647   // the vector types are divisible by 128.
18648   if (!isLegalInterleavedAccessType(Factor, VecTy, DL))
18649     return false;
18650 
18651   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
18652 
18653   // A pointer vector can not be the return type of the ldN intrinsics. Need to
18654   // load integer vectors first and then convert to pointer vectors.
18655   if (EltTy->isPointerTy())
18656     VecTy = FixedVectorType::get(DL.getIntPtrType(EltTy), VecTy);
18657 
18658   IRBuilder<> Builder(LI);
18659 
18660   // The base address of the load.
18661   Value *BaseAddr = LI->getPointerOperand();
18662 
18663   if (NumLoads > 1) {
18664     // If we're going to generate more than one load, reset the sub-vector type
18665     // to something legal.
18666     VecTy = FixedVectorType::get(VecTy->getElementType(),
18667                                  VecTy->getNumElements() / NumLoads);
18668 
18669     // We will compute the pointer operand of each load from the original base
18670     // address using GEPs. Cast the base address to a pointer to the scalar
18671     // element type.
18672     BaseAddr = Builder.CreateBitCast(
18673         BaseAddr,
18674         VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
18675   }
18676 
18677   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
18678 
18679   auto createLoadIntrinsic = [&](Value *BaseAddr) {
18680     if (Subtarget->hasNEON()) {
18681       Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
18682       Type *Tys[] = {VecTy, Int8Ptr};
18683       static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
18684                                                 Intrinsic::arm_neon_vld3,
18685                                                 Intrinsic::arm_neon_vld4};
18686       Function *VldnFunc =
18687           Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
18688 
18689       SmallVector<Value *, 2> Ops;
18690       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
18691       Ops.push_back(Builder.getInt32(LI->getAlignment()));
18692 
18693       return Builder.CreateCall(VldnFunc, Ops, "vldN");
18694     } else {
18695       assert((Factor == 2 || Factor == 4) &&
18696              "expected interleave factor of 2 or 4 for MVE");
18697       Intrinsic::ID LoadInts =
18698           Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
18699       Type *VecEltTy =
18700           VecTy->getElementType()->getPointerTo(LI->getPointerAddressSpace());
18701       Type *Tys[] = {VecTy, VecEltTy};
18702       Function *VldnFunc =
18703           Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys);
18704 
18705       SmallVector<Value *, 2> Ops;
18706       Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy));
18707       return Builder.CreateCall(VldnFunc, Ops, "vldN");
18708     }
18709   };
18710 
18711   // Holds sub-vectors extracted from the load intrinsic return values. The
18712   // sub-vectors are associated with the shufflevector instructions they will
18713   // replace.
18714   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
18715 
18716   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
18717     // If we're generating more than one load, compute the base address of
18718     // subsequent loads as an offset from the previous.
18719     if (LoadCount > 0)
18720       BaseAddr = Builder.CreateConstGEP1_32(VecTy->getElementType(), BaseAddr,
18721                                             VecTy->getNumElements() * Factor);
18722 
18723     CallInst *VldN = createLoadIntrinsic(BaseAddr);
18724 
18725     // Replace uses of each shufflevector with the corresponding vector loaded
18726     // by ldN.
18727     for (unsigned i = 0; i < Shuffles.size(); i++) {
18728       ShuffleVectorInst *SV = Shuffles[i];
18729       unsigned Index = Indices[i];
18730 
18731       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
18732 
18733       // Convert the integer vector to pointer vector if the element is pointer.
18734       if (EltTy->isPointerTy())
18735         SubVec = Builder.CreateIntToPtr(
18736             SubVec,
18737             FixedVectorType::get(SV->getType()->getElementType(), VecTy));
18738 
18739       SubVecs[SV].push_back(SubVec);
18740     }
18741   }
18742 
18743   // Replace uses of the shufflevector instructions with the sub-vectors
18744   // returned by the load intrinsic. If a shufflevector instruction is
18745   // associated with more than one sub-vector, those sub-vectors will be
18746   // concatenated into a single wide vector.
18747   for (ShuffleVectorInst *SVI : Shuffles) {
18748     auto &SubVec = SubVecs[SVI];
18749     auto *WideVec =
18750         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
18751     SVI->replaceAllUsesWith(WideVec);
18752   }
18753 
18754   return true;
18755 }
18756 
18757 /// Lower an interleaved store into a vstN intrinsic.
18758 ///
18759 /// E.g. Lower an interleaved store (Factor = 3):
18760 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
18761 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
18762 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
18763 ///
18764 ///      Into:
18765 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
18766 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
18767 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
18768 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
18769 ///
18770 /// Note that the new shufflevectors will be removed and we'll only generate one
18771 /// vst3 instruction in CodeGen.
18772 ///
18773 /// Example for a more general valid mask (Factor 3). Lower:
18774 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
18775 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
18776 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
18777 ///
18778 ///      Into:
18779 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
18780 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
18781 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
18782 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
18783 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
18784                                               ShuffleVectorInst *SVI,
18785                                               unsigned Factor) const {
18786   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
18787          "Invalid interleave factor");
18788 
18789   auto *VecTy = cast<FixedVectorType>(SVI->getType());
18790   assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
18791 
18792   unsigned LaneLen = VecTy->getNumElements() / Factor;
18793   Type *EltTy = VecTy->getElementType();
18794   auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
18795 
18796   const DataLayout &DL = SI->getModule()->getDataLayout();
18797 
18798   // Skip if we do not have NEON and skip illegal vector types. We can
18799   // "legalize" wide vector types into multiple interleaved accesses as long as
18800   // the vector types are divisible by 128.
18801   if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL))
18802     return false;
18803 
18804   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
18805 
18806   Value *Op0 = SVI->getOperand(0);
18807   Value *Op1 = SVI->getOperand(1);
18808   IRBuilder<> Builder(SI);
18809 
18810   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
18811   // vectors to integer vectors.
18812   if (EltTy->isPointerTy()) {
18813     Type *IntTy = DL.getIntPtrType(EltTy);
18814 
18815     // Convert to the corresponding integer vector.
18816     auto *IntVecTy =
18817         FixedVectorType::get(IntTy, cast<FixedVectorType>(Op0->getType()));
18818     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
18819     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
18820 
18821     SubVecTy = FixedVectorType::get(IntTy, LaneLen);
18822   }
18823 
18824   // The base address of the store.
18825   Value *BaseAddr = SI->getPointerOperand();
18826 
18827   if (NumStores > 1) {
18828     // If we're going to generate more than one store, reset the lane length
18829     // and sub-vector type to something legal.
18830     LaneLen /= NumStores;
18831     SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
18832 
18833     // We will compute the pointer operand of each store from the original base
18834     // address using GEPs. Cast the base address to a pointer to the scalar
18835     // element type.
18836     BaseAddr = Builder.CreateBitCast(
18837         BaseAddr,
18838         SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
18839   }
18840 
18841   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
18842 
18843   auto Mask = SVI->getShuffleMask();
18844 
18845   auto createStoreIntrinsic = [&](Value *BaseAddr,
18846                                   SmallVectorImpl<Value *> &Shuffles) {
18847     if (Subtarget->hasNEON()) {
18848       static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
18849                                                  Intrinsic::arm_neon_vst3,
18850                                                  Intrinsic::arm_neon_vst4};
18851       Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
18852       Type *Tys[] = {Int8Ptr, SubVecTy};
18853 
18854       Function *VstNFunc = Intrinsic::getDeclaration(
18855           SI->getModule(), StoreInts[Factor - 2], Tys);
18856 
18857       SmallVector<Value *, 6> Ops;
18858       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
18859       for (auto S : Shuffles)
18860         Ops.push_back(S);
18861       Ops.push_back(Builder.getInt32(SI->getAlignment()));
18862       Builder.CreateCall(VstNFunc, Ops);
18863     } else {
18864       assert((Factor == 2 || Factor == 4) &&
18865              "expected interleave factor of 2 or 4 for MVE");
18866       Intrinsic::ID StoreInts =
18867           Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
18868       Type *EltPtrTy = SubVecTy->getElementType()->getPointerTo(
18869           SI->getPointerAddressSpace());
18870       Type *Tys[] = {EltPtrTy, SubVecTy};
18871       Function *VstNFunc =
18872           Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys);
18873 
18874       SmallVector<Value *, 6> Ops;
18875       Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy));
18876       for (auto S : Shuffles)
18877         Ops.push_back(S);
18878       for (unsigned F = 0; F < Factor; F++) {
18879         Ops.push_back(Builder.getInt32(F));
18880         Builder.CreateCall(VstNFunc, Ops);
18881         Ops.pop_back();
18882       }
18883     }
18884   };
18885 
18886   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
18887     // If we generating more than one store, we compute the base address of
18888     // subsequent stores as an offset from the previous.
18889     if (StoreCount > 0)
18890       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
18891                                             BaseAddr, LaneLen * Factor);
18892 
18893     SmallVector<Value *, 4> Shuffles;
18894 
18895     // Split the shufflevector operands into sub vectors for the new vstN call.
18896     for (unsigned i = 0; i < Factor; i++) {
18897       unsigned IdxI = StoreCount * LaneLen * Factor + i;
18898       if (Mask[IdxI] >= 0) {
18899         Shuffles.push_back(Builder.CreateShuffleVector(
18900             Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
18901       } else {
18902         unsigned StartMask = 0;
18903         for (unsigned j = 1; j < LaneLen; j++) {
18904           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
18905           if (Mask[IdxJ * Factor + IdxI] >= 0) {
18906             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
18907             break;
18908           }
18909         }
18910         // Note: If all elements in a chunk are undefs, StartMask=0!
18911         // Note: Filling undef gaps with random elements is ok, since
18912         // those elements were being written anyway (with undefs).
18913         // In the case of all undefs we're defaulting to using elems from 0
18914         // Note: StartMask cannot be negative, it's checked in
18915         // isReInterleaveMask
18916         Shuffles.push_back(Builder.CreateShuffleVector(
18917             Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
18918       }
18919     }
18920 
18921     createStoreIntrinsic(BaseAddr, Shuffles);
18922   }
18923   return true;
18924 }
18925 
18926 enum HABaseType {
18927   HA_UNKNOWN = 0,
18928   HA_FLOAT,
18929   HA_DOUBLE,
18930   HA_VECT64,
18931   HA_VECT128
18932 };
18933 
18934 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
18935                                    uint64_t &Members) {
18936   if (auto *ST = dyn_cast<StructType>(Ty)) {
18937     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
18938       uint64_t SubMembers = 0;
18939       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
18940         return false;
18941       Members += SubMembers;
18942     }
18943   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
18944     uint64_t SubMembers = 0;
18945     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
18946       return false;
18947     Members += SubMembers * AT->getNumElements();
18948   } else if (Ty->isFloatTy()) {
18949     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
18950       return false;
18951     Members = 1;
18952     Base = HA_FLOAT;
18953   } else if (Ty->isDoubleTy()) {
18954     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
18955       return false;
18956     Members = 1;
18957     Base = HA_DOUBLE;
18958   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
18959     Members = 1;
18960     switch (Base) {
18961     case HA_FLOAT:
18962     case HA_DOUBLE:
18963       return false;
18964     case HA_VECT64:
18965       return VT->getPrimitiveSizeInBits().getFixedSize() == 64;
18966     case HA_VECT128:
18967       return VT->getPrimitiveSizeInBits().getFixedSize() == 128;
18968     case HA_UNKNOWN:
18969       switch (VT->getPrimitiveSizeInBits().getFixedSize()) {
18970       case 64:
18971         Base = HA_VECT64;
18972         return true;
18973       case 128:
18974         Base = HA_VECT128;
18975         return true;
18976       default:
18977         return false;
18978       }
18979     }
18980   }
18981 
18982   return (Members > 0 && Members <= 4);
18983 }
18984 
18985 /// Return the correct alignment for the current calling convention.
18986 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
18987                                                        DataLayout DL) const {
18988   const Align ABITypeAlign = DL.getABITypeAlign(ArgTy);
18989   if (!ArgTy->isVectorTy())
18990     return ABITypeAlign;
18991 
18992   // Avoid over-aligning vector parameters. It would require realigning the
18993   // stack and waste space for no real benefit.
18994   return std::min(ABITypeAlign, DL.getStackAlignment());
18995 }
18996 
18997 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
18998 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
18999 /// passing according to AAPCS rules.
19000 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
19001     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
19002   if (getEffectiveCallingConv(CallConv, isVarArg) !=
19003       CallingConv::ARM_AAPCS_VFP)
19004     return false;
19005 
19006   HABaseType Base = HA_UNKNOWN;
19007   uint64_t Members = 0;
19008   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
19009   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
19010 
19011   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
19012   return IsHA || IsIntArray;
19013 }
19014 
19015 Register ARMTargetLowering::getExceptionPointerRegister(
19016     const Constant *PersonalityFn) const {
19017   // Platforms which do not use SjLj EH may return values in these registers
19018   // via the personality function.
19019   return Subtarget->useSjLjEH() ? Register() : ARM::R0;
19020 }
19021 
19022 Register ARMTargetLowering::getExceptionSelectorRegister(
19023     const Constant *PersonalityFn) const {
19024   // Platforms which do not use SjLj EH may return values in these registers
19025   // via the personality function.
19026   return Subtarget->useSjLjEH() ? Register() : ARM::R1;
19027 }
19028 
19029 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
19030   // Update IsSplitCSR in ARMFunctionInfo.
19031   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
19032   AFI->setIsSplitCSR(true);
19033 }
19034 
19035 void ARMTargetLowering::insertCopiesSplitCSR(
19036     MachineBasicBlock *Entry,
19037     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
19038   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
19039   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
19040   if (!IStart)
19041     return;
19042 
19043   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19044   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
19045   MachineBasicBlock::iterator MBBI = Entry->begin();
19046   for (const MCPhysReg *I = IStart; *I; ++I) {
19047     const TargetRegisterClass *RC = nullptr;
19048     if (ARM::GPRRegClass.contains(*I))
19049       RC = &ARM::GPRRegClass;
19050     else if (ARM::DPRRegClass.contains(*I))
19051       RC = &ARM::DPRRegClass;
19052     else
19053       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
19054 
19055     Register NewVR = MRI->createVirtualRegister(RC);
19056     // Create copy from CSR to a virtual register.
19057     // FIXME: this currently does not emit CFI pseudo-instructions, it works
19058     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
19059     // nounwind. If we want to generalize this later, we may need to emit
19060     // CFI pseudo-instructions.
19061     assert(Entry->getParent()->getFunction().hasFnAttribute(
19062                Attribute::NoUnwind) &&
19063            "Function should be nounwind in insertCopiesSplitCSR!");
19064     Entry->addLiveIn(*I);
19065     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
19066         .addReg(*I);
19067 
19068     // Insert the copy-back instructions right before the terminator.
19069     for (auto *Exit : Exits)
19070       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
19071               TII->get(TargetOpcode::COPY), *I)
19072           .addReg(NewVR);
19073   }
19074 }
19075 
19076 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
19077   MF.getFrameInfo().computeMaxCallFrameSize(MF);
19078   TargetLoweringBase::finalizeLowering(MF);
19079 }
19080