]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/llvm/lib/Target/ARM/ARMISelLowering.cpp
Merge ^/vendor/llvm-project/release-10.x up to its last change (upstream
[FreeBSD/FreeBSD.git] / contrib / llvm-project / llvm / lib / Target / ARM / ARMISelLowering.cpp
1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that ARM uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "ARMISelLowering.h"
15 #include "ARMBaseInstrInfo.h"
16 #include "ARMBaseRegisterInfo.h"
17 #include "ARMCallingConv.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMMachineFunctionInfo.h"
20 #include "ARMPerfectShuffle.h"
21 #include "ARMRegisterInfo.h"
22 #include "ARMSelectionDAGInfo.h"
23 #include "ARMSubtarget.h"
24 #include "MCTargetDesc/ARMAddressingModes.h"
25 #include "MCTargetDesc/ARMBaseInfo.h"
26 #include "Utils/ARMBaseInfo.h"
27 #include "llvm/ADT/APFloat.h"
28 #include "llvm/ADT/APInt.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/BitVector.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/ADT/Twine.h"
41 #include "llvm/Analysis/VectorUtils.h"
42 #include "llvm/CodeGen/CallingConvLower.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/IntrinsicLowering.h"
45 #include "llvm/CodeGen/MachineBasicBlock.h"
46 #include "llvm/CodeGen/MachineConstantPool.h"
47 #include "llvm/CodeGen/MachineFrameInfo.h"
48 #include "llvm/CodeGen/MachineFunction.h"
49 #include "llvm/CodeGen/MachineInstr.h"
50 #include "llvm/CodeGen/MachineInstrBuilder.h"
51 #include "llvm/CodeGen/MachineJumpTableInfo.h"
52 #include "llvm/CodeGen/MachineMemOperand.h"
53 #include "llvm/CodeGen/MachineOperand.h"
54 #include "llvm/CodeGen/MachineRegisterInfo.h"
55 #include "llvm/CodeGen/RuntimeLibcalls.h"
56 #include "llvm/CodeGen/SelectionDAG.h"
57 #include "llvm/CodeGen/SelectionDAGNodes.h"
58 #include "llvm/CodeGen/TargetInstrInfo.h"
59 #include "llvm/CodeGen/TargetLowering.h"
60 #include "llvm/CodeGen/TargetOpcodes.h"
61 #include "llvm/CodeGen/TargetRegisterInfo.h"
62 #include "llvm/CodeGen/TargetSubtargetInfo.h"
63 #include "llvm/CodeGen/ValueTypes.h"
64 #include "llvm/IR/Attributes.h"
65 #include "llvm/IR/CallingConv.h"
66 #include "llvm/IR/Constant.h"
67 #include "llvm/IR/Constants.h"
68 #include "llvm/IR/DataLayout.h"
69 #include "llvm/IR/DebugLoc.h"
70 #include "llvm/IR/DerivedTypes.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GlobalAlias.h"
73 #include "llvm/IR/GlobalValue.h"
74 #include "llvm/IR/GlobalVariable.h"
75 #include "llvm/IR/IRBuilder.h"
76 #include "llvm/IR/InlineAsm.h"
77 #include "llvm/IR/Instruction.h"
78 #include "llvm/IR/Instructions.h"
79 #include "llvm/IR/IntrinsicInst.h"
80 #include "llvm/IR/Intrinsics.h"
81 #include "llvm/IR/IntrinsicsARM.h"
82 #include "llvm/IR/Module.h"
83 #include "llvm/IR/PatternMatch.h"
84 #include "llvm/IR/Type.h"
85 #include "llvm/IR/User.h"
86 #include "llvm/IR/Value.h"
87 #include "llvm/MC/MCInstrDesc.h"
88 #include "llvm/MC/MCInstrItineraries.h"
89 #include "llvm/MC/MCRegisterInfo.h"
90 #include "llvm/MC/MCSchedule.h"
91 #include "llvm/Support/AtomicOrdering.h"
92 #include "llvm/Support/BranchProbability.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CodeGen.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/ErrorHandling.h"
99 #include "llvm/Support/KnownBits.h"
100 #include "llvm/Support/MachineValueType.h"
101 #include "llvm/Support/MathExtras.h"
102 #include "llvm/Support/raw_ostream.h"
103 #include "llvm/Target/TargetMachine.h"
104 #include "llvm/Target/TargetOptions.h"
105 #include <algorithm>
106 #include <cassert>
107 #include <cstdint>
108 #include <cstdlib>
109 #include <iterator>
110 #include <limits>
111 #include <string>
112 #include <tuple>
113 #include <utility>
114 #include <vector>
115
116 using namespace llvm;
117 using namespace llvm::PatternMatch;
118
119 #define DEBUG_TYPE "arm-isel"
120
121 STATISTIC(NumTailCalls, "Number of tail calls");
122 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
123 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
124 STATISTIC(NumConstpoolPromoted,
125   "Number of constants with their storage promoted into constant pools");
126
127 static cl::opt<bool>
128 ARMInterworking("arm-interworking", cl::Hidden,
129   cl::desc("Enable / disable ARM interworking (for debugging only)"),
130   cl::init(true));
131
132 static cl::opt<bool> EnableConstpoolPromotion(
133     "arm-promote-constant", cl::Hidden,
134     cl::desc("Enable / disable promotion of unnamed_addr constants into "
135              "constant pools"),
136     cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
137 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
138     "arm-promote-constant-max-size", cl::Hidden,
139     cl::desc("Maximum size of constant to promote into a constant pool"),
140     cl::init(64));
141 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
142     "arm-promote-constant-max-total", cl::Hidden,
143     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
144     cl::init(128));
145
146 static cl::opt<unsigned>
147 MVEMaxSupportedInterleaveFactor("mve-max-interleave-factor", cl::Hidden,
148   cl::desc("Maximum interleave factor for MVE VLDn to generate."),
149   cl::init(2));
150
151 // The APCS parameter registers.
152 static const MCPhysReg GPRArgRegs[] = {
153   ARM::R0, ARM::R1, ARM::R2, ARM::R3
154 };
155
156 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
157                                        MVT PromotedBitwiseVT) {
158   if (VT != PromotedLdStVT) {
159     setOperationAction(ISD::LOAD, VT, Promote);
160     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
161
162     setOperationAction(ISD::STORE, VT, Promote);
163     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
164   }
165
166   MVT ElemTy = VT.getVectorElementType();
167   if (ElemTy != MVT::f64)
168     setOperationAction(ISD::SETCC, VT, Custom);
169   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
170   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
171   if (ElemTy == MVT::i32) {
172     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
173     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
174     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
175     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
176   } else {
177     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
178     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
179     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
180     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
181   }
182   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
183   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
184   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
185   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
186   setOperationAction(ISD::SELECT,            VT, Expand);
187   setOperationAction(ISD::SELECT_CC,         VT, Expand);
188   setOperationAction(ISD::VSELECT,           VT, Expand);
189   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
190   if (VT.isInteger()) {
191     setOperationAction(ISD::SHL, VT, Custom);
192     setOperationAction(ISD::SRA, VT, Custom);
193     setOperationAction(ISD::SRL, VT, Custom);
194   }
195
196   // Promote all bit-wise operations.
197   if (VT.isInteger() && VT != PromotedBitwiseVT) {
198     setOperationAction(ISD::AND, VT, Promote);
199     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
200     setOperationAction(ISD::OR,  VT, Promote);
201     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
202     setOperationAction(ISD::XOR, VT, Promote);
203     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
204   }
205
206   // Neon does not support vector divide/remainder operations.
207   setOperationAction(ISD::SDIV, VT, Expand);
208   setOperationAction(ISD::UDIV, VT, Expand);
209   setOperationAction(ISD::FDIV, VT, Expand);
210   setOperationAction(ISD::SREM, VT, Expand);
211   setOperationAction(ISD::UREM, VT, Expand);
212   setOperationAction(ISD::FREM, VT, Expand);
213
214   if (!VT.isFloatingPoint() &&
215       VT != MVT::v2i64 && VT != MVT::v1i64)
216     for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
217       setOperationAction(Opcode, VT, Legal);
218   if (!VT.isFloatingPoint())
219     for (auto Opcode : {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT})
220       setOperationAction(Opcode, VT, Legal);
221 }
222
223 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
224   addRegisterClass(VT, &ARM::DPRRegClass);
225   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
226 }
227
228 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
229   addRegisterClass(VT, &ARM::DPairRegClass);
230   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
231 }
232
233 void ARMTargetLowering::setAllExpand(MVT VT) {
234   for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
235     setOperationAction(Opc, VT, Expand);
236
237   // We support these really simple operations even on types where all
238   // the actual arithmetic has to be broken down into simpler
239   // operations or turned into library calls.
240   setOperationAction(ISD::BITCAST, VT, Legal);
241   setOperationAction(ISD::LOAD, VT, Legal);
242   setOperationAction(ISD::STORE, VT, Legal);
243   setOperationAction(ISD::UNDEF, VT, Legal);
244 }
245
246 void ARMTargetLowering::addAllExtLoads(const MVT From, const MVT To,
247                                        LegalizeAction Action) {
248   setLoadExtAction(ISD::EXTLOAD,  From, To, Action);
249   setLoadExtAction(ISD::ZEXTLOAD, From, To, Action);
250   setLoadExtAction(ISD::SEXTLOAD, From, To, Action);
251 }
252
253 void ARMTargetLowering::addMVEVectorTypes(bool HasMVEFP) {
254   const MVT IntTypes[] = { MVT::v16i8, MVT::v8i16, MVT::v4i32 };
255
256   for (auto VT : IntTypes) {
257     addRegisterClass(VT, &ARM::MQPRRegClass);
258     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
259     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
260     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
261     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
262     setOperationAction(ISD::SHL, VT, Custom);
263     setOperationAction(ISD::SRA, VT, Custom);
264     setOperationAction(ISD::SRL, VT, Custom);
265     setOperationAction(ISD::SMIN, VT, Legal);
266     setOperationAction(ISD::SMAX, VT, Legal);
267     setOperationAction(ISD::UMIN, VT, Legal);
268     setOperationAction(ISD::UMAX, VT, Legal);
269     setOperationAction(ISD::ABS, VT, Legal);
270     setOperationAction(ISD::SETCC, VT, Custom);
271     setOperationAction(ISD::MLOAD, VT, Custom);
272     setOperationAction(ISD::MSTORE, VT, Legal);
273     setOperationAction(ISD::CTLZ, VT, Legal);
274     setOperationAction(ISD::CTTZ, VT, Custom);
275     setOperationAction(ISD::BITREVERSE, VT, Legal);
276     setOperationAction(ISD::BSWAP, VT, Legal);
277     setOperationAction(ISD::SADDSAT, VT, Legal);
278     setOperationAction(ISD::UADDSAT, VT, Legal);
279     setOperationAction(ISD::SSUBSAT, VT, Legal);
280     setOperationAction(ISD::USUBSAT, VT, Legal);
281
282     // No native support for these.
283     setOperationAction(ISD::UDIV, VT, Expand);
284     setOperationAction(ISD::SDIV, VT, Expand);
285     setOperationAction(ISD::UREM, VT, Expand);
286     setOperationAction(ISD::SREM, VT, Expand);
287     setOperationAction(ISD::CTPOP, VT, Expand);
288
289     // Vector reductions
290     setOperationAction(ISD::VECREDUCE_ADD, VT, Legal);
291     setOperationAction(ISD::VECREDUCE_SMAX, VT, Legal);
292     setOperationAction(ISD::VECREDUCE_UMAX, VT, Legal);
293     setOperationAction(ISD::VECREDUCE_SMIN, VT, Legal);
294     setOperationAction(ISD::VECREDUCE_UMIN, VT, Legal);
295
296     if (!HasMVEFP) {
297       setOperationAction(ISD::SINT_TO_FP, VT, Expand);
298       setOperationAction(ISD::UINT_TO_FP, VT, Expand);
299       setOperationAction(ISD::FP_TO_SINT, VT, Expand);
300       setOperationAction(ISD::FP_TO_UINT, VT, Expand);
301     }
302
303     // Pre and Post inc are supported on loads and stores
304     for (unsigned im = (unsigned)ISD::PRE_INC;
305          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
306       setIndexedLoadAction(im, VT, Legal);
307       setIndexedStoreAction(im, VT, Legal);
308       setIndexedMaskedLoadAction(im, VT, Legal);
309       setIndexedMaskedStoreAction(im, VT, Legal);
310     }
311   }
312
313   const MVT FloatTypes[] = { MVT::v8f16, MVT::v4f32 };
314   for (auto VT : FloatTypes) {
315     addRegisterClass(VT, &ARM::MQPRRegClass);
316     if (!HasMVEFP)
317       setAllExpand(VT);
318
319     // These are legal or custom whether we have MVE.fp or not
320     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
321     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
322     setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getVectorElementType(), Custom);
323     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
324     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
325     setOperationAction(ISD::BUILD_VECTOR, VT.getVectorElementType(), Custom);
326     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Legal);
327     setOperationAction(ISD::SETCC, VT, Custom);
328     setOperationAction(ISD::MLOAD, VT, Custom);
329     setOperationAction(ISD::MSTORE, VT, Legal);
330
331     // Pre and Post inc are supported on loads and stores
332     for (unsigned im = (unsigned)ISD::PRE_INC;
333          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
334       setIndexedLoadAction(im, VT, Legal);
335       setIndexedStoreAction(im, VT, Legal);
336       setIndexedMaskedLoadAction(im, VT, Legal);
337       setIndexedMaskedStoreAction(im, VT, Legal);
338     }
339
340     if (HasMVEFP) {
341       setOperationAction(ISD::FMINNUM, VT, Legal);
342       setOperationAction(ISD::FMAXNUM, VT, Legal);
343       setOperationAction(ISD::FROUND, VT, Legal);
344
345       // No native support for these.
346       setOperationAction(ISD::FDIV, VT, Expand);
347       setOperationAction(ISD::FREM, VT, Expand);
348       setOperationAction(ISD::FSQRT, VT, Expand);
349       setOperationAction(ISD::FSIN, VT, Expand);
350       setOperationAction(ISD::FCOS, VT, Expand);
351       setOperationAction(ISD::FPOW, VT, Expand);
352       setOperationAction(ISD::FLOG, VT, Expand);
353       setOperationAction(ISD::FLOG2, VT, Expand);
354       setOperationAction(ISD::FLOG10, VT, Expand);
355       setOperationAction(ISD::FEXP, VT, Expand);
356       setOperationAction(ISD::FEXP2, VT, Expand);
357       setOperationAction(ISD::FNEARBYINT, VT, Expand);
358     }
359   }
360
361   // We 'support' these types up to bitcast/load/store level, regardless of
362   // MVE integer-only / float support. Only doing FP data processing on the FP
363   // vector types is inhibited at integer-only level.
364   const MVT LongTypes[] = { MVT::v2i64, MVT::v2f64 };
365   for (auto VT : LongTypes) {
366     addRegisterClass(VT, &ARM::MQPRRegClass);
367     setAllExpand(VT);
368     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
369     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
370     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
371   }
372   // We can do bitwise operations on v2i64 vectors
373   setOperationAction(ISD::AND, MVT::v2i64, Legal);
374   setOperationAction(ISD::OR, MVT::v2i64, Legal);
375   setOperationAction(ISD::XOR, MVT::v2i64, Legal);
376
377   // It is legal to extload from v4i8 to v4i16 or v4i32.
378   addAllExtLoads(MVT::v8i16, MVT::v8i8, Legal);
379   addAllExtLoads(MVT::v4i32, MVT::v4i16, Legal);
380   addAllExtLoads(MVT::v4i32, MVT::v4i8, Legal);
381
382   // It is legal to sign extend from v4i8/v4i16 to v4i32 or v8i8 to v8i16.
383   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
384   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
385   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
386   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i8,  Legal);
387   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v8i16, Legal);
388
389   // Some truncating stores are legal too.
390   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
391   setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
392   setTruncStoreAction(MVT::v8i16, MVT::v8i8,  Legal);
393
394   // Pre and Post inc on these are legal, given the correct extends
395   for (unsigned im = (unsigned)ISD::PRE_INC;
396        im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
397     for (auto VT : {MVT::v8i8, MVT::v4i8, MVT::v4i16}) {
398       setIndexedLoadAction(im, VT, Legal);
399       setIndexedStoreAction(im, VT, Legal);
400       setIndexedMaskedLoadAction(im, VT, Legal);
401       setIndexedMaskedStoreAction(im, VT, Legal);
402     }
403   }
404
405   // Predicate types
406   const MVT pTypes[] = {MVT::v16i1, MVT::v8i1, MVT::v4i1};
407   for (auto VT : pTypes) {
408     addRegisterClass(VT, &ARM::VCCRRegClass);
409     setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
410     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
411     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
412     setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
413     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
414     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
415     setOperationAction(ISD::SETCC, VT, Custom);
416     setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
417     setOperationAction(ISD::LOAD, VT, Custom);
418     setOperationAction(ISD::STORE, VT, Custom);
419   }
420 }
421
422 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
423                                      const ARMSubtarget &STI)
424     : TargetLowering(TM), Subtarget(&STI) {
425   RegInfo = Subtarget->getRegisterInfo();
426   Itins = Subtarget->getInstrItineraryData();
427
428   setBooleanContents(ZeroOrOneBooleanContent);
429   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
430
431   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
432       !Subtarget->isTargetWatchOS()) {
433     bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
434     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
435       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
436                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
437                                        : CallingConv::ARM_AAPCS);
438   }
439
440   if (Subtarget->isTargetMachO()) {
441     // Uses VFP for Thumb libfuncs if available.
442     if (Subtarget->isThumb() && Subtarget->hasVFP2Base() &&
443         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
444       static const struct {
445         const RTLIB::Libcall Op;
446         const char * const Name;
447         const ISD::CondCode Cond;
448       } LibraryCalls[] = {
449         // Single-precision floating-point arithmetic.
450         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
451         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
452         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
453         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
454
455         // Double-precision floating-point arithmetic.
456         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
457         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
458         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
459         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
460
461         // Single-precision comparisons.
462         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
463         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
464         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
465         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
466         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
467         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
468         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
469
470         // Double-precision comparisons.
471         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
472         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
473         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
474         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
475         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
476         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
477         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
478
479         // Floating-point to integer conversions.
480         // i64 conversions are done via library routines even when generating VFP
481         // instructions, so use the same ones.
482         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
483         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
484         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
485         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
486
487         // Conversions between floating types.
488         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
489         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
490
491         // Integer to floating-point conversions.
492         // i64 conversions are done via library routines even when generating VFP
493         // instructions, so use the same ones.
494         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
495         // e.g., __floatunsidf vs. __floatunssidfvfp.
496         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
497         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
498         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
499         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
500       };
501
502       for (const auto &LC : LibraryCalls) {
503         setLibcallName(LC.Op, LC.Name);
504         if (LC.Cond != ISD::SETCC_INVALID)
505           setCmpLibcallCC(LC.Op, LC.Cond);
506       }
507     }
508   }
509
510   // These libcalls are not available in 32-bit.
511   setLibcallName(RTLIB::SHL_I128, nullptr);
512   setLibcallName(RTLIB::SRL_I128, nullptr);
513   setLibcallName(RTLIB::SRA_I128, nullptr);
514
515   // RTLIB
516   if (Subtarget->isAAPCS_ABI() &&
517       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
518        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
519     static const struct {
520       const RTLIB::Libcall Op;
521       const char * const Name;
522       const CallingConv::ID CC;
523       const ISD::CondCode Cond;
524     } LibraryCalls[] = {
525       // Double-precision floating-point arithmetic helper functions
526       // RTABI chapter 4.1.2, Table 2
527       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
528       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
529       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
530       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
531
532       // Double-precision floating-point comparison helper functions
533       // RTABI chapter 4.1.2, Table 3
534       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
535       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
536       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
537       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
538       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
539       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
540       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
541
542       // Single-precision floating-point arithmetic helper functions
543       // RTABI chapter 4.1.2, Table 4
544       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
545       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
546       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
547       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
548
549       // Single-precision floating-point comparison helper functions
550       // RTABI chapter 4.1.2, Table 5
551       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
552       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
553       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
554       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
555       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
556       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
557       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
558
559       // Floating-point to integer conversions.
560       // RTABI chapter 4.1.2, Table 6
561       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
562       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
563       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
564       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
565       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
566       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
567       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
568       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
569
570       // Conversions between floating types.
571       // RTABI chapter 4.1.2, Table 7
572       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
573       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
574       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
575
576       // Integer to floating-point conversions.
577       // RTABI chapter 4.1.2, Table 8
578       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
579       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
580       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
581       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
582       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
583       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
584       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
585       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
586
587       // Long long helper functions
588       // RTABI chapter 4.2, Table 9
589       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
590       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
591       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
592       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
593
594       // Integer division functions
595       // RTABI chapter 4.3.1
596       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
597       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
598       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
599       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
600       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
601       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
602       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
603       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
604     };
605
606     for (const auto &LC : LibraryCalls) {
607       setLibcallName(LC.Op, LC.Name);
608       setLibcallCallingConv(LC.Op, LC.CC);
609       if (LC.Cond != ISD::SETCC_INVALID)
610         setCmpLibcallCC(LC.Op, LC.Cond);
611     }
612
613     // EABI dependent RTLIB
614     if (TM.Options.EABIVersion == EABI::EABI4 ||
615         TM.Options.EABIVersion == EABI::EABI5) {
616       static const struct {
617         const RTLIB::Libcall Op;
618         const char *const Name;
619         const CallingConv::ID CC;
620         const ISD::CondCode Cond;
621       } MemOpsLibraryCalls[] = {
622         // Memory operations
623         // RTABI chapter 4.3.4
624         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
625         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
626         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
627       };
628
629       for (const auto &LC : MemOpsLibraryCalls) {
630         setLibcallName(LC.Op, LC.Name);
631         setLibcallCallingConv(LC.Op, LC.CC);
632         if (LC.Cond != ISD::SETCC_INVALID)
633           setCmpLibcallCC(LC.Op, LC.Cond);
634       }
635     }
636   }
637
638   if (Subtarget->isTargetWindows()) {
639     static const struct {
640       const RTLIB::Libcall Op;
641       const char * const Name;
642       const CallingConv::ID CC;
643     } LibraryCalls[] = {
644       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
645       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
646       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
647       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
648       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
649       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
650       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
651       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
652     };
653
654     for (const auto &LC : LibraryCalls) {
655       setLibcallName(LC.Op, LC.Name);
656       setLibcallCallingConv(LC.Op, LC.CC);
657     }
658   }
659
660   // Use divmod compiler-rt calls for iOS 5.0 and later.
661   if (Subtarget->isTargetMachO() &&
662       !(Subtarget->isTargetIOS() &&
663         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
664     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
665     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
666   }
667
668   // The half <-> float conversion functions are always soft-float on
669   // non-watchos platforms, but are needed for some targets which use a
670   // hard-float calling convention by default.
671   if (!Subtarget->isTargetWatchABI()) {
672     if (Subtarget->isAAPCS_ABI()) {
673       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
674       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
675       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
676     } else {
677       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
678       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
679       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
680     }
681   }
682
683   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
684   // a __gnu_ prefix (which is the default).
685   if (Subtarget->isTargetAEABI()) {
686     static const struct {
687       const RTLIB::Libcall Op;
688       const char * const Name;
689       const CallingConv::ID CC;
690     } LibraryCalls[] = {
691       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
692       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
693       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
694     };
695
696     for (const auto &LC : LibraryCalls) {
697       setLibcallName(LC.Op, LC.Name);
698       setLibcallCallingConv(LC.Op, LC.CC);
699     }
700   }
701
702   if (Subtarget->isThumb1Only())
703     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
704   else
705     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
706
707   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only() &&
708       Subtarget->hasFPRegs()) {
709     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
710     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
711     if (!Subtarget->hasVFP2Base())
712       setAllExpand(MVT::f32);
713     if (!Subtarget->hasFP64())
714       setAllExpand(MVT::f64);
715   }
716
717   if (Subtarget->hasFullFP16()) {
718     addRegisterClass(MVT::f16, &ARM::HPRRegClass);
719     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
720     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
721     setOperationAction(ISD::BITCAST, MVT::f16, Custom);
722
723     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
724     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
725   }
726
727   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
728     for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
729       setTruncStoreAction(VT, InnerVT, Expand);
730       addAllExtLoads(VT, InnerVT, Expand);
731     }
732
733     setOperationAction(ISD::MULHS, VT, Expand);
734     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
735     setOperationAction(ISD::MULHU, VT, Expand);
736     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
737
738     setOperationAction(ISD::BSWAP, VT, Expand);
739   }
740
741   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
742   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
743
744   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
745   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
746
747   if (Subtarget->hasMVEIntegerOps())
748     addMVEVectorTypes(Subtarget->hasMVEFloatOps());
749
750   // Combine low-overhead loop intrinsics so that we can lower i1 types.
751   if (Subtarget->hasLOB()) {
752     setTargetDAGCombine(ISD::BRCOND);
753     setTargetDAGCombine(ISD::BR_CC);
754   }
755
756   if (Subtarget->hasNEON()) {
757     addDRTypeForNEON(MVT::v2f32);
758     addDRTypeForNEON(MVT::v8i8);
759     addDRTypeForNEON(MVT::v4i16);
760     addDRTypeForNEON(MVT::v2i32);
761     addDRTypeForNEON(MVT::v1i64);
762
763     addQRTypeForNEON(MVT::v4f32);
764     addQRTypeForNEON(MVT::v2f64);
765     addQRTypeForNEON(MVT::v16i8);
766     addQRTypeForNEON(MVT::v8i16);
767     addQRTypeForNEON(MVT::v4i32);
768     addQRTypeForNEON(MVT::v2i64);
769
770     if (Subtarget->hasFullFP16()) {
771       addQRTypeForNEON(MVT::v8f16);
772       addDRTypeForNEON(MVT::v4f16);
773     }
774   }
775
776   if (Subtarget->hasMVEIntegerOps() || Subtarget->hasNEON()) {
777     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
778     // none of Neon, MVE or VFP supports any arithmetic operations on it.
779     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
780     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
781     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
782     // FIXME: Code duplication: FDIV and FREM are expanded always, see
783     // ARMTargetLowering::addTypeForNEON method for details.
784     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
785     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
786     // FIXME: Create unittest.
787     // In another words, find a way when "copysign" appears in DAG with vector
788     // operands.
789     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
790     // FIXME: Code duplication: SETCC has custom operation action, see
791     // ARMTargetLowering::addTypeForNEON method for details.
792     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
793     // FIXME: Create unittest for FNEG and for FABS.
794     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
795     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
796     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
797     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
798     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
799     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
800     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
801     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
802     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
803     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
804     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
805     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
806     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
807     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
808     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
809     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
810     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
811     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
812   }
813
814   if (Subtarget->hasNEON()) {
815     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
816     // supported for v4f32.
817     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
818     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
819     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
820     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
821     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
822     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
823     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
824     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
825     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
826     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
827     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
828     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
829     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
830     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
831
832     // Mark v2f32 intrinsics.
833     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
834     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
835     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
836     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
837     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
838     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
839     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
840     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
841     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
842     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
843     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
844     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
845     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
846     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
847
848     // Neon does not support some operations on v1i64 and v2i64 types.
849     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
850     // Custom handling for some quad-vector types to detect VMULL.
851     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
852     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
853     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
854     // Custom handling for some vector types to avoid expensive expansions
855     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
856     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
857     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
858     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
859     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
860     // a destination type that is wider than the source, and nor does
861     // it have a FP_TO_[SU]INT instruction with a narrower destination than
862     // source.
863     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
864     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
865     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
866     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
867     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
868     setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
869     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
870     setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
871
872     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
873     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
874
875     // NEON does not have single instruction CTPOP for vectors with element
876     // types wider than 8-bits.  However, custom lowering can leverage the
877     // v8i8/v16i8 vcnt instruction.
878     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
879     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
880     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
881     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
882     setOperationAction(ISD::CTPOP,      MVT::v1i64, Custom);
883     setOperationAction(ISD::CTPOP,      MVT::v2i64, Custom);
884
885     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
886     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
887
888     // NEON does not have single instruction CTTZ for vectors.
889     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
890     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
891     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
892     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
893
894     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
895     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
896     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
897     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
898
899     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
900     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
901     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
902     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
903
904     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
905     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
906     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
907     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
908
909     // NEON only has FMA instructions as of VFP4.
910     if (!Subtarget->hasVFP4Base()) {
911       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
912       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
913     }
914
915     setTargetDAGCombine(ISD::INTRINSIC_VOID);
916     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
917     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
918     setTargetDAGCombine(ISD::SHL);
919     setTargetDAGCombine(ISD::SRL);
920     setTargetDAGCombine(ISD::SRA);
921     setTargetDAGCombine(ISD::FP_TO_SINT);
922     setTargetDAGCombine(ISD::FP_TO_UINT);
923     setTargetDAGCombine(ISD::FDIV);
924     setTargetDAGCombine(ISD::LOAD);
925
926     // It is legal to extload from v4i8 to v4i16 or v4i32.
927     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
928                    MVT::v2i32}) {
929       for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
930         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
931         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
932         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
933       }
934     }
935   }
936
937   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
938     setTargetDAGCombine(ISD::BUILD_VECTOR);
939     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
940     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
941     setTargetDAGCombine(ISD::STORE);
942     setTargetDAGCombine(ISD::SIGN_EXTEND);
943     setTargetDAGCombine(ISD::ZERO_EXTEND);
944     setTargetDAGCombine(ISD::ANY_EXTEND);
945   }
946
947   if (!Subtarget->hasFP64()) {
948     // When targeting a floating-point unit with only single-precision
949     // operations, f64 is legal for the few double-precision instructions which
950     // are present However, no double-precision operations other than moves,
951     // loads and stores are provided by the hardware.
952     setOperationAction(ISD::FADD,       MVT::f64, Expand);
953     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
954     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
955     setOperationAction(ISD::FMA,        MVT::f64, Expand);
956     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
957     setOperationAction(ISD::FREM,       MVT::f64, Expand);
958     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
959     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
960     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
961     setOperationAction(ISD::FABS,       MVT::f64, Expand);
962     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
963     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
964     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
965     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
966     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
967     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
968     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
969     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
970     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
971     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
972     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
973     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
974     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
975     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
976     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
977     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
978     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
979     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
980     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
981     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
982     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
983     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
984     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
985     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::f64, Custom);
986     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::f64, Custom);
987     setOperationAction(ISD::STRICT_FP_ROUND,   MVT::f32, Custom);
988   }
989
990   if (!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) {
991     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
992     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Custom);
993     if (Subtarget->hasFullFP16()) {
994       setOperationAction(ISD::FP_ROUND,  MVT::f16, Custom);
995       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
996     }
997   }
998
999   if (!Subtarget->hasFP16()) {
1000     setOperationAction(ISD::FP_EXTEND,  MVT::f32, Custom);
1001     setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Custom);
1002   }
1003
1004   computeRegisterProperties(Subtarget->getRegisterInfo());
1005
1006   // ARM does not have floating-point extending loads.
1007   for (MVT VT : MVT::fp_valuetypes()) {
1008     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
1009     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
1010   }
1011
1012   // ... or truncating stores
1013   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1014   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
1015   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
1016
1017   // ARM does not have i1 sign extending load.
1018   for (MVT VT : MVT::integer_valuetypes())
1019     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
1020
1021   // ARM supports all 4 flavors of integer indexed load / store.
1022   if (!Subtarget->isThumb1Only()) {
1023     for (unsigned im = (unsigned)ISD::PRE_INC;
1024          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
1025       setIndexedLoadAction(im,  MVT::i1,  Legal);
1026       setIndexedLoadAction(im,  MVT::i8,  Legal);
1027       setIndexedLoadAction(im,  MVT::i16, Legal);
1028       setIndexedLoadAction(im,  MVT::i32, Legal);
1029       setIndexedStoreAction(im, MVT::i1,  Legal);
1030       setIndexedStoreAction(im, MVT::i8,  Legal);
1031       setIndexedStoreAction(im, MVT::i16, Legal);
1032       setIndexedStoreAction(im, MVT::i32, Legal);
1033     }
1034   } else {
1035     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
1036     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
1037     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
1038   }
1039
1040   setOperationAction(ISD::SADDO, MVT::i32, Custom);
1041   setOperationAction(ISD::UADDO, MVT::i32, Custom);
1042   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1043   setOperationAction(ISD::USUBO, MVT::i32, Custom);
1044
1045   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
1046   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
1047   if (Subtarget->hasDSP()) {
1048     setOperationAction(ISD::SADDSAT, MVT::i8, Custom);
1049     setOperationAction(ISD::SSUBSAT, MVT::i8, Custom);
1050     setOperationAction(ISD::SADDSAT, MVT::i16, Custom);
1051     setOperationAction(ISD::SSUBSAT, MVT::i16, Custom);
1052   }
1053   if (Subtarget->hasBaseDSP()) {
1054     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
1055     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
1056   }
1057
1058   // i64 operation support.
1059   setOperationAction(ISD::MUL,     MVT::i64, Expand);
1060   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
1061   if (Subtarget->isThumb1Only()) {
1062     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1063     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1064   }
1065   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
1066       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
1067     setOperationAction(ISD::MULHS, MVT::i32, Expand);
1068
1069   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
1070   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
1071   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
1072   setOperationAction(ISD::SRL,       MVT::i64, Custom);
1073   setOperationAction(ISD::SRA,       MVT::i64, Custom);
1074   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1075   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
1076
1077   // MVE lowers 64 bit shifts to lsll and lsrl
1078   // assuming that ISD::SRL and SRA of i64 are already marked custom
1079   if (Subtarget->hasMVEIntegerOps())
1080     setOperationAction(ISD::SHL, MVT::i64, Custom);
1081
1082   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
1083   if (Subtarget->isThumb1Only()) {
1084     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1085     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1086     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1087   }
1088
1089   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
1090     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
1091
1092   // ARM does not have ROTL.
1093   setOperationAction(ISD::ROTL, MVT::i32, Expand);
1094   for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
1095     setOperationAction(ISD::ROTL, VT, Expand);
1096     setOperationAction(ISD::ROTR, VT, Expand);
1097   }
1098   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
1099   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1100   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only()) {
1101     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
1102     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
1103   }
1104
1105   // @llvm.readcyclecounter requires the Performance Monitors extension.
1106   // Default to the 0 expansion on unsupported platforms.
1107   // FIXME: Technically there are older ARM CPUs that have
1108   // implementation-specific ways of obtaining this information.
1109   if (Subtarget->hasPerfMon())
1110     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
1111
1112   // Only ARMv6 has BSWAP.
1113   if (!Subtarget->hasV6Ops())
1114     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1115
1116   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
1117                                         : Subtarget->hasDivideInARMMode();
1118   if (!hasDivide) {
1119     // These are expanded into libcalls if the cpu doesn't have HW divider.
1120     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
1121     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
1122   }
1123
1124   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
1125     setOperationAction(ISD::SDIV, MVT::i32, Custom);
1126     setOperationAction(ISD::UDIV, MVT::i32, Custom);
1127
1128     setOperationAction(ISD::SDIV, MVT::i64, Custom);
1129     setOperationAction(ISD::UDIV, MVT::i64, Custom);
1130   }
1131
1132   setOperationAction(ISD::SREM,  MVT::i32, Expand);
1133   setOperationAction(ISD::UREM,  MVT::i32, Expand);
1134
1135   // Register based DivRem for AEABI (RTABI 4.2)
1136   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
1137       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
1138       Subtarget->isTargetWindows()) {
1139     setOperationAction(ISD::SREM, MVT::i64, Custom);
1140     setOperationAction(ISD::UREM, MVT::i64, Custom);
1141     HasStandaloneRem = false;
1142
1143     if (Subtarget->isTargetWindows()) {
1144       const struct {
1145         const RTLIB::Libcall Op;
1146         const char * const Name;
1147         const CallingConv::ID CC;
1148       } LibraryCalls[] = {
1149         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
1150         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
1151         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
1152         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
1153
1154         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
1155         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
1156         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
1157         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
1158       };
1159
1160       for (const auto &LC : LibraryCalls) {
1161         setLibcallName(LC.Op, LC.Name);
1162         setLibcallCallingConv(LC.Op, LC.CC);
1163       }
1164     } else {
1165       const struct {
1166         const RTLIB::Libcall Op;
1167         const char * const Name;
1168         const CallingConv::ID CC;
1169       } LibraryCalls[] = {
1170         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1171         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1172         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
1173         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
1174
1175         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1176         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1177         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
1178         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
1179       };
1180
1181       for (const auto &LC : LibraryCalls) {
1182         setLibcallName(LC.Op, LC.Name);
1183         setLibcallCallingConv(LC.Op, LC.CC);
1184       }
1185     }
1186
1187     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1188     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1189     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1190     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1191   } else {
1192     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1193     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1194   }
1195
1196   if (Subtarget->getTargetTriple().isOSMSVCRT()) {
1197     // MSVCRT doesn't have powi; fall back to pow
1198     setLibcallName(RTLIB::POWI_F32, nullptr);
1199     setLibcallName(RTLIB::POWI_F64, nullptr);
1200   }
1201
1202   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
1203   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
1204   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1205   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1206
1207   setOperationAction(ISD::TRAP, MVT::Other, Legal);
1208   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
1209
1210   // Use the default implementation.
1211   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
1212   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
1213   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
1214   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
1215   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
1216   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
1217
1218   if (Subtarget->isTargetWindows())
1219     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1220   else
1221     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1222
1223   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1224   // the default expansion.
1225   InsertFencesForAtomic = false;
1226   if (Subtarget->hasAnyDataBarrier() &&
1227       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1228     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1229     // to ldrex/strex loops already.
1230     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
1231     if (!Subtarget->isThumb() || !Subtarget->isMClass())
1232       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
1233
1234     // On v8, we have particularly efficient implementations of atomic fences
1235     // if they can be combined with nearby atomic loads and stores.
1236     if (!Subtarget->hasAcquireRelease() ||
1237         getTargetMachine().getOptLevel() == 0) {
1238       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1239       InsertFencesForAtomic = true;
1240     }
1241   } else {
1242     // If there's anything we can use as a barrier, go through custom lowering
1243     // for ATOMIC_FENCE.
1244     // If target has DMB in thumb, Fences can be inserted.
1245     if (Subtarget->hasDataBarrier())
1246       InsertFencesForAtomic = true;
1247
1248     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1249                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1250
1251     // Set them all for expansion, which will force libcalls.
1252     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1253     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1254     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1255     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1256     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1257     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1258     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1259     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1260     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1261     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1262     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1263     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1264     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1265     // Unordered/Monotonic case.
1266     if (!InsertFencesForAtomic) {
1267       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1268       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1269     }
1270   }
1271
1272   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1273
1274   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1275   if (!Subtarget->hasV6Ops()) {
1276     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1277     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1278   }
1279   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1280
1281   if (!Subtarget->useSoftFloat() && Subtarget->hasFPRegs() &&
1282       !Subtarget->isThumb1Only()) {
1283     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1284     // iff target supports vfp2.
1285     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1286     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1287   }
1288
1289   // We want to custom lower some of our intrinsics.
1290   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1291   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1292   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1293   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1294   if (Subtarget->useSjLjEH())
1295     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1296
1297   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1298   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1299   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1300   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1301   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1302   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1303   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1304   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1305   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1306   if (Subtarget->hasFullFP16()) {
1307     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1308     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1309     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1310   }
1311
1312   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1313
1314   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1315   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1316   if (Subtarget->hasFullFP16())
1317       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1318   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1319   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1320   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1321
1322   // We don't support sin/cos/fmod/copysign/pow
1323   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1324   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1325   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1326   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1327   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1328   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1329   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1330   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1331   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2Base() &&
1332       !Subtarget->isThumb1Only()) {
1333     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1334     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1335   }
1336   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1337   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1338
1339   if (!Subtarget->hasVFP4Base()) {
1340     setOperationAction(ISD::FMA, MVT::f64, Expand);
1341     setOperationAction(ISD::FMA, MVT::f32, Expand);
1342   }
1343
1344   // Various VFP goodness
1345   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1346     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1347     if (!Subtarget->hasFPARMv8Base() || !Subtarget->hasFP64()) {
1348       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1349       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1350     }
1351
1352     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1353     if (!Subtarget->hasFP16()) {
1354       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1355       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1356     }
1357   }
1358
1359   // Use __sincos_stret if available.
1360   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1361       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1362     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1363     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1364   }
1365
1366   // FP-ARMv8 implements a lot of rounding-like FP operations.
1367   if (Subtarget->hasFPARMv8Base()) {
1368     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1369     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1370     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1371     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1372     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1373     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1374     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1375     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1376     if (Subtarget->hasNEON()) {
1377       setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1378       setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1379       setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1380       setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1381     }
1382
1383     if (Subtarget->hasFP64()) {
1384       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1385       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1386       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1387       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1388       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1389       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1390       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1391       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1392     }
1393   }
1394
1395   // FP16 often need to be promoted to call lib functions
1396   if (Subtarget->hasFullFP16()) {
1397     setOperationAction(ISD::FREM, MVT::f16, Promote);
1398     setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
1399     setOperationAction(ISD::FSIN, MVT::f16, Promote);
1400     setOperationAction(ISD::FCOS, MVT::f16, Promote);
1401     setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
1402     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
1403     setOperationAction(ISD::FPOW, MVT::f16, Promote);
1404     setOperationAction(ISD::FEXP, MVT::f16, Promote);
1405     setOperationAction(ISD::FEXP2, MVT::f16, Promote);
1406     setOperationAction(ISD::FLOG, MVT::f16, Promote);
1407     setOperationAction(ISD::FLOG10, MVT::f16, Promote);
1408     setOperationAction(ISD::FLOG2, MVT::f16, Promote);
1409
1410     setOperationAction(ISD::FROUND, MVT::f16, Legal);
1411   }
1412
1413   if (Subtarget->hasNEON()) {
1414     // vmin and vmax aren't available in a scalar form, so we use
1415     // a NEON instruction with an undef lane instead.
1416     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1417     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1418     setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1419     setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1420     setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1421     setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1422     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1423     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1424
1425     if (Subtarget->hasFullFP16()) {
1426       setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1427       setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1428       setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1429       setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1430
1431       setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1432       setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1433       setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1434       setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1435     }
1436   }
1437
1438   // We have target-specific dag combine patterns for the following nodes:
1439   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1440   setTargetDAGCombine(ISD::ADD);
1441   setTargetDAGCombine(ISD::SUB);
1442   setTargetDAGCombine(ISD::MUL);
1443   setTargetDAGCombine(ISD::AND);
1444   setTargetDAGCombine(ISD::OR);
1445   setTargetDAGCombine(ISD::XOR);
1446
1447   if (Subtarget->hasV6Ops())
1448     setTargetDAGCombine(ISD::SRL);
1449   if (Subtarget->isThumb1Only())
1450     setTargetDAGCombine(ISD::SHL);
1451
1452   setStackPointerRegisterToSaveRestore(ARM::SP);
1453
1454   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1455       !Subtarget->hasVFP2Base() || Subtarget->hasMinSize())
1456     setSchedulingPreference(Sched::RegPressure);
1457   else
1458     setSchedulingPreference(Sched::Hybrid);
1459
1460   //// temporary - rewrite interface to use type
1461   MaxStoresPerMemset = 8;
1462   MaxStoresPerMemsetOptSize = 4;
1463   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1464   MaxStoresPerMemcpyOptSize = 2;
1465   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1466   MaxStoresPerMemmoveOptSize = 2;
1467
1468   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1469   // are at least 4 bytes aligned.
1470   setMinStackArgumentAlignment(Align(4));
1471
1472   // Prefer likely predicted branches to selects on out-of-order cores.
1473   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1474
1475   setPrefLoopAlignment(Align(1ULL << Subtarget->getPrefLoopLogAlignment()));
1476
1477   setMinFunctionAlignment(Subtarget->isThumb() ? Align(2) : Align(4));
1478
1479   if (Subtarget->isThumb() || Subtarget->isThumb2())
1480     setTargetDAGCombine(ISD::ABS);
1481 }
1482
1483 bool ARMTargetLowering::useSoftFloat() const {
1484   return Subtarget->useSoftFloat();
1485 }
1486
1487 // FIXME: It might make sense to define the representative register class as the
1488 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1489 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1490 // SPR's representative would be DPR_VFP2. This should work well if register
1491 // pressure tracking were modified such that a register use would increment the
1492 // pressure of the register class's representative and all of it's super
1493 // classes' representatives transitively. We have not implemented this because
1494 // of the difficulty prior to coalescing of modeling operand register classes
1495 // due to the common occurrence of cross class copies and subregister insertions
1496 // and extractions.
1497 std::pair<const TargetRegisterClass *, uint8_t>
1498 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1499                                            MVT VT) const {
1500   const TargetRegisterClass *RRC = nullptr;
1501   uint8_t Cost = 1;
1502   switch (VT.SimpleTy) {
1503   default:
1504     return TargetLowering::findRepresentativeClass(TRI, VT);
1505   // Use DPR as representative register class for all floating point
1506   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1507   // the cost is 1 for both f32 and f64.
1508   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1509   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1510     RRC = &ARM::DPRRegClass;
1511     // When NEON is used for SP, only half of the register file is available
1512     // because operations that define both SP and DP results will be constrained
1513     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1514     // coalescing by double-counting the SP regs. See the FIXME above.
1515     if (Subtarget->useNEONForSinglePrecisionFP())
1516       Cost = 2;
1517     break;
1518   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1519   case MVT::v4f32: case MVT::v2f64:
1520     RRC = &ARM::DPRRegClass;
1521     Cost = 2;
1522     break;
1523   case MVT::v4i64:
1524     RRC = &ARM::DPRRegClass;
1525     Cost = 4;
1526     break;
1527   case MVT::v8i64:
1528     RRC = &ARM::DPRRegClass;
1529     Cost = 8;
1530     break;
1531   }
1532   return std::make_pair(RRC, Cost);
1533 }
1534
1535 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1536   switch ((ARMISD::NodeType)Opcode) {
1537   case ARMISD::FIRST_NUMBER:  break;
1538   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1539   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1540   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1541   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1542   case ARMISD::CALL:          return "ARMISD::CALL";
1543   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1544   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1545   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1546   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1547   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1548   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1549   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1550   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1551   case ARMISD::CMP:           return "ARMISD::CMP";
1552   case ARMISD::CMN:           return "ARMISD::CMN";
1553   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1554   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1555   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1556   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1557   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1558
1559   case ARMISD::CMOV:          return "ARMISD::CMOV";
1560   case ARMISD::SUBS:          return "ARMISD::SUBS";
1561
1562   case ARMISD::SSAT:          return "ARMISD::SSAT";
1563   case ARMISD::USAT:          return "ARMISD::USAT";
1564
1565   case ARMISD::ASRL:          return "ARMISD::ASRL";
1566   case ARMISD::LSRL:          return "ARMISD::LSRL";
1567   case ARMISD::LSLL:          return "ARMISD::LSLL";
1568
1569   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1570   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1571   case ARMISD::RRX:           return "ARMISD::RRX";
1572
1573   case ARMISD::ADDC:          return "ARMISD::ADDC";
1574   case ARMISD::ADDE:          return "ARMISD::ADDE";
1575   case ARMISD::SUBC:          return "ARMISD::SUBC";
1576   case ARMISD::SUBE:          return "ARMISD::SUBE";
1577   case ARMISD::LSLS:          return "ARMISD::LSLS";
1578
1579   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1580   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1581   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1582   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1583   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
1584
1585   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1586   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1587   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1588
1589   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1590
1591   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1592
1593   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1594
1595   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1596
1597   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1598
1599   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1600   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1601
1602   case ARMISD::PREDICATE_CAST: return "ARMISD::PREDICATE_CAST";
1603   case ARMISD::VCMP:          return "ARMISD::VCMP";
1604   case ARMISD::VCMPZ:         return "ARMISD::VCMPZ";
1605   case ARMISD::VTST:          return "ARMISD::VTST";
1606
1607   case ARMISD::VSHLs:         return "ARMISD::VSHLs";
1608   case ARMISD::VSHLu:         return "ARMISD::VSHLu";
1609   case ARMISD::VSHLIMM:       return "ARMISD::VSHLIMM";
1610   case ARMISD::VSHRsIMM:      return "ARMISD::VSHRsIMM";
1611   case ARMISD::VSHRuIMM:      return "ARMISD::VSHRuIMM";
1612   case ARMISD::VRSHRsIMM:     return "ARMISD::VRSHRsIMM";
1613   case ARMISD::VRSHRuIMM:     return "ARMISD::VRSHRuIMM";
1614   case ARMISD::VRSHRNIMM:     return "ARMISD::VRSHRNIMM";
1615   case ARMISD::VQSHLsIMM:     return "ARMISD::VQSHLsIMM";
1616   case ARMISD::VQSHLuIMM:     return "ARMISD::VQSHLuIMM";
1617   case ARMISD::VQSHLsuIMM:    return "ARMISD::VQSHLsuIMM";
1618   case ARMISD::VQSHRNsIMM:    return "ARMISD::VQSHRNsIMM";
1619   case ARMISD::VQSHRNuIMM:    return "ARMISD::VQSHRNuIMM";
1620   case ARMISD::VQSHRNsuIMM:   return "ARMISD::VQSHRNsuIMM";
1621   case ARMISD::VQRSHRNsIMM:   return "ARMISD::VQRSHRNsIMM";
1622   case ARMISD::VQRSHRNuIMM:   return "ARMISD::VQRSHRNuIMM";
1623   case ARMISD::VQRSHRNsuIMM:  return "ARMISD::VQRSHRNsuIMM";
1624   case ARMISD::VSLIIMM:       return "ARMISD::VSLIIMM";
1625   case ARMISD::VSRIIMM:       return "ARMISD::VSRIIMM";
1626   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1627   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1628   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1629   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1630   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1631   case ARMISD::VDUP:          return "ARMISD::VDUP";
1632   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1633   case ARMISD::VEXT:          return "ARMISD::VEXT";
1634   case ARMISD::VREV64:        return "ARMISD::VREV64";
1635   case ARMISD::VREV32:        return "ARMISD::VREV32";
1636   case ARMISD::VREV16:        return "ARMISD::VREV16";
1637   case ARMISD::VZIP:          return "ARMISD::VZIP";
1638   case ARMISD::VUZP:          return "ARMISD::VUZP";
1639   case ARMISD::VTRN:          return "ARMISD::VTRN";
1640   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1641   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1642   case ARMISD::VMOVN:         return "ARMISD::VMOVN";
1643   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1644   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1645   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1646   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1647   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1648   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1649   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1650   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1651   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1652   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1653   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1654   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1655   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1656   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1657   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1658   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1659   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1660   case ARMISD::QADD16b:       return "ARMISD::QADD16b";
1661   case ARMISD::QSUB16b:       return "ARMISD::QSUB16b";
1662   case ARMISD::QADD8b:        return "ARMISD::QADD8b";
1663   case ARMISD::QSUB8b:        return "ARMISD::QSUB8b";
1664   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1665   case ARMISD::BFI:           return "ARMISD::BFI";
1666   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1667   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1668   case ARMISD::VBSL:          return "ARMISD::VBSL";
1669   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1670   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1671   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1672   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1673   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1674   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1675   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1676   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1677   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1678   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1679   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1680   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1681   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1682   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1683   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1684   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1685   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1686   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1687   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1688   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1689   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1690   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1691   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1692   case ARMISD::WLS:           return "ARMISD::WLS";
1693   case ARMISD::LE:            return "ARMISD::LE";
1694   case ARMISD::LOOP_DEC:      return "ARMISD::LOOP_DEC";
1695   case ARMISD::CSINV:         return "ARMISD::CSINV";
1696   case ARMISD::CSNEG:         return "ARMISD::CSNEG";
1697   case ARMISD::CSINC:         return "ARMISD::CSINC";
1698   }
1699   return nullptr;
1700 }
1701
1702 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1703                                           EVT VT) const {
1704   if (!VT.isVector())
1705     return getPointerTy(DL);
1706
1707   // MVE has a predicate register.
1708   if (Subtarget->hasMVEIntegerOps() &&
1709       (VT == MVT::v4i32 || VT == MVT::v8i16 || VT == MVT::v16i8))
1710     return MVT::getVectorVT(MVT::i1, VT.getVectorElementCount());
1711   return VT.changeVectorElementTypeToInteger();
1712 }
1713
1714 /// getRegClassFor - Return the register class that should be used for the
1715 /// specified value type.
1716 const TargetRegisterClass *
1717 ARMTargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
1718   (void)isDivergent;
1719   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1720   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1721   // load / store 4 to 8 consecutive NEON D registers, or 2 to 4 consecutive
1722   // MVE Q registers.
1723   if (Subtarget->hasNEON() || Subtarget->hasMVEIntegerOps()) {
1724     if (VT == MVT::v4i64)
1725       return &ARM::QQPRRegClass;
1726     if (VT == MVT::v8i64)
1727       return &ARM::QQQQPRRegClass;
1728   }
1729   return TargetLowering::getRegClassFor(VT);
1730 }
1731
1732 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1733 // source/dest is aligned and the copy size is large enough. We therefore want
1734 // to align such objects passed to memory intrinsics.
1735 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1736                                                unsigned &PrefAlign) const {
1737   if (!isa<MemIntrinsic>(CI))
1738     return false;
1739   MinSize = 8;
1740   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1741   // cycle faster than 4-byte aligned LDM.
1742   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1743   return true;
1744 }
1745
1746 // Create a fast isel object.
1747 FastISel *
1748 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1749                                   const TargetLibraryInfo *libInfo) const {
1750   return ARM::createFastISel(funcInfo, libInfo);
1751 }
1752
1753 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1754   unsigned NumVals = N->getNumValues();
1755   if (!NumVals)
1756     return Sched::RegPressure;
1757
1758   for (unsigned i = 0; i != NumVals; ++i) {
1759     EVT VT = N->getValueType(i);
1760     if (VT == MVT::Glue || VT == MVT::Other)
1761       continue;
1762     if (VT.isFloatingPoint() || VT.isVector())
1763       return Sched::ILP;
1764   }
1765
1766   if (!N->isMachineOpcode())
1767     return Sched::RegPressure;
1768
1769   // Load are scheduled for latency even if there instruction itinerary
1770   // is not available.
1771   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1772   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1773
1774   if (MCID.getNumDefs() == 0)
1775     return Sched::RegPressure;
1776   if (!Itins->isEmpty() &&
1777       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1778     return Sched::ILP;
1779
1780   return Sched::RegPressure;
1781 }
1782
1783 //===----------------------------------------------------------------------===//
1784 // Lowering Code
1785 //===----------------------------------------------------------------------===//
1786
1787 static bool isSRL16(const SDValue &Op) {
1788   if (Op.getOpcode() != ISD::SRL)
1789     return false;
1790   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1791     return Const->getZExtValue() == 16;
1792   return false;
1793 }
1794
1795 static bool isSRA16(const SDValue &Op) {
1796   if (Op.getOpcode() != ISD::SRA)
1797     return false;
1798   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1799     return Const->getZExtValue() == 16;
1800   return false;
1801 }
1802
1803 static bool isSHL16(const SDValue &Op) {
1804   if (Op.getOpcode() != ISD::SHL)
1805     return false;
1806   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1807     return Const->getZExtValue() == 16;
1808   return false;
1809 }
1810
1811 // Check for a signed 16-bit value. We special case SRA because it makes it
1812 // more simple when also looking for SRAs that aren't sign extending a
1813 // smaller value. Without the check, we'd need to take extra care with
1814 // checking order for some operations.
1815 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1816   if (isSRA16(Op))
1817     return isSHL16(Op.getOperand(0));
1818   return DAG.ComputeNumSignBits(Op) == 17;
1819 }
1820
1821 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1822 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1823   switch (CC) {
1824   default: llvm_unreachable("Unknown condition code!");
1825   case ISD::SETNE:  return ARMCC::NE;
1826   case ISD::SETEQ:  return ARMCC::EQ;
1827   case ISD::SETGT:  return ARMCC::GT;
1828   case ISD::SETGE:  return ARMCC::GE;
1829   case ISD::SETLT:  return ARMCC::LT;
1830   case ISD::SETLE:  return ARMCC::LE;
1831   case ISD::SETUGT: return ARMCC::HI;
1832   case ISD::SETUGE: return ARMCC::HS;
1833   case ISD::SETULT: return ARMCC::LO;
1834   case ISD::SETULE: return ARMCC::LS;
1835   }
1836 }
1837
1838 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1839 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1840                         ARMCC::CondCodes &CondCode2) {
1841   CondCode2 = ARMCC::AL;
1842   switch (CC) {
1843   default: llvm_unreachable("Unknown FP condition!");
1844   case ISD::SETEQ:
1845   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1846   case ISD::SETGT:
1847   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1848   case ISD::SETGE:
1849   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1850   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1851   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1852   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1853   case ISD::SETO:   CondCode = ARMCC::VC; break;
1854   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1855   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1856   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1857   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1858   case ISD::SETLT:
1859   case ISD::SETULT: CondCode = ARMCC::LT; break;
1860   case ISD::SETLE:
1861   case ISD::SETULE: CondCode = ARMCC::LE; break;
1862   case ISD::SETNE:
1863   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1864   }
1865 }
1866
1867 //===----------------------------------------------------------------------===//
1868 //                      Calling Convention Implementation
1869 //===----------------------------------------------------------------------===//
1870
1871 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1872 /// account presence of floating point hardware and calling convention
1873 /// limitations, such as support for variadic functions.
1874 CallingConv::ID
1875 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1876                                            bool isVarArg) const {
1877   switch (CC) {
1878   default:
1879     report_fatal_error("Unsupported calling convention");
1880   case CallingConv::ARM_AAPCS:
1881   case CallingConv::ARM_APCS:
1882   case CallingConv::GHC:
1883   case CallingConv::CFGuard_Check:
1884     return CC;
1885   case CallingConv::PreserveMost:
1886     return CallingConv::PreserveMost;
1887   case CallingConv::ARM_AAPCS_VFP:
1888   case CallingConv::Swift:
1889     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1890   case CallingConv::C:
1891     if (!Subtarget->isAAPCS_ABI())
1892       return CallingConv::ARM_APCS;
1893     else if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() &&
1894              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1895              !isVarArg)
1896       return CallingConv::ARM_AAPCS_VFP;
1897     else
1898       return CallingConv::ARM_AAPCS;
1899   case CallingConv::Fast:
1900   case CallingConv::CXX_FAST_TLS:
1901     if (!Subtarget->isAAPCS_ABI()) {
1902       if (Subtarget->hasVFP2Base() && !Subtarget->isThumb1Only() && !isVarArg)
1903         return CallingConv::Fast;
1904       return CallingConv::ARM_APCS;
1905     } else if (Subtarget->hasVFP2Base() &&
1906                !Subtarget->isThumb1Only() && !isVarArg)
1907       return CallingConv::ARM_AAPCS_VFP;
1908     else
1909       return CallingConv::ARM_AAPCS;
1910   }
1911 }
1912
1913 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1914                                                  bool isVarArg) const {
1915   return CCAssignFnForNode(CC, false, isVarArg);
1916 }
1917
1918 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1919                                                    bool isVarArg) const {
1920   return CCAssignFnForNode(CC, true, isVarArg);
1921 }
1922
1923 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1924 /// CallingConvention.
1925 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1926                                                  bool Return,
1927                                                  bool isVarArg) const {
1928   switch (getEffectiveCallingConv(CC, isVarArg)) {
1929   default:
1930     report_fatal_error("Unsupported calling convention");
1931   case CallingConv::ARM_APCS:
1932     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1933   case CallingConv::ARM_AAPCS:
1934     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1935   case CallingConv::ARM_AAPCS_VFP:
1936     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1937   case CallingConv::Fast:
1938     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1939   case CallingConv::GHC:
1940     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1941   case CallingConv::PreserveMost:
1942     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1943   case CallingConv::CFGuard_Check:
1944     return (Return ? RetCC_ARM_AAPCS : CC_ARM_Win32_CFGuard_Check);
1945   }
1946 }
1947
1948 /// LowerCallResult - Lower the result values of a call into the
1949 /// appropriate copies out of appropriate physical registers.
1950 SDValue ARMTargetLowering::LowerCallResult(
1951     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1952     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1953     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1954     SDValue ThisVal) const {
1955   // Assign locations to each value returned by this call.
1956   SmallVector<CCValAssign, 16> RVLocs;
1957   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1958                  *DAG.getContext());
1959   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1960
1961   // Copy all of the result registers out of their specified physreg.
1962   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1963     CCValAssign VA = RVLocs[i];
1964
1965     // Pass 'this' value directly from the argument to return value, to avoid
1966     // reg unit interference
1967     if (i == 0 && isThisReturn) {
1968       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1969              "unexpected return calling convention register assignment");
1970       InVals.push_back(ThisVal);
1971       continue;
1972     }
1973
1974     SDValue Val;
1975     if (VA.needsCustom()) {
1976       // Handle f64 or half of a v2f64.
1977       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1978                                       InFlag);
1979       Chain = Lo.getValue(1);
1980       InFlag = Lo.getValue(2);
1981       VA = RVLocs[++i]; // skip ahead to next loc
1982       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1983                                       InFlag);
1984       Chain = Hi.getValue(1);
1985       InFlag = Hi.getValue(2);
1986       if (!Subtarget->isLittle())
1987         std::swap (Lo, Hi);
1988       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1989
1990       if (VA.getLocVT() == MVT::v2f64) {
1991         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1992         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1993                           DAG.getConstant(0, dl, MVT::i32));
1994
1995         VA = RVLocs[++i]; // skip ahead to next loc
1996         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1997         Chain = Lo.getValue(1);
1998         InFlag = Lo.getValue(2);
1999         VA = RVLocs[++i]; // skip ahead to next loc
2000         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
2001         Chain = Hi.getValue(1);
2002         InFlag = Hi.getValue(2);
2003         if (!Subtarget->isLittle())
2004           std::swap (Lo, Hi);
2005         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
2006         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
2007                           DAG.getConstant(1, dl, MVT::i32));
2008       }
2009     } else {
2010       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
2011                                InFlag);
2012       Chain = Val.getValue(1);
2013       InFlag = Val.getValue(2);
2014     }
2015
2016     switch (VA.getLocInfo()) {
2017     default: llvm_unreachable("Unknown loc info!");
2018     case CCValAssign::Full: break;
2019     case CCValAssign::BCvt:
2020       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
2021       break;
2022     }
2023
2024     InVals.push_back(Val);
2025   }
2026
2027   return Chain;
2028 }
2029
2030 /// LowerMemOpCallTo - Store the argument to the stack.
2031 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
2032                                             SDValue Arg, const SDLoc &dl,
2033                                             SelectionDAG &DAG,
2034                                             const CCValAssign &VA,
2035                                             ISD::ArgFlagsTy Flags) const {
2036   unsigned LocMemOffset = VA.getLocMemOffset();
2037   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2038   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2039                        StackPtr, PtrOff);
2040   return DAG.getStore(
2041       Chain, dl, Arg, PtrOff,
2042       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
2043 }
2044
2045 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
2046                                          SDValue Chain, SDValue &Arg,
2047                                          RegsToPassVector &RegsToPass,
2048                                          CCValAssign &VA, CCValAssign &NextVA,
2049                                          SDValue &StackPtr,
2050                                          SmallVectorImpl<SDValue> &MemOpChains,
2051                                          ISD::ArgFlagsTy Flags) const {
2052   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2053                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
2054   unsigned id = Subtarget->isLittle() ? 0 : 1;
2055   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
2056
2057   if (NextVA.isRegLoc())
2058     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
2059   else {
2060     assert(NextVA.isMemLoc());
2061     if (!StackPtr.getNode())
2062       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
2063                                     getPointerTy(DAG.getDataLayout()));
2064
2065     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
2066                                            dl, DAG, NextVA,
2067                                            Flags));
2068   }
2069 }
2070
2071 /// LowerCall - Lowering a call into a callseq_start <-
2072 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
2073 /// nodes.
2074 SDValue
2075 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2076                              SmallVectorImpl<SDValue> &InVals) const {
2077   SelectionDAG &DAG                     = CLI.DAG;
2078   SDLoc &dl                             = CLI.DL;
2079   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2080   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2081   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2082   SDValue Chain                         = CLI.Chain;
2083   SDValue Callee                        = CLI.Callee;
2084   bool &isTailCall                      = CLI.IsTailCall;
2085   CallingConv::ID CallConv              = CLI.CallConv;
2086   bool doesNotRet                       = CLI.DoesNotReturn;
2087   bool isVarArg                         = CLI.IsVarArg;
2088
2089   MachineFunction &MF = DAG.getMachineFunction();
2090   MachineFunction::CallSiteInfo CSInfo;
2091   bool isStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2092   bool isThisReturn = false;
2093   bool PreferIndirect = false;
2094
2095   // Disable tail calls if they're not supported.
2096   if (!Subtarget->supportsTailCall())
2097     isTailCall = false;
2098
2099   if (isa<GlobalAddressSDNode>(Callee)) {
2100     // If we're optimizing for minimum size and the function is called three or
2101     // more times in this block, we can improve codesize by calling indirectly
2102     // as BLXr has a 16-bit encoding.
2103     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2104     if (CLI.CS) {
2105       auto *BB = CLI.CS.getParent();
2106       PreferIndirect = Subtarget->isThumb() && Subtarget->hasMinSize() &&
2107                        count_if(GV->users(), [&BB](const User *U) {
2108                          return isa<Instruction>(U) &&
2109                                 cast<Instruction>(U)->getParent() == BB;
2110                        }) > 2;
2111     }
2112   }
2113   if (isTailCall) {
2114     // Check if it's really possible to do a tail call.
2115     isTailCall = IsEligibleForTailCallOptimization(
2116         Callee, CallConv, isVarArg, isStructRet,
2117         MF.getFunction().hasStructRetAttr(), Outs, OutVals, Ins, DAG,
2118         PreferIndirect);
2119     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
2120       report_fatal_error("failed to perform tail call elimination on a call "
2121                          "site marked musttail");
2122     // We don't support GuaranteedTailCallOpt for ARM, only automatically
2123     // detected sibcalls.
2124     if (isTailCall)
2125       ++NumTailCalls;
2126   }
2127
2128   // Analyze operands of the call, assigning locations to each operand.
2129   SmallVector<CCValAssign, 16> ArgLocs;
2130   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2131                  *DAG.getContext());
2132   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
2133
2134   // Get a count of how many bytes are to be pushed on the stack.
2135   unsigned NumBytes = CCInfo.getNextStackOffset();
2136
2137   if (isTailCall) {
2138     // For tail calls, memory operands are available in our caller's stack.
2139     NumBytes = 0;
2140   } else {
2141     // Adjust the stack pointer for the new arguments...
2142     // These operations are automatically eliminated by the prolog/epilog pass
2143     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
2144   }
2145
2146   SDValue StackPtr =
2147       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
2148
2149   RegsToPassVector RegsToPass;
2150   SmallVector<SDValue, 8> MemOpChains;
2151
2152   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2153   // of tail call optimization, arguments are handled later.
2154   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2155        i != e;
2156        ++i, ++realArgIdx) {
2157     CCValAssign &VA = ArgLocs[i];
2158     SDValue Arg = OutVals[realArgIdx];
2159     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2160     bool isByVal = Flags.isByVal();
2161
2162     // Promote the value if needed.
2163     switch (VA.getLocInfo()) {
2164     default: llvm_unreachable("Unknown loc info!");
2165     case CCValAssign::Full: break;
2166     case CCValAssign::SExt:
2167       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2168       break;
2169     case CCValAssign::ZExt:
2170       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2171       break;
2172     case CCValAssign::AExt:
2173       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2174       break;
2175     case CCValAssign::BCvt:
2176       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2177       break;
2178     }
2179
2180     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
2181     if (VA.needsCustom()) {
2182       if (VA.getLocVT() == MVT::v2f64) {
2183         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2184                                   DAG.getConstant(0, dl, MVT::i32));
2185         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2186                                   DAG.getConstant(1, dl, MVT::i32));
2187
2188         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
2189                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2190
2191         VA = ArgLocs[++i]; // skip ahead to next loc
2192         if (VA.isRegLoc()) {
2193           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
2194                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
2195         } else {
2196           assert(VA.isMemLoc());
2197
2198           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
2199                                                  dl, DAG, VA, Flags));
2200         }
2201       } else {
2202         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
2203                          StackPtr, MemOpChains, Flags);
2204       }
2205     } else if (VA.isRegLoc()) {
2206       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
2207           Outs[0].VT == MVT::i32) {
2208         assert(VA.getLocVT() == MVT::i32 &&
2209                "unexpected calling convention register assignment");
2210         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
2211                "unexpected use of 'returned'");
2212         isThisReturn = true;
2213       }
2214       const TargetOptions &Options = DAG.getTarget().Options;
2215       if (Options.EnableDebugEntryValues)
2216         CSInfo.emplace_back(VA.getLocReg(), i);
2217       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2218     } else if (isByVal) {
2219       assert(VA.isMemLoc());
2220       unsigned offset = 0;
2221
2222       // True if this byval aggregate will be split between registers
2223       // and memory.
2224       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
2225       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
2226
2227       if (CurByValIdx < ByValArgsCount) {
2228
2229         unsigned RegBegin, RegEnd;
2230         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
2231
2232         EVT PtrVT =
2233             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2234         unsigned int i, j;
2235         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
2236           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
2237           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
2238           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
2239                                      MachinePointerInfo(),
2240                                      DAG.InferPtrAlignment(AddArg));
2241           MemOpChains.push_back(Load.getValue(1));
2242           RegsToPass.push_back(std::make_pair(j, Load));
2243         }
2244
2245         // If parameter size outsides register area, "offset" value
2246         // helps us to calculate stack slot for remained part properly.
2247         offset = RegEnd - RegBegin;
2248
2249         CCInfo.nextInRegsParam();
2250       }
2251
2252       if (Flags.getByValSize() > 4*offset) {
2253         auto PtrVT = getPointerTy(DAG.getDataLayout());
2254         unsigned LocMemOffset = VA.getLocMemOffset();
2255         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2256         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
2257         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
2258         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
2259         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
2260                                            MVT::i32);
2261         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
2262                                             MVT::i32);
2263
2264         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2265         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
2266         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
2267                                           Ops));
2268       }
2269     } else if (!isTailCall) {
2270       assert(VA.isMemLoc());
2271
2272       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2273                                              dl, DAG, VA, Flags));
2274     }
2275   }
2276
2277   if (!MemOpChains.empty())
2278     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2279
2280   // Build a sequence of copy-to-reg nodes chained together with token chain
2281   // and flag operands which copy the outgoing args into the appropriate regs.
2282   SDValue InFlag;
2283   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2284     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2285                              RegsToPass[i].second, InFlag);
2286     InFlag = Chain.getValue(1);
2287   }
2288
2289   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2290   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2291   // node so that legalize doesn't hack it.
2292   bool isDirect = false;
2293
2294   const TargetMachine &TM = getTargetMachine();
2295   const Module *Mod = MF.getFunction().getParent();
2296   const GlobalValue *GV = nullptr;
2297   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2298     GV = G->getGlobal();
2299   bool isStub =
2300       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2301
2302   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2303   bool isLocalARMFunc = false;
2304   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2305   auto PtrVt = getPointerTy(DAG.getDataLayout());
2306
2307   if (Subtarget->genLongCalls()) {
2308     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2309            "long-calls codegen is not position independent!");
2310     // Handle a global address or an external symbol. If it's not one of
2311     // those, the target's already in a register, so we don't need to do
2312     // anything extra.
2313     if (isa<GlobalAddressSDNode>(Callee)) {
2314       // Create a constant pool entry for the callee address
2315       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2316       ARMConstantPoolValue *CPV =
2317         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2318
2319       // Get the address of the callee into a register
2320       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2321       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2322       Callee = DAG.getLoad(
2323           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2324           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2325     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2326       const char *Sym = S->getSymbol();
2327
2328       // Create a constant pool entry for the callee address
2329       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2330       ARMConstantPoolValue *CPV =
2331         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2332                                       ARMPCLabelIndex, 0);
2333       // Get the address of the callee into a register
2334       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2335       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2336       Callee = DAG.getLoad(
2337           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2338           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2339     }
2340   } else if (isa<GlobalAddressSDNode>(Callee)) {
2341     if (!PreferIndirect) {
2342       isDirect = true;
2343       bool isDef = GV->isStrongDefinitionForLinker();
2344
2345       // ARM call to a local ARM function is predicable.
2346       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2347       // tBX takes a register source operand.
2348       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2349         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2350         Callee = DAG.getNode(
2351             ARMISD::WrapperPIC, dl, PtrVt,
2352             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2353         Callee = DAG.getLoad(
2354             PtrVt, dl, DAG.getEntryNode(), Callee,
2355             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2356             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2357                                      MachineMemOperand::MOInvariant);
2358       } else if (Subtarget->isTargetCOFF()) {
2359         assert(Subtarget->isTargetWindows() &&
2360                "Windows is the only supported COFF target");
2361         unsigned TargetFlags = ARMII::MO_NO_FLAG;
2362         if (GV->hasDLLImportStorageClass())
2363           TargetFlags = ARMII::MO_DLLIMPORT;
2364         else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
2365           TargetFlags = ARMII::MO_COFFSTUB;
2366         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*offset=*/0,
2367                                             TargetFlags);
2368         if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
2369           Callee =
2370               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2371                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2372                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2373       } else {
2374         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2375       }
2376     }
2377   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2378     isDirect = true;
2379     // tBX takes a register source operand.
2380     const char *Sym = S->getSymbol();
2381     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2382       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2383       ARMConstantPoolValue *CPV =
2384         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2385                                       ARMPCLabelIndex, 4);
2386       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2387       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2388       Callee = DAG.getLoad(
2389           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2390           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2391       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2392       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2393     } else {
2394       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2395     }
2396   }
2397
2398   // FIXME: handle tail calls differently.
2399   unsigned CallOpc;
2400   if (Subtarget->isThumb()) {
2401     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2402       CallOpc = ARMISD::CALL_NOLINK;
2403     else
2404       CallOpc = ARMISD::CALL;
2405   } else {
2406     if (!isDirect && !Subtarget->hasV5TOps())
2407       CallOpc = ARMISD::CALL_NOLINK;
2408     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2409              // Emit regular call when code size is the priority
2410              !Subtarget->hasMinSize())
2411       // "mov lr, pc; b _foo" to avoid confusing the RSP
2412       CallOpc = ARMISD::CALL_NOLINK;
2413     else
2414       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2415   }
2416
2417   std::vector<SDValue> Ops;
2418   Ops.push_back(Chain);
2419   Ops.push_back(Callee);
2420
2421   // Add argument registers to the end of the list so that they are known live
2422   // into the call.
2423   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2424     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2425                                   RegsToPass[i].second.getValueType()));
2426
2427   // Add a register mask operand representing the call-preserved registers.
2428   if (!isTailCall) {
2429     const uint32_t *Mask;
2430     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2431     if (isThisReturn) {
2432       // For 'this' returns, use the R0-preserving mask if applicable
2433       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2434       if (!Mask) {
2435         // Set isThisReturn to false if the calling convention is not one that
2436         // allows 'returned' to be modeled in this way, so LowerCallResult does
2437         // not try to pass 'this' straight through
2438         isThisReturn = false;
2439         Mask = ARI->getCallPreservedMask(MF, CallConv);
2440       }
2441     } else
2442       Mask = ARI->getCallPreservedMask(MF, CallConv);
2443
2444     assert(Mask && "Missing call preserved mask for calling convention");
2445     Ops.push_back(DAG.getRegisterMask(Mask));
2446   }
2447
2448   if (InFlag.getNode())
2449     Ops.push_back(InFlag);
2450
2451   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2452   if (isTailCall) {
2453     MF.getFrameInfo().setHasTailCall();
2454     SDValue Ret = DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2455     DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
2456     return Ret;
2457   }
2458
2459   // Returns a chain and a flag for retval copy to use.
2460   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2461   InFlag = Chain.getValue(1);
2462   DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
2463
2464   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2465                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2466   if (!Ins.empty())
2467     InFlag = Chain.getValue(1);
2468
2469   // Handle result values, copying them out of physregs into vregs that we
2470   // return.
2471   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2472                          InVals, isThisReturn,
2473                          isThisReturn ? OutVals[0] : SDValue());
2474 }
2475
2476 /// HandleByVal - Every parameter *after* a byval parameter is passed
2477 /// on the stack.  Remember the next parameter register to allocate,
2478 /// and then confiscate the rest of the parameter registers to insure
2479 /// this.
2480 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2481                                     unsigned Align) const {
2482   // Byval (as with any stack) slots are always at least 4 byte aligned.
2483   Align = std::max(Align, 4U);
2484
2485   unsigned Reg = State->AllocateReg(GPRArgRegs);
2486   if (!Reg)
2487     return;
2488
2489   unsigned AlignInRegs = Align / 4;
2490   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2491   for (unsigned i = 0; i < Waste; ++i)
2492     Reg = State->AllocateReg(GPRArgRegs);
2493
2494   if (!Reg)
2495     return;
2496
2497   unsigned Excess = 4 * (ARM::R4 - Reg);
2498
2499   // Special case when NSAA != SP and parameter size greater than size of
2500   // all remained GPR regs. In that case we can't split parameter, we must
2501   // send it to stack. We also must set NCRN to R4, so waste all
2502   // remained registers.
2503   const unsigned NSAAOffset = State->getNextStackOffset();
2504   if (NSAAOffset != 0 && Size > Excess) {
2505     while (State->AllocateReg(GPRArgRegs))
2506       ;
2507     return;
2508   }
2509
2510   // First register for byval parameter is the first register that wasn't
2511   // allocated before this method call, so it would be "reg".
2512   // If parameter is small enough to be saved in range [reg, r4), then
2513   // the end (first after last) register would be reg + param-size-in-regs,
2514   // else parameter would be splitted between registers and stack,
2515   // end register would be r4 in this case.
2516   unsigned ByValRegBegin = Reg;
2517   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2518   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2519   // Note, first register is allocated in the beginning of function already,
2520   // allocate remained amount of registers we need.
2521   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2522     State->AllocateReg(GPRArgRegs);
2523   // A byval parameter that is split between registers and memory needs its
2524   // size truncated here.
2525   // In the case where the entire structure fits in registers, we set the
2526   // size in memory to zero.
2527   Size = std::max<int>(Size - Excess, 0);
2528 }
2529
2530 /// MatchingStackOffset - Return true if the given stack call argument is
2531 /// already available in the same position (relatively) of the caller's
2532 /// incoming argument stack.
2533 static
2534 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2535                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2536                          const TargetInstrInfo *TII) {
2537   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2538   int FI = std::numeric_limits<int>::max();
2539   if (Arg.getOpcode() == ISD::CopyFromReg) {
2540     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2541     if (!Register::isVirtualRegister(VR))
2542       return false;
2543     MachineInstr *Def = MRI->getVRegDef(VR);
2544     if (!Def)
2545       return false;
2546     if (!Flags.isByVal()) {
2547       if (!TII->isLoadFromStackSlot(*Def, FI))
2548         return false;
2549     } else {
2550       return false;
2551     }
2552   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2553     if (Flags.isByVal())
2554       // ByVal argument is passed in as a pointer but it's now being
2555       // dereferenced. e.g.
2556       // define @foo(%struct.X* %A) {
2557       //   tail call @bar(%struct.X* byval %A)
2558       // }
2559       return false;
2560     SDValue Ptr = Ld->getBasePtr();
2561     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2562     if (!FINode)
2563       return false;
2564     FI = FINode->getIndex();
2565   } else
2566     return false;
2567
2568   assert(FI != std::numeric_limits<int>::max());
2569   if (!MFI.isFixedObjectIndex(FI))
2570     return false;
2571   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2572 }
2573
2574 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2575 /// for tail call optimization. Targets which want to do tail call
2576 /// optimization should implement this function.
2577 bool ARMTargetLowering::IsEligibleForTailCallOptimization(
2578     SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2579     bool isCalleeStructRet, bool isCallerStructRet,
2580     const SmallVectorImpl<ISD::OutputArg> &Outs,
2581     const SmallVectorImpl<SDValue> &OutVals,
2582     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG,
2583     const bool isIndirect) const {
2584   MachineFunction &MF = DAG.getMachineFunction();
2585   const Function &CallerF = MF.getFunction();
2586   CallingConv::ID CallerCC = CallerF.getCallingConv();
2587
2588   assert(Subtarget->supportsTailCall());
2589
2590   // Indirect tail calls cannot be optimized for Thumb1 if the args
2591   // to the call take up r0-r3. The reason is that there are no legal registers
2592   // left to hold the pointer to the function to be called.
2593   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2594       (!isa<GlobalAddressSDNode>(Callee.getNode()) || isIndirect))
2595     return false;
2596
2597   // Look for obvious safe cases to perform tail call optimization that do not
2598   // require ABI changes. This is what gcc calls sibcall.
2599
2600   // Exception-handling functions need a special set of instructions to indicate
2601   // a return to the hardware. Tail-calling another function would probably
2602   // break this.
2603   if (CallerF.hasFnAttribute("interrupt"))
2604     return false;
2605
2606   // Also avoid sibcall optimization if either caller or callee uses struct
2607   // return semantics.
2608   if (isCalleeStructRet || isCallerStructRet)
2609     return false;
2610
2611   // Externally-defined functions with weak linkage should not be
2612   // tail-called on ARM when the OS does not support dynamic
2613   // pre-emption of symbols, as the AAELF spec requires normal calls
2614   // to undefined weak functions to be replaced with a NOP or jump to the
2615   // next instruction. The behaviour of branch instructions in this
2616   // situation (as used for tail calls) is implementation-defined, so we
2617   // cannot rely on the linker replacing the tail call with a return.
2618   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2619     const GlobalValue *GV = G->getGlobal();
2620     const Triple &TT = getTargetMachine().getTargetTriple();
2621     if (GV->hasExternalWeakLinkage() &&
2622         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2623       return false;
2624   }
2625
2626   // Check that the call results are passed in the same way.
2627   LLVMContext &C = *DAG.getContext();
2628   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2629                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2630                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2631     return false;
2632   // The callee has to preserve all registers the caller needs to preserve.
2633   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2634   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2635   if (CalleeCC != CallerCC) {
2636     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2637     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2638       return false;
2639   }
2640
2641   // If Caller's vararg or byval argument has been split between registers and
2642   // stack, do not perform tail call, since part of the argument is in caller's
2643   // local frame.
2644   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2645   if (AFI_Caller->getArgRegsSaveSize())
2646     return false;
2647
2648   // If the callee takes no arguments then go on to check the results of the
2649   // call.
2650   if (!Outs.empty()) {
2651     // Check if stack adjustment is needed. For now, do not do this if any
2652     // argument is passed on the stack.
2653     SmallVector<CCValAssign, 16> ArgLocs;
2654     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2655     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2656     if (CCInfo.getNextStackOffset()) {
2657       // Check if the arguments are already laid out in the right way as
2658       // the caller's fixed stack objects.
2659       MachineFrameInfo &MFI = MF.getFrameInfo();
2660       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2661       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2662       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2663            i != e;
2664            ++i, ++realArgIdx) {
2665         CCValAssign &VA = ArgLocs[i];
2666         EVT RegVT = VA.getLocVT();
2667         SDValue Arg = OutVals[realArgIdx];
2668         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2669         if (VA.getLocInfo() == CCValAssign::Indirect)
2670           return false;
2671         if (VA.needsCustom()) {
2672           // f64 and vector types are split into multiple registers or
2673           // register/stack-slot combinations.  The types will not match
2674           // the registers; give up on memory f64 refs until we figure
2675           // out what to do about this.
2676           if (!VA.isRegLoc())
2677             return false;
2678           if (!ArgLocs[++i].isRegLoc())
2679             return false;
2680           if (RegVT == MVT::v2f64) {
2681             if (!ArgLocs[++i].isRegLoc())
2682               return false;
2683             if (!ArgLocs[++i].isRegLoc())
2684               return false;
2685           }
2686         } else if (!VA.isRegLoc()) {
2687           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2688                                    MFI, MRI, TII))
2689             return false;
2690         }
2691       }
2692     }
2693
2694     const MachineRegisterInfo &MRI = MF.getRegInfo();
2695     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2696       return false;
2697   }
2698
2699   return true;
2700 }
2701
2702 bool
2703 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2704                                   MachineFunction &MF, bool isVarArg,
2705                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2706                                   LLVMContext &Context) const {
2707   SmallVector<CCValAssign, 16> RVLocs;
2708   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2709   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2710 }
2711
2712 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2713                                     const SDLoc &DL, SelectionDAG &DAG) {
2714   const MachineFunction &MF = DAG.getMachineFunction();
2715   const Function &F = MF.getFunction();
2716
2717   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2718
2719   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2720   // version of the "preferred return address". These offsets affect the return
2721   // instruction if this is a return from PL1 without hypervisor extensions.
2722   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2723   //    SWI:     0      "subs pc, lr, #0"
2724   //    ABORT:   +4     "subs pc, lr, #4"
2725   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2726   // UNDEF varies depending on where the exception came from ARM or Thumb
2727   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2728
2729   int64_t LROffset;
2730   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2731       IntKind == "ABORT")
2732     LROffset = 4;
2733   else if (IntKind == "SWI" || IntKind == "UNDEF")
2734     LROffset = 0;
2735   else
2736     report_fatal_error("Unsupported interrupt attribute. If present, value "
2737                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2738
2739   RetOps.insert(RetOps.begin() + 1,
2740                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2741
2742   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2743 }
2744
2745 SDValue
2746 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2747                                bool isVarArg,
2748                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2749                                const SmallVectorImpl<SDValue> &OutVals,
2750                                const SDLoc &dl, SelectionDAG &DAG) const {
2751   // CCValAssign - represent the assignment of the return value to a location.
2752   SmallVector<CCValAssign, 16> RVLocs;
2753
2754   // CCState - Info about the registers and stack slots.
2755   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2756                  *DAG.getContext());
2757
2758   // Analyze outgoing return values.
2759   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2760
2761   SDValue Flag;
2762   SmallVector<SDValue, 4> RetOps;
2763   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2764   bool isLittleEndian = Subtarget->isLittle();
2765
2766   MachineFunction &MF = DAG.getMachineFunction();
2767   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2768   AFI->setReturnRegsCount(RVLocs.size());
2769
2770   // Copy the result values into the output registers.
2771   for (unsigned i = 0, realRVLocIdx = 0;
2772        i != RVLocs.size();
2773        ++i, ++realRVLocIdx) {
2774     CCValAssign &VA = RVLocs[i];
2775     assert(VA.isRegLoc() && "Can only return in registers!");
2776
2777     SDValue Arg = OutVals[realRVLocIdx];
2778     bool ReturnF16 = false;
2779
2780     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2781       // Half-precision return values can be returned like this:
2782       //
2783       // t11 f16 = fadd ...
2784       // t12: i16 = bitcast t11
2785       //   t13: i32 = zero_extend t12
2786       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2787       //
2788       // to avoid code generation for bitcasts, we simply set Arg to the node
2789       // that produces the f16 value, t11 in this case.
2790       //
2791       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2792         SDValue ZE = Arg.getOperand(0);
2793         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2794           SDValue BC = ZE.getOperand(0);
2795           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2796             Arg = BC.getOperand(0);
2797             ReturnF16 = true;
2798           }
2799         }
2800       }
2801     }
2802
2803     switch (VA.getLocInfo()) {
2804     default: llvm_unreachable("Unknown loc info!");
2805     case CCValAssign::Full: break;
2806     case CCValAssign::BCvt:
2807       if (!ReturnF16)
2808         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2809       break;
2810     }
2811
2812     if (VA.needsCustom()) {
2813       if (VA.getLocVT() == MVT::v2f64) {
2814         // Extract the first half and return it in two registers.
2815         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2816                                    DAG.getConstant(0, dl, MVT::i32));
2817         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2818                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2819
2820         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2821                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2822                                  Flag);
2823         Flag = Chain.getValue(1);
2824         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2825         VA = RVLocs[++i]; // skip ahead to next loc
2826         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2827                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2828                                  Flag);
2829         Flag = Chain.getValue(1);
2830         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2831         VA = RVLocs[++i]; // skip ahead to next loc
2832
2833         // Extract the 2nd half and fall through to handle it as an f64 value.
2834         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2835                           DAG.getConstant(1, dl, MVT::i32));
2836       }
2837       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2838       // available.
2839       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2840                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2841       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2842                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2843                                Flag);
2844       Flag = Chain.getValue(1);
2845       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2846       VA = RVLocs[++i]; // skip ahead to next loc
2847       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2848                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2849                                Flag);
2850     } else
2851       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2852
2853     // Guarantee that all emitted copies are
2854     // stuck together, avoiding something bad.
2855     Flag = Chain.getValue(1);
2856     RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2857                                      ReturnF16 ? MVT::f16 : VA.getLocVT()));
2858   }
2859   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2860   const MCPhysReg *I =
2861       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2862   if (I) {
2863     for (; *I; ++I) {
2864       if (ARM::GPRRegClass.contains(*I))
2865         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2866       else if (ARM::DPRRegClass.contains(*I))
2867         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2868       else
2869         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2870     }
2871   }
2872
2873   // Update chain and glue.
2874   RetOps[0] = Chain;
2875   if (Flag.getNode())
2876     RetOps.push_back(Flag);
2877
2878   // CPUs which aren't M-class use a special sequence to return from
2879   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2880   // though we use "subs pc, lr, #N").
2881   //
2882   // M-class CPUs actually use a normal return sequence with a special
2883   // (hardware-provided) value in LR, so the normal code path works.
2884   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2885       !Subtarget->isMClass()) {
2886     if (Subtarget->isThumb1Only())
2887       report_fatal_error("interrupt attribute is not supported in Thumb1");
2888     return LowerInterruptReturn(RetOps, dl, DAG);
2889   }
2890
2891   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2892 }
2893
2894 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2895   if (N->getNumValues() != 1)
2896     return false;
2897   if (!N->hasNUsesOfValue(1, 0))
2898     return false;
2899
2900   SDValue TCChain = Chain;
2901   SDNode *Copy = *N->use_begin();
2902   if (Copy->getOpcode() == ISD::CopyToReg) {
2903     // If the copy has a glue operand, we conservatively assume it isn't safe to
2904     // perform a tail call.
2905     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2906       return false;
2907     TCChain = Copy->getOperand(0);
2908   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2909     SDNode *VMov = Copy;
2910     // f64 returned in a pair of GPRs.
2911     SmallPtrSet<SDNode*, 2> Copies;
2912     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2913          UI != UE; ++UI) {
2914       if (UI->getOpcode() != ISD::CopyToReg)
2915         return false;
2916       Copies.insert(*UI);
2917     }
2918     if (Copies.size() > 2)
2919       return false;
2920
2921     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2922          UI != UE; ++UI) {
2923       SDValue UseChain = UI->getOperand(0);
2924       if (Copies.count(UseChain.getNode()))
2925         // Second CopyToReg
2926         Copy = *UI;
2927       else {
2928         // We are at the top of this chain.
2929         // If the copy has a glue operand, we conservatively assume it
2930         // isn't safe to perform a tail call.
2931         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2932           return false;
2933         // First CopyToReg
2934         TCChain = UseChain;
2935       }
2936     }
2937   } else if (Copy->getOpcode() == ISD::BITCAST) {
2938     // f32 returned in a single GPR.
2939     if (!Copy->hasOneUse())
2940       return false;
2941     Copy = *Copy->use_begin();
2942     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2943       return false;
2944     // If the copy has a glue operand, we conservatively assume it isn't safe to
2945     // perform a tail call.
2946     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2947       return false;
2948     TCChain = Copy->getOperand(0);
2949   } else {
2950     return false;
2951   }
2952
2953   bool HasRet = false;
2954   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2955        UI != UE; ++UI) {
2956     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2957         UI->getOpcode() != ARMISD::INTRET_FLAG)
2958       return false;
2959     HasRet = true;
2960   }
2961
2962   if (!HasRet)
2963     return false;
2964
2965   Chain = TCChain;
2966   return true;
2967 }
2968
2969 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2970   if (!Subtarget->supportsTailCall())
2971     return false;
2972
2973   if (!CI->isTailCall())
2974     return false;
2975
2976   return true;
2977 }
2978
2979 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2980 // and pass the lower and high parts through.
2981 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2982   SDLoc DL(Op);
2983   SDValue WriteValue = Op->getOperand(2);
2984
2985   // This function is only supposed to be called for i64 type argument.
2986   assert(WriteValue.getValueType() == MVT::i64
2987           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2988
2989   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2990                            DAG.getConstant(0, DL, MVT::i32));
2991   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2992                            DAG.getConstant(1, DL, MVT::i32));
2993   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2994   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2995 }
2996
2997 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2998 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2999 // one of the above mentioned nodes. It has to be wrapped because otherwise
3000 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3001 // be used to form addressing mode. These wrapped nodes will be selected
3002 // into MOVi.
3003 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
3004                                              SelectionDAG &DAG) const {
3005   EVT PtrVT = Op.getValueType();
3006   // FIXME there is no actual debug info here
3007   SDLoc dl(Op);
3008   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3009   SDValue Res;
3010
3011   // When generating execute-only code Constant Pools must be promoted to the
3012   // global data section. It's a bit ugly that we can't share them across basic
3013   // blocks, but this way we guarantee that execute-only behaves correct with
3014   // position-independent addressing modes.
3015   if (Subtarget->genExecuteOnly()) {
3016     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
3017     auto T = const_cast<Type*>(CP->getType());
3018     auto C = const_cast<Constant*>(CP->getConstVal());
3019     auto M = const_cast<Module*>(DAG.getMachineFunction().
3020                                  getFunction().getParent());
3021     auto GV = new GlobalVariable(
3022                     *M, T, /*isConstant=*/true, GlobalVariable::InternalLinkage, C,
3023                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
3024                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
3025                     Twine(AFI->createPICLabelUId())
3026                   );
3027     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
3028                                             dl, PtrVT);
3029     return LowerGlobalAddress(GA, DAG);
3030   }
3031
3032   if (CP->isMachineConstantPoolEntry())
3033     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
3034                                     CP->getAlignment());
3035   else
3036     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
3037                                     CP->getAlignment());
3038   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
3039 }
3040
3041 unsigned ARMTargetLowering::getJumpTableEncoding() const {
3042   return MachineJumpTableInfo::EK_Inline;
3043 }
3044
3045 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
3046                                              SelectionDAG &DAG) const {
3047   MachineFunction &MF = DAG.getMachineFunction();
3048   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3049   unsigned ARMPCLabelIndex = 0;
3050   SDLoc DL(Op);
3051   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3052   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3053   SDValue CPAddr;
3054   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
3055   if (!IsPositionIndependent) {
3056     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
3057   } else {
3058     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3059     ARMPCLabelIndex = AFI->createPICLabelUId();
3060     ARMConstantPoolValue *CPV =
3061       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
3062                                       ARMCP::CPBlockAddress, PCAdj);
3063     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3064   }
3065   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
3066   SDValue Result = DAG.getLoad(
3067       PtrVT, DL, DAG.getEntryNode(), CPAddr,
3068       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3069   if (!IsPositionIndependent)
3070     return Result;
3071   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
3072   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
3073 }
3074
3075 /// Convert a TLS address reference into the correct sequence of loads
3076 /// and calls to compute the variable's address for Darwin, and return an
3077 /// SDValue containing the final node.
3078
3079 /// Darwin only has one TLS scheme which must be capable of dealing with the
3080 /// fully general situation, in the worst case. This means:
3081 ///     + "extern __thread" declaration.
3082 ///     + Defined in a possibly unknown dynamic library.
3083 ///
3084 /// The general system is that each __thread variable has a [3 x i32] descriptor
3085 /// which contains information used by the runtime to calculate the address. The
3086 /// only part of this the compiler needs to know about is the first word, which
3087 /// contains a function pointer that must be called with the address of the
3088 /// entire descriptor in "r0".
3089 ///
3090 /// Since this descriptor may be in a different unit, in general access must
3091 /// proceed along the usual ARM rules. A common sequence to produce is:
3092 ///
3093 ///     movw rT1, :lower16:_var$non_lazy_ptr
3094 ///     movt rT1, :upper16:_var$non_lazy_ptr
3095 ///     ldr r0, [rT1]
3096 ///     ldr rT2, [r0]
3097 ///     blx rT2
3098 ///     [...address now in r0...]
3099 SDValue
3100 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
3101                                                SelectionDAG &DAG) const {
3102   assert(Subtarget->isTargetDarwin() &&
3103          "This function expects a Darwin target");
3104   SDLoc DL(Op);
3105
3106   // First step is to get the address of the actua global symbol. This is where
3107   // the TLS descriptor lives.
3108   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
3109
3110   // The first entry in the descriptor is a function pointer that we must call
3111   // to obtain the address of the variable.
3112   SDValue Chain = DAG.getEntryNode();
3113   SDValue FuncTLVGet = DAG.getLoad(
3114       MVT::i32, DL, Chain, DescAddr,
3115       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3116       /* Alignment = */ 4,
3117       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
3118           MachineMemOperand::MOInvariant);
3119   Chain = FuncTLVGet.getValue(1);
3120
3121   MachineFunction &F = DAG.getMachineFunction();
3122   MachineFrameInfo &MFI = F.getFrameInfo();
3123   MFI.setAdjustsStack(true);
3124
3125   // TLS calls preserve all registers except those that absolutely must be
3126   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
3127   // silly).
3128   auto TRI =
3129       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
3130   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
3131   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
3132
3133   // Finally, we can make the call. This is just a degenerate version of a
3134   // normal AArch64 call node: r0 takes the address of the descriptor, and
3135   // returns the address of the variable in this thread.
3136   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
3137   Chain =
3138       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3139                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
3140                   DAG.getRegisterMask(Mask), Chain.getValue(1));
3141   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
3142 }
3143
3144 SDValue
3145 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
3146                                                 SelectionDAG &DAG) const {
3147   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
3148
3149   SDValue Chain = DAG.getEntryNode();
3150   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3151   SDLoc DL(Op);
3152
3153   // Load the current TEB (thread environment block)
3154   SDValue Ops[] = {Chain,
3155                    DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
3156                    DAG.getTargetConstant(15, DL, MVT::i32),
3157                    DAG.getTargetConstant(0, DL, MVT::i32),
3158                    DAG.getTargetConstant(13, DL, MVT::i32),
3159                    DAG.getTargetConstant(0, DL, MVT::i32),
3160                    DAG.getTargetConstant(2, DL, MVT::i32)};
3161   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
3162                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
3163
3164   SDValue TEB = CurrentTEB.getValue(0);
3165   Chain = CurrentTEB.getValue(1);
3166
3167   // Load the ThreadLocalStoragePointer from the TEB
3168   // A pointer to the TLS array is located at offset 0x2c from the TEB.
3169   SDValue TLSArray =
3170       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
3171   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
3172
3173   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
3174   // offset into the TLSArray.
3175
3176   // Load the TLS index from the C runtime
3177   SDValue TLSIndex =
3178       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
3179   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
3180   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
3181
3182   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
3183                               DAG.getConstant(2, DL, MVT::i32));
3184   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
3185                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
3186                             MachinePointerInfo());
3187
3188   // Get the offset of the start of the .tls section (section base)
3189   const auto *GA = cast<GlobalAddressSDNode>(Op);
3190   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
3191   SDValue Offset = DAG.getLoad(
3192       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
3193                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
3194       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3195
3196   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
3197 }
3198
3199 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3200 SDValue
3201 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
3202                                                  SelectionDAG &DAG) const {
3203   SDLoc dl(GA);
3204   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3205   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3206   MachineFunction &MF = DAG.getMachineFunction();
3207   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3208   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3209   ARMConstantPoolValue *CPV =
3210     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3211                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
3212   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3213   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
3214   Argument = DAG.getLoad(
3215       PtrVT, dl, DAG.getEntryNode(), Argument,
3216       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3217   SDValue Chain = Argument.getValue(1);
3218
3219   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3220   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
3221
3222   // call __tls_get_addr.
3223   ArgListTy Args;
3224   ArgListEntry Entry;
3225   Entry.Node = Argument;
3226   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
3227   Args.push_back(Entry);
3228
3229   // FIXME: is there useful debug info available here?
3230   TargetLowering::CallLoweringInfo CLI(DAG);
3231   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3232       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
3233       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
3234
3235   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3236   return CallResult.first;
3237 }
3238
3239 // Lower ISD::GlobalTLSAddress using the "initial exec" or
3240 // "local exec" model.
3241 SDValue
3242 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
3243                                         SelectionDAG &DAG,
3244                                         TLSModel::Model model) const {
3245   const GlobalValue *GV = GA->getGlobal();
3246   SDLoc dl(GA);
3247   SDValue Offset;
3248   SDValue Chain = DAG.getEntryNode();
3249   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3250   // Get the Thread Pointer
3251   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3252
3253   if (model == TLSModel::InitialExec) {
3254     MachineFunction &MF = DAG.getMachineFunction();
3255     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3256     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3257     // Initial exec model.
3258     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
3259     ARMConstantPoolValue *CPV =
3260       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
3261                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
3262                                       true);
3263     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3264     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3265     Offset = DAG.getLoad(
3266         PtrVT, dl, Chain, Offset,
3267         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3268     Chain = Offset.getValue(1);
3269
3270     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3271     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3272
3273     Offset = DAG.getLoad(
3274         PtrVT, dl, Chain, Offset,
3275         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3276   } else {
3277     // local exec model
3278     assert(model == TLSModel::LocalExec);
3279     ARMConstantPoolValue *CPV =
3280       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3281     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3282     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3283     Offset = DAG.getLoad(
3284         PtrVT, dl, Chain, Offset,
3285         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3286   }
3287
3288   // The address of the thread local variable is the add of the thread
3289   // pointer with the offset of the variable.
3290   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3291 }
3292
3293 SDValue
3294 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3295   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3296   if (DAG.getTarget().useEmulatedTLS())
3297     return LowerToTLSEmulatedModel(GA, DAG);
3298
3299   if (Subtarget->isTargetDarwin())
3300     return LowerGlobalTLSAddressDarwin(Op, DAG);
3301
3302   if (Subtarget->isTargetWindows())
3303     return LowerGlobalTLSAddressWindows(Op, DAG);
3304
3305   // TODO: implement the "local dynamic" model
3306   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3307   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3308
3309   switch (model) {
3310     case TLSModel::GeneralDynamic:
3311     case TLSModel::LocalDynamic:
3312       return LowerToTLSGeneralDynamicModel(GA, DAG);
3313     case TLSModel::InitialExec:
3314     case TLSModel::LocalExec:
3315       return LowerToTLSExecModels(GA, DAG, model);
3316   }
3317   llvm_unreachable("bogus TLS model");
3318 }
3319
3320 /// Return true if all users of V are within function F, looking through
3321 /// ConstantExprs.
3322 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3323   SmallVector<const User*,4> Worklist;
3324   for (auto *U : V->users())
3325     Worklist.push_back(U);
3326   while (!Worklist.empty()) {
3327     auto *U = Worklist.pop_back_val();
3328     if (isa<ConstantExpr>(U)) {
3329       for (auto *UU : U->users())
3330         Worklist.push_back(UU);
3331       continue;
3332     }
3333
3334     auto *I = dyn_cast<Instruction>(U);
3335     if (!I || I->getParent()->getParent() != F)
3336       return false;
3337   }
3338   return true;
3339 }
3340
3341 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3342                                      const GlobalValue *GV, SelectionDAG &DAG,
3343                                      EVT PtrVT, const SDLoc &dl) {
3344   // If we're creating a pool entry for a constant global with unnamed address,
3345   // and the global is small enough, we can emit it inline into the constant pool
3346   // to save ourselves an indirection.
3347   //
3348   // This is a win if the constant is only used in one function (so it doesn't
3349   // need to be duplicated) or duplicating the constant wouldn't increase code
3350   // size (implying the constant is no larger than 4 bytes).
3351   const Function &F = DAG.getMachineFunction().getFunction();
3352
3353   // We rely on this decision to inline being idemopotent and unrelated to the
3354   // use-site. We know that if we inline a variable at one use site, we'll
3355   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3356   // doesn't know about this optimization, so bail out if it's enabled else
3357   // we could decide to inline here (and thus never emit the GV) but require
3358   // the GV from fast-isel generated code.
3359   if (!EnableConstpoolPromotion ||
3360       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3361       return SDValue();
3362
3363   auto *GVar = dyn_cast<GlobalVariable>(GV);
3364   if (!GVar || !GVar->hasInitializer() ||
3365       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3366       !GVar->hasLocalLinkage())
3367     return SDValue();
3368
3369   // If we inline a value that contains relocations, we move the relocations
3370   // from .data to .text. This is not allowed in position-independent code.
3371   auto *Init = GVar->getInitializer();
3372   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3373       Init->needsRelocation())
3374     return SDValue();
3375
3376   // The constant islands pass can only really deal with alignment requests
3377   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3378   // any type wanting greater alignment requirements than 4 bytes. We also
3379   // can only promote constants that are multiples of 4 bytes in size or
3380   // are paddable to a multiple of 4. Currently we only try and pad constants
3381   // that are strings for simplicity.
3382   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3383   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3384   unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3385   unsigned RequiredPadding = 4 - (Size % 4);
3386   bool PaddingPossible =
3387     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3388   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3389       Size == 0)
3390     return SDValue();
3391
3392   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3393   MachineFunction &MF = DAG.getMachineFunction();
3394   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3395
3396   // We can't bloat the constant pool too much, else the ConstantIslands pass
3397   // may fail to converge. If we haven't promoted this global yet (it may have
3398   // multiple uses), and promoting it would increase the constant pool size (Sz
3399   // > 4), ensure we have space to do so up to MaxTotal.
3400   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3401     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3402         ConstpoolPromotionMaxTotal)
3403       return SDValue();
3404
3405   // This is only valid if all users are in a single function; we can't clone
3406   // the constant in general. The LLVM IR unnamed_addr allows merging
3407   // constants, but not cloning them.
3408   //
3409   // We could potentially allow cloning if we could prove all uses of the
3410   // constant in the current function don't care about the address, like
3411   // printf format strings. But that isn't implemented for now.
3412   if (!allUsersAreInFunction(GVar, &F))
3413     return SDValue();
3414
3415   // We're going to inline this global. Pad it out if needed.
3416   if (RequiredPadding != 4) {
3417     StringRef S = CDAInit->getAsString();
3418
3419     SmallVector<uint8_t,16> V(S.size());
3420     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3421     while (RequiredPadding--)
3422       V.push_back(0);
3423     Init = ConstantDataArray::get(*DAG.getContext(), V);
3424   }
3425
3426   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3427   SDValue CPAddr =
3428     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3429   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3430     AFI->markGlobalAsPromotedToConstantPool(GVar);
3431     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3432                                       PaddedSize - 4);
3433   }
3434   ++NumConstpoolPromoted;
3435   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3436 }
3437
3438 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3439   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3440     if (!(GV = GA->getBaseObject()))
3441       return false;
3442   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3443     return V->isConstant();
3444   return isa<Function>(GV);
3445 }
3446
3447 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3448                                               SelectionDAG &DAG) const {
3449   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3450   default: llvm_unreachable("unknown object format");
3451   case Triple::COFF:
3452     return LowerGlobalAddressWindows(Op, DAG);
3453   case Triple::ELF:
3454     return LowerGlobalAddressELF(Op, DAG);
3455   case Triple::MachO:
3456     return LowerGlobalAddressDarwin(Op, DAG);
3457   }
3458 }
3459
3460 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3461                                                  SelectionDAG &DAG) const {
3462   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3463   SDLoc dl(Op);
3464   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3465   const TargetMachine &TM = getTargetMachine();
3466   bool IsRO = isReadOnly(GV);
3467
3468   // promoteToConstantPool only if not generating XO text section
3469   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3470     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3471       return V;
3472
3473   if (isPositionIndependent()) {
3474     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3475     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3476                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3477     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3478     if (UseGOT_PREL)
3479       Result =
3480           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3481                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3482     return Result;
3483   } else if (Subtarget->isROPI() && IsRO) {
3484     // PC-relative.
3485     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3486     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3487     return Result;
3488   } else if (Subtarget->isRWPI() && !IsRO) {
3489     // SB-relative.
3490     SDValue RelAddr;
3491     if (Subtarget->useMovt()) {
3492       ++NumMovwMovt;
3493       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3494       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3495     } else { // use literal pool for address constant
3496       ARMConstantPoolValue *CPV =
3497         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3498       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3499       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3500       RelAddr = DAG.getLoad(
3501           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3502           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3503     }
3504     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3505     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3506     return Result;
3507   }
3508
3509   // If we have T2 ops, we can materialize the address directly via movt/movw
3510   // pair. This is always cheaper.
3511   if (Subtarget->useMovt()) {
3512     ++NumMovwMovt;
3513     // FIXME: Once remat is capable of dealing with instructions with register
3514     // operands, expand this into two nodes.
3515     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3516                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3517   } else {
3518     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3519     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3520     return DAG.getLoad(
3521         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3522         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3523   }
3524 }
3525
3526 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3527                                                     SelectionDAG &DAG) const {
3528   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3529          "ROPI/RWPI not currently supported for Darwin");
3530   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3531   SDLoc dl(Op);
3532   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3533
3534   if (Subtarget->useMovt())
3535     ++NumMovwMovt;
3536
3537   // FIXME: Once remat is capable of dealing with instructions with register
3538   // operands, expand this into multiple nodes
3539   unsigned Wrapper =
3540       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3541
3542   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3543   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3544
3545   if (Subtarget->isGVIndirectSymbol(GV))
3546     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3547                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3548   return Result;
3549 }
3550
3551 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3552                                                      SelectionDAG &DAG) const {
3553   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3554   assert(Subtarget->useMovt() &&
3555          "Windows on ARM expects to use movw/movt");
3556   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3557          "ROPI/RWPI not currently supported for Windows");
3558
3559   const TargetMachine &TM = getTargetMachine();
3560   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3561   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3562   if (GV->hasDLLImportStorageClass())
3563     TargetFlags = ARMII::MO_DLLIMPORT;
3564   else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3565     TargetFlags = ARMII::MO_COFFSTUB;
3566   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3567   SDValue Result;
3568   SDLoc DL(Op);
3569
3570   ++NumMovwMovt;
3571
3572   // FIXME: Once remat is capable of dealing with instructions with register
3573   // operands, expand this into two nodes.
3574   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3575                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*offset=*/0,
3576                                                   TargetFlags));
3577   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3578     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3579                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3580   return Result;
3581 }
3582
3583 SDValue
3584 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3585   SDLoc dl(Op);
3586   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3587   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3588                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3589                      Op.getOperand(1), Val);
3590 }
3591
3592 SDValue
3593 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3594   SDLoc dl(Op);
3595   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3596                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3597 }
3598
3599 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3600                                                       SelectionDAG &DAG) const {
3601   SDLoc dl(Op);
3602   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3603                      Op.getOperand(0));
3604 }
3605
3606 SDValue ARMTargetLowering::LowerINTRINSIC_VOID(
3607     SDValue Op, SelectionDAG &DAG, const ARMSubtarget *Subtarget) const {
3608   unsigned IntNo =
3609       cast<ConstantSDNode>(
3610           Op.getOperand(Op.getOperand(0).getValueType() == MVT::Other))
3611           ->getZExtValue();
3612   switch (IntNo) {
3613     default:
3614       return SDValue();  // Don't custom lower most intrinsics.
3615     case Intrinsic::arm_gnu_eabi_mcount: {
3616       MachineFunction &MF = DAG.getMachineFunction();
3617       EVT PtrVT = getPointerTy(DAG.getDataLayout());
3618       SDLoc dl(Op);
3619       SDValue Chain = Op.getOperand(0);
3620       // call "\01__gnu_mcount_nc"
3621       const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
3622       const uint32_t *Mask =
3623           ARI->getCallPreservedMask(DAG.getMachineFunction(), CallingConv::C);
3624       assert(Mask && "Missing call preserved mask for calling convention");
3625       // Mark LR an implicit live-in.
3626       unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
3627       SDValue ReturnAddress =
3628           DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, PtrVT);
3629       std::vector<EVT> ResultTys = {MVT::Other, MVT::Glue};
3630       SDValue Callee =
3631           DAG.getTargetExternalSymbol("\01__gnu_mcount_nc", PtrVT, 0);
3632       SDValue RegisterMask = DAG.getRegisterMask(Mask);
3633       if (Subtarget->isThumb())
3634         return SDValue(
3635             DAG.getMachineNode(
3636                 ARM::tBL_PUSHLR, dl, ResultTys,
3637                 {ReturnAddress, DAG.getTargetConstant(ARMCC::AL, dl, PtrVT),
3638                  DAG.getRegister(0, PtrVT), Callee, RegisterMask, Chain}),
3639             0);
3640       return SDValue(
3641           DAG.getMachineNode(ARM::BL_PUSHLR, dl, ResultTys,
3642                              {ReturnAddress, Callee, RegisterMask, Chain}),
3643           0);
3644     }
3645   }
3646 }
3647
3648 SDValue
3649 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3650                                           const ARMSubtarget *Subtarget) const {
3651   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3652   SDLoc dl(Op);
3653   switch (IntNo) {
3654   default: return SDValue();    // Don't custom lower most intrinsics.
3655   case Intrinsic::thread_pointer: {
3656     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3657     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3658   }
3659   case Intrinsic::arm_cls: {
3660     const SDValue &Operand = Op.getOperand(1);
3661     const EVT VTy = Op.getValueType();
3662     SDValue SRA =
3663         DAG.getNode(ISD::SRA, dl, VTy, Operand, DAG.getConstant(31, dl, VTy));
3664     SDValue XOR = DAG.getNode(ISD::XOR, dl, VTy, SRA, Operand);
3665     SDValue SHL =
3666         DAG.getNode(ISD::SHL, dl, VTy, XOR, DAG.getConstant(1, dl, VTy));
3667     SDValue OR =
3668         DAG.getNode(ISD::OR, dl, VTy, SHL, DAG.getConstant(1, dl, VTy));
3669     SDValue Result = DAG.getNode(ISD::CTLZ, dl, VTy, OR);
3670     return Result;
3671   }
3672   case Intrinsic::arm_cls64: {
3673     // cls(x) = if cls(hi(x)) != 31 then cls(hi(x))
3674     //          else 31 + clz(if hi(x) == 0 then lo(x) else not(lo(x)))
3675     const SDValue &Operand = Op.getOperand(1);
3676     const EVT VTy = Op.getValueType();
3677
3678     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3679                              DAG.getConstant(1, dl, VTy));
3680     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VTy, Operand,
3681                              DAG.getConstant(0, dl, VTy));
3682     SDValue Constant0 = DAG.getConstant(0, dl, VTy);
3683     SDValue Constant1 = DAG.getConstant(1, dl, VTy);
3684     SDValue Constant31 = DAG.getConstant(31, dl, VTy);
3685     SDValue SRAHi = DAG.getNode(ISD::SRA, dl, VTy, Hi, Constant31);
3686     SDValue XORHi = DAG.getNode(ISD::XOR, dl, VTy, SRAHi, Hi);
3687     SDValue SHLHi = DAG.getNode(ISD::SHL, dl, VTy, XORHi, Constant1);
3688     SDValue ORHi = DAG.getNode(ISD::OR, dl, VTy, SHLHi, Constant1);
3689     SDValue CLSHi = DAG.getNode(ISD::CTLZ, dl, VTy, ORHi);
3690     SDValue CheckLo =
3691         DAG.getSetCC(dl, MVT::i1, CLSHi, Constant31, ISD::CondCode::SETEQ);
3692     SDValue HiIsZero =
3693         DAG.getSetCC(dl, MVT::i1, Hi, Constant0, ISD::CondCode::SETEQ);
3694     SDValue AdjustedLo =
3695         DAG.getSelect(dl, VTy, HiIsZero, Lo, DAG.getNOT(dl, Lo, VTy));
3696     SDValue CLZAdjustedLo = DAG.getNode(ISD::CTLZ, dl, VTy, AdjustedLo);
3697     SDValue Result =
3698         DAG.getSelect(dl, VTy, CheckLo,
3699                       DAG.getNode(ISD::ADD, dl, VTy, CLZAdjustedLo, Constant31), CLSHi);
3700     return Result;
3701   }
3702   case Intrinsic::eh_sjlj_lsda: {
3703     MachineFunction &MF = DAG.getMachineFunction();
3704     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3705     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3706     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3707     SDValue CPAddr;
3708     bool IsPositionIndependent = isPositionIndependent();
3709     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3710     ARMConstantPoolValue *CPV =
3711       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3712                                       ARMCP::CPLSDA, PCAdj);
3713     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3714     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3715     SDValue Result = DAG.getLoad(
3716         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3717         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3718
3719     if (IsPositionIndependent) {
3720       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3721       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3722     }
3723     return Result;
3724   }
3725   case Intrinsic::arm_neon_vabs:
3726     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3727                         Op.getOperand(1));
3728   case Intrinsic::arm_neon_vmulls:
3729   case Intrinsic::arm_neon_vmullu: {
3730     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3731       ? ARMISD::VMULLs : ARMISD::VMULLu;
3732     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3733                        Op.getOperand(1), Op.getOperand(2));
3734   }
3735   case Intrinsic::arm_neon_vminnm:
3736   case Intrinsic::arm_neon_vmaxnm: {
3737     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3738       ? ISD::FMINNUM : ISD::FMAXNUM;
3739     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3740                        Op.getOperand(1), Op.getOperand(2));
3741   }
3742   case Intrinsic::arm_neon_vminu:
3743   case Intrinsic::arm_neon_vmaxu: {
3744     if (Op.getValueType().isFloatingPoint())
3745       return SDValue();
3746     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3747       ? ISD::UMIN : ISD::UMAX;
3748     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3749                          Op.getOperand(1), Op.getOperand(2));
3750   }
3751   case Intrinsic::arm_neon_vmins:
3752   case Intrinsic::arm_neon_vmaxs: {
3753     // v{min,max}s is overloaded between signed integers and floats.
3754     if (!Op.getValueType().isFloatingPoint()) {
3755       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3756         ? ISD::SMIN : ISD::SMAX;
3757       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3758                          Op.getOperand(1), Op.getOperand(2));
3759     }
3760     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3761       ? ISD::FMINIMUM : ISD::FMAXIMUM;
3762     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3763                        Op.getOperand(1), Op.getOperand(2));
3764   }
3765   case Intrinsic::arm_neon_vtbl1:
3766     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3767                        Op.getOperand(1), Op.getOperand(2));
3768   case Intrinsic::arm_neon_vtbl2:
3769     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3770                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3771   case Intrinsic::arm_mve_pred_i2v:
3772   case Intrinsic::arm_mve_pred_v2i:
3773     return DAG.getNode(ARMISD::PREDICATE_CAST, SDLoc(Op), Op.getValueType(),
3774                        Op.getOperand(1));
3775   }
3776 }
3777
3778 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3779                                  const ARMSubtarget *Subtarget) {
3780   SDLoc dl(Op);
3781   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3782   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3783   if (SSID == SyncScope::SingleThread)
3784     return Op;
3785
3786   if (!Subtarget->hasDataBarrier()) {
3787     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3788     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3789     // here.
3790     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3791            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3792     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3793                        DAG.getConstant(0, dl, MVT::i32));
3794   }
3795
3796   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3797   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3798   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3799   if (Subtarget->isMClass()) {
3800     // Only a full system barrier exists in the M-class architectures.
3801     Domain = ARM_MB::SY;
3802   } else if (Subtarget->preferISHSTBarriers() &&
3803              Ord == AtomicOrdering::Release) {
3804     // Swift happens to implement ISHST barriers in a way that's compatible with
3805     // Release semantics but weaker than ISH so we'd be fools not to use
3806     // it. Beware: other processors probably don't!
3807     Domain = ARM_MB::ISHST;
3808   }
3809
3810   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3811                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3812                      DAG.getConstant(Domain, dl, MVT::i32));
3813 }
3814
3815 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3816                              const ARMSubtarget *Subtarget) {
3817   // ARM pre v5TE and Thumb1 does not have preload instructions.
3818   if (!(Subtarget->isThumb2() ||
3819         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3820     // Just preserve the chain.
3821     return Op.getOperand(0);
3822
3823   SDLoc dl(Op);
3824   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3825   if (!isRead &&
3826       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3827     // ARMv7 with MP extension has PLDW.
3828     return Op.getOperand(0);
3829
3830   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3831   if (Subtarget->isThumb()) {
3832     // Invert the bits.
3833     isRead = ~isRead & 1;
3834     isData = ~isData & 1;
3835   }
3836
3837   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3838                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3839                      DAG.getConstant(isData, dl, MVT::i32));
3840 }
3841
3842 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3843   MachineFunction &MF = DAG.getMachineFunction();
3844   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3845
3846   // vastart just stores the address of the VarArgsFrameIndex slot into the
3847   // memory location argument.
3848   SDLoc dl(Op);
3849   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3850   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3851   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3852   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3853                       MachinePointerInfo(SV));
3854 }
3855
3856 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3857                                                 CCValAssign &NextVA,
3858                                                 SDValue &Root,
3859                                                 SelectionDAG &DAG,
3860                                                 const SDLoc &dl) const {
3861   MachineFunction &MF = DAG.getMachineFunction();
3862   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3863
3864   const TargetRegisterClass *RC;
3865   if (AFI->isThumb1OnlyFunction())
3866     RC = &ARM::tGPRRegClass;
3867   else
3868     RC = &ARM::GPRRegClass;
3869
3870   // Transform the arguments stored in physical registers into virtual ones.
3871   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3872   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3873
3874   SDValue ArgValue2;
3875   if (NextVA.isMemLoc()) {
3876     MachineFrameInfo &MFI = MF.getFrameInfo();
3877     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3878
3879     // Create load node to retrieve arguments from the stack.
3880     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3881     ArgValue2 = DAG.getLoad(
3882         MVT::i32, dl, Root, FIN,
3883         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3884   } else {
3885     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3886     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3887   }
3888   if (!Subtarget->isLittle())
3889     std::swap (ArgValue, ArgValue2);
3890   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3891 }
3892
3893 // The remaining GPRs hold either the beginning of variable-argument
3894 // data, or the beginning of an aggregate passed by value (usually
3895 // byval).  Either way, we allocate stack slots adjacent to the data
3896 // provided by our caller, and store the unallocated registers there.
3897 // If this is a variadic function, the va_list pointer will begin with
3898 // these values; otherwise, this reassembles a (byval) structure that
3899 // was split between registers and memory.
3900 // Return: The frame index registers were stored into.
3901 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3902                                       const SDLoc &dl, SDValue &Chain,
3903                                       const Value *OrigArg,
3904                                       unsigned InRegsParamRecordIdx,
3905                                       int ArgOffset, unsigned ArgSize) const {
3906   // Currently, two use-cases possible:
3907   // Case #1. Non-var-args function, and we meet first byval parameter.
3908   //          Setup first unallocated register as first byval register;
3909   //          eat all remained registers
3910   //          (these two actions are performed by HandleByVal method).
3911   //          Then, here, we initialize stack frame with
3912   //          "store-reg" instructions.
3913   // Case #2. Var-args function, that doesn't contain byval parameters.
3914   //          The same: eat all remained unallocated registers,
3915   //          initialize stack frame.
3916
3917   MachineFunction &MF = DAG.getMachineFunction();
3918   MachineFrameInfo &MFI = MF.getFrameInfo();
3919   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3920   unsigned RBegin, REnd;
3921   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3922     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3923   } else {
3924     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3925     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3926     REnd = ARM::R4;
3927   }
3928
3929   if (REnd != RBegin)
3930     ArgOffset = -4 * (ARM::R4 - RBegin);
3931
3932   auto PtrVT = getPointerTy(DAG.getDataLayout());
3933   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3934   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3935
3936   SmallVector<SDValue, 4> MemOps;
3937   const TargetRegisterClass *RC =
3938       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3939
3940   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3941     unsigned VReg = MF.addLiveIn(Reg, RC);
3942     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3943     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3944                                  MachinePointerInfo(OrigArg, 4 * i));
3945     MemOps.push_back(Store);
3946     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3947   }
3948
3949   if (!MemOps.empty())
3950     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3951   return FrameIndex;
3952 }
3953
3954 // Setup stack frame, the va_list pointer will start from.
3955 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3956                                              const SDLoc &dl, SDValue &Chain,
3957                                              unsigned ArgOffset,
3958                                              unsigned TotalArgRegsSaveSize,
3959                                              bool ForceMutable) const {
3960   MachineFunction &MF = DAG.getMachineFunction();
3961   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3962
3963   // Try to store any remaining integer argument regs
3964   // to their spots on the stack so that they may be loaded by dereferencing
3965   // the result of va_next.
3966   // If there is no regs to be stored, just point address after last
3967   // argument passed via stack.
3968   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3969                                   CCInfo.getInRegsParamsCount(),
3970                                   CCInfo.getNextStackOffset(),
3971                                   std::max(4U, TotalArgRegsSaveSize));
3972   AFI->setVarArgsFrameIndex(FrameIndex);
3973 }
3974
3975 SDValue ARMTargetLowering::LowerFormalArguments(
3976     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3977     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3978     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3979   MachineFunction &MF = DAG.getMachineFunction();
3980   MachineFrameInfo &MFI = MF.getFrameInfo();
3981
3982   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3983
3984   // Assign locations to all of the incoming arguments.
3985   SmallVector<CCValAssign, 16> ArgLocs;
3986   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3987                  *DAG.getContext());
3988   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3989
3990   SmallVector<SDValue, 16> ArgValues;
3991   SDValue ArgValue;
3992   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3993   unsigned CurArgIdx = 0;
3994
3995   // Initially ArgRegsSaveSize is zero.
3996   // Then we increase this value each time we meet byval parameter.
3997   // We also increase this value in case of varargs function.
3998   AFI->setArgRegsSaveSize(0);
3999
4000   // Calculate the amount of stack space that we need to allocate to store
4001   // byval and variadic arguments that are passed in registers.
4002   // We need to know this before we allocate the first byval or variadic
4003   // argument, as they will be allocated a stack slot below the CFA (Canonical
4004   // Frame Address, the stack pointer at entry to the function).
4005   unsigned ArgRegBegin = ARM::R4;
4006   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4007     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
4008       break;
4009
4010     CCValAssign &VA = ArgLocs[i];
4011     unsigned Index = VA.getValNo();
4012     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
4013     if (!Flags.isByVal())
4014       continue;
4015
4016     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
4017     unsigned RBegin, REnd;
4018     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
4019     ArgRegBegin = std::min(ArgRegBegin, RBegin);
4020
4021     CCInfo.nextInRegsParam();
4022   }
4023   CCInfo.rewindByValRegsInfo();
4024
4025   int lastInsIndex = -1;
4026   if (isVarArg && MFI.hasVAStart()) {
4027     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
4028     if (RegIdx != array_lengthof(GPRArgRegs))
4029       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
4030   }
4031
4032   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
4033   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
4034   auto PtrVT = getPointerTy(DAG.getDataLayout());
4035
4036   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
4037     CCValAssign &VA = ArgLocs[i];
4038     if (Ins[VA.getValNo()].isOrigArg()) {
4039       std::advance(CurOrigArg,
4040                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
4041       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
4042     }
4043     // Arguments stored in registers.
4044     if (VA.isRegLoc()) {
4045       EVT RegVT = VA.getLocVT();
4046
4047       if (VA.needsCustom()) {
4048         // f64 and vector types are split up into multiple registers or
4049         // combinations of registers and stack slots.
4050         if (VA.getLocVT() == MVT::v2f64) {
4051           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
4052                                                    Chain, DAG, dl);
4053           VA = ArgLocs[++i]; // skip ahead to next loc
4054           SDValue ArgValue2;
4055           if (VA.isMemLoc()) {
4056             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
4057             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4058             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
4059                                     MachinePointerInfo::getFixedStack(
4060                                         DAG.getMachineFunction(), FI));
4061           } else {
4062             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
4063                                              Chain, DAG, dl);
4064           }
4065           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
4066           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
4067                                  ArgValue, ArgValue1,
4068                                  DAG.getIntPtrConstant(0, dl));
4069           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
4070                                  ArgValue, ArgValue2,
4071                                  DAG.getIntPtrConstant(1, dl));
4072         } else
4073           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
4074       } else {
4075         const TargetRegisterClass *RC;
4076
4077
4078         if (RegVT == MVT::f16)
4079           RC = &ARM::HPRRegClass;
4080         else if (RegVT == MVT::f32)
4081           RC = &ARM::SPRRegClass;
4082         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
4083           RC = &ARM::DPRRegClass;
4084         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
4085           RC = &ARM::QPRRegClass;
4086         else if (RegVT == MVT::i32)
4087           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
4088                                            : &ARM::GPRRegClass;
4089         else
4090           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
4091
4092         // Transform the arguments in physical registers into virtual ones.
4093         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
4094         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
4095
4096         // If this value is passed in r0 and has the returned attribute (e.g.
4097         // C++ 'structors), record this fact for later use.
4098         if (VA.getLocReg() == ARM::R0 && Ins[VA.getValNo()].Flags.isReturned()) {
4099           AFI->setPreservesR0();
4100         }
4101       }
4102
4103       // If this is an 8 or 16-bit value, it is really passed promoted
4104       // to 32 bits.  Insert an assert[sz]ext to capture this, then
4105       // truncate to the right size.
4106       switch (VA.getLocInfo()) {
4107       default: llvm_unreachable("Unknown loc info!");
4108       case CCValAssign::Full: break;
4109       case CCValAssign::BCvt:
4110         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
4111         break;
4112       case CCValAssign::SExt:
4113         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
4114                                DAG.getValueType(VA.getValVT()));
4115         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4116         break;
4117       case CCValAssign::ZExt:
4118         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
4119                                DAG.getValueType(VA.getValVT()));
4120         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
4121         break;
4122       }
4123
4124       InVals.push_back(ArgValue);
4125     } else { // VA.isRegLoc()
4126       // sanity check
4127       assert(VA.isMemLoc());
4128       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
4129
4130       int index = VA.getValNo();
4131
4132       // Some Ins[] entries become multiple ArgLoc[] entries.
4133       // Process them only once.
4134       if (index != lastInsIndex)
4135         {
4136           ISD::ArgFlagsTy Flags = Ins[index].Flags;
4137           // FIXME: For now, all byval parameter objects are marked mutable.
4138           // This can be changed with more analysis.
4139           // In case of tail call optimization mark all arguments mutable.
4140           // Since they could be overwritten by lowering of arguments in case of
4141           // a tail call.
4142           if (Flags.isByVal()) {
4143             assert(Ins[index].isOrigArg() &&
4144                    "Byval arguments cannot be implicit");
4145             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
4146
4147             int FrameIndex = StoreByValRegs(
4148                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
4149                 VA.getLocMemOffset(), Flags.getByValSize());
4150             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
4151             CCInfo.nextInRegsParam();
4152           } else {
4153             unsigned FIOffset = VA.getLocMemOffset();
4154             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
4155                                            FIOffset, true);
4156
4157             // Create load nodes to retrieve arguments from the stack.
4158             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4159             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
4160                                          MachinePointerInfo::getFixedStack(
4161                                              DAG.getMachineFunction(), FI)));
4162           }
4163           lastInsIndex = index;
4164         }
4165     }
4166   }
4167
4168   // varargs
4169   if (isVarArg && MFI.hasVAStart())
4170     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
4171                          CCInfo.getNextStackOffset(),
4172                          TotalArgRegsSaveSize);
4173
4174   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
4175
4176   return Chain;
4177 }
4178
4179 /// isFloatingPointZero - Return true if this is +0.0.
4180 static bool isFloatingPointZero(SDValue Op) {
4181   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
4182     return CFP->getValueAPF().isPosZero();
4183   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
4184     // Maybe this has already been legalized into the constant pool?
4185     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
4186       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
4187       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
4188         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
4189           return CFP->getValueAPF().isPosZero();
4190     }
4191   } else if (Op->getOpcode() == ISD::BITCAST &&
4192              Op->getValueType(0) == MVT::f64) {
4193     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
4194     // created by LowerConstantFP().
4195     SDValue BitcastOp = Op->getOperand(0);
4196     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
4197         isNullConstant(BitcastOp->getOperand(0)))
4198       return true;
4199   }
4200   return false;
4201 }
4202
4203 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
4204 /// the given operands.
4205 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4206                                      SDValue &ARMcc, SelectionDAG &DAG,
4207                                      const SDLoc &dl) const {
4208   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
4209     unsigned C = RHSC->getZExtValue();
4210     if (!isLegalICmpImmediate((int32_t)C)) {
4211       // Constant does not fit, try adjusting it by one.
4212       switch (CC) {
4213       default: break;
4214       case ISD::SETLT:
4215       case ISD::SETGE:
4216         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
4217           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
4218           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4219         }
4220         break;
4221       case ISD::SETULT:
4222       case ISD::SETUGE:
4223         if (C != 0 && isLegalICmpImmediate(C-1)) {
4224           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
4225           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
4226         }
4227         break;
4228       case ISD::SETLE:
4229       case ISD::SETGT:
4230         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
4231           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
4232           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4233         }
4234         break;
4235       case ISD::SETULE:
4236       case ISD::SETUGT:
4237         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
4238           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4239           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
4240         }
4241         break;
4242       }
4243     }
4244   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
4245              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
4246     // In ARM and Thumb-2, the compare instructions can shift their second
4247     // operand.
4248     CC = ISD::getSetCCSwappedOperands(CC);
4249     std::swap(LHS, RHS);
4250   }
4251
4252   // Thumb1 has very limited immediate modes, so turning an "and" into a
4253   // shift can save multiple instructions.
4254   //
4255   // If we have (x & C1), and C1 is an appropriate mask, we can transform it
4256   // into "((x << n) >> n)".  But that isn't necessarily profitable on its
4257   // own. If it's the operand to an unsigned comparison with an immediate,
4258   // we can eliminate one of the shifts: we transform
4259   // "((x << n) >> n) == C2" to "(x << n) == (C2 << n)".
4260   //
4261   // We avoid transforming cases which aren't profitable due to encoding
4262   // details:
4263   //
4264   // 1. C2 fits into the immediate field of a cmp, and the transformed version
4265   // would not; in that case, we're essentially trading one immediate load for
4266   // another.
4267   // 2. C1 is 255 or 65535, so we can use uxtb or uxth.
4268   // 3. C2 is zero; we have other code for this special case.
4269   //
4270   // FIXME: Figure out profitability for Thumb2; we usually can't save an
4271   // instruction, since the AND is always one instruction anyway, but we could
4272   // use narrow instructions in some cases.
4273   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::AND &&
4274       LHS->hasOneUse() && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4275       LHS.getValueType() == MVT::i32 && isa<ConstantSDNode>(RHS) &&
4276       !isSignedIntSetCC(CC)) {
4277     unsigned Mask = cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue();
4278     auto *RHSC = cast<ConstantSDNode>(RHS.getNode());
4279     uint64_t RHSV = RHSC->getZExtValue();
4280     if (isMask_32(Mask) && (RHSV & ~Mask) == 0 && Mask != 255 && Mask != 65535) {
4281       unsigned ShiftBits = countLeadingZeros(Mask);
4282       if (RHSV && (RHSV > 255 || (RHSV << ShiftBits) <= 255)) {
4283         SDValue ShiftAmt = DAG.getConstant(ShiftBits, dl, MVT::i32);
4284         LHS = DAG.getNode(ISD::SHL, dl, MVT::i32, LHS.getOperand(0), ShiftAmt);
4285         RHS = DAG.getConstant(RHSV << ShiftBits, dl, MVT::i32);
4286       }
4287     }
4288   }
4289
4290   // The specific comparison "(x<<c) > 0x80000000U" can be optimized to a
4291   // single "lsls x, c+1".  The shift sets the "C" and "Z" flags the same
4292   // way a cmp would.
4293   // FIXME: Add support for ARM/Thumb2; this would need isel patterns, and
4294   // some tweaks to the heuristics for the previous and->shift transform.
4295   // FIXME: Optimize cases where the LHS isn't a shift.
4296   if (Subtarget->isThumb1Only() && LHS->getOpcode() == ISD::SHL &&
4297       isa<ConstantSDNode>(RHS) &&
4298       cast<ConstantSDNode>(RHS)->getZExtValue() == 0x80000000U &&
4299       CC == ISD::SETUGT && isa<ConstantSDNode>(LHS.getOperand(1)) &&
4300       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() < 31) {
4301     unsigned ShiftAmt =
4302       cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() + 1;
4303     SDValue Shift = DAG.getNode(ARMISD::LSLS, dl,
4304                                 DAG.getVTList(MVT::i32, MVT::i32),
4305                                 LHS.getOperand(0),
4306                                 DAG.getConstant(ShiftAmt, dl, MVT::i32));
4307     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
4308                                      Shift.getValue(1), SDValue());
4309     ARMcc = DAG.getConstant(ARMCC::HI, dl, MVT::i32);
4310     return Chain.getValue(1);
4311   }
4312
4313   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4314
4315   // If the RHS is a constant zero then the V (overflow) flag will never be
4316   // set. This can allow us to simplify GE to PL or LT to MI, which can be
4317   // simpler for other passes (like the peephole optimiser) to deal with.
4318   if (isNullConstant(RHS)) {
4319     switch (CondCode) {
4320       default: break;
4321       case ARMCC::GE:
4322         CondCode = ARMCC::PL;
4323         break;
4324       case ARMCC::LT:
4325         CondCode = ARMCC::MI;
4326         break;
4327     }
4328   }
4329
4330   ARMISD::NodeType CompareType;
4331   switch (CondCode) {
4332   default:
4333     CompareType = ARMISD::CMP;
4334     break;
4335   case ARMCC::EQ:
4336   case ARMCC::NE:
4337     // Uses only Z Flag
4338     CompareType = ARMISD::CMPZ;
4339     break;
4340   }
4341   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4342   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
4343 }
4344
4345 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
4346 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
4347                                      SelectionDAG &DAG, const SDLoc &dl) const {
4348   assert(Subtarget->hasFP64() || RHS.getValueType() != MVT::f64);
4349   SDValue Cmp;
4350   if (!isFloatingPointZero(RHS))
4351     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
4352   else
4353     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
4354   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
4355 }
4356
4357 /// duplicateCmp - Glue values can have only one use, so this function
4358 /// duplicates a comparison node.
4359 SDValue
4360 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
4361   unsigned Opc = Cmp.getOpcode();
4362   SDLoc DL(Cmp);
4363   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
4364     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4365
4366   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
4367   Cmp = Cmp.getOperand(0);
4368   Opc = Cmp.getOpcode();
4369   if (Opc == ARMISD::CMPFP)
4370     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
4371   else {
4372     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
4373     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
4374   }
4375   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
4376 }
4377
4378 // This function returns three things: the arithmetic computation itself
4379 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
4380 // comparison and the condition code define the case in which the arithmetic
4381 // computation *does not* overflow.
4382 std::pair<SDValue, SDValue>
4383 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
4384                                  SDValue &ARMcc) const {
4385   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
4386
4387   SDValue Value, OverflowCmp;
4388   SDValue LHS = Op.getOperand(0);
4389   SDValue RHS = Op.getOperand(1);
4390   SDLoc dl(Op);
4391
4392   // FIXME: We are currently always generating CMPs because we don't support
4393   // generating CMN through the backend. This is not as good as the natural
4394   // CMP case because it causes a register dependency and cannot be folded
4395   // later.
4396
4397   switch (Op.getOpcode()) {
4398   default:
4399     llvm_unreachable("Unknown overflow instruction!");
4400   case ISD::SADDO:
4401     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4402     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
4403     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4404     break;
4405   case ISD::UADDO:
4406     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4407     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
4408     // We do not use it in the USUBO case as Value may not be used.
4409     Value = DAG.getNode(ARMISD::ADDC, dl,
4410                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
4411                 .getValue(0);
4412     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
4413     break;
4414   case ISD::SSUBO:
4415     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
4416     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4417     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4418     break;
4419   case ISD::USUBO:
4420     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
4421     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
4422     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
4423     break;
4424   case ISD::UMULO:
4425     // We generate a UMUL_LOHI and then check if the high word is 0.
4426     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4427     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4428                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4429                         LHS, RHS);
4430     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4431                               DAG.getConstant(0, dl, MVT::i32));
4432     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4433     break;
4434   case ISD::SMULO:
4435     // We generate a SMUL_LOHI and then check if all the bits of the high word
4436     // are the same as the sign bit of the low word.
4437     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4438     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4439                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4440                         LHS, RHS);
4441     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4442                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4443                                           Value.getValue(0),
4444                                           DAG.getConstant(31, dl, MVT::i32)));
4445     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4446     break;
4447   } // switch (...)
4448
4449   return std::make_pair(Value, OverflowCmp);
4450 }
4451
4452 SDValue
4453 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4454   // Let legalize expand this if it isn't a legal type yet.
4455   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4456     return SDValue();
4457
4458   SDValue Value, OverflowCmp;
4459   SDValue ARMcc;
4460   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4461   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4462   SDLoc dl(Op);
4463   // We use 0 and 1 as false and true values.
4464   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4465   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4466   EVT VT = Op.getValueType();
4467
4468   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4469                                  ARMcc, CCR, OverflowCmp);
4470
4471   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4472   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4473 }
4474
4475 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4476                                               SelectionDAG &DAG) {
4477   SDLoc DL(BoolCarry);
4478   EVT CarryVT = BoolCarry.getValueType();
4479
4480   // This converts the boolean value carry into the carry flag by doing
4481   // ARMISD::SUBC Carry, 1
4482   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4483                               DAG.getVTList(CarryVT, MVT::i32),
4484                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
4485   return Carry.getValue(1);
4486 }
4487
4488 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4489                                               SelectionDAG &DAG) {
4490   SDLoc DL(Flags);
4491
4492   // Now convert the carry flag into a boolean carry. We do this
4493   // using ARMISD:ADDE 0, 0, Carry
4494   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4495                      DAG.getConstant(0, DL, MVT::i32),
4496                      DAG.getConstant(0, DL, MVT::i32), Flags);
4497 }
4498
4499 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4500                                              SelectionDAG &DAG) const {
4501   // Let legalize expand this if it isn't a legal type yet.
4502   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4503     return SDValue();
4504
4505   SDValue LHS = Op.getOperand(0);
4506   SDValue RHS = Op.getOperand(1);
4507   SDLoc dl(Op);
4508
4509   EVT VT = Op.getValueType();
4510   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4511   SDValue Value;
4512   SDValue Overflow;
4513   switch (Op.getOpcode()) {
4514   default:
4515     llvm_unreachable("Unknown overflow instruction!");
4516   case ISD::UADDO:
4517     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4518     // Convert the carry flag into a boolean value.
4519     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4520     break;
4521   case ISD::USUBO: {
4522     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4523     // Convert the carry flag into a boolean value.
4524     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4525     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4526     // value. So compute 1 - C.
4527     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4528                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4529     break;
4530   }
4531   }
4532
4533   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4534 }
4535
4536 static SDValue LowerSADDSUBSAT(SDValue Op, SelectionDAG &DAG,
4537                                const ARMSubtarget *Subtarget) {
4538   EVT VT = Op.getValueType();
4539   if (!Subtarget->hasDSP())
4540     return SDValue();
4541   if (!VT.isSimple())
4542     return SDValue();
4543
4544   unsigned NewOpcode;
4545   bool IsAdd = Op->getOpcode() == ISD::SADDSAT;
4546   switch (VT.getSimpleVT().SimpleTy) {
4547   default:
4548     return SDValue();
4549   case MVT::i8:
4550     NewOpcode = IsAdd ? ARMISD::QADD8b : ARMISD::QSUB8b;
4551     break;
4552   case MVT::i16:
4553     NewOpcode = IsAdd ? ARMISD::QADD16b : ARMISD::QSUB16b;
4554     break;
4555   }
4556
4557   SDLoc dl(Op);
4558   SDValue Add =
4559       DAG.getNode(NewOpcode, dl, MVT::i32,
4560                   DAG.getSExtOrTrunc(Op->getOperand(0), dl, MVT::i32),
4561                   DAG.getSExtOrTrunc(Op->getOperand(1), dl, MVT::i32));
4562   return DAG.getNode(ISD::TRUNCATE, dl, VT, Add);
4563 }
4564
4565 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4566   SDValue Cond = Op.getOperand(0);
4567   SDValue SelectTrue = Op.getOperand(1);
4568   SDValue SelectFalse = Op.getOperand(2);
4569   SDLoc dl(Op);
4570   unsigned Opc = Cond.getOpcode();
4571
4572   if (Cond.getResNo() == 1 &&
4573       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4574        Opc == ISD::USUBO)) {
4575     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4576       return SDValue();
4577
4578     SDValue Value, OverflowCmp;
4579     SDValue ARMcc;
4580     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4581     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4582     EVT VT = Op.getValueType();
4583
4584     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4585                    OverflowCmp, DAG);
4586   }
4587
4588   // Convert:
4589   //
4590   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4591   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4592   //
4593   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4594     const ConstantSDNode *CMOVTrue =
4595       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4596     const ConstantSDNode *CMOVFalse =
4597       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4598
4599     if (CMOVTrue && CMOVFalse) {
4600       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4601       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4602
4603       SDValue True;
4604       SDValue False;
4605       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4606         True = SelectTrue;
4607         False = SelectFalse;
4608       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4609         True = SelectFalse;
4610         False = SelectTrue;
4611       }
4612
4613       if (True.getNode() && False.getNode()) {
4614         EVT VT = Op.getValueType();
4615         SDValue ARMcc = Cond.getOperand(2);
4616         SDValue CCR = Cond.getOperand(3);
4617         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4618         assert(True.getValueType() == VT);
4619         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4620       }
4621     }
4622   }
4623
4624   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4625   // undefined bits before doing a full-word comparison with zero.
4626   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4627                      DAG.getConstant(1, dl, Cond.getValueType()));
4628
4629   return DAG.getSelectCC(dl, Cond,
4630                          DAG.getConstant(0, dl, Cond.getValueType()),
4631                          SelectTrue, SelectFalse, ISD::SETNE);
4632 }
4633
4634 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4635                                  bool &swpCmpOps, bool &swpVselOps) {
4636   // Start by selecting the GE condition code for opcodes that return true for
4637   // 'equality'
4638   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4639       CC == ISD::SETULE || CC == ISD::SETGE  || CC == ISD::SETLE)
4640     CondCode = ARMCC::GE;
4641
4642   // and GT for opcodes that return false for 'equality'.
4643   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4644            CC == ISD::SETULT || CC == ISD::SETGT  || CC == ISD::SETLT)
4645     CondCode = ARMCC::GT;
4646
4647   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4648   // to swap the compare operands.
4649   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4650       CC == ISD::SETULT || CC == ISD::SETLE  || CC == ISD::SETLT)
4651     swpCmpOps = true;
4652
4653   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4654   // If we have an unordered opcode, we need to swap the operands to the VSEL
4655   // instruction (effectively negating the condition).
4656   //
4657   // This also has the effect of swapping which one of 'less' or 'greater'
4658   // returns true, so we also swap the compare operands. It also switches
4659   // whether we return true for 'equality', so we compensate by picking the
4660   // opposite condition code to our original choice.
4661   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4662       CC == ISD::SETUGT) {
4663     swpCmpOps = !swpCmpOps;
4664     swpVselOps = !swpVselOps;
4665     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4666   }
4667
4668   // 'ordered' is 'anything but unordered', so use the VS condition code and
4669   // swap the VSEL operands.
4670   if (CC == ISD::SETO) {
4671     CondCode = ARMCC::VS;
4672     swpVselOps = true;
4673   }
4674
4675   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4676   // code and swap the VSEL operands. Also do this if we don't care about the
4677   // unordered case.
4678   if (CC == ISD::SETUNE || CC == ISD::SETNE) {
4679     CondCode = ARMCC::EQ;
4680     swpVselOps = true;
4681   }
4682 }
4683
4684 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4685                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4686                                    SDValue Cmp, SelectionDAG &DAG) const {
4687   if (!Subtarget->hasFP64() && VT == MVT::f64) {
4688     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4689                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4690     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4691                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4692
4693     SDValue TrueLow = TrueVal.getValue(0);
4694     SDValue TrueHigh = TrueVal.getValue(1);
4695     SDValue FalseLow = FalseVal.getValue(0);
4696     SDValue FalseHigh = FalseVal.getValue(1);
4697
4698     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4699                               ARMcc, CCR, Cmp);
4700     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4701                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4702
4703     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4704   } else {
4705     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4706                        Cmp);
4707   }
4708 }
4709
4710 static bool isGTorGE(ISD::CondCode CC) {
4711   return CC == ISD::SETGT || CC == ISD::SETGE;
4712 }
4713
4714 static bool isLTorLE(ISD::CondCode CC) {
4715   return CC == ISD::SETLT || CC == ISD::SETLE;
4716 }
4717
4718 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4719 // All of these conditions (and their <= and >= counterparts) will do:
4720 //          x < k ? k : x
4721 //          x > k ? x : k
4722 //          k < x ? x : k
4723 //          k > x ? k : x
4724 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4725                             const SDValue TrueVal, const SDValue FalseVal,
4726                             const ISD::CondCode CC, const SDValue K) {
4727   return (isGTorGE(CC) &&
4728           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4729          (isLTorLE(CC) &&
4730           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4731 }
4732
4733 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4734 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4735                             const SDValue TrueVal, const SDValue FalseVal,
4736                             const ISD::CondCode CC, const SDValue K) {
4737   return (isGTorGE(CC) &&
4738           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4739          (isLTorLE(CC) &&
4740           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4741 }
4742
4743 // Check if two chained conditionals could be converted into SSAT or USAT.
4744 //
4745 // SSAT can replace a set of two conditional selectors that bound a number to an
4746 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4747 //
4748 //     x < -k ? -k : (x > k ? k : x)
4749 //     x < -k ? -k : (x < k ? x : k)
4750 //     x > -k ? (x > k ? k : x) : -k
4751 //     x < k ? (x < -k ? -k : x) : k
4752 //     etc.
4753 //
4754 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4755 // a power of 2.
4756 //
4757 // It returns true if the conversion can be done, false otherwise.
4758 // Additionally, the variable is returned in parameter V, the constant in K and
4759 // usat is set to true if the conditional represents an unsigned saturation
4760 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4761                                     uint64_t &K, bool &usat) {
4762   SDValue LHS1 = Op.getOperand(0);
4763   SDValue RHS1 = Op.getOperand(1);
4764   SDValue TrueVal1 = Op.getOperand(2);
4765   SDValue FalseVal1 = Op.getOperand(3);
4766   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4767
4768   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4769   if (Op2.getOpcode() != ISD::SELECT_CC)
4770     return false;
4771
4772   SDValue LHS2 = Op2.getOperand(0);
4773   SDValue RHS2 = Op2.getOperand(1);
4774   SDValue TrueVal2 = Op2.getOperand(2);
4775   SDValue FalseVal2 = Op2.getOperand(3);
4776   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4777
4778   // Find out which are the constants and which are the variables
4779   // in each conditional
4780   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4781                                                         ? &RHS1
4782                                                         : nullptr;
4783   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4784                                                         ? &RHS2
4785                                                         : nullptr;
4786   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4787   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4788   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4789   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4790
4791   // We must detect cases where the original operations worked with 16- or
4792   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4793   // must work with sign-extended values but the select operations return
4794   // the original non-extended value.
4795   SDValue V2TmpReg = V2Tmp;
4796   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4797     V2TmpReg = V2Tmp->getOperand(0);
4798
4799   // Check that the registers and the constants have the correct values
4800   // in both conditionals
4801   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4802       V2TmpReg != V2)
4803     return false;
4804
4805   // Figure out which conditional is saturating the lower/upper bound.
4806   const SDValue *LowerCheckOp =
4807       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4808           ? &Op
4809           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4810                 ? &Op2
4811                 : nullptr;
4812   const SDValue *UpperCheckOp =
4813       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4814           ? &Op
4815           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4816                 ? &Op2
4817                 : nullptr;
4818
4819   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4820     return false;
4821
4822   // Check that the constant in the lower-bound check is
4823   // the opposite of the constant in the upper-bound check
4824   // in 1's complement.
4825   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4826   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4827   int64_t PosVal = std::max(Val1, Val2);
4828   int64_t NegVal = std::min(Val1, Val2);
4829
4830   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4831        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4832       isPowerOf2_64(PosVal + 1)) {
4833
4834     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4835     if (Val1 == ~Val2)
4836       usat = false;
4837     else if (NegVal == 0)
4838       usat = true;
4839     else
4840       return false;
4841
4842     V = V2;
4843     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4844
4845     return true;
4846   }
4847
4848   return false;
4849 }
4850
4851 // Check if a condition of the type x < k ? k : x can be converted into a
4852 // bit operation instead of conditional moves.
4853 // Currently this is allowed given:
4854 // - The conditions and values match up
4855 // - k is 0 or -1 (all ones)
4856 // This function will not check the last condition, thats up to the caller
4857 // It returns true if the transformation can be made, and in such case
4858 // returns x in V, and k in SatK.
4859 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4860                                          SDValue &SatK)
4861 {
4862   SDValue LHS = Op.getOperand(0);
4863   SDValue RHS = Op.getOperand(1);
4864   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4865   SDValue TrueVal = Op.getOperand(2);
4866   SDValue FalseVal = Op.getOperand(3);
4867
4868   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4869                                                ? &RHS
4870                                                : nullptr;
4871
4872   // No constant operation in comparison, early out
4873   if (!K)
4874     return false;
4875
4876   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4877   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4878   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4879
4880   // If the constant on left and right side, or variable on left and right,
4881   // does not match, early out
4882   if (*K != KTmp || V != VTmp)
4883     return false;
4884
4885   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4886     SatK = *K;
4887     return true;
4888   }
4889
4890   return false;
4891 }
4892
4893 bool ARMTargetLowering::isUnsupportedFloatingType(EVT VT) const {
4894   if (VT == MVT::f32)
4895     return !Subtarget->hasVFP2Base();
4896   if (VT == MVT::f64)
4897     return !Subtarget->hasFP64();
4898   if (VT == MVT::f16)
4899     return !Subtarget->hasFullFP16();
4900   return false;
4901 }
4902
4903 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4904   EVT VT = Op.getValueType();
4905   SDLoc dl(Op);
4906
4907   // Try to convert two saturating conditional selects into a single SSAT
4908   SDValue SatValue;
4909   uint64_t SatConstant;
4910   bool SatUSat;
4911   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4912       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4913     if (SatUSat)
4914       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4915                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4916     else
4917       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4918                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4919   }
4920
4921   // Try to convert expressions of the form x < k ? k : x (and similar forms)
4922   // into more efficient bit operations, which is possible when k is 0 or -1
4923   // On ARM and Thumb-2 which have flexible operand 2 this will result in
4924   // single instructions. On Thumb the shift and the bit operation will be two
4925   // instructions.
4926   // Only allow this transformation on full-width (32-bit) operations
4927   SDValue LowerSatConstant;
4928   if (VT == MVT::i32 &&
4929       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4930     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4931                                  DAG.getConstant(31, dl, VT));
4932     if (isNullConstant(LowerSatConstant)) {
4933       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4934                                       DAG.getAllOnesConstant(dl, VT));
4935       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4936     } else if (isAllOnesConstant(LowerSatConstant))
4937       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4938   }
4939
4940   SDValue LHS = Op.getOperand(0);
4941   SDValue RHS = Op.getOperand(1);
4942   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4943   SDValue TrueVal = Op.getOperand(2);
4944   SDValue FalseVal = Op.getOperand(3);
4945   ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FalseVal);
4946   ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TrueVal);
4947
4948   if (Subtarget->hasV8_1MMainlineOps() && CFVal && CTVal &&
4949       LHS.getValueType() == MVT::i32 && RHS.getValueType() == MVT::i32) {
4950     unsigned TVal = CTVal->getZExtValue();
4951     unsigned FVal = CFVal->getZExtValue();
4952     unsigned Opcode = 0;
4953
4954     if (TVal == ~FVal) {
4955       Opcode = ARMISD::CSINV;
4956     } else if (TVal == ~FVal + 1) {
4957       Opcode = ARMISD::CSNEG;
4958     } else if (TVal + 1 == FVal) {
4959       Opcode = ARMISD::CSINC;
4960     } else if (TVal == FVal + 1) {
4961       Opcode = ARMISD::CSINC;
4962       std::swap(TrueVal, FalseVal);
4963       std::swap(TVal, FVal);
4964       CC = ISD::getSetCCInverse(CC, LHS.getValueType());
4965     }
4966
4967     if (Opcode) {
4968       // If one of the constants is cheaper than another, materialise the
4969       // cheaper one and let the csel generate the other.
4970       if (Opcode != ARMISD::CSINC &&
4971           HasLowerConstantMaterializationCost(FVal, TVal, Subtarget)) {
4972         std::swap(TrueVal, FalseVal);
4973         std::swap(TVal, FVal);
4974         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
4975       }
4976
4977       // Attempt to use ZR checking TVal is 0, possibly inverting the condition
4978       // to get there. CSINC not is invertable like the other two (~(~a) == a,
4979       // -(-a) == a, but (a+1)+1 != a).
4980       if (FVal == 0 && Opcode != ARMISD::CSINC) {
4981         std::swap(TrueVal, FalseVal);
4982         std::swap(TVal, FVal);
4983         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
4984       }
4985       if (TVal == 0)
4986         TrueVal = DAG.getRegister(ARM::ZR, MVT::i32);
4987
4988       // Drops F's value because we can get it by inverting/negating TVal.
4989       FalseVal = TrueVal;
4990
4991       SDValue ARMcc;
4992       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4993       EVT VT = TrueVal.getValueType();
4994       return DAG.getNode(Opcode, dl, VT, TrueVal, FalseVal, ARMcc, Cmp);
4995     }
4996   }
4997
4998   if (isUnsupportedFloatingType(LHS.getValueType())) {
4999     DAG.getTargetLoweringInfo().softenSetCCOperands(
5000         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5001
5002     // If softenSetCCOperands only returned one value, we should compare it to
5003     // zero.
5004     if (!RHS.getNode()) {
5005       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5006       CC = ISD::SETNE;
5007     }
5008   }
5009
5010   if (LHS.getValueType() == MVT::i32) {
5011     // Try to generate VSEL on ARMv8.
5012     // The VSEL instruction can't use all the usual ARM condition
5013     // codes: it only has two bits to select the condition code, so it's
5014     // constrained to use only GE, GT, VS and EQ.
5015     //
5016     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
5017     // swap the operands of the previous compare instruction (effectively
5018     // inverting the compare condition, swapping 'less' and 'greater') and
5019     // sometimes need to swap the operands to the VSEL (which inverts the
5020     // condition in the sense of firing whenever the previous condition didn't)
5021     if (Subtarget->hasFPARMv8Base() && (TrueVal.getValueType() == MVT::f16 ||
5022                                         TrueVal.getValueType() == MVT::f32 ||
5023                                         TrueVal.getValueType() == MVT::f64)) {
5024       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5025       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
5026           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
5027         CC = ISD::getSetCCInverse(CC, LHS.getValueType());
5028         std::swap(TrueVal, FalseVal);
5029       }
5030     }
5031
5032     SDValue ARMcc;
5033     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5034     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5035     // Choose GE over PL, which vsel does now support
5036     if (cast<ConstantSDNode>(ARMcc)->getZExtValue() == ARMCC::PL)
5037       ARMcc = DAG.getConstant(ARMCC::GE, dl, MVT::i32);
5038     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5039   }
5040
5041   ARMCC::CondCodes CondCode, CondCode2;
5042   FPCCToARMCC(CC, CondCode, CondCode2);
5043
5044   // Normalize the fp compare. If RHS is zero we prefer to keep it there so we
5045   // match CMPFPw0 instead of CMPFP, though we don't do this for f16 because we
5046   // must use VSEL (limited condition codes), due to not having conditional f16
5047   // moves.
5048   if (Subtarget->hasFPARMv8Base() &&
5049       !(isFloatingPointZero(RHS) && TrueVal.getValueType() != MVT::f16) &&
5050       (TrueVal.getValueType() == MVT::f16 ||
5051        TrueVal.getValueType() == MVT::f32 ||
5052        TrueVal.getValueType() == MVT::f64)) {
5053     bool swpCmpOps = false;
5054     bool swpVselOps = false;
5055     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
5056
5057     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
5058         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
5059       if (swpCmpOps)
5060         std::swap(LHS, RHS);
5061       if (swpVselOps)
5062         std::swap(TrueVal, FalseVal);
5063     }
5064   }
5065
5066   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5067   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5068   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5069   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
5070   if (CondCode2 != ARMCC::AL) {
5071     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
5072     // FIXME: Needs another CMP because flag can have but one use.
5073     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
5074     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
5075   }
5076   return Result;
5077 }
5078
5079 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
5080 /// to morph to an integer compare sequence.
5081 static bool canChangeToInt(SDValue Op, bool &SeenZero,
5082                            const ARMSubtarget *Subtarget) {
5083   SDNode *N = Op.getNode();
5084   if (!N->hasOneUse())
5085     // Otherwise it requires moving the value from fp to integer registers.
5086     return false;
5087   if (!N->getNumValues())
5088     return false;
5089   EVT VT = Op.getValueType();
5090   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
5091     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
5092     // vmrs are very slow, e.g. cortex-a8.
5093     return false;
5094
5095   if (isFloatingPointZero(Op)) {
5096     SeenZero = true;
5097     return true;
5098   }
5099   return ISD::isNormalLoad(N);
5100 }
5101
5102 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
5103   if (isFloatingPointZero(Op))
5104     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
5105
5106   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
5107     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
5108                        Ld->getPointerInfo(), Ld->getAlignment(),
5109                        Ld->getMemOperand()->getFlags());
5110
5111   llvm_unreachable("Unknown VFP cmp argument!");
5112 }
5113
5114 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
5115                            SDValue &RetVal1, SDValue &RetVal2) {
5116   SDLoc dl(Op);
5117
5118   if (isFloatingPointZero(Op)) {
5119     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
5120     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
5121     return;
5122   }
5123
5124   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
5125     SDValue Ptr = Ld->getBasePtr();
5126     RetVal1 =
5127         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
5128                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
5129
5130     EVT PtrType = Ptr.getValueType();
5131     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
5132     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
5133                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
5134     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
5135                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
5136                           Ld->getMemOperand()->getFlags());
5137     return;
5138   }
5139
5140   llvm_unreachable("Unknown VFP cmp argument!");
5141 }
5142
5143 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
5144 /// f32 and even f64 comparisons to integer ones.
5145 SDValue
5146 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
5147   SDValue Chain = Op.getOperand(0);
5148   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5149   SDValue LHS = Op.getOperand(2);
5150   SDValue RHS = Op.getOperand(3);
5151   SDValue Dest = Op.getOperand(4);
5152   SDLoc dl(Op);
5153
5154   bool LHSSeenZero = false;
5155   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
5156   bool RHSSeenZero = false;
5157   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
5158   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
5159     // If unsafe fp math optimization is enabled and there are no other uses of
5160     // the CMP operands, and the condition code is EQ or NE, we can optimize it
5161     // to an integer comparison.
5162     if (CC == ISD::SETOEQ)
5163       CC = ISD::SETEQ;
5164     else if (CC == ISD::SETUNE)
5165       CC = ISD::SETNE;
5166
5167     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5168     SDValue ARMcc;
5169     if (LHS.getValueType() == MVT::f32) {
5170       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5171                         bitcastf32Toi32(LHS, DAG), Mask);
5172       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
5173                         bitcastf32Toi32(RHS, DAG), Mask);
5174       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5175       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5176       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5177                          Chain, Dest, ARMcc, CCR, Cmp);
5178     }
5179
5180     SDValue LHS1, LHS2;
5181     SDValue RHS1, RHS2;
5182     expandf64Toi32(LHS, DAG, LHS1, LHS2);
5183     expandf64Toi32(RHS, DAG, RHS1, RHS2);
5184     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
5185     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
5186     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
5187     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5188     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5189     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
5190     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
5191   }
5192
5193   return SDValue();
5194 }
5195
5196 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
5197   SDValue Chain = Op.getOperand(0);
5198   SDValue Cond = Op.getOperand(1);
5199   SDValue Dest = Op.getOperand(2);
5200   SDLoc dl(Op);
5201
5202   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5203   // instruction.
5204   unsigned Opc = Cond.getOpcode();
5205   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5206                       !Subtarget->isThumb1Only();
5207   if (Cond.getResNo() == 1 &&
5208       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5209        Opc == ISD::USUBO || OptimizeMul)) {
5210     // Only lower legal XALUO ops.
5211     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
5212       return SDValue();
5213
5214     // The actual operation with overflow check.
5215     SDValue Value, OverflowCmp;
5216     SDValue ARMcc;
5217     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
5218
5219     // Reverse the condition code.
5220     ARMCC::CondCodes CondCode =
5221         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5222     CondCode = ARMCC::getOppositeCondition(CondCode);
5223     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5224     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5225
5226     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5227                        OverflowCmp);
5228   }
5229
5230   return SDValue();
5231 }
5232
5233 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
5234   SDValue Chain = Op.getOperand(0);
5235   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
5236   SDValue LHS = Op.getOperand(2);
5237   SDValue RHS = Op.getOperand(3);
5238   SDValue Dest = Op.getOperand(4);
5239   SDLoc dl(Op);
5240
5241   if (isUnsupportedFloatingType(LHS.getValueType())) {
5242     DAG.getTargetLoweringInfo().softenSetCCOperands(
5243         DAG, LHS.getValueType(), LHS, RHS, CC, dl, LHS, RHS);
5244
5245     // If softenSetCCOperands only returned one value, we should compare it to
5246     // zero.
5247     if (!RHS.getNode()) {
5248       RHS = DAG.getConstant(0, dl, LHS.getValueType());
5249       CC = ISD::SETNE;
5250     }
5251   }
5252
5253   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
5254   // instruction.
5255   unsigned Opc = LHS.getOpcode();
5256   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
5257                       !Subtarget->isThumb1Only();
5258   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
5259       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
5260        Opc == ISD::USUBO || OptimizeMul) &&
5261       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5262     // Only lower legal XALUO ops.
5263     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
5264       return SDValue();
5265
5266     // The actual operation with overflow check.
5267     SDValue Value, OverflowCmp;
5268     SDValue ARMcc;
5269     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
5270
5271     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
5272       // Reverse the condition code.
5273       ARMCC::CondCodes CondCode =
5274           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
5275       CondCode = ARMCC::getOppositeCondition(CondCode);
5276       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
5277     }
5278     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5279
5280     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
5281                        OverflowCmp);
5282   }
5283
5284   if (LHS.getValueType() == MVT::i32) {
5285     SDValue ARMcc;
5286     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
5287     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5288     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
5289                        Chain, Dest, ARMcc, CCR, Cmp);
5290   }
5291
5292   if (getTargetMachine().Options.UnsafeFPMath &&
5293       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
5294        CC == ISD::SETNE || CC == ISD::SETUNE)) {
5295     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
5296       return Result;
5297   }
5298
5299   ARMCC::CondCodes CondCode, CondCode2;
5300   FPCCToARMCC(CC, CondCode, CondCode2);
5301
5302   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
5303   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
5304   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5305   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
5306   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
5307   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5308   if (CondCode2 != ARMCC::AL) {
5309     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
5310     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
5311     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
5312   }
5313   return Res;
5314 }
5315
5316 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
5317   SDValue Chain = Op.getOperand(0);
5318   SDValue Table = Op.getOperand(1);
5319   SDValue Index = Op.getOperand(2);
5320   SDLoc dl(Op);
5321
5322   EVT PTy = getPointerTy(DAG.getDataLayout());
5323   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
5324   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
5325   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
5326   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
5327   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
5328   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
5329     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
5330     // which does another jump to the destination. This also makes it easier
5331     // to translate it to TBB / TBH later (Thumb2 only).
5332     // FIXME: This might not work if the function is extremely large.
5333     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
5334                        Addr, Op.getOperand(2), JTI);
5335   }
5336   if (isPositionIndependent() || Subtarget->isROPI()) {
5337     Addr =
5338         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
5339                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5340     Chain = Addr.getValue(1);
5341     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
5342     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5343   } else {
5344     Addr =
5345         DAG.getLoad(PTy, dl, Chain, Addr,
5346                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
5347     Chain = Addr.getValue(1);
5348     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
5349   }
5350 }
5351
5352 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
5353   EVT VT = Op.getValueType();
5354   SDLoc dl(Op);
5355
5356   if (Op.getValueType().getVectorElementType() == MVT::i32) {
5357     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
5358       return Op;
5359     return DAG.UnrollVectorOp(Op.getNode());
5360   }
5361
5362   const bool HasFullFP16 =
5363     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5364
5365   EVT NewTy;
5366   const EVT OpTy = Op.getOperand(0).getValueType();
5367   if (OpTy == MVT::v4f32)
5368     NewTy = MVT::v4i32;
5369   else if (OpTy == MVT::v4f16 && HasFullFP16)
5370     NewTy = MVT::v4i16;
5371   else if (OpTy == MVT::v8f16 && HasFullFP16)
5372     NewTy = MVT::v8i16;
5373   else
5374     llvm_unreachable("Invalid type for custom lowering!");
5375
5376   if (VT != MVT::v4i16 && VT != MVT::v8i16)
5377     return DAG.UnrollVectorOp(Op.getNode());
5378
5379   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
5380   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
5381 }
5382
5383 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
5384   EVT VT = Op.getValueType();
5385   if (VT.isVector())
5386     return LowerVectorFP_TO_INT(Op, DAG);
5387
5388   bool IsStrict = Op->isStrictFPOpcode();
5389   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
5390
5391   if (isUnsupportedFloatingType(SrcVal.getValueType())) {
5392     RTLIB::Libcall LC;
5393     if (Op.getOpcode() == ISD::FP_TO_SINT ||
5394         Op.getOpcode() == ISD::STRICT_FP_TO_SINT)
5395       LC = RTLIB::getFPTOSINT(SrcVal.getValueType(),
5396                               Op.getValueType());
5397     else
5398       LC = RTLIB::getFPTOUINT(SrcVal.getValueType(),
5399                               Op.getValueType());
5400     SDLoc Loc(Op);
5401     MakeLibCallOptions CallOptions;
5402     SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
5403     SDValue Result;
5404     std::tie(Result, Chain) = makeLibCall(DAG, LC, Op.getValueType(), SrcVal,
5405                                           CallOptions, Loc, Chain);
5406     return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
5407   }
5408
5409   // FIXME: Remove this when we have strict fp instruction selection patterns
5410   if (IsStrict) {
5411     DAG.mutateStrictFPToFP(Op.getNode());
5412   }
5413
5414   return Op;
5415 }
5416
5417 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5418   EVT VT = Op.getValueType();
5419   SDLoc dl(Op);
5420
5421   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
5422     if (VT.getVectorElementType() == MVT::f32)
5423       return Op;
5424     return DAG.UnrollVectorOp(Op.getNode());
5425   }
5426
5427   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
5428           Op.getOperand(0).getValueType() == MVT::v8i16) &&
5429          "Invalid type for custom lowering!");
5430
5431   const bool HasFullFP16 =
5432     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
5433
5434   EVT DestVecType;
5435   if (VT == MVT::v4f32)
5436     DestVecType = MVT::v4i32;
5437   else if (VT == MVT::v4f16 && HasFullFP16)
5438     DestVecType = MVT::v4i16;
5439   else if (VT == MVT::v8f16 && HasFullFP16)
5440     DestVecType = MVT::v8i16;
5441   else
5442     return DAG.UnrollVectorOp(Op.getNode());
5443
5444   unsigned CastOpc;
5445   unsigned Opc;
5446   switch (Op.getOpcode()) {
5447   default: llvm_unreachable("Invalid opcode!");
5448   case ISD::SINT_TO_FP:
5449     CastOpc = ISD::SIGN_EXTEND;
5450     Opc = ISD::SINT_TO_FP;
5451     break;
5452   case ISD::UINT_TO_FP:
5453     CastOpc = ISD::ZERO_EXTEND;
5454     Opc = ISD::UINT_TO_FP;
5455     break;
5456   }
5457
5458   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
5459   return DAG.getNode(Opc, dl, VT, Op);
5460 }
5461
5462 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
5463   EVT VT = Op.getValueType();
5464   if (VT.isVector())
5465     return LowerVectorINT_TO_FP(Op, DAG);
5466   if (isUnsupportedFloatingType(VT)) {
5467     RTLIB::Libcall LC;
5468     if (Op.getOpcode() == ISD::SINT_TO_FP)
5469       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
5470                               Op.getValueType());
5471     else
5472       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
5473                               Op.getValueType());
5474     MakeLibCallOptions CallOptions;
5475     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
5476                        CallOptions, SDLoc(Op)).first;
5477   }
5478
5479   return Op;
5480 }
5481
5482 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5483   // Implement fcopysign with a fabs and a conditional fneg.
5484   SDValue Tmp0 = Op.getOperand(0);
5485   SDValue Tmp1 = Op.getOperand(1);
5486   SDLoc dl(Op);
5487   EVT VT = Op.getValueType();
5488   EVT SrcVT = Tmp1.getValueType();
5489   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
5490     Tmp0.getOpcode() == ARMISD::VMOVDRR;
5491   bool UseNEON = !InGPR && Subtarget->hasNEON();
5492
5493   if (UseNEON) {
5494     // Use VBSL to copy the sign bit.
5495     unsigned EncodedVal = ARM_AM::createVMOVModImm(0x6, 0x80);
5496     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
5497                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
5498     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
5499     if (VT == MVT::f64)
5500       Mask = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5501                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
5502                          DAG.getConstant(32, dl, MVT::i32));
5503     else /*if (VT == MVT::f32)*/
5504       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
5505     if (SrcVT == MVT::f32) {
5506       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
5507       if (VT == MVT::f64)
5508         Tmp1 = DAG.getNode(ARMISD::VSHLIMM, dl, OpVT,
5509                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
5510                            DAG.getConstant(32, dl, MVT::i32));
5511     } else if (VT == MVT::f32)
5512       Tmp1 = DAG.getNode(ARMISD::VSHRuIMM, dl, MVT::v1i64,
5513                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
5514                          DAG.getConstant(32, dl, MVT::i32));
5515     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
5516     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
5517
5518     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff),
5519                                             dl, MVT::i32);
5520     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
5521     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
5522                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
5523
5524     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
5525                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
5526                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
5527     if (VT == MVT::f32) {
5528       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
5529       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
5530                         DAG.getConstant(0, dl, MVT::i32));
5531     } else {
5532       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
5533     }
5534
5535     return Res;
5536   }
5537
5538   // Bitcast operand 1 to i32.
5539   if (SrcVT == MVT::f64)
5540     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5541                        Tmp1).getValue(1);
5542   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
5543
5544   // Or in the signbit with integer operations.
5545   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5546   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5547   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5548   if (VT == MVT::f32) {
5549     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5550                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5551     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5552                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5553   }
5554
5555   // f64: Or the high part with signbit and then combine two parts.
5556   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5557                      Tmp0);
5558   SDValue Lo = Tmp0.getValue(0);
5559   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5560   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5561   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5562 }
5563
5564 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5565   MachineFunction &MF = DAG.getMachineFunction();
5566   MachineFrameInfo &MFI = MF.getFrameInfo();
5567   MFI.setReturnAddressIsTaken(true);
5568
5569   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5570     return SDValue();
5571
5572   EVT VT = Op.getValueType();
5573   SDLoc dl(Op);
5574   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5575   if (Depth) {
5576     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5577     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5578     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5579                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5580                        MachinePointerInfo());
5581   }
5582
5583   // Return LR, which contains the return address. Mark it an implicit live-in.
5584   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5585   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5586 }
5587
5588 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5589   const ARMBaseRegisterInfo &ARI =
5590     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5591   MachineFunction &MF = DAG.getMachineFunction();
5592   MachineFrameInfo &MFI = MF.getFrameInfo();
5593   MFI.setFrameAddressIsTaken(true);
5594
5595   EVT VT = Op.getValueType();
5596   SDLoc dl(Op);  // FIXME probably not meaningful
5597   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5598   Register FrameReg = ARI.getFrameRegister(MF);
5599   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5600   while (Depth--)
5601     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5602                             MachinePointerInfo());
5603   return FrameAddr;
5604 }
5605
5606 // FIXME? Maybe this could be a TableGen attribute on some registers and
5607 // this table could be generated automatically from RegInfo.
5608 Register ARMTargetLowering::getRegisterByName(const char* RegName, LLT VT,
5609                                               const MachineFunction &MF) const {
5610   Register Reg = StringSwitch<unsigned>(RegName)
5611                        .Case("sp", ARM::SP)
5612                        .Default(0);
5613   if (Reg)
5614     return Reg;
5615   report_fatal_error(Twine("Invalid register name \""
5616                               + StringRef(RegName)  + "\"."));
5617 }
5618
5619 // Result is 64 bit value so split into two 32 bit values and return as a
5620 // pair of values.
5621 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5622                                 SelectionDAG &DAG) {
5623   SDLoc DL(N);
5624
5625   // This function is only supposed to be called for i64 type destination.
5626   assert(N->getValueType(0) == MVT::i64
5627           && "ExpandREAD_REGISTER called for non-i64 type result.");
5628
5629   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5630                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5631                              N->getOperand(0),
5632                              N->getOperand(1));
5633
5634   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5635                     Read.getValue(1)));
5636   Results.push_back(Read.getOperand(0));
5637 }
5638
5639 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5640 /// When \p DstVT, the destination type of \p BC, is on the vector
5641 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5642 /// it might be possible to combine them, such that everything stays on the
5643 /// vector register bank.
5644 /// \p return The node that would replace \p BT, if the combine
5645 /// is possible.
5646 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5647                                                 SelectionDAG &DAG) {
5648   SDValue Op = BC->getOperand(0);
5649   EVT DstVT = BC->getValueType(0);
5650
5651   // The only vector instruction that can produce a scalar (remember,
5652   // since the bitcast was about to be turned into VMOVDRR, the source
5653   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5654   // Moreover, we can do this combine only if there is one use.
5655   // Finally, if the destination type is not a vector, there is not
5656   // much point on forcing everything on the vector bank.
5657   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5658       !Op.hasOneUse())
5659     return SDValue();
5660
5661   // If the index is not constant, we will introduce an additional
5662   // multiply that will stick.
5663   // Give up in that case.
5664   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5665   if (!Index)
5666     return SDValue();
5667   unsigned DstNumElt = DstVT.getVectorNumElements();
5668
5669   // Compute the new index.
5670   const APInt &APIntIndex = Index->getAPIntValue();
5671   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5672   NewIndex *= APIntIndex;
5673   // Check if the new constant index fits into i32.
5674   if (NewIndex.getBitWidth() > 32)
5675     return SDValue();
5676
5677   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5678   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5679   SDLoc dl(Op);
5680   SDValue ExtractSrc = Op.getOperand(0);
5681   EVT VecVT = EVT::getVectorVT(
5682       *DAG.getContext(), DstVT.getScalarType(),
5683       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5684   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5685   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5686                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5687 }
5688
5689 /// ExpandBITCAST - If the target supports VFP, this function is called to
5690 /// expand a bit convert where either the source or destination type is i64 to
5691 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5692 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5693 /// vectors), since the legalizer won't know what to do with that.
5694 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5695                              const ARMSubtarget *Subtarget) {
5696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5697   SDLoc dl(N);
5698   SDValue Op = N->getOperand(0);
5699
5700   // This function is only supposed to be called for i64 types, either as the
5701   // source or destination of the bit convert.
5702   EVT SrcVT = Op.getValueType();
5703   EVT DstVT = N->getValueType(0);
5704   const bool HasFullFP16 = Subtarget->hasFullFP16();
5705
5706   if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5707      // FullFP16: half values are passed in S-registers, and we don't
5708      // need any of the bitcast and moves:
5709      //
5710      // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5711      //   t5: i32 = bitcast t2
5712      // t18: f16 = ARMISD::VMOVhr t5
5713      if (Op.getOpcode() != ISD::CopyFromReg ||
5714          Op.getValueType() != MVT::f32)
5715        return SDValue();
5716
5717      auto Move = N->use_begin();
5718      if (Move->getOpcode() != ARMISD::VMOVhr)
5719        return SDValue();
5720
5721      SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5722      SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5723      DAG.ReplaceAllUsesWith(*Move, &Copy);
5724      return Copy;
5725   }
5726
5727   if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5728     if (!HasFullFP16)
5729       return SDValue();
5730     // SoftFP: read half-precision arguments:
5731     //
5732     // t2: i32,ch = ...
5733     //        t7: i16 = truncate t2 <~~~~ Op
5734     //      t8: f16 = bitcast t7    <~~~~ N
5735     //
5736     if (Op.getOperand(0).getValueType() == MVT::i32)
5737       return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5738                          MVT::f16, Op.getOperand(0));
5739
5740     return SDValue();
5741   }
5742
5743   // Half-precision return values
5744   if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5745     if (!HasFullFP16)
5746       return SDValue();
5747     //
5748     //          t11: f16 = fadd t8, t10
5749     //        t12: i16 = bitcast t11       <~~~ SDNode N
5750     //      t13: i32 = zero_extend t12
5751     //    t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5752     //  t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5753     //
5754     // transform this into:
5755     //
5756     //    t20: i32 = ARMISD::VMOVrh t11
5757     //  t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5758     //
5759     auto ZeroExtend = N->use_begin();
5760     if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5761         ZeroExtend->getValueType(0) != MVT::i32)
5762       return SDValue();
5763
5764     auto Copy = ZeroExtend->use_begin();
5765     if (Copy->getOpcode() == ISD::CopyToReg &&
5766         Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5767       SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5768       DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5769       return Cvt;
5770     }
5771     return SDValue();
5772   }
5773
5774   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5775     return SDValue();
5776
5777   // Turn i64->f64 into VMOVDRR.
5778   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5779     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5780     // if we can combine the bitcast with its source.
5781     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5782       return Val;
5783
5784     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5785                              DAG.getConstant(0, dl, MVT::i32));
5786     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5787                              DAG.getConstant(1, dl, MVT::i32));
5788     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5789                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5790   }
5791
5792   // Turn f64->i64 into VMOVRRD.
5793   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5794     SDValue Cvt;
5795     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5796         SrcVT.getVectorNumElements() > 1)
5797       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5798                         DAG.getVTList(MVT::i32, MVT::i32),
5799                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5800     else
5801       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5802                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5803     // Merge the pieces into a single i64 value.
5804     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5805   }
5806
5807   return SDValue();
5808 }
5809
5810 /// getZeroVector - Returns a vector of specified type with all zero elements.
5811 /// Zero vectors are used to represent vector negation and in those cases
5812 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5813 /// not support i64 elements, so sometimes the zero vectors will need to be
5814 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5815 /// zero vector.
5816 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5817   assert(VT.isVector() && "Expected a vector type");
5818   // The canonical modified immediate encoding of a zero vector is....0!
5819   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5820   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5821   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5822   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5823 }
5824
5825 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5826 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5827 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5828                                                 SelectionDAG &DAG) const {
5829   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5830   EVT VT = Op.getValueType();
5831   unsigned VTBits = VT.getSizeInBits();
5832   SDLoc dl(Op);
5833   SDValue ShOpLo = Op.getOperand(0);
5834   SDValue ShOpHi = Op.getOperand(1);
5835   SDValue ShAmt  = Op.getOperand(2);
5836   SDValue ARMcc;
5837   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5838   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5839
5840   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5841
5842   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5843                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5844   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5845   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5846                                    DAG.getConstant(VTBits, dl, MVT::i32));
5847   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5848   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5849   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5850   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5851                             ISD::SETGE, ARMcc, DAG, dl);
5852   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5853                            ARMcc, CCR, CmpLo);
5854
5855   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5856   SDValue HiBigShift = Opc == ISD::SRA
5857                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5858                                          DAG.getConstant(VTBits - 1, dl, VT))
5859                            : DAG.getConstant(0, dl, VT);
5860   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5861                             ISD::SETGE, ARMcc, DAG, dl);
5862   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5863                            ARMcc, CCR, CmpHi);
5864
5865   SDValue Ops[2] = { Lo, Hi };
5866   return DAG.getMergeValues(Ops, dl);
5867 }
5868
5869 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5870 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5871 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5872                                                SelectionDAG &DAG) const {
5873   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5874   EVT VT = Op.getValueType();
5875   unsigned VTBits = VT.getSizeInBits();
5876   SDLoc dl(Op);
5877   SDValue ShOpLo = Op.getOperand(0);
5878   SDValue ShOpHi = Op.getOperand(1);
5879   SDValue ShAmt  = Op.getOperand(2);
5880   SDValue ARMcc;
5881   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5882
5883   assert(Op.getOpcode() == ISD::SHL_PARTS);
5884   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5885                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5886   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5887   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5888   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5889
5890   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5891                                    DAG.getConstant(VTBits, dl, MVT::i32));
5892   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5893   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5894                             ISD::SETGE, ARMcc, DAG, dl);
5895   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5896                            ARMcc, CCR, CmpHi);
5897
5898   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5899                           ISD::SETGE, ARMcc, DAG, dl);
5900   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5901   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5902                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5903
5904   SDValue Ops[2] = { Lo, Hi };
5905   return DAG.getMergeValues(Ops, dl);
5906 }
5907
5908 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5909                                             SelectionDAG &DAG) const {
5910   // The rounding mode is in bits 23:22 of the FPSCR.
5911   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5912   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5913   // so that the shift + and get folded into a bitfield extract.
5914   SDLoc dl(Op);
5915   SDValue Ops[] = { DAG.getEntryNode(),
5916                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5917
5918   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5919   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5920                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5921   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5922                               DAG.getConstant(22, dl, MVT::i32));
5923   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5924                      DAG.getConstant(3, dl, MVT::i32));
5925 }
5926
5927 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5928                          const ARMSubtarget *ST) {
5929   SDLoc dl(N);
5930   EVT VT = N->getValueType(0);
5931   if (VT.isVector() && ST->hasNEON()) {
5932
5933     // Compute the least significant set bit: LSB = X & -X
5934     SDValue X = N->getOperand(0);
5935     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5936     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5937
5938     EVT ElemTy = VT.getVectorElementType();
5939
5940     if (ElemTy == MVT::i8) {
5941       // Compute with: cttz(x) = ctpop(lsb - 1)
5942       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5943                                 DAG.getTargetConstant(1, dl, ElemTy));
5944       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5945       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5946     }
5947
5948     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5949         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5950       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5951       unsigned NumBits = ElemTy.getSizeInBits();
5952       SDValue WidthMinus1 =
5953           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5954                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5955       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5956       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5957     }
5958
5959     // Compute with: cttz(x) = ctpop(lsb - 1)
5960
5961     // Compute LSB - 1.
5962     SDValue Bits;
5963     if (ElemTy == MVT::i64) {
5964       // Load constant 0xffff'ffff'ffff'ffff to register.
5965       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5966                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5967       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5968     } else {
5969       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5970                                 DAG.getTargetConstant(1, dl, ElemTy));
5971       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5972     }
5973     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5974   }
5975
5976   if (!ST->hasV6T2Ops())
5977     return SDValue();
5978
5979   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5980   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5981 }
5982
5983 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5984                           const ARMSubtarget *ST) {
5985   EVT VT = N->getValueType(0);
5986   SDLoc DL(N);
5987
5988   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5989   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5990           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5991          "Unexpected type for custom ctpop lowering");
5992
5993   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5994   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5995   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5996   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5997
5998   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5999   unsigned EltSize = 8;
6000   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
6001   while (EltSize != VT.getScalarSizeInBits()) {
6002     SmallVector<SDValue, 8> Ops;
6003     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
6004                                   TLI.getPointerTy(DAG.getDataLayout())));
6005     Ops.push_back(Res);
6006
6007     EltSize *= 2;
6008     NumElts /= 2;
6009     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
6010     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
6011   }
6012
6013   return Res;
6014 }
6015
6016 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
6017 /// operand of a vector shift operation, where all the elements of the
6018 /// build_vector must have the same constant integer value.
6019 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6020   // Ignore bit_converts.
6021   while (Op.getOpcode() == ISD::BITCAST)
6022     Op = Op.getOperand(0);
6023   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6024   APInt SplatBits, SplatUndef;
6025   unsigned SplatBitSize;
6026   bool HasAnyUndefs;
6027   if (!BVN ||
6028       !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs,
6029                             ElementBits) ||
6030       SplatBitSize > ElementBits)
6031     return false;
6032   Cnt = SplatBits.getSExtValue();
6033   return true;
6034 }
6035
6036 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6037 /// operand of a vector shift left operation.  That value must be in the range:
6038 ///   0 <= Value < ElementBits for a left shift; or
6039 ///   0 <= Value <= ElementBits for a long left shift.
6040 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6041   assert(VT.isVector() && "vector shift count is not a vector type");
6042   int64_t ElementBits = VT.getScalarSizeInBits();
6043   if (!getVShiftImm(Op, ElementBits, Cnt))
6044     return false;
6045   return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6046 }
6047
6048 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6049 /// operand of a vector shift right operation.  For a shift opcode, the value
6050 /// is positive, but for an intrinsic the value count must be negative. The
6051 /// absolute value must be in the range:
6052 ///   1 <= |Value| <= ElementBits for a right shift; or
6053 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
6054 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6055                          int64_t &Cnt) {
6056   assert(VT.isVector() && "vector shift count is not a vector type");
6057   int64_t ElementBits = VT.getScalarSizeInBits();
6058   if (!getVShiftImm(Op, ElementBits, Cnt))
6059     return false;
6060   if (!isIntrinsic)
6061     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6062   if (Cnt >= -(isNarrow ? ElementBits / 2 : ElementBits) && Cnt <= -1) {
6063     Cnt = -Cnt;
6064     return true;
6065   }
6066   return false;
6067 }
6068
6069 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
6070                           const ARMSubtarget *ST) {
6071   EVT VT = N->getValueType(0);
6072   SDLoc dl(N);
6073   int64_t Cnt;
6074
6075   if (!VT.isVector())
6076     return SDValue();
6077
6078   // We essentially have two forms here. Shift by an immediate and shift by a
6079   // vector register (there are also shift by a gpr, but that is just handled
6080   // with a tablegen pattern). We cannot easily match shift by an immediate in
6081   // tablegen so we do that here and generate a VSHLIMM/VSHRsIMM/VSHRuIMM.
6082   // For shifting by a vector, we don't have VSHR, only VSHL (which can be
6083   // signed or unsigned, and a negative shift indicates a shift right).
6084   if (N->getOpcode() == ISD::SHL) {
6085     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt))
6086       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
6087                          DAG.getConstant(Cnt, dl, MVT::i32));
6088     return DAG.getNode(ARMISD::VSHLu, dl, VT, N->getOperand(0),
6089                        N->getOperand(1));
6090   }
6091
6092   assert((N->getOpcode() == ISD::SRA || N->getOpcode() == ISD::SRL) &&
6093          "unexpected vector shift opcode");
6094
6095   if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
6096     unsigned VShiftOpc =
6097         (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
6098     return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
6099                        DAG.getConstant(Cnt, dl, MVT::i32));
6100   }
6101
6102   // Other right shifts we don't have operations for (we use a shift left by a
6103   // negative number).
6104   EVT ShiftVT = N->getOperand(1).getValueType();
6105   SDValue NegatedCount = DAG.getNode(
6106       ISD::SUB, dl, ShiftVT, getZeroVector(ShiftVT, DAG, dl), N->getOperand(1));
6107   unsigned VShiftOpc =
6108       (N->getOpcode() == ISD::SRA ? ARMISD::VSHLs : ARMISD::VSHLu);
6109   return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0), NegatedCount);
6110 }
6111
6112 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
6113                                 const ARMSubtarget *ST) {
6114   EVT VT = N->getValueType(0);
6115   SDLoc dl(N);
6116
6117   // We can get here for a node like i32 = ISD::SHL i32, i64
6118   if (VT != MVT::i64)
6119     return SDValue();
6120
6121   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA ||
6122           N->getOpcode() == ISD::SHL) &&
6123          "Unknown shift to lower!");
6124
6125   unsigned ShOpc = N->getOpcode();
6126   if (ST->hasMVEIntegerOps()) {
6127     SDValue ShAmt = N->getOperand(1);
6128     unsigned ShPartsOpc = ARMISD::LSLL;
6129     ConstantSDNode *Con = dyn_cast<ConstantSDNode>(ShAmt);
6130
6131     // If the shift amount is greater than 32 or has a greater bitwidth than 64
6132     // then do the default optimisation
6133     if (ShAmt->getValueType(0).getSizeInBits() > 64 ||
6134         (Con && (Con->getZExtValue() == 0 || Con->getZExtValue() >= 32)))
6135       return SDValue();
6136
6137     // Extract the lower 32 bits of the shift amount if it's not an i32
6138     if (ShAmt->getValueType(0) != MVT::i32)
6139       ShAmt = DAG.getZExtOrTrunc(ShAmt, dl, MVT::i32);
6140
6141     if (ShOpc == ISD::SRL) {
6142       if (!Con)
6143         // There is no t2LSRLr instruction so negate and perform an lsll if the
6144         // shift amount is in a register, emulating a right shift.
6145         ShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
6146                             DAG.getConstant(0, dl, MVT::i32), ShAmt);
6147       else
6148         // Else generate an lsrl on the immediate shift amount
6149         ShPartsOpc = ARMISD::LSRL;
6150     } else if (ShOpc == ISD::SRA)
6151       ShPartsOpc = ARMISD::ASRL;
6152
6153     // Lower 32 bits of the destination/source
6154     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6155                              DAG.getConstant(0, dl, MVT::i32));
6156     // Upper 32 bits of the destination/source
6157     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6158                              DAG.getConstant(1, dl, MVT::i32));
6159
6160     // Generate the shift operation as computed above
6161     Lo = DAG.getNode(ShPartsOpc, dl, DAG.getVTList(MVT::i32, MVT::i32), Lo, Hi,
6162                      ShAmt);
6163     // The upper 32 bits come from the second return value of lsll
6164     Hi = SDValue(Lo.getNode(), 1);
6165     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6166   }
6167
6168   // We only lower SRA, SRL of 1 here, all others use generic lowering.
6169   if (!isOneConstant(N->getOperand(1)) || N->getOpcode() == ISD::SHL)
6170     return SDValue();
6171
6172   // If we are in thumb mode, we don't have RRX.
6173   if (ST->isThumb1Only())
6174     return SDValue();
6175
6176   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
6177   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6178                            DAG.getConstant(0, dl, MVT::i32));
6179   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
6180                            DAG.getConstant(1, dl, MVT::i32));
6181
6182   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
6183   // captures the result into a carry flag.
6184   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
6185   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
6186
6187   // The low part is an ARMISD::RRX operand, which shifts the carry in.
6188   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
6189
6190   // Merge the pieces into a single i64 value.
6191  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6192 }
6193
6194 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG,
6195                            const ARMSubtarget *ST) {
6196   bool Invert = false;
6197   bool Swap = false;
6198   unsigned Opc = ARMCC::AL;
6199
6200   SDValue Op0 = Op.getOperand(0);
6201   SDValue Op1 = Op.getOperand(1);
6202   SDValue CC = Op.getOperand(2);
6203   EVT VT = Op.getValueType();
6204   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6205   SDLoc dl(Op);
6206
6207   EVT CmpVT;
6208   if (ST->hasNEON())
6209     CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
6210   else {
6211     assert(ST->hasMVEIntegerOps() &&
6212            "No hardware support for integer vector comparison!");
6213
6214     if (Op.getValueType().getVectorElementType() != MVT::i1)
6215       return SDValue();
6216
6217     // Make sure we expand floating point setcc to scalar if we do not have
6218     // mve.fp, so that we can handle them from there.
6219     if (Op0.getValueType().isFloatingPoint() && !ST->hasMVEFloatOps())
6220       return SDValue();
6221
6222     CmpVT = VT;
6223   }
6224
6225   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
6226       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
6227     // Special-case integer 64-bit equality comparisons. They aren't legal,
6228     // but they can be lowered with a few vector instructions.
6229     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
6230     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
6231     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
6232     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
6233     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
6234                               DAG.getCondCode(ISD::SETEQ));
6235     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
6236     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
6237     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
6238     if (SetCCOpcode == ISD::SETNE)
6239       Merged = DAG.getNOT(dl, Merged, CmpVT);
6240     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
6241     return Merged;
6242   }
6243
6244   if (CmpVT.getVectorElementType() == MVT::i64)
6245     // 64-bit comparisons are not legal in general.
6246     return SDValue();
6247
6248   if (Op1.getValueType().isFloatingPoint()) {
6249     switch (SetCCOpcode) {
6250     default: llvm_unreachable("Illegal FP comparison");
6251     case ISD::SETUNE:
6252     case ISD::SETNE:
6253       if (ST->hasMVEFloatOps()) {
6254         Opc = ARMCC::NE; break;
6255       } else {
6256         Invert = true; LLVM_FALLTHROUGH;
6257       }
6258     case ISD::SETOEQ:
6259     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6260     case ISD::SETOLT:
6261     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
6262     case ISD::SETOGT:
6263     case ISD::SETGT:  Opc = ARMCC::GT; break;
6264     case ISD::SETOLE:
6265     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6266     case ISD::SETOGE:
6267     case ISD::SETGE: Opc = ARMCC::GE; break;
6268     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
6269     case ISD::SETULE: Invert = true; Opc = ARMCC::GT; break;
6270     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
6271     case ISD::SETULT: Invert = true; Opc = ARMCC::GE; break;
6272     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
6273     case ISD::SETONE: {
6274       // Expand this to (OLT | OGT).
6275       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6276                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6277       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6278                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6279       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6280       if (Invert)
6281         Result = DAG.getNOT(dl, Result, VT);
6282       return Result;
6283     }
6284     case ISD::SETUO: Invert = true; LLVM_FALLTHROUGH;
6285     case ISD::SETO: {
6286       // Expand this to (OLT | OGE).
6287       SDValue TmpOp0 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op1, Op0,
6288                                    DAG.getConstant(ARMCC::GT, dl, MVT::i32));
6289       SDValue TmpOp1 = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6290                                    DAG.getConstant(ARMCC::GE, dl, MVT::i32));
6291       SDValue Result = DAG.getNode(ISD::OR, dl, CmpVT, TmpOp0, TmpOp1);
6292       if (Invert)
6293         Result = DAG.getNOT(dl, Result, VT);
6294       return Result;
6295     }
6296     }
6297   } else {
6298     // Integer comparisons.
6299     switch (SetCCOpcode) {
6300     default: llvm_unreachable("Illegal integer comparison");
6301     case ISD::SETNE:
6302       if (ST->hasMVEIntegerOps()) {
6303         Opc = ARMCC::NE; break;
6304       } else {
6305         Invert = true; LLVM_FALLTHROUGH;
6306       }
6307     case ISD::SETEQ:  Opc = ARMCC::EQ; break;
6308     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
6309     case ISD::SETGT:  Opc = ARMCC::GT; break;
6310     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
6311     case ISD::SETGE:  Opc = ARMCC::GE; break;
6312     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
6313     case ISD::SETUGT: Opc = ARMCC::HI; break;
6314     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
6315     case ISD::SETUGE: Opc = ARMCC::HS; break;
6316     }
6317
6318     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
6319     if (ST->hasNEON() && Opc == ARMCC::EQ) {
6320       SDValue AndOp;
6321       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6322         AndOp = Op0;
6323       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
6324         AndOp = Op1;
6325
6326       // Ignore bitconvert.
6327       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
6328         AndOp = AndOp.getOperand(0);
6329
6330       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
6331         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
6332         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
6333         SDValue Result = DAG.getNode(ARMISD::VTST, dl, CmpVT, Op0, Op1);
6334         if (!Invert)
6335           Result = DAG.getNOT(dl, Result, VT);
6336         return Result;
6337       }
6338     }
6339   }
6340
6341   if (Swap)
6342     std::swap(Op0, Op1);
6343
6344   // If one of the operands is a constant vector zero, attempt to fold the
6345   // comparison to a specialized compare-against-zero form.
6346   SDValue SingleOp;
6347   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
6348     SingleOp = Op0;
6349   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
6350     if (Opc == ARMCC::GE)
6351       Opc = ARMCC::LE;
6352     else if (Opc == ARMCC::GT)
6353       Opc = ARMCC::LT;
6354     SingleOp = Op1;
6355   }
6356
6357   SDValue Result;
6358   if (SingleOp.getNode()) {
6359     Result = DAG.getNode(ARMISD::VCMPZ, dl, CmpVT, SingleOp,
6360                          DAG.getConstant(Opc, dl, MVT::i32));
6361   } else {
6362     Result = DAG.getNode(ARMISD::VCMP, dl, CmpVT, Op0, Op1,
6363                          DAG.getConstant(Opc, dl, MVT::i32));
6364   }
6365
6366   Result = DAG.getSExtOrTrunc(Result, dl, VT);
6367
6368   if (Invert)
6369     Result = DAG.getNOT(dl, Result, VT);
6370
6371   return Result;
6372 }
6373
6374 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
6375   SDValue LHS = Op.getOperand(0);
6376   SDValue RHS = Op.getOperand(1);
6377   SDValue Carry = Op.getOperand(2);
6378   SDValue Cond = Op.getOperand(3);
6379   SDLoc DL(Op);
6380
6381   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
6382
6383   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
6384   // have to invert the carry first.
6385   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
6386                       DAG.getConstant(1, DL, MVT::i32), Carry);
6387   // This converts the boolean value carry into the carry flag.
6388   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
6389
6390   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
6391   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
6392
6393   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
6394   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
6395   SDValue ARMcc = DAG.getConstant(
6396       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
6397   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
6398   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
6399                                    Cmp.getValue(1), SDValue());
6400   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
6401                      CCR, Chain.getValue(1));
6402 }
6403
6404 /// isVMOVModifiedImm - Check if the specified splat value corresponds to a
6405 /// valid vector constant for a NEON or MVE instruction with a "modified
6406 /// immediate" operand (e.g., VMOV).  If so, return the encoded value.
6407 static SDValue isVMOVModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
6408                                  unsigned SplatBitSize, SelectionDAG &DAG,
6409                                  const SDLoc &dl, EVT &VT, bool is128Bits,
6410                                  VMOVModImmType type) {
6411   unsigned OpCmode, Imm;
6412
6413   // SplatBitSize is set to the smallest size that splats the vector, so a
6414   // zero vector will always have SplatBitSize == 8.  However, NEON modified
6415   // immediate instructions others than VMOV do not support the 8-bit encoding
6416   // of a zero vector, and the default encoding of zero is supposed to be the
6417   // 32-bit version.
6418   if (SplatBits == 0)
6419     SplatBitSize = 32;
6420
6421   switch (SplatBitSize) {
6422   case 8:
6423     if (type != VMOVModImm)
6424       return SDValue();
6425     // Any 1-byte value is OK.  Op=0, Cmode=1110.
6426     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
6427     OpCmode = 0xe;
6428     Imm = SplatBits;
6429     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
6430     break;
6431
6432   case 16:
6433     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
6434     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
6435     if ((SplatBits & ~0xff) == 0) {
6436       // Value = 0x00nn: Op=x, Cmode=100x.
6437       OpCmode = 0x8;
6438       Imm = SplatBits;
6439       break;
6440     }
6441     if ((SplatBits & ~0xff00) == 0) {
6442       // Value = 0xnn00: Op=x, Cmode=101x.
6443       OpCmode = 0xa;
6444       Imm = SplatBits >> 8;
6445       break;
6446     }
6447     return SDValue();
6448
6449   case 32:
6450     // NEON's 32-bit VMOV supports splat values where:
6451     // * only one byte is nonzero, or
6452     // * the least significant byte is 0xff and the second byte is nonzero, or
6453     // * the least significant 2 bytes are 0xff and the third is nonzero.
6454     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
6455     if ((SplatBits & ~0xff) == 0) {
6456       // Value = 0x000000nn: Op=x, Cmode=000x.
6457       OpCmode = 0;
6458       Imm = SplatBits;
6459       break;
6460     }
6461     if ((SplatBits & ~0xff00) == 0) {
6462       // Value = 0x0000nn00: Op=x, Cmode=001x.
6463       OpCmode = 0x2;
6464       Imm = SplatBits >> 8;
6465       break;
6466     }
6467     if ((SplatBits & ~0xff0000) == 0) {
6468       // Value = 0x00nn0000: Op=x, Cmode=010x.
6469       OpCmode = 0x4;
6470       Imm = SplatBits >> 16;
6471       break;
6472     }
6473     if ((SplatBits & ~0xff000000) == 0) {
6474       // Value = 0xnn000000: Op=x, Cmode=011x.
6475       OpCmode = 0x6;
6476       Imm = SplatBits >> 24;
6477       break;
6478     }
6479
6480     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
6481     if (type == OtherModImm) return SDValue();
6482
6483     if ((SplatBits & ~0xffff) == 0 &&
6484         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
6485       // Value = 0x0000nnff: Op=x, Cmode=1100.
6486       OpCmode = 0xc;
6487       Imm = SplatBits >> 8;
6488       break;
6489     }
6490
6491     // cmode == 0b1101 is not supported for MVE VMVN
6492     if (type == MVEVMVNModImm)
6493       return SDValue();
6494
6495     if ((SplatBits & ~0xffffff) == 0 &&
6496         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
6497       // Value = 0x00nnffff: Op=x, Cmode=1101.
6498       OpCmode = 0xd;
6499       Imm = SplatBits >> 16;
6500       break;
6501     }
6502
6503     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
6504     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
6505     // VMOV.I32.  A (very) minor optimization would be to replicate the value
6506     // and fall through here to test for a valid 64-bit splat.  But, then the
6507     // caller would also need to check and handle the change in size.
6508     return SDValue();
6509
6510   case 64: {
6511     if (type != VMOVModImm)
6512       return SDValue();
6513     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
6514     uint64_t BitMask = 0xff;
6515     uint64_t Val = 0;
6516     unsigned ImmMask = 1;
6517     Imm = 0;
6518     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
6519       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
6520         Val |= BitMask;
6521         Imm |= ImmMask;
6522       } else if ((SplatBits & BitMask) != 0) {
6523         return SDValue();
6524       }
6525       BitMask <<= 8;
6526       ImmMask <<= 1;
6527     }
6528
6529     if (DAG.getDataLayout().isBigEndian())
6530       // swap higher and lower 32 bit word
6531       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
6532
6533     // Op=1, Cmode=1110.
6534     OpCmode = 0x1e;
6535     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
6536     break;
6537   }
6538
6539   default:
6540     llvm_unreachable("unexpected size for isVMOVModifiedImm");
6541   }
6542
6543   unsigned EncodedVal = ARM_AM::createVMOVModImm(OpCmode, Imm);
6544   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
6545 }
6546
6547 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
6548                                            const ARMSubtarget *ST) const {
6549   EVT VT = Op.getValueType();
6550   bool IsDouble = (VT == MVT::f64);
6551   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
6552   const APFloat &FPVal = CFP->getValueAPF();
6553
6554   // Prevent floating-point constants from using literal loads
6555   // when execute-only is enabled.
6556   if (ST->genExecuteOnly()) {
6557     // If we can represent the constant as an immediate, don't lower it
6558     if (isFPImmLegal(FPVal, VT))
6559       return Op;
6560     // Otherwise, construct as integer, and move to float register
6561     APInt INTVal = FPVal.bitcastToAPInt();
6562     SDLoc DL(CFP);
6563     switch (VT.getSimpleVT().SimpleTy) {
6564       default:
6565         llvm_unreachable("Unknown floating point type!");
6566         break;
6567       case MVT::f64: {
6568         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
6569         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
6570         if (!ST->isLittle())
6571           std::swap(Lo, Hi);
6572         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
6573       }
6574       case MVT::f32:
6575           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
6576               DAG.getConstant(INTVal, DL, MVT::i32));
6577     }
6578   }
6579
6580   if (!ST->hasVFP3Base())
6581     return SDValue();
6582
6583   // Use the default (constant pool) lowering for double constants when we have
6584   // an SP-only FPU
6585   if (IsDouble && !Subtarget->hasFP64())
6586     return SDValue();
6587
6588   // Try splatting with a VMOV.f32...
6589   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
6590
6591   if (ImmVal != -1) {
6592     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
6593       // We have code in place to select a valid ConstantFP already, no need to
6594       // do any mangling.
6595       return Op;
6596     }
6597
6598     // It's a float and we are trying to use NEON operations where
6599     // possible. Lower it to a splat followed by an extract.
6600     SDLoc DL(Op);
6601     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
6602     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
6603                                       NewVal);
6604     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
6605                        DAG.getConstant(0, DL, MVT::i32));
6606   }
6607
6608   // The rest of our options are NEON only, make sure that's allowed before
6609   // proceeding..
6610   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
6611     return SDValue();
6612
6613   EVT VMovVT;
6614   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6615
6616   // It wouldn't really be worth bothering for doubles except for one very
6617   // important value, which does happen to match: 0.0. So make sure we don't do
6618   // anything stupid.
6619   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6620     return SDValue();
6621
6622   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6623   SDValue NewVal = isVMOVModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6624                                      VMovVT, false, VMOVModImm);
6625   if (NewVal != SDValue()) {
6626     SDLoc DL(Op);
6627     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6628                                       NewVal);
6629     if (IsDouble)
6630       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6631
6632     // It's a float: cast and extract a vector element.
6633     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6634                                        VecConstant);
6635     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6636                        DAG.getConstant(0, DL, MVT::i32));
6637   }
6638
6639   // Finally, try a VMVN.i32
6640   NewVal = isVMOVModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6641                              false, VMVNModImm);
6642   if (NewVal != SDValue()) {
6643     SDLoc DL(Op);
6644     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6645
6646     if (IsDouble)
6647       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6648
6649     // It's a float: cast and extract a vector element.
6650     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6651                                        VecConstant);
6652     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6653                        DAG.getConstant(0, DL, MVT::i32));
6654   }
6655
6656   return SDValue();
6657 }
6658
6659 // check if an VEXT instruction can handle the shuffle mask when the
6660 // vector sources of the shuffle are the same.
6661 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6662   unsigned NumElts = VT.getVectorNumElements();
6663
6664   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6665   if (M[0] < 0)
6666     return false;
6667
6668   Imm = M[0];
6669
6670   // If this is a VEXT shuffle, the immediate value is the index of the first
6671   // element.  The other shuffle indices must be the successive elements after
6672   // the first one.
6673   unsigned ExpectedElt = Imm;
6674   for (unsigned i = 1; i < NumElts; ++i) {
6675     // Increment the expected index.  If it wraps around, just follow it
6676     // back to index zero and keep going.
6677     ++ExpectedElt;
6678     if (ExpectedElt == NumElts)
6679       ExpectedElt = 0;
6680
6681     if (M[i] < 0) continue; // ignore UNDEF indices
6682     if (ExpectedElt != static_cast<unsigned>(M[i]))
6683       return false;
6684   }
6685
6686   return true;
6687 }
6688
6689 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6690                        bool &ReverseVEXT, unsigned &Imm) {
6691   unsigned NumElts = VT.getVectorNumElements();
6692   ReverseVEXT = false;
6693
6694   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6695   if (M[0] < 0)
6696     return false;
6697
6698   Imm = M[0];
6699
6700   // If this is a VEXT shuffle, the immediate value is the index of the first
6701   // element.  The other shuffle indices must be the successive elements after
6702   // the first one.
6703   unsigned ExpectedElt = Imm;
6704   for (unsigned i = 1; i < NumElts; ++i) {
6705     // Increment the expected index.  If it wraps around, it may still be
6706     // a VEXT but the source vectors must be swapped.
6707     ExpectedElt += 1;
6708     if (ExpectedElt == NumElts * 2) {
6709       ExpectedElt = 0;
6710       ReverseVEXT = true;
6711     }
6712
6713     if (M[i] < 0) continue; // ignore UNDEF indices
6714     if (ExpectedElt != static_cast<unsigned>(M[i]))
6715       return false;
6716   }
6717
6718   // Adjust the index value if the source operands will be swapped.
6719   if (ReverseVEXT)
6720     Imm -= NumElts;
6721
6722   return true;
6723 }
6724
6725 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6726 /// instruction with the specified blocksize.  (The order of the elements
6727 /// within each block of the vector is reversed.)
6728 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6729   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6730          "Only possible block sizes for VREV are: 16, 32, 64");
6731
6732   unsigned EltSz = VT.getScalarSizeInBits();
6733   if (EltSz == 64)
6734     return false;
6735
6736   unsigned NumElts = VT.getVectorNumElements();
6737   unsigned BlockElts = M[0] + 1;
6738   // If the first shuffle index is UNDEF, be optimistic.
6739   if (M[0] < 0)
6740     BlockElts = BlockSize / EltSz;
6741
6742   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6743     return false;
6744
6745   for (unsigned i = 0; i < NumElts; ++i) {
6746     if (M[i] < 0) continue; // ignore UNDEF indices
6747     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6748       return false;
6749   }
6750
6751   return true;
6752 }
6753
6754 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6755   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6756   // range, then 0 is placed into the resulting vector. So pretty much any mask
6757   // of 8 elements can work here.
6758   return VT == MVT::v8i8 && M.size() == 8;
6759 }
6760
6761 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6762                                unsigned Index) {
6763   if (Mask.size() == Elements * 2)
6764     return Index / Elements;
6765   return Mask[Index] == 0 ? 0 : 1;
6766 }
6767
6768 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6769 // checking that pairs of elements in the shuffle mask represent the same index
6770 // in each vector, incrementing the expected index by 2 at each step.
6771 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6772 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6773 //  v2={e,f,g,h}
6774 // WhichResult gives the offset for each element in the mask based on which
6775 // of the two results it belongs to.
6776 //
6777 // The transpose can be represented either as:
6778 // result1 = shufflevector v1, v2, result1_shuffle_mask
6779 // result2 = shufflevector v1, v2, result2_shuffle_mask
6780 // where v1/v2 and the shuffle masks have the same number of elements
6781 // (here WhichResult (see below) indicates which result is being checked)
6782 //
6783 // or as:
6784 // results = shufflevector v1, v2, shuffle_mask
6785 // where both results are returned in one vector and the shuffle mask has twice
6786 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6787 // want to check the low half and high half of the shuffle mask as if it were
6788 // the other case
6789 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6790   unsigned EltSz = VT.getScalarSizeInBits();
6791   if (EltSz == 64)
6792     return false;
6793
6794   unsigned NumElts = VT.getVectorNumElements();
6795   if (M.size() != NumElts && M.size() != NumElts*2)
6796     return false;
6797
6798   // If the mask is twice as long as the input vector then we need to check the
6799   // upper and lower parts of the mask with a matching value for WhichResult
6800   // FIXME: A mask with only even values will be rejected in case the first
6801   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6802   // M[0] is used to determine WhichResult
6803   for (unsigned i = 0; i < M.size(); i += NumElts) {
6804     WhichResult = SelectPairHalf(NumElts, M, i);
6805     for (unsigned j = 0; j < NumElts; j += 2) {
6806       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6807           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6808         return false;
6809     }
6810   }
6811
6812   if (M.size() == NumElts*2)
6813     WhichResult = 0;
6814
6815   return true;
6816 }
6817
6818 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6819 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6820 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6821 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6822   unsigned EltSz = VT.getScalarSizeInBits();
6823   if (EltSz == 64)
6824     return false;
6825
6826   unsigned NumElts = VT.getVectorNumElements();
6827   if (M.size() != NumElts && M.size() != NumElts*2)
6828     return false;
6829
6830   for (unsigned i = 0; i < M.size(); i += NumElts) {
6831     WhichResult = SelectPairHalf(NumElts, M, i);
6832     for (unsigned j = 0; j < NumElts; j += 2) {
6833       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6834           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6835         return false;
6836     }
6837   }
6838
6839   if (M.size() == NumElts*2)
6840     WhichResult = 0;
6841
6842   return true;
6843 }
6844
6845 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6846 // that the mask elements are either all even and in steps of size 2 or all odd
6847 // and in steps of size 2.
6848 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6849 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6850 //  v2={e,f,g,h}
6851 // Requires similar checks to that of isVTRNMask with
6852 // respect the how results are returned.
6853 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6854   unsigned EltSz = VT.getScalarSizeInBits();
6855   if (EltSz == 64)
6856     return false;
6857
6858   unsigned NumElts = VT.getVectorNumElements();
6859   if (M.size() != NumElts && M.size() != NumElts*2)
6860     return false;
6861
6862   for (unsigned i = 0; i < M.size(); i += NumElts) {
6863     WhichResult = SelectPairHalf(NumElts, M, i);
6864     for (unsigned j = 0; j < NumElts; ++j) {
6865       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6866         return false;
6867     }
6868   }
6869
6870   if (M.size() == NumElts*2)
6871     WhichResult = 0;
6872
6873   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6874   if (VT.is64BitVector() && EltSz == 32)
6875     return false;
6876
6877   return true;
6878 }
6879
6880 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6881 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6882 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6883 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6884   unsigned EltSz = VT.getScalarSizeInBits();
6885   if (EltSz == 64)
6886     return false;
6887
6888   unsigned NumElts = VT.getVectorNumElements();
6889   if (M.size() != NumElts && M.size() != NumElts*2)
6890     return false;
6891
6892   unsigned Half = NumElts / 2;
6893   for (unsigned i = 0; i < M.size(); i += NumElts) {
6894     WhichResult = SelectPairHalf(NumElts, M, i);
6895     for (unsigned j = 0; j < NumElts; j += Half) {
6896       unsigned Idx = WhichResult;
6897       for (unsigned k = 0; k < Half; ++k) {
6898         int MIdx = M[i + j + k];
6899         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6900           return false;
6901         Idx += 2;
6902       }
6903     }
6904   }
6905
6906   if (M.size() == NumElts*2)
6907     WhichResult = 0;
6908
6909   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6910   if (VT.is64BitVector() && EltSz == 32)
6911     return false;
6912
6913   return true;
6914 }
6915
6916 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6917 // that pairs of elements of the shufflemask represent the same index in each
6918 // vector incrementing sequentially through the vectors.
6919 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6920 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6921 //  v2={e,f,g,h}
6922 // Requires similar checks to that of isVTRNMask with respect the how results
6923 // are returned.
6924 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6925   unsigned EltSz = VT.getScalarSizeInBits();
6926   if (EltSz == 64)
6927     return false;
6928
6929   unsigned NumElts = VT.getVectorNumElements();
6930   if (M.size() != NumElts && M.size() != NumElts*2)
6931     return false;
6932
6933   for (unsigned i = 0; i < M.size(); i += NumElts) {
6934     WhichResult = SelectPairHalf(NumElts, M, i);
6935     unsigned Idx = WhichResult * NumElts / 2;
6936     for (unsigned j = 0; j < NumElts; j += 2) {
6937       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6938           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6939         return false;
6940       Idx += 1;
6941     }
6942   }
6943
6944   if (M.size() == NumElts*2)
6945     WhichResult = 0;
6946
6947   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6948   if (VT.is64BitVector() && EltSz == 32)
6949     return false;
6950
6951   return true;
6952 }
6953
6954 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6955 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6956 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6957 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6958   unsigned EltSz = VT.getScalarSizeInBits();
6959   if (EltSz == 64)
6960     return false;
6961
6962   unsigned NumElts = VT.getVectorNumElements();
6963   if (M.size() != NumElts && M.size() != NumElts*2)
6964     return false;
6965
6966   for (unsigned i = 0; i < M.size(); i += NumElts) {
6967     WhichResult = SelectPairHalf(NumElts, M, i);
6968     unsigned Idx = WhichResult * NumElts / 2;
6969     for (unsigned j = 0; j < NumElts; j += 2) {
6970       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6971           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6972         return false;
6973       Idx += 1;
6974     }
6975   }
6976
6977   if (M.size() == NumElts*2)
6978     WhichResult = 0;
6979
6980   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6981   if (VT.is64BitVector() && EltSz == 32)
6982     return false;
6983
6984   return true;
6985 }
6986
6987 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6988 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6989 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6990                                            unsigned &WhichResult,
6991                                            bool &isV_UNDEF) {
6992   isV_UNDEF = false;
6993   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6994     return ARMISD::VTRN;
6995   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6996     return ARMISD::VUZP;
6997   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6998     return ARMISD::VZIP;
6999
7000   isV_UNDEF = true;
7001   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
7002     return ARMISD::VTRN;
7003   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7004     return ARMISD::VUZP;
7005   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
7006     return ARMISD::VZIP;
7007
7008   return 0;
7009 }
7010
7011 /// \return true if this is a reverse operation on an vector.
7012 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
7013   unsigned NumElts = VT.getVectorNumElements();
7014   // Make sure the mask has the right size.
7015   if (NumElts != M.size())
7016       return false;
7017
7018   // Look for <15, ..., 3, -1, 1, 0>.
7019   for (unsigned i = 0; i != NumElts; ++i)
7020     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
7021       return false;
7022
7023   return true;
7024 }
7025
7026 static bool isVMOVNMask(ArrayRef<int> M, EVT VT, bool Top) {
7027   unsigned NumElts = VT.getVectorNumElements();
7028   // Make sure the mask has the right size.
7029   if (NumElts != M.size() || (VT != MVT::v8i16 && VT != MVT::v16i8))
7030       return false;
7031
7032   // If Top
7033   //   Look for <0, N, 2, N+2, 4, N+4, ..>.
7034   //   This inserts Input2 into Input1
7035   // else if not Top
7036   //   Look for <0, N+1, 2, N+3, 4, N+5, ..>
7037   //   This inserts Input1 into Input2
7038   unsigned Offset = Top ? 0 : 1;
7039   for (unsigned i = 0; i < NumElts; i+=2) {
7040     if (M[i] >= 0 && M[i] != (int)i)
7041       return false;
7042     if (M[i+1] >= 0 && M[i+1] != (int)(NumElts + i + Offset))
7043       return false;
7044   }
7045
7046   return true;
7047 }
7048
7049 // If N is an integer constant that can be moved into a register in one
7050 // instruction, return an SDValue of such a constant (will become a MOV
7051 // instruction).  Otherwise return null.
7052 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
7053                                      const ARMSubtarget *ST, const SDLoc &dl) {
7054   uint64_t Val;
7055   if (!isa<ConstantSDNode>(N))
7056     return SDValue();
7057   Val = cast<ConstantSDNode>(N)->getZExtValue();
7058
7059   if (ST->isThumb1Only()) {
7060     if (Val <= 255 || ~Val <= 255)
7061       return DAG.getConstant(Val, dl, MVT::i32);
7062   } else {
7063     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
7064       return DAG.getConstant(Val, dl, MVT::i32);
7065   }
7066   return SDValue();
7067 }
7068
7069 static SDValue LowerBUILD_VECTOR_i1(SDValue Op, SelectionDAG &DAG,
7070                                     const ARMSubtarget *ST) {
7071   SDLoc dl(Op);
7072   EVT VT = Op.getValueType();
7073
7074   assert(ST->hasMVEIntegerOps() && "LowerBUILD_VECTOR_i1 called without MVE!");
7075
7076   unsigned NumElts = VT.getVectorNumElements();
7077   unsigned BoolMask;
7078   unsigned BitsPerBool;
7079   if (NumElts == 4) {
7080     BitsPerBool = 4;
7081     BoolMask = 0xf;
7082   } else if (NumElts == 8) {
7083     BitsPerBool = 2;
7084     BoolMask = 0x3;
7085   } else if (NumElts == 16) {
7086     BitsPerBool = 1;
7087     BoolMask = 0x1;
7088   } else
7089     return SDValue();
7090
7091   // If this is a single value copied into all lanes (a splat), we can just sign
7092   // extend that single value
7093   SDValue FirstOp = Op.getOperand(0);
7094   if (!isa<ConstantSDNode>(FirstOp) &&
7095       std::all_of(std::next(Op->op_begin()), Op->op_end(),
7096                   [&FirstOp](SDUse &U) {
7097                     return U.get().isUndef() || U.get() == FirstOp;
7098                   })) {
7099     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32, FirstOp,
7100                               DAG.getValueType(MVT::i1));
7101     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), Ext);
7102   }
7103
7104   // First create base with bits set where known
7105   unsigned Bits32 = 0;
7106   for (unsigned i = 0; i < NumElts; ++i) {
7107     SDValue V = Op.getOperand(i);
7108     if (!isa<ConstantSDNode>(V) && !V.isUndef())
7109       continue;
7110     bool BitSet = V.isUndef() ? false : cast<ConstantSDNode>(V)->getZExtValue();
7111     if (BitSet)
7112       Bits32 |= BoolMask << (i * BitsPerBool);
7113   }
7114
7115   // Add in unknown nodes
7116   SDValue Base = DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT,
7117                              DAG.getConstant(Bits32, dl, MVT::i32));
7118   for (unsigned i = 0; i < NumElts; ++i) {
7119     SDValue V = Op.getOperand(i);
7120     if (isa<ConstantSDNode>(V) || V.isUndef())
7121       continue;
7122     Base = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Base, V,
7123                        DAG.getConstant(i, dl, MVT::i32));
7124   }
7125
7126   return Base;
7127 }
7128
7129 // If this is a case we can't handle, return null and let the default
7130 // expansion code take care of it.
7131 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
7132                                              const ARMSubtarget *ST) const {
7133   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
7134   SDLoc dl(Op);
7135   EVT VT = Op.getValueType();
7136
7137   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
7138     return LowerBUILD_VECTOR_i1(Op, DAG, ST);
7139
7140   APInt SplatBits, SplatUndef;
7141   unsigned SplatBitSize;
7142   bool HasAnyUndefs;
7143   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
7144     if (SplatUndef.isAllOnesValue())
7145       return DAG.getUNDEF(VT);
7146
7147     if ((ST->hasNEON() && SplatBitSize <= 64) ||
7148         (ST->hasMVEIntegerOps() && SplatBitSize <= 32)) {
7149       // Check if an immediate VMOV works.
7150       EVT VmovVT;
7151       SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
7152                                       SplatUndef.getZExtValue(), SplatBitSize,
7153                                       DAG, dl, VmovVT, VT.is128BitVector(),
7154                                       VMOVModImm);
7155
7156       if (Val.getNode()) {
7157         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
7158         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7159       }
7160
7161       // Try an immediate VMVN.
7162       uint64_t NegatedImm = (~SplatBits).getZExtValue();
7163       Val = isVMOVModifiedImm(
7164           NegatedImm, SplatUndef.getZExtValue(), SplatBitSize,
7165           DAG, dl, VmovVT, VT.is128BitVector(),
7166           ST->hasMVEIntegerOps() ? MVEVMVNModImm : VMVNModImm);
7167       if (Val.getNode()) {
7168         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
7169         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
7170       }
7171
7172       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
7173       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
7174         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
7175         if (ImmVal != -1) {
7176           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
7177           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
7178         }
7179       }
7180     }
7181   }
7182
7183   // Scan through the operands to see if only one value is used.
7184   //
7185   // As an optimisation, even if more than one value is used it may be more
7186   // profitable to splat with one value then change some lanes.
7187   //
7188   // Heuristically we decide to do this if the vector has a "dominant" value,
7189   // defined as splatted to more than half of the lanes.
7190   unsigned NumElts = VT.getVectorNumElements();
7191   bool isOnlyLowElement = true;
7192   bool usesOnlyOneValue = true;
7193   bool hasDominantValue = false;
7194   bool isConstant = true;
7195
7196   // Map of the number of times a particular SDValue appears in the
7197   // element list.
7198   DenseMap<SDValue, unsigned> ValueCounts;
7199   SDValue Value;
7200   for (unsigned i = 0; i < NumElts; ++i) {
7201     SDValue V = Op.getOperand(i);
7202     if (V.isUndef())
7203       continue;
7204     if (i > 0)
7205       isOnlyLowElement = false;
7206     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
7207       isConstant = false;
7208
7209     ValueCounts.insert(std::make_pair(V, 0));
7210     unsigned &Count = ValueCounts[V];
7211
7212     // Is this value dominant? (takes up more than half of the lanes)
7213     if (++Count > (NumElts / 2)) {
7214       hasDominantValue = true;
7215       Value = V;
7216     }
7217   }
7218   if (ValueCounts.size() != 1)
7219     usesOnlyOneValue = false;
7220   if (!Value.getNode() && !ValueCounts.empty())
7221     Value = ValueCounts.begin()->first;
7222
7223   if (ValueCounts.empty())
7224     return DAG.getUNDEF(VT);
7225
7226   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
7227   // Keep going if we are hitting this case.
7228   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
7229     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
7230
7231   unsigned EltSize = VT.getScalarSizeInBits();
7232
7233   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
7234   // i32 and try again.
7235   if (hasDominantValue && EltSize <= 32) {
7236     if (!isConstant) {
7237       SDValue N;
7238
7239       // If we are VDUPing a value that comes directly from a vector, that will
7240       // cause an unnecessary move to and from a GPR, where instead we could
7241       // just use VDUPLANE. We can only do this if the lane being extracted
7242       // is at a constant index, as the VDUP from lane instructions only have
7243       // constant-index forms.
7244       ConstantSDNode *constIndex;
7245       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7246           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
7247         // We need to create a new undef vector to use for the VDUPLANE if the
7248         // size of the vector from which we get the value is different than the
7249         // size of the vector that we need to create. We will insert the element
7250         // such that the register coalescer will remove unnecessary copies.
7251         if (VT != Value->getOperand(0).getValueType()) {
7252           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
7253                              VT.getVectorNumElements();
7254           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7255                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
7256                         Value, DAG.getConstant(index, dl, MVT::i32)),
7257                            DAG.getConstant(index, dl, MVT::i32));
7258         } else
7259           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7260                         Value->getOperand(0), Value->getOperand(1));
7261       } else
7262         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
7263
7264       if (!usesOnlyOneValue) {
7265         // The dominant value was splatted as 'N', but we now have to insert
7266         // all differing elements.
7267         for (unsigned I = 0; I < NumElts; ++I) {
7268           if (Op.getOperand(I) == Value)
7269             continue;
7270           SmallVector<SDValue, 3> Ops;
7271           Ops.push_back(N);
7272           Ops.push_back(Op.getOperand(I));
7273           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
7274           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
7275         }
7276       }
7277       return N;
7278     }
7279     if (VT.getVectorElementType().isFloatingPoint()) {
7280       SmallVector<SDValue, 8> Ops;
7281       MVT FVT = VT.getVectorElementType().getSimpleVT();
7282       assert(FVT == MVT::f32 || FVT == MVT::f16);
7283       MVT IVT = (FVT == MVT::f32) ? MVT::i32 : MVT::i16;
7284       for (unsigned i = 0; i < NumElts; ++i)
7285         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, IVT,
7286                                   Op.getOperand(i)));
7287       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), IVT, NumElts);
7288       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
7289       Val = LowerBUILD_VECTOR(Val, DAG, ST);
7290       if (Val.getNode())
7291         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7292     }
7293     if (usesOnlyOneValue) {
7294       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
7295       if (isConstant && Val.getNode())
7296         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
7297     }
7298   }
7299
7300   // If all elements are constants and the case above didn't get hit, fall back
7301   // to the default expansion, which will generate a load from the constant
7302   // pool.
7303   if (isConstant)
7304     return SDValue();
7305
7306   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7307   if (NumElts >= 4) {
7308     SDValue shuffle = ReconstructShuffle(Op, DAG);
7309     if (shuffle != SDValue())
7310       return shuffle;
7311   }
7312
7313   if (ST->hasNEON() && VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
7314     // If we haven't found an efficient lowering, try splitting a 128-bit vector
7315     // into two 64-bit vectors; we might discover a better way to lower it.
7316     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
7317     EVT ExtVT = VT.getVectorElementType();
7318     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
7319     SDValue Lower =
7320         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
7321     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
7322       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
7323     SDValue Upper = DAG.getBuildVector(
7324         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
7325     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
7326       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
7327     if (Lower && Upper)
7328       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
7329   }
7330
7331   // Vectors with 32- or 64-bit elements can be built by directly assigning
7332   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
7333   // will be legalized.
7334   if (EltSize >= 32) {
7335     // Do the expansion with floating-point types, since that is what the VFP
7336     // registers are defined to use, and since i64 is not legal.
7337     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7338     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7339     SmallVector<SDValue, 8> Ops;
7340     for (unsigned i = 0; i < NumElts; ++i)
7341       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
7342     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7343     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7344   }
7345
7346   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7347   // know the default expansion would otherwise fall back on something even
7348   // worse. For a vector with one or two non-undef values, that's
7349   // scalar_to_vector for the elements followed by a shuffle (provided the
7350   // shuffle is valid for the target) and materialization element by element
7351   // on the stack followed by a load for everything else.
7352   if (!isConstant && !usesOnlyOneValue) {
7353     SDValue Vec = DAG.getUNDEF(VT);
7354     for (unsigned i = 0 ; i < NumElts; ++i) {
7355       SDValue V = Op.getOperand(i);
7356       if (V.isUndef())
7357         continue;
7358       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
7359       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
7360     }
7361     return Vec;
7362   }
7363
7364   return SDValue();
7365 }
7366
7367 // Gather data to see if the operation can be modelled as a
7368 // shuffle in combination with VEXTs.
7369 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
7370                                               SelectionDAG &DAG) const {
7371   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
7372   SDLoc dl(Op);
7373   EVT VT = Op.getValueType();
7374   unsigned NumElts = VT.getVectorNumElements();
7375
7376   struct ShuffleSourceInfo {
7377     SDValue Vec;
7378     unsigned MinElt = std::numeric_limits<unsigned>::max();
7379     unsigned MaxElt = 0;
7380
7381     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
7382     // be compatible with the shuffle we intend to construct. As a result
7383     // ShuffleVec will be some sliding window into the original Vec.
7384     SDValue ShuffleVec;
7385
7386     // Code should guarantee that element i in Vec starts at element "WindowBase
7387     // + i * WindowScale in ShuffleVec".
7388     int WindowBase = 0;
7389     int WindowScale = 1;
7390
7391     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
7392
7393     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
7394   };
7395
7396   // First gather all vectors used as an immediate source for this BUILD_VECTOR
7397   // node.
7398   SmallVector<ShuffleSourceInfo, 2> Sources;
7399   for (unsigned i = 0; i < NumElts; ++i) {
7400     SDValue V = Op.getOperand(i);
7401     if (V.isUndef())
7402       continue;
7403     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
7404       // A shuffle can only come from building a vector from various
7405       // elements of other vectors.
7406       return SDValue();
7407     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
7408       // Furthermore, shuffles require a constant mask, whereas extractelts
7409       // accept variable indices.
7410       return SDValue();
7411     }
7412
7413     // Add this element source to the list if it's not already there.
7414     SDValue SourceVec = V.getOperand(0);
7415     auto Source = llvm::find(Sources, SourceVec);
7416     if (Source == Sources.end())
7417       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
7418
7419     // Update the minimum and maximum lane number seen.
7420     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
7421     Source->MinElt = std::min(Source->MinElt, EltNo);
7422     Source->MaxElt = std::max(Source->MaxElt, EltNo);
7423   }
7424
7425   // Currently only do something sane when at most two source vectors
7426   // are involved.
7427   if (Sources.size() > 2)
7428     return SDValue();
7429
7430   // Find out the smallest element size among result and two sources, and use
7431   // it as element size to build the shuffle_vector.
7432   EVT SmallestEltTy = VT.getVectorElementType();
7433   for (auto &Source : Sources) {
7434     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
7435     if (SrcEltTy.bitsLT(SmallestEltTy))
7436       SmallestEltTy = SrcEltTy;
7437   }
7438   unsigned ResMultiplier =
7439       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
7440   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
7441   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
7442
7443   // If the source vector is too wide or too narrow, we may nevertheless be able
7444   // to construct a compatible shuffle either by concatenating it with UNDEF or
7445   // extracting a suitable range of elements.
7446   for (auto &Src : Sources) {
7447     EVT SrcVT = Src.ShuffleVec.getValueType();
7448
7449     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
7450       continue;
7451
7452     // This stage of the search produces a source with the same element type as
7453     // the original, but with a total width matching the BUILD_VECTOR output.
7454     EVT EltVT = SrcVT.getVectorElementType();
7455     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
7456     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
7457
7458     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
7459       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
7460         return SDValue();
7461       // We can pad out the smaller vector for free, so if it's part of a
7462       // shuffle...
7463       Src.ShuffleVec =
7464           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
7465                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
7466       continue;
7467     }
7468
7469     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
7470       return SDValue();
7471
7472     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
7473       // Span too large for a VEXT to cope
7474       return SDValue();
7475     }
7476
7477     if (Src.MinElt >= NumSrcElts) {
7478       // The extraction can just take the second half
7479       Src.ShuffleVec =
7480           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7481                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7482       Src.WindowBase = -NumSrcElts;
7483     } else if (Src.MaxElt < NumSrcElts) {
7484       // The extraction can just take the first half
7485       Src.ShuffleVec =
7486           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7487                       DAG.getConstant(0, dl, MVT::i32));
7488     } else {
7489       // An actual VEXT is needed
7490       SDValue VEXTSrc1 =
7491           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7492                       DAG.getConstant(0, dl, MVT::i32));
7493       SDValue VEXTSrc2 =
7494           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
7495                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
7496
7497       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
7498                                    VEXTSrc2,
7499                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
7500       Src.WindowBase = -Src.MinElt;
7501     }
7502   }
7503
7504   // Another possible incompatibility occurs from the vector element types. We
7505   // can fix this by bitcasting the source vectors to the same type we intend
7506   // for the shuffle.
7507   for (auto &Src : Sources) {
7508     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
7509     if (SrcEltTy == SmallestEltTy)
7510       continue;
7511     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
7512     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
7513     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
7514     Src.WindowBase *= Src.WindowScale;
7515   }
7516
7517   // Final sanity check before we try to actually produce a shuffle.
7518   LLVM_DEBUG(for (auto Src
7519                   : Sources)
7520                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
7521
7522   // The stars all align, our next step is to produce the mask for the shuffle.
7523   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
7524   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
7525   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
7526     SDValue Entry = Op.getOperand(i);
7527     if (Entry.isUndef())
7528       continue;
7529
7530     auto Src = llvm::find(Sources, Entry.getOperand(0));
7531     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
7532
7533     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
7534     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
7535     // segment.
7536     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
7537     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
7538                                VT.getScalarSizeInBits());
7539     int LanesDefined = BitsDefined / BitsPerShuffleLane;
7540
7541     // This source is expected to fill ResMultiplier lanes of the final shuffle,
7542     // starting at the appropriate offset.
7543     int *LaneMask = &Mask[i * ResMultiplier];
7544
7545     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
7546     ExtractBase += NumElts * (Src - Sources.begin());
7547     for (int j = 0; j < LanesDefined; ++j)
7548       LaneMask[j] = ExtractBase + j;
7549   }
7550
7551
7552   // We can't handle more than two sources. This should have already
7553   // been checked before this point.
7554   assert(Sources.size() <= 2 && "Too many sources!");
7555
7556   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
7557   for (unsigned i = 0; i < Sources.size(); ++i)
7558     ShuffleOps[i] = Sources[i].ShuffleVec;
7559
7560   SDValue Shuffle = buildLegalVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
7561                                             ShuffleOps[1], Mask, DAG);
7562   if (!Shuffle)
7563     return SDValue();
7564   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
7565 }
7566
7567 enum ShuffleOpCodes {
7568   OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7569   OP_VREV,
7570   OP_VDUP0,
7571   OP_VDUP1,
7572   OP_VDUP2,
7573   OP_VDUP3,
7574   OP_VEXT1,
7575   OP_VEXT2,
7576   OP_VEXT3,
7577   OP_VUZPL, // VUZP, left result
7578   OP_VUZPR, // VUZP, right result
7579   OP_VZIPL, // VZIP, left result
7580   OP_VZIPR, // VZIP, right result
7581   OP_VTRNL, // VTRN, left result
7582   OP_VTRNR  // VTRN, right result
7583 };
7584
7585 static bool isLegalMVEShuffleOp(unsigned PFEntry) {
7586   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7587   switch (OpNum) {
7588   case OP_COPY:
7589   case OP_VREV:
7590   case OP_VDUP0:
7591   case OP_VDUP1:
7592   case OP_VDUP2:
7593   case OP_VDUP3:
7594     return true;
7595   }
7596   return false;
7597 }
7598
7599 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7600 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7601 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7602 /// are assumed to be legal.
7603 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7604   if (VT.getVectorNumElements() == 4 &&
7605       (VT.is128BitVector() || VT.is64BitVector())) {
7606     unsigned PFIndexes[4];
7607     for (unsigned i = 0; i != 4; ++i) {
7608       if (M[i] < 0)
7609         PFIndexes[i] = 8;
7610       else
7611         PFIndexes[i] = M[i];
7612     }
7613
7614     // Compute the index in the perfect shuffle table.
7615     unsigned PFTableIndex =
7616       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7617     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7618     unsigned Cost = (PFEntry >> 30);
7619
7620     if (Cost <= 4 && (Subtarget->hasNEON() || isLegalMVEShuffleOp(PFEntry)))
7621       return true;
7622   }
7623
7624   bool ReverseVEXT, isV_UNDEF;
7625   unsigned Imm, WhichResult;
7626
7627   unsigned EltSize = VT.getScalarSizeInBits();
7628   if (EltSize >= 32 ||
7629       ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7630       ShuffleVectorInst::isIdentityMask(M) ||
7631       isVREVMask(M, VT, 64) ||
7632       isVREVMask(M, VT, 32) ||
7633       isVREVMask(M, VT, 16))
7634     return true;
7635   else if (Subtarget->hasNEON() &&
7636            (isVEXTMask(M, VT, ReverseVEXT, Imm) ||
7637             isVTBLMask(M, VT) ||
7638             isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF)))
7639     return true;
7640   else if (Subtarget->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) &&
7641            isReverseMask(M, VT))
7642     return true;
7643   else if (Subtarget->hasMVEIntegerOps() &&
7644            (isVMOVNMask(M, VT, 0) || isVMOVNMask(M, VT, 1)))
7645     return true;
7646   else
7647     return false;
7648 }
7649
7650 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7651 /// the specified operations to build the shuffle.
7652 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7653                                       SDValue RHS, SelectionDAG &DAG,
7654                                       const SDLoc &dl) {
7655   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7656   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7657   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7658
7659   if (OpNum == OP_COPY) {
7660     if (LHSID == (1*9+2)*9+3) return LHS;
7661     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7662     return RHS;
7663   }
7664
7665   SDValue OpLHS, OpRHS;
7666   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7667   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7668   EVT VT = OpLHS.getValueType();
7669
7670   switch (OpNum) {
7671   default: llvm_unreachable("Unknown shuffle opcode!");
7672   case OP_VREV:
7673     // VREV divides the vector in half and swaps within the half.
7674     if (VT.getVectorElementType() == MVT::i32 ||
7675         VT.getVectorElementType() == MVT::f32)
7676       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
7677     // vrev <4 x i16> -> VREV32
7678     if (VT.getVectorElementType() == MVT::i16)
7679       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
7680     // vrev <4 x i8> -> VREV16
7681     assert(VT.getVectorElementType() == MVT::i8);
7682     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
7683   case OP_VDUP0:
7684   case OP_VDUP1:
7685   case OP_VDUP2:
7686   case OP_VDUP3:
7687     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
7688                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
7689   case OP_VEXT1:
7690   case OP_VEXT2:
7691   case OP_VEXT3:
7692     return DAG.getNode(ARMISD::VEXT, dl, VT,
7693                        OpLHS, OpRHS,
7694                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
7695   case OP_VUZPL:
7696   case OP_VUZPR:
7697     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
7698                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
7699   case OP_VZIPL:
7700   case OP_VZIPR:
7701     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
7702                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
7703   case OP_VTRNL:
7704   case OP_VTRNR:
7705     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
7706                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
7707   }
7708 }
7709
7710 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
7711                                        ArrayRef<int> ShuffleMask,
7712                                        SelectionDAG &DAG) {
7713   // Check to see if we can use the VTBL instruction.
7714   SDValue V1 = Op.getOperand(0);
7715   SDValue V2 = Op.getOperand(1);
7716   SDLoc DL(Op);
7717
7718   SmallVector<SDValue, 8> VTBLMask;
7719   for (ArrayRef<int>::iterator
7720          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
7721     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
7722
7723   if (V2.getNode()->isUndef())
7724     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
7725                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7726
7727   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
7728                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7729 }
7730
7731 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7732                                                       SelectionDAG &DAG) {
7733   SDLoc DL(Op);
7734   SDValue OpLHS = Op.getOperand(0);
7735   EVT VT = OpLHS.getValueType();
7736
7737   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7738          "Expect an v8i16/v16i8 type");
7739   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7740   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7741   // extract the first 8 bytes into the top double word and the last 8 bytes
7742   // into the bottom double word. The v8i16 case is similar.
7743   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7744   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7745                      DAG.getConstant(ExtractNum, DL, MVT::i32));
7746 }
7747
7748 static EVT getVectorTyFromPredicateVector(EVT VT) {
7749   switch (VT.getSimpleVT().SimpleTy) {
7750   case MVT::v4i1:
7751     return MVT::v4i32;
7752   case MVT::v8i1:
7753     return MVT::v8i16;
7754   case MVT::v16i1:
7755     return MVT::v16i8;
7756   default:
7757     llvm_unreachable("Unexpected vector predicate type");
7758   }
7759 }
7760
7761 static SDValue PromoteMVEPredVector(SDLoc dl, SDValue Pred, EVT VT,
7762                                     SelectionDAG &DAG) {
7763   // Converting from boolean predicates to integers involves creating a vector
7764   // of all ones or all zeroes and selecting the lanes based upon the real
7765   // predicate.
7766   SDValue AllOnes =
7767       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0xff), dl, MVT::i32);
7768   AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllOnes);
7769
7770   SDValue AllZeroes =
7771       DAG.getTargetConstant(ARM_AM::createVMOVModImm(0xe, 0x0), dl, MVT::i32);
7772   AllZeroes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v16i8, AllZeroes);
7773
7774   // Get full vector type from predicate type
7775   EVT NewVT = getVectorTyFromPredicateVector(VT);
7776
7777   SDValue RecastV1;
7778   // If the real predicate is an v8i1 or v4i1 (not v16i1) then we need to recast
7779   // this to a v16i1. This cannot be done with an ordinary bitcast because the
7780   // sizes are not the same. We have to use a MVE specific PREDICATE_CAST node,
7781   // since we know in hardware the sizes are really the same.
7782   if (VT != MVT::v16i1)
7783     RecastV1 = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Pred);
7784   else
7785     RecastV1 = Pred;
7786
7787   // Select either all ones or zeroes depending upon the real predicate bits.
7788   SDValue PredAsVector =
7789       DAG.getNode(ISD::VSELECT, dl, MVT::v16i8, RecastV1, AllOnes, AllZeroes);
7790
7791   // Recast our new predicate-as-integer v16i8 vector into something
7792   // appropriate for the shuffle, i.e. v4i32 for a real v4i1 predicate.
7793   return DAG.getNode(ISD::BITCAST, dl, NewVT, PredAsVector);
7794 }
7795
7796 static SDValue LowerVECTOR_SHUFFLE_i1(SDValue Op, SelectionDAG &DAG,
7797                                       const ARMSubtarget *ST) {
7798   EVT VT = Op.getValueType();
7799   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7800   ArrayRef<int> ShuffleMask = SVN->getMask();
7801
7802   assert(ST->hasMVEIntegerOps() &&
7803          "No support for vector shuffle of boolean predicates");
7804
7805   SDValue V1 = Op.getOperand(0);
7806   SDLoc dl(Op);
7807   if (isReverseMask(ShuffleMask, VT)) {
7808     SDValue cast = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, V1);
7809     SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, cast);
7810     SDValue srl = DAG.getNode(ISD::SRL, dl, MVT::i32, rbit,
7811                               DAG.getConstant(16, dl, MVT::i32));
7812     return DAG.getNode(ARMISD::PREDICATE_CAST, dl, VT, srl);
7813   }
7814
7815   // Until we can come up with optimised cases for every single vector
7816   // shuffle in existence we have chosen the least painful strategy. This is
7817   // to essentially promote the boolean predicate to a 8-bit integer, where
7818   // each predicate represents a byte. Then we fall back on a normal integer
7819   // vector shuffle and convert the result back into a predicate vector. In
7820   // many cases the generated code might be even better than scalar code
7821   // operating on bits. Just imagine trying to shuffle 8 arbitrary 2-bit
7822   // fields in a register into 8 other arbitrary 2-bit fields!
7823   SDValue PredAsVector = PromoteMVEPredVector(dl, V1, VT, DAG);
7824   EVT NewVT = PredAsVector.getValueType();
7825
7826   // Do the shuffle!
7827   SDValue Shuffled = DAG.getVectorShuffle(NewVT, dl, PredAsVector,
7828                                           DAG.getUNDEF(NewVT), ShuffleMask);
7829
7830   // Now return the result of comparing the shuffled vector with zero,
7831   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
7832   return DAG.getNode(ARMISD::VCMPZ, dl, VT, Shuffled,
7833                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
7834 }
7835
7836 static SDValue LowerVECTOR_SHUFFLEUsingMovs(SDValue Op,
7837                                             ArrayRef<int> ShuffleMask,
7838                                             SelectionDAG &DAG) {
7839   // Attempt to lower the vector shuffle using as many whole register movs as
7840   // possible. This is useful for types smaller than 32bits, which would
7841   // often otherwise become a series for grp movs.
7842   SDLoc dl(Op);
7843   EVT VT = Op.getValueType();
7844   if (VT.getScalarSizeInBits() >= 32)
7845     return SDValue();
7846
7847   assert((VT == MVT::v8i16 || VT == MVT::v8f16 || VT == MVT::v16i8) &&
7848          "Unexpected vector type");
7849   int NumElts = VT.getVectorNumElements();
7850   int QuarterSize = NumElts / 4;
7851   // The four final parts of the vector, as i32's
7852   SDValue Parts[4];
7853
7854   // Look for full lane vmovs like <0,1,2,3> or <u,5,6,7> etc, (but not
7855   // <u,u,u,u>), returning the vmov lane index
7856   auto getMovIdx = [](ArrayRef<int> ShuffleMask, int Start, int Length) {
7857     // Detect which mov lane this would be from the first non-undef element.
7858     int MovIdx = -1;
7859     for (int i = 0; i < Length; i++) {
7860       if (ShuffleMask[Start + i] >= 0) {
7861         if (ShuffleMask[Start + i] % Length != i)
7862           return -1;
7863         MovIdx = ShuffleMask[Start + i] / Length;
7864         break;
7865       }
7866     }
7867     // If all items are undef, leave this for other combines
7868     if (MovIdx == -1)
7869       return -1;
7870     // Check the remaining values are the correct part of the same mov
7871     for (int i = 1; i < Length; i++) {
7872       if (ShuffleMask[Start + i] >= 0 &&
7873           (ShuffleMask[Start + i] / Length != MovIdx ||
7874            ShuffleMask[Start + i] % Length != i))
7875         return -1;
7876     }
7877     return MovIdx;
7878   };
7879
7880   for (int Part = 0; Part < 4; ++Part) {
7881     // Does this part look like a mov
7882     int Elt = getMovIdx(ShuffleMask, Part * QuarterSize, QuarterSize);
7883     if (Elt != -1) {
7884       SDValue Input = Op->getOperand(0);
7885       if (Elt >= 4) {
7886         Input = Op->getOperand(1);
7887         Elt -= 4;
7888       }
7889       SDValue BitCast = DAG.getBitcast(MVT::v4i32, Input);
7890       Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, BitCast,
7891                                 DAG.getConstant(Elt, dl, MVT::i32));
7892     }
7893   }
7894
7895   // Nothing interesting found, just return
7896   if (!Parts[0] && !Parts[1] && !Parts[2] && !Parts[3])
7897     return SDValue();
7898
7899   // The other parts need to be built with the old shuffle vector, cast to a
7900   // v4i32 and extract_vector_elts
7901   if (!Parts[0] || !Parts[1] || !Parts[2] || !Parts[3]) {
7902     SmallVector<int, 16> NewShuffleMask;
7903     for (int Part = 0; Part < 4; ++Part)
7904       for (int i = 0; i < QuarterSize; i++)
7905         NewShuffleMask.push_back(
7906             Parts[Part] ? -1 : ShuffleMask[Part * QuarterSize + i]);
7907     SDValue NewShuffle = DAG.getVectorShuffle(
7908         VT, dl, Op->getOperand(0), Op->getOperand(1), NewShuffleMask);
7909     SDValue BitCast = DAG.getBitcast(MVT::v4i32, NewShuffle);
7910
7911     for (int Part = 0; Part < 4; ++Part)
7912       if (!Parts[Part])
7913         Parts[Part] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
7914                                   BitCast, DAG.getConstant(Part, dl, MVT::i32));
7915   }
7916   // Build a vector out of the various parts and bitcast it back to the original
7917   // type.
7918   SDValue NewVec = DAG.getBuildVector(MVT::v4i32, dl, Parts);
7919   return DAG.getBitcast(VT, NewVec);
7920 }
7921
7922 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
7923                                    const ARMSubtarget *ST) {
7924   SDValue V1 = Op.getOperand(0);
7925   SDValue V2 = Op.getOperand(1);
7926   SDLoc dl(Op);
7927   EVT VT = Op.getValueType();
7928   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7929   unsigned EltSize = VT.getScalarSizeInBits();
7930
7931   if (ST->hasMVEIntegerOps() && EltSize == 1)
7932     return LowerVECTOR_SHUFFLE_i1(Op, DAG, ST);
7933
7934   // Convert shuffles that are directly supported on NEON to target-specific
7935   // DAG nodes, instead of keeping them as shuffles and matching them again
7936   // during code selection.  This is more efficient and avoids the possibility
7937   // of inconsistencies between legalization and selection.
7938   // FIXME: floating-point vectors should be canonicalized to integer vectors
7939   // of the same time so that they get CSEd properly.
7940   ArrayRef<int> ShuffleMask = SVN->getMask();
7941
7942   if (EltSize <= 32) {
7943     if (SVN->isSplat()) {
7944       int Lane = SVN->getSplatIndex();
7945       // If this is undef splat, generate it via "just" vdup, if possible.
7946       if (Lane == -1) Lane = 0;
7947
7948       // Test if V1 is a SCALAR_TO_VECTOR.
7949       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7950         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7951       }
7952       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7953       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7954       // reaches it).
7955       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7956           !isa<ConstantSDNode>(V1.getOperand(0))) {
7957         bool IsScalarToVector = true;
7958         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7959           if (!V1.getOperand(i).isUndef()) {
7960             IsScalarToVector = false;
7961             break;
7962           }
7963         if (IsScalarToVector)
7964           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7965       }
7966       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7967                          DAG.getConstant(Lane, dl, MVT::i32));
7968     }
7969
7970     bool ReverseVEXT = false;
7971     unsigned Imm = 0;
7972     if (ST->hasNEON() && isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7973       if (ReverseVEXT)
7974         std::swap(V1, V2);
7975       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7976                          DAG.getConstant(Imm, dl, MVT::i32));
7977     }
7978
7979     if (isVREVMask(ShuffleMask, VT, 64))
7980       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7981     if (isVREVMask(ShuffleMask, VT, 32))
7982       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7983     if (isVREVMask(ShuffleMask, VT, 16))
7984       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7985
7986     if (ST->hasNEON() && V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7987       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7988                          DAG.getConstant(Imm, dl, MVT::i32));
7989     }
7990
7991     // Check for Neon shuffles that modify both input vectors in place.
7992     // If both results are used, i.e., if there are two shuffles with the same
7993     // source operands and with masks corresponding to both results of one of
7994     // these operations, DAG memoization will ensure that a single node is
7995     // used for both shuffles.
7996     unsigned WhichResult = 0;
7997     bool isV_UNDEF = false;
7998     if (ST->hasNEON()) {
7999       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8000               ShuffleMask, VT, WhichResult, isV_UNDEF)) {
8001         if (isV_UNDEF)
8002           V2 = V1;
8003         return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
8004             .getValue(WhichResult);
8005       }
8006     }
8007     if (ST->hasMVEIntegerOps()) {
8008       if (isVMOVNMask(ShuffleMask, VT, 0))
8009         return DAG.getNode(ARMISD::VMOVN, dl, VT, V2, V1,
8010                            DAG.getConstant(0, dl, MVT::i32));
8011       if (isVMOVNMask(ShuffleMask, VT, 1))
8012         return DAG.getNode(ARMISD::VMOVN, dl, VT, V1, V2,
8013                            DAG.getConstant(1, dl, MVT::i32));
8014     }
8015
8016     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
8017     // shuffles that produce a result larger than their operands with:
8018     //   shuffle(concat(v1, undef), concat(v2, undef))
8019     // ->
8020     //   shuffle(concat(v1, v2), undef)
8021     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
8022     //
8023     // This is useful in the general case, but there are special cases where
8024     // native shuffles produce larger results: the two-result ops.
8025     //
8026     // Look through the concat when lowering them:
8027     //   shuffle(concat(v1, v2), undef)
8028     // ->
8029     //   concat(VZIP(v1, v2):0, :1)
8030     //
8031     if (ST->hasNEON() && V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
8032       SDValue SubV1 = V1->getOperand(0);
8033       SDValue SubV2 = V1->getOperand(1);
8034       EVT SubVT = SubV1.getValueType();
8035
8036       // We expect these to have been canonicalized to -1.
8037       assert(llvm::all_of(ShuffleMask, [&](int i) {
8038         return i < (int)VT.getVectorNumElements();
8039       }) && "Unexpected shuffle index into UNDEF operand!");
8040
8041       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
8042               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
8043         if (isV_UNDEF)
8044           SubV2 = SubV1;
8045         assert((WhichResult == 0) &&
8046                "In-place shuffle of concat can only have one result!");
8047         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
8048                                   SubV1, SubV2);
8049         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
8050                            Res.getValue(1));
8051       }
8052     }
8053   }
8054
8055   // If the shuffle is not directly supported and it has 4 elements, use
8056   // the PerfectShuffle-generated table to synthesize it from other shuffles.
8057   unsigned NumElts = VT.getVectorNumElements();
8058   if (NumElts == 4) {
8059     unsigned PFIndexes[4];
8060     for (unsigned i = 0; i != 4; ++i) {
8061       if (ShuffleMask[i] < 0)
8062         PFIndexes[i] = 8;
8063       else
8064         PFIndexes[i] = ShuffleMask[i];
8065     }
8066
8067     // Compute the index in the perfect shuffle table.
8068     unsigned PFTableIndex =
8069       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8070     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8071     unsigned Cost = (PFEntry >> 30);
8072
8073     if (Cost <= 4) {
8074       if (ST->hasNEON())
8075         return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8076       else if (isLegalMVEShuffleOp(PFEntry)) {
8077         unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8078         unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8079         unsigned PFEntryLHS = PerfectShuffleTable[LHSID];
8080         unsigned PFEntryRHS = PerfectShuffleTable[RHSID];
8081         if (isLegalMVEShuffleOp(PFEntryLHS) && isLegalMVEShuffleOp(PFEntryRHS))
8082           return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8083       }
8084     }
8085   }
8086
8087   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
8088   if (EltSize >= 32) {
8089     // Do the expansion with floating-point types, since that is what the VFP
8090     // registers are defined to use, and since i64 is not legal.
8091     EVT EltVT = EVT::getFloatingPointVT(EltSize);
8092     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
8093     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
8094     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
8095     SmallVector<SDValue, 8> Ops;
8096     for (unsigned i = 0; i < NumElts; ++i) {
8097       if (ShuffleMask[i] < 0)
8098         Ops.push_back(DAG.getUNDEF(EltVT));
8099       else
8100         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8101                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
8102                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
8103                                                   dl, MVT::i32)));
8104     }
8105     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
8106     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
8107   }
8108
8109   if (ST->hasNEON() && (VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
8110     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
8111
8112   if (ST->hasNEON() && VT == MVT::v8i8)
8113     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
8114       return NewOp;
8115
8116   if (ST->hasMVEIntegerOps())
8117     if (SDValue NewOp = LowerVECTOR_SHUFFLEUsingMovs(Op, ShuffleMask, DAG))
8118       return NewOp;
8119
8120   return SDValue();
8121 }
8122
8123 static SDValue LowerINSERT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8124                                          const ARMSubtarget *ST) {
8125   EVT VecVT = Op.getOperand(0).getValueType();
8126   SDLoc dl(Op);
8127
8128   assert(ST->hasMVEIntegerOps() &&
8129          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8130
8131   SDValue Conv =
8132       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8133   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8134   unsigned LaneWidth =
8135       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8136   unsigned Mask = ((1 << LaneWidth) - 1) << Lane * LaneWidth;
8137   SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i32,
8138                             Op.getOperand(1), DAG.getValueType(MVT::i1));
8139   SDValue BFI = DAG.getNode(ARMISD::BFI, dl, MVT::i32, Conv, Ext,
8140                             DAG.getConstant(~Mask, dl, MVT::i32));
8141   return DAG.getNode(ARMISD::PREDICATE_CAST, dl, Op.getValueType(), BFI);
8142 }
8143
8144 SDValue ARMTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8145                                                   SelectionDAG &DAG) const {
8146   // INSERT_VECTOR_ELT is legal only for immediate indexes.
8147   SDValue Lane = Op.getOperand(2);
8148   if (!isa<ConstantSDNode>(Lane))
8149     return SDValue();
8150
8151   SDValue Elt = Op.getOperand(1);
8152   EVT EltVT = Elt.getValueType();
8153
8154   if (Subtarget->hasMVEIntegerOps() &&
8155       Op.getValueType().getScalarSizeInBits() == 1)
8156     return LowerINSERT_VECTOR_ELT_i1(Op, DAG, Subtarget);
8157
8158   if (getTypeAction(*DAG.getContext(), EltVT) ==
8159       TargetLowering::TypePromoteFloat) {
8160     // INSERT_VECTOR_ELT doesn't want f16 operands promoting to f32,
8161     // but the type system will try to do that if we don't intervene.
8162     // Reinterpret any such vector-element insertion as one with the
8163     // corresponding integer types.
8164
8165     SDLoc dl(Op);
8166
8167     EVT IEltVT = MVT::getIntegerVT(EltVT.getScalarSizeInBits());
8168     assert(getTypeAction(*DAG.getContext(), IEltVT) !=
8169            TargetLowering::TypePromoteFloat);
8170
8171     SDValue VecIn = Op.getOperand(0);
8172     EVT VecVT = VecIn.getValueType();
8173     EVT IVecVT = EVT::getVectorVT(*DAG.getContext(), IEltVT,
8174                                   VecVT.getVectorNumElements());
8175
8176     SDValue IElt = DAG.getNode(ISD::BITCAST, dl, IEltVT, Elt);
8177     SDValue IVecIn = DAG.getNode(ISD::BITCAST, dl, IVecVT, VecIn);
8178     SDValue IVecOut = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, IVecVT,
8179                                   IVecIn, IElt, Lane);
8180     return DAG.getNode(ISD::BITCAST, dl, VecVT, IVecOut);
8181   }
8182
8183   return Op;
8184 }
8185
8186 static SDValue LowerEXTRACT_VECTOR_ELT_i1(SDValue Op, SelectionDAG &DAG,
8187                                           const ARMSubtarget *ST) {
8188   EVT VecVT = Op.getOperand(0).getValueType();
8189   SDLoc dl(Op);
8190
8191   assert(ST->hasMVEIntegerOps() &&
8192          "LowerINSERT_VECTOR_ELT_i1 called without MVE!");
8193
8194   SDValue Conv =
8195       DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Op->getOperand(0));
8196   unsigned Lane = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8197   unsigned LaneWidth =
8198       getVectorTyFromPredicateVector(VecVT).getScalarSizeInBits() / 8;
8199   SDValue Shift = DAG.getNode(ISD::SRL, dl, MVT::i32, Conv,
8200                               DAG.getConstant(Lane * LaneWidth, dl, MVT::i32));
8201   return Shift;
8202 }
8203
8204 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG,
8205                                        const ARMSubtarget *ST) {
8206   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
8207   SDValue Lane = Op.getOperand(1);
8208   if (!isa<ConstantSDNode>(Lane))
8209     return SDValue();
8210
8211   SDValue Vec = Op.getOperand(0);
8212   EVT VT = Vec.getValueType();
8213
8214   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8215     return LowerEXTRACT_VECTOR_ELT_i1(Op, DAG, ST);
8216
8217   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
8218     SDLoc dl(Op);
8219     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
8220   }
8221
8222   return Op;
8223 }
8224
8225 static SDValue LowerCONCAT_VECTORS_i1(SDValue Op, SelectionDAG &DAG,
8226                                       const ARMSubtarget *ST) {
8227   SDValue V1 = Op.getOperand(0);
8228   SDValue V2 = Op.getOperand(1);
8229   SDLoc dl(Op);
8230   EVT VT = Op.getValueType();
8231   EVT Op1VT = V1.getValueType();
8232   EVT Op2VT = V2.getValueType();
8233   unsigned NumElts = VT.getVectorNumElements();
8234
8235   assert(Op1VT == Op2VT && "Operand types don't match!");
8236   assert(VT.getScalarSizeInBits() == 1 &&
8237          "Unexpected custom CONCAT_VECTORS lowering");
8238   assert(ST->hasMVEIntegerOps() &&
8239          "CONCAT_VECTORS lowering only supported for MVE");
8240
8241   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8242   SDValue NewV2 = PromoteMVEPredVector(dl, V2, Op2VT, DAG);
8243
8244   // We now have Op1 + Op2 promoted to vectors of integers, where v8i1 gets
8245   // promoted to v8i16, etc.
8246
8247   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8248
8249   // Extract the vector elements from Op1 and Op2 one by one and truncate them
8250   // to be the right size for the destination. For example, if Op1 is v4i1 then
8251   // the promoted vector is v4i32. The result of concatentation gives a v8i1,
8252   // which when promoted is v8i16. That means each i32 element from Op1 needs
8253   // truncating to i16 and inserting in the result.
8254   EVT ConcatVT = MVT::getVectorVT(ElType, NumElts);
8255   SDValue ConVec = DAG.getNode(ISD::UNDEF, dl, ConcatVT);
8256   auto ExractInto = [&DAG, &dl](SDValue NewV, SDValue ConVec, unsigned &j) {
8257     EVT NewVT = NewV.getValueType();
8258     EVT ConcatVT = ConVec.getValueType();
8259     for (unsigned i = 0, e = NewVT.getVectorNumElements(); i < e; i++, j++) {
8260       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV,
8261                                 DAG.getIntPtrConstant(i, dl));
8262       ConVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ConcatVT, ConVec, Elt,
8263                            DAG.getConstant(j, dl, MVT::i32));
8264     }
8265     return ConVec;
8266   };
8267   unsigned j = 0;
8268   ConVec = ExractInto(NewV1, ConVec, j);
8269   ConVec = ExractInto(NewV2, ConVec, j);
8270
8271   // Now return the result of comparing the subvector with zero,
8272   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8273   return DAG.getNode(ARMISD::VCMPZ, dl, VT, ConVec,
8274                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8275 }
8276
8277 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG,
8278                                    const ARMSubtarget *ST) {
8279   EVT VT = Op->getValueType(0);
8280   if (ST->hasMVEIntegerOps() && VT.getScalarSizeInBits() == 1)
8281     return LowerCONCAT_VECTORS_i1(Op, DAG, ST);
8282
8283   // The only time a CONCAT_VECTORS operation can have legal types is when
8284   // two 64-bit vectors are concatenated to a 128-bit vector.
8285   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
8286          "unexpected CONCAT_VECTORS");
8287   SDLoc dl(Op);
8288   SDValue Val = DAG.getUNDEF(MVT::v2f64);
8289   SDValue Op0 = Op.getOperand(0);
8290   SDValue Op1 = Op.getOperand(1);
8291   if (!Op0.isUndef())
8292     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8293                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
8294                       DAG.getIntPtrConstant(0, dl));
8295   if (!Op1.isUndef())
8296     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
8297                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
8298                       DAG.getIntPtrConstant(1, dl));
8299   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
8300 }
8301
8302 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, SelectionDAG &DAG,
8303                                       const ARMSubtarget *ST) {
8304   SDValue V1 = Op.getOperand(0);
8305   SDValue V2 = Op.getOperand(1);
8306   SDLoc dl(Op);
8307   EVT VT = Op.getValueType();
8308   EVT Op1VT = V1.getValueType();
8309   unsigned NumElts = VT.getVectorNumElements();
8310   unsigned Index = cast<ConstantSDNode>(V2)->getZExtValue();
8311
8312   assert(VT.getScalarSizeInBits() == 1 &&
8313          "Unexpected custom EXTRACT_SUBVECTOR lowering");
8314   assert(ST->hasMVEIntegerOps() &&
8315          "EXTRACT_SUBVECTOR lowering only supported for MVE");
8316
8317   SDValue NewV1 = PromoteMVEPredVector(dl, V1, Op1VT, DAG);
8318
8319   // We now have Op1 promoted to a vector of integers, where v8i1 gets
8320   // promoted to v8i16, etc.
8321
8322   MVT ElType = getVectorTyFromPredicateVector(VT).getScalarType().getSimpleVT();
8323
8324   EVT SubVT = MVT::getVectorVT(ElType, NumElts);
8325   SDValue SubVec = DAG.getNode(ISD::UNDEF, dl, SubVT);
8326   for (unsigned i = Index, j = 0; i < (Index + NumElts); i++, j++) {
8327     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, NewV1,
8328                               DAG.getIntPtrConstant(i, dl));
8329     SubVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, SubVT, SubVec, Elt,
8330                          DAG.getConstant(j, dl, MVT::i32));
8331   }
8332
8333   // Now return the result of comparing the subvector with zero,
8334   // which will generate a real predicate, i.e. v4i1, v8i1 or v16i1.
8335   return DAG.getNode(ARMISD::VCMPZ, dl, VT, SubVec,
8336                      DAG.getConstant(ARMCC::NE, dl, MVT::i32));
8337 }
8338
8339 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
8340 /// element has been zero/sign-extended, depending on the isSigned parameter,
8341 /// from an integer type half its size.
8342 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
8343                                    bool isSigned) {
8344   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
8345   EVT VT = N->getValueType(0);
8346   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
8347     SDNode *BVN = N->getOperand(0).getNode();
8348     if (BVN->getValueType(0) != MVT::v4i32 ||
8349         BVN->getOpcode() != ISD::BUILD_VECTOR)
8350       return false;
8351     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8352     unsigned HiElt = 1 - LoElt;
8353     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
8354     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
8355     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
8356     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
8357     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
8358       return false;
8359     if (isSigned) {
8360       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
8361           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
8362         return true;
8363     } else {
8364       if (Hi0->isNullValue() && Hi1->isNullValue())
8365         return true;
8366     }
8367     return false;
8368   }
8369
8370   if (N->getOpcode() != ISD::BUILD_VECTOR)
8371     return false;
8372
8373   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8374     SDNode *Elt = N->getOperand(i).getNode();
8375     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
8376       unsigned EltSize = VT.getScalarSizeInBits();
8377       unsigned HalfSize = EltSize / 2;
8378       if (isSigned) {
8379         if (!isIntN(HalfSize, C->getSExtValue()))
8380           return false;
8381       } else {
8382         if (!isUIntN(HalfSize, C->getZExtValue()))
8383           return false;
8384       }
8385       continue;
8386     }
8387     return false;
8388   }
8389
8390   return true;
8391 }
8392
8393 /// isSignExtended - Check if a node is a vector value that is sign-extended
8394 /// or a constant BUILD_VECTOR with sign-extended elements.
8395 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
8396   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
8397     return true;
8398   if (isExtendedBUILD_VECTOR(N, DAG, true))
8399     return true;
8400   return false;
8401 }
8402
8403 /// isZeroExtended - Check if a node is a vector value that is zero-extended
8404 /// or a constant BUILD_VECTOR with zero-extended elements.
8405 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
8406   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
8407     return true;
8408   if (isExtendedBUILD_VECTOR(N, DAG, false))
8409     return true;
8410   return false;
8411 }
8412
8413 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
8414   if (OrigVT.getSizeInBits() >= 64)
8415     return OrigVT;
8416
8417   assert(OrigVT.isSimple() && "Expecting a simple value type");
8418
8419   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
8420   switch (OrigSimpleTy) {
8421   default: llvm_unreachable("Unexpected Vector Type");
8422   case MVT::v2i8:
8423   case MVT::v2i16:
8424      return MVT::v2i32;
8425   case MVT::v4i8:
8426     return  MVT::v4i16;
8427   }
8428 }
8429
8430 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
8431 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
8432 /// We insert the required extension here to get the vector to fill a D register.
8433 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
8434                                             const EVT &OrigTy,
8435                                             const EVT &ExtTy,
8436                                             unsigned ExtOpcode) {
8437   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
8438   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
8439   // 64-bits we need to insert a new extension so that it will be 64-bits.
8440   assert(ExtTy.is128BitVector() && "Unexpected extension size");
8441   if (OrigTy.getSizeInBits() >= 64)
8442     return N;
8443
8444   // Must extend size to at least 64 bits to be used as an operand for VMULL.
8445   EVT NewVT = getExtensionTo64Bits(OrigTy);
8446
8447   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
8448 }
8449
8450 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
8451 /// does not do any sign/zero extension. If the original vector is less
8452 /// than 64 bits, an appropriate extension will be added after the load to
8453 /// reach a total size of 64 bits. We have to add the extension separately
8454 /// because ARM does not have a sign/zero extending load for vectors.
8455 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
8456   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
8457
8458   // The load already has the right type.
8459   if (ExtendedTy == LD->getMemoryVT())
8460     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
8461                        LD->getBasePtr(), LD->getPointerInfo(),
8462                        LD->getAlignment(), LD->getMemOperand()->getFlags());
8463
8464   // We need to create a zextload/sextload. We cannot just create a load
8465   // followed by a zext/zext node because LowerMUL is also run during normal
8466   // operation legalization where we can't create illegal types.
8467   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
8468                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
8469                         LD->getMemoryVT(), LD->getAlignment(),
8470                         LD->getMemOperand()->getFlags());
8471 }
8472
8473 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
8474 /// extending load, or BUILD_VECTOR with extended elements, return the
8475 /// unextended value. The unextended vector should be 64 bits so that it can
8476 /// be used as an operand to a VMULL instruction. If the original vector size
8477 /// before extension is less than 64 bits we add a an extension to resize
8478 /// the vector to 64 bits.
8479 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
8480   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
8481     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
8482                                         N->getOperand(0)->getValueType(0),
8483                                         N->getValueType(0),
8484                                         N->getOpcode());
8485
8486   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8487     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
8488            "Expected extending load");
8489
8490     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
8491     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
8492     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8493     SDValue extLoad =
8494         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
8495     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
8496
8497     return newLoad;
8498   }
8499
8500   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
8501   // have been legalized as a BITCAST from v4i32.
8502   if (N->getOpcode() == ISD::BITCAST) {
8503     SDNode *BVN = N->getOperand(0).getNode();
8504     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
8505            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
8506     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
8507     return DAG.getBuildVector(
8508         MVT::v2i32, SDLoc(N),
8509         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
8510   }
8511   // Construct a new BUILD_VECTOR with elements truncated to half the size.
8512   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
8513   EVT VT = N->getValueType(0);
8514   unsigned EltSize = VT.getScalarSizeInBits() / 2;
8515   unsigned NumElts = VT.getVectorNumElements();
8516   MVT TruncVT = MVT::getIntegerVT(EltSize);
8517   SmallVector<SDValue, 8> Ops;
8518   SDLoc dl(N);
8519   for (unsigned i = 0; i != NumElts; ++i) {
8520     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
8521     const APInt &CInt = C->getAPIntValue();
8522     // Element types smaller than 32 bits are not legal, so use i32 elements.
8523     // The values are implicitly truncated so sext vs. zext doesn't matter.
8524     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
8525   }
8526   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
8527 }
8528
8529 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
8530   unsigned Opcode = N->getOpcode();
8531   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8532     SDNode *N0 = N->getOperand(0).getNode();
8533     SDNode *N1 = N->getOperand(1).getNode();
8534     return N0->hasOneUse() && N1->hasOneUse() &&
8535       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
8536   }
8537   return false;
8538 }
8539
8540 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
8541   unsigned Opcode = N->getOpcode();
8542   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
8543     SDNode *N0 = N->getOperand(0).getNode();
8544     SDNode *N1 = N->getOperand(1).getNode();
8545     return N0->hasOneUse() && N1->hasOneUse() &&
8546       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
8547   }
8548   return false;
8549 }
8550
8551 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
8552   // Multiplications are only custom-lowered for 128-bit vectors so that
8553   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
8554   EVT VT = Op.getValueType();
8555   assert(VT.is128BitVector() && VT.isInteger() &&
8556          "unexpected type for custom-lowering ISD::MUL");
8557   SDNode *N0 = Op.getOperand(0).getNode();
8558   SDNode *N1 = Op.getOperand(1).getNode();
8559   unsigned NewOpc = 0;
8560   bool isMLA = false;
8561   bool isN0SExt = isSignExtended(N0, DAG);
8562   bool isN1SExt = isSignExtended(N1, DAG);
8563   if (isN0SExt && isN1SExt)
8564     NewOpc = ARMISD::VMULLs;
8565   else {
8566     bool isN0ZExt = isZeroExtended(N0, DAG);
8567     bool isN1ZExt = isZeroExtended(N1, DAG);
8568     if (isN0ZExt && isN1ZExt)
8569       NewOpc = ARMISD::VMULLu;
8570     else if (isN1SExt || isN1ZExt) {
8571       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
8572       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
8573       if (isN1SExt && isAddSubSExt(N0, DAG)) {
8574         NewOpc = ARMISD::VMULLs;
8575         isMLA = true;
8576       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
8577         NewOpc = ARMISD::VMULLu;
8578         isMLA = true;
8579       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
8580         std::swap(N0, N1);
8581         NewOpc = ARMISD::VMULLu;
8582         isMLA = true;
8583       }
8584     }
8585
8586     if (!NewOpc) {
8587       if (VT == MVT::v2i64)
8588         // Fall through to expand this.  It is not legal.
8589         return SDValue();
8590       else
8591         // Other vector multiplications are legal.
8592         return Op;
8593     }
8594   }
8595
8596   // Legalize to a VMULL instruction.
8597   SDLoc DL(Op);
8598   SDValue Op0;
8599   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
8600   if (!isMLA) {
8601     Op0 = SkipExtensionForVMULL(N0, DAG);
8602     assert(Op0.getValueType().is64BitVector() &&
8603            Op1.getValueType().is64BitVector() &&
8604            "unexpected types for extended operands to VMULL");
8605     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
8606   }
8607
8608   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
8609   // isel lowering to take advantage of no-stall back to back vmul + vmla.
8610   //   vmull q0, d4, d6
8611   //   vmlal q0, d5, d6
8612   // is faster than
8613   //   vaddl q0, d4, d5
8614   //   vmovl q1, d6
8615   //   vmul  q0, q0, q1
8616   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
8617   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
8618   EVT Op1VT = Op1.getValueType();
8619   return DAG.getNode(N0->getOpcode(), DL, VT,
8620                      DAG.getNode(NewOpc, DL, VT,
8621                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
8622                      DAG.getNode(NewOpc, DL, VT,
8623                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
8624 }
8625
8626 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
8627                               SelectionDAG &DAG) {
8628   // TODO: Should this propagate fast-math-flags?
8629
8630   // Convert to float
8631   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
8632   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
8633   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
8634   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
8635   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
8636   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
8637   // Get reciprocal estimate.
8638   // float4 recip = vrecpeq_f32(yf);
8639   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8640                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8641                    Y);
8642   // Because char has a smaller range than uchar, we can actually get away
8643   // without any newton steps.  This requires that we use a weird bias
8644   // of 0xb000, however (again, this has been exhaustively tested).
8645   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
8646   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
8647   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
8648   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
8649   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
8650   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
8651   // Convert back to short.
8652   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
8653   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
8654   return X;
8655 }
8656
8657 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
8658                                SelectionDAG &DAG) {
8659   // TODO: Should this propagate fast-math-flags?
8660
8661   SDValue N2;
8662   // Convert to float.
8663   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
8664   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
8665   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
8666   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
8667   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8668   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8669
8670   // Use reciprocal estimate and one refinement step.
8671   // float4 recip = vrecpeq_f32(yf);
8672   // recip *= vrecpsq_f32(yf, recip);
8673   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8674                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8675                    N1);
8676   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8677                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8678                    N1, N2);
8679   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8680   // Because short has a smaller range than ushort, we can actually get away
8681   // with only a single newton step.  This requires that we use a weird bias
8682   // of 89, however (again, this has been exhaustively tested).
8683   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
8684   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8685   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8686   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
8687   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8688   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8689   // Convert back to integer and return.
8690   // return vmovn_s32(vcvt_s32_f32(result));
8691   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8692   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8693   return N0;
8694 }
8695
8696 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG,
8697                          const ARMSubtarget *ST) {
8698   EVT VT = Op.getValueType();
8699   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8700          "unexpected type for custom-lowering ISD::SDIV");
8701
8702   SDLoc dl(Op);
8703   SDValue N0 = Op.getOperand(0);
8704   SDValue N1 = Op.getOperand(1);
8705   SDValue N2, N3;
8706
8707   if (VT == MVT::v8i8) {
8708     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
8709     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
8710
8711     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8712                      DAG.getIntPtrConstant(4, dl));
8713     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8714                      DAG.getIntPtrConstant(4, dl));
8715     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8716                      DAG.getIntPtrConstant(0, dl));
8717     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8718                      DAG.getIntPtrConstant(0, dl));
8719
8720     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
8721     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
8722
8723     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8724     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8725
8726     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
8727     return N0;
8728   }
8729   return LowerSDIV_v4i16(N0, N1, dl, DAG);
8730 }
8731
8732 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG,
8733                          const ARMSubtarget *ST) {
8734   // TODO: Should this propagate fast-math-flags?
8735   EVT VT = Op.getValueType();
8736   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
8737          "unexpected type for custom-lowering ISD::UDIV");
8738
8739   SDLoc dl(Op);
8740   SDValue N0 = Op.getOperand(0);
8741   SDValue N1 = Op.getOperand(1);
8742   SDValue N2, N3;
8743
8744   if (VT == MVT::v8i8) {
8745     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
8746     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
8747
8748     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8749                      DAG.getIntPtrConstant(4, dl));
8750     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8751                      DAG.getIntPtrConstant(4, dl));
8752     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
8753                      DAG.getIntPtrConstant(0, dl));
8754     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
8755                      DAG.getIntPtrConstant(0, dl));
8756
8757     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
8758     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
8759
8760     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
8761     N0 = LowerCONCAT_VECTORS(N0, DAG, ST);
8762
8763     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
8764                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
8765                                      MVT::i32),
8766                      N0);
8767     return N0;
8768   }
8769
8770   // v4i16 sdiv ... Convert to float.
8771   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
8772   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
8773   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
8774   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
8775   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
8776   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
8777
8778   // Use reciprocal estimate and two refinement steps.
8779   // float4 recip = vrecpeq_f32(yf);
8780   // recip *= vrecpsq_f32(yf, recip);
8781   // recip *= vrecpsq_f32(yf, recip);
8782   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8783                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
8784                    BN1);
8785   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8786                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8787                    BN1, N2);
8788   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8789   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
8790                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
8791                    BN1, N2);
8792   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
8793   // Simply multiplying by the reciprocal estimate can leave us a few ulps
8794   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
8795   // and that it will never cause us to return an answer too large).
8796   // float4 result = as_float4(as_int4(xf*recip) + 2);
8797   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
8798   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
8799   N1 = DAG.getConstant(2, dl, MVT::v4i32);
8800   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
8801   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
8802   // Convert back to integer and return.
8803   // return vmovn_u32(vcvt_s32_f32(result));
8804   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
8805   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
8806   return N0;
8807 }
8808
8809 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
8810   SDNode *N = Op.getNode();
8811   EVT VT = N->getValueType(0);
8812   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8813
8814   SDValue Carry = Op.getOperand(2);
8815
8816   SDLoc DL(Op);
8817
8818   SDValue Result;
8819   if (Op.getOpcode() == ISD::ADDCARRY) {
8820     // This converts the boolean value carry into the carry flag.
8821     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8822
8823     // Do the addition proper using the carry flag we wanted.
8824     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
8825                          Op.getOperand(1), Carry);
8826
8827     // Now convert the carry flag into a boolean value.
8828     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8829   } else {
8830     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
8831     // have to invert the carry first.
8832     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8833                         DAG.getConstant(1, DL, MVT::i32), Carry);
8834     // This converts the boolean value carry into the carry flag.
8835     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
8836
8837     // Do the subtraction proper using the carry flag we wanted.
8838     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
8839                          Op.getOperand(1), Carry);
8840
8841     // Now convert the carry flag into a boolean value.
8842     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
8843     // But the carry returned by ARMISD::SUBE is not a borrow as expected
8844     // by ISD::SUBCARRY, so compute 1 - C.
8845     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
8846                         DAG.getConstant(1, DL, MVT::i32), Carry);
8847   }
8848
8849   // Return both values.
8850   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
8851 }
8852
8853 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
8854   assert(Subtarget->isTargetDarwin());
8855
8856   // For iOS, we want to call an alternative entry point: __sincos_stret,
8857   // return values are passed via sret.
8858   SDLoc dl(Op);
8859   SDValue Arg = Op.getOperand(0);
8860   EVT ArgVT = Arg.getValueType();
8861   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
8862   auto PtrVT = getPointerTy(DAG.getDataLayout());
8863
8864   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8866
8867   // Pair of floats / doubles used to pass the result.
8868   Type *RetTy = StructType::get(ArgTy, ArgTy);
8869   auto &DL = DAG.getDataLayout();
8870
8871   ArgListTy Args;
8872   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
8873   SDValue SRet;
8874   if (ShouldUseSRet) {
8875     // Create stack object for sret.
8876     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
8877     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
8878     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
8879     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
8880
8881     ArgListEntry Entry;
8882     Entry.Node = SRet;
8883     Entry.Ty = RetTy->getPointerTo();
8884     Entry.IsSExt = false;
8885     Entry.IsZExt = false;
8886     Entry.IsSRet = true;
8887     Args.push_back(Entry);
8888     RetTy = Type::getVoidTy(*DAG.getContext());
8889   }
8890
8891   ArgListEntry Entry;
8892   Entry.Node = Arg;
8893   Entry.Ty = ArgTy;
8894   Entry.IsSExt = false;
8895   Entry.IsZExt = false;
8896   Args.push_back(Entry);
8897
8898   RTLIB::Libcall LC =
8899       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
8900   const char *LibcallName = getLibcallName(LC);
8901   CallingConv::ID CC = getLibcallCallingConv(LC);
8902   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
8903
8904   TargetLowering::CallLoweringInfo CLI(DAG);
8905   CLI.setDebugLoc(dl)
8906       .setChain(DAG.getEntryNode())
8907       .setCallee(CC, RetTy, Callee, std::move(Args))
8908       .setDiscardResult(ShouldUseSRet);
8909   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8910
8911   if (!ShouldUseSRet)
8912     return CallResult.first;
8913
8914   SDValue LoadSin =
8915       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
8916
8917   // Address of cos field.
8918   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
8919                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
8920   SDValue LoadCos =
8921       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
8922
8923   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
8924   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
8925                      LoadSin.getValue(0), LoadCos.getValue(0));
8926 }
8927
8928 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
8929                                                   bool Signed,
8930                                                   SDValue &Chain) const {
8931   EVT VT = Op.getValueType();
8932   assert((VT == MVT::i32 || VT == MVT::i64) &&
8933          "unexpected type for custom lowering DIV");
8934   SDLoc dl(Op);
8935
8936   const auto &DL = DAG.getDataLayout();
8937   const auto &TLI = DAG.getTargetLoweringInfo();
8938
8939   const char *Name = nullptr;
8940   if (Signed)
8941     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
8942   else
8943     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
8944
8945   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
8946
8947   ARMTargetLowering::ArgListTy Args;
8948
8949   for (auto AI : {1, 0}) {
8950     ArgListEntry Arg;
8951     Arg.Node = Op.getOperand(AI);
8952     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
8953     Args.push_back(Arg);
8954   }
8955
8956   CallLoweringInfo CLI(DAG);
8957   CLI.setDebugLoc(dl)
8958     .setChain(Chain)
8959     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
8960                ES, std::move(Args));
8961
8962   return LowerCallTo(CLI).first;
8963 }
8964
8965 // This is a code size optimisation: return the original SDIV node to
8966 // DAGCombiner when we don't want to expand SDIV into a sequence of
8967 // instructions, and an empty node otherwise which will cause the
8968 // SDIV to be expanded in DAGCombine.
8969 SDValue
8970 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8971                                  SelectionDAG &DAG,
8972                                  SmallVectorImpl<SDNode *> &Created) const {
8973   // TODO: Support SREM
8974   if (N->getOpcode() != ISD::SDIV)
8975     return SDValue();
8976
8977   const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
8978   const bool MinSize = ST.hasMinSize();
8979   const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
8980                                       : ST.hasDivideInARMMode();
8981
8982   // Don't touch vector types; rewriting this may lead to scalarizing
8983   // the int divs.
8984   if (N->getOperand(0).getValueType().isVector())
8985     return SDValue();
8986
8987   // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
8988   // hwdiv support for this to be really profitable.
8989   if (!(MinSize && HasDivide))
8990     return SDValue();
8991
8992   // ARM mode is a bit simpler than Thumb: we can handle large power
8993   // of 2 immediates with 1 mov instruction; no further checks required,
8994   // just return the sdiv node.
8995   if (!ST.isThumb())
8996     return SDValue(N, 0);
8997
8998   // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
8999   // and thus lose the code size benefits of a MOVS that requires only 2.
9000   // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
9001   // but as it's doing exactly this, it's not worth the trouble to get TTI.
9002   if (Divisor.sgt(128))
9003     return SDValue();
9004
9005   return SDValue(N, 0);
9006 }
9007
9008 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
9009                                             bool Signed) const {
9010   assert(Op.getValueType() == MVT::i32 &&
9011          "unexpected type for custom lowering DIV");
9012   SDLoc dl(Op);
9013
9014   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
9015                                DAG.getEntryNode(), Op.getOperand(1));
9016
9017   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9018 }
9019
9020 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
9021   SDLoc DL(N);
9022   SDValue Op = N->getOperand(1);
9023   if (N->getValueType(0) == MVT::i32)
9024     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
9025   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9026                            DAG.getConstant(0, DL, MVT::i32));
9027   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
9028                            DAG.getConstant(1, DL, MVT::i32));
9029   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
9030                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
9031 }
9032
9033 void ARMTargetLowering::ExpandDIV_Windows(
9034     SDValue Op, SelectionDAG &DAG, bool Signed,
9035     SmallVectorImpl<SDValue> &Results) const {
9036   const auto &DL = DAG.getDataLayout();
9037   const auto &TLI = DAG.getTargetLoweringInfo();
9038
9039   assert(Op.getValueType() == MVT::i64 &&
9040          "unexpected type for custom lowering DIV");
9041   SDLoc dl(Op);
9042
9043   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
9044
9045   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
9046
9047   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
9048   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
9049                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
9050   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
9051
9052   Results.push_back(Lower);
9053   Results.push_back(Upper);
9054 }
9055
9056 static SDValue LowerPredicateLoad(SDValue Op, SelectionDAG &DAG) {
9057   LoadSDNode *LD = cast<LoadSDNode>(Op.getNode());
9058   EVT MemVT = LD->getMemoryVT();
9059   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9060          "Expected a predicate type!");
9061   assert(MemVT == Op.getValueType());
9062   assert(LD->getExtensionType() == ISD::NON_EXTLOAD &&
9063          "Expected a non-extending load");
9064   assert(LD->isUnindexed() && "Expected a unindexed load");
9065
9066   // The basic MVE VLDR on a v4i1/v8i1 actually loads the entire 16bit
9067   // predicate, with the "v4i1" bits spread out over the 16 bits loaded. We
9068   // need to make sure that 8/4 bits are actually loaded into the correct
9069   // place, which means loading the value and then shuffling the values into
9070   // the bottom bits of the predicate.
9071   // Equally, VLDR for an v16i1 will actually load 32bits (so will be incorrect
9072   // for BE).
9073
9074   SDLoc dl(Op);
9075   SDValue Load = DAG.getExtLoad(
9076       ISD::EXTLOAD, dl, MVT::i32, LD->getChain(), LD->getBasePtr(),
9077       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9078       LD->getMemOperand());
9079   SDValue Pred = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::v16i1, Load);
9080   if (MemVT != MVT::v16i1)
9081     Pred = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MemVT, Pred,
9082                        DAG.getConstant(0, dl, MVT::i32));
9083   return DAG.getMergeValues({Pred, Load.getValue(1)}, dl);
9084 }
9085
9086 static SDValue LowerPredicateStore(SDValue Op, SelectionDAG &DAG) {
9087   StoreSDNode *ST = cast<StoreSDNode>(Op.getNode());
9088   EVT MemVT = ST->getMemoryVT();
9089   assert((MemVT == MVT::v4i1 || MemVT == MVT::v8i1 || MemVT == MVT::v16i1) &&
9090          "Expected a predicate type!");
9091   assert(MemVT == ST->getValue().getValueType());
9092   assert(!ST->isTruncatingStore() && "Expected a non-extending store");
9093   assert(ST->isUnindexed() && "Expected a unindexed store");
9094
9095   // Only store the v4i1 or v8i1 worth of bits, via a buildvector with top bits
9096   // unset and a scalar store.
9097   SDLoc dl(Op);
9098   SDValue Build = ST->getValue();
9099   if (MemVT != MVT::v16i1) {
9100     SmallVector<SDValue, 16> Ops;
9101     for (unsigned I = 0; I < MemVT.getVectorNumElements(); I++)
9102       Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32, Build,
9103                                 DAG.getConstant(I, dl, MVT::i32)));
9104     for (unsigned I = MemVT.getVectorNumElements(); I < 16; I++)
9105       Ops.push_back(DAG.getUNDEF(MVT::i32));
9106     Build = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i1, Ops);
9107   }
9108   SDValue GRP = DAG.getNode(ARMISD::PREDICATE_CAST, dl, MVT::i32, Build);
9109   return DAG.getTruncStore(
9110       ST->getChain(), dl, GRP, ST->getBasePtr(),
9111       EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits()),
9112       ST->getMemOperand());
9113 }
9114
9115 static bool isZeroVector(SDValue N) {
9116   return (ISD::isBuildVectorAllZeros(N.getNode()) ||
9117           (N->getOpcode() == ARMISD::VMOVIMM &&
9118            isNullConstant(N->getOperand(0))));
9119 }
9120
9121 static SDValue LowerMLOAD(SDValue Op, SelectionDAG &DAG) {
9122   MaskedLoadSDNode *N = cast<MaskedLoadSDNode>(Op.getNode());
9123   MVT VT = Op.getSimpleValueType();
9124   SDValue Mask = N->getMask();
9125   SDValue PassThru = N->getPassThru();
9126   SDLoc dl(Op);
9127
9128   if (isZeroVector(PassThru))
9129     return Op;
9130
9131   // MVE Masked loads use zero as the passthru value. Here we convert undef to
9132   // zero too, and other values are lowered to a select.
9133   SDValue ZeroVec = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
9134                                 DAG.getTargetConstant(0, dl, MVT::i32));
9135   SDValue NewLoad = DAG.getMaskedLoad(
9136       VT, dl, N->getChain(), N->getBasePtr(), N->getOffset(), Mask, ZeroVec,
9137       N->getMemoryVT(), N->getMemOperand(), N->getAddressingMode(),
9138       N->getExtensionType(), N->isExpandingLoad());
9139   SDValue Combo = NewLoad;
9140   if (!PassThru.isUndef() &&
9141       (PassThru.getOpcode() != ISD::BITCAST ||
9142        !isZeroVector(PassThru->getOperand(0))))
9143     Combo = DAG.getNode(ISD::VSELECT, dl, VT, Mask, NewLoad, PassThru);
9144   return DAG.getMergeValues({Combo, NewLoad.getValue(1)}, dl);
9145 }
9146
9147 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
9148   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
9149     // Acquire/Release load/store is not legal for targets without a dmb or
9150     // equivalent available.
9151     return SDValue();
9152
9153   // Monotonic load/store is legal for all targets.
9154   return Op;
9155 }
9156
9157 static void ReplaceREADCYCLECOUNTER(SDNode *N,
9158                                     SmallVectorImpl<SDValue> &Results,
9159                                     SelectionDAG &DAG,
9160                                     const ARMSubtarget *Subtarget) {
9161   SDLoc DL(N);
9162   // Under Power Management extensions, the cycle-count is:
9163   //    mrc p15, #0, <Rt>, c9, c13, #0
9164   SDValue Ops[] = { N->getOperand(0), // Chain
9165                     DAG.getTargetConstant(Intrinsic::arm_mrc, DL, MVT::i32),
9166                     DAG.getTargetConstant(15, DL, MVT::i32),
9167                     DAG.getTargetConstant(0, DL, MVT::i32),
9168                     DAG.getTargetConstant(9, DL, MVT::i32),
9169                     DAG.getTargetConstant(13, DL, MVT::i32),
9170                     DAG.getTargetConstant(0, DL, MVT::i32)
9171   };
9172
9173   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
9174                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
9175   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
9176                                 DAG.getConstant(0, DL, MVT::i32)));
9177   Results.push_back(Cycles32.getValue(1));
9178 }
9179
9180 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
9181   SDLoc dl(V.getNode());
9182   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
9183   SDValue VHi = DAG.getAnyExtOrTrunc(
9184       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
9185       dl, MVT::i32);
9186   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9187   if (isBigEndian)
9188     std::swap (VLo, VHi);
9189   SDValue RegClass =
9190       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
9191   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
9192   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
9193   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
9194   return SDValue(
9195       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
9196 }
9197
9198 static void ReplaceCMP_SWAP_64Results(SDNode *N,
9199                                        SmallVectorImpl<SDValue> & Results,
9200                                        SelectionDAG &DAG) {
9201   assert(N->getValueType(0) == MVT::i64 &&
9202          "AtomicCmpSwap on types less than 64 should be legal");
9203   SDValue Ops[] = {N->getOperand(1),
9204                    createGPRPairNode(DAG, N->getOperand(2)),
9205                    createGPRPairNode(DAG, N->getOperand(3)),
9206                    N->getOperand(0)};
9207   SDNode *CmpSwap = DAG.getMachineNode(
9208       ARM::CMP_SWAP_64, SDLoc(N),
9209       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
9210
9211   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
9212   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
9213
9214   bool isBigEndian = DAG.getDataLayout().isBigEndian();
9215
9216   Results.push_back(
9217       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
9218                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
9219   Results.push_back(
9220       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
9221                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
9222   Results.push_back(SDValue(CmpSwap, 2));
9223 }
9224
9225 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9226   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
9227   switch (Op.getOpcode()) {
9228   default: llvm_unreachable("Don't know how to custom lower this!");
9229   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
9230   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
9231   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
9232   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
9233   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
9234   case ISD::SELECT:        return LowerSELECT(Op, DAG);
9235   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
9236   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
9237   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
9238   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
9239   case ISD::VASTART:       return LowerVASTART(Op, DAG);
9240   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
9241   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
9242   case ISD::SINT_TO_FP:
9243   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
9244   case ISD::STRICT_FP_TO_SINT:
9245   case ISD::STRICT_FP_TO_UINT:
9246   case ISD::FP_TO_SINT:
9247   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
9248   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
9249   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
9250   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
9251   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
9252   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
9253   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
9254   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG, Subtarget);
9255   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
9256                                                                Subtarget);
9257   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
9258   case ISD::SHL:
9259   case ISD::SRL:
9260   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
9261   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
9262   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
9263   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
9264   case ISD::SRL_PARTS:
9265   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
9266   case ISD::CTTZ:
9267   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
9268   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
9269   case ISD::SETCC:         return LowerVSETCC(Op, DAG, Subtarget);
9270   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
9271   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
9272   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
9273   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
9274   case ISD::EXTRACT_SUBVECTOR: return LowerEXTRACT_SUBVECTOR(Op, DAG, Subtarget);
9275   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
9276   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG, Subtarget);
9277   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG, Subtarget);
9278   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
9279   case ISD::MUL:           return LowerMUL(Op, DAG);
9280   case ISD::SDIV:
9281     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9282       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
9283     return LowerSDIV(Op, DAG, Subtarget);
9284   case ISD::UDIV:
9285     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
9286       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
9287     return LowerUDIV(Op, DAG, Subtarget);
9288   case ISD::ADDCARRY:
9289   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
9290   case ISD::SADDO:
9291   case ISD::SSUBO:
9292     return LowerSignedALUO(Op, DAG);
9293   case ISD::UADDO:
9294   case ISD::USUBO:
9295     return LowerUnsignedALUO(Op, DAG);
9296   case ISD::SADDSAT:
9297   case ISD::SSUBSAT:
9298     return LowerSADDSUBSAT(Op, DAG, Subtarget);
9299   case ISD::LOAD:
9300     return LowerPredicateLoad(Op, DAG);
9301   case ISD::STORE:
9302     return LowerPredicateStore(Op, DAG);
9303   case ISD::MLOAD:
9304     return LowerMLOAD(Op, DAG);
9305   case ISD::ATOMIC_LOAD:
9306   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
9307   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
9308   case ISD::SDIVREM:
9309   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
9310   case ISD::DYNAMIC_STACKALLOC:
9311     if (Subtarget->isTargetWindows())
9312       return LowerDYNAMIC_STACKALLOC(Op, DAG);
9313     llvm_unreachable("Don't know how to custom lower this!");
9314   case ISD::STRICT_FP_ROUND:
9315   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
9316   case ISD::STRICT_FP_EXTEND:
9317   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
9318   case ARMISD::WIN__DBZCHK: return SDValue();
9319   }
9320 }
9321
9322 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
9323                                  SelectionDAG &DAG) {
9324   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9325   unsigned Opc = 0;
9326   if (IntNo == Intrinsic::arm_smlald)
9327     Opc = ARMISD::SMLALD;
9328   else if (IntNo == Intrinsic::arm_smlaldx)
9329     Opc = ARMISD::SMLALDX;
9330   else if (IntNo == Intrinsic::arm_smlsld)
9331     Opc = ARMISD::SMLSLD;
9332   else if (IntNo == Intrinsic::arm_smlsldx)
9333     Opc = ARMISD::SMLSLDX;
9334   else
9335     return;
9336
9337   SDLoc dl(N);
9338   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9339                            N->getOperand(3),
9340                            DAG.getConstant(0, dl, MVT::i32));
9341   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
9342                            N->getOperand(3),
9343                            DAG.getConstant(1, dl, MVT::i32));
9344
9345   SDValue LongMul = DAG.getNode(Opc, dl,
9346                                 DAG.getVTList(MVT::i32, MVT::i32),
9347                                 N->getOperand(1), N->getOperand(2),
9348                                 Lo, Hi);
9349   Results.push_back(LongMul.getValue(0));
9350   Results.push_back(LongMul.getValue(1));
9351 }
9352
9353 /// ReplaceNodeResults - Replace the results of node with an illegal result
9354 /// type with new values built out of custom code.
9355 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
9356                                            SmallVectorImpl<SDValue> &Results,
9357                                            SelectionDAG &DAG) const {
9358   SDValue Res;
9359   switch (N->getOpcode()) {
9360   default:
9361     llvm_unreachable("Don't know how to custom expand this!");
9362   case ISD::READ_REGISTER:
9363     ExpandREAD_REGISTER(N, Results, DAG);
9364     break;
9365   case ISD::BITCAST:
9366     Res = ExpandBITCAST(N, DAG, Subtarget);
9367     break;
9368   case ISD::SRL:
9369   case ISD::SRA:
9370   case ISD::SHL:
9371     Res = Expand64BitShift(N, DAG, Subtarget);
9372     break;
9373   case ISD::SREM:
9374   case ISD::UREM:
9375     Res = LowerREM(N, DAG);
9376     break;
9377   case ISD::SDIVREM:
9378   case ISD::UDIVREM:
9379     Res = LowerDivRem(SDValue(N, 0), DAG);
9380     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
9381     Results.push_back(Res.getValue(0));
9382     Results.push_back(Res.getValue(1));
9383     return;
9384   case ISD::SADDSAT:
9385   case ISD::SSUBSAT:
9386     Res = LowerSADDSUBSAT(SDValue(N, 0), DAG, Subtarget);
9387     break;
9388   case ISD::READCYCLECOUNTER:
9389     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
9390     return;
9391   case ISD::UDIV:
9392   case ISD::SDIV:
9393     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
9394     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
9395                              Results);
9396   case ISD::ATOMIC_CMP_SWAP:
9397     ReplaceCMP_SWAP_64Results(N, Results, DAG);
9398     return;
9399   case ISD::INTRINSIC_WO_CHAIN:
9400     return ReplaceLongIntrinsic(N, Results, DAG);
9401   case ISD::ABS:
9402      lowerABS(N, Results, DAG);
9403      return ;
9404
9405   }
9406   if (Res.getNode())
9407     Results.push_back(Res);
9408 }
9409
9410 //===----------------------------------------------------------------------===//
9411 //                           ARM Scheduler Hooks
9412 //===----------------------------------------------------------------------===//
9413
9414 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
9415 /// registers the function context.
9416 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
9417                                                MachineBasicBlock *MBB,
9418                                                MachineBasicBlock *DispatchBB,
9419                                                int FI) const {
9420   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
9421          "ROPI/RWPI not currently supported with SjLj");
9422   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9423   DebugLoc dl = MI.getDebugLoc();
9424   MachineFunction *MF = MBB->getParent();
9425   MachineRegisterInfo *MRI = &MF->getRegInfo();
9426   MachineConstantPool *MCP = MF->getConstantPool();
9427   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
9428   const Function &F = MF->getFunction();
9429
9430   bool isThumb = Subtarget->isThumb();
9431   bool isThumb2 = Subtarget->isThumb2();
9432
9433   unsigned PCLabelId = AFI->createPICLabelUId();
9434   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
9435   ARMConstantPoolValue *CPV =
9436     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
9437   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
9438
9439   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
9440                                            : &ARM::GPRRegClass;
9441
9442   // Grab constant pool and fixed stack memory operands.
9443   MachineMemOperand *CPMMO =
9444       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
9445                                MachineMemOperand::MOLoad, 4, 4);
9446
9447   MachineMemOperand *FIMMOSt =
9448       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
9449                                MachineMemOperand::MOStore, 4, 4);
9450
9451   // Load the address of the dispatch MBB into the jump buffer.
9452   if (isThumb2) {
9453     // Incoming value: jbuf
9454     //   ldr.n  r5, LCPI1_1
9455     //   orr    r5, r5, #1
9456     //   add    r5, pc
9457     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
9458     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9459     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
9460         .addConstantPoolIndex(CPI)
9461         .addMemOperand(CPMMO)
9462         .add(predOps(ARMCC::AL));
9463     // Set the low bit because of thumb mode.
9464     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9465     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
9466         .addReg(NewVReg1, RegState::Kill)
9467         .addImm(0x01)
9468         .add(predOps(ARMCC::AL))
9469         .add(condCodeOp());
9470     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9471     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
9472       .addReg(NewVReg2, RegState::Kill)
9473       .addImm(PCLabelId);
9474     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
9475         .addReg(NewVReg3, RegState::Kill)
9476         .addFrameIndex(FI)
9477         .addImm(36) // &jbuf[1] :: pc
9478         .addMemOperand(FIMMOSt)
9479         .add(predOps(ARMCC::AL));
9480   } else if (isThumb) {
9481     // Incoming value: jbuf
9482     //   ldr.n  r1, LCPI1_4
9483     //   add    r1, pc
9484     //   mov    r2, #1
9485     //   orrs   r1, r2
9486     //   add    r2, $jbuf, #+4 ; &jbuf[1]
9487     //   str    r1, [r2]
9488     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9489     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
9490         .addConstantPoolIndex(CPI)
9491         .addMemOperand(CPMMO)
9492         .add(predOps(ARMCC::AL));
9493     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9494     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
9495       .addReg(NewVReg1, RegState::Kill)
9496       .addImm(PCLabelId);
9497     // Set the low bit because of thumb mode.
9498     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9499     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
9500         .addReg(ARM::CPSR, RegState::Define)
9501         .addImm(1)
9502         .add(predOps(ARMCC::AL));
9503     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9504     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
9505         .addReg(ARM::CPSR, RegState::Define)
9506         .addReg(NewVReg2, RegState::Kill)
9507         .addReg(NewVReg3, RegState::Kill)
9508         .add(predOps(ARMCC::AL));
9509     Register NewVReg5 = MRI->createVirtualRegister(TRC);
9510     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
9511             .addFrameIndex(FI)
9512             .addImm(36); // &jbuf[1] :: pc
9513     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
9514         .addReg(NewVReg4, RegState::Kill)
9515         .addReg(NewVReg5, RegState::Kill)
9516         .addImm(0)
9517         .addMemOperand(FIMMOSt)
9518         .add(predOps(ARMCC::AL));
9519   } else {
9520     // Incoming value: jbuf
9521     //   ldr  r1, LCPI1_1
9522     //   add  r1, pc, r1
9523     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
9524     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9525     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
9526         .addConstantPoolIndex(CPI)
9527         .addImm(0)
9528         .addMemOperand(CPMMO)
9529         .add(predOps(ARMCC::AL));
9530     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9531     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
9532         .addReg(NewVReg1, RegState::Kill)
9533         .addImm(PCLabelId)
9534         .add(predOps(ARMCC::AL));
9535     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
9536         .addReg(NewVReg2, RegState::Kill)
9537         .addFrameIndex(FI)
9538         .addImm(36) // &jbuf[1] :: pc
9539         .addMemOperand(FIMMOSt)
9540         .add(predOps(ARMCC::AL));
9541   }
9542 }
9543
9544 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
9545                                               MachineBasicBlock *MBB) const {
9546   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9547   DebugLoc dl = MI.getDebugLoc();
9548   MachineFunction *MF = MBB->getParent();
9549   MachineRegisterInfo *MRI = &MF->getRegInfo();
9550   MachineFrameInfo &MFI = MF->getFrameInfo();
9551   int FI = MFI.getFunctionContextIndex();
9552
9553   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
9554                                                         : &ARM::GPRnopcRegClass;
9555
9556   // Get a mapping of the call site numbers to all of the landing pads they're
9557   // associated with.
9558   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
9559   unsigned MaxCSNum = 0;
9560   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
9561        ++BB) {
9562     if (!BB->isEHPad()) continue;
9563
9564     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
9565     // pad.
9566     for (MachineBasicBlock::iterator
9567            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
9568       if (!II->isEHLabel()) continue;
9569
9570       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
9571       if (!MF->hasCallSiteLandingPad(Sym)) continue;
9572
9573       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
9574       for (SmallVectorImpl<unsigned>::iterator
9575              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
9576            CSI != CSE; ++CSI) {
9577         CallSiteNumToLPad[*CSI].push_back(&*BB);
9578         MaxCSNum = std::max(MaxCSNum, *CSI);
9579       }
9580       break;
9581     }
9582   }
9583
9584   // Get an ordered list of the machine basic blocks for the jump table.
9585   std::vector<MachineBasicBlock*> LPadList;
9586   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
9587   LPadList.reserve(CallSiteNumToLPad.size());
9588   for (unsigned I = 1; I <= MaxCSNum; ++I) {
9589     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
9590     for (SmallVectorImpl<MachineBasicBlock*>::iterator
9591            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
9592       LPadList.push_back(*II);
9593       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
9594     }
9595   }
9596
9597   assert(!LPadList.empty() &&
9598          "No landing pad destinations for the dispatch jump table!");
9599
9600   // Create the jump table and associated information.
9601   MachineJumpTableInfo *JTI =
9602     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
9603   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
9604
9605   // Create the MBBs for the dispatch code.
9606
9607   // Shove the dispatch's address into the return slot in the function context.
9608   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
9609   DispatchBB->setIsEHPad();
9610
9611   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9612   unsigned trap_opcode;
9613   if (Subtarget->isThumb())
9614     trap_opcode = ARM::tTRAP;
9615   else
9616     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
9617
9618   BuildMI(TrapBB, dl, TII->get(trap_opcode));
9619   DispatchBB->addSuccessor(TrapBB);
9620
9621   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
9622   DispatchBB->addSuccessor(DispContBB);
9623
9624   // Insert and MBBs.
9625   MF->insert(MF->end(), DispatchBB);
9626   MF->insert(MF->end(), DispContBB);
9627   MF->insert(MF->end(), TrapBB);
9628
9629   // Insert code into the entry block that creates and registers the function
9630   // context.
9631   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
9632
9633   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
9634       MachinePointerInfo::getFixedStack(*MF, FI),
9635       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
9636
9637   MachineInstrBuilder MIB;
9638   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
9639
9640   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
9641   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
9642
9643   // Add a register mask with no preserved registers.  This results in all
9644   // registers being marked as clobbered. This can't work if the dispatch block
9645   // is in a Thumb1 function and is linked with ARM code which uses the FP
9646   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
9647   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
9648
9649   bool IsPositionIndependent = isPositionIndependent();
9650   unsigned NumLPads = LPadList.size();
9651   if (Subtarget->isThumb2()) {
9652     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9653     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
9654         .addFrameIndex(FI)
9655         .addImm(4)
9656         .addMemOperand(FIMMOLd)
9657         .add(predOps(ARMCC::AL));
9658
9659     if (NumLPads < 256) {
9660       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
9661           .addReg(NewVReg1)
9662           .addImm(LPadList.size())
9663           .add(predOps(ARMCC::AL));
9664     } else {
9665       Register VReg1 = MRI->createVirtualRegister(TRC);
9666       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
9667           .addImm(NumLPads & 0xFFFF)
9668           .add(predOps(ARMCC::AL));
9669
9670       unsigned VReg2 = VReg1;
9671       if ((NumLPads & 0xFFFF0000) != 0) {
9672         VReg2 = MRI->createVirtualRegister(TRC);
9673         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
9674             .addReg(VReg1)
9675             .addImm(NumLPads >> 16)
9676             .add(predOps(ARMCC::AL));
9677       }
9678
9679       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
9680           .addReg(NewVReg1)
9681           .addReg(VReg2)
9682           .add(predOps(ARMCC::AL));
9683     }
9684
9685     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
9686       .addMBB(TrapBB)
9687       .addImm(ARMCC::HI)
9688       .addReg(ARM::CPSR);
9689
9690     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9691     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
9692         .addJumpTableIndex(MJTI)
9693         .add(predOps(ARMCC::AL));
9694
9695     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9696     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
9697         .addReg(NewVReg3, RegState::Kill)
9698         .addReg(NewVReg1)
9699         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9700         .add(predOps(ARMCC::AL))
9701         .add(condCodeOp());
9702
9703     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
9704       .addReg(NewVReg4, RegState::Kill)
9705       .addReg(NewVReg1)
9706       .addJumpTableIndex(MJTI);
9707   } else if (Subtarget->isThumb()) {
9708     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9709     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
9710         .addFrameIndex(FI)
9711         .addImm(1)
9712         .addMemOperand(FIMMOLd)
9713         .add(predOps(ARMCC::AL));
9714
9715     if (NumLPads < 256) {
9716       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
9717           .addReg(NewVReg1)
9718           .addImm(NumLPads)
9719           .add(predOps(ARMCC::AL));
9720     } else {
9721       MachineConstantPool *ConstantPool = MF->getConstantPool();
9722       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9723       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9724
9725       // MachineConstantPool wants an explicit alignment.
9726       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9727       if (Align == 0)
9728         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9729       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9730
9731       Register VReg1 = MRI->createVirtualRegister(TRC);
9732       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
9733           .addReg(VReg1, RegState::Define)
9734           .addConstantPoolIndex(Idx)
9735           .add(predOps(ARMCC::AL));
9736       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
9737           .addReg(NewVReg1)
9738           .addReg(VReg1)
9739           .add(predOps(ARMCC::AL));
9740     }
9741
9742     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
9743       .addMBB(TrapBB)
9744       .addImm(ARMCC::HI)
9745       .addReg(ARM::CPSR);
9746
9747     Register NewVReg2 = MRI->createVirtualRegister(TRC);
9748     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
9749         .addReg(ARM::CPSR, RegState::Define)
9750         .addReg(NewVReg1)
9751         .addImm(2)
9752         .add(predOps(ARMCC::AL));
9753
9754     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9755     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
9756         .addJumpTableIndex(MJTI)
9757         .add(predOps(ARMCC::AL));
9758
9759     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9760     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
9761         .addReg(ARM::CPSR, RegState::Define)
9762         .addReg(NewVReg2, RegState::Kill)
9763         .addReg(NewVReg3)
9764         .add(predOps(ARMCC::AL));
9765
9766     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9767         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9768
9769     Register NewVReg5 = MRI->createVirtualRegister(TRC);
9770     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
9771         .addReg(NewVReg4, RegState::Kill)
9772         .addImm(0)
9773         .addMemOperand(JTMMOLd)
9774         .add(predOps(ARMCC::AL));
9775
9776     unsigned NewVReg6 = NewVReg5;
9777     if (IsPositionIndependent) {
9778       NewVReg6 = MRI->createVirtualRegister(TRC);
9779       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
9780           .addReg(ARM::CPSR, RegState::Define)
9781           .addReg(NewVReg5, RegState::Kill)
9782           .addReg(NewVReg3)
9783           .add(predOps(ARMCC::AL));
9784     }
9785
9786     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
9787       .addReg(NewVReg6, RegState::Kill)
9788       .addJumpTableIndex(MJTI);
9789   } else {
9790     Register NewVReg1 = MRI->createVirtualRegister(TRC);
9791     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
9792         .addFrameIndex(FI)
9793         .addImm(4)
9794         .addMemOperand(FIMMOLd)
9795         .add(predOps(ARMCC::AL));
9796
9797     if (NumLPads < 256) {
9798       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
9799           .addReg(NewVReg1)
9800           .addImm(NumLPads)
9801           .add(predOps(ARMCC::AL));
9802     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
9803       Register VReg1 = MRI->createVirtualRegister(TRC);
9804       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
9805           .addImm(NumLPads & 0xFFFF)
9806           .add(predOps(ARMCC::AL));
9807
9808       unsigned VReg2 = VReg1;
9809       if ((NumLPads & 0xFFFF0000) != 0) {
9810         VReg2 = MRI->createVirtualRegister(TRC);
9811         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
9812             .addReg(VReg1)
9813             .addImm(NumLPads >> 16)
9814             .add(predOps(ARMCC::AL));
9815       }
9816
9817       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9818           .addReg(NewVReg1)
9819           .addReg(VReg2)
9820           .add(predOps(ARMCC::AL));
9821     } else {
9822       MachineConstantPool *ConstantPool = MF->getConstantPool();
9823       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9824       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
9825
9826       // MachineConstantPool wants an explicit alignment.
9827       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9828       if (Align == 0)
9829         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9830       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9831
9832       Register VReg1 = MRI->createVirtualRegister(TRC);
9833       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
9834           .addReg(VReg1, RegState::Define)
9835           .addConstantPoolIndex(Idx)
9836           .addImm(0)
9837           .add(predOps(ARMCC::AL));
9838       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
9839           .addReg(NewVReg1)
9840           .addReg(VReg1, RegState::Kill)
9841           .add(predOps(ARMCC::AL));
9842     }
9843
9844     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
9845       .addMBB(TrapBB)
9846       .addImm(ARMCC::HI)
9847       .addReg(ARM::CPSR);
9848
9849     Register NewVReg3 = MRI->createVirtualRegister(TRC);
9850     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
9851         .addReg(NewVReg1)
9852         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
9853         .add(predOps(ARMCC::AL))
9854         .add(condCodeOp());
9855     Register NewVReg4 = MRI->createVirtualRegister(TRC);
9856     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
9857         .addJumpTableIndex(MJTI)
9858         .add(predOps(ARMCC::AL));
9859
9860     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
9861         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
9862     Register NewVReg5 = MRI->createVirtualRegister(TRC);
9863     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
9864         .addReg(NewVReg3, RegState::Kill)
9865         .addReg(NewVReg4)
9866         .addImm(0)
9867         .addMemOperand(JTMMOLd)
9868         .add(predOps(ARMCC::AL));
9869
9870     if (IsPositionIndependent) {
9871       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
9872         .addReg(NewVReg5, RegState::Kill)
9873         .addReg(NewVReg4)
9874         .addJumpTableIndex(MJTI);
9875     } else {
9876       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
9877         .addReg(NewVReg5, RegState::Kill)
9878         .addJumpTableIndex(MJTI);
9879     }
9880   }
9881
9882   // Add the jump table entries as successors to the MBB.
9883   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
9884   for (std::vector<MachineBasicBlock*>::iterator
9885          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
9886     MachineBasicBlock *CurMBB = *I;
9887     if (SeenMBBs.insert(CurMBB).second)
9888       DispContBB->addSuccessor(CurMBB);
9889   }
9890
9891   // N.B. the order the invoke BBs are processed in doesn't matter here.
9892   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
9893   SmallVector<MachineBasicBlock*, 64> MBBLPads;
9894   for (MachineBasicBlock *BB : InvokeBBs) {
9895
9896     // Remove the landing pad successor from the invoke block and replace it
9897     // with the new dispatch block.
9898     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
9899                                                   BB->succ_end());
9900     while (!Successors.empty()) {
9901       MachineBasicBlock *SMBB = Successors.pop_back_val();
9902       if (SMBB->isEHPad()) {
9903         BB->removeSuccessor(SMBB);
9904         MBBLPads.push_back(SMBB);
9905       }
9906     }
9907
9908     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
9909     BB->normalizeSuccProbs();
9910
9911     // Find the invoke call and mark all of the callee-saved registers as
9912     // 'implicit defined' so that they're spilled. This prevents code from
9913     // moving instructions to before the EH block, where they will never be
9914     // executed.
9915     for (MachineBasicBlock::reverse_iterator
9916            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
9917       if (!II->isCall()) continue;
9918
9919       DenseMap<unsigned, bool> DefRegs;
9920       for (MachineInstr::mop_iterator
9921              OI = II->operands_begin(), OE = II->operands_end();
9922            OI != OE; ++OI) {
9923         if (!OI->isReg()) continue;
9924         DefRegs[OI->getReg()] = true;
9925       }
9926
9927       MachineInstrBuilder MIB(*MF, &*II);
9928
9929       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
9930         unsigned Reg = SavedRegs[i];
9931         if (Subtarget->isThumb2() &&
9932             !ARM::tGPRRegClass.contains(Reg) &&
9933             !ARM::hGPRRegClass.contains(Reg))
9934           continue;
9935         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
9936           continue;
9937         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
9938           continue;
9939         if (!DefRegs[Reg])
9940           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
9941       }
9942
9943       break;
9944     }
9945   }
9946
9947   // Mark all former landing pads as non-landing pads. The dispatch is the only
9948   // landing pad now.
9949   for (SmallVectorImpl<MachineBasicBlock*>::iterator
9950          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
9951     (*I)->setIsEHPad(false);
9952
9953   // The instruction is gone now.
9954   MI.eraseFromParent();
9955 }
9956
9957 static
9958 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
9959   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
9960        E = MBB->succ_end(); I != E; ++I)
9961     if (*I != Succ)
9962       return *I;
9963   llvm_unreachable("Expecting a BB with two successors!");
9964 }
9965
9966 /// Return the load opcode for a given load size. If load size >= 8,
9967 /// neon opcode will be returned.
9968 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
9969   if (LdSize >= 8)
9970     return LdSize == 16 ? ARM::VLD1q32wb_fixed
9971                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
9972   if (IsThumb1)
9973     return LdSize == 4 ? ARM::tLDRi
9974                        : LdSize == 2 ? ARM::tLDRHi
9975                                      : LdSize == 1 ? ARM::tLDRBi : 0;
9976   if (IsThumb2)
9977     return LdSize == 4 ? ARM::t2LDR_POST
9978                        : LdSize == 2 ? ARM::t2LDRH_POST
9979                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
9980   return LdSize == 4 ? ARM::LDR_POST_IMM
9981                      : LdSize == 2 ? ARM::LDRH_POST
9982                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
9983 }
9984
9985 /// Return the store opcode for a given store size. If store size >= 8,
9986 /// neon opcode will be returned.
9987 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
9988   if (StSize >= 8)
9989     return StSize == 16 ? ARM::VST1q32wb_fixed
9990                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
9991   if (IsThumb1)
9992     return StSize == 4 ? ARM::tSTRi
9993                        : StSize == 2 ? ARM::tSTRHi
9994                                      : StSize == 1 ? ARM::tSTRBi : 0;
9995   if (IsThumb2)
9996     return StSize == 4 ? ARM::t2STR_POST
9997                        : StSize == 2 ? ARM::t2STRH_POST
9998                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
9999   return StSize == 4 ? ARM::STR_POST_IMM
10000                      : StSize == 2 ? ARM::STRH_POST
10001                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
10002 }
10003
10004 /// Emit a post-increment load operation with given size. The instructions
10005 /// will be added to BB at Pos.
10006 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10007                        const TargetInstrInfo *TII, const DebugLoc &dl,
10008                        unsigned LdSize, unsigned Data, unsigned AddrIn,
10009                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10010   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
10011   assert(LdOpc != 0 && "Should have a load opcode");
10012   if (LdSize >= 8) {
10013     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10014         .addReg(AddrOut, RegState::Define)
10015         .addReg(AddrIn)
10016         .addImm(0)
10017         .add(predOps(ARMCC::AL));
10018   } else if (IsThumb1) {
10019     // load + update AddrIn
10020     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10021         .addReg(AddrIn)
10022         .addImm(0)
10023         .add(predOps(ARMCC::AL));
10024     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10025         .add(t1CondCodeOp())
10026         .addReg(AddrIn)
10027         .addImm(LdSize)
10028         .add(predOps(ARMCC::AL));
10029   } else if (IsThumb2) {
10030     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10031         .addReg(AddrOut, RegState::Define)
10032         .addReg(AddrIn)
10033         .addImm(LdSize)
10034         .add(predOps(ARMCC::AL));
10035   } else { // arm
10036     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
10037         .addReg(AddrOut, RegState::Define)
10038         .addReg(AddrIn)
10039         .addReg(0)
10040         .addImm(LdSize)
10041         .add(predOps(ARMCC::AL));
10042   }
10043 }
10044
10045 /// Emit a post-increment store operation with given size. The instructions
10046 /// will be added to BB at Pos.
10047 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
10048                        const TargetInstrInfo *TII, const DebugLoc &dl,
10049                        unsigned StSize, unsigned Data, unsigned AddrIn,
10050                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
10051   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
10052   assert(StOpc != 0 && "Should have a store opcode");
10053   if (StSize >= 8) {
10054     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10055         .addReg(AddrIn)
10056         .addImm(0)
10057         .addReg(Data)
10058         .add(predOps(ARMCC::AL));
10059   } else if (IsThumb1) {
10060     // store + update AddrIn
10061     BuildMI(*BB, Pos, dl, TII->get(StOpc))
10062         .addReg(Data)
10063         .addReg(AddrIn)
10064         .addImm(0)
10065         .add(predOps(ARMCC::AL));
10066     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
10067         .add(t1CondCodeOp())
10068         .addReg(AddrIn)
10069         .addImm(StSize)
10070         .add(predOps(ARMCC::AL));
10071   } else if (IsThumb2) {
10072     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10073         .addReg(Data)
10074         .addReg(AddrIn)
10075         .addImm(StSize)
10076         .add(predOps(ARMCC::AL));
10077   } else { // arm
10078     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
10079         .addReg(Data)
10080         .addReg(AddrIn)
10081         .addReg(0)
10082         .addImm(StSize)
10083         .add(predOps(ARMCC::AL));
10084   }
10085 }
10086
10087 MachineBasicBlock *
10088 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
10089                                    MachineBasicBlock *BB) const {
10090   // This pseudo instruction has 3 operands: dst, src, size
10091   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
10092   // Otherwise, we will generate unrolled scalar copies.
10093   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10094   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10095   MachineFunction::iterator It = ++BB->getIterator();
10096
10097   Register dest = MI.getOperand(0).getReg();
10098   Register src = MI.getOperand(1).getReg();
10099   unsigned SizeVal = MI.getOperand(2).getImm();
10100   unsigned Align = MI.getOperand(3).getImm();
10101   DebugLoc dl = MI.getDebugLoc();
10102
10103   MachineFunction *MF = BB->getParent();
10104   MachineRegisterInfo &MRI = MF->getRegInfo();
10105   unsigned UnitSize = 0;
10106   const TargetRegisterClass *TRC = nullptr;
10107   const TargetRegisterClass *VecTRC = nullptr;
10108
10109   bool IsThumb1 = Subtarget->isThumb1Only();
10110   bool IsThumb2 = Subtarget->isThumb2();
10111   bool IsThumb = Subtarget->isThumb();
10112
10113   if (Align & 1) {
10114     UnitSize = 1;
10115   } else if (Align & 2) {
10116     UnitSize = 2;
10117   } else {
10118     // Check whether we can use NEON instructions.
10119     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
10120         Subtarget->hasNEON()) {
10121       if ((Align % 16 == 0) && SizeVal >= 16)
10122         UnitSize = 16;
10123       else if ((Align % 8 == 0) && SizeVal >= 8)
10124         UnitSize = 8;
10125     }
10126     // Can't use NEON instructions.
10127     if (UnitSize == 0)
10128       UnitSize = 4;
10129   }
10130
10131   // Select the correct opcode and register class for unit size load/store
10132   bool IsNeon = UnitSize >= 8;
10133   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
10134   if (IsNeon)
10135     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
10136                             : UnitSize == 8 ? &ARM::DPRRegClass
10137                                             : nullptr;
10138
10139   unsigned BytesLeft = SizeVal % UnitSize;
10140   unsigned LoopSize = SizeVal - BytesLeft;
10141
10142   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
10143     // Use LDR and STR to copy.
10144     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
10145     // [destOut] = STR_POST(scratch, destIn, UnitSize)
10146     unsigned srcIn = src;
10147     unsigned destIn = dest;
10148     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
10149       Register srcOut = MRI.createVirtualRegister(TRC);
10150       Register destOut = MRI.createVirtualRegister(TRC);
10151       Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10152       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
10153                  IsThumb1, IsThumb2);
10154       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
10155                  IsThumb1, IsThumb2);
10156       srcIn = srcOut;
10157       destIn = destOut;
10158     }
10159
10160     // Handle the leftover bytes with LDRB and STRB.
10161     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
10162     // [destOut] = STRB_POST(scratch, destIn, 1)
10163     for (unsigned i = 0; i < BytesLeft; i++) {
10164       Register srcOut = MRI.createVirtualRegister(TRC);
10165       Register destOut = MRI.createVirtualRegister(TRC);
10166       Register scratch = MRI.createVirtualRegister(TRC);
10167       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
10168                  IsThumb1, IsThumb2);
10169       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
10170                  IsThumb1, IsThumb2);
10171       srcIn = srcOut;
10172       destIn = destOut;
10173     }
10174     MI.eraseFromParent(); // The instruction is gone now.
10175     return BB;
10176   }
10177
10178   // Expand the pseudo op to a loop.
10179   // thisMBB:
10180   //   ...
10181   //   movw varEnd, # --> with thumb2
10182   //   movt varEnd, #
10183   //   ldrcp varEnd, idx --> without thumb2
10184   //   fallthrough --> loopMBB
10185   // loopMBB:
10186   //   PHI varPhi, varEnd, varLoop
10187   //   PHI srcPhi, src, srcLoop
10188   //   PHI destPhi, dst, destLoop
10189   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10190   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
10191   //   subs varLoop, varPhi, #UnitSize
10192   //   bne loopMBB
10193   //   fallthrough --> exitMBB
10194   // exitMBB:
10195   //   epilogue to handle left-over bytes
10196   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10197   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10198   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10199   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
10200   MF->insert(It, loopMBB);
10201   MF->insert(It, exitMBB);
10202
10203   // Transfer the remainder of BB and its successor edges to exitMBB.
10204   exitMBB->splice(exitMBB->begin(), BB,
10205                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10206   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10207
10208   // Load an immediate to varEnd.
10209   Register varEnd = MRI.createVirtualRegister(TRC);
10210   if (Subtarget->useMovt()) {
10211     unsigned Vtmp = varEnd;
10212     if ((LoopSize & 0xFFFF0000) != 0)
10213       Vtmp = MRI.createVirtualRegister(TRC);
10214     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
10215         .addImm(LoopSize & 0xFFFF)
10216         .add(predOps(ARMCC::AL));
10217
10218     if ((LoopSize & 0xFFFF0000) != 0)
10219       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
10220           .addReg(Vtmp)
10221           .addImm(LoopSize >> 16)
10222           .add(predOps(ARMCC::AL));
10223   } else {
10224     MachineConstantPool *ConstantPool = MF->getConstantPool();
10225     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
10226     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
10227
10228     // MachineConstantPool wants an explicit alignment.
10229     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
10230     if (Align == 0)
10231       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
10232     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
10233     MachineMemOperand *CPMMO =
10234         MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
10235                                  MachineMemOperand::MOLoad, 4, 4);
10236
10237     if (IsThumb)
10238       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
10239           .addReg(varEnd, RegState::Define)
10240           .addConstantPoolIndex(Idx)
10241           .add(predOps(ARMCC::AL))
10242           .addMemOperand(CPMMO);
10243     else
10244       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
10245           .addReg(varEnd, RegState::Define)
10246           .addConstantPoolIndex(Idx)
10247           .addImm(0)
10248           .add(predOps(ARMCC::AL))
10249           .addMemOperand(CPMMO);
10250   }
10251   BB->addSuccessor(loopMBB);
10252
10253   // Generate the loop body:
10254   //   varPhi = PHI(varLoop, varEnd)
10255   //   srcPhi = PHI(srcLoop, src)
10256   //   destPhi = PHI(destLoop, dst)
10257   MachineBasicBlock *entryBB = BB;
10258   BB = loopMBB;
10259   Register varLoop = MRI.createVirtualRegister(TRC);
10260   Register varPhi = MRI.createVirtualRegister(TRC);
10261   Register srcLoop = MRI.createVirtualRegister(TRC);
10262   Register srcPhi = MRI.createVirtualRegister(TRC);
10263   Register destLoop = MRI.createVirtualRegister(TRC);
10264   Register destPhi = MRI.createVirtualRegister(TRC);
10265
10266   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
10267     .addReg(varLoop).addMBB(loopMBB)
10268     .addReg(varEnd).addMBB(entryBB);
10269   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
10270     .addReg(srcLoop).addMBB(loopMBB)
10271     .addReg(src).addMBB(entryBB);
10272   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
10273     .addReg(destLoop).addMBB(loopMBB)
10274     .addReg(dest).addMBB(entryBB);
10275
10276   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
10277   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
10278   Register scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
10279   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
10280              IsThumb1, IsThumb2);
10281   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
10282              IsThumb1, IsThumb2);
10283
10284   // Decrement loop variable by UnitSize.
10285   if (IsThumb1) {
10286     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
10287         .add(t1CondCodeOp())
10288         .addReg(varPhi)
10289         .addImm(UnitSize)
10290         .add(predOps(ARMCC::AL));
10291   } else {
10292     MachineInstrBuilder MIB =
10293         BuildMI(*BB, BB->end(), dl,
10294                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
10295     MIB.addReg(varPhi)
10296         .addImm(UnitSize)
10297         .add(predOps(ARMCC::AL))
10298         .add(condCodeOp());
10299     MIB->getOperand(5).setReg(ARM::CPSR);
10300     MIB->getOperand(5).setIsDef(true);
10301   }
10302   BuildMI(*BB, BB->end(), dl,
10303           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
10304       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
10305
10306   // loopMBB can loop back to loopMBB or fall through to exitMBB.
10307   BB->addSuccessor(loopMBB);
10308   BB->addSuccessor(exitMBB);
10309
10310   // Add epilogue to handle BytesLeft.
10311   BB = exitMBB;
10312   auto StartOfExit = exitMBB->begin();
10313
10314   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
10315   //   [destOut] = STRB_POST(scratch, destLoop, 1)
10316   unsigned srcIn = srcLoop;
10317   unsigned destIn = destLoop;
10318   for (unsigned i = 0; i < BytesLeft; i++) {
10319     Register srcOut = MRI.createVirtualRegister(TRC);
10320     Register destOut = MRI.createVirtualRegister(TRC);
10321     Register scratch = MRI.createVirtualRegister(TRC);
10322     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
10323                IsThumb1, IsThumb2);
10324     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
10325                IsThumb1, IsThumb2);
10326     srcIn = srcOut;
10327     destIn = destOut;
10328   }
10329
10330   MI.eraseFromParent(); // The instruction is gone now.
10331   return BB;
10332 }
10333
10334 MachineBasicBlock *
10335 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
10336                                        MachineBasicBlock *MBB) const {
10337   const TargetMachine &TM = getTargetMachine();
10338   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
10339   DebugLoc DL = MI.getDebugLoc();
10340
10341   assert(Subtarget->isTargetWindows() &&
10342          "__chkstk is only supported on Windows");
10343   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
10344
10345   // __chkstk takes the number of words to allocate on the stack in R4, and
10346   // returns the stack adjustment in number of bytes in R4.  This will not
10347   // clober any other registers (other than the obvious lr).
10348   //
10349   // Although, technically, IP should be considered a register which may be
10350   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
10351   // thumb-2 environment, so there is no interworking required.  As a result, we
10352   // do not expect a veneer to be emitted by the linker, clobbering IP.
10353   //
10354   // Each module receives its own copy of __chkstk, so no import thunk is
10355   // required, again, ensuring that IP is not clobbered.
10356   //
10357   // Finally, although some linkers may theoretically provide a trampoline for
10358   // out of range calls (which is quite common due to a 32M range limitation of
10359   // branches for Thumb), we can generate the long-call version via
10360   // -mcmodel=large, alleviating the need for the trampoline which may clobber
10361   // IP.
10362
10363   switch (TM.getCodeModel()) {
10364   case CodeModel::Tiny:
10365     llvm_unreachable("Tiny code model not available on ARM.");
10366   case CodeModel::Small:
10367   case CodeModel::Medium:
10368   case CodeModel::Kernel:
10369     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
10370         .add(predOps(ARMCC::AL))
10371         .addExternalSymbol("__chkstk")
10372         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10373         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10374         .addReg(ARM::R12,
10375                 RegState::Implicit | RegState::Define | RegState::Dead)
10376         .addReg(ARM::CPSR,
10377                 RegState::Implicit | RegState::Define | RegState::Dead);
10378     break;
10379   case CodeModel::Large: {
10380     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
10381     Register Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
10382
10383     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
10384       .addExternalSymbol("__chkstk");
10385     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
10386         .add(predOps(ARMCC::AL))
10387         .addReg(Reg, RegState::Kill)
10388         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
10389         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
10390         .addReg(ARM::R12,
10391                 RegState::Implicit | RegState::Define | RegState::Dead)
10392         .addReg(ARM::CPSR,
10393                 RegState::Implicit | RegState::Define | RegState::Dead);
10394     break;
10395   }
10396   }
10397
10398   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
10399       .addReg(ARM::SP, RegState::Kill)
10400       .addReg(ARM::R4, RegState::Kill)
10401       .setMIFlags(MachineInstr::FrameSetup)
10402       .add(predOps(ARMCC::AL))
10403       .add(condCodeOp());
10404
10405   MI.eraseFromParent();
10406   return MBB;
10407 }
10408
10409 MachineBasicBlock *
10410 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
10411                                        MachineBasicBlock *MBB) const {
10412   DebugLoc DL = MI.getDebugLoc();
10413   MachineFunction *MF = MBB->getParent();
10414   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10415
10416   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
10417   MF->insert(++MBB->getIterator(), ContBB);
10418   ContBB->splice(ContBB->begin(), MBB,
10419                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10420   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
10421   MBB->addSuccessor(ContBB);
10422
10423   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
10424   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
10425   MF->push_back(TrapBB);
10426   MBB->addSuccessor(TrapBB);
10427
10428   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
10429       .addReg(MI.getOperand(0).getReg())
10430       .addImm(0)
10431       .add(predOps(ARMCC::AL));
10432   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
10433       .addMBB(TrapBB)
10434       .addImm(ARMCC::EQ)
10435       .addReg(ARM::CPSR);
10436
10437   MI.eraseFromParent();
10438   return ContBB;
10439 }
10440
10441 // The CPSR operand of SelectItr might be missing a kill marker
10442 // because there were multiple uses of CPSR, and ISel didn't know
10443 // which to mark. Figure out whether SelectItr should have had a
10444 // kill marker, and set it if it should. Returns the correct kill
10445 // marker value.
10446 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
10447                                    MachineBasicBlock* BB,
10448                                    const TargetRegisterInfo* TRI) {
10449   // Scan forward through BB for a use/def of CPSR.
10450   MachineBasicBlock::iterator miI(std::next(SelectItr));
10451   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
10452     const MachineInstr& mi = *miI;
10453     if (mi.readsRegister(ARM::CPSR))
10454       return false;
10455     if (mi.definesRegister(ARM::CPSR))
10456       break; // Should have kill-flag - update below.
10457   }
10458
10459   // If we hit the end of the block, check whether CPSR is live into a
10460   // successor.
10461   if (miI == BB->end()) {
10462     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
10463                                           sEnd = BB->succ_end();
10464          sItr != sEnd; ++sItr) {
10465       MachineBasicBlock* succ = *sItr;
10466       if (succ->isLiveIn(ARM::CPSR))
10467         return false;
10468     }
10469   }
10470
10471   // We found a def, or hit the end of the basic block and CPSR wasn't live
10472   // out. SelectMI should have a kill flag on CPSR.
10473   SelectItr->addRegisterKilled(ARM::CPSR, TRI);
10474   return true;
10475 }
10476
10477 MachineBasicBlock *
10478 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10479                                                MachineBasicBlock *BB) const {
10480   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10481   DebugLoc dl = MI.getDebugLoc();
10482   bool isThumb2 = Subtarget->isThumb2();
10483   switch (MI.getOpcode()) {
10484   default: {
10485     MI.print(errs());
10486     llvm_unreachable("Unexpected instr type to insert");
10487   }
10488
10489   // Thumb1 post-indexed loads are really just single-register LDMs.
10490   case ARM::tLDR_postidx: {
10491     MachineOperand Def(MI.getOperand(1));
10492     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
10493         .add(Def)  // Rn_wb
10494         .add(MI.getOperand(2))  // Rn
10495         .add(MI.getOperand(3))  // PredImm
10496         .add(MI.getOperand(4))  // PredReg
10497         .add(MI.getOperand(0))  // Rt
10498         .cloneMemRefs(MI);
10499     MI.eraseFromParent();
10500     return BB;
10501   }
10502
10503   // The Thumb2 pre-indexed stores have the same MI operands, they just
10504   // define them differently in the .td files from the isel patterns, so
10505   // they need pseudos.
10506   case ARM::t2STR_preidx:
10507     MI.setDesc(TII->get(ARM::t2STR_PRE));
10508     return BB;
10509   case ARM::t2STRB_preidx:
10510     MI.setDesc(TII->get(ARM::t2STRB_PRE));
10511     return BB;
10512   case ARM::t2STRH_preidx:
10513     MI.setDesc(TII->get(ARM::t2STRH_PRE));
10514     return BB;
10515
10516   case ARM::STRi_preidx:
10517   case ARM::STRBi_preidx: {
10518     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
10519                                                          : ARM::STRB_PRE_IMM;
10520     // Decode the offset.
10521     unsigned Offset = MI.getOperand(4).getImm();
10522     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
10523     Offset = ARM_AM::getAM2Offset(Offset);
10524     if (isSub)
10525       Offset = -Offset;
10526
10527     MachineMemOperand *MMO = *MI.memoperands_begin();
10528     BuildMI(*BB, MI, dl, TII->get(NewOpc))
10529         .add(MI.getOperand(0)) // Rn_wb
10530         .add(MI.getOperand(1)) // Rt
10531         .add(MI.getOperand(2)) // Rn
10532         .addImm(Offset)        // offset (skip GPR==zero_reg)
10533         .add(MI.getOperand(5)) // pred
10534         .add(MI.getOperand(6))
10535         .addMemOperand(MMO);
10536     MI.eraseFromParent();
10537     return BB;
10538   }
10539   case ARM::STRr_preidx:
10540   case ARM::STRBr_preidx:
10541   case ARM::STRH_preidx: {
10542     unsigned NewOpc;
10543     switch (MI.getOpcode()) {
10544     default: llvm_unreachable("unexpected opcode!");
10545     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
10546     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
10547     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
10548     }
10549     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
10550     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
10551       MIB.add(MI.getOperand(i));
10552     MI.eraseFromParent();
10553     return BB;
10554   }
10555
10556   case ARM::tMOVCCr_pseudo: {
10557     // To "insert" a SELECT_CC instruction, we actually have to insert the
10558     // diamond control-flow pattern.  The incoming instruction knows the
10559     // destination vreg to set, the condition code register to branch on, the
10560     // true/false values to select between, and a branch opcode to use.
10561     const BasicBlock *LLVM_BB = BB->getBasicBlock();
10562     MachineFunction::iterator It = ++BB->getIterator();
10563
10564     //  thisMBB:
10565     //  ...
10566     //   TrueVal = ...
10567     //   cmpTY ccX, r1, r2
10568     //   bCC copy1MBB
10569     //   fallthrough --> copy0MBB
10570     MachineBasicBlock *thisMBB  = BB;
10571     MachineFunction *F = BB->getParent();
10572     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10573     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
10574     F->insert(It, copy0MBB);
10575     F->insert(It, sinkMBB);
10576
10577     // Check whether CPSR is live past the tMOVCCr_pseudo.
10578     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
10579     if (!MI.killsRegister(ARM::CPSR) &&
10580         !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
10581       copy0MBB->addLiveIn(ARM::CPSR);
10582       sinkMBB->addLiveIn(ARM::CPSR);
10583     }
10584
10585     // Transfer the remainder of BB and its successor edges to sinkMBB.
10586     sinkMBB->splice(sinkMBB->begin(), BB,
10587                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10588     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10589
10590     BB->addSuccessor(copy0MBB);
10591     BB->addSuccessor(sinkMBB);
10592
10593     BuildMI(BB, dl, TII->get(ARM::tBcc))
10594         .addMBB(sinkMBB)
10595         .addImm(MI.getOperand(3).getImm())
10596         .addReg(MI.getOperand(4).getReg());
10597
10598     //  copy0MBB:
10599     //   %FalseValue = ...
10600     //   # fallthrough to sinkMBB
10601     BB = copy0MBB;
10602
10603     // Update machine-CFG edges
10604     BB->addSuccessor(sinkMBB);
10605
10606     //  sinkMBB:
10607     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10608     //  ...
10609     BB = sinkMBB;
10610     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
10611         .addReg(MI.getOperand(1).getReg())
10612         .addMBB(copy0MBB)
10613         .addReg(MI.getOperand(2).getReg())
10614         .addMBB(thisMBB);
10615
10616     MI.eraseFromParent(); // The pseudo instruction is gone now.
10617     return BB;
10618   }
10619
10620   case ARM::BCCi64:
10621   case ARM::BCCZi64: {
10622     // If there is an unconditional branch to the other successor, remove it.
10623     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
10624
10625     // Compare both parts that make up the double comparison separately for
10626     // equality.
10627     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
10628
10629     Register LHS1 = MI.getOperand(1).getReg();
10630     Register LHS2 = MI.getOperand(2).getReg();
10631     if (RHSisZero) {
10632       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10633           .addReg(LHS1)
10634           .addImm(0)
10635           .add(predOps(ARMCC::AL));
10636       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10637         .addReg(LHS2).addImm(0)
10638         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10639     } else {
10640       Register RHS1 = MI.getOperand(3).getReg();
10641       Register RHS2 = MI.getOperand(4).getReg();
10642       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10643           .addReg(LHS1)
10644           .addReg(RHS1)
10645           .add(predOps(ARMCC::AL));
10646       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
10647         .addReg(LHS2).addReg(RHS2)
10648         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
10649     }
10650
10651     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
10652     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
10653     if (MI.getOperand(0).getImm() == ARMCC::NE)
10654       std::swap(destMBB, exitMBB);
10655
10656     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
10657       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
10658     if (isThumb2)
10659       BuildMI(BB, dl, TII->get(ARM::t2B))
10660           .addMBB(exitMBB)
10661           .add(predOps(ARMCC::AL));
10662     else
10663       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
10664
10665     MI.eraseFromParent(); // The pseudo instruction is gone now.
10666     return BB;
10667   }
10668
10669   case ARM::Int_eh_sjlj_setjmp:
10670   case ARM::Int_eh_sjlj_setjmp_nofp:
10671   case ARM::tInt_eh_sjlj_setjmp:
10672   case ARM::t2Int_eh_sjlj_setjmp:
10673   case ARM::t2Int_eh_sjlj_setjmp_nofp:
10674     return BB;
10675
10676   case ARM::Int_eh_sjlj_setup_dispatch:
10677     EmitSjLjDispatchBlock(MI, BB);
10678     return BB;
10679
10680   case ARM::ABS:
10681   case ARM::t2ABS: {
10682     // To insert an ABS instruction, we have to insert the
10683     // diamond control-flow pattern.  The incoming instruction knows the
10684     // source vreg to test against 0, the destination vreg to set,
10685     // the condition code register to branch on, the
10686     // true/false values to select between, and a branch opcode to use.
10687     // It transforms
10688     //     V1 = ABS V0
10689     // into
10690     //     V2 = MOVS V0
10691     //     BCC                      (branch to SinkBB if V0 >= 0)
10692     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
10693     //     SinkBB: V1 = PHI(V2, V3)
10694     const BasicBlock *LLVM_BB = BB->getBasicBlock();
10695     MachineFunction::iterator BBI = ++BB->getIterator();
10696     MachineFunction *Fn = BB->getParent();
10697     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
10698     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
10699     Fn->insert(BBI, RSBBB);
10700     Fn->insert(BBI, SinkBB);
10701
10702     Register ABSSrcReg = MI.getOperand(1).getReg();
10703     Register ABSDstReg = MI.getOperand(0).getReg();
10704     bool ABSSrcKIll = MI.getOperand(1).isKill();
10705     bool isThumb2 = Subtarget->isThumb2();
10706     MachineRegisterInfo &MRI = Fn->getRegInfo();
10707     // In Thumb mode S must not be specified if source register is the SP or
10708     // PC and if destination register is the SP, so restrict register class
10709     Register NewRsbDstReg = MRI.createVirtualRegister(
10710         isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
10711
10712     // Transfer the remainder of BB and its successor edges to sinkMBB.
10713     SinkBB->splice(SinkBB->begin(), BB,
10714                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
10715     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
10716
10717     BB->addSuccessor(RSBBB);
10718     BB->addSuccessor(SinkBB);
10719
10720     // fall through to SinkMBB
10721     RSBBB->addSuccessor(SinkBB);
10722
10723     // insert a cmp at the end of BB
10724     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
10725         .addReg(ABSSrcReg)
10726         .addImm(0)
10727         .add(predOps(ARMCC::AL));
10728
10729     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
10730     BuildMI(BB, dl,
10731       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
10732       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
10733
10734     // insert rsbri in RSBBB
10735     // Note: BCC and rsbri will be converted into predicated rsbmi
10736     // by if-conversion pass
10737     BuildMI(*RSBBB, RSBBB->begin(), dl,
10738             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
10739         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
10740         .addImm(0)
10741         .add(predOps(ARMCC::AL))
10742         .add(condCodeOp());
10743
10744     // insert PHI in SinkBB,
10745     // reuse ABSDstReg to not change uses of ABS instruction
10746     BuildMI(*SinkBB, SinkBB->begin(), dl,
10747       TII->get(ARM::PHI), ABSDstReg)
10748       .addReg(NewRsbDstReg).addMBB(RSBBB)
10749       .addReg(ABSSrcReg).addMBB(BB);
10750
10751     // remove ABS instruction
10752     MI.eraseFromParent();
10753
10754     // return last added BB
10755     return SinkBB;
10756   }
10757   case ARM::COPY_STRUCT_BYVAL_I32:
10758     ++NumLoopByVals;
10759     return EmitStructByval(MI, BB);
10760   case ARM::WIN__CHKSTK:
10761     return EmitLowered__chkstk(MI, BB);
10762   case ARM::WIN__DBZCHK:
10763     return EmitLowered__dbzchk(MI, BB);
10764   }
10765 }
10766
10767 /// Attaches vregs to MEMCPY that it will use as scratch registers
10768 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
10769 /// instead of as a custom inserter because we need the use list from the SDNode.
10770 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
10771                                     MachineInstr &MI, const SDNode *Node) {
10772   bool isThumb1 = Subtarget->isThumb1Only();
10773
10774   DebugLoc DL = MI.getDebugLoc();
10775   MachineFunction *MF = MI.getParent()->getParent();
10776   MachineRegisterInfo &MRI = MF->getRegInfo();
10777   MachineInstrBuilder MIB(*MF, MI);
10778
10779   // If the new dst/src is unused mark it as dead.
10780   if (!Node->hasAnyUseOfValue(0)) {
10781     MI.getOperand(0).setIsDead(true);
10782   }
10783   if (!Node->hasAnyUseOfValue(1)) {
10784     MI.getOperand(1).setIsDead(true);
10785   }
10786
10787   // The MEMCPY both defines and kills the scratch registers.
10788   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
10789     Register TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
10790                                                          : &ARM::GPRRegClass);
10791     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
10792   }
10793 }
10794
10795 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10796                                                       SDNode *Node) const {
10797   if (MI.getOpcode() == ARM::MEMCPY) {
10798     attachMEMCPYScratchRegs(Subtarget, MI, Node);
10799     return;
10800   }
10801
10802   const MCInstrDesc *MCID = &MI.getDesc();
10803   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
10804   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
10805   // operand is still set to noreg. If needed, set the optional operand's
10806   // register to CPSR, and remove the redundant implicit def.
10807   //
10808   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
10809
10810   // Rename pseudo opcodes.
10811   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
10812   unsigned ccOutIdx;
10813   if (NewOpc) {
10814     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
10815     MCID = &TII->get(NewOpc);
10816
10817     assert(MCID->getNumOperands() ==
10818            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
10819         && "converted opcode should be the same except for cc_out"
10820            " (and, on Thumb1, pred)");
10821
10822     MI.setDesc(*MCID);
10823
10824     // Add the optional cc_out operand
10825     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
10826
10827     // On Thumb1, move all input operands to the end, then add the predicate
10828     if (Subtarget->isThumb1Only()) {
10829       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
10830         MI.addOperand(MI.getOperand(1));
10831         MI.RemoveOperand(1);
10832       }
10833
10834       // Restore the ties
10835       for (unsigned i = MI.getNumOperands(); i--;) {
10836         const MachineOperand& op = MI.getOperand(i);
10837         if (op.isReg() && op.isUse()) {
10838           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
10839           if (DefIdx != -1)
10840             MI.tieOperands(DefIdx, i);
10841         }
10842       }
10843
10844       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
10845       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
10846       ccOutIdx = 1;
10847     } else
10848       ccOutIdx = MCID->getNumOperands() - 1;
10849   } else
10850     ccOutIdx = MCID->getNumOperands() - 1;
10851
10852   // Any ARM instruction that sets the 's' bit should specify an optional
10853   // "cc_out" operand in the last operand position.
10854   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
10855     assert(!NewOpc && "Optional cc_out operand required");
10856     return;
10857   }
10858   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
10859   // since we already have an optional CPSR def.
10860   bool definesCPSR = false;
10861   bool deadCPSR = false;
10862   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
10863        ++i) {
10864     const MachineOperand &MO = MI.getOperand(i);
10865     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
10866       definesCPSR = true;
10867       if (MO.isDead())
10868         deadCPSR = true;
10869       MI.RemoveOperand(i);
10870       break;
10871     }
10872   }
10873   if (!definesCPSR) {
10874     assert(!NewOpc && "Optional cc_out operand required");
10875     return;
10876   }
10877   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
10878   if (deadCPSR) {
10879     assert(!MI.getOperand(ccOutIdx).getReg() &&
10880            "expect uninitialized optional cc_out operand");
10881     // Thumb1 instructions must have the S bit even if the CPSR is dead.
10882     if (!Subtarget->isThumb1Only())
10883       return;
10884   }
10885
10886   // If this instruction was defined with an optional CPSR def and its dag node
10887   // had a live implicit CPSR def, then activate the optional CPSR def.
10888   MachineOperand &MO = MI.getOperand(ccOutIdx);
10889   MO.setReg(ARM::CPSR);
10890   MO.setIsDef(true);
10891 }
10892
10893 //===----------------------------------------------------------------------===//
10894 //                           ARM Optimization Hooks
10895 //===----------------------------------------------------------------------===//
10896
10897 // Helper function that checks if N is a null or all ones constant.
10898 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
10899   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
10900 }
10901
10902 // Return true if N is conditionally 0 or all ones.
10903 // Detects these expressions where cc is an i1 value:
10904 //
10905 //   (select cc 0, y)   [AllOnes=0]
10906 //   (select cc y, 0)   [AllOnes=0]
10907 //   (zext cc)          [AllOnes=0]
10908 //   (sext cc)          [AllOnes=0/1]
10909 //   (select cc -1, y)  [AllOnes=1]
10910 //   (select cc y, -1)  [AllOnes=1]
10911 //
10912 // Invert is set when N is the null/all ones constant when CC is false.
10913 // OtherOp is set to the alternative value of N.
10914 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
10915                                        SDValue &CC, bool &Invert,
10916                                        SDValue &OtherOp,
10917                                        SelectionDAG &DAG) {
10918   switch (N->getOpcode()) {
10919   default: return false;
10920   case ISD::SELECT: {
10921     CC = N->getOperand(0);
10922     SDValue N1 = N->getOperand(1);
10923     SDValue N2 = N->getOperand(2);
10924     if (isZeroOrAllOnes(N1, AllOnes)) {
10925       Invert = false;
10926       OtherOp = N2;
10927       return true;
10928     }
10929     if (isZeroOrAllOnes(N2, AllOnes)) {
10930       Invert = true;
10931       OtherOp = N1;
10932       return true;
10933     }
10934     return false;
10935   }
10936   case ISD::ZERO_EXTEND:
10937     // (zext cc) can never be the all ones value.
10938     if (AllOnes)
10939       return false;
10940     LLVM_FALLTHROUGH;
10941   case ISD::SIGN_EXTEND: {
10942     SDLoc dl(N);
10943     EVT VT = N->getValueType(0);
10944     CC = N->getOperand(0);
10945     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
10946       return false;
10947     Invert = !AllOnes;
10948     if (AllOnes)
10949       // When looking for an AllOnes constant, N is an sext, and the 'other'
10950       // value is 0.
10951       OtherOp = DAG.getConstant(0, dl, VT);
10952     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10953       // When looking for a 0 constant, N can be zext or sext.
10954       OtherOp = DAG.getConstant(1, dl, VT);
10955     else
10956       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
10957                                 VT);
10958     return true;
10959   }
10960   }
10961 }
10962
10963 // Combine a constant select operand into its use:
10964 //
10965 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
10966 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
10967 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
10968 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
10969 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
10970 //
10971 // The transform is rejected if the select doesn't have a constant operand that
10972 // is null, or all ones when AllOnes is set.
10973 //
10974 // Also recognize sext/zext from i1:
10975 //
10976 //   (add (zext cc), x) -> (select cc (add x, 1), x)
10977 //   (add (sext cc), x) -> (select cc (add x, -1), x)
10978 //
10979 // These transformations eventually create predicated instructions.
10980 //
10981 // @param N       The node to transform.
10982 // @param Slct    The N operand that is a select.
10983 // @param OtherOp The other N operand (x above).
10984 // @param DCI     Context.
10985 // @param AllOnes Require the select constant to be all ones instead of null.
10986 // @returns The new node, or SDValue() on failure.
10987 static
10988 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
10989                             TargetLowering::DAGCombinerInfo &DCI,
10990                             bool AllOnes = false) {
10991   SelectionDAG &DAG = DCI.DAG;
10992   EVT VT = N->getValueType(0);
10993   SDValue NonConstantVal;
10994   SDValue CCOp;
10995   bool SwapSelectOps;
10996   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
10997                                   NonConstantVal, DAG))
10998     return SDValue();
10999
11000   // Slct is now know to be the desired identity constant when CC is true.
11001   SDValue TrueVal = OtherOp;
11002   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11003                                  OtherOp, NonConstantVal);
11004   // Unless SwapSelectOps says CC should be false.
11005   if (SwapSelectOps)
11006     std::swap(TrueVal, FalseVal);
11007
11008   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
11009                      CCOp, TrueVal, FalseVal);
11010 }
11011
11012 // Attempt combineSelectAndUse on each operand of a commutative operator N.
11013 static
11014 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
11015                                        TargetLowering::DAGCombinerInfo &DCI) {
11016   SDValue N0 = N->getOperand(0);
11017   SDValue N1 = N->getOperand(1);
11018   if (N0.getNode()->hasOneUse())
11019     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
11020       return Result;
11021   if (N1.getNode()->hasOneUse())
11022     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
11023       return Result;
11024   return SDValue();
11025 }
11026
11027 static bool IsVUZPShuffleNode(SDNode *N) {
11028   // VUZP shuffle node.
11029   if (N->getOpcode() == ARMISD::VUZP)
11030     return true;
11031
11032   // "VUZP" on i32 is an alias for VTRN.
11033   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
11034     return true;
11035
11036   return false;
11037 }
11038
11039 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
11040                                  TargetLowering::DAGCombinerInfo &DCI,
11041                                  const ARMSubtarget *Subtarget) {
11042   // Look for ADD(VUZP.0, VUZP.1).
11043   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
11044       N0 == N1)
11045    return SDValue();
11046
11047   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
11048   if (!N->getValueType(0).is64BitVector())
11049     return SDValue();
11050
11051   // Generate vpadd.
11052   SelectionDAG &DAG = DCI.DAG;
11053   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11054   SDLoc dl(N);
11055   SDNode *Unzip = N0.getNode();
11056   EVT VT = N->getValueType(0);
11057
11058   SmallVector<SDValue, 8> Ops;
11059   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
11060                                 TLI.getPointerTy(DAG.getDataLayout())));
11061   Ops.push_back(Unzip->getOperand(0));
11062   Ops.push_back(Unzip->getOperand(1));
11063
11064   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11065 }
11066
11067 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11068                                       TargetLowering::DAGCombinerInfo &DCI,
11069                                       const ARMSubtarget *Subtarget) {
11070   // Check for two extended operands.
11071   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
11072         N1.getOpcode() == ISD::SIGN_EXTEND) &&
11073       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
11074         N1.getOpcode() == ISD::ZERO_EXTEND))
11075     return SDValue();
11076
11077   SDValue N00 = N0.getOperand(0);
11078   SDValue N10 = N1.getOperand(0);
11079
11080   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
11081   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
11082       N00 == N10)
11083     return SDValue();
11084
11085   // We only recognize Q register paddl here; this can't be reached until
11086   // after type legalization.
11087   if (!N00.getValueType().is64BitVector() ||
11088       !N0.getValueType().is128BitVector())
11089     return SDValue();
11090
11091   // Generate vpaddl.
11092   SelectionDAG &DAG = DCI.DAG;
11093   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11094   SDLoc dl(N);
11095   EVT VT = N->getValueType(0);
11096
11097   SmallVector<SDValue, 8> Ops;
11098   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
11099   unsigned Opcode;
11100   if (N0.getOpcode() == ISD::SIGN_EXTEND)
11101     Opcode = Intrinsic::arm_neon_vpaddls;
11102   else
11103     Opcode = Intrinsic::arm_neon_vpaddlu;
11104   Ops.push_back(DAG.getConstant(Opcode, dl,
11105                                 TLI.getPointerTy(DAG.getDataLayout())));
11106   EVT ElemTy = N00.getValueType().getVectorElementType();
11107   unsigned NumElts = VT.getVectorNumElements();
11108   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
11109   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
11110                                N00.getOperand(0), N00.getOperand(1));
11111   Ops.push_back(Concat);
11112
11113   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
11114 }
11115
11116 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
11117 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
11118 // much easier to match.
11119 static SDValue
11120 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
11121                                TargetLowering::DAGCombinerInfo &DCI,
11122                                const ARMSubtarget *Subtarget) {
11123   // Only perform optimization if after legalize, and if NEON is available. We
11124   // also expected both operands to be BUILD_VECTORs.
11125   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
11126       || N0.getOpcode() != ISD::BUILD_VECTOR
11127       || N1.getOpcode() != ISD::BUILD_VECTOR)
11128     return SDValue();
11129
11130   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
11131   EVT VT = N->getValueType(0);
11132   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
11133     return SDValue();
11134
11135   // Check that the vector operands are of the right form.
11136   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
11137   // operands, where N is the size of the formed vector.
11138   // Each EXTRACT_VECTOR should have the same input vector and odd or even
11139   // index such that we have a pair wise add pattern.
11140
11141   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
11142   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11143     return SDValue();
11144   SDValue Vec = N0->getOperand(0)->getOperand(0);
11145   SDNode *V = Vec.getNode();
11146   unsigned nextIndex = 0;
11147
11148   // For each operands to the ADD which are BUILD_VECTORs,
11149   // check to see if each of their operands are an EXTRACT_VECTOR with
11150   // the same vector and appropriate index.
11151   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
11152     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
11153         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11154
11155       SDValue ExtVec0 = N0->getOperand(i);
11156       SDValue ExtVec1 = N1->getOperand(i);
11157
11158       // First operand is the vector, verify its the same.
11159       if (V != ExtVec0->getOperand(0).getNode() ||
11160           V != ExtVec1->getOperand(0).getNode())
11161         return SDValue();
11162
11163       // Second is the constant, verify its correct.
11164       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
11165       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
11166
11167       // For the constant, we want to see all the even or all the odd.
11168       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
11169           || C1->getZExtValue() != nextIndex+1)
11170         return SDValue();
11171
11172       // Increment index.
11173       nextIndex+=2;
11174     } else
11175       return SDValue();
11176   }
11177
11178   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
11179   // we're using the entire input vector, otherwise there's a size/legality
11180   // mismatch somewhere.
11181   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
11182       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
11183     return SDValue();
11184
11185   // Create VPADDL node.
11186   SelectionDAG &DAG = DCI.DAG;
11187   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11188
11189   SDLoc dl(N);
11190
11191   // Build operand list.
11192   SmallVector<SDValue, 8> Ops;
11193   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
11194                                 TLI.getPointerTy(DAG.getDataLayout())));
11195
11196   // Input is the vector.
11197   Ops.push_back(Vec);
11198
11199   // Get widened type and narrowed type.
11200   MVT widenType;
11201   unsigned numElem = VT.getVectorNumElements();
11202
11203   EVT inputLaneType = Vec.getValueType().getVectorElementType();
11204   switch (inputLaneType.getSimpleVT().SimpleTy) {
11205     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
11206     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
11207     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
11208     default:
11209       llvm_unreachable("Invalid vector element type for padd optimization.");
11210   }
11211
11212   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
11213   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
11214   return DAG.getNode(ExtOp, dl, VT, tmp);
11215 }
11216
11217 static SDValue findMUL_LOHI(SDValue V) {
11218   if (V->getOpcode() == ISD::UMUL_LOHI ||
11219       V->getOpcode() == ISD::SMUL_LOHI)
11220     return V;
11221   return SDValue();
11222 }
11223
11224 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
11225                                         TargetLowering::DAGCombinerInfo &DCI,
11226                                         const ARMSubtarget *Subtarget) {
11227   if (!Subtarget->hasBaseDSP())
11228     return SDValue();
11229
11230   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
11231   // accumulates the product into a 64-bit value. The 16-bit values will
11232   // be sign extended somehow or SRA'd into 32-bit values
11233   // (addc (adde (mul 16bit, 16bit), lo), hi)
11234   SDValue Mul = AddcNode->getOperand(0);
11235   SDValue Lo = AddcNode->getOperand(1);
11236   if (Mul.getOpcode() != ISD::MUL) {
11237     Lo = AddcNode->getOperand(0);
11238     Mul = AddcNode->getOperand(1);
11239     if (Mul.getOpcode() != ISD::MUL)
11240       return SDValue();
11241   }
11242
11243   SDValue SRA = AddeNode->getOperand(0);
11244   SDValue Hi = AddeNode->getOperand(1);
11245   if (SRA.getOpcode() != ISD::SRA) {
11246     SRA = AddeNode->getOperand(1);
11247     Hi = AddeNode->getOperand(0);
11248     if (SRA.getOpcode() != ISD::SRA)
11249       return SDValue();
11250   }
11251   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
11252     if (Const->getZExtValue() != 31)
11253       return SDValue();
11254   } else
11255     return SDValue();
11256
11257   if (SRA.getOperand(0) != Mul)
11258     return SDValue();
11259
11260   SelectionDAG &DAG = DCI.DAG;
11261   SDLoc dl(AddcNode);
11262   unsigned Opcode = 0;
11263   SDValue Op0;
11264   SDValue Op1;
11265
11266   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
11267     Opcode = ARMISD::SMLALBB;
11268     Op0 = Mul.getOperand(0);
11269     Op1 = Mul.getOperand(1);
11270   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
11271     Opcode = ARMISD::SMLALBT;
11272     Op0 = Mul.getOperand(0);
11273     Op1 = Mul.getOperand(1).getOperand(0);
11274   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
11275     Opcode = ARMISD::SMLALTB;
11276     Op0 = Mul.getOperand(0).getOperand(0);
11277     Op1 = Mul.getOperand(1);
11278   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
11279     Opcode = ARMISD::SMLALTT;
11280     Op0 = Mul->getOperand(0).getOperand(0);
11281     Op1 = Mul->getOperand(1).getOperand(0);
11282   }
11283
11284   if (!Op0 || !Op1)
11285     return SDValue();
11286
11287   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
11288                               Op0, Op1, Lo, Hi);
11289   // Replace the ADDs' nodes uses by the MLA node's values.
11290   SDValue HiMLALResult(SMLAL.getNode(), 1);
11291   SDValue LoMLALResult(SMLAL.getNode(), 0);
11292
11293   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
11294   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
11295
11296   // Return original node to notify the driver to stop replacing.
11297   SDValue resNode(AddcNode, 0);
11298   return resNode;
11299 }
11300
11301 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
11302                                      TargetLowering::DAGCombinerInfo &DCI,
11303                                      const ARMSubtarget *Subtarget) {
11304   // Look for multiply add opportunities.
11305   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
11306   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
11307   // a glue link from the first add to the second add.
11308   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
11309   // a S/UMLAL instruction.
11310   //                  UMUL_LOHI
11311   //                 / :lo    \ :hi
11312   //                V          \          [no multiline comment]
11313   //    loAdd ->  ADDC         |
11314   //                 \ :carry /
11315   //                  V      V
11316   //                    ADDE   <- hiAdd
11317   //
11318   // In the special case where only the higher part of a signed result is used
11319   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
11320   // a constant with the exact value of 0x80000000, we recognize we are dealing
11321   // with a "rounded multiply and add" (or subtract) and transform it into
11322   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
11323
11324   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
11325           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
11326          "Expect an ADDE or SUBE");
11327
11328   assert(AddeSubeNode->getNumOperands() == 3 &&
11329          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
11330          "ADDE node has the wrong inputs");
11331
11332   // Check that we are chained to the right ADDC or SUBC node.
11333   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
11334   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11335        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
11336       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
11337        AddcSubcNode->getOpcode() != ARMISD::SUBC))
11338     return SDValue();
11339
11340   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
11341   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
11342
11343   // Check if the two operands are from the same mul_lohi node.
11344   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
11345     return SDValue();
11346
11347   assert(AddcSubcNode->getNumValues() == 2 &&
11348          AddcSubcNode->getValueType(0) == MVT::i32 &&
11349          "Expect ADDC with two result values. First: i32");
11350
11351   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
11352   // maybe a SMLAL which multiplies two 16-bit values.
11353   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
11354       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
11355       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
11356       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
11357       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
11358     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
11359
11360   // Check for the triangle shape.
11361   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
11362   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
11363
11364   // Make sure that the ADDE/SUBE operands are not coming from the same node.
11365   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
11366     return SDValue();
11367
11368   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
11369   bool IsLeftOperandMUL = false;
11370   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
11371   if (MULOp == SDValue())
11372     MULOp = findMUL_LOHI(AddeSubeOp1);
11373   else
11374     IsLeftOperandMUL = true;
11375   if (MULOp == SDValue())
11376     return SDValue();
11377
11378   // Figure out the right opcode.
11379   unsigned Opc = MULOp->getOpcode();
11380   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
11381
11382   // Figure out the high and low input values to the MLAL node.
11383   SDValue *HiAddSub = nullptr;
11384   SDValue *LoMul = nullptr;
11385   SDValue *LowAddSub = nullptr;
11386
11387   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
11388   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
11389     return SDValue();
11390
11391   if (IsLeftOperandMUL)
11392     HiAddSub = &AddeSubeOp1;
11393   else
11394     HiAddSub = &AddeSubeOp0;
11395
11396   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
11397   // whose low result is fed to the ADDC/SUBC we are checking.
11398
11399   if (AddcSubcOp0 == MULOp.getValue(0)) {
11400     LoMul = &AddcSubcOp0;
11401     LowAddSub = &AddcSubcOp1;
11402   }
11403   if (AddcSubcOp1 == MULOp.getValue(0)) {
11404     LoMul = &AddcSubcOp1;
11405     LowAddSub = &AddcSubcOp0;
11406   }
11407
11408   if (!LoMul)
11409     return SDValue();
11410
11411   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
11412   // the replacement below will create a cycle.
11413   if (AddcSubcNode == HiAddSub->getNode() ||
11414       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
11415     return SDValue();
11416
11417   // Create the merged node.
11418   SelectionDAG &DAG = DCI.DAG;
11419
11420   // Start building operand list.
11421   SmallVector<SDValue, 8> Ops;
11422   Ops.push_back(LoMul->getOperand(0));
11423   Ops.push_back(LoMul->getOperand(1));
11424
11425   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
11426   // the case, we must be doing signed multiplication and only use the higher
11427   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
11428   // addition or subtraction with the value of 0x800000.
11429   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
11430       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
11431       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
11432       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
11433           0x80000000) {
11434     Ops.push_back(*HiAddSub);
11435     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
11436       FinalOpc = ARMISD::SMMLSR;
11437     } else {
11438       FinalOpc = ARMISD::SMMLAR;
11439     }
11440     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
11441     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
11442
11443     return SDValue(AddeSubeNode, 0);
11444   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
11445     // SMMLS is generated during instruction selection and the rest of this
11446     // function can not handle the case where AddcSubcNode is a SUBC.
11447     return SDValue();
11448
11449   // Finish building the operand list for {U/S}MLAL
11450   Ops.push_back(*LowAddSub);
11451   Ops.push_back(*HiAddSub);
11452
11453   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
11454                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
11455
11456   // Replace the ADDs' nodes uses by the MLA node's values.
11457   SDValue HiMLALResult(MLALNode.getNode(), 1);
11458   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
11459
11460   SDValue LoMLALResult(MLALNode.getNode(), 0);
11461   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
11462
11463   // Return original node to notify the driver to stop replacing.
11464   return SDValue(AddeSubeNode, 0);
11465 }
11466
11467 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
11468                                       TargetLowering::DAGCombinerInfo &DCI,
11469                                       const ARMSubtarget *Subtarget) {
11470   // UMAAL is similar to UMLAL except that it adds two unsigned values.
11471   // While trying to combine for the other MLAL nodes, first search for the
11472   // chance to use UMAAL. Check if Addc uses a node which has already
11473   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
11474   // as the addend, and it's handled in PerformUMLALCombine.
11475
11476   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11477     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11478
11479   // Check that we have a glued ADDC node.
11480   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
11481   if (AddcNode->getOpcode() != ARMISD::ADDC)
11482     return SDValue();
11483
11484   // Find the converted UMAAL or quit if it doesn't exist.
11485   SDNode *UmlalNode = nullptr;
11486   SDValue AddHi;
11487   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
11488     UmlalNode = AddcNode->getOperand(0).getNode();
11489     AddHi = AddcNode->getOperand(1);
11490   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
11491     UmlalNode = AddcNode->getOperand(1).getNode();
11492     AddHi = AddcNode->getOperand(0);
11493   } else {
11494     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
11495   }
11496
11497   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
11498   // the ADDC as well as Zero.
11499   if (!isNullConstant(UmlalNode->getOperand(3)))
11500     return SDValue();
11501
11502   if ((isNullConstant(AddeNode->getOperand(0)) &&
11503        AddeNode->getOperand(1).getNode() == UmlalNode) ||
11504       (AddeNode->getOperand(0).getNode() == UmlalNode &&
11505        isNullConstant(AddeNode->getOperand(1)))) {
11506     SelectionDAG &DAG = DCI.DAG;
11507     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
11508                       UmlalNode->getOperand(2), AddHi };
11509     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
11510                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
11511
11512     // Replace the ADDs' nodes uses by the UMAAL node's values.
11513     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
11514     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
11515
11516     // Return original node to notify the driver to stop replacing.
11517     return SDValue(AddeNode, 0);
11518   }
11519   return SDValue();
11520 }
11521
11522 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
11523                                    const ARMSubtarget *Subtarget) {
11524   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
11525     return SDValue();
11526
11527   // Check that we have a pair of ADDC and ADDE as operands.
11528   // Both addends of the ADDE must be zero.
11529   SDNode* AddcNode = N->getOperand(2).getNode();
11530   SDNode* AddeNode = N->getOperand(3).getNode();
11531   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
11532       (AddeNode->getOpcode() == ARMISD::ADDE) &&
11533       isNullConstant(AddeNode->getOperand(0)) &&
11534       isNullConstant(AddeNode->getOperand(1)) &&
11535       (AddeNode->getOperand(2).getNode() == AddcNode))
11536     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
11537                        DAG.getVTList(MVT::i32, MVT::i32),
11538                        {N->getOperand(0), N->getOperand(1),
11539                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
11540   else
11541     return SDValue();
11542 }
11543
11544 static SDValue PerformAddcSubcCombine(SDNode *N,
11545                                       TargetLowering::DAGCombinerInfo &DCI,
11546                                       const ARMSubtarget *Subtarget) {
11547   SelectionDAG &DAG(DCI.DAG);
11548
11549   if (N->getOpcode() == ARMISD::SUBC) {
11550     // (SUBC (ADDE 0, 0, C), 1) -> C
11551     SDValue LHS = N->getOperand(0);
11552     SDValue RHS = N->getOperand(1);
11553     if (LHS->getOpcode() == ARMISD::ADDE &&
11554         isNullConstant(LHS->getOperand(0)) &&
11555         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
11556       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
11557     }
11558   }
11559
11560   if (Subtarget->isThumb1Only()) {
11561     SDValue RHS = N->getOperand(1);
11562     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11563       int32_t imm = C->getSExtValue();
11564       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
11565         SDLoc DL(N);
11566         RHS = DAG.getConstant(-imm, DL, MVT::i32);
11567         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
11568                                                            : ARMISD::ADDC;
11569         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
11570       }
11571     }
11572   }
11573
11574   return SDValue();
11575 }
11576
11577 static SDValue PerformAddeSubeCombine(SDNode *N,
11578                                       TargetLowering::DAGCombinerInfo &DCI,
11579                                       const ARMSubtarget *Subtarget) {
11580   if (Subtarget->isThumb1Only()) {
11581     SelectionDAG &DAG = DCI.DAG;
11582     SDValue RHS = N->getOperand(1);
11583     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
11584       int64_t imm = C->getSExtValue();
11585       if (imm < 0) {
11586         SDLoc DL(N);
11587
11588         // The with-carry-in form matches bitwise not instead of the negation.
11589         // Effectively, the inverse interpretation of the carry flag already
11590         // accounts for part of the negation.
11591         RHS = DAG.getConstant(~imm, DL, MVT::i32);
11592
11593         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
11594                                                            : ARMISD::ADDE;
11595         return DAG.getNode(Opcode, DL, N->getVTList(),
11596                            N->getOperand(0), RHS, N->getOperand(2));
11597       }
11598     }
11599   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
11600     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
11601   }
11602   return SDValue();
11603 }
11604
11605 static SDValue PerformABSCombine(SDNode *N,
11606                                   TargetLowering::DAGCombinerInfo &DCI,
11607                                   const ARMSubtarget *Subtarget) {
11608   SDValue res;
11609   SelectionDAG &DAG = DCI.DAG;
11610   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11611
11612   if (TLI.isOperationLegal(N->getOpcode(), N->getValueType(0)))
11613     return SDValue();
11614
11615   if (!TLI.expandABS(N, res, DAG))
11616       return SDValue();
11617
11618   return res;
11619 }
11620
11621 /// PerformADDECombine - Target-specific dag combine transform from
11622 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
11623 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
11624 static SDValue PerformADDECombine(SDNode *N,
11625                                   TargetLowering::DAGCombinerInfo &DCI,
11626                                   const ARMSubtarget *Subtarget) {
11627   // Only ARM and Thumb2 support UMLAL/SMLAL.
11628   if (Subtarget->isThumb1Only())
11629     return PerformAddeSubeCombine(N, DCI, Subtarget);
11630
11631   // Only perform the checks after legalize when the pattern is available.
11632   if (DCI.isBeforeLegalize()) return SDValue();
11633
11634   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
11635 }
11636
11637 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
11638 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
11639 /// called with the default operands, and if that fails, with commuted
11640 /// operands.
11641 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
11642                                           TargetLowering::DAGCombinerInfo &DCI,
11643                                           const ARMSubtarget *Subtarget){
11644   // Attempt to create vpadd for this add.
11645   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
11646     return Result;
11647
11648   // Attempt to create vpaddl for this add.
11649   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
11650     return Result;
11651   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
11652                                                       Subtarget))
11653     return Result;
11654
11655   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
11656   if (N0.getNode()->hasOneUse())
11657     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
11658       return Result;
11659   return SDValue();
11660 }
11661
11662 bool
11663 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
11664                                                  CombineLevel Level) const {
11665   if (Level == BeforeLegalizeTypes)
11666     return true;
11667
11668   if (N->getOpcode() != ISD::SHL)
11669     return true;
11670
11671   if (Subtarget->isThumb1Only()) {
11672     // Avoid making expensive immediates by commuting shifts. (This logic
11673     // only applies to Thumb1 because ARM and Thumb2 immediates can be shifted
11674     // for free.)
11675     if (N->getOpcode() != ISD::SHL)
11676       return true;
11677     SDValue N1 = N->getOperand(0);
11678     if (N1->getOpcode() != ISD::ADD && N1->getOpcode() != ISD::AND &&
11679         N1->getOpcode() != ISD::OR && N1->getOpcode() != ISD::XOR)
11680       return true;
11681     if (auto *Const = dyn_cast<ConstantSDNode>(N1->getOperand(1))) {
11682       if (Const->getAPIntValue().ult(256))
11683         return false;
11684       if (N1->getOpcode() == ISD::ADD && Const->getAPIntValue().slt(0) &&
11685           Const->getAPIntValue().sgt(-256))
11686         return false;
11687     }
11688     return true;
11689   }
11690
11691   // Turn off commute-with-shift transform after legalization, so it doesn't
11692   // conflict with PerformSHLSimplify.  (We could try to detect when
11693   // PerformSHLSimplify would trigger more precisely, but it isn't
11694   // really necessary.)
11695   return false;
11696 }
11697
11698 bool ARMTargetLowering::shouldFoldConstantShiftPairToMask(
11699     const SDNode *N, CombineLevel Level) const {
11700   if (!Subtarget->isThumb1Only())
11701     return true;
11702
11703   if (Level == BeforeLegalizeTypes)
11704     return true;
11705
11706   return false;
11707 }
11708
11709 bool ARMTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
11710   if (!Subtarget->hasNEON()) {
11711     if (Subtarget->isThumb1Only())
11712       return VT.getScalarSizeInBits() <= 32;
11713     return true;
11714   }
11715   return VT.isScalarInteger();
11716 }
11717
11718 static SDValue PerformSHLSimplify(SDNode *N,
11719                                 TargetLowering::DAGCombinerInfo &DCI,
11720                                 const ARMSubtarget *ST) {
11721   // Allow the generic combiner to identify potential bswaps.
11722   if (DCI.isBeforeLegalize())
11723     return SDValue();
11724
11725   // DAG combiner will fold:
11726   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
11727   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
11728   // Other code patterns that can be also be modified have the following form:
11729   // b + ((a << 1) | 510)
11730   // b + ((a << 1) & 510)
11731   // b + ((a << 1) ^ 510)
11732   // b + ((a << 1) + 510)
11733
11734   // Many instructions can  perform the shift for free, but it requires both
11735   // the operands to be registers. If c1 << c2 is too large, a mov immediate
11736   // instruction will needed. So, unfold back to the original pattern if:
11737   // - if c1 and c2 are small enough that they don't require mov imms.
11738   // - the user(s) of the node can perform an shl
11739
11740   // No shifted operands for 16-bit instructions.
11741   if (ST->isThumb() && ST->isThumb1Only())
11742     return SDValue();
11743
11744   // Check that all the users could perform the shl themselves.
11745   for (auto U : N->uses()) {
11746     switch(U->getOpcode()) {
11747     default:
11748       return SDValue();
11749     case ISD::SUB:
11750     case ISD::ADD:
11751     case ISD::AND:
11752     case ISD::OR:
11753     case ISD::XOR:
11754     case ISD::SETCC:
11755     case ARMISD::CMP:
11756       // Check that the user isn't already using a constant because there
11757       // aren't any instructions that support an immediate operand and a
11758       // shifted operand.
11759       if (isa<ConstantSDNode>(U->getOperand(0)) ||
11760           isa<ConstantSDNode>(U->getOperand(1)))
11761         return SDValue();
11762
11763       // Check that it's not already using a shift.
11764       if (U->getOperand(0).getOpcode() == ISD::SHL ||
11765           U->getOperand(1).getOpcode() == ISD::SHL)
11766         return SDValue();
11767       break;
11768     }
11769   }
11770
11771   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
11772       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
11773     return SDValue();
11774
11775   if (N->getOperand(0).getOpcode() != ISD::SHL)
11776     return SDValue();
11777
11778   SDValue SHL = N->getOperand(0);
11779
11780   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
11781   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
11782   if (!C1ShlC2 || !C2)
11783     return SDValue();
11784
11785   APInt C2Int = C2->getAPIntValue();
11786   APInt C1Int = C1ShlC2->getAPIntValue();
11787
11788   // Check that performing a lshr will not lose any information.
11789   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
11790                                      C2Int.getBitWidth() - C2->getZExtValue());
11791   if ((C1Int & Mask) != C1Int)
11792     return SDValue();
11793
11794   // Shift the first constant.
11795   C1Int.lshrInPlace(C2Int);
11796
11797   // The immediates are encoded as an 8-bit value that can be rotated.
11798   auto LargeImm = [](const APInt &Imm) {
11799     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
11800     return Imm.getBitWidth() - Zeros > 8;
11801   };
11802
11803   if (LargeImm(C1Int) || LargeImm(C2Int))
11804     return SDValue();
11805
11806   SelectionDAG &DAG = DCI.DAG;
11807   SDLoc dl(N);
11808   SDValue X = SHL.getOperand(0);
11809   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
11810                               DAG.getConstant(C1Int, dl, MVT::i32));
11811   // Shift left to compensate for the lshr of C1Int.
11812   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
11813
11814   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
11815              SHL.dump(); N->dump());
11816   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
11817   return Res;
11818 }
11819
11820
11821 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
11822 ///
11823 static SDValue PerformADDCombine(SDNode *N,
11824                                  TargetLowering::DAGCombinerInfo &DCI,
11825                                  const ARMSubtarget *Subtarget) {
11826   SDValue N0 = N->getOperand(0);
11827   SDValue N1 = N->getOperand(1);
11828
11829   // Only works one way, because it needs an immediate operand.
11830   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11831     return Result;
11832
11833   // First try with the default operand order.
11834   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
11835     return Result;
11836
11837   // If that didn't work, try again with the operands commuted.
11838   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
11839 }
11840
11841 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
11842 ///
11843 static SDValue PerformSUBCombine(SDNode *N,
11844                                  TargetLowering::DAGCombinerInfo &DCI,
11845                                  const ARMSubtarget *Subtarget) {
11846   SDValue N0 = N->getOperand(0);
11847   SDValue N1 = N->getOperand(1);
11848
11849   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
11850   if (N1.getNode()->hasOneUse())
11851     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
11852       return Result;
11853
11854   if (!Subtarget->hasMVEIntegerOps() || !N->getValueType(0).isVector())
11855     return SDValue();
11856
11857   // Fold (sub (ARMvmovImm 0), (ARMvdup x)) -> (ARMvdup (sub 0, x))
11858   // so that we can readily pattern match more mve instructions which can use
11859   // a scalar operand.
11860   SDValue VDup = N->getOperand(1);
11861   if (VDup->getOpcode() != ARMISD::VDUP)
11862     return SDValue();
11863
11864   SDValue VMov = N->getOperand(0);
11865   if (VMov->getOpcode() == ISD::BITCAST)
11866     VMov = VMov->getOperand(0);
11867
11868   if (VMov->getOpcode() != ARMISD::VMOVIMM || !isZeroVector(VMov))
11869     return SDValue();
11870
11871   SDLoc dl(N);
11872   SDValue Negate = DCI.DAG.getNode(ISD::SUB, dl, MVT::i32,
11873                                    DCI.DAG.getConstant(0, dl, MVT::i32),
11874                                    VDup->getOperand(0));
11875   return DCI.DAG.getNode(ARMISD::VDUP, dl, N->getValueType(0), Negate);
11876 }
11877
11878 /// PerformVMULCombine
11879 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
11880 /// special multiplier accumulator forwarding.
11881 ///   vmul d3, d0, d2
11882 ///   vmla d3, d1, d2
11883 /// is faster than
11884 ///   vadd d3, d0, d1
11885 ///   vmul d3, d3, d2
11886 //  However, for (A + B) * (A + B),
11887 //    vadd d2, d0, d1
11888 //    vmul d3, d0, d2
11889 //    vmla d3, d1, d2
11890 //  is slower than
11891 //    vadd d2, d0, d1
11892 //    vmul d3, d2, d2
11893 static SDValue PerformVMULCombine(SDNode *N,
11894                                   TargetLowering::DAGCombinerInfo &DCI,
11895                                   const ARMSubtarget *Subtarget) {
11896   if (!Subtarget->hasVMLxForwarding())
11897     return SDValue();
11898
11899   SelectionDAG &DAG = DCI.DAG;
11900   SDValue N0 = N->getOperand(0);
11901   SDValue N1 = N->getOperand(1);
11902   unsigned Opcode = N0.getOpcode();
11903   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11904       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
11905     Opcode = N1.getOpcode();
11906     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
11907         Opcode != ISD::FADD && Opcode != ISD::FSUB)
11908       return SDValue();
11909     std::swap(N0, N1);
11910   }
11911
11912   if (N0 == N1)
11913     return SDValue();
11914
11915   EVT VT = N->getValueType(0);
11916   SDLoc DL(N);
11917   SDValue N00 = N0->getOperand(0);
11918   SDValue N01 = N0->getOperand(1);
11919   return DAG.getNode(Opcode, DL, VT,
11920                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
11921                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
11922 }
11923
11924 static SDValue PerformMULCombine(SDNode *N,
11925                                  TargetLowering::DAGCombinerInfo &DCI,
11926                                  const ARMSubtarget *Subtarget) {
11927   SelectionDAG &DAG = DCI.DAG;
11928
11929   if (Subtarget->isThumb1Only())
11930     return SDValue();
11931
11932   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11933     return SDValue();
11934
11935   EVT VT = N->getValueType(0);
11936   if (VT.is64BitVector() || VT.is128BitVector())
11937     return PerformVMULCombine(N, DCI, Subtarget);
11938   if (VT != MVT::i32)
11939     return SDValue();
11940
11941   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
11942   if (!C)
11943     return SDValue();
11944
11945   int64_t MulAmt = C->getSExtValue();
11946   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
11947
11948   ShiftAmt = ShiftAmt & (32 - 1);
11949   SDValue V = N->getOperand(0);
11950   SDLoc DL(N);
11951
11952   SDValue Res;
11953   MulAmt >>= ShiftAmt;
11954
11955   if (MulAmt >= 0) {
11956     if (isPowerOf2_32(MulAmt - 1)) {
11957       // (mul x, 2^N + 1) => (add (shl x, N), x)
11958       Res = DAG.getNode(ISD::ADD, DL, VT,
11959                         V,
11960                         DAG.getNode(ISD::SHL, DL, VT,
11961                                     V,
11962                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
11963                                                     MVT::i32)));
11964     } else if (isPowerOf2_32(MulAmt + 1)) {
11965       // (mul x, 2^N - 1) => (sub (shl x, N), x)
11966       Res = DAG.getNode(ISD::SUB, DL, VT,
11967                         DAG.getNode(ISD::SHL, DL, VT,
11968                                     V,
11969                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
11970                                                     MVT::i32)),
11971                         V);
11972     } else
11973       return SDValue();
11974   } else {
11975     uint64_t MulAmtAbs = -MulAmt;
11976     if (isPowerOf2_32(MulAmtAbs + 1)) {
11977       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
11978       Res = DAG.getNode(ISD::SUB, DL, VT,
11979                         V,
11980                         DAG.getNode(ISD::SHL, DL, VT,
11981                                     V,
11982                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
11983                                                     MVT::i32)));
11984     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
11985       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
11986       Res = DAG.getNode(ISD::ADD, DL, VT,
11987                         V,
11988                         DAG.getNode(ISD::SHL, DL, VT,
11989                                     V,
11990                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
11991                                                     MVT::i32)));
11992       Res = DAG.getNode(ISD::SUB, DL, VT,
11993                         DAG.getConstant(0, DL, MVT::i32), Res);
11994     } else
11995       return SDValue();
11996   }
11997
11998   if (ShiftAmt != 0)
11999     Res = DAG.getNode(ISD::SHL, DL, VT,
12000                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
12001
12002   // Do not add new nodes to DAG combiner worklist.
12003   DCI.CombineTo(N, Res, false);
12004   return SDValue();
12005 }
12006
12007 static SDValue CombineANDShift(SDNode *N,
12008                                TargetLowering::DAGCombinerInfo &DCI,
12009                                const ARMSubtarget *Subtarget) {
12010   // Allow DAGCombine to pattern-match before we touch the canonical form.
12011   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
12012     return SDValue();
12013
12014   if (N->getValueType(0) != MVT::i32)
12015     return SDValue();
12016
12017   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
12018   if (!N1C)
12019     return SDValue();
12020
12021   uint32_t C1 = (uint32_t)N1C->getZExtValue();
12022   // Don't transform uxtb/uxth.
12023   if (C1 == 255 || C1 == 65535)
12024     return SDValue();
12025
12026   SDNode *N0 = N->getOperand(0).getNode();
12027   if (!N0->hasOneUse())
12028     return SDValue();
12029
12030   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
12031     return SDValue();
12032
12033   bool LeftShift = N0->getOpcode() == ISD::SHL;
12034
12035   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12036   if (!N01C)
12037     return SDValue();
12038
12039   uint32_t C2 = (uint32_t)N01C->getZExtValue();
12040   if (!C2 || C2 >= 32)
12041     return SDValue();
12042
12043   // Clear irrelevant bits in the mask.
12044   if (LeftShift)
12045     C1 &= (-1U << C2);
12046   else
12047     C1 &= (-1U >> C2);
12048
12049   SelectionDAG &DAG = DCI.DAG;
12050   SDLoc DL(N);
12051
12052   // We have a pattern of the form "(and (shl x, c2) c1)" or
12053   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
12054   // transform to a pair of shifts, to save materializing c1.
12055
12056   // First pattern: right shift, then mask off leading bits.
12057   // FIXME: Use demanded bits?
12058   if (!LeftShift && isMask_32(C1)) {
12059     uint32_t C3 = countLeadingZeros(C1);
12060     if (C2 < C3) {
12061       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12062                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12063       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12064                          DAG.getConstant(C3, DL, MVT::i32));
12065     }
12066   }
12067
12068   // First pattern, reversed: left shift, then mask off trailing bits.
12069   if (LeftShift && isMask_32(~C1)) {
12070     uint32_t C3 = countTrailingZeros(C1);
12071     if (C2 < C3) {
12072       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12073                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
12074       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12075                          DAG.getConstant(C3, DL, MVT::i32));
12076     }
12077   }
12078
12079   // Second pattern: left shift, then mask off leading bits.
12080   // FIXME: Use demanded bits?
12081   if (LeftShift && isShiftedMask_32(C1)) {
12082     uint32_t Trailing = countTrailingZeros(C1);
12083     uint32_t C3 = countLeadingZeros(C1);
12084     if (Trailing == C2 && C2 + C3 < 32) {
12085       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
12086                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12087       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
12088                         DAG.getConstant(C3, DL, MVT::i32));
12089     }
12090   }
12091
12092   // Second pattern, reversed: right shift, then mask off trailing bits.
12093   // FIXME: Handle other patterns of known/demanded bits.
12094   if (!LeftShift && isShiftedMask_32(C1)) {
12095     uint32_t Leading = countLeadingZeros(C1);
12096     uint32_t C3 = countTrailingZeros(C1);
12097     if (Leading == C2 && C2 + C3 < 32) {
12098       SDValue SHL = DAG.getNode(ISD::SRL, DL, MVT::i32, N0->getOperand(0),
12099                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
12100       return DAG.getNode(ISD::SHL, DL, MVT::i32, SHL,
12101                          DAG.getConstant(C3, DL, MVT::i32));
12102     }
12103   }
12104
12105   // FIXME: Transform "(and (shl x, c2) c1)" ->
12106   // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
12107   // c1.
12108   return SDValue();
12109 }
12110
12111 static SDValue PerformANDCombine(SDNode *N,
12112                                  TargetLowering::DAGCombinerInfo &DCI,
12113                                  const ARMSubtarget *Subtarget) {
12114   // Attempt to use immediate-form VBIC
12115   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12116   SDLoc dl(N);
12117   EVT VT = N->getValueType(0);
12118   SelectionDAG &DAG = DCI.DAG;
12119
12120   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12121     return SDValue();
12122
12123   APInt SplatBits, SplatUndef;
12124   unsigned SplatBitSize;
12125   bool HasAnyUndefs;
12126   if (BVN && Subtarget->hasNEON() &&
12127       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12128     if (SplatBitSize <= 64) {
12129       EVT VbicVT;
12130       SDValue Val = isVMOVModifiedImm((~SplatBits).getZExtValue(),
12131                                       SplatUndef.getZExtValue(), SplatBitSize,
12132                                       DAG, dl, VbicVT, VT.is128BitVector(),
12133                                       OtherModImm);
12134       if (Val.getNode()) {
12135         SDValue Input =
12136           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
12137         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
12138         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
12139       }
12140     }
12141   }
12142
12143   if (!Subtarget->isThumb1Only()) {
12144     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
12145     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
12146       return Result;
12147
12148     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12149       return Result;
12150   }
12151
12152   if (Subtarget->isThumb1Only())
12153     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
12154       return Result;
12155
12156   return SDValue();
12157 }
12158
12159 // Try combining OR nodes to SMULWB, SMULWT.
12160 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
12161                                          TargetLowering::DAGCombinerInfo &DCI,
12162                                          const ARMSubtarget *Subtarget) {
12163   if (!Subtarget->hasV6Ops() ||
12164       (Subtarget->isThumb() &&
12165        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
12166     return SDValue();
12167
12168   SDValue SRL = OR->getOperand(0);
12169   SDValue SHL = OR->getOperand(1);
12170
12171   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
12172     SRL = OR->getOperand(1);
12173     SHL = OR->getOperand(0);
12174   }
12175   if (!isSRL16(SRL) || !isSHL16(SHL))
12176     return SDValue();
12177
12178   // The first operands to the shifts need to be the two results from the
12179   // same smul_lohi node.
12180   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
12181        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
12182     return SDValue();
12183
12184   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
12185   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
12186       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
12187     return SDValue();
12188
12189   // Now we have:
12190   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
12191   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
12192   // For SMUWB the 16-bit value will signed extended somehow.
12193   // For SMULWT only the SRA is required.
12194   // Check both sides of SMUL_LOHI
12195   SDValue OpS16 = SMULLOHI->getOperand(0);
12196   SDValue OpS32 = SMULLOHI->getOperand(1);
12197
12198   SelectionDAG &DAG = DCI.DAG;
12199   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
12200     OpS16 = OpS32;
12201     OpS32 = SMULLOHI->getOperand(0);
12202   }
12203
12204   SDLoc dl(OR);
12205   unsigned Opcode = 0;
12206   if (isS16(OpS16, DAG))
12207     Opcode = ARMISD::SMULWB;
12208   else if (isSRA16(OpS16)) {
12209     Opcode = ARMISD::SMULWT;
12210     OpS16 = OpS16->getOperand(0);
12211   }
12212   else
12213     return SDValue();
12214
12215   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
12216   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
12217   return SDValue(OR, 0);
12218 }
12219
12220 static SDValue PerformORCombineToBFI(SDNode *N,
12221                                      TargetLowering::DAGCombinerInfo &DCI,
12222                                      const ARMSubtarget *Subtarget) {
12223   // BFI is only available on V6T2+
12224   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
12225     return SDValue();
12226
12227   EVT VT = N->getValueType(0);
12228   SDValue N0 = N->getOperand(0);
12229   SDValue N1 = N->getOperand(1);
12230   SelectionDAG &DAG = DCI.DAG;
12231   SDLoc DL(N);
12232   // 1) or (and A, mask), val => ARMbfi A, val, mask
12233   //      iff (val & mask) == val
12234   //
12235   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12236   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
12237   //          && mask == ~mask2
12238   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
12239   //          && ~mask == mask2
12240   //  (i.e., copy a bitfield value into another bitfield of the same width)
12241
12242   if (VT != MVT::i32)
12243     return SDValue();
12244
12245   SDValue N00 = N0.getOperand(0);
12246
12247   // The value and the mask need to be constants so we can verify this is
12248   // actually a bitfield set. If the mask is 0xffff, we can do better
12249   // via a movt instruction, so don't use BFI in that case.
12250   SDValue MaskOp = N0.getOperand(1);
12251   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
12252   if (!MaskC)
12253     return SDValue();
12254   unsigned Mask = MaskC->getZExtValue();
12255   if (Mask == 0xffff)
12256     return SDValue();
12257   SDValue Res;
12258   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
12259   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
12260   if (N1C) {
12261     unsigned Val = N1C->getZExtValue();
12262     if ((Val & ~Mask) != Val)
12263       return SDValue();
12264
12265     if (ARM::isBitFieldInvertedMask(Mask)) {
12266       Val >>= countTrailingZeros(~Mask);
12267
12268       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
12269                         DAG.getConstant(Val, DL, MVT::i32),
12270                         DAG.getConstant(Mask, DL, MVT::i32));
12271
12272       DCI.CombineTo(N, Res, false);
12273       // Return value from the original node to inform the combiner than N is
12274       // now dead.
12275       return SDValue(N, 0);
12276     }
12277   } else if (N1.getOpcode() == ISD::AND) {
12278     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
12279     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12280     if (!N11C)
12281       return SDValue();
12282     unsigned Mask2 = N11C->getZExtValue();
12283
12284     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
12285     // as is to match.
12286     if (ARM::isBitFieldInvertedMask(Mask) &&
12287         (Mask == ~Mask2)) {
12288       // The pack halfword instruction works better for masks that fit it,
12289       // so use that when it's available.
12290       if (Subtarget->hasDSP() &&
12291           (Mask == 0xffff || Mask == 0xffff0000))
12292         return SDValue();
12293       // 2a
12294       unsigned amt = countTrailingZeros(Mask2);
12295       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
12296                         DAG.getConstant(amt, DL, MVT::i32));
12297       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
12298                         DAG.getConstant(Mask, DL, MVT::i32));
12299       DCI.CombineTo(N, Res, false);
12300       // Return value from the original node to inform the combiner than N is
12301       // now dead.
12302       return SDValue(N, 0);
12303     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
12304                (~Mask == Mask2)) {
12305       // The pack halfword instruction works better for masks that fit it,
12306       // so use that when it's available.
12307       if (Subtarget->hasDSP() &&
12308           (Mask2 == 0xffff || Mask2 == 0xffff0000))
12309         return SDValue();
12310       // 2b
12311       unsigned lsb = countTrailingZeros(Mask);
12312       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
12313                         DAG.getConstant(lsb, DL, MVT::i32));
12314       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
12315                         DAG.getConstant(Mask2, DL, MVT::i32));
12316       DCI.CombineTo(N, Res, false);
12317       // Return value from the original node to inform the combiner than N is
12318       // now dead.
12319       return SDValue(N, 0);
12320     }
12321   }
12322
12323   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
12324       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
12325       ARM::isBitFieldInvertedMask(~Mask)) {
12326     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
12327     // where lsb(mask) == #shamt and masked bits of B are known zero.
12328     SDValue ShAmt = N00.getOperand(1);
12329     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
12330     unsigned LSB = countTrailingZeros(Mask);
12331     if (ShAmtC != LSB)
12332       return SDValue();
12333
12334     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
12335                       DAG.getConstant(~Mask, DL, MVT::i32));
12336
12337     DCI.CombineTo(N, Res, false);
12338     // Return value from the original node to inform the combiner than N is
12339     // now dead.
12340     return SDValue(N, 0);
12341   }
12342
12343   return SDValue();
12344 }
12345
12346 static bool isValidMVECond(unsigned CC, bool IsFloat) {
12347   switch (CC) {
12348   case ARMCC::EQ:
12349   case ARMCC::NE:
12350   case ARMCC::LE:
12351   case ARMCC::GT:
12352   case ARMCC::GE:
12353   case ARMCC::LT:
12354     return true;
12355   case ARMCC::HS:
12356   case ARMCC::HI:
12357     return !IsFloat;
12358   default:
12359     return false;
12360   };
12361 }
12362
12363 static SDValue PerformORCombine_i1(SDNode *N,
12364                                    TargetLowering::DAGCombinerInfo &DCI,
12365                                    const ARMSubtarget *Subtarget) {
12366   // Try to invert "or A, B" -> "and ~A, ~B", as the "and" is easier to chain
12367   // together with predicates
12368   EVT VT = N->getValueType(0);
12369   SDValue N0 = N->getOperand(0);
12370   SDValue N1 = N->getOperand(1);
12371
12372   ARMCC::CondCodes CondCode0 = ARMCC::AL;
12373   ARMCC::CondCodes CondCode1 = ARMCC::AL;
12374   if (N0->getOpcode() == ARMISD::VCMP)
12375     CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(2))
12376                     ->getZExtValue();
12377   else if (N0->getOpcode() == ARMISD::VCMPZ)
12378     CondCode0 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N0->getOperand(1))
12379                     ->getZExtValue();
12380   if (N1->getOpcode() == ARMISD::VCMP)
12381     CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(2))
12382                     ->getZExtValue();
12383   else if (N1->getOpcode() == ARMISD::VCMPZ)
12384     CondCode1 = (ARMCC::CondCodes)cast<const ConstantSDNode>(N1->getOperand(1))
12385                     ->getZExtValue();
12386
12387   if (CondCode0 == ARMCC::AL || CondCode1 == ARMCC::AL)
12388     return SDValue();
12389
12390   unsigned Opposite0 = ARMCC::getOppositeCondition(CondCode0);
12391   unsigned Opposite1 = ARMCC::getOppositeCondition(CondCode1);
12392
12393   if (!isValidMVECond(Opposite0,
12394                       N0->getOperand(0)->getValueType(0).isFloatingPoint()) ||
12395       !isValidMVECond(Opposite1,
12396                       N1->getOperand(0)->getValueType(0).isFloatingPoint()))
12397     return SDValue();
12398
12399   SmallVector<SDValue, 4> Ops0;
12400   Ops0.push_back(N0->getOperand(0));
12401   if (N0->getOpcode() == ARMISD::VCMP)
12402     Ops0.push_back(N0->getOperand(1));
12403   Ops0.push_back(DCI.DAG.getConstant(Opposite0, SDLoc(N0), MVT::i32));
12404   SmallVector<SDValue, 4> Ops1;
12405   Ops1.push_back(N1->getOperand(0));
12406   if (N1->getOpcode() == ARMISD::VCMP)
12407     Ops1.push_back(N1->getOperand(1));
12408   Ops1.push_back(DCI.DAG.getConstant(Opposite1, SDLoc(N1), MVT::i32));
12409
12410   SDValue NewN0 = DCI.DAG.getNode(N0->getOpcode(), SDLoc(N0), VT, Ops0);
12411   SDValue NewN1 = DCI.DAG.getNode(N1->getOpcode(), SDLoc(N1), VT, Ops1);
12412   SDValue And = DCI.DAG.getNode(ISD::AND, SDLoc(N), VT, NewN0, NewN1);
12413   return DCI.DAG.getNode(ISD::XOR, SDLoc(N), VT, And,
12414                          DCI.DAG.getAllOnesConstant(SDLoc(N), VT));
12415 }
12416
12417 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
12418 static SDValue PerformORCombine(SDNode *N,
12419                                 TargetLowering::DAGCombinerInfo &DCI,
12420                                 const ARMSubtarget *Subtarget) {
12421   // Attempt to use immediate-form VORR
12422   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
12423   SDLoc dl(N);
12424   EVT VT = N->getValueType(0);
12425   SelectionDAG &DAG = DCI.DAG;
12426
12427   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12428     return SDValue();
12429
12430   APInt SplatBits, SplatUndef;
12431   unsigned SplatBitSize;
12432   bool HasAnyUndefs;
12433   if (BVN && Subtarget->hasNEON() &&
12434       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
12435     if (SplatBitSize <= 64) {
12436       EVT VorrVT;
12437       SDValue Val = isVMOVModifiedImm(SplatBits.getZExtValue(),
12438                                       SplatUndef.getZExtValue(), SplatBitSize,
12439                                       DAG, dl, VorrVT, VT.is128BitVector(),
12440                                       OtherModImm);
12441       if (Val.getNode()) {
12442         SDValue Input =
12443           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
12444         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
12445         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
12446       }
12447     }
12448   }
12449
12450   if (!Subtarget->isThumb1Only()) {
12451     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
12452     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12453       return Result;
12454     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
12455       return Result;
12456   }
12457
12458   SDValue N0 = N->getOperand(0);
12459   SDValue N1 = N->getOperand(1);
12460
12461   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
12462   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
12463       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
12464
12465     // The code below optimizes (or (and X, Y), Z).
12466     // The AND operand needs to have a single user to make these optimizations
12467     // profitable.
12468     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
12469       return SDValue();
12470
12471     APInt SplatUndef;
12472     unsigned SplatBitSize;
12473     bool HasAnyUndefs;
12474
12475     APInt SplatBits0, SplatBits1;
12476     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
12477     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
12478     // Ensure that the second operand of both ands are constants
12479     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
12480                                       HasAnyUndefs) && !HasAnyUndefs) {
12481         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
12482                                           HasAnyUndefs) && !HasAnyUndefs) {
12483             // Ensure that the bit width of the constants are the same and that
12484             // the splat arguments are logical inverses as per the pattern we
12485             // are trying to simplify.
12486             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
12487                 SplatBits0 == ~SplatBits1) {
12488                 // Canonicalize the vector type to make instruction selection
12489                 // simpler.
12490                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
12491                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
12492                                              N0->getOperand(1),
12493                                              N0->getOperand(0),
12494                                              N1->getOperand(0));
12495                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12496             }
12497         }
12498     }
12499   }
12500
12501   if (Subtarget->hasMVEIntegerOps() &&
12502       (VT == MVT::v4i1 || VT == MVT::v8i1 || VT == MVT::v16i1))
12503     return PerformORCombine_i1(N, DCI, Subtarget);
12504
12505   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
12506   // reasonable.
12507   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
12508     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
12509       return Res;
12510   }
12511
12512   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12513     return Result;
12514
12515   return SDValue();
12516 }
12517
12518 static SDValue PerformXORCombine(SDNode *N,
12519                                  TargetLowering::DAGCombinerInfo &DCI,
12520                                  const ARMSubtarget *Subtarget) {
12521   EVT VT = N->getValueType(0);
12522   SelectionDAG &DAG = DCI.DAG;
12523
12524   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
12525     return SDValue();
12526
12527   if (!Subtarget->isThumb1Only()) {
12528     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
12529     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
12530       return Result;
12531
12532     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
12533       return Result;
12534   }
12535
12536   return SDValue();
12537 }
12538
12539 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
12540 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
12541 // their position in "to" (Rd).
12542 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
12543   assert(N->getOpcode() == ARMISD::BFI);
12544
12545   SDValue From = N->getOperand(1);
12546   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
12547   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
12548
12549   // If the Base came from a SHR #C, we can deduce that it is really testing bit
12550   // #C in the base of the SHR.
12551   if (From->getOpcode() == ISD::SRL &&
12552       isa<ConstantSDNode>(From->getOperand(1))) {
12553     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
12554     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
12555     FromMask <<= Shift.getLimitedValue(31);
12556     From = From->getOperand(0);
12557   }
12558
12559   return From;
12560 }
12561
12562 // If A and B contain one contiguous set of bits, does A | B == A . B?
12563 //
12564 // Neither A nor B must be zero.
12565 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
12566   unsigned LastActiveBitInA =  A.countTrailingZeros();
12567   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
12568   return LastActiveBitInA - 1 == FirstActiveBitInB;
12569 }
12570
12571 static SDValue FindBFIToCombineWith(SDNode *N) {
12572   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
12573   // if one exists.
12574   APInt ToMask, FromMask;
12575   SDValue From = ParseBFI(N, ToMask, FromMask);
12576   SDValue To = N->getOperand(0);
12577
12578   // Now check for a compatible BFI to merge with. We can pass through BFIs that
12579   // aren't compatible, but not if they set the same bit in their destination as
12580   // we do (or that of any BFI we're going to combine with).
12581   SDValue V = To;
12582   APInt CombinedToMask = ToMask;
12583   while (V.getOpcode() == ARMISD::BFI) {
12584     APInt NewToMask, NewFromMask;
12585     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
12586     if (NewFrom != From) {
12587       // This BFI has a different base. Keep going.
12588       CombinedToMask |= NewToMask;
12589       V = V.getOperand(0);
12590       continue;
12591     }
12592
12593     // Do the written bits conflict with any we've seen so far?
12594     if ((NewToMask & CombinedToMask).getBoolValue())
12595       // Conflicting bits - bail out because going further is unsafe.
12596       return SDValue();
12597
12598     // Are the new bits contiguous when combined with the old bits?
12599     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
12600         BitsProperlyConcatenate(FromMask, NewFromMask))
12601       return V;
12602     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
12603         BitsProperlyConcatenate(NewFromMask, FromMask))
12604       return V;
12605
12606     // We've seen a write to some bits, so track it.
12607     CombinedToMask |= NewToMask;
12608     // Keep going...
12609     V = V.getOperand(0);
12610   }
12611
12612   return SDValue();
12613 }
12614
12615 static SDValue PerformBFICombine(SDNode *N,
12616                                  TargetLowering::DAGCombinerInfo &DCI) {
12617   SDValue N1 = N->getOperand(1);
12618   if (N1.getOpcode() == ISD::AND) {
12619     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
12620     // the bits being cleared by the AND are not demanded by the BFI.
12621     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
12622     if (!N11C)
12623       return SDValue();
12624     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12625     unsigned LSB = countTrailingZeros(~InvMask);
12626     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
12627     assert(Width <
12628                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
12629            "undefined behavior");
12630     unsigned Mask = (1u << Width) - 1;
12631     unsigned Mask2 = N11C->getZExtValue();
12632     if ((Mask & (~Mask2)) == 0)
12633       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
12634                              N->getOperand(0), N1.getOperand(0),
12635                              N->getOperand(2));
12636   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
12637     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
12638     // Keep track of any consecutive bits set that all come from the same base
12639     // value. We can combine these together into a single BFI.
12640     SDValue CombineBFI = FindBFIToCombineWith(N);
12641     if (CombineBFI == SDValue())
12642       return SDValue();
12643
12644     // We've found a BFI.
12645     APInt ToMask1, FromMask1;
12646     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
12647
12648     APInt ToMask2, FromMask2;
12649     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
12650     assert(From1 == From2);
12651     (void)From2;
12652
12653     // First, unlink CombineBFI.
12654     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
12655     // Then create a new BFI, combining the two together.
12656     APInt NewFromMask = FromMask1 | FromMask2;
12657     APInt NewToMask = ToMask1 | ToMask2;
12658
12659     EVT VT = N->getValueType(0);
12660     SDLoc dl(N);
12661
12662     if (NewFromMask[0] == 0)
12663       From1 = DCI.DAG.getNode(
12664         ISD::SRL, dl, VT, From1,
12665         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
12666     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
12667                            DCI.DAG.getConstant(~NewToMask, dl, VT));
12668   }
12669   return SDValue();
12670 }
12671
12672 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
12673 /// ARMISD::VMOVRRD.
12674 static SDValue PerformVMOVRRDCombine(SDNode *N,
12675                                      TargetLowering::DAGCombinerInfo &DCI,
12676                                      const ARMSubtarget *Subtarget) {
12677   // vmovrrd(vmovdrr x, y) -> x,y
12678   SDValue InDouble = N->getOperand(0);
12679   if (InDouble.getOpcode() == ARMISD::VMOVDRR && Subtarget->hasFP64())
12680     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
12681
12682   // vmovrrd(load f64) -> (load i32), (load i32)
12683   SDNode *InNode = InDouble.getNode();
12684   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
12685       InNode->getValueType(0) == MVT::f64 &&
12686       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
12687       !cast<LoadSDNode>(InNode)->isVolatile()) {
12688     // TODO: Should this be done for non-FrameIndex operands?
12689     LoadSDNode *LD = cast<LoadSDNode>(InNode);
12690
12691     SelectionDAG &DAG = DCI.DAG;
12692     SDLoc DL(LD);
12693     SDValue BasePtr = LD->getBasePtr();
12694     SDValue NewLD1 =
12695         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
12696                     LD->getAlignment(), LD->getMemOperand()->getFlags());
12697
12698     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12699                                     DAG.getConstant(4, DL, MVT::i32));
12700
12701     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, LD->getChain(), OffsetPtr,
12702                                  LD->getPointerInfo().getWithOffset(4),
12703                                  std::min(4U, LD->getAlignment()),
12704                                  LD->getMemOperand()->getFlags());
12705
12706     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
12707     if (DCI.DAG.getDataLayout().isBigEndian())
12708       std::swap (NewLD1, NewLD2);
12709     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
12710     return Result;
12711   }
12712
12713   return SDValue();
12714 }
12715
12716 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
12717 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
12718 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
12719   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
12720   SDValue Op0 = N->getOperand(0);
12721   SDValue Op1 = N->getOperand(1);
12722   if (Op0.getOpcode() == ISD::BITCAST)
12723     Op0 = Op0.getOperand(0);
12724   if (Op1.getOpcode() == ISD::BITCAST)
12725     Op1 = Op1.getOperand(0);
12726   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
12727       Op0.getNode() == Op1.getNode() &&
12728       Op0.getResNo() == 0 && Op1.getResNo() == 1)
12729     return DAG.getNode(ISD::BITCAST, SDLoc(N),
12730                        N->getValueType(0), Op0.getOperand(0));
12731   return SDValue();
12732 }
12733
12734 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
12735 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
12736 /// i64 vector to have f64 elements, since the value can then be loaded
12737 /// directly into a VFP register.
12738 static bool hasNormalLoadOperand(SDNode *N) {
12739   unsigned NumElts = N->getValueType(0).getVectorNumElements();
12740   for (unsigned i = 0; i < NumElts; ++i) {
12741     SDNode *Elt = N->getOperand(i).getNode();
12742     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
12743       return true;
12744   }
12745   return false;
12746 }
12747
12748 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
12749 /// ISD::BUILD_VECTOR.
12750 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
12751                                           TargetLowering::DAGCombinerInfo &DCI,
12752                                           const ARMSubtarget *Subtarget) {
12753   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
12754   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
12755   // into a pair of GPRs, which is fine when the value is used as a scalar,
12756   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
12757   SelectionDAG &DAG = DCI.DAG;
12758   if (N->getNumOperands() == 2)
12759     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
12760       return RV;
12761
12762   // Load i64 elements as f64 values so that type legalization does not split
12763   // them up into i32 values.
12764   EVT VT = N->getValueType(0);
12765   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
12766     return SDValue();
12767   SDLoc dl(N);
12768   SmallVector<SDValue, 8> Ops;
12769   unsigned NumElts = VT.getVectorNumElements();
12770   for (unsigned i = 0; i < NumElts; ++i) {
12771     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
12772     Ops.push_back(V);
12773     // Make the DAGCombiner fold the bitcast.
12774     DCI.AddToWorklist(V.getNode());
12775   }
12776   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
12777   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
12778   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12779 }
12780
12781 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
12782 static SDValue
12783 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12784   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
12785   // At that time, we may have inserted bitcasts from integer to float.
12786   // If these bitcasts have survived DAGCombine, change the lowering of this
12787   // BUILD_VECTOR in something more vector friendly, i.e., that does not
12788   // force to use floating point types.
12789
12790   // Make sure we can change the type of the vector.
12791   // This is possible iff:
12792   // 1. The vector is only used in a bitcast to a integer type. I.e.,
12793   //    1.1. Vector is used only once.
12794   //    1.2. Use is a bit convert to an integer type.
12795   // 2. The size of its operands are 32-bits (64-bits are not legal).
12796   EVT VT = N->getValueType(0);
12797   EVT EltVT = VT.getVectorElementType();
12798
12799   // Check 1.1. and 2.
12800   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
12801     return SDValue();
12802
12803   // By construction, the input type must be float.
12804   assert(EltVT == MVT::f32 && "Unexpected type!");
12805
12806   // Check 1.2.
12807   SDNode *Use = *N->use_begin();
12808   if (Use->getOpcode() != ISD::BITCAST ||
12809       Use->getValueType(0).isFloatingPoint())
12810     return SDValue();
12811
12812   // Check profitability.
12813   // Model is, if more than half of the relevant operands are bitcast from
12814   // i32, turn the build_vector into a sequence of insert_vector_elt.
12815   // Relevant operands are everything that is not statically
12816   // (i.e., at compile time) bitcasted.
12817   unsigned NumOfBitCastedElts = 0;
12818   unsigned NumElts = VT.getVectorNumElements();
12819   unsigned NumOfRelevantElts = NumElts;
12820   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
12821     SDValue Elt = N->getOperand(Idx);
12822     if (Elt->getOpcode() == ISD::BITCAST) {
12823       // Assume only bit cast to i32 will go away.
12824       if (Elt->getOperand(0).getValueType() == MVT::i32)
12825         ++NumOfBitCastedElts;
12826     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
12827       // Constants are statically casted, thus do not count them as
12828       // relevant operands.
12829       --NumOfRelevantElts;
12830   }
12831
12832   // Check if more than half of the elements require a non-free bitcast.
12833   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
12834     return SDValue();
12835
12836   SelectionDAG &DAG = DCI.DAG;
12837   // Create the new vector type.
12838   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
12839   // Check if the type is legal.
12840   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12841   if (!TLI.isTypeLegal(VecVT))
12842     return SDValue();
12843
12844   // Combine:
12845   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
12846   // => BITCAST INSERT_VECTOR_ELT
12847   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
12848   //                      (BITCAST EN), N.
12849   SDValue Vec = DAG.getUNDEF(VecVT);
12850   SDLoc dl(N);
12851   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
12852     SDValue V = N->getOperand(Idx);
12853     if (V.isUndef())
12854       continue;
12855     if (V.getOpcode() == ISD::BITCAST &&
12856         V->getOperand(0).getValueType() == MVT::i32)
12857       // Fold obvious case.
12858       V = V.getOperand(0);
12859     else {
12860       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
12861       // Make the DAGCombiner fold the bitcasts.
12862       DCI.AddToWorklist(V.getNode());
12863     }
12864     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
12865     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
12866   }
12867   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
12868   // Make the DAGCombiner fold the bitcasts.
12869   DCI.AddToWorklist(Vec.getNode());
12870   return Vec;
12871 }
12872
12873 static SDValue
12874 PerformPREDICATE_CASTCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
12875   EVT VT = N->getValueType(0);
12876   SDValue Op = N->getOperand(0);
12877   SDLoc dl(N);
12878
12879   // PREDICATE_CAST(PREDICATE_CAST(x)) == PREDICATE_CAST(x)
12880   if (Op->getOpcode() == ARMISD::PREDICATE_CAST) {
12881     // If the valuetypes are the same, we can remove the cast entirely.
12882     if (Op->getOperand(0).getValueType() == VT)
12883       return Op->getOperand(0);
12884     return DCI.DAG.getNode(ARMISD::PREDICATE_CAST, dl,
12885                            Op->getOperand(0).getValueType(), Op->getOperand(0));
12886   }
12887
12888   return SDValue();
12889 }
12890
12891 static SDValue PerformVCMPCombine(SDNode *N,
12892                                   TargetLowering::DAGCombinerInfo &DCI,
12893                                   const ARMSubtarget *Subtarget) {
12894   if (!Subtarget->hasMVEIntegerOps())
12895     return SDValue();
12896
12897   EVT VT = N->getValueType(0);
12898   SDValue Op0 = N->getOperand(0);
12899   SDValue Op1 = N->getOperand(1);
12900   ARMCC::CondCodes Cond =
12901       (ARMCC::CondCodes)cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
12902   SDLoc dl(N);
12903
12904   // vcmp X, 0, cc -> vcmpz X, cc
12905   if (isZeroVector(Op1))
12906     return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op0,
12907                            N->getOperand(2));
12908
12909   unsigned SwappedCond = getSwappedCondition(Cond);
12910   if (isValidMVECond(SwappedCond, VT.isFloatingPoint())) {
12911     // vcmp 0, X, cc -> vcmpz X, reversed(cc)
12912     if (isZeroVector(Op0))
12913       return DCI.DAG.getNode(ARMISD::VCMPZ, dl, VT, Op1,
12914                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
12915     // vcmp vdup(Y), X, cc -> vcmp X, vdup(Y), reversed(cc)
12916     if (Op0->getOpcode() == ARMISD::VDUP && Op1->getOpcode() != ARMISD::VDUP)
12917       return DCI.DAG.getNode(ARMISD::VCMP, dl, VT, Op1, Op0,
12918                              DCI.DAG.getConstant(SwappedCond, dl, MVT::i32));
12919   }
12920
12921   return SDValue();
12922 }
12923
12924 /// PerformInsertEltCombine - Target-specific dag combine xforms for
12925 /// ISD::INSERT_VECTOR_ELT.
12926 static SDValue PerformInsertEltCombine(SDNode *N,
12927                                        TargetLowering::DAGCombinerInfo &DCI) {
12928   // Bitcast an i64 load inserted into a vector to f64.
12929   // Otherwise, the i64 value will be legalized to a pair of i32 values.
12930   EVT VT = N->getValueType(0);
12931   SDNode *Elt = N->getOperand(1).getNode();
12932   if (VT.getVectorElementType() != MVT::i64 ||
12933       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
12934     return SDValue();
12935
12936   SelectionDAG &DAG = DCI.DAG;
12937   SDLoc dl(N);
12938   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12939                                  VT.getVectorNumElements());
12940   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
12941   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
12942   // Make the DAGCombiner fold the bitcasts.
12943   DCI.AddToWorklist(Vec.getNode());
12944   DCI.AddToWorklist(V.getNode());
12945   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
12946                                Vec, V, N->getOperand(2));
12947   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
12948 }
12949
12950 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
12951 /// ISD::VECTOR_SHUFFLE.
12952 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
12953   // The LLVM shufflevector instruction does not require the shuffle mask
12954   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
12955   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
12956   // operands do not match the mask length, they are extended by concatenating
12957   // them with undef vectors.  That is probably the right thing for other
12958   // targets, but for NEON it is better to concatenate two double-register
12959   // size vector operands into a single quad-register size vector.  Do that
12960   // transformation here:
12961   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
12962   //   shuffle(concat(v1, v2), undef)
12963   SDValue Op0 = N->getOperand(0);
12964   SDValue Op1 = N->getOperand(1);
12965   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
12966       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
12967       Op0.getNumOperands() != 2 ||
12968       Op1.getNumOperands() != 2)
12969     return SDValue();
12970   SDValue Concat0Op1 = Op0.getOperand(1);
12971   SDValue Concat1Op1 = Op1.getOperand(1);
12972   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
12973     return SDValue();
12974   // Skip the transformation if any of the types are illegal.
12975   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12976   EVT VT = N->getValueType(0);
12977   if (!TLI.isTypeLegal(VT) ||
12978       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
12979       !TLI.isTypeLegal(Concat1Op1.getValueType()))
12980     return SDValue();
12981
12982   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12983                                   Op0.getOperand(0), Op1.getOperand(0));
12984   // Translate the shuffle mask.
12985   SmallVector<int, 16> NewMask;
12986   unsigned NumElts = VT.getVectorNumElements();
12987   unsigned HalfElts = NumElts/2;
12988   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12989   for (unsigned n = 0; n < NumElts; ++n) {
12990     int MaskElt = SVN->getMaskElt(n);
12991     int NewElt = -1;
12992     if (MaskElt < (int)HalfElts)
12993       NewElt = MaskElt;
12994     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
12995       NewElt = HalfElts + MaskElt - NumElts;
12996     NewMask.push_back(NewElt);
12997   }
12998   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
12999                               DAG.getUNDEF(VT), NewMask);
13000 }
13001
13002 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
13003 /// NEON load/store intrinsics, and generic vector load/stores, to merge
13004 /// base address updates.
13005 /// For generic load/stores, the memory type is assumed to be a vector.
13006 /// The caller is assumed to have checked legality.
13007 static SDValue CombineBaseUpdate(SDNode *N,
13008                                  TargetLowering::DAGCombinerInfo &DCI) {
13009   SelectionDAG &DAG = DCI.DAG;
13010   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
13011                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
13012   const bool isStore = N->getOpcode() == ISD::STORE;
13013   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
13014   SDValue Addr = N->getOperand(AddrOpIdx);
13015   MemSDNode *MemN = cast<MemSDNode>(N);
13016   SDLoc dl(N);
13017
13018   // Search for a use of the address operand that is an increment.
13019   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
13020          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
13021     SDNode *User = *UI;
13022     if (User->getOpcode() != ISD::ADD ||
13023         UI.getUse().getResNo() != Addr.getResNo())
13024       continue;
13025
13026     // Check that the add is independent of the load/store.  Otherwise, folding
13027     // it would create a cycle. We can avoid searching through Addr as it's a
13028     // predecessor to both.
13029     SmallPtrSet<const SDNode *, 32> Visited;
13030     SmallVector<const SDNode *, 16> Worklist;
13031     Visited.insert(Addr.getNode());
13032     Worklist.push_back(N);
13033     Worklist.push_back(User);
13034     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
13035         SDNode::hasPredecessorHelper(User, Visited, Worklist))
13036       continue;
13037
13038     // Find the new opcode for the updating load/store.
13039     bool isLoadOp = true;
13040     bool isLaneOp = false;
13041     unsigned NewOpc = 0;
13042     unsigned NumVecs = 0;
13043     if (isIntrinsic) {
13044       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
13045       switch (IntNo) {
13046       default: llvm_unreachable("unexpected intrinsic for Neon base update");
13047       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
13048         NumVecs = 1; break;
13049       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
13050         NumVecs = 2; break;
13051       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
13052         NumVecs = 3; break;
13053       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
13054         NumVecs = 4; break;
13055       case Intrinsic::arm_neon_vld2dup:
13056       case Intrinsic::arm_neon_vld3dup:
13057       case Intrinsic::arm_neon_vld4dup:
13058         // TODO: Support updating VLDxDUP nodes. For now, we just skip
13059         // combining base updates for such intrinsics.
13060         continue;
13061       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
13062         NumVecs = 2; isLaneOp = true; break;
13063       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
13064         NumVecs = 3; isLaneOp = true; break;
13065       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
13066         NumVecs = 4; isLaneOp = true; break;
13067       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
13068         NumVecs = 1; isLoadOp = false; break;
13069       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
13070         NumVecs = 2; isLoadOp = false; break;
13071       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
13072         NumVecs = 3; isLoadOp = false; break;
13073       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
13074         NumVecs = 4; isLoadOp = false; break;
13075       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
13076         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
13077       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
13078         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
13079       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
13080         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
13081       }
13082     } else {
13083       isLaneOp = true;
13084       switch (N->getOpcode()) {
13085       default: llvm_unreachable("unexpected opcode for Neon base update");
13086       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
13087       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
13088       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
13089       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
13090       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
13091         NumVecs = 1; isLaneOp = false; break;
13092       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
13093         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
13094       }
13095     }
13096
13097     // Find the size of memory referenced by the load/store.
13098     EVT VecTy;
13099     if (isLoadOp) {
13100       VecTy = N->getValueType(0);
13101     } else if (isIntrinsic) {
13102       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
13103     } else {
13104       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
13105       VecTy = N->getOperand(1).getValueType();
13106     }
13107
13108     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
13109     if (isLaneOp)
13110       NumBytes /= VecTy.getVectorNumElements();
13111
13112     // If the increment is a constant, it must match the memory ref size.
13113     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
13114     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
13115     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
13116       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
13117       // separate instructions that make it harder to use a non-constant update.
13118       continue;
13119     }
13120
13121     // OK, we found an ADD we can fold into the base update.
13122     // Now, create a _UPD node, taking care of not breaking alignment.
13123
13124     EVT AlignedVecTy = VecTy;
13125     unsigned Alignment = MemN->getAlignment();
13126
13127     // If this is a less-than-standard-aligned load/store, change the type to
13128     // match the standard alignment.
13129     // The alignment is overlooked when selecting _UPD variants; and it's
13130     // easier to introduce bitcasts here than fix that.
13131     // There are 3 ways to get to this base-update combine:
13132     // - intrinsics: they are assumed to be properly aligned (to the standard
13133     //   alignment of the memory type), so we don't need to do anything.
13134     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
13135     //   intrinsics, so, likewise, there's nothing to do.
13136     // - generic load/store instructions: the alignment is specified as an
13137     //   explicit operand, rather than implicitly as the standard alignment
13138     //   of the memory type (like the intrisics).  We need to change the
13139     //   memory type to match the explicit alignment.  That way, we don't
13140     //   generate non-standard-aligned ARMISD::VLDx nodes.
13141     if (isa<LSBaseSDNode>(N)) {
13142       if (Alignment == 0)
13143         Alignment = 1;
13144       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
13145         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
13146         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
13147         assert(!isLaneOp && "Unexpected generic load/store lane.");
13148         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
13149         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
13150       }
13151       // Don't set an explicit alignment on regular load/stores that we want
13152       // to transform to VLD/VST 1_UPD nodes.
13153       // This matches the behavior of regular load/stores, which only get an
13154       // explicit alignment if the MMO alignment is larger than the standard
13155       // alignment of the memory type.
13156       // Intrinsics, however, always get an explicit alignment, set to the
13157       // alignment of the MMO.
13158       Alignment = 1;
13159     }
13160
13161     // Create the new updating load/store node.
13162     // First, create an SDVTList for the new updating node's results.
13163     EVT Tys[6];
13164     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
13165     unsigned n;
13166     for (n = 0; n < NumResultVecs; ++n)
13167       Tys[n] = AlignedVecTy;
13168     Tys[n++] = MVT::i32;
13169     Tys[n] = MVT::Other;
13170     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
13171
13172     // Then, gather the new node's operands.
13173     SmallVector<SDValue, 8> Ops;
13174     Ops.push_back(N->getOperand(0)); // incoming chain
13175     Ops.push_back(N->getOperand(AddrOpIdx));
13176     Ops.push_back(Inc);
13177
13178     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
13179       // Try to match the intrinsic's signature
13180       Ops.push_back(StN->getValue());
13181     } else {
13182       // Loads (and of course intrinsics) match the intrinsics' signature,
13183       // so just add all but the alignment operand.
13184       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
13185         Ops.push_back(N->getOperand(i));
13186     }
13187
13188     // For all node types, the alignment operand is always the last one.
13189     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
13190
13191     // If this is a non-standard-aligned STORE, the penultimate operand is the
13192     // stored value.  Bitcast it to the aligned type.
13193     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
13194       SDValue &StVal = Ops[Ops.size()-2];
13195       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
13196     }
13197
13198     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
13199     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
13200                                            MemN->getMemOperand());
13201
13202     // Update the uses.
13203     SmallVector<SDValue, 5> NewResults;
13204     for (unsigned i = 0; i < NumResultVecs; ++i)
13205       NewResults.push_back(SDValue(UpdN.getNode(), i));
13206
13207     // If this is an non-standard-aligned LOAD, the first result is the loaded
13208     // value.  Bitcast it to the expected result type.
13209     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
13210       SDValue &LdVal = NewResults[0];
13211       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
13212     }
13213
13214     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
13215     DCI.CombineTo(N, NewResults);
13216     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
13217
13218     break;
13219   }
13220   return SDValue();
13221 }
13222
13223 static SDValue PerformVLDCombine(SDNode *N,
13224                                  TargetLowering::DAGCombinerInfo &DCI) {
13225   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13226     return SDValue();
13227
13228   return CombineBaseUpdate(N, DCI);
13229 }
13230
13231 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
13232 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
13233 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
13234 /// return true.
13235 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
13236   SelectionDAG &DAG = DCI.DAG;
13237   EVT VT = N->getValueType(0);
13238   // vldN-dup instructions only support 64-bit vectors for N > 1.
13239   if (!VT.is64BitVector())
13240     return false;
13241
13242   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
13243   SDNode *VLD = N->getOperand(0).getNode();
13244   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
13245     return false;
13246   unsigned NumVecs = 0;
13247   unsigned NewOpc = 0;
13248   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
13249   if (IntNo == Intrinsic::arm_neon_vld2lane) {
13250     NumVecs = 2;
13251     NewOpc = ARMISD::VLD2DUP;
13252   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
13253     NumVecs = 3;
13254     NewOpc = ARMISD::VLD3DUP;
13255   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
13256     NumVecs = 4;
13257     NewOpc = ARMISD::VLD4DUP;
13258   } else {
13259     return false;
13260   }
13261
13262   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
13263   // numbers match the load.
13264   unsigned VLDLaneNo =
13265     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
13266   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13267        UI != UE; ++UI) {
13268     // Ignore uses of the chain result.
13269     if (UI.getUse().getResNo() == NumVecs)
13270       continue;
13271     SDNode *User = *UI;
13272     if (User->getOpcode() != ARMISD::VDUPLANE ||
13273         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
13274       return false;
13275   }
13276
13277   // Create the vldN-dup node.
13278   EVT Tys[5];
13279   unsigned n;
13280   for (n = 0; n < NumVecs; ++n)
13281     Tys[n] = VT;
13282   Tys[n] = MVT::Other;
13283   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
13284   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
13285   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
13286   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
13287                                            Ops, VLDMemInt->getMemoryVT(),
13288                                            VLDMemInt->getMemOperand());
13289
13290   // Update the uses.
13291   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
13292        UI != UE; ++UI) {
13293     unsigned ResNo = UI.getUse().getResNo();
13294     // Ignore uses of the chain result.
13295     if (ResNo == NumVecs)
13296       continue;
13297     SDNode *User = *UI;
13298     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
13299   }
13300
13301   // Now the vldN-lane intrinsic is dead except for its chain result.
13302   // Update uses of the chain.
13303   std::vector<SDValue> VLDDupResults;
13304   for (unsigned n = 0; n < NumVecs; ++n)
13305     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
13306   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
13307   DCI.CombineTo(VLD, VLDDupResults);
13308
13309   return true;
13310 }
13311
13312 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
13313 /// ARMISD::VDUPLANE.
13314 static SDValue PerformVDUPLANECombine(SDNode *N,
13315                                       TargetLowering::DAGCombinerInfo &DCI) {
13316   SDValue Op = N->getOperand(0);
13317
13318   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
13319   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
13320   if (CombineVLDDUP(N, DCI))
13321     return SDValue(N, 0);
13322
13323   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
13324   // redundant.  Ignore bit_converts for now; element sizes are checked below.
13325   while (Op.getOpcode() == ISD::BITCAST)
13326     Op = Op.getOperand(0);
13327   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
13328     return SDValue();
13329
13330   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
13331   unsigned EltSize = Op.getScalarValueSizeInBits();
13332   // The canonical VMOV for a zero vector uses a 32-bit element size.
13333   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13334   unsigned EltBits;
13335   if (ARM_AM::decodeVMOVModImm(Imm, EltBits) == 0)
13336     EltSize = 8;
13337   EVT VT = N->getValueType(0);
13338   if (EltSize > VT.getScalarSizeInBits())
13339     return SDValue();
13340
13341   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
13342 }
13343
13344 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
13345 static SDValue PerformVDUPCombine(SDNode *N,
13346                                   TargetLowering::DAGCombinerInfo &DCI,
13347                                   const ARMSubtarget *Subtarget) {
13348   SelectionDAG &DAG = DCI.DAG;
13349   SDValue Op = N->getOperand(0);
13350
13351   if (!Subtarget->hasNEON())
13352     return SDValue();
13353
13354   // Match VDUP(LOAD) -> VLD1DUP.
13355   // We match this pattern here rather than waiting for isel because the
13356   // transform is only legal for unindexed loads.
13357   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
13358   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
13359       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
13360     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
13361                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
13362     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
13363     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
13364                                              Ops, LD->getMemoryVT(),
13365                                              LD->getMemOperand());
13366     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
13367     return VLDDup;
13368   }
13369
13370   return SDValue();
13371 }
13372
13373 static SDValue PerformLOADCombine(SDNode *N,
13374                                   TargetLowering::DAGCombinerInfo &DCI) {
13375   EVT VT = N->getValueType(0);
13376
13377   // If this is a legal vector load, try to combine it into a VLD1_UPD.
13378   if (ISD::isNormalLoad(N) && VT.isVector() &&
13379       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13380     return CombineBaseUpdate(N, DCI);
13381
13382   return SDValue();
13383 }
13384
13385 // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
13386 // pack all of the elements in one place.  Next, store to memory in fewer
13387 // chunks.
13388 static SDValue PerformTruncatingStoreCombine(StoreSDNode *St,
13389                                              SelectionDAG &DAG) {
13390   SDValue StVal = St->getValue();
13391   EVT VT = StVal.getValueType();
13392   if (!St->isTruncatingStore() || !VT.isVector())
13393     return SDValue();
13394   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13395   EVT StVT = St->getMemoryVT();
13396   unsigned NumElems = VT.getVectorNumElements();
13397   assert(StVT != VT && "Cannot truncate to the same type");
13398   unsigned FromEltSz = VT.getScalarSizeInBits();
13399   unsigned ToEltSz = StVT.getScalarSizeInBits();
13400
13401   // From, To sizes and ElemCount must be pow of two
13402   if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz))
13403     return SDValue();
13404
13405   // We are going to use the original vector elt for storing.
13406   // Accumulated smaller vector elements must be a multiple of the store size.
13407   if (0 != (NumElems * FromEltSz) % ToEltSz)
13408     return SDValue();
13409
13410   unsigned SizeRatio = FromEltSz / ToEltSz;
13411   assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
13412
13413   // Create a type on which we perform the shuffle.
13414   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
13415                                    NumElems * SizeRatio);
13416   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
13417
13418   SDLoc DL(St);
13419   SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
13420   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13421   for (unsigned i = 0; i < NumElems; ++i)
13422     ShuffleVec[i] = DAG.getDataLayout().isBigEndian() ? (i + 1) * SizeRatio - 1
13423                                                       : i * SizeRatio;
13424
13425   // Can't shuffle using an illegal type.
13426   if (!TLI.isTypeLegal(WideVecVT))
13427     return SDValue();
13428
13429   SDValue Shuff = DAG.getVectorShuffle(
13430       WideVecVT, DL, WideVec, DAG.getUNDEF(WideVec.getValueType()), ShuffleVec);
13431   // At this point all of the data is stored at the bottom of the
13432   // register. We now need to save it to mem.
13433
13434   // Find the largest store unit
13435   MVT StoreType = MVT::i8;
13436   for (MVT Tp : MVT::integer_valuetypes()) {
13437     if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
13438       StoreType = Tp;
13439   }
13440   // Didn't find a legal store type.
13441   if (!TLI.isTypeLegal(StoreType))
13442     return SDValue();
13443
13444   // Bitcast the original vector into a vector of store-size units
13445   EVT StoreVecVT =
13446       EVT::getVectorVT(*DAG.getContext(), StoreType,
13447                        VT.getSizeInBits() / EVT(StoreType).getSizeInBits());
13448   assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
13449   SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
13450   SmallVector<SDValue, 8> Chains;
13451   SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
13452                                       TLI.getPointerTy(DAG.getDataLayout()));
13453   SDValue BasePtr = St->getBasePtr();
13454
13455   // Perform one or more big stores into memory.
13456   unsigned E = (ToEltSz * NumElems) / StoreType.getSizeInBits();
13457   for (unsigned I = 0; I < E; I++) {
13458     SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, StoreType,
13459                                  ShuffWide, DAG.getIntPtrConstant(I, DL));
13460     SDValue Ch =
13461         DAG.getStore(St->getChain(), DL, SubVec, BasePtr, St->getPointerInfo(),
13462                      St->getAlignment(), St->getMemOperand()->getFlags());
13463     BasePtr =
13464         DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr, Increment);
13465     Chains.push_back(Ch);
13466   }
13467   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
13468 }
13469
13470 // Try taking a single vector store from an truncate (which would otherwise turn
13471 // into an expensive buildvector) and splitting it into a series of narrowing
13472 // stores.
13473 static SDValue PerformSplittingToNarrowingStores(StoreSDNode *St,
13474                                                  SelectionDAG &DAG) {
13475   if (!St->isSimple() || St->isTruncatingStore() || !St->isUnindexed())
13476     return SDValue();
13477   SDValue Trunc = St->getValue();
13478   if (Trunc->getOpcode() != ISD::TRUNCATE)
13479     return SDValue();
13480   EVT FromVT = Trunc->getOperand(0).getValueType();
13481   EVT ToVT = Trunc.getValueType();
13482   if (!ToVT.isVector())
13483     return SDValue();
13484   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
13485   EVT ToEltVT = ToVT.getVectorElementType();
13486   EVT FromEltVT = FromVT.getVectorElementType();
13487
13488   unsigned NumElements = 0;
13489   if (FromEltVT == MVT::i32 && (ToEltVT == MVT::i16 || ToEltVT == MVT::i8))
13490     NumElements = 4;
13491   if (FromEltVT == MVT::i16 && ToEltVT == MVT::i8)
13492     NumElements = 8;
13493   if (NumElements == 0 || FromVT.getVectorNumElements() == NumElements ||
13494       FromVT.getVectorNumElements() % NumElements != 0)
13495     return SDValue();
13496
13497   SDLoc DL(St);
13498   // Details about the old store
13499   SDValue Ch = St->getChain();
13500   SDValue BasePtr = St->getBasePtr();
13501   unsigned Alignment = St->getOriginalAlignment();
13502   MachineMemOperand::Flags MMOFlags = St->getMemOperand()->getFlags();
13503   AAMDNodes AAInfo = St->getAAInfo();
13504
13505   EVT NewFromVT = EVT::getVectorVT(*DAG.getContext(), FromEltVT, NumElements);
13506   EVT NewToVT = EVT::getVectorVT(*DAG.getContext(), ToEltVT, NumElements);
13507
13508   SmallVector<SDValue, 4> Stores;
13509   for (unsigned i = 0; i < FromVT.getVectorNumElements() / NumElements; i++) {
13510     unsigned NewOffset = i * NumElements * ToEltVT.getSizeInBits() / 8;
13511     SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
13512
13513     SDValue Extract =
13514         DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewFromVT, Trunc.getOperand(0),
13515                     DAG.getConstant(i * NumElements, DL, MVT::i32));
13516     SDValue Store = DAG.getTruncStore(
13517         Ch, DL, Extract, NewPtr, St->getPointerInfo().getWithOffset(NewOffset),
13518         NewToVT, Alignment, MMOFlags, AAInfo);
13519     Stores.push_back(Store);
13520   }
13521   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Stores);
13522 }
13523
13524 /// PerformSTORECombine - Target-specific dag combine xforms for
13525 /// ISD::STORE.
13526 static SDValue PerformSTORECombine(SDNode *N,
13527                                    TargetLowering::DAGCombinerInfo &DCI,
13528                                    const ARMSubtarget *Subtarget) {
13529   StoreSDNode *St = cast<StoreSDNode>(N);
13530   if (St->isVolatile())
13531     return SDValue();
13532   SDValue StVal = St->getValue();
13533   EVT VT = StVal.getValueType();
13534
13535   if (Subtarget->hasNEON())
13536     if (SDValue Store = PerformTruncatingStoreCombine(St, DCI.DAG))
13537       return Store;
13538
13539   if (Subtarget->hasMVEIntegerOps())
13540     if (SDValue NewToken = PerformSplittingToNarrowingStores(St, DCI.DAG))
13541       return NewToken;
13542
13543   if (!ISD::isNormalStore(St))
13544     return SDValue();
13545
13546   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
13547   // ARM stores of arguments in the same cache line.
13548   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
13549       StVal.getNode()->hasOneUse()) {
13550     SelectionDAG  &DAG = DCI.DAG;
13551     bool isBigEndian = DAG.getDataLayout().isBigEndian();
13552     SDLoc DL(St);
13553     SDValue BasePtr = St->getBasePtr();
13554     SDValue NewST1 = DAG.getStore(
13555         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
13556         BasePtr, St->getPointerInfo(), St->getAlignment(),
13557         St->getMemOperand()->getFlags());
13558
13559     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
13560                                     DAG.getConstant(4, DL, MVT::i32));
13561     return DAG.getStore(NewST1.getValue(0), DL,
13562                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
13563                         OffsetPtr, St->getPointerInfo(),
13564                         std::min(4U, St->getAlignment() / 2),
13565                         St->getMemOperand()->getFlags());
13566   }
13567
13568   if (StVal.getValueType() == MVT::i64 &&
13569       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13570
13571     // Bitcast an i64 store extracted from a vector to f64.
13572     // Otherwise, the i64 value will be legalized to a pair of i32 values.
13573     SelectionDAG &DAG = DCI.DAG;
13574     SDLoc dl(StVal);
13575     SDValue IntVec = StVal.getOperand(0);
13576     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
13577                                    IntVec.getValueType().getVectorNumElements());
13578     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
13579     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
13580                                  Vec, StVal.getOperand(1));
13581     dl = SDLoc(N);
13582     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
13583     // Make the DAGCombiner fold the bitcasts.
13584     DCI.AddToWorklist(Vec.getNode());
13585     DCI.AddToWorklist(ExtElt.getNode());
13586     DCI.AddToWorklist(V.getNode());
13587     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
13588                         St->getPointerInfo(), St->getAlignment(),
13589                         St->getMemOperand()->getFlags(), St->getAAInfo());
13590   }
13591
13592   // If this is a legal vector store, try to combine it into a VST1_UPD.
13593   if (Subtarget->hasNEON() && ISD::isNormalStore(N) && VT.isVector() &&
13594       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
13595     return CombineBaseUpdate(N, DCI);
13596
13597   return SDValue();
13598 }
13599
13600 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
13601 /// can replace combinations of VMUL and VCVT (floating-point to integer)
13602 /// when the VMUL has a constant operand that is a power of 2.
13603 ///
13604 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13605 ///  vmul.f32        d16, d17, d16
13606 ///  vcvt.s32.f32    d16, d16
13607 /// becomes:
13608 ///  vcvt.s32.f32    d16, d16, #3
13609 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
13610                                   const ARMSubtarget *Subtarget) {
13611   if (!Subtarget->hasNEON())
13612     return SDValue();
13613
13614   SDValue Op = N->getOperand(0);
13615   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
13616       Op.getOpcode() != ISD::FMUL)
13617     return SDValue();
13618
13619   SDValue ConstVec = Op->getOperand(1);
13620   if (!isa<BuildVectorSDNode>(ConstVec))
13621     return SDValue();
13622
13623   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
13624   uint32_t FloatBits = FloatTy.getSizeInBits();
13625   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
13626   uint32_t IntBits = IntTy.getSizeInBits();
13627   unsigned NumLanes = Op.getValueType().getVectorNumElements();
13628   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13629     // These instructions only exist converting from f32 to i32. We can handle
13630     // smaller integers by generating an extra truncate, but larger ones would
13631     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13632     // these intructions only support v2i32/v4i32 types.
13633     return SDValue();
13634   }
13635
13636   BitVector UndefElements;
13637   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13638   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13639   if (C == -1 || C == 0 || C > 32)
13640     return SDValue();
13641
13642   SDLoc dl(N);
13643   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
13644   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
13645     Intrinsic::arm_neon_vcvtfp2fxu;
13646   SDValue FixConv = DAG.getNode(
13647       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13648       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
13649       DAG.getConstant(C, dl, MVT::i32));
13650
13651   if (IntBits < FloatBits)
13652     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
13653
13654   return FixConv;
13655 }
13656
13657 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
13658 /// can replace combinations of VCVT (integer to floating-point) and VDIV
13659 /// when the VDIV has a constant operand that is a power of 2.
13660 ///
13661 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
13662 ///  vcvt.f32.s32    d16, d16
13663 ///  vdiv.f32        d16, d17, d16
13664 /// becomes:
13665 ///  vcvt.f32.s32    d16, d16, #3
13666 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
13667                                   const ARMSubtarget *Subtarget) {
13668   if (!Subtarget->hasNEON())
13669     return SDValue();
13670
13671   SDValue Op = N->getOperand(0);
13672   unsigned OpOpcode = Op.getNode()->getOpcode();
13673   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
13674       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
13675     return SDValue();
13676
13677   SDValue ConstVec = N->getOperand(1);
13678   if (!isa<BuildVectorSDNode>(ConstVec))
13679     return SDValue();
13680
13681   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
13682   uint32_t FloatBits = FloatTy.getSizeInBits();
13683   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
13684   uint32_t IntBits = IntTy.getSizeInBits();
13685   unsigned NumLanes = Op.getValueType().getVectorNumElements();
13686   if (FloatBits != 32 || IntBits > 32 || (NumLanes != 4 && NumLanes != 2)) {
13687     // These instructions only exist converting from i32 to f32. We can handle
13688     // smaller integers by generating an extra extend, but larger ones would
13689     // be lossy. We also can't handle anything other than 2 or 4 lanes, since
13690     // these intructions only support v2i32/v4i32 types.
13691     return SDValue();
13692   }
13693
13694   BitVector UndefElements;
13695   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
13696   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
13697   if (C == -1 || C == 0 || C > 32)
13698     return SDValue();
13699
13700   SDLoc dl(N);
13701   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
13702   SDValue ConvInput = Op.getOperand(0);
13703   if (IntBits < FloatBits)
13704     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
13705                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
13706                             ConvInput);
13707
13708   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
13709     Intrinsic::arm_neon_vcvtfxu2fp;
13710   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
13711                      Op.getValueType(),
13712                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
13713                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
13714 }
13715
13716 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
13717 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
13718   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13719   switch (IntNo) {
13720   default:
13721     // Don't do anything for most intrinsics.
13722     break;
13723
13724   // Vector shifts: check for immediate versions and lower them.
13725   // Note: This is done during DAG combining instead of DAG legalizing because
13726   // the build_vectors for 64-bit vector element shift counts are generally
13727   // not legal, and it is hard to see their values after they get legalized to
13728   // loads from a constant pool.
13729   case Intrinsic::arm_neon_vshifts:
13730   case Intrinsic::arm_neon_vshiftu:
13731   case Intrinsic::arm_neon_vrshifts:
13732   case Intrinsic::arm_neon_vrshiftu:
13733   case Intrinsic::arm_neon_vrshiftn:
13734   case Intrinsic::arm_neon_vqshifts:
13735   case Intrinsic::arm_neon_vqshiftu:
13736   case Intrinsic::arm_neon_vqshiftsu:
13737   case Intrinsic::arm_neon_vqshiftns:
13738   case Intrinsic::arm_neon_vqshiftnu:
13739   case Intrinsic::arm_neon_vqshiftnsu:
13740   case Intrinsic::arm_neon_vqrshiftns:
13741   case Intrinsic::arm_neon_vqrshiftnu:
13742   case Intrinsic::arm_neon_vqrshiftnsu: {
13743     EVT VT = N->getOperand(1).getValueType();
13744     int64_t Cnt;
13745     unsigned VShiftOpc = 0;
13746
13747     switch (IntNo) {
13748     case Intrinsic::arm_neon_vshifts:
13749     case Intrinsic::arm_neon_vshiftu:
13750       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
13751         VShiftOpc = ARMISD::VSHLIMM;
13752         break;
13753       }
13754       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
13755         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ? ARMISD::VSHRsIMM
13756                                                           : ARMISD::VSHRuIMM);
13757         break;
13758       }
13759       return SDValue();
13760
13761     case Intrinsic::arm_neon_vrshifts:
13762     case Intrinsic::arm_neon_vrshiftu:
13763       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
13764         break;
13765       return SDValue();
13766
13767     case Intrinsic::arm_neon_vqshifts:
13768     case Intrinsic::arm_neon_vqshiftu:
13769       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13770         break;
13771       return SDValue();
13772
13773     case Intrinsic::arm_neon_vqshiftsu:
13774       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
13775         break;
13776       llvm_unreachable("invalid shift count for vqshlu intrinsic");
13777
13778     case Intrinsic::arm_neon_vrshiftn:
13779     case Intrinsic::arm_neon_vqshiftns:
13780     case Intrinsic::arm_neon_vqshiftnu:
13781     case Intrinsic::arm_neon_vqshiftnsu:
13782     case Intrinsic::arm_neon_vqrshiftns:
13783     case Intrinsic::arm_neon_vqrshiftnu:
13784     case Intrinsic::arm_neon_vqrshiftnsu:
13785       // Narrowing shifts require an immediate right shift.
13786       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
13787         break;
13788       llvm_unreachable("invalid shift count for narrowing vector shift "
13789                        "intrinsic");
13790
13791     default:
13792       llvm_unreachable("unhandled vector shift");
13793     }
13794
13795     switch (IntNo) {
13796     case Intrinsic::arm_neon_vshifts:
13797     case Intrinsic::arm_neon_vshiftu:
13798       // Opcode already set above.
13799       break;
13800     case Intrinsic::arm_neon_vrshifts:
13801       VShiftOpc = ARMISD::VRSHRsIMM;
13802       break;
13803     case Intrinsic::arm_neon_vrshiftu:
13804       VShiftOpc = ARMISD::VRSHRuIMM;
13805       break;
13806     case Intrinsic::arm_neon_vrshiftn:
13807       VShiftOpc = ARMISD::VRSHRNIMM;
13808       break;
13809     case Intrinsic::arm_neon_vqshifts:
13810       VShiftOpc = ARMISD::VQSHLsIMM;
13811       break;
13812     case Intrinsic::arm_neon_vqshiftu:
13813       VShiftOpc = ARMISD::VQSHLuIMM;
13814       break;
13815     case Intrinsic::arm_neon_vqshiftsu:
13816       VShiftOpc = ARMISD::VQSHLsuIMM;
13817       break;
13818     case Intrinsic::arm_neon_vqshiftns:
13819       VShiftOpc = ARMISD::VQSHRNsIMM;
13820       break;
13821     case Intrinsic::arm_neon_vqshiftnu:
13822       VShiftOpc = ARMISD::VQSHRNuIMM;
13823       break;
13824     case Intrinsic::arm_neon_vqshiftnsu:
13825       VShiftOpc = ARMISD::VQSHRNsuIMM;
13826       break;
13827     case Intrinsic::arm_neon_vqrshiftns:
13828       VShiftOpc = ARMISD::VQRSHRNsIMM;
13829       break;
13830     case Intrinsic::arm_neon_vqrshiftnu:
13831       VShiftOpc = ARMISD::VQRSHRNuIMM;
13832       break;
13833     case Intrinsic::arm_neon_vqrshiftnsu:
13834       VShiftOpc = ARMISD::VQRSHRNsuIMM;
13835       break;
13836     }
13837
13838     SDLoc dl(N);
13839     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13840                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
13841   }
13842
13843   case Intrinsic::arm_neon_vshiftins: {
13844     EVT VT = N->getOperand(1).getValueType();
13845     int64_t Cnt;
13846     unsigned VShiftOpc = 0;
13847
13848     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
13849       VShiftOpc = ARMISD::VSLIIMM;
13850     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
13851       VShiftOpc = ARMISD::VSRIIMM;
13852     else {
13853       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
13854     }
13855
13856     SDLoc dl(N);
13857     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
13858                        N->getOperand(1), N->getOperand(2),
13859                        DAG.getConstant(Cnt, dl, MVT::i32));
13860   }
13861
13862   case Intrinsic::arm_neon_vqrshifts:
13863   case Intrinsic::arm_neon_vqrshiftu:
13864     // No immediate versions of these to check for.
13865     break;
13866   }
13867
13868   return SDValue();
13869 }
13870
13871 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
13872 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
13873 /// combining instead of DAG legalizing because the build_vectors for 64-bit
13874 /// vector element shift counts are generally not legal, and it is hard to see
13875 /// their values after they get legalized to loads from a constant pool.
13876 static SDValue PerformShiftCombine(SDNode *N,
13877                                    TargetLowering::DAGCombinerInfo &DCI,
13878                                    const ARMSubtarget *ST) {
13879   SelectionDAG &DAG = DCI.DAG;
13880   EVT VT = N->getValueType(0);
13881   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
13882     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
13883     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
13884     SDValue N1 = N->getOperand(1);
13885     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
13886       SDValue N0 = N->getOperand(0);
13887       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
13888           DAG.MaskedValueIsZero(N0.getOperand(0),
13889                                 APInt::getHighBitsSet(32, 16)))
13890         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
13891     }
13892   }
13893
13894   if (ST->isThumb1Only() && N->getOpcode() == ISD::SHL && VT == MVT::i32 &&
13895       N->getOperand(0)->getOpcode() == ISD::AND &&
13896       N->getOperand(0)->hasOneUse()) {
13897     if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
13898       return SDValue();
13899     // Look for the pattern (shl (and x, AndMask), ShiftAmt). This doesn't
13900     // usually show up because instcombine prefers to canonicalize it to
13901     // (and (shl x, ShiftAmt) (shl AndMask, ShiftAmt)), but the shift can come
13902     // out of GEP lowering in some cases.
13903     SDValue N0 = N->getOperand(0);
13904     ConstantSDNode *ShiftAmtNode = dyn_cast<ConstantSDNode>(N->getOperand(1));
13905     if (!ShiftAmtNode)
13906       return SDValue();
13907     uint32_t ShiftAmt = static_cast<uint32_t>(ShiftAmtNode->getZExtValue());
13908     ConstantSDNode *AndMaskNode = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13909     if (!AndMaskNode)
13910       return SDValue();
13911     uint32_t AndMask = static_cast<uint32_t>(AndMaskNode->getZExtValue());
13912     // Don't transform uxtb/uxth.
13913     if (AndMask == 255 || AndMask == 65535)
13914       return SDValue();
13915     if (isMask_32(AndMask)) {
13916       uint32_t MaskedBits = countLeadingZeros(AndMask);
13917       if (MaskedBits > ShiftAmt) {
13918         SDLoc DL(N);
13919         SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
13920                                   DAG.getConstant(MaskedBits, DL, MVT::i32));
13921         return DAG.getNode(
13922             ISD::SRL, DL, MVT::i32, SHL,
13923             DAG.getConstant(MaskedBits - ShiftAmt, DL, MVT::i32));
13924       }
13925     }
13926   }
13927
13928   // Nothing to be done for scalar shifts.
13929   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13930   if (!VT.isVector() || !TLI.isTypeLegal(VT))
13931     return SDValue();
13932   if (ST->hasMVEIntegerOps() && VT == MVT::v2i64)
13933     return SDValue();
13934
13935   int64_t Cnt;
13936
13937   switch (N->getOpcode()) {
13938   default: llvm_unreachable("unexpected shift opcode");
13939
13940   case ISD::SHL:
13941     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
13942       SDLoc dl(N);
13943       return DAG.getNode(ARMISD::VSHLIMM, dl, VT, N->getOperand(0),
13944                          DAG.getConstant(Cnt, dl, MVT::i32));
13945     }
13946     break;
13947
13948   case ISD::SRA:
13949   case ISD::SRL:
13950     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
13951       unsigned VShiftOpc =
13952           (N->getOpcode() == ISD::SRA ? ARMISD::VSHRsIMM : ARMISD::VSHRuIMM);
13953       SDLoc dl(N);
13954       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
13955                          DAG.getConstant(Cnt, dl, MVT::i32));
13956     }
13957   }
13958   return SDValue();
13959 }
13960
13961 // Look for a sign/zero extend of a larger than legal load. This can be split
13962 // into two extending loads, which are simpler to deal with than an arbitrary
13963 // sign extend.
13964 static SDValue PerformSplittingToWideningLoad(SDNode *N, SelectionDAG &DAG) {
13965   SDValue N0 = N->getOperand(0);
13966   if (N0.getOpcode() != ISD::LOAD)
13967     return SDValue();
13968   LoadSDNode *LD = cast<LoadSDNode>(N0.getNode());
13969   if (!LD->isSimple() || !N0.hasOneUse() || LD->isIndexed() ||
13970       LD->getExtensionType() != ISD::NON_EXTLOAD)
13971     return SDValue();
13972   EVT FromVT = LD->getValueType(0);
13973   EVT ToVT = N->getValueType(0);
13974   if (!ToVT.isVector())
13975     return SDValue();
13976   assert(FromVT.getVectorNumElements() == ToVT.getVectorNumElements());
13977   EVT ToEltVT = ToVT.getVectorElementType();
13978   EVT FromEltVT = FromVT.getVectorElementType();
13979
13980   unsigned NumElements = 0;
13981   if (ToEltVT == MVT::i32 && (FromEltVT == MVT::i16 || FromEltVT == MVT::i8))
13982     NumElements = 4;
13983   if (ToEltVT == MVT::i16 && FromEltVT == MVT::i8)
13984     NumElements = 8;
13985   if (NumElements == 0 ||
13986       FromVT.getVectorNumElements() == NumElements ||
13987       FromVT.getVectorNumElements() % NumElements != 0 ||
13988       !isPowerOf2_32(NumElements))
13989     return SDValue();
13990
13991   SDLoc DL(LD);
13992   // Details about the old load
13993   SDValue Ch = LD->getChain();
13994   SDValue BasePtr = LD->getBasePtr();
13995   unsigned Alignment = LD->getOriginalAlignment();
13996   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
13997   AAMDNodes AAInfo = LD->getAAInfo();
13998
13999   ISD::LoadExtType NewExtType =
14000       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
14001   SDValue Offset = DAG.getUNDEF(BasePtr.getValueType());
14002   EVT NewFromVT = FromVT.getHalfNumVectorElementsVT(*DAG.getContext());
14003   EVT NewToVT = ToVT.getHalfNumVectorElementsVT(*DAG.getContext());
14004   unsigned NewOffset = NewFromVT.getSizeInBits() / 8;
14005   SDValue NewPtr = DAG.getObjectPtrOffset(DL, BasePtr, NewOffset);
14006
14007   // Split the load in half, each side of which is extended separately. This
14008   // is good enough, as legalisation will take it from there. They are either
14009   // already legal or they will be split further into something that is
14010   // legal.
14011   SDValue NewLoad1 =
14012       DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, BasePtr, Offset,
14013                   LD->getPointerInfo(), NewFromVT, Alignment, MMOFlags, AAInfo);
14014   SDValue NewLoad2 =
14015       DAG.getLoad(ISD::UNINDEXED, NewExtType, NewToVT, DL, Ch, NewPtr, Offset,
14016                   LD->getPointerInfo().getWithOffset(NewOffset), NewFromVT,
14017                   Alignment, MMOFlags, AAInfo);
14018
14019   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
14020                                  SDValue(NewLoad1.getNode(), 1),
14021                                  SDValue(NewLoad2.getNode(), 1));
14022   DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewChain);
14023   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ToVT, NewLoad1, NewLoad2);
14024 }
14025
14026 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
14027 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
14028 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
14029                                     const ARMSubtarget *ST) {
14030   SDValue N0 = N->getOperand(0);
14031
14032   // Check for sign- and zero-extensions of vector extract operations of 8- and
14033   // 16-bit vector elements. NEON and MVE support these directly. They are
14034   // handled during DAG combining because type legalization will promote them
14035   // to 32-bit types and it is messy to recognize the operations after that.
14036   if ((ST->hasNEON() || ST->hasMVEIntegerOps()) &&
14037       N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
14038     SDValue Vec = N0.getOperand(0);
14039     SDValue Lane = N0.getOperand(1);
14040     EVT VT = N->getValueType(0);
14041     EVT EltVT = N0.getValueType();
14042     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14043
14044     if (VT == MVT::i32 &&
14045         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
14046         TLI.isTypeLegal(Vec.getValueType()) &&
14047         isa<ConstantSDNode>(Lane)) {
14048
14049       unsigned Opc = 0;
14050       switch (N->getOpcode()) {
14051       default: llvm_unreachable("unexpected opcode");
14052       case ISD::SIGN_EXTEND:
14053         Opc = ARMISD::VGETLANEs;
14054         break;
14055       case ISD::ZERO_EXTEND:
14056       case ISD::ANY_EXTEND:
14057         Opc = ARMISD::VGETLANEu;
14058         break;
14059       }
14060       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
14061     }
14062   }
14063
14064   if (ST->hasMVEIntegerOps())
14065     if (SDValue NewLoad = PerformSplittingToWideningLoad(N, DAG))
14066       return NewLoad;
14067
14068   return SDValue();
14069 }
14070
14071 static const APInt *isPowerOf2Constant(SDValue V) {
14072   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
14073   if (!C)
14074     return nullptr;
14075   const APInt *CV = &C->getAPIntValue();
14076   return CV->isPowerOf2() ? CV : nullptr;
14077 }
14078
14079 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
14080   // If we have a CMOV, OR and AND combination such as:
14081   //   if (x & CN)
14082   //     y |= CM;
14083   //
14084   // And:
14085   //   * CN is a single bit;
14086   //   * All bits covered by CM are known zero in y
14087   //
14088   // Then we can convert this into a sequence of BFI instructions. This will
14089   // always be a win if CM is a single bit, will always be no worse than the
14090   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
14091   // three bits (due to the extra IT instruction).
14092
14093   SDValue Op0 = CMOV->getOperand(0);
14094   SDValue Op1 = CMOV->getOperand(1);
14095   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
14096   auto CC = CCNode->getAPIntValue().getLimitedValue();
14097   SDValue CmpZ = CMOV->getOperand(4);
14098
14099   // The compare must be against zero.
14100   if (!isNullConstant(CmpZ->getOperand(1)))
14101     return SDValue();
14102
14103   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
14104   SDValue And = CmpZ->getOperand(0);
14105   if (And->getOpcode() != ISD::AND)
14106     return SDValue();
14107   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
14108   if (!AndC)
14109     return SDValue();
14110   SDValue X = And->getOperand(0);
14111
14112   if (CC == ARMCC::EQ) {
14113     // We're performing an "equal to zero" compare. Swap the operands so we
14114     // canonicalize on a "not equal to zero" compare.
14115     std::swap(Op0, Op1);
14116   } else {
14117     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
14118   }
14119
14120   if (Op1->getOpcode() != ISD::OR)
14121     return SDValue();
14122
14123   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
14124   if (!OrC)
14125     return SDValue();
14126   SDValue Y = Op1->getOperand(0);
14127
14128   if (Op0 != Y)
14129     return SDValue();
14130
14131   // Now, is it profitable to continue?
14132   APInt OrCI = OrC->getAPIntValue();
14133   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
14134   if (OrCI.countPopulation() > Heuristic)
14135     return SDValue();
14136
14137   // Lastly, can we determine that the bits defined by OrCI
14138   // are zero in Y?
14139   KnownBits Known = DAG.computeKnownBits(Y);
14140   if ((OrCI & Known.Zero) != OrCI)
14141     return SDValue();
14142
14143   // OK, we can do the combine.
14144   SDValue V = Y;
14145   SDLoc dl(X);
14146   EVT VT = X.getValueType();
14147   unsigned BitInX = AndC->logBase2();
14148
14149   if (BitInX != 0) {
14150     // We must shift X first.
14151     X = DAG.getNode(ISD::SRL, dl, VT, X,
14152                     DAG.getConstant(BitInX, dl, VT));
14153   }
14154
14155   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
14156        BitInY < NumActiveBits; ++BitInY) {
14157     if (OrCI[BitInY] == 0)
14158       continue;
14159     APInt Mask(VT.getSizeInBits(), 0);
14160     Mask.setBit(BitInY);
14161     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
14162                     // Confusingly, the operand is an *inverted* mask.
14163                     DAG.getConstant(~Mask, dl, VT));
14164   }
14165
14166   return V;
14167 }
14168
14169 // Given N, the value controlling the conditional branch, search for the loop
14170 // intrinsic, returning it, along with how the value is used. We need to handle
14171 // patterns such as the following:
14172 // (brcond (xor (setcc (loop.decrement), 0, ne), 1), exit)
14173 // (brcond (setcc (loop.decrement), 0, eq), exit)
14174 // (brcond (setcc (loop.decrement), 0, ne), header)
14175 static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
14176                                    bool &Negate) {
14177   switch (N->getOpcode()) {
14178   default:
14179     break;
14180   case ISD::XOR: {
14181     if (!isa<ConstantSDNode>(N.getOperand(1)))
14182       return SDValue();
14183     if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
14184       return SDValue();
14185     Negate = !Negate;
14186     return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
14187   }
14188   case ISD::SETCC: {
14189     auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
14190     if (!Const)
14191       return SDValue();
14192     if (Const->isNullValue())
14193       Imm = 0;
14194     else if (Const->isOne())
14195       Imm = 1;
14196     else
14197       return SDValue();
14198     CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
14199     return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
14200   }
14201   case ISD::INTRINSIC_W_CHAIN: {
14202     unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
14203     if (IntOp != Intrinsic::test_set_loop_iterations &&
14204         IntOp != Intrinsic::loop_decrement_reg)
14205       return SDValue();
14206     return N;
14207   }
14208   }
14209   return SDValue();
14210 }
14211
14212 static SDValue PerformHWLoopCombine(SDNode *N,
14213                                     TargetLowering::DAGCombinerInfo &DCI,
14214                                     const ARMSubtarget *ST) {
14215
14216   // The hwloop intrinsics that we're interested are used for control-flow,
14217   // either for entering or exiting the loop:
14218   // - test.set.loop.iterations will test whether its operand is zero. If it
14219   //   is zero, the proceeding branch should not enter the loop.
14220   // - loop.decrement.reg also tests whether its operand is zero. If it is
14221   //   zero, the proceeding branch should not branch back to the beginning of
14222   //   the loop.
14223   // So here, we need to check that how the brcond is using the result of each
14224   // of the intrinsics to ensure that we're branching to the right place at the
14225   // right time.
14226
14227   ISD::CondCode CC;
14228   SDValue Cond;
14229   int Imm = 1;
14230   bool Negate = false;
14231   SDValue Chain = N->getOperand(0);
14232   SDValue Dest;
14233
14234   if (N->getOpcode() == ISD::BRCOND) {
14235     CC = ISD::SETEQ;
14236     Cond = N->getOperand(1);
14237     Dest = N->getOperand(2);
14238   } else {
14239     assert(N->getOpcode() == ISD::BR_CC && "Expected BRCOND or BR_CC!");
14240     CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14241     Cond = N->getOperand(2);
14242     Dest = N->getOperand(4);
14243     if (auto *Const = dyn_cast<ConstantSDNode>(N->getOperand(3))) {
14244       if (!Const->isOne() && !Const->isNullValue())
14245         return SDValue();
14246       Imm = Const->getZExtValue();
14247     } else
14248       return SDValue();
14249   }
14250
14251   SDValue Int = SearchLoopIntrinsic(Cond, CC, Imm, Negate);
14252   if (!Int)
14253     return SDValue();
14254
14255   if (Negate)
14256     CC = ISD::getSetCCInverse(CC, /* Integer inverse */ MVT::i32);
14257
14258   auto IsTrueIfZero = [](ISD::CondCode CC, int Imm) {
14259     return (CC == ISD::SETEQ && Imm == 0) ||
14260            (CC == ISD::SETNE && Imm == 1) ||
14261            (CC == ISD::SETLT && Imm == 1) ||
14262            (CC == ISD::SETULT && Imm == 1);
14263   };
14264
14265   auto IsFalseIfZero = [](ISD::CondCode CC, int Imm) {
14266     return (CC == ISD::SETEQ && Imm == 1) ||
14267            (CC == ISD::SETNE && Imm == 0) ||
14268            (CC == ISD::SETGT && Imm == 0) ||
14269            (CC == ISD::SETUGT && Imm == 0) ||
14270            (CC == ISD::SETGE && Imm == 1) ||
14271            (CC == ISD::SETUGE && Imm == 1);
14272   };
14273
14274   assert((IsTrueIfZero(CC, Imm) || IsFalseIfZero(CC, Imm)) &&
14275          "unsupported condition");
14276
14277   SDLoc dl(Int);
14278   SelectionDAG &DAG = DCI.DAG;
14279   SDValue Elements = Int.getOperand(2);
14280   unsigned IntOp = cast<ConstantSDNode>(Int->getOperand(1))->getZExtValue();
14281   assert((N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BR)
14282           && "expected single br user");
14283   SDNode *Br = *N->use_begin();
14284   SDValue OtherTarget = Br->getOperand(1);
14285
14286   // Update the unconditional branch to branch to the given Dest.
14287   auto UpdateUncondBr = [](SDNode *Br, SDValue Dest, SelectionDAG &DAG) {
14288     SDValue NewBrOps[] = { Br->getOperand(0), Dest };
14289     SDValue NewBr = DAG.getNode(ISD::BR, SDLoc(Br), MVT::Other, NewBrOps);
14290     DAG.ReplaceAllUsesOfValueWith(SDValue(Br, 0), NewBr);
14291   };
14292
14293   if (IntOp == Intrinsic::test_set_loop_iterations) {
14294     SDValue Res;
14295     // We expect this 'instruction' to branch when the counter is zero.
14296     if (IsTrueIfZero(CC, Imm)) {
14297       SDValue Ops[] = { Chain, Elements, Dest };
14298       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
14299     } else {
14300       // The logic is the reverse of what we need for WLS, so find the other
14301       // basic block target: the target of the proceeding br.
14302       UpdateUncondBr(Br, Dest, DAG);
14303
14304       SDValue Ops[] = { Chain, Elements, OtherTarget };
14305       Res = DAG.getNode(ARMISD::WLS, dl, MVT::Other, Ops);
14306     }
14307     DAG.ReplaceAllUsesOfValueWith(Int.getValue(1), Int.getOperand(0));
14308     return Res;
14309   } else {
14310     SDValue Size = DAG.getTargetConstant(
14311       cast<ConstantSDNode>(Int.getOperand(3))->getZExtValue(), dl, MVT::i32);
14312     SDValue Args[] = { Int.getOperand(0), Elements, Size, };
14313     SDValue LoopDec = DAG.getNode(ARMISD::LOOP_DEC, dl,
14314                                   DAG.getVTList(MVT::i32, MVT::Other), Args);
14315     DAG.ReplaceAllUsesWith(Int.getNode(), LoopDec.getNode());
14316
14317     // We expect this instruction to branch when the count is not zero.
14318     SDValue Target = IsFalseIfZero(CC, Imm) ? Dest : OtherTarget;
14319
14320     // Update the unconditional branch to target the loop preheader if we've
14321     // found the condition has been reversed.
14322     if (Target == OtherTarget)
14323       UpdateUncondBr(Br, Dest, DAG);
14324
14325     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14326                         SDValue(LoopDec.getNode(), 1), Chain);
14327
14328     SDValue EndArgs[] = { Chain, SDValue(LoopDec.getNode(), 0), Target };
14329     return DAG.getNode(ARMISD::LE, dl, MVT::Other, EndArgs);
14330   }
14331   return SDValue();
14332 }
14333
14334 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
14335 SDValue
14336 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
14337   SDValue Cmp = N->getOperand(4);
14338   if (Cmp.getOpcode() != ARMISD::CMPZ)
14339     // Only looking at NE cases.
14340     return SDValue();
14341
14342   EVT VT = N->getValueType(0);
14343   SDLoc dl(N);
14344   SDValue LHS = Cmp.getOperand(0);
14345   SDValue RHS = Cmp.getOperand(1);
14346   SDValue Chain = N->getOperand(0);
14347   SDValue BB = N->getOperand(1);
14348   SDValue ARMcc = N->getOperand(2);
14349   ARMCC::CondCodes CC =
14350     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
14351
14352   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
14353   // -> (brcond Chain BB CC CPSR Cmp)
14354   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
14355       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
14356       LHS->getOperand(0)->hasOneUse()) {
14357     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
14358     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
14359     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
14360     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
14361     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
14362         (LHS01C && LHS01C->getZExtValue() == 1) &&
14363         (LHS1C && LHS1C->getZExtValue() == 1) &&
14364         (RHSC && RHSC->getZExtValue() == 0)) {
14365       return DAG.getNode(
14366           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
14367           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
14368     }
14369   }
14370
14371   return SDValue();
14372 }
14373
14374 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
14375 SDValue
14376 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
14377   SDValue Cmp = N->getOperand(4);
14378   if (Cmp.getOpcode() != ARMISD::CMPZ)
14379     // Only looking at EQ and NE cases.
14380     return SDValue();
14381
14382   EVT VT = N->getValueType(0);
14383   SDLoc dl(N);
14384   SDValue LHS = Cmp.getOperand(0);
14385   SDValue RHS = Cmp.getOperand(1);
14386   SDValue FalseVal = N->getOperand(0);
14387   SDValue TrueVal = N->getOperand(1);
14388   SDValue ARMcc = N->getOperand(2);
14389   ARMCC::CondCodes CC =
14390     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
14391
14392   // BFI is only available on V6T2+.
14393   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
14394     SDValue R = PerformCMOVToBFICombine(N, DAG);
14395     if (R)
14396       return R;
14397   }
14398
14399   // Simplify
14400   //   mov     r1, r0
14401   //   cmp     r1, x
14402   //   mov     r0, y
14403   //   moveq   r0, x
14404   // to
14405   //   cmp     r0, x
14406   //   movne   r0, y
14407   //
14408   //   mov     r1, r0
14409   //   cmp     r1, x
14410   //   mov     r0, x
14411   //   movne   r0, y
14412   // to
14413   //   cmp     r0, x
14414   //   movne   r0, y
14415   /// FIXME: Turn this into a target neutral optimization?
14416   SDValue Res;
14417   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
14418     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
14419                       N->getOperand(3), Cmp);
14420   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
14421     SDValue ARMcc;
14422     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
14423     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
14424                       N->getOperand(3), NewCmp);
14425   }
14426
14427   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
14428   // -> (cmov F T CC CPSR Cmp)
14429   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
14430     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
14431     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
14432     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
14433     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
14434         (LHS1C && LHS1C->getZExtValue() == 1) &&
14435         (RHSC && RHSC->getZExtValue() == 0)) {
14436       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
14437                          LHS->getOperand(2), LHS->getOperand(3),
14438                          LHS->getOperand(4));
14439     }
14440   }
14441
14442   if (!VT.isInteger())
14443       return SDValue();
14444
14445   // Materialize a boolean comparison for integers so we can avoid branching.
14446   if (isNullConstant(FalseVal)) {
14447     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
14448       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
14449         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
14450         // right 5 bits will make that 32 be 1, otherwise it will be 0.
14451         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
14452         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
14453         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
14454                           DAG.getConstant(5, dl, MVT::i32));
14455       } else {
14456         // CMOV 0, 1, ==, (CMPZ x, y) ->
14457         //     (ADDCARRY (SUB x, y), t:0, t:1)
14458         // where t = (SUBCARRY 0, (SUB x, y), 0)
14459         //
14460         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
14461         // x != y. In other words, a carry C == 1 when x == y, C == 0
14462         // otherwise.
14463         // The final ADDCARRY computes
14464         //     x - y + (0 - (x - y)) + C == C
14465         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
14466         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14467         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
14468         // ISD::SUBCARRY returns a borrow but we want the carry here
14469         // actually.
14470         SDValue Carry =
14471             DAG.getNode(ISD::SUB, dl, MVT::i32,
14472                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
14473         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
14474       }
14475     } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
14476                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
14477       // This seems pointless but will allow us to combine it further below.
14478       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
14479       SDValue Sub =
14480           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
14481       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
14482                                           Sub.getValue(1), SDValue());
14483       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
14484                         N->getOperand(3), CPSRGlue.getValue(1));
14485       FalseVal = Sub;
14486     }
14487   } else if (isNullConstant(TrueVal)) {
14488     if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
14489         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
14490       // This seems pointless but will allow us to combine it further below
14491       // Note that we change == for != as this is the dual for the case above.
14492       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
14493       SDValue Sub =
14494           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
14495       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
14496                                           Sub.getValue(1), SDValue());
14497       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
14498                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
14499                         N->getOperand(3), CPSRGlue.getValue(1));
14500       FalseVal = Sub;
14501     }
14502   }
14503
14504   // On Thumb1, the DAG above may be further combined if z is a power of 2
14505   // (z == 2 ^ K).
14506   // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
14507   // t1 = (USUBO (SUB x, y), 1)
14508   // t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
14509   // Result = if K != 0 then (SHL t2:0, K) else t2:0
14510   //
14511   // This also handles the special case of comparing against zero; it's
14512   // essentially, the same pattern, except there's no SUBS:
14513   // CMOV x, z, !=, (CMPZ x, 0) ->
14514   // t1 = (USUBO x, 1)
14515   // t2 = (SUBCARRY x, t1:0, t1:1)
14516   // Result = if K != 0 then (SHL t2:0, K) else t2:0
14517   const APInt *TrueConst;
14518   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
14519       ((FalseVal.getOpcode() == ARMISD::SUBS &&
14520         FalseVal.getOperand(0) == LHS && FalseVal.getOperand(1) == RHS) ||
14521        (FalseVal == LHS && isNullConstant(RHS))) &&
14522       (TrueConst = isPowerOf2Constant(TrueVal))) {
14523     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14524     unsigned ShiftAmount = TrueConst->logBase2();
14525     if (ShiftAmount)
14526       TrueVal = DAG.getConstant(1, dl, VT);
14527     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
14528     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
14529
14530     if (ShiftAmount)
14531       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
14532                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
14533   }
14534
14535   if (Res.getNode()) {
14536     KnownBits Known = DAG.computeKnownBits(SDValue(N,0));
14537     // Capture demanded bits information that would be otherwise lost.
14538     if (Known.Zero == 0xfffffffe)
14539       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14540                         DAG.getValueType(MVT::i1));
14541     else if (Known.Zero == 0xffffff00)
14542       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14543                         DAG.getValueType(MVT::i8));
14544     else if (Known.Zero == 0xffff0000)
14545       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
14546                         DAG.getValueType(MVT::i16));
14547   }
14548
14549   return Res;
14550 }
14551
14552 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
14553                                              DAGCombinerInfo &DCI) const {
14554   switch (N->getOpcode()) {
14555   default: break;
14556   case ISD::ABS:        return PerformABSCombine(N, DCI, Subtarget);
14557   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
14558   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
14559   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
14560   case ISD::SUB:        return PerformSUBCombine(N, DCI, Subtarget);
14561   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
14562   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
14563   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
14564   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
14565   case ISD::BRCOND:
14566   case ISD::BR_CC:      return PerformHWLoopCombine(N, DCI, Subtarget);
14567   case ARMISD::ADDC:
14568   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
14569   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
14570   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
14571   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
14572   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
14573   case ISD::STORE:      return PerformSTORECombine(N, DCI, Subtarget);
14574   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
14575   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
14576   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
14577   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
14578   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI, Subtarget);
14579   case ISD::FP_TO_SINT:
14580   case ISD::FP_TO_UINT:
14581     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
14582   case ISD::FDIV:
14583     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
14584   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
14585   case ISD::SHL:
14586   case ISD::SRA:
14587   case ISD::SRL:
14588     return PerformShiftCombine(N, DCI, Subtarget);
14589   case ISD::SIGN_EXTEND:
14590   case ISD::ZERO_EXTEND:
14591   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
14592   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
14593   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
14594   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
14595   case ARMISD::VLD1DUP:
14596   case ARMISD::VLD2DUP:
14597   case ARMISD::VLD3DUP:
14598   case ARMISD::VLD4DUP:
14599     return PerformVLDCombine(N, DCI);
14600   case ARMISD::BUILD_VECTOR:
14601     return PerformARMBUILD_VECTORCombine(N, DCI);
14602   case ARMISD::PREDICATE_CAST:
14603     return PerformPREDICATE_CASTCombine(N, DCI);
14604   case ARMISD::VCMP:
14605     return PerformVCMPCombine(N, DCI, Subtarget);
14606   case ARMISD::SMULWB: {
14607     unsigned BitWidth = N->getValueType(0).getSizeInBits();
14608     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14609     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14610       return SDValue();
14611     break;
14612   }
14613   case ARMISD::SMULWT: {
14614     unsigned BitWidth = N->getValueType(0).getSizeInBits();
14615     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14616     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
14617       return SDValue();
14618     break;
14619   }
14620   case ARMISD::SMLALBB:
14621   case ARMISD::QADD16b:
14622   case ARMISD::QSUB16b: {
14623     unsigned BitWidth = N->getValueType(0).getSizeInBits();
14624     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
14625     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14626         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14627       return SDValue();
14628     break;
14629   }
14630   case ARMISD::SMLALBT: {
14631     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
14632     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14633     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
14634     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14635     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
14636         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
14637       return SDValue();
14638     break;
14639   }
14640   case ARMISD::SMLALTB: {
14641     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
14642     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
14643     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
14644     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
14645     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
14646         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
14647       return SDValue();
14648     break;
14649   }
14650   case ARMISD::SMLALTT: {
14651     unsigned BitWidth = N->getValueType(0).getSizeInBits();
14652     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
14653     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14654         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14655       return SDValue();
14656     break;
14657   }
14658   case ARMISD::QADD8b:
14659   case ARMISD::QSUB8b: {
14660     unsigned BitWidth = N->getValueType(0).getSizeInBits();
14661     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 8);
14662     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
14663         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
14664       return SDValue();
14665     break;
14666   }
14667   case ISD::INTRINSIC_VOID:
14668   case ISD::INTRINSIC_W_CHAIN:
14669     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14670     case Intrinsic::arm_neon_vld1:
14671     case Intrinsic::arm_neon_vld1x2:
14672     case Intrinsic::arm_neon_vld1x3:
14673     case Intrinsic::arm_neon_vld1x4:
14674     case Intrinsic::arm_neon_vld2:
14675     case Intrinsic::arm_neon_vld3:
14676     case Intrinsic::arm_neon_vld4:
14677     case Intrinsic::arm_neon_vld2lane:
14678     case Intrinsic::arm_neon_vld3lane:
14679     case Intrinsic::arm_neon_vld4lane:
14680     case Intrinsic::arm_neon_vld2dup:
14681     case Intrinsic::arm_neon_vld3dup:
14682     case Intrinsic::arm_neon_vld4dup:
14683     case Intrinsic::arm_neon_vst1:
14684     case Intrinsic::arm_neon_vst1x2:
14685     case Intrinsic::arm_neon_vst1x3:
14686     case Intrinsic::arm_neon_vst1x4:
14687     case Intrinsic::arm_neon_vst2:
14688     case Intrinsic::arm_neon_vst3:
14689     case Intrinsic::arm_neon_vst4:
14690     case Intrinsic::arm_neon_vst2lane:
14691     case Intrinsic::arm_neon_vst3lane:
14692     case Intrinsic::arm_neon_vst4lane:
14693       return PerformVLDCombine(N, DCI);
14694     default: break;
14695     }
14696     break;
14697   }
14698   return SDValue();
14699 }
14700
14701 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
14702                                                           EVT VT) const {
14703   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
14704 }
14705
14706 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT, unsigned,
14707                                                        unsigned Alignment,
14708                                                        MachineMemOperand::Flags,
14709                                                        bool *Fast) const {
14710   // Depends what it gets converted into if the type is weird.
14711   if (!VT.isSimple())
14712     return false;
14713
14714   // The AllowsUnaligned flag models the SCTLR.A setting in ARM cpus
14715   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
14716   auto Ty = VT.getSimpleVT().SimpleTy;
14717
14718   if (Ty == MVT::i8 || Ty == MVT::i16 || Ty == MVT::i32) {
14719     // Unaligned access can use (for example) LRDB, LRDH, LDR
14720     if (AllowsUnaligned) {
14721       if (Fast)
14722         *Fast = Subtarget->hasV7Ops();
14723       return true;
14724     }
14725   }
14726
14727   if (Ty == MVT::f64 || Ty == MVT::v2f64) {
14728     // For any little-endian targets with neon, we can support unaligned ld/st
14729     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
14730     // A big-endian target may also explicitly support unaligned accesses
14731     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
14732       if (Fast)
14733         *Fast = true;
14734       return true;
14735     }
14736   }
14737
14738   if (!Subtarget->hasMVEIntegerOps())
14739     return false;
14740
14741   // These are for predicates
14742   if ((Ty == MVT::v16i1 || Ty == MVT::v8i1 || Ty == MVT::v4i1)) {
14743     if (Fast)
14744       *Fast = true;
14745     return true;
14746   }
14747
14748   // These are for truncated stores/narrowing loads. They are fine so long as
14749   // the alignment is at least the size of the item being loaded
14750   if ((Ty == MVT::v4i8 || Ty == MVT::v8i8 || Ty == MVT::v4i16) &&
14751       Alignment >= VT.getScalarSizeInBits() / 8) {
14752     if (Fast)
14753       *Fast = true;
14754     return true;
14755   }
14756
14757   // In little-endian MVE, the store instructions VSTRB.U8, VSTRH.U16 and
14758   // VSTRW.U32 all store the vector register in exactly the same format, and
14759   // differ only in the range of their immediate offset field and the required
14760   // alignment. So there is always a store that can be used, regardless of
14761   // actual type.
14762   //
14763   // For big endian, that is not the case. But can still emit a (VSTRB.U8;
14764   // VREV64.8) pair and get the same effect. This will likely be better than
14765   // aligning the vector through the stack.
14766   if (Ty == MVT::v16i8 || Ty == MVT::v8i16 || Ty == MVT::v8f16 ||
14767       Ty == MVT::v4i32 || Ty == MVT::v4f32 || Ty == MVT::v2i64 ||
14768       Ty == MVT::v2f64) {
14769     if (Fast)
14770       *Fast = true;
14771     return true;
14772   }
14773
14774   return false;
14775 }
14776
14777 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
14778                        unsigned AlignCheck) {
14779   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
14780           (DstAlign == 0 || DstAlign % AlignCheck == 0));
14781 }
14782
14783 EVT ARMTargetLowering::getOptimalMemOpType(
14784     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
14785     bool ZeroMemset, bool MemcpyStrSrc,
14786     const AttributeList &FuncAttributes) const {
14787   // See if we can use NEON instructions for this...
14788   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
14789       !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
14790     bool Fast;
14791     if (Size >= 16 &&
14792         (memOpAlign(SrcAlign, DstAlign, 16) ||
14793          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1,
14794                                          MachineMemOperand::MONone, &Fast) &&
14795           Fast))) {
14796       return MVT::v2f64;
14797     } else if (Size >= 8 &&
14798                (memOpAlign(SrcAlign, DstAlign, 8) ||
14799                 (allowsMisalignedMemoryAccesses(
14800                      MVT::f64, 0, 1, MachineMemOperand::MONone, &Fast) &&
14801                  Fast))) {
14802       return MVT::f64;
14803     }
14804   }
14805
14806   // Let the target-independent logic figure it out.
14807   return MVT::Other;
14808 }
14809
14810 // 64-bit integers are split into their high and low parts and held in two
14811 // different registers, so the trunc is free since the low register can just
14812 // be used.
14813 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
14814   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
14815     return false;
14816   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
14817   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
14818   return (SrcBits == 64 && DestBits == 32);
14819 }
14820
14821 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
14822   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
14823       !DstVT.isInteger())
14824     return false;
14825   unsigned SrcBits = SrcVT.getSizeInBits();
14826   unsigned DestBits = DstVT.getSizeInBits();
14827   return (SrcBits == 64 && DestBits == 32);
14828 }
14829
14830 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
14831   if (Val.getOpcode() != ISD::LOAD)
14832     return false;
14833
14834   EVT VT1 = Val.getValueType();
14835   if (!VT1.isSimple() || !VT1.isInteger() ||
14836       !VT2.isSimple() || !VT2.isInteger())
14837     return false;
14838
14839   switch (VT1.getSimpleVT().SimpleTy) {
14840   default: break;
14841   case MVT::i1:
14842   case MVT::i8:
14843   case MVT::i16:
14844     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
14845     return true;
14846   }
14847
14848   return false;
14849 }
14850
14851 bool ARMTargetLowering::isFNegFree(EVT VT) const {
14852   if (!VT.isSimple())
14853     return false;
14854
14855   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
14856   // negate values directly (fneg is free). So, we don't want to let the DAG
14857   // combiner rewrite fneg into xors and some other instructions.  For f16 and
14858   // FullFP16 argument passing, some bitcast nodes may be introduced,
14859   // triggering this DAG combine rewrite, so we are avoiding that with this.
14860   switch (VT.getSimpleVT().SimpleTy) {
14861   default: break;
14862   case MVT::f16:
14863     return Subtarget->hasFullFP16();
14864   }
14865
14866   return false;
14867 }
14868
14869 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
14870 /// of the vector elements.
14871 static bool areExtractExts(Value *Ext1, Value *Ext2) {
14872   auto areExtDoubled = [](Instruction *Ext) {
14873     return Ext->getType()->getScalarSizeInBits() ==
14874            2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
14875   };
14876
14877   if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
14878       !match(Ext2, m_ZExtOrSExt(m_Value())) ||
14879       !areExtDoubled(cast<Instruction>(Ext1)) ||
14880       !areExtDoubled(cast<Instruction>(Ext2)))
14881     return false;
14882
14883   return true;
14884 }
14885
14886 /// Check if sinking \p I's operands to I's basic block is profitable, because
14887 /// the operands can be folded into a target instruction, e.g.
14888 /// sext/zext can be folded into vsubl.
14889 bool ARMTargetLowering::shouldSinkOperands(Instruction *I,
14890                                            SmallVectorImpl<Use *> &Ops) const {
14891   if (!I->getType()->isVectorTy())
14892     return false;
14893
14894   if (Subtarget->hasNEON()) {
14895     switch (I->getOpcode()) {
14896     case Instruction::Sub:
14897     case Instruction::Add: {
14898       if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
14899         return false;
14900       Ops.push_back(&I->getOperandUse(0));
14901       Ops.push_back(&I->getOperandUse(1));
14902       return true;
14903     }
14904     default:
14905       return false;
14906     }
14907   }
14908
14909   if (!Subtarget->hasMVEIntegerOps())
14910     return false;
14911
14912   auto IsSinker = [](Instruction *I, int Operand) {
14913     switch (I->getOpcode()) {
14914     case Instruction::Add:
14915     case Instruction::Mul:
14916     case Instruction::ICmp:
14917       return true;
14918     case Instruction::Sub:
14919     case Instruction::Shl:
14920     case Instruction::LShr:
14921     case Instruction::AShr:
14922       return Operand == 1;
14923     default:
14924       return false;
14925     }
14926   };
14927
14928   int Op = 0;
14929   if (!isa<ShuffleVectorInst>(I->getOperand(Op)))
14930     Op = 1;
14931   if (!IsSinker(I, Op))
14932     return false;
14933   if (!match(I->getOperand(Op),
14934              m_ShuffleVector(m_InsertElement(m_Undef(), m_Value(), m_ZeroInt()),
14935                              m_Undef(), m_Zero()))) {
14936     return false;
14937   }
14938   Instruction *Shuffle = cast<Instruction>(I->getOperand(Op));
14939   // All uses of the shuffle should be sunk to avoid duplicating it across gpr
14940   // and vector registers
14941   for (Use &U : Shuffle->uses()) {
14942     Instruction *Insn = cast<Instruction>(U.getUser());
14943     if (!IsSinker(Insn, U.getOperandNo()))
14944       return false;
14945   }
14946   Ops.push_back(&Shuffle->getOperandUse(0));
14947   Ops.push_back(&I->getOperandUse(Op));
14948   return true;
14949 }
14950
14951 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
14952   EVT VT = ExtVal.getValueType();
14953
14954   if (!isTypeLegal(VT))
14955     return false;
14956
14957   if (auto *Ld = dyn_cast<MaskedLoadSDNode>(ExtVal.getOperand(0))) {
14958     if (Ld->isExpandingLoad())
14959       return false;
14960   }
14961
14962   // Don't create a loadext if we can fold the extension into a wide/long
14963   // instruction.
14964   // If there's more than one user instruction, the loadext is desirable no
14965   // matter what.  There can be two uses by the same instruction.
14966   if (ExtVal->use_empty() ||
14967       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
14968     return true;
14969
14970   SDNode *U = *ExtVal->use_begin();
14971   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
14972        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHLIMM))
14973     return false;
14974
14975   return true;
14976 }
14977
14978 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
14979   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
14980     return false;
14981
14982   if (!isTypeLegal(EVT::getEVT(Ty1)))
14983     return false;
14984
14985   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
14986
14987   // Assuming the caller doesn't have a zeroext or signext return parameter,
14988   // truncation all the way down to i1 is valid.
14989   return true;
14990 }
14991
14992 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
14993                                                 const AddrMode &AM, Type *Ty,
14994                                                 unsigned AS) const {
14995   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
14996     if (Subtarget->hasFPAO())
14997       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
14998     return 0;
14999   }
15000   return -1;
15001 }
15002
15003 /// isFMAFasterThanFMulAndFAdd - Return true if an FMA operation is faster
15004 /// than a pair of fmul and fadd instructions. fmuladd intrinsics will be
15005 /// expanded to FMAs when this method returns true, otherwise fmuladd is
15006 /// expanded to fmul + fadd.
15007 ///
15008 /// ARM supports both fused and unfused multiply-add operations; we already
15009 /// lower a pair of fmul and fadd to the latter so it's not clear that there
15010 /// would be a gain or that the gain would be worthwhile enough to risk
15011 /// correctness bugs.
15012 ///
15013 /// For MVE, we set this to true as it helps simplify the need for some
15014 /// patterns (and we don't have the non-fused floating point instruction).
15015 bool ARMTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15016                                                    EVT VT) const {
15017   if (!VT.isSimple())
15018     return false;
15019
15020   switch (VT.getSimpleVT().SimpleTy) {
15021   case MVT::v4f32:
15022   case MVT::v8f16:
15023     return Subtarget->hasMVEFloatOps();
15024   case MVT::f16:
15025     return Subtarget->useFPVFMx16();
15026   case MVT::f32:
15027     return Subtarget->useFPVFMx();
15028   case MVT::f64:
15029     return Subtarget->useFPVFMx64();
15030   default:
15031     break;
15032   }
15033
15034   return false;
15035 }
15036
15037 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
15038   if (V < 0)
15039     return false;
15040
15041   unsigned Scale = 1;
15042   switch (VT.getSimpleVT().SimpleTy) {
15043   case MVT::i1:
15044   case MVT::i8:
15045     // Scale == 1;
15046     break;
15047   case MVT::i16:
15048     // Scale == 2;
15049     Scale = 2;
15050     break;
15051   default:
15052     // On thumb1 we load most things (i32, i64, floats, etc) with a LDR
15053     // Scale == 4;
15054     Scale = 4;
15055     break;
15056   }
15057
15058   if ((V & (Scale - 1)) != 0)
15059     return false;
15060   return isUInt<5>(V / Scale);
15061 }
15062
15063 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
15064                                       const ARMSubtarget *Subtarget) {
15065   if (!VT.isInteger() && !VT.isFloatingPoint())
15066     return false;
15067   if (VT.isVector() && Subtarget->hasNEON())
15068     return false;
15069   if (VT.isVector() && VT.isFloatingPoint() && Subtarget->hasMVEIntegerOps() &&
15070       !Subtarget->hasMVEFloatOps())
15071     return false;
15072
15073   bool IsNeg = false;
15074   if (V < 0) {
15075     IsNeg = true;
15076     V = -V;
15077   }
15078
15079   unsigned NumBytes = std::max((unsigned)VT.getSizeInBits() / 8, 1U);
15080
15081   // MVE: size * imm7
15082   if (VT.isVector() && Subtarget->hasMVEIntegerOps()) {
15083     switch (VT.getSimpleVT().getVectorElementType().SimpleTy) {
15084     case MVT::i32:
15085     case MVT::f32:
15086       return isShiftedUInt<7,2>(V);
15087     case MVT::i16:
15088     case MVT::f16:
15089       return isShiftedUInt<7,1>(V);
15090     case MVT::i8:
15091       return isUInt<7>(V);
15092     default:
15093       return false;
15094     }
15095   }
15096
15097   // half VLDR: 2 * imm8
15098   if (VT.isFloatingPoint() && NumBytes == 2 && Subtarget->hasFPRegs16())
15099     return isShiftedUInt<8, 1>(V);
15100   // VLDR and LDRD: 4 * imm8
15101   if ((VT.isFloatingPoint() && Subtarget->hasVFP2Base()) || NumBytes == 8)
15102     return isShiftedUInt<8, 2>(V);
15103
15104   if (NumBytes == 1 || NumBytes == 2 || NumBytes == 4) {
15105     // + imm12 or - imm8
15106     if (IsNeg)
15107       return isUInt<8>(V);
15108     return isUInt<12>(V);
15109   }
15110
15111   return false;
15112 }
15113
15114 /// isLegalAddressImmediate - Return true if the integer value can be used
15115 /// as the offset of the target addressing mode for load / store of the
15116 /// given type.
15117 static bool isLegalAddressImmediate(int64_t V, EVT VT,
15118                                     const ARMSubtarget *Subtarget) {
15119   if (V == 0)
15120     return true;
15121
15122   if (!VT.isSimple())
15123     return false;
15124
15125   if (Subtarget->isThumb1Only())
15126     return isLegalT1AddressImmediate(V, VT);
15127   else if (Subtarget->isThumb2())
15128     return isLegalT2AddressImmediate(V, VT, Subtarget);
15129
15130   // ARM mode.
15131   if (V < 0)
15132     V = - V;
15133   switch (VT.getSimpleVT().SimpleTy) {
15134   default: return false;
15135   case MVT::i1:
15136   case MVT::i8:
15137   case MVT::i32:
15138     // +- imm12
15139     return isUInt<12>(V);
15140   case MVT::i16:
15141     // +- imm8
15142     return isUInt<8>(V);
15143   case MVT::f32:
15144   case MVT::f64:
15145     if (!Subtarget->hasVFP2Base()) // FIXME: NEON?
15146       return false;
15147     return isShiftedUInt<8, 2>(V);
15148   }
15149 }
15150
15151 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
15152                                                       EVT VT) const {
15153   int Scale = AM.Scale;
15154   if (Scale < 0)
15155     return false;
15156
15157   switch (VT.getSimpleVT().SimpleTy) {
15158   default: return false;
15159   case MVT::i1:
15160   case MVT::i8:
15161   case MVT::i16:
15162   case MVT::i32:
15163     if (Scale == 1)
15164       return true;
15165     // r + r << imm
15166     Scale = Scale & ~1;
15167     return Scale == 2 || Scale == 4 || Scale == 8;
15168   case MVT::i64:
15169     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
15170     // version in Thumb mode.
15171     // r + r
15172     if (Scale == 1)
15173       return true;
15174     // r * 2 (this can be lowered to r + r).
15175     if (!AM.HasBaseReg && Scale == 2)
15176       return true;
15177     return false;
15178   case MVT::isVoid:
15179     // Note, we allow "void" uses (basically, uses that aren't loads or
15180     // stores), because arm allows folding a scale into many arithmetic
15181     // operations.  This should be made more precise and revisited later.
15182
15183     // Allow r << imm, but the imm has to be a multiple of two.
15184     if (Scale & 1) return false;
15185     return isPowerOf2_32(Scale);
15186   }
15187 }
15188
15189 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
15190                                                       EVT VT) const {
15191   const int Scale = AM.Scale;
15192
15193   // Negative scales are not supported in Thumb1.
15194   if (Scale < 0)
15195     return false;
15196
15197   // Thumb1 addressing modes do not support register scaling excepting the
15198   // following cases:
15199   // 1. Scale == 1 means no scaling.
15200   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
15201   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
15202 }
15203
15204 /// isLegalAddressingMode - Return true if the addressing mode represented
15205 /// by AM is legal for this target, for a load/store of the specified type.
15206 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15207                                               const AddrMode &AM, Type *Ty,
15208                                               unsigned AS, Instruction *I) const {
15209   EVT VT = getValueType(DL, Ty, true);
15210   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
15211     return false;
15212
15213   // Can never fold addr of global into load/store.
15214   if (AM.BaseGV)
15215     return false;
15216
15217   switch (AM.Scale) {
15218   case 0:  // no scale reg, must be "r+i" or "r", or "i".
15219     break;
15220   default:
15221     // ARM doesn't support any R+R*scale+imm addr modes.
15222     if (AM.BaseOffs)
15223       return false;
15224
15225     if (!VT.isSimple())
15226       return false;
15227
15228     if (Subtarget->isThumb1Only())
15229       return isLegalT1ScaledAddressingMode(AM, VT);
15230
15231     if (Subtarget->isThumb2())
15232       return isLegalT2ScaledAddressingMode(AM, VT);
15233
15234     int Scale = AM.Scale;
15235     switch (VT.getSimpleVT().SimpleTy) {
15236     default: return false;
15237     case MVT::i1:
15238     case MVT::i8:
15239     case MVT::i32:
15240       if (Scale < 0) Scale = -Scale;
15241       if (Scale == 1)
15242         return true;
15243       // r + r << imm
15244       return isPowerOf2_32(Scale & ~1);
15245     case MVT::i16:
15246     case MVT::i64:
15247       // r +/- r
15248       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
15249         return true;
15250       // r * 2 (this can be lowered to r + r).
15251       if (!AM.HasBaseReg && Scale == 2)
15252         return true;
15253       return false;
15254
15255     case MVT::isVoid:
15256       // Note, we allow "void" uses (basically, uses that aren't loads or
15257       // stores), because arm allows folding a scale into many arithmetic
15258       // operations.  This should be made more precise and revisited later.
15259
15260       // Allow r << imm, but the imm has to be a multiple of two.
15261       if (Scale & 1) return false;
15262       return isPowerOf2_32(Scale);
15263     }
15264   }
15265   return true;
15266 }
15267
15268 /// isLegalICmpImmediate - Return true if the specified immediate is legal
15269 /// icmp immediate, that is the target has icmp instructions which can compare
15270 /// a register against the immediate without having to materialize the
15271 /// immediate into a register.
15272 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15273   // Thumb2 and ARM modes can use cmn for negative immediates.
15274   if (!Subtarget->isThumb())
15275     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
15276            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
15277   if (Subtarget->isThumb2())
15278     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
15279            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
15280   // Thumb1 doesn't have cmn, and only 8-bit immediates.
15281   return Imm >= 0 && Imm <= 255;
15282 }
15283
15284 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
15285 /// *or sub* immediate, that is the target has add or sub instructions which can
15286 /// add a register with the immediate without having to materialize the
15287 /// immediate into a register.
15288 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15289   // Same encoding for add/sub, just flip the sign.
15290   int64_t AbsImm = std::abs(Imm);
15291   if (!Subtarget->isThumb())
15292     return ARM_AM::getSOImmVal(AbsImm) != -1;
15293   if (Subtarget->isThumb2())
15294     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
15295   // Thumb1 only has 8-bit unsigned immediate.
15296   return AbsImm >= 0 && AbsImm <= 255;
15297 }
15298
15299 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
15300                                       bool isSEXTLoad, SDValue &Base,
15301                                       SDValue &Offset, bool &isInc,
15302                                       SelectionDAG &DAG) {
15303   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
15304     return false;
15305
15306   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
15307     // AddressingMode 3
15308     Base = Ptr->getOperand(0);
15309     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
15310       int RHSC = (int)RHS->getZExtValue();
15311       if (RHSC < 0 && RHSC > -256) {
15312         assert(Ptr->getOpcode() == ISD::ADD);
15313         isInc = false;
15314         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15315         return true;
15316       }
15317     }
15318     isInc = (Ptr->getOpcode() == ISD::ADD);
15319     Offset = Ptr->getOperand(1);
15320     return true;
15321   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
15322     // AddressingMode 2
15323     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
15324       int RHSC = (int)RHS->getZExtValue();
15325       if (RHSC < 0 && RHSC > -0x1000) {
15326         assert(Ptr->getOpcode() == ISD::ADD);
15327         isInc = false;
15328         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15329         Base = Ptr->getOperand(0);
15330         return true;
15331       }
15332     }
15333
15334     if (Ptr->getOpcode() == ISD::ADD) {
15335       isInc = true;
15336       ARM_AM::ShiftOpc ShOpcVal=
15337         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
15338       if (ShOpcVal != ARM_AM::no_shift) {
15339         Base = Ptr->getOperand(1);
15340         Offset = Ptr->getOperand(0);
15341       } else {
15342         Base = Ptr->getOperand(0);
15343         Offset = Ptr->getOperand(1);
15344       }
15345       return true;
15346     }
15347
15348     isInc = (Ptr->getOpcode() == ISD::ADD);
15349     Base = Ptr->getOperand(0);
15350     Offset = Ptr->getOperand(1);
15351     return true;
15352   }
15353
15354   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
15355   return false;
15356 }
15357
15358 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
15359                                      bool isSEXTLoad, SDValue &Base,
15360                                      SDValue &Offset, bool &isInc,
15361                                      SelectionDAG &DAG) {
15362   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
15363     return false;
15364
15365   Base = Ptr->getOperand(0);
15366   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
15367     int RHSC = (int)RHS->getZExtValue();
15368     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
15369       assert(Ptr->getOpcode() == ISD::ADD);
15370       isInc = false;
15371       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15372       return true;
15373     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
15374       isInc = Ptr->getOpcode() == ISD::ADD;
15375       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
15376       return true;
15377     }
15378   }
15379
15380   return false;
15381 }
15382
15383 static bool getMVEIndexedAddressParts(SDNode *Ptr, EVT VT, unsigned Align,
15384                                       bool isSEXTLoad, bool IsMasked, bool isLE,
15385                                       SDValue &Base, SDValue &Offset,
15386                                       bool &isInc, SelectionDAG &DAG) {
15387   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
15388     return false;
15389   if (!isa<ConstantSDNode>(Ptr->getOperand(1)))
15390     return false;
15391
15392   // We allow LE non-masked loads to change the type (for example use a vldrb.8
15393   // as opposed to a vldrw.32). This can allow extra addressing modes or
15394   // alignments for what is otherwise an equivalent instruction.
15395   bool CanChangeType = isLE && !IsMasked;
15396
15397   ConstantSDNode *RHS = cast<ConstantSDNode>(Ptr->getOperand(1));
15398   int RHSC = (int)RHS->getZExtValue();
15399
15400   auto IsInRange = [&](int RHSC, int Limit, int Scale) {
15401     if (RHSC < 0 && RHSC > -Limit * Scale && RHSC % Scale == 0) {
15402       assert(Ptr->getOpcode() == ISD::ADD);
15403       isInc = false;
15404       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
15405       return true;
15406     } else if (RHSC > 0 && RHSC < Limit * Scale && RHSC % Scale == 0) {
15407       isInc = Ptr->getOpcode() == ISD::ADD;
15408       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
15409       return true;
15410     }
15411     return false;
15412   };
15413
15414   // Try to find a matching instruction based on s/zext, Alignment, Offset and
15415   // (in BE/masked) type.
15416   Base = Ptr->getOperand(0);
15417   if (VT == MVT::v4i16) {
15418     if (Align >= 2 && IsInRange(RHSC, 0x80, 2))
15419       return true;
15420   } else if (VT == MVT::v4i8 || VT == MVT::v8i8) {
15421     if (IsInRange(RHSC, 0x80, 1))
15422       return true;
15423   } else if (Align >= 4 &&
15424              (CanChangeType || VT == MVT::v4i32 || VT == MVT::v4f32) &&
15425              IsInRange(RHSC, 0x80, 4))
15426     return true;
15427   else if (Align >= 2 &&
15428            (CanChangeType || VT == MVT::v8i16 || VT == MVT::v8f16) &&
15429            IsInRange(RHSC, 0x80, 2))
15430     return true;
15431   else if ((CanChangeType || VT == MVT::v16i8) && IsInRange(RHSC, 0x80, 1))
15432     return true;
15433   return false;
15434 }
15435
15436 /// getPreIndexedAddressParts - returns true by value, base pointer and
15437 /// offset pointer and addressing mode by reference if the node's address
15438 /// can be legally represented as pre-indexed load / store address.
15439 bool
15440 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
15441                                              SDValue &Offset,
15442                                              ISD::MemIndexedMode &AM,
15443                                              SelectionDAG &DAG) const {
15444   if (Subtarget->isThumb1Only())
15445     return false;
15446
15447   EVT VT;
15448   SDValue Ptr;
15449   unsigned Align;
15450   bool isSEXTLoad = false;
15451   bool IsMasked = false;
15452   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15453     Ptr = LD->getBasePtr();
15454     VT = LD->getMemoryVT();
15455     Align = LD->getAlignment();
15456     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
15457   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15458     Ptr = ST->getBasePtr();
15459     VT = ST->getMemoryVT();
15460     Align = ST->getAlignment();
15461   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
15462     Ptr = LD->getBasePtr();
15463     VT = LD->getMemoryVT();
15464     Align = LD->getAlignment();
15465     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
15466     IsMasked = true;
15467   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
15468     Ptr = ST->getBasePtr();
15469     VT = ST->getMemoryVT();
15470     Align = ST->getAlignment();
15471     IsMasked = true;
15472   } else
15473     return false;
15474
15475   bool isInc;
15476   bool isLegal = false;
15477   if (VT.isVector())
15478     isLegal = Subtarget->hasMVEIntegerOps() &&
15479               getMVEIndexedAddressParts(Ptr.getNode(), VT, Align, isSEXTLoad,
15480                                         IsMasked, Subtarget->isLittle(), Base,
15481                                         Offset, isInc, DAG);
15482   else {
15483     if (Subtarget->isThumb2())
15484       isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
15485                                          Offset, isInc, DAG);
15486     else
15487       isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
15488                                           Offset, isInc, DAG);
15489   }
15490   if (!isLegal)
15491     return false;
15492
15493   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
15494   return true;
15495 }
15496
15497 /// getPostIndexedAddressParts - returns true by value, base pointer and
15498 /// offset pointer and addressing mode by reference if this node can be
15499 /// combined with a load / store to form a post-indexed load / store.
15500 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
15501                                                    SDValue &Base,
15502                                                    SDValue &Offset,
15503                                                    ISD::MemIndexedMode &AM,
15504                                                    SelectionDAG &DAG) const {
15505   EVT VT;
15506   SDValue Ptr;
15507   unsigned Align;
15508   bool isSEXTLoad = false, isNonExt;
15509   bool IsMasked = false;
15510   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
15511     VT = LD->getMemoryVT();
15512     Ptr = LD->getBasePtr();
15513     Align = LD->getAlignment();
15514     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
15515     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
15516   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
15517     VT = ST->getMemoryVT();
15518     Ptr = ST->getBasePtr();
15519     Align = ST->getAlignment();
15520     isNonExt = !ST->isTruncatingStore();
15521   } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
15522     VT = LD->getMemoryVT();
15523     Ptr = LD->getBasePtr();
15524     Align = LD->getAlignment();
15525     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
15526     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
15527     IsMasked = true;
15528   } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
15529     VT = ST->getMemoryVT();
15530     Ptr = ST->getBasePtr();
15531     Align = ST->getAlignment();
15532     isNonExt = !ST->isTruncatingStore();
15533     IsMasked = true;
15534   } else
15535     return false;
15536
15537   if (Subtarget->isThumb1Only()) {
15538     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
15539     // must be non-extending/truncating, i32, with an offset of 4.
15540     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
15541     if (Op->getOpcode() != ISD::ADD || !isNonExt)
15542       return false;
15543     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
15544     if (!RHS || RHS->getZExtValue() != 4)
15545       return false;
15546
15547     Offset = Op->getOperand(1);
15548     Base = Op->getOperand(0);
15549     AM = ISD::POST_INC;
15550     return true;
15551   }
15552
15553   bool isInc;
15554   bool isLegal = false;
15555   if (VT.isVector())
15556     isLegal = Subtarget->hasMVEIntegerOps() &&
15557               getMVEIndexedAddressParts(Op, VT, Align, isSEXTLoad, IsMasked,
15558                                         Subtarget->isLittle(), Base, Offset,
15559                                         isInc, DAG);
15560   else {
15561     if (Subtarget->isThumb2())
15562       isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
15563                                          isInc, DAG);
15564     else
15565       isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
15566                                           isInc, DAG);
15567   }
15568   if (!isLegal)
15569     return false;
15570
15571   if (Ptr != Base) {
15572     // Swap base ptr and offset to catch more post-index load / store when
15573     // it's legal. In Thumb2 mode, offset must be an immediate.
15574     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
15575         !Subtarget->isThumb2())
15576       std::swap(Base, Offset);
15577
15578     // Post-indexed load / store update the base pointer.
15579     if (Ptr != Base)
15580       return false;
15581   }
15582
15583   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
15584   return true;
15585 }
15586
15587 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
15588                                                       KnownBits &Known,
15589                                                       const APInt &DemandedElts,
15590                                                       const SelectionDAG &DAG,
15591                                                       unsigned Depth) const {
15592   unsigned BitWidth = Known.getBitWidth();
15593   Known.resetAll();
15594   switch (Op.getOpcode()) {
15595   default: break;
15596   case ARMISD::ADDC:
15597   case ARMISD::ADDE:
15598   case ARMISD::SUBC:
15599   case ARMISD::SUBE:
15600     // Special cases when we convert a carry to a boolean.
15601     if (Op.getResNo() == 0) {
15602       SDValue LHS = Op.getOperand(0);
15603       SDValue RHS = Op.getOperand(1);
15604       // (ADDE 0, 0, C) will give us a single bit.
15605       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
15606           isNullConstant(RHS)) {
15607         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
15608         return;
15609       }
15610     }
15611     break;
15612   case ARMISD::CMOV: {
15613     // Bits are known zero/one if known on the LHS and RHS.
15614     Known = DAG.computeKnownBits(Op.getOperand(0), Depth+1);
15615     if (Known.isUnknown())
15616       return;
15617
15618     KnownBits KnownRHS = DAG.computeKnownBits(Op.getOperand(1), Depth+1);
15619     Known.Zero &= KnownRHS.Zero;
15620     Known.One  &= KnownRHS.One;
15621     return;
15622   }
15623   case ISD::INTRINSIC_W_CHAIN: {
15624     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
15625     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
15626     switch (IntID) {
15627     default: return;
15628     case Intrinsic::arm_ldaex:
15629     case Intrinsic::arm_ldrex: {
15630       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
15631       unsigned MemBits = VT.getScalarSizeInBits();
15632       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
15633       return;
15634     }
15635     }
15636   }
15637   case ARMISD::BFI: {
15638     // Conservatively, we can recurse down the first operand
15639     // and just mask out all affected bits.
15640     Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
15641
15642     // The operand to BFI is already a mask suitable for removing the bits it
15643     // sets.
15644     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
15645     const APInt &Mask = CI->getAPIntValue();
15646     Known.Zero &= Mask;
15647     Known.One &= Mask;
15648     return;
15649   }
15650   case ARMISD::VGETLANEs:
15651   case ARMISD::VGETLANEu: {
15652     const SDValue &SrcSV = Op.getOperand(0);
15653     EVT VecVT = SrcSV.getValueType();
15654     assert(VecVT.isVector() && "VGETLANE expected a vector type");
15655     const unsigned NumSrcElts = VecVT.getVectorNumElements();
15656     ConstantSDNode *Pos = cast<ConstantSDNode>(Op.getOperand(1).getNode());
15657     assert(Pos->getAPIntValue().ult(NumSrcElts) &&
15658            "VGETLANE index out of bounds");
15659     unsigned Idx = Pos->getZExtValue();
15660     APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
15661     Known = DAG.computeKnownBits(SrcSV, DemandedElt, Depth + 1);
15662
15663     EVT VT = Op.getValueType();
15664     const unsigned DstSz = VT.getScalarSizeInBits();
15665     const unsigned SrcSz = VecVT.getVectorElementType().getSizeInBits();
15666     (void)SrcSz;
15667     assert(SrcSz == Known.getBitWidth());
15668     assert(DstSz > SrcSz);
15669     if (Op.getOpcode() == ARMISD::VGETLANEs)
15670       Known = Known.sext(DstSz);
15671     else {
15672       Known = Known.zext(DstSz, true /* extended bits are known zero */);
15673     }
15674     assert(DstSz == Known.getBitWidth());
15675     break;
15676   }
15677   }
15678 }
15679
15680 bool
15681 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
15682                                                 const APInt &DemandedAPInt,
15683                                                 TargetLoweringOpt &TLO) const {
15684   // Delay optimization, so we don't have to deal with illegal types, or block
15685   // optimizations.
15686   if (!TLO.LegalOps)
15687     return false;
15688
15689   // Only optimize AND for now.
15690   if (Op.getOpcode() != ISD::AND)
15691     return false;
15692
15693   EVT VT = Op.getValueType();
15694
15695   // Ignore vectors.
15696   if (VT.isVector())
15697     return false;
15698
15699   assert(VT == MVT::i32 && "Unexpected integer type");
15700
15701   // Make sure the RHS really is a constant.
15702   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
15703   if (!C)
15704     return false;
15705
15706   unsigned Mask = C->getZExtValue();
15707
15708   unsigned Demanded = DemandedAPInt.getZExtValue();
15709   unsigned ShrunkMask = Mask & Demanded;
15710   unsigned ExpandedMask = Mask | ~Demanded;
15711
15712   // If the mask is all zeros, let the target-independent code replace the
15713   // result with zero.
15714   if (ShrunkMask == 0)
15715     return false;
15716
15717   // If the mask is all ones, erase the AND. (Currently, the target-independent
15718   // code won't do this, so we have to do it explicitly to avoid an infinite
15719   // loop in obscure cases.)
15720   if (ExpandedMask == ~0U)
15721     return TLO.CombineTo(Op, Op.getOperand(0));
15722
15723   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
15724     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
15725   };
15726   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
15727     if (NewMask == Mask)
15728       return true;
15729     SDLoc DL(Op);
15730     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
15731     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
15732     return TLO.CombineTo(Op, NewOp);
15733   };
15734
15735   // Prefer uxtb mask.
15736   if (IsLegalMask(0xFF))
15737     return UseMask(0xFF);
15738
15739   // Prefer uxth mask.
15740   if (IsLegalMask(0xFFFF))
15741     return UseMask(0xFFFF);
15742
15743   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
15744   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15745   if (ShrunkMask < 256)
15746     return UseMask(ShrunkMask);
15747
15748   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
15749   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
15750   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
15751     return UseMask(ExpandedMask);
15752
15753   // Potential improvements:
15754   //
15755   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
15756   // We could try to prefer Thumb1 immediates which can be lowered to a
15757   // two-instruction sequence.
15758   // We could try to recognize more legal ARM/Thumb2 immediates here.
15759
15760   return false;
15761 }
15762
15763
15764 //===----------------------------------------------------------------------===//
15765 //                           ARM Inline Assembly Support
15766 //===----------------------------------------------------------------------===//
15767
15768 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
15769   // Looking for "rev" which is V6+.
15770   if (!Subtarget->hasV6Ops())
15771     return false;
15772
15773   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
15774   std::string AsmStr = IA->getAsmString();
15775   SmallVector<StringRef, 4> AsmPieces;
15776   SplitString(AsmStr, AsmPieces, ";\n");
15777
15778   switch (AsmPieces.size()) {
15779   default: return false;
15780   case 1:
15781     AsmStr = AsmPieces[0];
15782     AsmPieces.clear();
15783     SplitString(AsmStr, AsmPieces, " \t,");
15784
15785     // rev $0, $1
15786     if (AsmPieces.size() == 3 &&
15787         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
15788         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
15789       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
15790       if (Ty && Ty->getBitWidth() == 32)
15791         return IntrinsicLowering::LowerToByteSwap(CI);
15792     }
15793     break;
15794   }
15795
15796   return false;
15797 }
15798
15799 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
15800   // At this point, we have to lower this constraint to something else, so we
15801   // lower it to an "r" or "w". However, by doing this we will force the result
15802   // to be in register, while the X constraint is much more permissive.
15803   //
15804   // Although we are correct (we are free to emit anything, without
15805   // constraints), we might break use cases that would expect us to be more
15806   // efficient and emit something else.
15807   if (!Subtarget->hasVFP2Base())
15808     return "r";
15809   if (ConstraintVT.isFloatingPoint())
15810     return "w";
15811   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
15812      (ConstraintVT.getSizeInBits() == 64 ||
15813       ConstraintVT.getSizeInBits() == 128))
15814     return "w";
15815
15816   return "r";
15817 }
15818
15819 /// getConstraintType - Given a constraint letter, return the type of
15820 /// constraint it is for this target.
15821 ARMTargetLowering::ConstraintType
15822 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
15823   unsigned S = Constraint.size();
15824   if (S == 1) {
15825     switch (Constraint[0]) {
15826     default:  break;
15827     case 'l': return C_RegisterClass;
15828     case 'w': return C_RegisterClass;
15829     case 'h': return C_RegisterClass;
15830     case 'x': return C_RegisterClass;
15831     case 't': return C_RegisterClass;
15832     case 'j': return C_Immediate; // Constant for movw.
15833     // An address with a single base register. Due to the way we
15834     // currently handle addresses it is the same as an 'r' memory constraint.
15835     case 'Q': return C_Memory;
15836     }
15837   } else if (S == 2) {
15838     switch (Constraint[0]) {
15839     default: break;
15840     case 'T': return C_RegisterClass;
15841     // All 'U+' constraints are addresses.
15842     case 'U': return C_Memory;
15843     }
15844   }
15845   return TargetLowering::getConstraintType(Constraint);
15846 }
15847
15848 /// Examine constraint type and operand type and determine a weight value.
15849 /// This object must already have been set up with the operand type
15850 /// and the current alternative constraint selected.
15851 TargetLowering::ConstraintWeight
15852 ARMTargetLowering::getSingleConstraintMatchWeight(
15853     AsmOperandInfo &info, const char *constraint) const {
15854   ConstraintWeight weight = CW_Invalid;
15855   Value *CallOperandVal = info.CallOperandVal;
15856     // If we don't have a value, we can't do a match,
15857     // but allow it at the lowest weight.
15858   if (!CallOperandVal)
15859     return CW_Default;
15860   Type *type = CallOperandVal->getType();
15861   // Look at the constraint type.
15862   switch (*constraint) {
15863   default:
15864     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15865     break;
15866   case 'l':
15867     if (type->isIntegerTy()) {
15868       if (Subtarget->isThumb())
15869         weight = CW_SpecificReg;
15870       else
15871         weight = CW_Register;
15872     }
15873     break;
15874   case 'w':
15875     if (type->isFloatingPointTy())
15876       weight = CW_Register;
15877     break;
15878   }
15879   return weight;
15880 }
15881
15882 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
15883
15884 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
15885     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
15886   switch (Constraint.size()) {
15887   case 1:
15888     // GCC ARM Constraint Letters
15889     switch (Constraint[0]) {
15890     case 'l': // Low regs or general regs.
15891       if (Subtarget->isThumb())
15892         return RCPair(0U, &ARM::tGPRRegClass);
15893       return RCPair(0U, &ARM::GPRRegClass);
15894     case 'h': // High regs or no regs.
15895       if (Subtarget->isThumb())
15896         return RCPair(0U, &ARM::hGPRRegClass);
15897       break;
15898     case 'r':
15899       if (Subtarget->isThumb1Only())
15900         return RCPair(0U, &ARM::tGPRRegClass);
15901       return RCPair(0U, &ARM::GPRRegClass);
15902     case 'w':
15903       if (VT == MVT::Other)
15904         break;
15905       if (VT == MVT::f32)
15906         return RCPair(0U, &ARM::SPRRegClass);
15907       if (VT.getSizeInBits() == 64)
15908         return RCPair(0U, &ARM::DPRRegClass);
15909       if (VT.getSizeInBits() == 128)
15910         return RCPair(0U, &ARM::QPRRegClass);
15911       break;
15912     case 'x':
15913       if (VT == MVT::Other)
15914         break;
15915       if (VT == MVT::f32)
15916         return RCPair(0U, &ARM::SPR_8RegClass);
15917       if (VT.getSizeInBits() == 64)
15918         return RCPair(0U, &ARM::DPR_8RegClass);
15919       if (VT.getSizeInBits() == 128)
15920         return RCPair(0U, &ARM::QPR_8RegClass);
15921       break;
15922     case 't':
15923       if (VT == MVT::Other)
15924         break;
15925       if (VT == MVT::f32 || VT == MVT::i32)
15926         return RCPair(0U, &ARM::SPRRegClass);
15927       if (VT.getSizeInBits() == 64)
15928         return RCPair(0U, &ARM::DPR_VFP2RegClass);
15929       if (VT.getSizeInBits() == 128)
15930         return RCPair(0U, &ARM::QPR_VFP2RegClass);
15931       break;
15932     }
15933     break;
15934
15935   case 2:
15936     if (Constraint[0] == 'T') {
15937       switch (Constraint[1]) {
15938       default:
15939         break;
15940       case 'e':
15941         return RCPair(0U, &ARM::tGPREvenRegClass);
15942       case 'o':
15943         return RCPair(0U, &ARM::tGPROddRegClass);
15944       }
15945     }
15946     break;
15947
15948   default:
15949     break;
15950   }
15951
15952   if (StringRef("{cc}").equals_lower(Constraint))
15953     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
15954
15955   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15956 }
15957
15958 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15959 /// vector.  If it is invalid, don't add anything to Ops.
15960 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15961                                                      std::string &Constraint,
15962                                                      std::vector<SDValue>&Ops,
15963                                                      SelectionDAG &DAG) const {
15964   SDValue Result;
15965
15966   // Currently only support length 1 constraints.
15967   if (Constraint.length() != 1) return;
15968
15969   char ConstraintLetter = Constraint[0];
15970   switch (ConstraintLetter) {
15971   default: break;
15972   case 'j':
15973   case 'I': case 'J': case 'K': case 'L':
15974   case 'M': case 'N': case 'O':
15975     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
15976     if (!C)
15977       return;
15978
15979     int64_t CVal64 = C->getSExtValue();
15980     int CVal = (int) CVal64;
15981     // None of these constraints allow values larger than 32 bits.  Check
15982     // that the value fits in an int.
15983     if (CVal != CVal64)
15984       return;
15985
15986     switch (ConstraintLetter) {
15987       case 'j':
15988         // Constant suitable for movw, must be between 0 and
15989         // 65535.
15990         if (Subtarget->hasV6T2Ops() || (Subtarget->hasV8MBaselineOps()))
15991           if (CVal >= 0 && CVal <= 65535)
15992             break;
15993         return;
15994       case 'I':
15995         if (Subtarget->isThumb1Only()) {
15996           // This must be a constant between 0 and 255, for ADD
15997           // immediates.
15998           if (CVal >= 0 && CVal <= 255)
15999             break;
16000         } else if (Subtarget->isThumb2()) {
16001           // A constant that can be used as an immediate value in a
16002           // data-processing instruction.
16003           if (ARM_AM::getT2SOImmVal(CVal) != -1)
16004             break;
16005         } else {
16006           // A constant that can be used as an immediate value in a
16007           // data-processing instruction.
16008           if (ARM_AM::getSOImmVal(CVal) != -1)
16009             break;
16010         }
16011         return;
16012
16013       case 'J':
16014         if (Subtarget->isThumb1Only()) {
16015           // This must be a constant between -255 and -1, for negated ADD
16016           // immediates. This can be used in GCC with an "n" modifier that
16017           // prints the negated value, for use with SUB instructions. It is
16018           // not useful otherwise but is implemented for compatibility.
16019           if (CVal >= -255 && CVal <= -1)
16020             break;
16021         } else {
16022           // This must be a constant between -4095 and 4095. It is not clear
16023           // what this constraint is intended for. Implemented for
16024           // compatibility with GCC.
16025           if (CVal >= -4095 && CVal <= 4095)
16026             break;
16027         }
16028         return;
16029
16030       case 'K':
16031         if (Subtarget->isThumb1Only()) {
16032           // A 32-bit value where only one byte has a nonzero value. Exclude
16033           // zero to match GCC. This constraint is used by GCC internally for
16034           // constants that can be loaded with a move/shift combination.
16035           // It is not useful otherwise but is implemented for compatibility.
16036           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
16037             break;
16038         } else if (Subtarget->isThumb2()) {
16039           // A constant whose bitwise inverse can be used as an immediate
16040           // value in a data-processing instruction. This can be used in GCC
16041           // with a "B" modifier that prints the inverted value, for use with
16042           // BIC and MVN instructions. It is not useful otherwise but is
16043           // implemented for compatibility.
16044           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
16045             break;
16046         } else {
16047           // A constant whose bitwise inverse can be used as an immediate
16048           // value in a data-processing instruction. This can be used in GCC
16049           // with a "B" modifier that prints the inverted value, for use with
16050           // BIC and MVN instructions. It is not useful otherwise but is
16051           // implemented for compatibility.
16052           if (ARM_AM::getSOImmVal(~CVal) != -1)
16053             break;
16054         }
16055         return;
16056
16057       case 'L':
16058         if (Subtarget->isThumb1Only()) {
16059           // This must be a constant between -7 and 7,
16060           // for 3-operand ADD/SUB immediate instructions.
16061           if (CVal >= -7 && CVal < 7)
16062             break;
16063         } else if (Subtarget->isThumb2()) {
16064           // A constant whose negation can be used as an immediate value in a
16065           // data-processing instruction. This can be used in GCC with an "n"
16066           // modifier that prints the negated value, for use with SUB
16067           // instructions. It is not useful otherwise but is implemented for
16068           // compatibility.
16069           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
16070             break;
16071         } else {
16072           // A constant whose negation can be used as an immediate value in a
16073           // data-processing instruction. This can be used in GCC with an "n"
16074           // modifier that prints the negated value, for use with SUB
16075           // instructions. It is not useful otherwise but is implemented for
16076           // compatibility.
16077           if (ARM_AM::getSOImmVal(-CVal) != -1)
16078             break;
16079         }
16080         return;
16081
16082       case 'M':
16083         if (Subtarget->isThumb1Only()) {
16084           // This must be a multiple of 4 between 0 and 1020, for
16085           // ADD sp + immediate.
16086           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
16087             break;
16088         } else {
16089           // A power of two or a constant between 0 and 32.  This is used in
16090           // GCC for the shift amount on shifted register operands, but it is
16091           // useful in general for any shift amounts.
16092           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
16093             break;
16094         }
16095         return;
16096
16097       case 'N':
16098         if (Subtarget->isThumb1Only()) {
16099           // This must be a constant between 0 and 31, for shift amounts.
16100           if (CVal >= 0 && CVal <= 31)
16101             break;
16102         }
16103         return;
16104
16105       case 'O':
16106         if (Subtarget->isThumb1Only()) {
16107           // This must be a multiple of 4 between -508 and 508, for
16108           // ADD/SUB sp = sp + immediate.
16109           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
16110             break;
16111         }
16112         return;
16113     }
16114     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
16115     break;
16116   }
16117
16118   if (Result.getNode()) {
16119     Ops.push_back(Result);
16120     return;
16121   }
16122   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
16123 }
16124
16125 static RTLIB::Libcall getDivRemLibcall(
16126     const SDNode *N, MVT::SimpleValueType SVT) {
16127   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
16128           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
16129          "Unhandled Opcode in getDivRemLibcall");
16130   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
16131                   N->getOpcode() == ISD::SREM;
16132   RTLIB::Libcall LC;
16133   switch (SVT) {
16134   default: llvm_unreachable("Unexpected request for libcall!");
16135   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
16136   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
16137   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
16138   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
16139   }
16140   return LC;
16141 }
16142
16143 static TargetLowering::ArgListTy getDivRemArgList(
16144     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
16145   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
16146           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
16147          "Unhandled Opcode in getDivRemArgList");
16148   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
16149                   N->getOpcode() == ISD::SREM;
16150   TargetLowering::ArgListTy Args;
16151   TargetLowering::ArgListEntry Entry;
16152   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
16153     EVT ArgVT = N->getOperand(i).getValueType();
16154     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
16155     Entry.Node = N->getOperand(i);
16156     Entry.Ty = ArgTy;
16157     Entry.IsSExt = isSigned;
16158     Entry.IsZExt = !isSigned;
16159     Args.push_back(Entry);
16160   }
16161   if (Subtarget->isTargetWindows() && Args.size() >= 2)
16162     std::swap(Args[0], Args[1]);
16163   return Args;
16164 }
16165
16166 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
16167   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
16168           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
16169           Subtarget->isTargetWindows()) &&
16170          "Register-based DivRem lowering only");
16171   unsigned Opcode = Op->getOpcode();
16172   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
16173          "Invalid opcode for Div/Rem lowering");
16174   bool isSigned = (Opcode == ISD::SDIVREM);
16175   EVT VT = Op->getValueType(0);
16176   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
16177   SDLoc dl(Op);
16178
16179   // If the target has hardware divide, use divide + multiply + subtract:
16180   //     div = a / b
16181   //     rem = a - b * div
16182   //     return {div, rem}
16183   // This should be lowered into UDIV/SDIV + MLS later on.
16184   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
16185                                         : Subtarget->hasDivideInARMMode();
16186   if (hasDivide && Op->getValueType(0).isSimple() &&
16187       Op->getSimpleValueType(0) == MVT::i32) {
16188     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
16189     const SDValue Dividend = Op->getOperand(0);
16190     const SDValue Divisor = Op->getOperand(1);
16191     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
16192     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
16193     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
16194
16195     SDValue Values[2] = {Div, Rem};
16196     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
16197   }
16198
16199   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
16200                                        VT.getSimpleVT().SimpleTy);
16201   SDValue InChain = DAG.getEntryNode();
16202
16203   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
16204                                                     DAG.getContext(),
16205                                                     Subtarget);
16206
16207   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16208                                          getPointerTy(DAG.getDataLayout()));
16209
16210   Type *RetTy = StructType::get(Ty, Ty);
16211
16212   if (Subtarget->isTargetWindows())
16213     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
16214
16215   TargetLowering::CallLoweringInfo CLI(DAG);
16216   CLI.setDebugLoc(dl).setChain(InChain)
16217     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
16218     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16219
16220   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16221   return CallInfo.first;
16222 }
16223
16224 // Lowers REM using divmod helpers
16225 // see RTABI section 4.2/4.3
16226 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
16227   // Build return types (div and rem)
16228   std::vector<Type*> RetTyParams;
16229   Type *RetTyElement;
16230
16231   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
16232   default: llvm_unreachable("Unexpected request for libcall!");
16233   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
16234   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
16235   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
16236   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
16237   }
16238
16239   RetTyParams.push_back(RetTyElement);
16240   RetTyParams.push_back(RetTyElement);
16241   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
16242   Type *RetTy = StructType::get(*DAG.getContext(), ret);
16243
16244   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
16245                                                              SimpleTy);
16246   SDValue InChain = DAG.getEntryNode();
16247   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
16248                                                     Subtarget);
16249   bool isSigned = N->getOpcode() == ISD::SREM;
16250   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16251                                          getPointerTy(DAG.getDataLayout()));
16252
16253   if (Subtarget->isTargetWindows())
16254     InChain = WinDBZCheckDenominator(DAG, N, InChain);
16255
16256   // Lower call
16257   CallLoweringInfo CLI(DAG);
16258   CLI.setChain(InChain)
16259      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
16260      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
16261   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
16262
16263   // Return second (rem) result operand (first contains div)
16264   SDNode *ResNode = CallResult.first.getNode();
16265   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
16266   return ResNode->getOperand(1);
16267 }
16268
16269 SDValue
16270 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
16271   assert(Subtarget->isTargetWindows() && "unsupported target platform");
16272   SDLoc DL(Op);
16273
16274   // Get the inputs.
16275   SDValue Chain = Op.getOperand(0);
16276   SDValue Size  = Op.getOperand(1);
16277
16278   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
16279           "no-stack-arg-probe")) {
16280     unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
16281     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
16282     Chain = SP.getValue(1);
16283     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
16284     if (Align)
16285       SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
16286                        DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
16287     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
16288     SDValue Ops[2] = { SP, Chain };
16289     return DAG.getMergeValues(Ops, DL);
16290   }
16291
16292   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
16293                               DAG.getConstant(2, DL, MVT::i32));
16294
16295   SDValue Flag;
16296   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
16297   Flag = Chain.getValue(1);
16298
16299   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
16300   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
16301
16302   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
16303   Chain = NewSP.getValue(1);
16304
16305   SDValue Ops[2] = { NewSP, Chain };
16306   return DAG.getMergeValues(Ops, DL);
16307 }
16308
16309 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
16310   bool IsStrict = Op->isStrictFPOpcode();
16311   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
16312   const unsigned DstSz = Op.getValueType().getSizeInBits();
16313   const unsigned SrcSz = SrcVal.getValueType().getSizeInBits();
16314   assert(DstSz > SrcSz && DstSz <= 64 && SrcSz >= 16 &&
16315          "Unexpected type for custom-lowering FP_EXTEND");
16316
16317   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
16318          "With both FP DP and 16, any FP conversion is legal!");
16319
16320   assert(!(DstSz == 32 && Subtarget->hasFP16()) &&
16321          "With FP16, 16 to 32 conversion is legal!");
16322
16323   // Either we are converting from 16 -> 64, without FP16 and/or
16324   // FP.double-precision or without Armv8-fp. So we must do it in two
16325   // steps.
16326   // Or we are converting from 32 -> 64 without fp.double-precision or 16 -> 32
16327   // without FP16. So we must do a function call.
16328   SDLoc Loc(Op);
16329   RTLIB::Libcall LC;
16330   MakeLibCallOptions CallOptions;
16331   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
16332   for (unsigned Sz = SrcSz; Sz <= 32 && Sz < DstSz; Sz *= 2) {
16333     bool Supported = (Sz == 16 ? Subtarget->hasFP16() : Subtarget->hasFP64());
16334     MVT SrcVT = (Sz == 16 ? MVT::f16 : MVT::f32);
16335     MVT DstVT = (Sz == 16 ? MVT::f32 : MVT::f64);
16336     if (Supported) {
16337       if (IsStrict) {
16338         SrcVal = DAG.getNode(ISD::STRICT_FP_EXTEND, Loc,
16339                              {DstVT, MVT::Other}, {Chain, SrcVal});
16340         Chain = SrcVal.getValue(1);
16341       } else {
16342         SrcVal = DAG.getNode(ISD::FP_EXTEND, Loc, DstVT, SrcVal);
16343       }
16344     } else {
16345       LC = RTLIB::getFPEXT(SrcVT, DstVT);
16346       assert(LC != RTLIB::UNKNOWN_LIBCALL &&
16347              "Unexpected type for custom-lowering FP_EXTEND");
16348       std::tie(SrcVal, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
16349                                             Loc, Chain);
16350     }
16351   }
16352
16353   return IsStrict ? DAG.getMergeValues({SrcVal, Chain}, Loc) : SrcVal;
16354 }
16355
16356 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
16357   bool IsStrict = Op->isStrictFPOpcode();
16358
16359   SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
16360   EVT SrcVT = SrcVal.getValueType();
16361   EVT DstVT = Op.getValueType();
16362   const unsigned DstSz = Op.getValueType().getSizeInBits();
16363   const unsigned SrcSz = SrcVT.getSizeInBits();
16364   (void)DstSz;
16365   assert(DstSz < SrcSz && SrcSz <= 64 && DstSz >= 16 &&
16366          "Unexpected type for custom-lowering FP_ROUND");
16367
16368   assert((!Subtarget->hasFP64() || !Subtarget->hasFPARMv8Base()) &&
16369          "With both FP DP and 16, any FP conversion is legal!");
16370
16371   SDLoc Loc(Op);
16372
16373   // Instruction from 32 -> 16 if hasFP16 is valid
16374   if (SrcSz == 32 && Subtarget->hasFP16())
16375     return Op;
16376
16377   // Lib call from 32 -> 16 / 64 -> [32, 16]
16378   RTLIB::Libcall LC = RTLIB::getFPROUND(SrcVT, DstVT);
16379   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
16380          "Unexpected type for custom-lowering FP_ROUND");
16381   MakeLibCallOptions CallOptions;
16382   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
16383   SDValue Result;
16384   std::tie(Result, Chain) = makeLibCall(DAG, LC, DstVT, SrcVal, CallOptions,
16385                                         Loc, Chain);
16386   return IsStrict ? DAG.getMergeValues({Result, Chain}, Loc) : Result;
16387 }
16388
16389 void ARMTargetLowering::lowerABS(SDNode *N, SmallVectorImpl<SDValue> &Results,
16390                                  SelectionDAG &DAG) const {
16391   assert(N->getValueType(0) == MVT::i64 && "Unexpected type (!= i64) on ABS.");
16392   MVT HalfT = MVT::i32;
16393   SDLoc dl(N);
16394   SDValue Hi, Lo, Tmp;
16395
16396   if (!isOperationLegalOrCustom(ISD::ADDCARRY, HalfT) ||
16397       !isOperationLegalOrCustom(ISD::UADDO, HalfT))
16398     return ;
16399
16400   unsigned OpTypeBits = HalfT.getScalarSizeInBits();
16401   SDVTList VTList = DAG.getVTList(HalfT, MVT::i1);
16402
16403   Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
16404                    DAG.getConstant(0, dl, HalfT));
16405   Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(0),
16406                    DAG.getConstant(1, dl, HalfT));
16407
16408   Tmp = DAG.getNode(ISD::SRA, dl, HalfT, Hi,
16409                     DAG.getConstant(OpTypeBits - 1, dl,
16410                     getShiftAmountTy(HalfT, DAG.getDataLayout())));
16411   Lo = DAG.getNode(ISD::UADDO, dl, VTList, Tmp, Lo);
16412   Hi = DAG.getNode(ISD::ADDCARRY, dl, VTList, Tmp, Hi,
16413                    SDValue(Lo.getNode(), 1));
16414   Hi = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Hi);
16415   Lo = DAG.getNode(ISD::XOR, dl, HalfT, Tmp, Lo);
16416
16417   Results.push_back(Lo);
16418   Results.push_back(Hi);
16419 }
16420
16421 bool
16422 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
16423   // The ARM target isn't yet aware of offsets.
16424   return false;
16425 }
16426
16427 bool ARM::isBitFieldInvertedMask(unsigned v) {
16428   if (v == 0xffffffff)
16429     return false;
16430
16431   // there can be 1's on either or both "outsides", all the "inside"
16432   // bits must be 0's
16433   return isShiftedMask_32(~v);
16434 }
16435
16436 /// isFPImmLegal - Returns true if the target can instruction select the
16437 /// specified FP immediate natively. If false, the legalizer will
16438 /// materialize the FP immediate as a load from a constant pool.
16439 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
16440                                      bool ForCodeSize) const {
16441   if (!Subtarget->hasVFP3Base())
16442     return false;
16443   if (VT == MVT::f16 && Subtarget->hasFullFP16())
16444     return ARM_AM::getFP16Imm(Imm) != -1;
16445   if (VT == MVT::f32)
16446     return ARM_AM::getFP32Imm(Imm) != -1;
16447   if (VT == MVT::f64 && Subtarget->hasFP64())
16448     return ARM_AM::getFP64Imm(Imm) != -1;
16449   return false;
16450 }
16451
16452 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
16453 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
16454 /// specified in the intrinsic calls.
16455 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
16456                                            const CallInst &I,
16457                                            MachineFunction &MF,
16458                                            unsigned Intrinsic) const {
16459   switch (Intrinsic) {
16460   case Intrinsic::arm_neon_vld1:
16461   case Intrinsic::arm_neon_vld2:
16462   case Intrinsic::arm_neon_vld3:
16463   case Intrinsic::arm_neon_vld4:
16464   case Intrinsic::arm_neon_vld2lane:
16465   case Intrinsic::arm_neon_vld3lane:
16466   case Intrinsic::arm_neon_vld4lane:
16467   case Intrinsic::arm_neon_vld2dup:
16468   case Intrinsic::arm_neon_vld3dup:
16469   case Intrinsic::arm_neon_vld4dup: {
16470     Info.opc = ISD::INTRINSIC_W_CHAIN;
16471     // Conservatively set memVT to the entire set of vectors loaded.
16472     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16473     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
16474     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16475     Info.ptrVal = I.getArgOperand(0);
16476     Info.offset = 0;
16477     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
16478     Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
16479     // volatile loads with NEON intrinsics not supported
16480     Info.flags = MachineMemOperand::MOLoad;
16481     return true;
16482   }
16483   case Intrinsic::arm_neon_vld1x2:
16484   case Intrinsic::arm_neon_vld1x3:
16485   case Intrinsic::arm_neon_vld1x4: {
16486     Info.opc = ISD::INTRINSIC_W_CHAIN;
16487     // Conservatively set memVT to the entire set of vectors loaded.
16488     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16489     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
16490     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16491     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
16492     Info.offset = 0;
16493     Info.align.reset();
16494     // volatile loads with NEON intrinsics not supported
16495     Info.flags = MachineMemOperand::MOLoad;
16496     return true;
16497   }
16498   case Intrinsic::arm_neon_vst1:
16499   case Intrinsic::arm_neon_vst2:
16500   case Intrinsic::arm_neon_vst3:
16501   case Intrinsic::arm_neon_vst4:
16502   case Intrinsic::arm_neon_vst2lane:
16503   case Intrinsic::arm_neon_vst3lane:
16504   case Intrinsic::arm_neon_vst4lane: {
16505     Info.opc = ISD::INTRINSIC_VOID;
16506     // Conservatively set memVT to the entire set of vectors stored.
16507     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16508     unsigned NumElts = 0;
16509     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
16510       Type *ArgTy = I.getArgOperand(ArgI)->getType();
16511       if (!ArgTy->isVectorTy())
16512         break;
16513       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
16514     }
16515     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16516     Info.ptrVal = I.getArgOperand(0);
16517     Info.offset = 0;
16518     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
16519     Info.align = MaybeAlign(cast<ConstantInt>(AlignArg)->getZExtValue());
16520     // volatile stores with NEON intrinsics not supported
16521     Info.flags = MachineMemOperand::MOStore;
16522     return true;
16523   }
16524   case Intrinsic::arm_neon_vst1x2:
16525   case Intrinsic::arm_neon_vst1x3:
16526   case Intrinsic::arm_neon_vst1x4: {
16527     Info.opc = ISD::INTRINSIC_VOID;
16528     // Conservatively set memVT to the entire set of vectors stored.
16529     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16530     unsigned NumElts = 0;
16531     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
16532       Type *ArgTy = I.getArgOperand(ArgI)->getType();
16533       if (!ArgTy->isVectorTy())
16534         break;
16535       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
16536     }
16537     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
16538     Info.ptrVal = I.getArgOperand(0);
16539     Info.offset = 0;
16540     Info.align.reset();
16541     // volatile stores with NEON intrinsics not supported
16542     Info.flags = MachineMemOperand::MOStore;
16543     return true;
16544   }
16545   case Intrinsic::arm_ldaex:
16546   case Intrinsic::arm_ldrex: {
16547     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16548     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
16549     Info.opc = ISD::INTRINSIC_W_CHAIN;
16550     Info.memVT = MVT::getVT(PtrTy->getElementType());
16551     Info.ptrVal = I.getArgOperand(0);
16552     Info.offset = 0;
16553     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
16554     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16555     return true;
16556   }
16557   case Intrinsic::arm_stlex:
16558   case Intrinsic::arm_strex: {
16559     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
16560     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
16561     Info.opc = ISD::INTRINSIC_W_CHAIN;
16562     Info.memVT = MVT::getVT(PtrTy->getElementType());
16563     Info.ptrVal = I.getArgOperand(1);
16564     Info.offset = 0;
16565     Info.align = MaybeAlign(DL.getABITypeAlignment(PtrTy->getElementType()));
16566     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16567     return true;
16568   }
16569   case Intrinsic::arm_stlexd:
16570   case Intrinsic::arm_strexd:
16571     Info.opc = ISD::INTRINSIC_W_CHAIN;
16572     Info.memVT = MVT::i64;
16573     Info.ptrVal = I.getArgOperand(2);
16574     Info.offset = 0;
16575     Info.align = Align(8);
16576     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
16577     return true;
16578
16579   case Intrinsic::arm_ldaexd:
16580   case Intrinsic::arm_ldrexd:
16581     Info.opc = ISD::INTRINSIC_W_CHAIN;
16582     Info.memVT = MVT::i64;
16583     Info.ptrVal = I.getArgOperand(0);
16584     Info.offset = 0;
16585     Info.align = Align(8);
16586     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
16587     return true;
16588
16589   default:
16590     break;
16591   }
16592
16593   return false;
16594 }
16595
16596 /// Returns true if it is beneficial to convert a load of a constant
16597 /// to just the constant itself.
16598 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
16599                                                           Type *Ty) const {
16600   assert(Ty->isIntegerTy());
16601
16602   unsigned Bits = Ty->getPrimitiveSizeInBits();
16603   if (Bits == 0 || Bits > 32)
16604     return false;
16605   return true;
16606 }
16607
16608 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
16609                                                 unsigned Index) const {
16610   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
16611     return false;
16612
16613   return (Index == 0 || Index == ResVT.getVectorNumElements());
16614 }
16615
16616 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
16617                                         ARM_MB::MemBOpt Domain) const {
16618   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16619
16620   // First, if the target has no DMB, see what fallback we can use.
16621   if (!Subtarget->hasDataBarrier()) {
16622     // Some ARMv6 cpus can support data barriers with an mcr instruction.
16623     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
16624     // here.
16625     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
16626       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
16627       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
16628                         Builder.getInt32(0), Builder.getInt32(7),
16629                         Builder.getInt32(10), Builder.getInt32(5)};
16630       return Builder.CreateCall(MCR, args);
16631     } else {
16632       // Instead of using barriers, atomic accesses on these subtargets use
16633       // libcalls.
16634       llvm_unreachable("makeDMB on a target so old that it has no barriers");
16635     }
16636   } else {
16637     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
16638     // Only a full system barrier exists in the M-class architectures.
16639     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
16640     Constant *CDomain = Builder.getInt32(Domain);
16641     return Builder.CreateCall(DMB, CDomain);
16642   }
16643 }
16644
16645 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
16646 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
16647                                                  Instruction *Inst,
16648                                                  AtomicOrdering Ord) const {
16649   switch (Ord) {
16650   case AtomicOrdering::NotAtomic:
16651   case AtomicOrdering::Unordered:
16652     llvm_unreachable("Invalid fence: unordered/non-atomic");
16653   case AtomicOrdering::Monotonic:
16654   case AtomicOrdering::Acquire:
16655     return nullptr; // Nothing to do
16656   case AtomicOrdering::SequentiallyConsistent:
16657     if (!Inst->hasAtomicStore())
16658       return nullptr; // Nothing to do
16659     LLVM_FALLTHROUGH;
16660   case AtomicOrdering::Release:
16661   case AtomicOrdering::AcquireRelease:
16662     if (Subtarget->preferISHSTBarriers())
16663       return makeDMB(Builder, ARM_MB::ISHST);
16664     // FIXME: add a comment with a link to documentation justifying this.
16665     else
16666       return makeDMB(Builder, ARM_MB::ISH);
16667   }
16668   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
16669 }
16670
16671 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
16672                                                   Instruction *Inst,
16673                                                   AtomicOrdering Ord) const {
16674   switch (Ord) {
16675   case AtomicOrdering::NotAtomic:
16676   case AtomicOrdering::Unordered:
16677     llvm_unreachable("Invalid fence: unordered/not-atomic");
16678   case AtomicOrdering::Monotonic:
16679   case AtomicOrdering::Release:
16680     return nullptr; // Nothing to do
16681   case AtomicOrdering::Acquire:
16682   case AtomicOrdering::AcquireRelease:
16683   case AtomicOrdering::SequentiallyConsistent:
16684     return makeDMB(Builder, ARM_MB::ISH);
16685   }
16686   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
16687 }
16688
16689 // Loads and stores less than 64-bits are already atomic; ones above that
16690 // are doomed anyway, so defer to the default libcall and blame the OS when
16691 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16692 // anything for those.
16693 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16694   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
16695   return (Size == 64) && !Subtarget->isMClass();
16696 }
16697
16698 // Loads and stores less than 64-bits are already atomic; ones above that
16699 // are doomed anyway, so defer to the default libcall and blame the OS when
16700 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
16701 // anything for those.
16702 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
16703 // guarantee, see DDI0406C ARM architecture reference manual,
16704 // sections A8.8.72-74 LDRD)
16705 TargetLowering::AtomicExpansionKind
16706 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
16707   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
16708   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
16709                                                   : AtomicExpansionKind::None;
16710 }
16711
16712 // For the real atomic operations, we have ldrex/strex up to 32 bits,
16713 // and up to 64 bits on the non-M profiles
16714 TargetLowering::AtomicExpansionKind
16715 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16716   if (AI->isFloatingPointOperation())
16717     return AtomicExpansionKind::CmpXChg;
16718
16719   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
16720   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16721   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
16722              ? AtomicExpansionKind::LLSC
16723              : AtomicExpansionKind::None;
16724 }
16725
16726 TargetLowering::AtomicExpansionKind
16727 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
16728   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
16729   // implement cmpxchg without spilling. If the address being exchanged is also
16730   // on the stack and close enough to the spill slot, this can lead to a
16731   // situation where the monitor always gets cleared and the atomic operation
16732   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
16733   bool HasAtomicCmpXchg =
16734       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
16735   if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
16736     return AtomicExpansionKind::LLSC;
16737   return AtomicExpansionKind::None;
16738 }
16739
16740 bool ARMTargetLowering::shouldInsertFencesForAtomic(
16741     const Instruction *I) const {
16742   return InsertFencesForAtomic;
16743 }
16744
16745 // This has so far only been implemented for MachO.
16746 bool ARMTargetLowering::useLoadStackGuardNode() const {
16747   return Subtarget->isTargetMachO();
16748 }
16749
16750 void ARMTargetLowering::insertSSPDeclarations(Module &M) const {
16751   if (!Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16752     return TargetLowering::insertSSPDeclarations(M);
16753
16754   // MSVC CRT has a global variable holding security cookie.
16755   M.getOrInsertGlobal("__security_cookie",
16756                       Type::getInt8PtrTy(M.getContext()));
16757
16758   // MSVC CRT has a function to validate security cookie.
16759   FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
16760       "__security_check_cookie", Type::getVoidTy(M.getContext()),
16761       Type::getInt8PtrTy(M.getContext()));
16762   if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee()))
16763     F->addAttribute(1, Attribute::AttrKind::InReg);
16764 }
16765
16766 Value *ARMTargetLowering::getSDagStackGuard(const Module &M) const {
16767   // MSVC CRT has a global variable holding security cookie.
16768   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16769     return M.getGlobalVariable("__security_cookie");
16770   return TargetLowering::getSDagStackGuard(M);
16771 }
16772
16773 Function *ARMTargetLowering::getSSPStackGuardCheck(const Module &M) const {
16774   // MSVC CRT has a function to validate security cookie.
16775   if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
16776     return M.getFunction("__security_check_cookie");
16777   return TargetLowering::getSSPStackGuardCheck(M);
16778 }
16779
16780 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
16781                                                   unsigned &Cost) const {
16782   // If we do not have NEON, vector types are not natively supported.
16783   if (!Subtarget->hasNEON())
16784     return false;
16785
16786   // Floating point values and vector values map to the same register file.
16787   // Therefore, although we could do a store extract of a vector type, this is
16788   // better to leave at float as we have more freedom in the addressing mode for
16789   // those.
16790   if (VectorTy->isFPOrFPVectorTy())
16791     return false;
16792
16793   // If the index is unknown at compile time, this is very expensive to lower
16794   // and it is not possible to combine the store with the extract.
16795   if (!isa<ConstantInt>(Idx))
16796     return false;
16797
16798   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
16799   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
16800   // We can do a store + vector extract on any vector that fits perfectly in a D
16801   // or Q register.
16802   if (BitWidth == 64 || BitWidth == 128) {
16803     Cost = 0;
16804     return true;
16805   }
16806   return false;
16807 }
16808
16809 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
16810   return Subtarget->hasV6T2Ops();
16811 }
16812
16813 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
16814   return Subtarget->hasV6T2Ops();
16815 }
16816
16817 bool ARMTargetLowering::shouldExpandShift(SelectionDAG &DAG, SDNode *N) const {
16818   return !Subtarget->hasMinSize();
16819 }
16820
16821 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
16822                                          AtomicOrdering Ord) const {
16823   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16824   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
16825   bool IsAcquire = isAcquireOrStronger(Ord);
16826
16827   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
16828   // intrinsic must return {i32, i32} and we have to recombine them into a
16829   // single i64 here.
16830   if (ValTy->getPrimitiveSizeInBits() == 64) {
16831     Intrinsic::ID Int =
16832         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
16833     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
16834
16835     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16836     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
16837
16838     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
16839     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
16840     if (!Subtarget->isLittle())
16841       std::swap (Lo, Hi);
16842     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
16843     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
16844     return Builder.CreateOr(
16845         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
16846   }
16847
16848   Type *Tys[] = { Addr->getType() };
16849   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
16850   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
16851
16852   return Builder.CreateTruncOrBitCast(
16853       Builder.CreateCall(Ldrex, Addr),
16854       cast<PointerType>(Addr->getType())->getElementType());
16855 }
16856
16857 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
16858     IRBuilder<> &Builder) const {
16859   if (!Subtarget->hasV7Ops())
16860     return;
16861   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16862   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
16863 }
16864
16865 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
16866                                                Value *Addr,
16867                                                AtomicOrdering Ord) const {
16868   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
16869   bool IsRelease = isReleaseOrStronger(Ord);
16870
16871   // Since the intrinsics must have legal type, the i64 intrinsics take two
16872   // parameters: "i32, i32". We must marshal Val into the appropriate form
16873   // before the call.
16874   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
16875     Intrinsic::ID Int =
16876         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
16877     Function *Strex = Intrinsic::getDeclaration(M, Int);
16878     Type *Int32Ty = Type::getInt32Ty(M->getContext());
16879
16880     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
16881     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
16882     if (!Subtarget->isLittle())
16883       std::swap(Lo, Hi);
16884     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
16885     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
16886   }
16887
16888   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
16889   Type *Tys[] = { Addr->getType() };
16890   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
16891
16892   return Builder.CreateCall(
16893       Strex, {Builder.CreateZExtOrBitCast(
16894                   Val, Strex->getFunctionType()->getParamType(0)),
16895               Addr});
16896 }
16897
16898
16899 bool ARMTargetLowering::alignLoopsWithOptSize() const {
16900   return Subtarget->isMClass();
16901 }
16902
16903 /// A helper function for determining the number of interleaved accesses we
16904 /// will generate when lowering accesses of the given type.
16905 unsigned
16906 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
16907                                              const DataLayout &DL) const {
16908   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
16909 }
16910
16911 bool ARMTargetLowering::isLegalInterleavedAccessType(
16912     unsigned Factor, VectorType *VecTy, const DataLayout &DL) const {
16913
16914   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
16915   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
16916
16917   if (!Subtarget->hasNEON() && !Subtarget->hasMVEIntegerOps())
16918     return false;
16919
16920   // Ensure the vector doesn't have f16 elements. Even though we could do an
16921   // i16 vldN, we can't hold the f16 vectors and will end up converting via
16922   // f32.
16923   if (Subtarget->hasNEON() && VecTy->getElementType()->isHalfTy())
16924     return false;
16925   if (Subtarget->hasMVEIntegerOps() && Factor == 3)
16926     return false;
16927
16928   // Ensure the number of vector elements is greater than 1.
16929   if (VecTy->getNumElements() < 2)
16930     return false;
16931
16932   // Ensure the element type is legal.
16933   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
16934     return false;
16935
16936   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
16937   // 128 will be split into multiple interleaved accesses.
16938   if (Subtarget->hasNEON() && VecSize == 64)
16939     return true;
16940   return VecSize % 128 == 0;
16941 }
16942
16943 unsigned ARMTargetLowering::getMaxSupportedInterleaveFactor() const {
16944   if (Subtarget->hasNEON())
16945     return 4;
16946   if (Subtarget->hasMVEIntegerOps())
16947     return MVEMaxSupportedInterleaveFactor;
16948   return TargetLoweringBase::getMaxSupportedInterleaveFactor();
16949 }
16950
16951 /// Lower an interleaved load into a vldN intrinsic.
16952 ///
16953 /// E.g. Lower an interleaved load (Factor = 2):
16954 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
16955 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
16956 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
16957 ///
16958 ///      Into:
16959 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
16960 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
16961 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
16962 bool ARMTargetLowering::lowerInterleavedLoad(
16963     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
16964     ArrayRef<unsigned> Indices, unsigned Factor) const {
16965   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
16966          "Invalid interleave factor");
16967   assert(!Shuffles.empty() && "Empty shufflevector input");
16968   assert(Shuffles.size() == Indices.size() &&
16969          "Unmatched number of shufflevectors and indices");
16970
16971   VectorType *VecTy = Shuffles[0]->getType();
16972   Type *EltTy = VecTy->getVectorElementType();
16973
16974   const DataLayout &DL = LI->getModule()->getDataLayout();
16975
16976   // Skip if we do not have NEON and skip illegal vector types. We can
16977   // "legalize" wide vector types into multiple interleaved accesses as long as
16978   // the vector types are divisible by 128.
16979   if (!isLegalInterleavedAccessType(Factor, VecTy, DL))
16980     return false;
16981
16982   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
16983
16984   // A pointer vector can not be the return type of the ldN intrinsics. Need to
16985   // load integer vectors first and then convert to pointer vectors.
16986   if (EltTy->isPointerTy())
16987     VecTy =
16988         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
16989
16990   IRBuilder<> Builder(LI);
16991
16992   // The base address of the load.
16993   Value *BaseAddr = LI->getPointerOperand();
16994
16995   if (NumLoads > 1) {
16996     // If we're going to generate more than one load, reset the sub-vector type
16997     // to something legal.
16998     VecTy = VectorType::get(VecTy->getVectorElementType(),
16999                             VecTy->getVectorNumElements() / NumLoads);
17000
17001     // We will compute the pointer operand of each load from the original base
17002     // address using GEPs. Cast the base address to a pointer to the scalar
17003     // element type.
17004     BaseAddr = Builder.CreateBitCast(
17005         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
17006                       LI->getPointerAddressSpace()));
17007   }
17008
17009   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
17010
17011   auto createLoadIntrinsic = [&](Value *BaseAddr) {
17012     if (Subtarget->hasNEON()) {
17013       Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
17014       Type *Tys[] = {VecTy, Int8Ptr};
17015       static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
17016                                                 Intrinsic::arm_neon_vld3,
17017                                                 Intrinsic::arm_neon_vld4};
17018       Function *VldnFunc =
17019           Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
17020
17021       SmallVector<Value *, 2> Ops;
17022       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
17023       Ops.push_back(Builder.getInt32(LI->getAlignment()));
17024
17025       return Builder.CreateCall(VldnFunc, Ops, "vldN");
17026     } else {
17027       assert((Factor == 2 || Factor == 4) &&
17028              "expected interleave factor of 2 or 4 for MVE");
17029       Intrinsic::ID LoadInts =
17030           Factor == 2 ? Intrinsic::arm_mve_vld2q : Intrinsic::arm_mve_vld4q;
17031       Type *VecEltTy = VecTy->getVectorElementType()->getPointerTo(
17032           LI->getPointerAddressSpace());
17033       Type *Tys[] = {VecTy, VecEltTy};
17034       Function *VldnFunc =
17035           Intrinsic::getDeclaration(LI->getModule(), LoadInts, Tys);
17036
17037       SmallVector<Value *, 2> Ops;
17038       Ops.push_back(Builder.CreateBitCast(BaseAddr, VecEltTy));
17039       return Builder.CreateCall(VldnFunc, Ops, "vldN");
17040     }
17041   };
17042
17043   // Holds sub-vectors extracted from the load intrinsic return values. The
17044   // sub-vectors are associated with the shufflevector instructions they will
17045   // replace.
17046   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
17047
17048   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
17049     // If we're generating more than one load, compute the base address of
17050     // subsequent loads as an offset from the previous.
17051     if (LoadCount > 0)
17052       BaseAddr =
17053           Builder.CreateConstGEP1_32(VecTy->getVectorElementType(), BaseAddr,
17054                                      VecTy->getVectorNumElements() * Factor);
17055
17056     CallInst *VldN = createLoadIntrinsic(BaseAddr);
17057
17058     // Replace uses of each shufflevector with the corresponding vector loaded
17059     // by ldN.
17060     for (unsigned i = 0; i < Shuffles.size(); i++) {
17061       ShuffleVectorInst *SV = Shuffles[i];
17062       unsigned Index = Indices[i];
17063
17064       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
17065
17066       // Convert the integer vector to pointer vector if the element is pointer.
17067       if (EltTy->isPointerTy())
17068         SubVec = Builder.CreateIntToPtr(
17069             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
17070                                     VecTy->getVectorNumElements()));
17071
17072       SubVecs[SV].push_back(SubVec);
17073     }
17074   }
17075
17076   // Replace uses of the shufflevector instructions with the sub-vectors
17077   // returned by the load intrinsic. If a shufflevector instruction is
17078   // associated with more than one sub-vector, those sub-vectors will be
17079   // concatenated into a single wide vector.
17080   for (ShuffleVectorInst *SVI : Shuffles) {
17081     auto &SubVec = SubVecs[SVI];
17082     auto *WideVec =
17083         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
17084     SVI->replaceAllUsesWith(WideVec);
17085   }
17086
17087   return true;
17088 }
17089
17090 /// Lower an interleaved store into a vstN intrinsic.
17091 ///
17092 /// E.g. Lower an interleaved store (Factor = 3):
17093 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
17094 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
17095 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
17096 ///
17097 ///      Into:
17098 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
17099 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
17100 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
17101 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
17102 ///
17103 /// Note that the new shufflevectors will be removed and we'll only generate one
17104 /// vst3 instruction in CodeGen.
17105 ///
17106 /// Example for a more general valid mask (Factor 3). Lower:
17107 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
17108 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
17109 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
17110 ///
17111 ///      Into:
17112 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
17113 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
17114 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
17115 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
17116 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
17117                                               ShuffleVectorInst *SVI,
17118                                               unsigned Factor) const {
17119   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
17120          "Invalid interleave factor");
17121
17122   VectorType *VecTy = SVI->getType();
17123   assert(VecTy->getVectorNumElements() % Factor == 0 &&
17124          "Invalid interleaved store");
17125
17126   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
17127   Type *EltTy = VecTy->getVectorElementType();
17128   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
17129
17130   const DataLayout &DL = SI->getModule()->getDataLayout();
17131
17132   // Skip if we do not have NEON and skip illegal vector types. We can
17133   // "legalize" wide vector types into multiple interleaved accesses as long as
17134   // the vector types are divisible by 128.
17135   if (!isLegalInterleavedAccessType(Factor, SubVecTy, DL))
17136     return false;
17137
17138   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
17139
17140   Value *Op0 = SVI->getOperand(0);
17141   Value *Op1 = SVI->getOperand(1);
17142   IRBuilder<> Builder(SI);
17143
17144   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
17145   // vectors to integer vectors.
17146   if (EltTy->isPointerTy()) {
17147     Type *IntTy = DL.getIntPtrType(EltTy);
17148
17149     // Convert to the corresponding integer vector.
17150     Type *IntVecTy =
17151         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
17152     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
17153     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
17154
17155     SubVecTy = VectorType::get(IntTy, LaneLen);
17156   }
17157
17158   // The base address of the store.
17159   Value *BaseAddr = SI->getPointerOperand();
17160
17161   if (NumStores > 1) {
17162     // If we're going to generate more than one store, reset the lane length
17163     // and sub-vector type to something legal.
17164     LaneLen /= NumStores;
17165     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
17166
17167     // We will compute the pointer operand of each store from the original base
17168     // address using GEPs. Cast the base address to a pointer to the scalar
17169     // element type.
17170     BaseAddr = Builder.CreateBitCast(
17171         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
17172                       SI->getPointerAddressSpace()));
17173   }
17174
17175   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
17176
17177   auto Mask = SVI->getShuffleMask();
17178
17179   auto createStoreIntrinsic = [&](Value *BaseAddr,
17180                                   SmallVectorImpl<Value *> &Shuffles) {
17181     if (Subtarget->hasNEON()) {
17182       static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
17183                                                  Intrinsic::arm_neon_vst3,
17184                                                  Intrinsic::arm_neon_vst4};
17185       Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
17186       Type *Tys[] = {Int8Ptr, SubVecTy};
17187
17188       Function *VstNFunc = Intrinsic::getDeclaration(
17189           SI->getModule(), StoreInts[Factor - 2], Tys);
17190
17191       SmallVector<Value *, 6> Ops;
17192       Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
17193       for (auto S : Shuffles)
17194         Ops.push_back(S);
17195       Ops.push_back(Builder.getInt32(SI->getAlignment()));
17196       Builder.CreateCall(VstNFunc, Ops);
17197     } else {
17198       assert((Factor == 2 || Factor == 4) &&
17199              "expected interleave factor of 2 or 4 for MVE");
17200       Intrinsic::ID StoreInts =
17201           Factor == 2 ? Intrinsic::arm_mve_vst2q : Intrinsic::arm_mve_vst4q;
17202       Type *EltPtrTy = SubVecTy->getVectorElementType()->getPointerTo(
17203           SI->getPointerAddressSpace());
17204       Type *Tys[] = {EltPtrTy, SubVecTy};
17205       Function *VstNFunc =
17206           Intrinsic::getDeclaration(SI->getModule(), StoreInts, Tys);
17207
17208       SmallVector<Value *, 6> Ops;
17209       Ops.push_back(Builder.CreateBitCast(BaseAddr, EltPtrTy));
17210       for (auto S : Shuffles)
17211         Ops.push_back(S);
17212       for (unsigned F = 0; F < Factor; F++) {
17213         Ops.push_back(Builder.getInt32(F));
17214         Builder.CreateCall(VstNFunc, Ops);
17215         Ops.pop_back();
17216       }
17217     }
17218   };
17219
17220   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
17221     // If we generating more than one store, we compute the base address of
17222     // subsequent stores as an offset from the previous.
17223     if (StoreCount > 0)
17224       BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getVectorElementType(),
17225                                             BaseAddr, LaneLen * Factor);
17226
17227     SmallVector<Value *, 4> Shuffles;
17228
17229     // Split the shufflevector operands into sub vectors for the new vstN call.
17230     for (unsigned i = 0; i < Factor; i++) {
17231       unsigned IdxI = StoreCount * LaneLen * Factor + i;
17232       if (Mask[IdxI] >= 0) {
17233         Shuffles.push_back(Builder.CreateShuffleVector(
17234             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
17235       } else {
17236         unsigned StartMask = 0;
17237         for (unsigned j = 1; j < LaneLen; j++) {
17238           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
17239           if (Mask[IdxJ * Factor + IdxI] >= 0) {
17240             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
17241             break;
17242           }
17243         }
17244         // Note: If all elements in a chunk are undefs, StartMask=0!
17245         // Note: Filling undef gaps with random elements is ok, since
17246         // those elements were being written anyway (with undefs).
17247         // In the case of all undefs we're defaulting to using elems from 0
17248         // Note: StartMask cannot be negative, it's checked in
17249         // isReInterleaveMask
17250         Shuffles.push_back(Builder.CreateShuffleVector(
17251             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
17252       }
17253     }
17254
17255     createStoreIntrinsic(BaseAddr, Shuffles);
17256   }
17257   return true;
17258 }
17259
17260 enum HABaseType {
17261   HA_UNKNOWN = 0,
17262   HA_FLOAT,
17263   HA_DOUBLE,
17264   HA_VECT64,
17265   HA_VECT128
17266 };
17267
17268 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
17269                                    uint64_t &Members) {
17270   if (auto *ST = dyn_cast<StructType>(Ty)) {
17271     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
17272       uint64_t SubMembers = 0;
17273       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
17274         return false;
17275       Members += SubMembers;
17276     }
17277   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
17278     uint64_t SubMembers = 0;
17279     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
17280       return false;
17281     Members += SubMembers * AT->getNumElements();
17282   } else if (Ty->isFloatTy()) {
17283     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
17284       return false;
17285     Members = 1;
17286     Base = HA_FLOAT;
17287   } else if (Ty->isDoubleTy()) {
17288     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
17289       return false;
17290     Members = 1;
17291     Base = HA_DOUBLE;
17292   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
17293     Members = 1;
17294     switch (Base) {
17295     case HA_FLOAT:
17296     case HA_DOUBLE:
17297       return false;
17298     case HA_VECT64:
17299       return VT->getBitWidth() == 64;
17300     case HA_VECT128:
17301       return VT->getBitWidth() == 128;
17302     case HA_UNKNOWN:
17303       switch (VT->getBitWidth()) {
17304       case 64:
17305         Base = HA_VECT64;
17306         return true;
17307       case 128:
17308         Base = HA_VECT128;
17309         return true;
17310       default:
17311         return false;
17312       }
17313     }
17314   }
17315
17316   return (Members > 0 && Members <= 4);
17317 }
17318
17319 /// Return the correct alignment for the current calling convention.
17320 Align ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
17321                                                        DataLayout DL) const {
17322   const Align ABITypeAlign(DL.getABITypeAlignment(ArgTy));
17323   if (!ArgTy->isVectorTy())
17324     return ABITypeAlign;
17325
17326   // Avoid over-aligning vector parameters. It would require realigning the
17327   // stack and waste space for no real benefit.
17328   return std::min(ABITypeAlign, DL.getStackAlignment());
17329 }
17330
17331 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
17332 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
17333 /// passing according to AAPCS rules.
17334 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
17335     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
17336   if (getEffectiveCallingConv(CallConv, isVarArg) !=
17337       CallingConv::ARM_AAPCS_VFP)
17338     return false;
17339
17340   HABaseType Base = HA_UNKNOWN;
17341   uint64_t Members = 0;
17342   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
17343   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
17344
17345   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
17346   return IsHA || IsIntArray;
17347 }
17348
17349 unsigned ARMTargetLowering::getExceptionPointerRegister(
17350     const Constant *PersonalityFn) const {
17351   // Platforms which do not use SjLj EH may return values in these registers
17352   // via the personality function.
17353   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
17354 }
17355
17356 unsigned ARMTargetLowering::getExceptionSelectorRegister(
17357     const Constant *PersonalityFn) const {
17358   // Platforms which do not use SjLj EH may return values in these registers
17359   // via the personality function.
17360   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
17361 }
17362
17363 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
17364   // Update IsSplitCSR in ARMFunctionInfo.
17365   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
17366   AFI->setIsSplitCSR(true);
17367 }
17368
17369 void ARMTargetLowering::insertCopiesSplitCSR(
17370     MachineBasicBlock *Entry,
17371     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
17372   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
17373   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
17374   if (!IStart)
17375     return;
17376
17377   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
17378   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
17379   MachineBasicBlock::iterator MBBI = Entry->begin();
17380   for (const MCPhysReg *I = IStart; *I; ++I) {
17381     const TargetRegisterClass *RC = nullptr;
17382     if (ARM::GPRRegClass.contains(*I))
17383       RC = &ARM::GPRRegClass;
17384     else if (ARM::DPRRegClass.contains(*I))
17385       RC = &ARM::DPRRegClass;
17386     else
17387       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
17388
17389     Register NewVR = MRI->createVirtualRegister(RC);
17390     // Create copy from CSR to a virtual register.
17391     // FIXME: this currently does not emit CFI pseudo-instructions, it works
17392     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
17393     // nounwind. If we want to generalize this later, we may need to emit
17394     // CFI pseudo-instructions.
17395     assert(Entry->getParent()->getFunction().hasFnAttribute(
17396                Attribute::NoUnwind) &&
17397            "Function should be nounwind in insertCopiesSplitCSR!");
17398     Entry->addLiveIn(*I);
17399     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
17400         .addReg(*I);
17401
17402     // Insert the copy-back instructions right before the terminator.
17403     for (auto *Exit : Exits)
17404       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
17405               TII->get(TargetOpcode::COPY), *I)
17406           .addReg(NewVR);
17407   }
17408 }
17409
17410 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
17411   MF.getFrameInfo().computeMaxCallFrameSize(MF);
17412   TargetLoweringBase::finalizeLowering(MF);
17413 }