1 //===-- ARMISelLowering.cpp - ARM DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARMISelLowering.h"
16 #include "ARMCallingConv.h"
17 #include "ARMConstantPoolValue.h"
18 #include "ARMMachineFunctionInfo.h"
19 #include "ARMPerfectShuffle.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "ARMTargetObjectFile.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineBasicBlock.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/DebugInfoMetadata.h"
41 #include "llvm/IR/GlobalValue.h"
42 #include "llvm/IR/IRBuilder.h"
43 #include "llvm/IR/Instruction.h"
44 #include "llvm/IR/Instructions.h"
45 #include "llvm/IR/IntrinsicInst.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/IR/Type.h"
48 #include "llvm/MC/MCSectionMachO.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include <utility>
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "arm-isel"
59 
60 STATISTIC(NumTailCalls, "Number of tail calls");
61 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
62 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
63 STATISTIC(NumConstpoolPromoted,
64   "Number of constants with their storage promoted into constant pools");
65 
66 static cl::opt<bool>
67 ARMInterworking("arm-interworking", cl::Hidden,
68   cl::desc("Enable / disable ARM interworking (for debugging only)"),
69   cl::init(true));
70 
71 static cl::opt<bool> EnableConstpoolPromotion(
72     "arm-promote-constant", cl::Hidden,
73     cl::desc("Enable / disable promotion of unnamed_addr constants into "
74              "constant pools"),
75     cl::init(true));
76 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
77     "arm-promote-constant-max-size", cl::Hidden,
78     cl::desc("Maximum size of constant to promote into a constant pool"),
79     cl::init(64));
80 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
81     "arm-promote-constant-max-total", cl::Hidden,
82     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
83     cl::init(128));
84 
85 namespace {
86   class ARMCCState : public CCState {
87   public:
88     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
89                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
90                ParmContext PC)
91         : CCState(CC, isVarArg, MF, locs, C) {
92       assert(((PC == Call) || (PC == Prologue)) &&
93              "ARMCCState users must specify whether their context is call"
94              "or prologue generation.");
95       CallOrPrologue = PC;
96     }
97   };
98 }
99 
100 void ARMTargetLowering::InitLibcallCallingConvs() {
101   // The builtins on ARM always use AAPCS, irrespective of wheter C is AAPCS or
102   // AAPCS_VFP.
103   for (const auto LC : {
104            RTLIB::SHL_I16,
105            RTLIB::SHL_I32,
106            RTLIB::SHL_I64,
107            RTLIB::SHL_I128,
108            RTLIB::SRL_I16,
109            RTLIB::SRL_I32,
110            RTLIB::SRL_I64,
111            RTLIB::SRL_I128,
112            RTLIB::SRA_I16,
113            RTLIB::SRA_I32,
114            RTLIB::SRA_I64,
115            RTLIB::SRA_I128,
116            RTLIB::MUL_I8,
117            RTLIB::MUL_I16,
118            RTLIB::MUL_I32,
119            RTLIB::MUL_I64,
120            RTLIB::MUL_I128,
121            RTLIB::MULO_I32,
122            RTLIB::MULO_I64,
123            RTLIB::MULO_I128,
124            RTLIB::SDIV_I8,
125            RTLIB::SDIV_I16,
126            RTLIB::SDIV_I32,
127            RTLIB::SDIV_I64,
128            RTLIB::SDIV_I128,
129            RTLIB::UDIV_I8,
130            RTLIB::UDIV_I16,
131            RTLIB::UDIV_I32,
132            RTLIB::UDIV_I64,
133            RTLIB::UDIV_I128,
134            RTLIB::SREM_I8,
135            RTLIB::SREM_I16,
136            RTLIB::SREM_I32,
137            RTLIB::SREM_I64,
138            RTLIB::SREM_I128,
139            RTLIB::UREM_I8,
140            RTLIB::UREM_I16,
141            RTLIB::UREM_I32,
142            RTLIB::UREM_I64,
143            RTLIB::UREM_I128,
144            RTLIB::SDIVREM_I8,
145            RTLIB::SDIVREM_I16,
146            RTLIB::SDIVREM_I32,
147            RTLIB::SDIVREM_I64,
148            RTLIB::SDIVREM_I128,
149            RTLIB::UDIVREM_I8,
150            RTLIB::UDIVREM_I16,
151            RTLIB::UDIVREM_I32,
152            RTLIB::UDIVREM_I64,
153            RTLIB::UDIVREM_I128,
154            RTLIB::NEG_I32,
155            RTLIB::NEG_I64,
156            RTLIB::ADD_F32,
157            RTLIB::ADD_F64,
158            RTLIB::ADD_F80,
159            RTLIB::ADD_F128,
160            RTLIB::SUB_F32,
161            RTLIB::SUB_F64,
162            RTLIB::SUB_F80,
163            RTLIB::SUB_F128,
164            RTLIB::MUL_F32,
165            RTLIB::MUL_F64,
166            RTLIB::MUL_F80,
167            RTLIB::MUL_F128,
168            RTLIB::DIV_F32,
169            RTLIB::DIV_F64,
170            RTLIB::DIV_F80,
171            RTLIB::DIV_F128,
172            RTLIB::POWI_F32,
173            RTLIB::POWI_F64,
174            RTLIB::POWI_F80,
175            RTLIB::POWI_F128,
176            RTLIB::FPEXT_F64_F128,
177            RTLIB::FPEXT_F32_F128,
178            RTLIB::FPEXT_F32_F64,
179            RTLIB::FPEXT_F16_F32,
180            RTLIB::FPROUND_F32_F16,
181            RTLIB::FPROUND_F64_F16,
182            RTLIB::FPROUND_F80_F16,
183            RTLIB::FPROUND_F128_F16,
184            RTLIB::FPROUND_F64_F32,
185            RTLIB::FPROUND_F80_F32,
186            RTLIB::FPROUND_F128_F32,
187            RTLIB::FPROUND_F80_F64,
188            RTLIB::FPROUND_F128_F64,
189            RTLIB::FPTOSINT_F32_I32,
190            RTLIB::FPTOSINT_F32_I64,
191            RTLIB::FPTOSINT_F32_I128,
192            RTLIB::FPTOSINT_F64_I32,
193            RTLIB::FPTOSINT_F64_I64,
194            RTLIB::FPTOSINT_F64_I128,
195            RTLIB::FPTOSINT_F80_I32,
196            RTLIB::FPTOSINT_F80_I64,
197            RTLIB::FPTOSINT_F80_I128,
198            RTLIB::FPTOSINT_F128_I32,
199            RTLIB::FPTOSINT_F128_I64,
200            RTLIB::FPTOSINT_F128_I128,
201            RTLIB::FPTOUINT_F32_I32,
202            RTLIB::FPTOUINT_F32_I64,
203            RTLIB::FPTOUINT_F32_I128,
204            RTLIB::FPTOUINT_F64_I32,
205            RTLIB::FPTOUINT_F64_I64,
206            RTLIB::FPTOUINT_F64_I128,
207            RTLIB::FPTOUINT_F80_I32,
208            RTLIB::FPTOUINT_F80_I64,
209            RTLIB::FPTOUINT_F80_I128,
210            RTLIB::FPTOUINT_F128_I32,
211            RTLIB::FPTOUINT_F128_I64,
212            RTLIB::FPTOUINT_F128_I128,
213            RTLIB::SINTTOFP_I32_F32,
214            RTLIB::SINTTOFP_I32_F64,
215            RTLIB::SINTTOFP_I32_F80,
216            RTLIB::SINTTOFP_I32_F128,
217            RTLIB::SINTTOFP_I64_F32,
218            RTLIB::SINTTOFP_I64_F64,
219            RTLIB::SINTTOFP_I64_F80,
220            RTLIB::SINTTOFP_I64_F128,
221            RTLIB::SINTTOFP_I128_F32,
222            RTLIB::SINTTOFP_I128_F64,
223            RTLIB::SINTTOFP_I128_F80,
224            RTLIB::SINTTOFP_I128_F128,
225            RTLIB::UINTTOFP_I32_F32,
226            RTLIB::UINTTOFP_I32_F64,
227            RTLIB::UINTTOFP_I32_F80,
228            RTLIB::UINTTOFP_I32_F128,
229            RTLIB::UINTTOFP_I64_F32,
230            RTLIB::UINTTOFP_I64_F64,
231            RTLIB::UINTTOFP_I64_F80,
232            RTLIB::UINTTOFP_I64_F128,
233            RTLIB::UINTTOFP_I128_F32,
234            RTLIB::UINTTOFP_I128_F64,
235            RTLIB::UINTTOFP_I128_F80,
236            RTLIB::UINTTOFP_I128_F128,
237            RTLIB::OEQ_F32,
238            RTLIB::OEQ_F64,
239            RTLIB::OEQ_F128,
240            RTLIB::UNE_F32,
241            RTLIB::UNE_F64,
242            RTLIB::UNE_F128,
243            RTLIB::OGE_F32,
244            RTLIB::OGE_F64,
245            RTLIB::OGE_F128,
246            RTLIB::OLT_F32,
247            RTLIB::OLT_F64,
248            RTLIB::OLT_F128,
249            RTLIB::OLE_F32,
250            RTLIB::OLE_F64,
251            RTLIB::OLE_F128,
252            RTLIB::OGT_F32,
253            RTLIB::OGT_F64,
254            RTLIB::OGT_F128,
255            RTLIB::UO_F32,
256            RTLIB::UO_F64,
257            RTLIB::UO_F128,
258            RTLIB::O_F32,
259            RTLIB::O_F64,
260            RTLIB::O_F128,
261        })
262   setLibcallCallingConv(LC, CallingConv::ARM_AAPCS);
263 }
264 
265 // The APCS parameter registers.
266 static const MCPhysReg GPRArgRegs[] = {
267   ARM::R0, ARM::R1, ARM::R2, ARM::R3
268 };
269 
270 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
271                                        MVT PromotedBitwiseVT) {
272   if (VT != PromotedLdStVT) {
273     setOperationAction(ISD::LOAD, VT, Promote);
274     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
275 
276     setOperationAction(ISD::STORE, VT, Promote);
277     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
278   }
279 
280   MVT ElemTy = VT.getVectorElementType();
281   if (ElemTy != MVT::f64)
282     setOperationAction(ISD::SETCC, VT, Custom);
283   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
284   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
285   if (ElemTy == MVT::i32) {
286     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
287     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
288     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
289     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
290   } else {
291     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
292     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
293     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
294     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
295   }
296   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
297   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
298   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
299   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
300   setOperationAction(ISD::SELECT,            VT, Expand);
301   setOperationAction(ISD::SELECT_CC,         VT, Expand);
302   setOperationAction(ISD::VSELECT,           VT, Expand);
303   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
304   if (VT.isInteger()) {
305     setOperationAction(ISD::SHL, VT, Custom);
306     setOperationAction(ISD::SRA, VT, Custom);
307     setOperationAction(ISD::SRL, VT, Custom);
308   }
309 
310   // Promote all bit-wise operations.
311   if (VT.isInteger() && VT != PromotedBitwiseVT) {
312     setOperationAction(ISD::AND, VT, Promote);
313     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
314     setOperationAction(ISD::OR,  VT, Promote);
315     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
316     setOperationAction(ISD::XOR, VT, Promote);
317     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
318   }
319 
320   // Neon does not support vector divide/remainder operations.
321   setOperationAction(ISD::SDIV, VT, Expand);
322   setOperationAction(ISD::UDIV, VT, Expand);
323   setOperationAction(ISD::FDIV, VT, Expand);
324   setOperationAction(ISD::SREM, VT, Expand);
325   setOperationAction(ISD::UREM, VT, Expand);
326   setOperationAction(ISD::FREM, VT, Expand);
327 
328   if (!VT.isFloatingPoint() &&
329       VT != MVT::v2i64 && VT != MVT::v1i64)
330     for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
331       setOperationAction(Opcode, VT, Legal);
332 }
333 
334 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
335   addRegisterClass(VT, &ARM::DPRRegClass);
336   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
337 }
338 
339 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
340   addRegisterClass(VT, &ARM::DPairRegClass);
341   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
342 }
343 
344 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
345                                      const ARMSubtarget &STI)
346     : TargetLowering(TM), Subtarget(&STI) {
347   RegInfo = Subtarget->getRegisterInfo();
348   Itins = Subtarget->getInstrItineraryData();
349 
350   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
351 
352   InitLibcallCallingConvs();
353 
354   if (Subtarget->isTargetMachO()) {
355     // Uses VFP for Thumb libfuncs if available.
356     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
357         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
358       static const struct {
359         const RTLIB::Libcall Op;
360         const char * const Name;
361         const ISD::CondCode Cond;
362       } LibraryCalls[] = {
363         // Single-precision floating-point arithmetic.
364         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
365         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
366         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
367         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
368 
369         // Double-precision floating-point arithmetic.
370         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
371         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
372         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
373         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
374 
375         // Single-precision comparisons.
376         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
377         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
378         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
379         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
380         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
381         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
382         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
383         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
384 
385         // Double-precision comparisons.
386         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
387         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
388         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
389         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
390         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
391         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
392         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
393         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
394 
395         // Floating-point to integer conversions.
396         // i64 conversions are done via library routines even when generating VFP
397         // instructions, so use the same ones.
398         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
399         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
400         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
401         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
402 
403         // Conversions between floating types.
404         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
405         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
406 
407         // Integer to floating-point conversions.
408         // i64 conversions are done via library routines even when generating VFP
409         // instructions, so use the same ones.
410         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
411         // e.g., __floatunsidf vs. __floatunssidfvfp.
412         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
413         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
414         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
415         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
416       };
417 
418       for (const auto &LC : LibraryCalls) {
419         setLibcallName(LC.Op, LC.Name);
420         if (LC.Cond != ISD::SETCC_INVALID)
421           setCmpLibcallCC(LC.Op, LC.Cond);
422       }
423     }
424 
425     // Set the correct calling convention for ARMv7k WatchOS. It's just
426     // AAPCS_VFP for functions as simple as libcalls.
427     if (Subtarget->isTargetWatchABI()) {
428       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
429         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
430     }
431   }
432 
433   // These libcalls are not available in 32-bit.
434   setLibcallName(RTLIB::SHL_I128, nullptr);
435   setLibcallName(RTLIB::SRL_I128, nullptr);
436   setLibcallName(RTLIB::SRA_I128, nullptr);
437 
438   // RTLIB
439   if (Subtarget->isAAPCS_ABI() &&
440       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
441        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
442     static const struct {
443       const RTLIB::Libcall Op;
444       const char * const Name;
445       const CallingConv::ID CC;
446       const ISD::CondCode Cond;
447     } LibraryCalls[] = {
448       // Double-precision floating-point arithmetic helper functions
449       // RTABI chapter 4.1.2, Table 2
450       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
451       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
452       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
453       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
454 
455       // Double-precision floating-point comparison helper functions
456       // RTABI chapter 4.1.2, Table 3
457       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
458       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
459       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
460       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
461       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
462       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
463       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
464       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
465 
466       // Single-precision floating-point arithmetic helper functions
467       // RTABI chapter 4.1.2, Table 4
468       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
469       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
470       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
471       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
472 
473       // Single-precision floating-point comparison helper functions
474       // RTABI chapter 4.1.2, Table 5
475       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
476       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
477       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
478       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
479       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
480       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
481       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
482       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
483 
484       // Floating-point to integer conversions.
485       // RTABI chapter 4.1.2, Table 6
486       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
487       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
488       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
489       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
490       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
491       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
492       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
493       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
494 
495       // Conversions between floating types.
496       // RTABI chapter 4.1.2, Table 7
497       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
498       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
499       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
500 
501       // Integer to floating-point conversions.
502       // RTABI chapter 4.1.2, Table 8
503       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
504       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
505       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
506       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
507       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
508       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
509       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
510       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
511 
512       // Long long helper functions
513       // RTABI chapter 4.2, Table 9
514       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
515       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
516       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
517       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
518 
519       // Integer division functions
520       // RTABI chapter 4.3.1
521       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
522       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
523       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
524       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
525       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
526       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
527       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
528       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
529     };
530 
531     for (const auto &LC : LibraryCalls) {
532       setLibcallName(LC.Op, LC.Name);
533       setLibcallCallingConv(LC.Op, LC.CC);
534       if (LC.Cond != ISD::SETCC_INVALID)
535         setCmpLibcallCC(LC.Op, LC.Cond);
536     }
537 
538     // EABI dependent RTLIB
539     if (TM.Options.EABIVersion == EABI::EABI4 ||
540         TM.Options.EABIVersion == EABI::EABI5) {
541       static const struct {
542         const RTLIB::Libcall Op;
543         const char *const Name;
544         const CallingConv::ID CC;
545         const ISD::CondCode Cond;
546       } MemOpsLibraryCalls[] = {
547         // Memory operations
548         // RTABI chapter 4.3.4
549         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
550         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
551         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
552       };
553 
554       for (const auto &LC : MemOpsLibraryCalls) {
555         setLibcallName(LC.Op, LC.Name);
556         setLibcallCallingConv(LC.Op, LC.CC);
557         if (LC.Cond != ISD::SETCC_INVALID)
558           setCmpLibcallCC(LC.Op, LC.Cond);
559       }
560     }
561   }
562 
563   if (Subtarget->isTargetWindows()) {
564     static const struct {
565       const RTLIB::Libcall Op;
566       const char * const Name;
567       const CallingConv::ID CC;
568     } LibraryCalls[] = {
569       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
570       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
571       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
572       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
573       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
574       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
575       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
576       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
577     };
578 
579     for (const auto &LC : LibraryCalls) {
580       setLibcallName(LC.Op, LC.Name);
581       setLibcallCallingConv(LC.Op, LC.CC);
582     }
583   }
584 
585   // Use divmod compiler-rt calls for iOS 5.0 and later.
586   if (Subtarget->isTargetWatchOS() ||
587       (Subtarget->isTargetIOS() &&
588        !Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
589     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
590     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
591   }
592 
593   // The half <-> float conversion functions are always soft-float on
594   // non-watchos platforms, but are needed for some targets which use a
595   // hard-float calling convention by default.
596   if (!Subtarget->isTargetWatchABI()) {
597     if (Subtarget->isAAPCS_ABI()) {
598       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
599       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
600       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
601     } else {
602       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
603       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
604       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
605     }
606   }
607 
608   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
609   // a __gnu_ prefix (which is the default).
610   if (Subtarget->isTargetAEABI()) {
611     setLibcallName(RTLIB::FPROUND_F32_F16, "__aeabi_f2h");
612     setLibcallName(RTLIB::FPROUND_F64_F16, "__aeabi_d2h");
613     setLibcallName(RTLIB::FPEXT_F16_F32,   "__aeabi_h2f");
614   }
615 
616   if (Subtarget->isThumb1Only())
617     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
618   else
619     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
620   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
621       !Subtarget->isThumb1Only()) {
622     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
623     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
624   }
625 
626   for (MVT VT : MVT::vector_valuetypes()) {
627     for (MVT InnerVT : MVT::vector_valuetypes()) {
628       setTruncStoreAction(VT, InnerVT, Expand);
629       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
630       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
631       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
632     }
633 
634     setOperationAction(ISD::MULHS, VT, Expand);
635     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
636     setOperationAction(ISD::MULHU, VT, Expand);
637     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
638 
639     setOperationAction(ISD::BSWAP, VT, Expand);
640   }
641 
642   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
643   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
644 
645   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
646   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
647 
648   if (Subtarget->hasNEON()) {
649     addDRTypeForNEON(MVT::v2f32);
650     addDRTypeForNEON(MVT::v8i8);
651     addDRTypeForNEON(MVT::v4i16);
652     addDRTypeForNEON(MVT::v2i32);
653     addDRTypeForNEON(MVT::v1i64);
654 
655     addQRTypeForNEON(MVT::v4f32);
656     addQRTypeForNEON(MVT::v2f64);
657     addQRTypeForNEON(MVT::v16i8);
658     addQRTypeForNEON(MVT::v8i16);
659     addQRTypeForNEON(MVT::v4i32);
660     addQRTypeForNEON(MVT::v2i64);
661 
662     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
663     // neither Neon nor VFP support any arithmetic operations on it.
664     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
665     // supported for v4f32.
666     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
667     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
668     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
669     // FIXME: Code duplication: FDIV and FREM are expanded always, see
670     // ARMTargetLowering::addTypeForNEON method for details.
671     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
672     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
673     // FIXME: Create unittest.
674     // In another words, find a way when "copysign" appears in DAG with vector
675     // operands.
676     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
677     // FIXME: Code duplication: SETCC has custom operation action, see
678     // ARMTargetLowering::addTypeForNEON method for details.
679     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
680     // FIXME: Create unittest for FNEG and for FABS.
681     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
682     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
683     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
684     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
685     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
686     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
687     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
688     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
689     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
690     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
691     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
692     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
693     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
694     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
695     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
696     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
697     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
698     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
699     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
700 
701     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
702     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
703     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
704     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
705     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
706     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
707     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
708     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
709     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
710     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
711     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
712     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
713     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
714     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
715     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
716 
717     // Mark v2f32 intrinsics.
718     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
719     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
720     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
721     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
722     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
723     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
724     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
725     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
726     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
727     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
728     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
729     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
730     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
731     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
732     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
733 
734     // Neon does not support some operations on v1i64 and v2i64 types.
735     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
736     // Custom handling for some quad-vector types to detect VMULL.
737     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
738     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
739     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
740     // Custom handling for some vector types to avoid expensive expansions
741     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
742     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
743     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
744     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
745     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
746     // a destination type that is wider than the source, and nor does
747     // it have a FP_TO_[SU]INT instruction with a narrower destination than
748     // source.
749     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
750     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
751     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
752     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
753 
754     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
755     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
756 
757     // NEON does not have single instruction CTPOP for vectors with element
758     // types wider than 8-bits.  However, custom lowering can leverage the
759     // v8i8/v16i8 vcnt instruction.
760     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
761     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
762     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
763     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
764     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
765     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
766 
767     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
768     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
769 
770     // NEON does not have single instruction CTTZ for vectors.
771     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
772     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
773     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
774     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
775 
776     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
777     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
778     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
779     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
780 
781     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
782     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
783     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
784     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
785 
786     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
787     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
788     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
789     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
790 
791     // NEON only has FMA instructions as of VFP4.
792     if (!Subtarget->hasVFP4()) {
793       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
794       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
795     }
796 
797     setTargetDAGCombine(ISD::INTRINSIC_VOID);
798     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
799     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
800     setTargetDAGCombine(ISD::SHL);
801     setTargetDAGCombine(ISD::SRL);
802     setTargetDAGCombine(ISD::SRA);
803     setTargetDAGCombine(ISD::SIGN_EXTEND);
804     setTargetDAGCombine(ISD::ZERO_EXTEND);
805     setTargetDAGCombine(ISD::ANY_EXTEND);
806     setTargetDAGCombine(ISD::BUILD_VECTOR);
807     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
808     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
809     setTargetDAGCombine(ISD::STORE);
810     setTargetDAGCombine(ISD::FP_TO_SINT);
811     setTargetDAGCombine(ISD::FP_TO_UINT);
812     setTargetDAGCombine(ISD::FDIV);
813     setTargetDAGCombine(ISD::LOAD);
814 
815     // It is legal to extload from v4i8 to v4i16 or v4i32.
816     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
817                    MVT::v2i32}) {
818       for (MVT VT : MVT::integer_vector_valuetypes()) {
819         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
820         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
821         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
822       }
823     }
824   }
825 
826   // ARM and Thumb2 support UMLAL/SMLAL.
827   if (!Subtarget->isThumb1Only())
828     setTargetDAGCombine(ISD::ADDC);
829 
830   if (Subtarget->isFPOnlySP()) {
831     // When targeting a floating-point unit with only single-precision
832     // operations, f64 is legal for the few double-precision instructions which
833     // are present However, no double-precision operations other than moves,
834     // loads and stores are provided by the hardware.
835     setOperationAction(ISD::FADD,       MVT::f64, Expand);
836     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
837     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
838     setOperationAction(ISD::FMA,        MVT::f64, Expand);
839     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
840     setOperationAction(ISD::FREM,       MVT::f64, Expand);
841     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
842     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
843     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
844     setOperationAction(ISD::FABS,       MVT::f64, Expand);
845     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
846     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
847     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
848     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
849     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
850     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
851     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
852     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
853     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
854     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
855     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
856     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
857     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
858     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
859     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
860     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
861     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
862     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
863     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
864     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
865     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
866     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
867     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
868   }
869 
870   computeRegisterProperties(Subtarget->getRegisterInfo());
871 
872   // ARM does not have floating-point extending loads.
873   for (MVT VT : MVT::fp_valuetypes()) {
874     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
875     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
876   }
877 
878   // ... or truncating stores
879   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
880   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
881   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
882 
883   // ARM does not have i1 sign extending load.
884   for (MVT VT : MVT::integer_valuetypes())
885     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
886 
887   // ARM supports all 4 flavors of integer indexed load / store.
888   if (!Subtarget->isThumb1Only()) {
889     for (unsigned im = (unsigned)ISD::PRE_INC;
890          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
891       setIndexedLoadAction(im,  MVT::i1,  Legal);
892       setIndexedLoadAction(im,  MVT::i8,  Legal);
893       setIndexedLoadAction(im,  MVT::i16, Legal);
894       setIndexedLoadAction(im,  MVT::i32, Legal);
895       setIndexedStoreAction(im, MVT::i1,  Legal);
896       setIndexedStoreAction(im, MVT::i8,  Legal);
897       setIndexedStoreAction(im, MVT::i16, Legal);
898       setIndexedStoreAction(im, MVT::i32, Legal);
899     }
900   } else {
901     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
902     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
903     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
904   }
905 
906   setOperationAction(ISD::SADDO, MVT::i32, Custom);
907   setOperationAction(ISD::UADDO, MVT::i32, Custom);
908   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
909   setOperationAction(ISD::USUBO, MVT::i32, Custom);
910 
911   // i64 operation support.
912   setOperationAction(ISD::MUL,     MVT::i64, Expand);
913   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
914   if (Subtarget->isThumb1Only()) {
915     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
916     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
917   }
918   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
919       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
920     setOperationAction(ISD::MULHS, MVT::i32, Expand);
921 
922   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
923   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
924   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
925   setOperationAction(ISD::SRL,       MVT::i64, Custom);
926   setOperationAction(ISD::SRA,       MVT::i64, Custom);
927 
928   if (!Subtarget->isThumb1Only()) {
929     // FIXME: We should do this for Thumb1 as well.
930     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
931     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
932     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
933     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
934   }
935 
936   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
937     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
938 
939   // ARM does not have ROTL.
940   setOperationAction(ISD::ROTL, MVT::i32, Expand);
941   for (MVT VT : MVT::vector_valuetypes()) {
942     setOperationAction(ISD::ROTL, VT, Expand);
943     setOperationAction(ISD::ROTR, VT, Expand);
944   }
945   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
946   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
947   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
948     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
949 
950   // @llvm.readcyclecounter requires the Performance Monitors extension.
951   // Default to the 0 expansion on unsupported platforms.
952   // FIXME: Technically there are older ARM CPUs that have
953   // implementation-specific ways of obtaining this information.
954   if (Subtarget->hasPerfMon())
955     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
956 
957   // Only ARMv6 has BSWAP.
958   if (!Subtarget->hasV6Ops())
959     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
960 
961   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide()
962                                         : Subtarget->hasDivideInARMMode();
963   if (!hasDivide) {
964     // These are expanded into libcalls if the cpu doesn't have HW divider.
965     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
966     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
967   }
968 
969   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
970     setOperationAction(ISD::SDIV, MVT::i32, Custom);
971     setOperationAction(ISD::UDIV, MVT::i32, Custom);
972 
973     setOperationAction(ISD::SDIV, MVT::i64, Custom);
974     setOperationAction(ISD::UDIV, MVT::i64, Custom);
975   }
976 
977   setOperationAction(ISD::SREM,  MVT::i32, Expand);
978   setOperationAction(ISD::UREM,  MVT::i32, Expand);
979   // Register based DivRem for AEABI (RTABI 4.2)
980   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
981       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
982       Subtarget->isTargetWindows()) {
983     setOperationAction(ISD::SREM, MVT::i64, Custom);
984     setOperationAction(ISD::UREM, MVT::i64, Custom);
985     HasStandaloneRem = false;
986 
987     for (const auto &LC :
988          {RTLIB::SDIVREM_I8, RTLIB::SDIVREM_I16, RTLIB::SDIVREM_I32})
989       setLibcallName(LC, Subtarget->isTargetWindows() ? "__rt_sdiv"
990                                                       : "__aeabi_idivmod");
991     setLibcallName(RTLIB::SDIVREM_I64, Subtarget->isTargetWindows()
992                                            ? "__rt_sdiv64"
993                                            : "__aeabi_ldivmod");
994     for (const auto &LC :
995          {RTLIB::UDIVREM_I8, RTLIB::UDIVREM_I16, RTLIB::UDIVREM_I32})
996       setLibcallName(LC, Subtarget->isTargetWindows() ? "__rt_udiv"
997                                                       : "__aeabi_uidivmod");
998     setLibcallName(RTLIB::UDIVREM_I64, Subtarget->isTargetWindows()
999                                            ? "__rt_udiv64"
1000                                            : "__aeabi_uldivmod");
1001 
1002     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
1003     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
1004     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
1005     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
1006     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
1007     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
1008     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
1009     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
1010 
1011     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
1012     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
1013     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
1014     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
1015   } else {
1016     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1017     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1018   }
1019 
1020   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
1021   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
1022   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1023   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
1024 
1025   setOperationAction(ISD::TRAP, MVT::Other, Legal);
1026 
1027   // Use the default implementation.
1028   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
1029   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
1030   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
1031   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
1032   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
1033   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
1034 
1035   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
1036     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
1037   else
1038     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
1039 
1040   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
1041   // the default expansion.
1042   InsertFencesForAtomic = false;
1043   if (Subtarget->hasAnyDataBarrier() &&
1044       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
1045     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
1046     // to ldrex/strex loops already.
1047     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
1048     if (!Subtarget->isThumb() || !Subtarget->isMClass())
1049       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
1050 
1051     // On v8, we have particularly efficient implementations of atomic fences
1052     // if they can be combined with nearby atomic loads and stores.
1053     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
1054       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
1055       InsertFencesForAtomic = true;
1056     }
1057   } else {
1058     // If there's anything we can use as a barrier, go through custom lowering
1059     // for ATOMIC_FENCE.
1060     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1061                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1062 
1063     // Set them all for expansion, which will force libcalls.
1064     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1065     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1066     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1067     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1068     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1069     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1070     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1071     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1072     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1073     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1074     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1075     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1076     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1077     // Unordered/Monotonic case.
1078     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1079     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1080   }
1081 
1082   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1083 
1084   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1085   if (!Subtarget->hasV6Ops()) {
1086     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1087     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1088   }
1089   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1090 
1091   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1092       !Subtarget->isThumb1Only()) {
1093     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1094     // iff target supports vfp2.
1095     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1096     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1097   }
1098 
1099   // We want to custom lower some of our intrinsics.
1100   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1101   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1102   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1103   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1104   if (Subtarget->useSjLjEH())
1105     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1106 
1107   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1108   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1109   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1110   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1111   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1112   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1113   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1114   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1115   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1116 
1117   // Thumb-1 cannot currently select ARMISD::SUBE.
1118   if (!Subtarget->isThumb1Only())
1119     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1120 
1121   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
1122   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1123   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1124   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1125   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1126 
1127   // We don't support sin/cos/fmod/copysign/pow
1128   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1129   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1130   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1131   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1132   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1133   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1134   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1135   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1136   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1137       !Subtarget->isThumb1Only()) {
1138     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1139     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1140   }
1141   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1142   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1143 
1144   if (!Subtarget->hasVFP4()) {
1145     setOperationAction(ISD::FMA, MVT::f64, Expand);
1146     setOperationAction(ISD::FMA, MVT::f32, Expand);
1147   }
1148 
1149   // Various VFP goodness
1150   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1151     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1152     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1153       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1154       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1155     }
1156 
1157     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1158     if (!Subtarget->hasFP16()) {
1159       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1160       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1161     }
1162   }
1163 
1164   // Combine sin / cos into one node or libcall if possible.
1165   if (Subtarget->hasSinCos()) {
1166     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1167     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1168     if (Subtarget->isTargetWatchABI()) {
1169       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
1170       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
1171     }
1172     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
1173       // For iOS, we don't want to the normal expansion of a libcall to
1174       // sincos. We want to issue a libcall to __sincos_stret.
1175       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1176       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1177     }
1178   }
1179 
1180   // FP-ARMv8 implements a lot of rounding-like FP operations.
1181   if (Subtarget->hasFPARMv8()) {
1182     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1183     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1184     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1185     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1186     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1187     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1188     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1189     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1190     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1191     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1192     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1193     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1194 
1195     if (!Subtarget->isFPOnlySP()) {
1196       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1197       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1198       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1199       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1200       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1201       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1202       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1203       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1204     }
1205   }
1206 
1207   if (Subtarget->hasNEON()) {
1208     // vmin and vmax aren't available in a scalar form, so we use
1209     // a NEON instruction with an undef lane instead.
1210     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1211     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1212     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1213     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1214     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1215     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1216   }
1217 
1218   // We have target-specific dag combine patterns for the following nodes:
1219   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1220   setTargetDAGCombine(ISD::ADD);
1221   setTargetDAGCombine(ISD::SUB);
1222   setTargetDAGCombine(ISD::MUL);
1223   setTargetDAGCombine(ISD::AND);
1224   setTargetDAGCombine(ISD::OR);
1225   setTargetDAGCombine(ISD::XOR);
1226 
1227   if (Subtarget->hasV6Ops())
1228     setTargetDAGCombine(ISD::SRL);
1229 
1230   setStackPointerRegisterToSaveRestore(ARM::SP);
1231 
1232   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1233       !Subtarget->hasVFP2())
1234     setSchedulingPreference(Sched::RegPressure);
1235   else
1236     setSchedulingPreference(Sched::Hybrid);
1237 
1238   //// temporary - rewrite interface to use type
1239   MaxStoresPerMemset = 8;
1240   MaxStoresPerMemsetOptSize = 4;
1241   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1242   MaxStoresPerMemcpyOptSize = 2;
1243   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1244   MaxStoresPerMemmoveOptSize = 2;
1245 
1246   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1247   // are at least 4 bytes aligned.
1248   setMinStackArgumentAlignment(4);
1249 
1250   // Prefer likely predicted branches to selects on out-of-order cores.
1251   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1252 
1253   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1254 }
1255 
1256 bool ARMTargetLowering::useSoftFloat() const {
1257   return Subtarget->useSoftFloat();
1258 }
1259 
1260 // FIXME: It might make sense to define the representative register class as the
1261 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1262 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1263 // SPR's representative would be DPR_VFP2. This should work well if register
1264 // pressure tracking were modified such that a register use would increment the
1265 // pressure of the register class's representative and all of it's super
1266 // classes' representatives transitively. We have not implemented this because
1267 // of the difficulty prior to coalescing of modeling operand register classes
1268 // due to the common occurrence of cross class copies and subregister insertions
1269 // and extractions.
1270 std::pair<const TargetRegisterClass *, uint8_t>
1271 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1272                                            MVT VT) const {
1273   const TargetRegisterClass *RRC = nullptr;
1274   uint8_t Cost = 1;
1275   switch (VT.SimpleTy) {
1276   default:
1277     return TargetLowering::findRepresentativeClass(TRI, VT);
1278   // Use DPR as representative register class for all floating point
1279   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1280   // the cost is 1 for both f32 and f64.
1281   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1282   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1283     RRC = &ARM::DPRRegClass;
1284     // When NEON is used for SP, only half of the register file is available
1285     // because operations that define both SP and DP results will be constrained
1286     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1287     // coalescing by double-counting the SP regs. See the FIXME above.
1288     if (Subtarget->useNEONForSinglePrecisionFP())
1289       Cost = 2;
1290     break;
1291   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1292   case MVT::v4f32: case MVT::v2f64:
1293     RRC = &ARM::DPRRegClass;
1294     Cost = 2;
1295     break;
1296   case MVT::v4i64:
1297     RRC = &ARM::DPRRegClass;
1298     Cost = 4;
1299     break;
1300   case MVT::v8i64:
1301     RRC = &ARM::DPRRegClass;
1302     Cost = 8;
1303     break;
1304   }
1305   return std::make_pair(RRC, Cost);
1306 }
1307 
1308 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1309   switch ((ARMISD::NodeType)Opcode) {
1310   case ARMISD::FIRST_NUMBER:  break;
1311   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1312   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1313   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1314   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1315   case ARMISD::CALL:          return "ARMISD::CALL";
1316   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1317   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1318   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1319   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1320   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1321   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1322   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1323   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1324   case ARMISD::CMP:           return "ARMISD::CMP";
1325   case ARMISD::CMN:           return "ARMISD::CMN";
1326   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1327   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1328   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1329   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1330   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1331 
1332   case ARMISD::CMOV:          return "ARMISD::CMOV";
1333 
1334   case ARMISD::SSAT:          return "ARMISD::SSAT";
1335 
1336   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1337   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1338   case ARMISD::RRX:           return "ARMISD::RRX";
1339 
1340   case ARMISD::ADDC:          return "ARMISD::ADDC";
1341   case ARMISD::ADDE:          return "ARMISD::ADDE";
1342   case ARMISD::SUBC:          return "ARMISD::SUBC";
1343   case ARMISD::SUBE:          return "ARMISD::SUBE";
1344 
1345   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1346   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1347 
1348   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1349   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1350   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1351 
1352   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1353 
1354   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1355 
1356   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1357 
1358   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1359 
1360   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1361 
1362   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1363   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1364 
1365   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1366   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1367   case ARMISD::VCGE:          return "ARMISD::VCGE";
1368   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1369   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1370   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1371   case ARMISD::VCGT:          return "ARMISD::VCGT";
1372   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1373   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1374   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1375   case ARMISD::VTST:          return "ARMISD::VTST";
1376 
1377   case ARMISD::VSHL:          return "ARMISD::VSHL";
1378   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1379   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1380   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1381   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1382   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1383   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1384   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1385   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1386   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1387   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1388   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1389   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1390   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1391   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1392   case ARMISD::VSLI:          return "ARMISD::VSLI";
1393   case ARMISD::VSRI:          return "ARMISD::VSRI";
1394   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1395   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1396   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1397   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1398   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1399   case ARMISD::VDUP:          return "ARMISD::VDUP";
1400   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1401   case ARMISD::VEXT:          return "ARMISD::VEXT";
1402   case ARMISD::VREV64:        return "ARMISD::VREV64";
1403   case ARMISD::VREV32:        return "ARMISD::VREV32";
1404   case ARMISD::VREV16:        return "ARMISD::VREV16";
1405   case ARMISD::VZIP:          return "ARMISD::VZIP";
1406   case ARMISD::VUZP:          return "ARMISD::VUZP";
1407   case ARMISD::VTRN:          return "ARMISD::VTRN";
1408   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1409   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1410   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1411   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1412   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1413   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1414   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1415   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1416   case ARMISD::BFI:           return "ARMISD::BFI";
1417   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1418   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1419   case ARMISD::VBSL:          return "ARMISD::VBSL";
1420   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1421   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1422   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1423   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1424   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1425   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1426   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1427   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1428   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1429   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1430   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1431   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1432   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1433   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1434   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1435   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1436   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1437   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1438   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1439   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1440   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1441   }
1442   return nullptr;
1443 }
1444 
1445 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1446                                           EVT VT) const {
1447   if (!VT.isVector())
1448     return getPointerTy(DL);
1449   return VT.changeVectorElementTypeToInteger();
1450 }
1451 
1452 /// getRegClassFor - Return the register class that should be used for the
1453 /// specified value type.
1454 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1455   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1456   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1457   // load / store 4 to 8 consecutive D registers.
1458   if (Subtarget->hasNEON()) {
1459     if (VT == MVT::v4i64)
1460       return &ARM::QQPRRegClass;
1461     if (VT == MVT::v8i64)
1462       return &ARM::QQQQPRRegClass;
1463   }
1464   return TargetLowering::getRegClassFor(VT);
1465 }
1466 
1467 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1468 // source/dest is aligned and the copy size is large enough. We therefore want
1469 // to align such objects passed to memory intrinsics.
1470 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1471                                                unsigned &PrefAlign) const {
1472   if (!isa<MemIntrinsic>(CI))
1473     return false;
1474   MinSize = 8;
1475   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1476   // cycle faster than 4-byte aligned LDM.
1477   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1478   return true;
1479 }
1480 
1481 // Create a fast isel object.
1482 FastISel *
1483 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1484                                   const TargetLibraryInfo *libInfo) const {
1485   return ARM::createFastISel(funcInfo, libInfo);
1486 }
1487 
1488 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1489   unsigned NumVals = N->getNumValues();
1490   if (!NumVals)
1491     return Sched::RegPressure;
1492 
1493   for (unsigned i = 0; i != NumVals; ++i) {
1494     EVT VT = N->getValueType(i);
1495     if (VT == MVT::Glue || VT == MVT::Other)
1496       continue;
1497     if (VT.isFloatingPoint() || VT.isVector())
1498       return Sched::ILP;
1499   }
1500 
1501   if (!N->isMachineOpcode())
1502     return Sched::RegPressure;
1503 
1504   // Load are scheduled for latency even if there instruction itinerary
1505   // is not available.
1506   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1507   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1508 
1509   if (MCID.getNumDefs() == 0)
1510     return Sched::RegPressure;
1511   if (!Itins->isEmpty() &&
1512       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1513     return Sched::ILP;
1514 
1515   return Sched::RegPressure;
1516 }
1517 
1518 //===----------------------------------------------------------------------===//
1519 // Lowering Code
1520 //===----------------------------------------------------------------------===//
1521 
1522 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1523 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1524   switch (CC) {
1525   default: llvm_unreachable("Unknown condition code!");
1526   case ISD::SETNE:  return ARMCC::NE;
1527   case ISD::SETEQ:  return ARMCC::EQ;
1528   case ISD::SETGT:  return ARMCC::GT;
1529   case ISD::SETGE:  return ARMCC::GE;
1530   case ISD::SETLT:  return ARMCC::LT;
1531   case ISD::SETLE:  return ARMCC::LE;
1532   case ISD::SETUGT: return ARMCC::HI;
1533   case ISD::SETUGE: return ARMCC::HS;
1534   case ISD::SETULT: return ARMCC::LO;
1535   case ISD::SETULE: return ARMCC::LS;
1536   }
1537 }
1538 
1539 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1540 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1541                         ARMCC::CondCodes &CondCode2) {
1542   CondCode2 = ARMCC::AL;
1543   switch (CC) {
1544   default: llvm_unreachable("Unknown FP condition!");
1545   case ISD::SETEQ:
1546   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1547   case ISD::SETGT:
1548   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1549   case ISD::SETGE:
1550   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1551   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1552   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1553   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1554   case ISD::SETO:   CondCode = ARMCC::VC; break;
1555   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1556   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1557   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1558   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1559   case ISD::SETLT:
1560   case ISD::SETULT: CondCode = ARMCC::LT; break;
1561   case ISD::SETLE:
1562   case ISD::SETULE: CondCode = ARMCC::LE; break;
1563   case ISD::SETNE:
1564   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1565   }
1566 }
1567 
1568 //===----------------------------------------------------------------------===//
1569 //                      Calling Convention Implementation
1570 //===----------------------------------------------------------------------===//
1571 
1572 #include "ARMGenCallingConv.inc"
1573 
1574 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1575 /// account presence of floating point hardware and calling convention
1576 /// limitations, such as support for variadic functions.
1577 CallingConv::ID
1578 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1579                                            bool isVarArg) const {
1580   switch (CC) {
1581   default:
1582     llvm_unreachable("Unsupported calling convention");
1583   case CallingConv::ARM_AAPCS:
1584   case CallingConv::ARM_APCS:
1585   case CallingConv::GHC:
1586     return CC;
1587   case CallingConv::PreserveMost:
1588     return CallingConv::PreserveMost;
1589   case CallingConv::ARM_AAPCS_VFP:
1590   case CallingConv::Swift:
1591     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1592   case CallingConv::C:
1593     if (!Subtarget->isAAPCS_ABI())
1594       return CallingConv::ARM_APCS;
1595     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1596              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1597              !isVarArg)
1598       return CallingConv::ARM_AAPCS_VFP;
1599     else
1600       return CallingConv::ARM_AAPCS;
1601   case CallingConv::Fast:
1602   case CallingConv::CXX_FAST_TLS:
1603     if (!Subtarget->isAAPCS_ABI()) {
1604       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1605         return CallingConv::Fast;
1606       return CallingConv::ARM_APCS;
1607     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1608       return CallingConv::ARM_AAPCS_VFP;
1609     else
1610       return CallingConv::ARM_AAPCS;
1611   }
1612 }
1613 
1614 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1615 /// CallingConvention.
1616 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1617                                                  bool Return,
1618                                                  bool isVarArg) const {
1619   switch (getEffectiveCallingConv(CC, isVarArg)) {
1620   default:
1621     llvm_unreachable("Unsupported calling convention");
1622   case CallingConv::ARM_APCS:
1623     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1624   case CallingConv::ARM_AAPCS:
1625     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1626   case CallingConv::ARM_AAPCS_VFP:
1627     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1628   case CallingConv::Fast:
1629     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1630   case CallingConv::GHC:
1631     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1632   case CallingConv::PreserveMost:
1633     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1634   }
1635 }
1636 
1637 /// LowerCallResult - Lower the result values of a call into the
1638 /// appropriate copies out of appropriate physical registers.
1639 SDValue ARMTargetLowering::LowerCallResult(
1640     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1641     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1642     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1643     SDValue ThisVal) const {
1644 
1645   // Assign locations to each value returned by this call.
1646   SmallVector<CCValAssign, 16> RVLocs;
1647   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1648                     *DAG.getContext(), Call);
1649   CCInfo.AnalyzeCallResult(Ins,
1650                            CCAssignFnForNode(CallConv, /* Return*/ true,
1651                                              isVarArg));
1652 
1653   // Copy all of the result registers out of their specified physreg.
1654   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1655     CCValAssign VA = RVLocs[i];
1656 
1657     // Pass 'this' value directly from the argument to return value, to avoid
1658     // reg unit interference
1659     if (i == 0 && isThisReturn) {
1660       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1661              "unexpected return calling convention register assignment");
1662       InVals.push_back(ThisVal);
1663       continue;
1664     }
1665 
1666     SDValue Val;
1667     if (VA.needsCustom()) {
1668       // Handle f64 or half of a v2f64.
1669       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1670                                       InFlag);
1671       Chain = Lo.getValue(1);
1672       InFlag = Lo.getValue(2);
1673       VA = RVLocs[++i]; // skip ahead to next loc
1674       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1675                                       InFlag);
1676       Chain = Hi.getValue(1);
1677       InFlag = Hi.getValue(2);
1678       if (!Subtarget->isLittle())
1679         std::swap (Lo, Hi);
1680       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1681 
1682       if (VA.getLocVT() == MVT::v2f64) {
1683         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1684         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1685                           DAG.getConstant(0, dl, MVT::i32));
1686 
1687         VA = RVLocs[++i]; // skip ahead to next loc
1688         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1689         Chain = Lo.getValue(1);
1690         InFlag = Lo.getValue(2);
1691         VA = RVLocs[++i]; // skip ahead to next loc
1692         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1693         Chain = Hi.getValue(1);
1694         InFlag = Hi.getValue(2);
1695         if (!Subtarget->isLittle())
1696           std::swap (Lo, Hi);
1697         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1698         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1699                           DAG.getConstant(1, dl, MVT::i32));
1700       }
1701     } else {
1702       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1703                                InFlag);
1704       Chain = Val.getValue(1);
1705       InFlag = Val.getValue(2);
1706     }
1707 
1708     switch (VA.getLocInfo()) {
1709     default: llvm_unreachable("Unknown loc info!");
1710     case CCValAssign::Full: break;
1711     case CCValAssign::BCvt:
1712       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1713       break;
1714     }
1715 
1716     InVals.push_back(Val);
1717   }
1718 
1719   return Chain;
1720 }
1721 
1722 /// LowerMemOpCallTo - Store the argument to the stack.
1723 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1724                                             SDValue Arg, const SDLoc &dl,
1725                                             SelectionDAG &DAG,
1726                                             const CCValAssign &VA,
1727                                             ISD::ArgFlagsTy Flags) const {
1728   unsigned LocMemOffset = VA.getLocMemOffset();
1729   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1730   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1731                        StackPtr, PtrOff);
1732   return DAG.getStore(
1733       Chain, dl, Arg, PtrOff,
1734       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1735 }
1736 
1737 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1738                                          SDValue Chain, SDValue &Arg,
1739                                          RegsToPassVector &RegsToPass,
1740                                          CCValAssign &VA, CCValAssign &NextVA,
1741                                          SDValue &StackPtr,
1742                                          SmallVectorImpl<SDValue> &MemOpChains,
1743                                          ISD::ArgFlagsTy Flags) const {
1744 
1745   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1746                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1747   unsigned id = Subtarget->isLittle() ? 0 : 1;
1748   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1749 
1750   if (NextVA.isRegLoc())
1751     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1752   else {
1753     assert(NextVA.isMemLoc());
1754     if (!StackPtr.getNode())
1755       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1756                                     getPointerTy(DAG.getDataLayout()));
1757 
1758     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1759                                            dl, DAG, NextVA,
1760                                            Flags));
1761   }
1762 }
1763 
1764 /// LowerCall - Lowering a call into a callseq_start <-
1765 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1766 /// nodes.
1767 SDValue
1768 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1769                              SmallVectorImpl<SDValue> &InVals) const {
1770   SelectionDAG &DAG                     = CLI.DAG;
1771   SDLoc &dl                             = CLI.DL;
1772   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1773   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1774   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1775   SDValue Chain                         = CLI.Chain;
1776   SDValue Callee                        = CLI.Callee;
1777   bool &isTailCall                      = CLI.IsTailCall;
1778   CallingConv::ID CallConv              = CLI.CallConv;
1779   bool doesNotRet                       = CLI.DoesNotReturn;
1780   bool isVarArg                         = CLI.IsVarArg;
1781 
1782   MachineFunction &MF = DAG.getMachineFunction();
1783   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1784   bool isThisReturn   = false;
1785   bool isSibCall      = false;
1786   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1787 
1788   // Disable tail calls if they're not supported.
1789   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1790     isTailCall = false;
1791 
1792   if (isTailCall) {
1793     // Check if it's really possible to do a tail call.
1794     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1795                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1796                                                    Outs, OutVals, Ins, DAG);
1797     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1798       report_fatal_error("failed to perform tail call elimination on a call "
1799                          "site marked musttail");
1800     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1801     // detected sibcalls.
1802     if (isTailCall) {
1803       ++NumTailCalls;
1804       isSibCall = true;
1805     }
1806   }
1807 
1808   // Analyze operands of the call, assigning locations to each operand.
1809   SmallVector<CCValAssign, 16> ArgLocs;
1810   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1811                     *DAG.getContext(), Call);
1812   CCInfo.AnalyzeCallOperands(Outs,
1813                              CCAssignFnForNode(CallConv, /* Return*/ false,
1814                                                isVarArg));
1815 
1816   // Get a count of how many bytes are to be pushed on the stack.
1817   unsigned NumBytes = CCInfo.getNextStackOffset();
1818 
1819   // For tail calls, memory operands are available in our caller's stack.
1820   if (isSibCall)
1821     NumBytes = 0;
1822 
1823   // Adjust the stack pointer for the new arguments...
1824   // These operations are automatically eliminated by the prolog/epilog pass
1825   if (!isSibCall)
1826     Chain = DAG.getCALLSEQ_START(Chain,
1827                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1828 
1829   SDValue StackPtr =
1830       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1831 
1832   RegsToPassVector RegsToPass;
1833   SmallVector<SDValue, 8> MemOpChains;
1834 
1835   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1836   // of tail call optimization, arguments are handled later.
1837   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1838        i != e;
1839        ++i, ++realArgIdx) {
1840     CCValAssign &VA = ArgLocs[i];
1841     SDValue Arg = OutVals[realArgIdx];
1842     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1843     bool isByVal = Flags.isByVal();
1844 
1845     // Promote the value if needed.
1846     switch (VA.getLocInfo()) {
1847     default: llvm_unreachable("Unknown loc info!");
1848     case CCValAssign::Full: break;
1849     case CCValAssign::SExt:
1850       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1851       break;
1852     case CCValAssign::ZExt:
1853       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1854       break;
1855     case CCValAssign::AExt:
1856       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1857       break;
1858     case CCValAssign::BCvt:
1859       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1860       break;
1861     }
1862 
1863     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1864     if (VA.needsCustom()) {
1865       if (VA.getLocVT() == MVT::v2f64) {
1866         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1867                                   DAG.getConstant(0, dl, MVT::i32));
1868         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1869                                   DAG.getConstant(1, dl, MVT::i32));
1870 
1871         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1872                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1873 
1874         VA = ArgLocs[++i]; // skip ahead to next loc
1875         if (VA.isRegLoc()) {
1876           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1877                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1878         } else {
1879           assert(VA.isMemLoc());
1880 
1881           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1882                                                  dl, DAG, VA, Flags));
1883         }
1884       } else {
1885         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1886                          StackPtr, MemOpChains, Flags);
1887       }
1888     } else if (VA.isRegLoc()) {
1889       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1890         assert(VA.getLocVT() == MVT::i32 &&
1891                "unexpected calling convention register assignment");
1892         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1893                "unexpected use of 'returned'");
1894         isThisReturn = true;
1895       }
1896       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1897     } else if (isByVal) {
1898       assert(VA.isMemLoc());
1899       unsigned offset = 0;
1900 
1901       // True if this byval aggregate will be split between registers
1902       // and memory.
1903       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1904       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1905 
1906       if (CurByValIdx < ByValArgsCount) {
1907 
1908         unsigned RegBegin, RegEnd;
1909         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1910 
1911         EVT PtrVT =
1912             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1913         unsigned int i, j;
1914         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1915           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1916           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1917           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1918                                      MachinePointerInfo(),
1919                                      DAG.InferPtrAlignment(AddArg));
1920           MemOpChains.push_back(Load.getValue(1));
1921           RegsToPass.push_back(std::make_pair(j, Load));
1922         }
1923 
1924         // If parameter size outsides register area, "offset" value
1925         // helps us to calculate stack slot for remained part properly.
1926         offset = RegEnd - RegBegin;
1927 
1928         CCInfo.nextInRegsParam();
1929       }
1930 
1931       if (Flags.getByValSize() > 4*offset) {
1932         auto PtrVT = getPointerTy(DAG.getDataLayout());
1933         unsigned LocMemOffset = VA.getLocMemOffset();
1934         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1935         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1936         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1937         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1938         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1939                                            MVT::i32);
1940         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1941                                             MVT::i32);
1942 
1943         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1944         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1945         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1946                                           Ops));
1947       }
1948     } else if (!isSibCall) {
1949       assert(VA.isMemLoc());
1950 
1951       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1952                                              dl, DAG, VA, Flags));
1953     }
1954   }
1955 
1956   if (!MemOpChains.empty())
1957     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1958 
1959   // Build a sequence of copy-to-reg nodes chained together with token chain
1960   // and flag operands which copy the outgoing args into the appropriate regs.
1961   SDValue InFlag;
1962   // Tail call byval lowering might overwrite argument registers so in case of
1963   // tail call optimization the copies to registers are lowered later.
1964   if (!isTailCall)
1965     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1966       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1967                                RegsToPass[i].second, InFlag);
1968       InFlag = Chain.getValue(1);
1969     }
1970 
1971   // For tail calls lower the arguments to the 'real' stack slot.
1972   if (isTailCall) {
1973     // Force all the incoming stack arguments to be loaded from the stack
1974     // before any new outgoing arguments are stored to the stack, because the
1975     // outgoing stack slots may alias the incoming argument stack slots, and
1976     // the alias isn't otherwise explicit. This is slightly more conservative
1977     // than necessary, because it means that each store effectively depends
1978     // on every argument instead of just those arguments it would clobber.
1979 
1980     // Do not flag preceding copytoreg stuff together with the following stuff.
1981     InFlag = SDValue();
1982     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1983       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1984                                RegsToPass[i].second, InFlag);
1985       InFlag = Chain.getValue(1);
1986     }
1987     InFlag = SDValue();
1988   }
1989 
1990   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1991   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1992   // node so that legalize doesn't hack it.
1993   bool isDirect = false;
1994 
1995   const TargetMachine &TM = getTargetMachine();
1996   const Module *Mod = MF.getFunction()->getParent();
1997   const GlobalValue *GV = nullptr;
1998   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1999     GV = G->getGlobal();
2000   bool isStub =
2001       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2002 
2003   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2004   bool isLocalARMFunc = false;
2005   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2006   auto PtrVt = getPointerTy(DAG.getDataLayout());
2007 
2008   if (Subtarget->genLongCalls()) {
2009     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2010            "long-calls codegen is not position independent!");
2011     // Handle a global address or an external symbol. If it's not one of
2012     // those, the target's already in a register, so we don't need to do
2013     // anything extra.
2014     if (isa<GlobalAddressSDNode>(Callee)) {
2015       // Create a constant pool entry for the callee address
2016       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2017       ARMConstantPoolValue *CPV =
2018         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2019 
2020       // Get the address of the callee into a register
2021       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2022       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2023       Callee = DAG.getLoad(
2024           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2025           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2026     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2027       const char *Sym = S->getSymbol();
2028 
2029       // Create a constant pool entry for the callee address
2030       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2031       ARMConstantPoolValue *CPV =
2032         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2033                                       ARMPCLabelIndex, 0);
2034       // Get the address of the callee into a register
2035       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2036       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2037       Callee = DAG.getLoad(
2038           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2039           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2040     }
2041   } else if (isa<GlobalAddressSDNode>(Callee)) {
2042     // If we're optimizing for minimum size and the function is called three or
2043     // more times in this block, we can improve codesize by calling indirectly
2044     // as BLXr has a 16-bit encoding.
2045     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2046     auto *BB = CLI.CS->getParent();
2047     bool PreferIndirect =
2048         Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
2049         count_if(GV->users(), [&BB](const User *U) {
2050           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2051         }) > 2;
2052 
2053     if (!PreferIndirect) {
2054       isDirect = true;
2055       bool isDef = GV->isStrongDefinitionForLinker();
2056 
2057       // ARM call to a local ARM function is predicable.
2058       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2059       // tBX takes a register source operand.
2060       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2061         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2062         Callee = DAG.getNode(
2063             ARMISD::WrapperPIC, dl, PtrVt,
2064             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2065         Callee = DAG.getLoad(
2066             PtrVt, dl, DAG.getEntryNode(), Callee,
2067             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2068             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2069                                      MachineMemOperand::MOInvariant);
2070       } else if (Subtarget->isTargetCOFF()) {
2071         assert(Subtarget->isTargetWindows() &&
2072                "Windows is the only supported COFF target");
2073         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2074                                    ? ARMII::MO_DLLIMPORT
2075                                    : ARMII::MO_NO_FLAG;
2076         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2077                                             TargetFlags);
2078         if (GV->hasDLLImportStorageClass())
2079           Callee =
2080               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2081                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2082                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2083       } else {
2084         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2085       }
2086     }
2087   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2088     isDirect = true;
2089     // tBX takes a register source operand.
2090     const char *Sym = S->getSymbol();
2091     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2092       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2093       ARMConstantPoolValue *CPV =
2094         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2095                                       ARMPCLabelIndex, 4);
2096       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2097       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2098       Callee = DAG.getLoad(
2099           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2100           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2101       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2102       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2103     } else {
2104       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2105     }
2106   }
2107 
2108   // FIXME: handle tail calls differently.
2109   unsigned CallOpc;
2110   if (Subtarget->isThumb()) {
2111     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2112       CallOpc = ARMISD::CALL_NOLINK;
2113     else
2114       CallOpc = ARMISD::CALL;
2115   } else {
2116     if (!isDirect && !Subtarget->hasV5TOps())
2117       CallOpc = ARMISD::CALL_NOLINK;
2118     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2119              // Emit regular call when code size is the priority
2120              !MF.getFunction()->optForMinSize())
2121       // "mov lr, pc; b _foo" to avoid confusing the RSP
2122       CallOpc = ARMISD::CALL_NOLINK;
2123     else
2124       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2125   }
2126 
2127   std::vector<SDValue> Ops;
2128   Ops.push_back(Chain);
2129   Ops.push_back(Callee);
2130 
2131   // Add argument registers to the end of the list so that they are known live
2132   // into the call.
2133   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2134     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2135                                   RegsToPass[i].second.getValueType()));
2136 
2137   // Add a register mask operand representing the call-preserved registers.
2138   if (!isTailCall) {
2139     const uint32_t *Mask;
2140     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2141     if (isThisReturn) {
2142       // For 'this' returns, use the R0-preserving mask if applicable
2143       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2144       if (!Mask) {
2145         // Set isThisReturn to false if the calling convention is not one that
2146         // allows 'returned' to be modeled in this way, so LowerCallResult does
2147         // not try to pass 'this' straight through
2148         isThisReturn = false;
2149         Mask = ARI->getCallPreservedMask(MF, CallConv);
2150       }
2151     } else
2152       Mask = ARI->getCallPreservedMask(MF, CallConv);
2153 
2154     assert(Mask && "Missing call preserved mask for calling convention");
2155     Ops.push_back(DAG.getRegisterMask(Mask));
2156   }
2157 
2158   if (InFlag.getNode())
2159     Ops.push_back(InFlag);
2160 
2161   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2162   if (isTailCall) {
2163     MF.getFrameInfo().setHasTailCall();
2164     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2165   }
2166 
2167   // Returns a chain and a flag for retval copy to use.
2168   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2169   InFlag = Chain.getValue(1);
2170 
2171   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2172                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2173   if (!Ins.empty())
2174     InFlag = Chain.getValue(1);
2175 
2176   // Handle result values, copying them out of physregs into vregs that we
2177   // return.
2178   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2179                          InVals, isThisReturn,
2180                          isThisReturn ? OutVals[0] : SDValue());
2181 }
2182 
2183 /// HandleByVal - Every parameter *after* a byval parameter is passed
2184 /// on the stack.  Remember the next parameter register to allocate,
2185 /// and then confiscate the rest of the parameter registers to insure
2186 /// this.
2187 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2188                                     unsigned Align) const {
2189   assert((State->getCallOrPrologue() == Prologue ||
2190           State->getCallOrPrologue() == Call) &&
2191          "unhandled ParmContext");
2192 
2193   // Byval (as with any stack) slots are always at least 4 byte aligned.
2194   Align = std::max(Align, 4U);
2195 
2196   unsigned Reg = State->AllocateReg(GPRArgRegs);
2197   if (!Reg)
2198     return;
2199 
2200   unsigned AlignInRegs = Align / 4;
2201   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2202   for (unsigned i = 0; i < Waste; ++i)
2203     Reg = State->AllocateReg(GPRArgRegs);
2204 
2205   if (!Reg)
2206     return;
2207 
2208   unsigned Excess = 4 * (ARM::R4 - Reg);
2209 
2210   // Special case when NSAA != SP and parameter size greater than size of
2211   // all remained GPR regs. In that case we can't split parameter, we must
2212   // send it to stack. We also must set NCRN to R4, so waste all
2213   // remained registers.
2214   const unsigned NSAAOffset = State->getNextStackOffset();
2215   if (NSAAOffset != 0 && Size > Excess) {
2216     while (State->AllocateReg(GPRArgRegs))
2217       ;
2218     return;
2219   }
2220 
2221   // First register for byval parameter is the first register that wasn't
2222   // allocated before this method call, so it would be "reg".
2223   // If parameter is small enough to be saved in range [reg, r4), then
2224   // the end (first after last) register would be reg + param-size-in-regs,
2225   // else parameter would be splitted between registers and stack,
2226   // end register would be r4 in this case.
2227   unsigned ByValRegBegin = Reg;
2228   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2229   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2230   // Note, first register is allocated in the beginning of function already,
2231   // allocate remained amount of registers we need.
2232   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2233     State->AllocateReg(GPRArgRegs);
2234   // A byval parameter that is split between registers and memory needs its
2235   // size truncated here.
2236   // In the case where the entire structure fits in registers, we set the
2237   // size in memory to zero.
2238   Size = std::max<int>(Size - Excess, 0);
2239 }
2240 
2241 /// MatchingStackOffset - Return true if the given stack call argument is
2242 /// already available in the same position (relatively) of the caller's
2243 /// incoming argument stack.
2244 static
2245 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2246                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2247                          const TargetInstrInfo *TII) {
2248   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2249   int FI = INT_MAX;
2250   if (Arg.getOpcode() == ISD::CopyFromReg) {
2251     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2252     if (!TargetRegisterInfo::isVirtualRegister(VR))
2253       return false;
2254     MachineInstr *Def = MRI->getVRegDef(VR);
2255     if (!Def)
2256       return false;
2257     if (!Flags.isByVal()) {
2258       if (!TII->isLoadFromStackSlot(*Def, FI))
2259         return false;
2260     } else {
2261       return false;
2262     }
2263   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2264     if (Flags.isByVal())
2265       // ByVal argument is passed in as a pointer but it's now being
2266       // dereferenced. e.g.
2267       // define @foo(%struct.X* %A) {
2268       //   tail call @bar(%struct.X* byval %A)
2269       // }
2270       return false;
2271     SDValue Ptr = Ld->getBasePtr();
2272     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2273     if (!FINode)
2274       return false;
2275     FI = FINode->getIndex();
2276   } else
2277     return false;
2278 
2279   assert(FI != INT_MAX);
2280   if (!MFI.isFixedObjectIndex(FI))
2281     return false;
2282   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2283 }
2284 
2285 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2286 /// for tail call optimization. Targets which want to do tail call
2287 /// optimization should implement this function.
2288 bool
2289 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2290                                                      CallingConv::ID CalleeCC,
2291                                                      bool isVarArg,
2292                                                      bool isCalleeStructRet,
2293                                                      bool isCallerStructRet,
2294                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2295                                     const SmallVectorImpl<SDValue> &OutVals,
2296                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2297                                                      SelectionDAG& DAG) const {
2298   MachineFunction &MF = DAG.getMachineFunction();
2299   const Function *CallerF = MF.getFunction();
2300   CallingConv::ID CallerCC = CallerF->getCallingConv();
2301 
2302   assert(Subtarget->supportsTailCall());
2303 
2304   // Look for obvious safe cases to perform tail call optimization that do not
2305   // require ABI changes. This is what gcc calls sibcall.
2306 
2307   // Do not sibcall optimize vararg calls unless the call site is not passing
2308   // any arguments.
2309   if (isVarArg && !Outs.empty())
2310     return false;
2311 
2312   // Exception-handling functions need a special set of instructions to indicate
2313   // a return to the hardware. Tail-calling another function would probably
2314   // break this.
2315   if (CallerF->hasFnAttribute("interrupt"))
2316     return false;
2317 
2318   // Also avoid sibcall optimization if either caller or callee uses struct
2319   // return semantics.
2320   if (isCalleeStructRet || isCallerStructRet)
2321     return false;
2322 
2323   // Externally-defined functions with weak linkage should not be
2324   // tail-called on ARM when the OS does not support dynamic
2325   // pre-emption of symbols, as the AAELF spec requires normal calls
2326   // to undefined weak functions to be replaced with a NOP or jump to the
2327   // next instruction. The behaviour of branch instructions in this
2328   // situation (as used for tail calls) is implementation-defined, so we
2329   // cannot rely on the linker replacing the tail call with a return.
2330   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2331     const GlobalValue *GV = G->getGlobal();
2332     const Triple &TT = getTargetMachine().getTargetTriple();
2333     if (GV->hasExternalWeakLinkage() &&
2334         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2335       return false;
2336   }
2337 
2338   // Check that the call results are passed in the same way.
2339   LLVMContext &C = *DAG.getContext();
2340   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2341                                   CCAssignFnForNode(CalleeCC, true, isVarArg),
2342                                   CCAssignFnForNode(CallerCC, true, isVarArg)))
2343     return false;
2344   // The callee has to preserve all registers the caller needs to preserve.
2345   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2346   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2347   if (CalleeCC != CallerCC) {
2348     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2349     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2350       return false;
2351   }
2352 
2353   // If Caller's vararg or byval argument has been split between registers and
2354   // stack, do not perform tail call, since part of the argument is in caller's
2355   // local frame.
2356   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2357   if (AFI_Caller->getArgRegsSaveSize())
2358     return false;
2359 
2360   // If the callee takes no arguments then go on to check the results of the
2361   // call.
2362   if (!Outs.empty()) {
2363     // Check if stack adjustment is needed. For now, do not do this if any
2364     // argument is passed on the stack.
2365     SmallVector<CCValAssign, 16> ArgLocs;
2366     ARMCCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C, Call);
2367     CCInfo.AnalyzeCallOperands(Outs,
2368                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2369     if (CCInfo.getNextStackOffset()) {
2370       // Check if the arguments are already laid out in the right way as
2371       // the caller's fixed stack objects.
2372       MachineFrameInfo &MFI = MF.getFrameInfo();
2373       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2374       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2375       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2376            i != e;
2377            ++i, ++realArgIdx) {
2378         CCValAssign &VA = ArgLocs[i];
2379         EVT RegVT = VA.getLocVT();
2380         SDValue Arg = OutVals[realArgIdx];
2381         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2382         if (VA.getLocInfo() == CCValAssign::Indirect)
2383           return false;
2384         if (VA.needsCustom()) {
2385           // f64 and vector types are split into multiple registers or
2386           // register/stack-slot combinations.  The types will not match
2387           // the registers; give up on memory f64 refs until we figure
2388           // out what to do about this.
2389           if (!VA.isRegLoc())
2390             return false;
2391           if (!ArgLocs[++i].isRegLoc())
2392             return false;
2393           if (RegVT == MVT::v2f64) {
2394             if (!ArgLocs[++i].isRegLoc())
2395               return false;
2396             if (!ArgLocs[++i].isRegLoc())
2397               return false;
2398           }
2399         } else if (!VA.isRegLoc()) {
2400           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2401                                    MFI, MRI, TII))
2402             return false;
2403         }
2404       }
2405     }
2406 
2407     const MachineRegisterInfo &MRI = MF.getRegInfo();
2408     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2409       return false;
2410   }
2411 
2412   return true;
2413 }
2414 
2415 bool
2416 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2417                                   MachineFunction &MF, bool isVarArg,
2418                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2419                                   LLVMContext &Context) const {
2420   SmallVector<CCValAssign, 16> RVLocs;
2421   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2422   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2423                                                     isVarArg));
2424 }
2425 
2426 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2427                                     const SDLoc &DL, SelectionDAG &DAG) {
2428   const MachineFunction &MF = DAG.getMachineFunction();
2429   const Function *F = MF.getFunction();
2430 
2431   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2432 
2433   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2434   // version of the "preferred return address". These offsets affect the return
2435   // instruction if this is a return from PL1 without hypervisor extensions.
2436   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2437   //    SWI:     0      "subs pc, lr, #0"
2438   //    ABORT:   +4     "subs pc, lr, #4"
2439   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2440   // UNDEF varies depending on where the exception came from ARM or Thumb
2441   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2442 
2443   int64_t LROffset;
2444   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2445       IntKind == "ABORT")
2446     LROffset = 4;
2447   else if (IntKind == "SWI" || IntKind == "UNDEF")
2448     LROffset = 0;
2449   else
2450     report_fatal_error("Unsupported interrupt attribute. If present, value "
2451                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2452 
2453   RetOps.insert(RetOps.begin() + 1,
2454                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2455 
2456   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2457 }
2458 
2459 SDValue
2460 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2461                                bool isVarArg,
2462                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2463                                const SmallVectorImpl<SDValue> &OutVals,
2464                                const SDLoc &dl, SelectionDAG &DAG) const {
2465 
2466   // CCValAssign - represent the assignment of the return value to a location.
2467   SmallVector<CCValAssign, 16> RVLocs;
2468 
2469   // CCState - Info about the registers and stack slots.
2470   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2471                     *DAG.getContext(), Call);
2472 
2473   // Analyze outgoing return values.
2474   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2475                                                isVarArg));
2476 
2477   SDValue Flag;
2478   SmallVector<SDValue, 4> RetOps;
2479   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2480   bool isLittleEndian = Subtarget->isLittle();
2481 
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2484   AFI->setReturnRegsCount(RVLocs.size());
2485 
2486   // Copy the result values into the output registers.
2487   for (unsigned i = 0, realRVLocIdx = 0;
2488        i != RVLocs.size();
2489        ++i, ++realRVLocIdx) {
2490     CCValAssign &VA = RVLocs[i];
2491     assert(VA.isRegLoc() && "Can only return in registers!");
2492 
2493     SDValue Arg = OutVals[realRVLocIdx];
2494 
2495     switch (VA.getLocInfo()) {
2496     default: llvm_unreachable("Unknown loc info!");
2497     case CCValAssign::Full: break;
2498     case CCValAssign::BCvt:
2499       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2500       break;
2501     }
2502 
2503     if (VA.needsCustom()) {
2504       if (VA.getLocVT() == MVT::v2f64) {
2505         // Extract the first half and return it in two registers.
2506         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2507                                    DAG.getConstant(0, dl, MVT::i32));
2508         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2509                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2510 
2511         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2512                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2513                                  Flag);
2514         Flag = Chain.getValue(1);
2515         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2516         VA = RVLocs[++i]; // skip ahead to next loc
2517         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2518                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2519                                  Flag);
2520         Flag = Chain.getValue(1);
2521         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2522         VA = RVLocs[++i]; // skip ahead to next loc
2523 
2524         // Extract the 2nd half and fall through to handle it as an f64 value.
2525         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2526                           DAG.getConstant(1, dl, MVT::i32));
2527       }
2528       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2529       // available.
2530       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2531                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2532       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2533                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2534                                Flag);
2535       Flag = Chain.getValue(1);
2536       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2537       VA = RVLocs[++i]; // skip ahead to next loc
2538       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2539                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2540                                Flag);
2541     } else
2542       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2543 
2544     // Guarantee that all emitted copies are
2545     // stuck together, avoiding something bad.
2546     Flag = Chain.getValue(1);
2547     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2548   }
2549   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2550   const MCPhysReg *I =
2551       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2552   if (I) {
2553     for (; *I; ++I) {
2554       if (ARM::GPRRegClass.contains(*I))
2555         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2556       else if (ARM::DPRRegClass.contains(*I))
2557         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2558       else
2559         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2560     }
2561   }
2562 
2563   // Update chain and glue.
2564   RetOps[0] = Chain;
2565   if (Flag.getNode())
2566     RetOps.push_back(Flag);
2567 
2568   // CPUs which aren't M-class use a special sequence to return from
2569   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2570   // though we use "subs pc, lr, #N").
2571   //
2572   // M-class CPUs actually use a normal return sequence with a special
2573   // (hardware-provided) value in LR, so the normal code path works.
2574   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2575       !Subtarget->isMClass()) {
2576     if (Subtarget->isThumb1Only())
2577       report_fatal_error("interrupt attribute is not supported in Thumb1");
2578     return LowerInterruptReturn(RetOps, dl, DAG);
2579   }
2580 
2581   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2582 }
2583 
2584 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2585   if (N->getNumValues() != 1)
2586     return false;
2587   if (!N->hasNUsesOfValue(1, 0))
2588     return false;
2589 
2590   SDValue TCChain = Chain;
2591   SDNode *Copy = *N->use_begin();
2592   if (Copy->getOpcode() == ISD::CopyToReg) {
2593     // If the copy has a glue operand, we conservatively assume it isn't safe to
2594     // perform a tail call.
2595     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2596       return false;
2597     TCChain = Copy->getOperand(0);
2598   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2599     SDNode *VMov = Copy;
2600     // f64 returned in a pair of GPRs.
2601     SmallPtrSet<SDNode*, 2> Copies;
2602     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2603          UI != UE; ++UI) {
2604       if (UI->getOpcode() != ISD::CopyToReg)
2605         return false;
2606       Copies.insert(*UI);
2607     }
2608     if (Copies.size() > 2)
2609       return false;
2610 
2611     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2612          UI != UE; ++UI) {
2613       SDValue UseChain = UI->getOperand(0);
2614       if (Copies.count(UseChain.getNode()))
2615         // Second CopyToReg
2616         Copy = *UI;
2617       else {
2618         // We are at the top of this chain.
2619         // If the copy has a glue operand, we conservatively assume it
2620         // isn't safe to perform a tail call.
2621         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2622           return false;
2623         // First CopyToReg
2624         TCChain = UseChain;
2625       }
2626     }
2627   } else if (Copy->getOpcode() == ISD::BITCAST) {
2628     // f32 returned in a single GPR.
2629     if (!Copy->hasOneUse())
2630       return false;
2631     Copy = *Copy->use_begin();
2632     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2633       return false;
2634     // If the copy has a glue operand, we conservatively assume it isn't safe to
2635     // perform a tail call.
2636     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2637       return false;
2638     TCChain = Copy->getOperand(0);
2639   } else {
2640     return false;
2641   }
2642 
2643   bool HasRet = false;
2644   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2645        UI != UE; ++UI) {
2646     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2647         UI->getOpcode() != ARMISD::INTRET_FLAG)
2648       return false;
2649     HasRet = true;
2650   }
2651 
2652   if (!HasRet)
2653     return false;
2654 
2655   Chain = TCChain;
2656   return true;
2657 }
2658 
2659 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2660   if (!Subtarget->supportsTailCall())
2661     return false;
2662 
2663   auto Attr =
2664       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2665   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2666     return false;
2667 
2668   return true;
2669 }
2670 
2671 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2672 // and pass the lower and high parts through.
2673 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2674   SDLoc DL(Op);
2675   SDValue WriteValue = Op->getOperand(2);
2676 
2677   // This function is only supposed to be called for i64 type argument.
2678   assert(WriteValue.getValueType() == MVT::i64
2679           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2680 
2681   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2682                            DAG.getConstant(0, DL, MVT::i32));
2683   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2684                            DAG.getConstant(1, DL, MVT::i32));
2685   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2686   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2687 }
2688 
2689 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2690 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2691 // one of the above mentioned nodes. It has to be wrapped because otherwise
2692 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2693 // be used to form addressing mode. These wrapped nodes will be selected
2694 // into MOVi.
2695 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2696   EVT PtrVT = Op.getValueType();
2697   // FIXME there is no actual debug info here
2698   SDLoc dl(Op);
2699   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2700   SDValue Res;
2701   if (CP->isMachineConstantPoolEntry())
2702     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2703                                     CP->getAlignment());
2704   else
2705     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2706                                     CP->getAlignment());
2707   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2708 }
2709 
2710 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2711   return MachineJumpTableInfo::EK_Inline;
2712 }
2713 
2714 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2715                                              SelectionDAG &DAG) const {
2716   MachineFunction &MF = DAG.getMachineFunction();
2717   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2718   unsigned ARMPCLabelIndex = 0;
2719   SDLoc DL(Op);
2720   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2721   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2722   SDValue CPAddr;
2723   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2724   if (!IsPositionIndependent) {
2725     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2726   } else {
2727     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2728     ARMPCLabelIndex = AFI->createPICLabelUId();
2729     ARMConstantPoolValue *CPV =
2730       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2731                                       ARMCP::CPBlockAddress, PCAdj);
2732     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2733   }
2734   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2735   SDValue Result = DAG.getLoad(
2736       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2737       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2738   if (!IsPositionIndependent)
2739     return Result;
2740   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2741   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2742 }
2743 
2744 /// \brief Convert a TLS address reference into the correct sequence of loads
2745 /// and calls to compute the variable's address for Darwin, and return an
2746 /// SDValue containing the final node.
2747 
2748 /// Darwin only has one TLS scheme which must be capable of dealing with the
2749 /// fully general situation, in the worst case. This means:
2750 ///     + "extern __thread" declaration.
2751 ///     + Defined in a possibly unknown dynamic library.
2752 ///
2753 /// The general system is that each __thread variable has a [3 x i32] descriptor
2754 /// which contains information used by the runtime to calculate the address. The
2755 /// only part of this the compiler needs to know about is the first word, which
2756 /// contains a function pointer that must be called with the address of the
2757 /// entire descriptor in "r0".
2758 ///
2759 /// Since this descriptor may be in a different unit, in general access must
2760 /// proceed along the usual ARM rules. A common sequence to produce is:
2761 ///
2762 ///     movw rT1, :lower16:_var$non_lazy_ptr
2763 ///     movt rT1, :upper16:_var$non_lazy_ptr
2764 ///     ldr r0, [rT1]
2765 ///     ldr rT2, [r0]
2766 ///     blx rT2
2767 ///     [...address now in r0...]
2768 SDValue
2769 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2770                                                SelectionDAG &DAG) const {
2771   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2772   SDLoc DL(Op);
2773 
2774   // First step is to get the address of the actua global symbol. This is where
2775   // the TLS descriptor lives.
2776   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2777 
2778   // The first entry in the descriptor is a function pointer that we must call
2779   // to obtain the address of the variable.
2780   SDValue Chain = DAG.getEntryNode();
2781   SDValue FuncTLVGet = DAG.getLoad(
2782       MVT::i32, DL, Chain, DescAddr,
2783       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2784       /* Alignment = */ 4,
2785       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2786           MachineMemOperand::MOInvariant);
2787   Chain = FuncTLVGet.getValue(1);
2788 
2789   MachineFunction &F = DAG.getMachineFunction();
2790   MachineFrameInfo &MFI = F.getFrameInfo();
2791   MFI.setAdjustsStack(true);
2792 
2793   // TLS calls preserve all registers except those that absolutely must be
2794   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2795   // silly).
2796   auto TRI =
2797       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2798   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2799   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2800 
2801   // Finally, we can make the call. This is just a degenerate version of a
2802   // normal AArch64 call node: r0 takes the address of the descriptor, and
2803   // returns the address of the variable in this thread.
2804   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2805   Chain =
2806       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2807                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2808                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2809   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2810 }
2811 
2812 SDValue
2813 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2814                                                 SelectionDAG &DAG) const {
2815   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2816 
2817   SDValue Chain = DAG.getEntryNode();
2818   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2819   SDLoc DL(Op);
2820 
2821   // Load the current TEB (thread environment block)
2822   SDValue Ops[] = {Chain,
2823                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2824                    DAG.getConstant(15, DL, MVT::i32),
2825                    DAG.getConstant(0, DL, MVT::i32),
2826                    DAG.getConstant(13, DL, MVT::i32),
2827                    DAG.getConstant(0, DL, MVT::i32),
2828                    DAG.getConstant(2, DL, MVT::i32)};
2829   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2830                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2831 
2832   SDValue TEB = CurrentTEB.getValue(0);
2833   Chain = CurrentTEB.getValue(1);
2834 
2835   // Load the ThreadLocalStoragePointer from the TEB
2836   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2837   SDValue TLSArray =
2838       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2839   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2840 
2841   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2842   // offset into the TLSArray.
2843 
2844   // Load the TLS index from the C runtime
2845   SDValue TLSIndex =
2846       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2847   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2848   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2849 
2850   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2851                               DAG.getConstant(2, DL, MVT::i32));
2852   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2853                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2854                             MachinePointerInfo());
2855 
2856   // Get the offset of the start of the .tls section (section base)
2857   const auto *GA = cast<GlobalAddressSDNode>(Op);
2858   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2859   SDValue Offset = DAG.getLoad(
2860       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2861                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2862       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2863 
2864   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2865 }
2866 
2867 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2868 SDValue
2869 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2870                                                  SelectionDAG &DAG) const {
2871   SDLoc dl(GA);
2872   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2873   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2874   MachineFunction &MF = DAG.getMachineFunction();
2875   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2876   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2877   ARMConstantPoolValue *CPV =
2878     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2879                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2880   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2881   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2882   Argument = DAG.getLoad(
2883       PtrVT, dl, DAG.getEntryNode(), Argument,
2884       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2885   SDValue Chain = Argument.getValue(1);
2886 
2887   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2888   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2889 
2890   // call __tls_get_addr.
2891   ArgListTy Args;
2892   ArgListEntry Entry;
2893   Entry.Node = Argument;
2894   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2895   Args.push_back(Entry);
2896 
2897   // FIXME: is there useful debug info available here?
2898   TargetLowering::CallLoweringInfo CLI(DAG);
2899   CLI.setDebugLoc(dl).setChain(Chain)
2900     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2901                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2902 
2903   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2904   return CallResult.first;
2905 }
2906 
2907 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2908 // "local exec" model.
2909 SDValue
2910 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2911                                         SelectionDAG &DAG,
2912                                         TLSModel::Model model) const {
2913   const GlobalValue *GV = GA->getGlobal();
2914   SDLoc dl(GA);
2915   SDValue Offset;
2916   SDValue Chain = DAG.getEntryNode();
2917   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2918   // Get the Thread Pointer
2919   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2920 
2921   if (model == TLSModel::InitialExec) {
2922     MachineFunction &MF = DAG.getMachineFunction();
2923     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2924     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2925     // Initial exec model.
2926     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2927     ARMConstantPoolValue *CPV =
2928       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2929                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2930                                       true);
2931     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2932     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2933     Offset = DAG.getLoad(
2934         PtrVT, dl, Chain, Offset,
2935         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2936     Chain = Offset.getValue(1);
2937 
2938     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2939     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2940 
2941     Offset = DAG.getLoad(
2942         PtrVT, dl, Chain, Offset,
2943         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2944   } else {
2945     // local exec model
2946     assert(model == TLSModel::LocalExec);
2947     ARMConstantPoolValue *CPV =
2948       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2949     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2950     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2951     Offset = DAG.getLoad(
2952         PtrVT, dl, Chain, Offset,
2953         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2954   }
2955 
2956   // The address of the thread local variable is the add of the thread
2957   // pointer with the offset of the variable.
2958   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2959 }
2960 
2961 SDValue
2962 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2963   if (Subtarget->isTargetDarwin())
2964     return LowerGlobalTLSAddressDarwin(Op, DAG);
2965 
2966   if (Subtarget->isTargetWindows())
2967     return LowerGlobalTLSAddressWindows(Op, DAG);
2968 
2969   // TODO: implement the "local dynamic" model
2970   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2971   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2972   if (DAG.getTarget().Options.EmulatedTLS)
2973     return LowerToTLSEmulatedModel(GA, DAG);
2974 
2975   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2976 
2977   switch (model) {
2978     case TLSModel::GeneralDynamic:
2979     case TLSModel::LocalDynamic:
2980       return LowerToTLSGeneralDynamicModel(GA, DAG);
2981     case TLSModel::InitialExec:
2982     case TLSModel::LocalExec:
2983       return LowerToTLSExecModels(GA, DAG, model);
2984   }
2985   llvm_unreachable("bogus TLS model");
2986 }
2987 
2988 /// Return true if all users of V are within function F, looking through
2989 /// ConstantExprs.
2990 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2991   SmallVector<const User*,4> Worklist;
2992   for (auto *U : V->users())
2993     Worklist.push_back(U);
2994   while (!Worklist.empty()) {
2995     auto *U = Worklist.pop_back_val();
2996     if (isa<ConstantExpr>(U)) {
2997       for (auto *UU : U->users())
2998         Worklist.push_back(UU);
2999       continue;
3000     }
3001 
3002     auto *I = dyn_cast<Instruction>(U);
3003     if (!I || I->getParent()->getParent() != F)
3004       return false;
3005   }
3006   return true;
3007 }
3008 
3009 /// Return true if all users of V are within some (any) function, looking through
3010 /// ConstantExprs. In other words, are there any global constant users?
3011 static bool allUsersAreInFunctions(const Value *V) {
3012   SmallVector<const User*,4> Worklist;
3013   for (auto *U : V->users())
3014     Worklist.push_back(U);
3015   while (!Worklist.empty()) {
3016     auto *U = Worklist.pop_back_val();
3017     if (isa<ConstantExpr>(U)) {
3018       for (auto *UU : U->users())
3019         Worklist.push_back(UU);
3020       continue;
3021     }
3022 
3023     if (!isa<Instruction>(U))
3024       return false;
3025   }
3026   return true;
3027 }
3028 
3029 // Return true if T is an integer, float or an array/vector of either.
3030 static bool isSimpleType(Type *T) {
3031   if (T->isIntegerTy() || T->isFloatingPointTy())
3032     return true;
3033   Type *SubT = nullptr;
3034   if (T->isArrayTy())
3035     SubT = T->getArrayElementType();
3036   else if (T->isVectorTy())
3037     SubT = T->getVectorElementType();
3038   else
3039     return false;
3040   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3041 }
3042 
3043 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3044                                      EVT PtrVT, SDLoc dl) {
3045   // If we're creating a pool entry for a constant global with unnamed address,
3046   // and the global is small enough, we can emit it inline into the constant pool
3047   // to save ourselves an indirection.
3048   //
3049   // This is a win if the constant is only used in one function (so it doesn't
3050   // need to be duplicated) or duplicating the constant wouldn't increase code
3051   // size (implying the constant is no larger than 4 bytes).
3052   const Function *F = DAG.getMachineFunction().getFunction();
3053 
3054   // We rely on this decision to inline being idemopotent and unrelated to the
3055   // use-site. We know that if we inline a variable at one use site, we'll
3056   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3057   // doesn't know about this optimization, so bail out if it's enabled else
3058   // we could decide to inline here (and thus never emit the GV) but require
3059   // the GV from fast-isel generated code.
3060   if (!EnableConstpoolPromotion ||
3061       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3062       return SDValue();
3063 
3064   auto *GVar = dyn_cast<GlobalVariable>(GV);
3065   if (!GVar || !GVar->hasInitializer() ||
3066       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3067       !GVar->hasLocalLinkage())
3068     return SDValue();
3069 
3070   // Ensure that we don't try and inline any type that contains pointers. If
3071   // we inline a value that contains relocations, we move the relocations from
3072   // .data to .text which is not ideal.
3073   auto *Init = GVar->getInitializer();
3074   if (!isSimpleType(Init->getType()))
3075     return SDValue();
3076 
3077   // The constant islands pass can only really deal with alignment requests
3078   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3079   // any type wanting greater alignment requirements than 4 bytes. We also
3080   // can only promote constants that are multiples of 4 bytes in size or
3081   // are paddable to a multiple of 4. Currently we only try and pad constants
3082   // that are strings for simplicity.
3083   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3084   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3085   unsigned Align = GVar->getAlignment();
3086   unsigned RequiredPadding = 4 - (Size % 4);
3087   bool PaddingPossible =
3088     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3089   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize)
3090     return SDValue();
3091 
3092   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3093   MachineFunction &MF = DAG.getMachineFunction();
3094   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3095 
3096   // We can't bloat the constant pool too much, else the ConstantIslands pass
3097   // may fail to converge. If we haven't promoted this global yet (it may have
3098   // multiple uses), and promoting it would increase the constant pool size (Sz
3099   // > 4), ensure we have space to do so up to MaxTotal.
3100   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3101     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3102         ConstpoolPromotionMaxTotal)
3103       return SDValue();
3104 
3105   // This is only valid if all users are in a single function OR it has users
3106   // in multiple functions but it no larger than a pointer. We also check if
3107   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3108   // address taken.
3109   if (!allUsersAreInFunction(GVar, F) &&
3110       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3111     return SDValue();
3112 
3113   // We're going to inline this global. Pad it out if needed.
3114   if (RequiredPadding != 4) {
3115     StringRef S = CDAInit->getAsString();
3116 
3117     SmallVector<uint8_t,16> V(S.size());
3118     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3119     while (RequiredPadding--)
3120       V.push_back(0);
3121     Init = ConstantDataArray::get(*DAG.getContext(), V);
3122   }
3123 
3124   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3125   SDValue CPAddr =
3126     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3127   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3128     AFI->markGlobalAsPromotedToConstantPool(GVar);
3129     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3130                                       PaddedSize - 4);
3131   }
3132   ++NumConstpoolPromoted;
3133   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3134 }
3135 
3136 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3137                                                  SelectionDAG &DAG) const {
3138   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3139   SDLoc dl(Op);
3140   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3141   const TargetMachine &TM = getTargetMachine();
3142   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3143     GV = GA->getBaseObject();
3144   bool IsRO =
3145       (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3146       isa<Function>(GV);
3147 
3148   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3149     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3150       return V;
3151 
3152   if (isPositionIndependent()) {
3153     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3154 
3155     MachineFunction &MF = DAG.getMachineFunction();
3156     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3157     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3158     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3159     SDLoc dl(Op);
3160     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3161     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
3162         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
3163         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
3164         /*AddCurrentAddress=*/UseGOT_PREL);
3165     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3166     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3167     SDValue Result = DAG.getLoad(
3168         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3169         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3170     SDValue Chain = Result.getValue(1);
3171     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3172     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3173     if (UseGOT_PREL)
3174       Result =
3175           DAG.getLoad(PtrVT, dl, Chain, Result,
3176                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3177     return Result;
3178   } else if (Subtarget->isROPI() && IsRO) {
3179     // PC-relative.
3180     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3181     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3182     return Result;
3183   } else if (Subtarget->isRWPI() && !IsRO) {
3184     // SB-relative.
3185     ARMConstantPoolValue *CPV =
3186       ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3187     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3188     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3189     SDValue G = DAG.getLoad(
3190         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3191         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3192     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3193     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, G);
3194     return Result;
3195   }
3196 
3197   // If we have T2 ops, we can materialize the address directly via movt/movw
3198   // pair. This is always cheaper.
3199   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3200     ++NumMovwMovt;
3201     // FIXME: Once remat is capable of dealing with instructions with register
3202     // operands, expand this into two nodes.
3203     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3204                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3205   } else {
3206     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3207     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3208     return DAG.getLoad(
3209         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3210         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3211   }
3212 }
3213 
3214 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3215                                                     SelectionDAG &DAG) const {
3216   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3217          "ROPI/RWPI not currently supported for Darwin");
3218   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3219   SDLoc dl(Op);
3220   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3221 
3222   if (Subtarget->useMovt(DAG.getMachineFunction()))
3223     ++NumMovwMovt;
3224 
3225   // FIXME: Once remat is capable of dealing with instructions with register
3226   // operands, expand this into multiple nodes
3227   unsigned Wrapper =
3228       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3229 
3230   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3231   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3232 
3233   if (Subtarget->isGVIndirectSymbol(GV))
3234     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3235                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3236   return Result;
3237 }
3238 
3239 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3240                                                      SelectionDAG &DAG) const {
3241   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3242   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3243          "Windows on ARM expects to use movw/movt");
3244   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3245          "ROPI/RWPI not currently supported for Windows");
3246 
3247   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3248   const ARMII::TOF TargetFlags =
3249     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3250   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3251   SDValue Result;
3252   SDLoc DL(Op);
3253 
3254   ++NumMovwMovt;
3255 
3256   // FIXME: Once remat is capable of dealing with instructions with register
3257   // operands, expand this into two nodes.
3258   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3259                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3260                                                   TargetFlags));
3261   if (GV->hasDLLImportStorageClass())
3262     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3263                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3264   return Result;
3265 }
3266 
3267 SDValue
3268 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3269   SDLoc dl(Op);
3270   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3271   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3272                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3273                      Op.getOperand(1), Val);
3274 }
3275 
3276 SDValue
3277 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3278   SDLoc dl(Op);
3279   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3280                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3281 }
3282 
3283 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3284                                                       SelectionDAG &DAG) const {
3285   SDLoc dl(Op);
3286   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3287                      Op.getOperand(0));
3288 }
3289 
3290 SDValue
3291 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3292                                           const ARMSubtarget *Subtarget) const {
3293   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3294   SDLoc dl(Op);
3295   switch (IntNo) {
3296   default: return SDValue();    // Don't custom lower most intrinsics.
3297   case Intrinsic::arm_rbit: {
3298     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
3299            "RBIT intrinsic must have i32 type!");
3300     return DAG.getNode(ISD::BITREVERSE, dl, MVT::i32, Op.getOperand(1));
3301   }
3302   case Intrinsic::thread_pointer: {
3303     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3304     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3305   }
3306   case Intrinsic::eh_sjlj_lsda: {
3307     MachineFunction &MF = DAG.getMachineFunction();
3308     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3309     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3310     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3311     SDValue CPAddr;
3312     bool IsPositionIndependent = isPositionIndependent();
3313     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3314     ARMConstantPoolValue *CPV =
3315       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
3316                                       ARMCP::CPLSDA, PCAdj);
3317     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3318     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3319     SDValue Result = DAG.getLoad(
3320         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3321         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3322 
3323     if (IsPositionIndependent) {
3324       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3325       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3326     }
3327     return Result;
3328   }
3329   case Intrinsic::arm_neon_vmulls:
3330   case Intrinsic::arm_neon_vmullu: {
3331     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3332       ? ARMISD::VMULLs : ARMISD::VMULLu;
3333     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3334                        Op.getOperand(1), Op.getOperand(2));
3335   }
3336   case Intrinsic::arm_neon_vminnm:
3337   case Intrinsic::arm_neon_vmaxnm: {
3338     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3339       ? ISD::FMINNUM : ISD::FMAXNUM;
3340     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3341                        Op.getOperand(1), Op.getOperand(2));
3342   }
3343   case Intrinsic::arm_neon_vminu:
3344   case Intrinsic::arm_neon_vmaxu: {
3345     if (Op.getValueType().isFloatingPoint())
3346       return SDValue();
3347     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3348       ? ISD::UMIN : ISD::UMAX;
3349     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3350                          Op.getOperand(1), Op.getOperand(2));
3351   }
3352   case Intrinsic::arm_neon_vmins:
3353   case Intrinsic::arm_neon_vmaxs: {
3354     // v{min,max}s is overloaded between signed integers and floats.
3355     if (!Op.getValueType().isFloatingPoint()) {
3356       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3357         ? ISD::SMIN : ISD::SMAX;
3358       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3359                          Op.getOperand(1), Op.getOperand(2));
3360     }
3361     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3362       ? ISD::FMINNAN : ISD::FMAXNAN;
3363     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3364                        Op.getOperand(1), Op.getOperand(2));
3365   }
3366   }
3367 }
3368 
3369 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3370                                  const ARMSubtarget *Subtarget) {
3371   // FIXME: handle "fence singlethread" more efficiently.
3372   SDLoc dl(Op);
3373   if (!Subtarget->hasDataBarrier()) {
3374     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3375     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3376     // here.
3377     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3378            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3379     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3380                        DAG.getConstant(0, dl, MVT::i32));
3381   }
3382 
3383   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3384   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3385   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3386   if (Subtarget->isMClass()) {
3387     // Only a full system barrier exists in the M-class architectures.
3388     Domain = ARM_MB::SY;
3389   } else if (Subtarget->preferISHSTBarriers() &&
3390              Ord == AtomicOrdering::Release) {
3391     // Swift happens to implement ISHST barriers in a way that's compatible with
3392     // Release semantics but weaker than ISH so we'd be fools not to use
3393     // it. Beware: other processors probably don't!
3394     Domain = ARM_MB::ISHST;
3395   }
3396 
3397   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3398                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3399                      DAG.getConstant(Domain, dl, MVT::i32));
3400 }
3401 
3402 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3403                              const ARMSubtarget *Subtarget) {
3404   // ARM pre v5TE and Thumb1 does not have preload instructions.
3405   if (!(Subtarget->isThumb2() ||
3406         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3407     // Just preserve the chain.
3408     return Op.getOperand(0);
3409 
3410   SDLoc dl(Op);
3411   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3412   if (!isRead &&
3413       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3414     // ARMv7 with MP extension has PLDW.
3415     return Op.getOperand(0);
3416 
3417   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3418   if (Subtarget->isThumb()) {
3419     // Invert the bits.
3420     isRead = ~isRead & 1;
3421     isData = ~isData & 1;
3422   }
3423 
3424   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3425                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3426                      DAG.getConstant(isData, dl, MVT::i32));
3427 }
3428 
3429 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3430   MachineFunction &MF = DAG.getMachineFunction();
3431   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3432 
3433   // vastart just stores the address of the VarArgsFrameIndex slot into the
3434   // memory location argument.
3435   SDLoc dl(Op);
3436   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3437   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3438   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3439   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3440                       MachinePointerInfo(SV));
3441 }
3442 
3443 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3444                                                 CCValAssign &NextVA,
3445                                                 SDValue &Root,
3446                                                 SelectionDAG &DAG,
3447                                                 const SDLoc &dl) const {
3448   MachineFunction &MF = DAG.getMachineFunction();
3449   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3450 
3451   const TargetRegisterClass *RC;
3452   if (AFI->isThumb1OnlyFunction())
3453     RC = &ARM::tGPRRegClass;
3454   else
3455     RC = &ARM::GPRRegClass;
3456 
3457   // Transform the arguments stored in physical registers into virtual ones.
3458   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3459   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3460 
3461   SDValue ArgValue2;
3462   if (NextVA.isMemLoc()) {
3463     MachineFrameInfo &MFI = MF.getFrameInfo();
3464     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3465 
3466     // Create load node to retrieve arguments from the stack.
3467     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3468     ArgValue2 = DAG.getLoad(
3469         MVT::i32, dl, Root, FIN,
3470         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3471   } else {
3472     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3473     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3474   }
3475   if (!Subtarget->isLittle())
3476     std::swap (ArgValue, ArgValue2);
3477   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3478 }
3479 
3480 // The remaining GPRs hold either the beginning of variable-argument
3481 // data, or the beginning of an aggregate passed by value (usually
3482 // byval).  Either way, we allocate stack slots adjacent to the data
3483 // provided by our caller, and store the unallocated registers there.
3484 // If this is a variadic function, the va_list pointer will begin with
3485 // these values; otherwise, this reassembles a (byval) structure that
3486 // was split between registers and memory.
3487 // Return: The frame index registers were stored into.
3488 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3489                                       const SDLoc &dl, SDValue &Chain,
3490                                       const Value *OrigArg,
3491                                       unsigned InRegsParamRecordIdx,
3492                                       int ArgOffset, unsigned ArgSize) const {
3493   // Currently, two use-cases possible:
3494   // Case #1. Non-var-args function, and we meet first byval parameter.
3495   //          Setup first unallocated register as first byval register;
3496   //          eat all remained registers
3497   //          (these two actions are performed by HandleByVal method).
3498   //          Then, here, we initialize stack frame with
3499   //          "store-reg" instructions.
3500   // Case #2. Var-args function, that doesn't contain byval parameters.
3501   //          The same: eat all remained unallocated registers,
3502   //          initialize stack frame.
3503 
3504   MachineFunction &MF = DAG.getMachineFunction();
3505   MachineFrameInfo &MFI = MF.getFrameInfo();
3506   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3507   unsigned RBegin, REnd;
3508   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3509     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3510   } else {
3511     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3512     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3513     REnd = ARM::R4;
3514   }
3515 
3516   if (REnd != RBegin)
3517     ArgOffset = -4 * (ARM::R4 - RBegin);
3518 
3519   auto PtrVT = getPointerTy(DAG.getDataLayout());
3520   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3521   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3522 
3523   SmallVector<SDValue, 4> MemOps;
3524   const TargetRegisterClass *RC =
3525       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3526 
3527   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3528     unsigned VReg = MF.addLiveIn(Reg, RC);
3529     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3530     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3531                                  MachinePointerInfo(OrigArg, 4 * i));
3532     MemOps.push_back(Store);
3533     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3534   }
3535 
3536   if (!MemOps.empty())
3537     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3538   return FrameIndex;
3539 }
3540 
3541 // Setup stack frame, the va_list pointer will start from.
3542 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3543                                              const SDLoc &dl, SDValue &Chain,
3544                                              unsigned ArgOffset,
3545                                              unsigned TotalArgRegsSaveSize,
3546                                              bool ForceMutable) const {
3547   MachineFunction &MF = DAG.getMachineFunction();
3548   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3549 
3550   // Try to store any remaining integer argument regs
3551   // to their spots on the stack so that they may be loaded by dereferencing
3552   // the result of va_next.
3553   // If there is no regs to be stored, just point address after last
3554   // argument passed via stack.
3555   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3556                                   CCInfo.getInRegsParamsCount(),
3557                                   CCInfo.getNextStackOffset(), 4);
3558   AFI->setVarArgsFrameIndex(FrameIndex);
3559 }
3560 
3561 SDValue ARMTargetLowering::LowerFormalArguments(
3562     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3563     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3564     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3565   MachineFunction &MF = DAG.getMachineFunction();
3566   MachineFrameInfo &MFI = MF.getFrameInfo();
3567 
3568   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3569 
3570   // Assign locations to all of the incoming arguments.
3571   SmallVector<CCValAssign, 16> ArgLocs;
3572   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3573                     *DAG.getContext(), Prologue);
3574   CCInfo.AnalyzeFormalArguments(Ins,
3575                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3576                                                   isVarArg));
3577 
3578   SmallVector<SDValue, 16> ArgValues;
3579   SDValue ArgValue;
3580   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3581   unsigned CurArgIdx = 0;
3582 
3583   // Initially ArgRegsSaveSize is zero.
3584   // Then we increase this value each time we meet byval parameter.
3585   // We also increase this value in case of varargs function.
3586   AFI->setArgRegsSaveSize(0);
3587 
3588   // Calculate the amount of stack space that we need to allocate to store
3589   // byval and variadic arguments that are passed in registers.
3590   // We need to know this before we allocate the first byval or variadic
3591   // argument, as they will be allocated a stack slot below the CFA (Canonical
3592   // Frame Address, the stack pointer at entry to the function).
3593   unsigned ArgRegBegin = ARM::R4;
3594   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3595     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3596       break;
3597 
3598     CCValAssign &VA = ArgLocs[i];
3599     unsigned Index = VA.getValNo();
3600     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3601     if (!Flags.isByVal())
3602       continue;
3603 
3604     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3605     unsigned RBegin, REnd;
3606     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3607     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3608 
3609     CCInfo.nextInRegsParam();
3610   }
3611   CCInfo.rewindByValRegsInfo();
3612 
3613   int lastInsIndex = -1;
3614   if (isVarArg && MFI.hasVAStart()) {
3615     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3616     if (RegIdx != array_lengthof(GPRArgRegs))
3617       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3618   }
3619 
3620   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3621   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3622   auto PtrVT = getPointerTy(DAG.getDataLayout());
3623 
3624   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3625     CCValAssign &VA = ArgLocs[i];
3626     if (Ins[VA.getValNo()].isOrigArg()) {
3627       std::advance(CurOrigArg,
3628                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3629       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3630     }
3631     // Arguments stored in registers.
3632     if (VA.isRegLoc()) {
3633       EVT RegVT = VA.getLocVT();
3634 
3635       if (VA.needsCustom()) {
3636         // f64 and vector types are split up into multiple registers or
3637         // combinations of registers and stack slots.
3638         if (VA.getLocVT() == MVT::v2f64) {
3639           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3640                                                    Chain, DAG, dl);
3641           VA = ArgLocs[++i]; // skip ahead to next loc
3642           SDValue ArgValue2;
3643           if (VA.isMemLoc()) {
3644             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3645             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3646             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3647                                     MachinePointerInfo::getFixedStack(
3648                                         DAG.getMachineFunction(), FI));
3649           } else {
3650             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3651                                              Chain, DAG, dl);
3652           }
3653           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3654           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3655                                  ArgValue, ArgValue1,
3656                                  DAG.getIntPtrConstant(0, dl));
3657           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3658                                  ArgValue, ArgValue2,
3659                                  DAG.getIntPtrConstant(1, dl));
3660         } else
3661           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3662 
3663       } else {
3664         const TargetRegisterClass *RC;
3665 
3666         if (RegVT == MVT::f32)
3667           RC = &ARM::SPRRegClass;
3668         else if (RegVT == MVT::f64)
3669           RC = &ARM::DPRRegClass;
3670         else if (RegVT == MVT::v2f64)
3671           RC = &ARM::QPRRegClass;
3672         else if (RegVT == MVT::i32)
3673           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3674                                            : &ARM::GPRRegClass;
3675         else
3676           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3677 
3678         // Transform the arguments in physical registers into virtual ones.
3679         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3680         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3681       }
3682 
3683       // If this is an 8 or 16-bit value, it is really passed promoted
3684       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3685       // truncate to the right size.
3686       switch (VA.getLocInfo()) {
3687       default: llvm_unreachable("Unknown loc info!");
3688       case CCValAssign::Full: break;
3689       case CCValAssign::BCvt:
3690         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3691         break;
3692       case CCValAssign::SExt:
3693         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3694                                DAG.getValueType(VA.getValVT()));
3695         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3696         break;
3697       case CCValAssign::ZExt:
3698         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3699                                DAG.getValueType(VA.getValVT()));
3700         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3701         break;
3702       }
3703 
3704       InVals.push_back(ArgValue);
3705 
3706     } else { // VA.isRegLoc()
3707 
3708       // sanity check
3709       assert(VA.isMemLoc());
3710       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3711 
3712       int index = VA.getValNo();
3713 
3714       // Some Ins[] entries become multiple ArgLoc[] entries.
3715       // Process them only once.
3716       if (index != lastInsIndex)
3717         {
3718           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3719           // FIXME: For now, all byval parameter objects are marked mutable.
3720           // This can be changed with more analysis.
3721           // In case of tail call optimization mark all arguments mutable.
3722           // Since they could be overwritten by lowering of arguments in case of
3723           // a tail call.
3724           if (Flags.isByVal()) {
3725             assert(Ins[index].isOrigArg() &&
3726                    "Byval arguments cannot be implicit");
3727             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3728 
3729             int FrameIndex = StoreByValRegs(
3730                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3731                 VA.getLocMemOffset(), Flags.getByValSize());
3732             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3733             CCInfo.nextInRegsParam();
3734           } else {
3735             unsigned FIOffset = VA.getLocMemOffset();
3736             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3737                                            FIOffset, true);
3738 
3739             // Create load nodes to retrieve arguments from the stack.
3740             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3741             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3742                                          MachinePointerInfo::getFixedStack(
3743                                              DAG.getMachineFunction(), FI)));
3744           }
3745           lastInsIndex = index;
3746         }
3747     }
3748   }
3749 
3750   // varargs
3751   if (isVarArg && MFI.hasVAStart())
3752     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3753                          CCInfo.getNextStackOffset(),
3754                          TotalArgRegsSaveSize);
3755 
3756   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3757 
3758   return Chain;
3759 }
3760 
3761 /// isFloatingPointZero - Return true if this is +0.0.
3762 static bool isFloatingPointZero(SDValue Op) {
3763   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3764     return CFP->getValueAPF().isPosZero();
3765   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3766     // Maybe this has already been legalized into the constant pool?
3767     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3768       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3769       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3770         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3771           return CFP->getValueAPF().isPosZero();
3772     }
3773   } else if (Op->getOpcode() == ISD::BITCAST &&
3774              Op->getValueType(0) == MVT::f64) {
3775     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3776     // created by LowerConstantFP().
3777     SDValue BitcastOp = Op->getOperand(0);
3778     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3779         isNullConstant(BitcastOp->getOperand(0)))
3780       return true;
3781   }
3782   return false;
3783 }
3784 
3785 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3786 /// the given operands.
3787 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3788                                      SDValue &ARMcc, SelectionDAG &DAG,
3789                                      const SDLoc &dl) const {
3790   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3791     unsigned C = RHSC->getZExtValue();
3792     if (!isLegalICmpImmediate(C)) {
3793       // Constant does not fit, try adjusting it by one?
3794       switch (CC) {
3795       default: break;
3796       case ISD::SETLT:
3797       case ISD::SETGE:
3798         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3799           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3800           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3801         }
3802         break;
3803       case ISD::SETULT:
3804       case ISD::SETUGE:
3805         if (C != 0 && isLegalICmpImmediate(C-1)) {
3806           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3807           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3808         }
3809         break;
3810       case ISD::SETLE:
3811       case ISD::SETGT:
3812         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3813           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3814           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3815         }
3816         break;
3817       case ISD::SETULE:
3818       case ISD::SETUGT:
3819         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3820           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3821           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3822         }
3823         break;
3824       }
3825     }
3826   }
3827 
3828   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3829   ARMISD::NodeType CompareType;
3830   switch (CondCode) {
3831   default:
3832     CompareType = ARMISD::CMP;
3833     break;
3834   case ARMCC::EQ:
3835   case ARMCC::NE:
3836     // Uses only Z Flag
3837     CompareType = ARMISD::CMPZ;
3838     break;
3839   }
3840   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3841   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3842 }
3843 
3844 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3845 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3846                                      SelectionDAG &DAG, const SDLoc &dl) const {
3847   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3848   SDValue Cmp;
3849   if (!isFloatingPointZero(RHS))
3850     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3851   else
3852     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3853   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3854 }
3855 
3856 /// duplicateCmp - Glue values can have only one use, so this function
3857 /// duplicates a comparison node.
3858 SDValue
3859 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3860   unsigned Opc = Cmp.getOpcode();
3861   SDLoc DL(Cmp);
3862   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3863     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3864 
3865   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3866   Cmp = Cmp.getOperand(0);
3867   Opc = Cmp.getOpcode();
3868   if (Opc == ARMISD::CMPFP)
3869     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3870   else {
3871     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3872     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3873   }
3874   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3875 }
3876 
3877 std::pair<SDValue, SDValue>
3878 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3879                                  SDValue &ARMcc) const {
3880   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3881 
3882   SDValue Value, OverflowCmp;
3883   SDValue LHS = Op.getOperand(0);
3884   SDValue RHS = Op.getOperand(1);
3885   SDLoc dl(Op);
3886 
3887   // FIXME: We are currently always generating CMPs because we don't support
3888   // generating CMN through the backend. This is not as good as the natural
3889   // CMP case because it causes a register dependency and cannot be folded
3890   // later.
3891 
3892   switch (Op.getOpcode()) {
3893   default:
3894     llvm_unreachable("Unknown overflow instruction!");
3895   case ISD::SADDO:
3896     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3897     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3898     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3899     break;
3900   case ISD::UADDO:
3901     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3902     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3903     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3904     break;
3905   case ISD::SSUBO:
3906     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3907     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3908     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3909     break;
3910   case ISD::USUBO:
3911     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3912     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3913     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3914     break;
3915   } // switch (...)
3916 
3917   return std::make_pair(Value, OverflowCmp);
3918 }
3919 
3920 
3921 SDValue
3922 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3923   // Let legalize expand this if it isn't a legal type yet.
3924   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3925     return SDValue();
3926 
3927   SDValue Value, OverflowCmp;
3928   SDValue ARMcc;
3929   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3930   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3931   SDLoc dl(Op);
3932   // We use 0 and 1 as false and true values.
3933   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3934   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3935   EVT VT = Op.getValueType();
3936 
3937   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3938                                  ARMcc, CCR, OverflowCmp);
3939 
3940   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3941   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3942 }
3943 
3944 
3945 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3946   SDValue Cond = Op.getOperand(0);
3947   SDValue SelectTrue = Op.getOperand(1);
3948   SDValue SelectFalse = Op.getOperand(2);
3949   SDLoc dl(Op);
3950   unsigned Opc = Cond.getOpcode();
3951 
3952   if (Cond.getResNo() == 1 &&
3953       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3954        Opc == ISD::USUBO)) {
3955     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3956       return SDValue();
3957 
3958     SDValue Value, OverflowCmp;
3959     SDValue ARMcc;
3960     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3961     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3962     EVT VT = Op.getValueType();
3963 
3964     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3965                    OverflowCmp, DAG);
3966   }
3967 
3968   // Convert:
3969   //
3970   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3971   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3972   //
3973   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3974     const ConstantSDNode *CMOVTrue =
3975       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3976     const ConstantSDNode *CMOVFalse =
3977       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3978 
3979     if (CMOVTrue && CMOVFalse) {
3980       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3981       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3982 
3983       SDValue True;
3984       SDValue False;
3985       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3986         True = SelectTrue;
3987         False = SelectFalse;
3988       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3989         True = SelectFalse;
3990         False = SelectTrue;
3991       }
3992 
3993       if (True.getNode() && False.getNode()) {
3994         EVT VT = Op.getValueType();
3995         SDValue ARMcc = Cond.getOperand(2);
3996         SDValue CCR = Cond.getOperand(3);
3997         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3998         assert(True.getValueType() == VT);
3999         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4000       }
4001     }
4002   }
4003 
4004   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4005   // undefined bits before doing a full-word comparison with zero.
4006   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4007                      DAG.getConstant(1, dl, Cond.getValueType()));
4008 
4009   return DAG.getSelectCC(dl, Cond,
4010                          DAG.getConstant(0, dl, Cond.getValueType()),
4011                          SelectTrue, SelectFalse, ISD::SETNE);
4012 }
4013 
4014 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4015                                  bool &swpCmpOps, bool &swpVselOps) {
4016   // Start by selecting the GE condition code for opcodes that return true for
4017   // 'equality'
4018   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4019       CC == ISD::SETULE)
4020     CondCode = ARMCC::GE;
4021 
4022   // and GT for opcodes that return false for 'equality'.
4023   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4024            CC == ISD::SETULT)
4025     CondCode = ARMCC::GT;
4026 
4027   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4028   // to swap the compare operands.
4029   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4030       CC == ISD::SETULT)
4031     swpCmpOps = true;
4032 
4033   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4034   // If we have an unordered opcode, we need to swap the operands to the VSEL
4035   // instruction (effectively negating the condition).
4036   //
4037   // This also has the effect of swapping which one of 'less' or 'greater'
4038   // returns true, so we also swap the compare operands. It also switches
4039   // whether we return true for 'equality', so we compensate by picking the
4040   // opposite condition code to our original choice.
4041   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4042       CC == ISD::SETUGT) {
4043     swpCmpOps = !swpCmpOps;
4044     swpVselOps = !swpVselOps;
4045     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4046   }
4047 
4048   // 'ordered' is 'anything but unordered', so use the VS condition code and
4049   // swap the VSEL operands.
4050   if (CC == ISD::SETO) {
4051     CondCode = ARMCC::VS;
4052     swpVselOps = true;
4053   }
4054 
4055   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4056   // code and swap the VSEL operands.
4057   if (CC == ISD::SETUNE) {
4058     CondCode = ARMCC::EQ;
4059     swpVselOps = true;
4060   }
4061 }
4062 
4063 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4064                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4065                                    SDValue Cmp, SelectionDAG &DAG) const {
4066   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4067     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4068                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4069     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4070                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4071 
4072     SDValue TrueLow = TrueVal.getValue(0);
4073     SDValue TrueHigh = TrueVal.getValue(1);
4074     SDValue FalseLow = FalseVal.getValue(0);
4075     SDValue FalseHigh = FalseVal.getValue(1);
4076 
4077     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4078                               ARMcc, CCR, Cmp);
4079     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4080                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4081 
4082     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4083   } else {
4084     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4085                        Cmp);
4086   }
4087 }
4088 
4089 static bool isGTorGE(ISD::CondCode CC) {
4090   return CC == ISD::SETGT || CC == ISD::SETGE;
4091 }
4092 
4093 static bool isLTorLE(ISD::CondCode CC) {
4094   return CC == ISD::SETLT || CC == ISD::SETLE;
4095 }
4096 
4097 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4098 // All of these conditions (and their <= and >= counterparts) will do:
4099 //          x < k ? k : x
4100 //          x > k ? x : k
4101 //          k < x ? x : k
4102 //          k > x ? k : x
4103 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4104                             const SDValue TrueVal, const SDValue FalseVal,
4105                             const ISD::CondCode CC, const SDValue K) {
4106   return (isGTorGE(CC) &&
4107           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4108          (isLTorLE(CC) &&
4109           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4110 }
4111 
4112 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4113 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4114                             const SDValue TrueVal, const SDValue FalseVal,
4115                             const ISD::CondCode CC, const SDValue K) {
4116   return (isGTorGE(CC) &&
4117           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4118          (isLTorLE(CC) &&
4119           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4120 }
4121 
4122 // Check if two chained conditionals could be converted into SSAT.
4123 //
4124 // SSAT can replace a set of two conditional selectors that bound a number to an
4125 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4126 //
4127 //     x < -k ? -k : (x > k ? k : x)
4128 //     x < -k ? -k : (x < k ? x : k)
4129 //     x > -k ? (x > k ? k : x) : -k
4130 //     x < k ? (x < -k ? -k : x) : k
4131 //     etc.
4132 //
4133 // It returns true if the conversion can be done, false otherwise.
4134 // Additionally, the variable is returned in parameter V and the constant in K.
4135 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4136                                     uint64_t &K) {
4137 
4138   SDValue LHS1 = Op.getOperand(0);
4139   SDValue RHS1 = Op.getOperand(1);
4140   SDValue TrueVal1 = Op.getOperand(2);
4141   SDValue FalseVal1 = Op.getOperand(3);
4142   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4143 
4144   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4145   if (Op2.getOpcode() != ISD::SELECT_CC)
4146     return false;
4147 
4148   SDValue LHS2 = Op2.getOperand(0);
4149   SDValue RHS2 = Op2.getOperand(1);
4150   SDValue TrueVal2 = Op2.getOperand(2);
4151   SDValue FalseVal2 = Op2.getOperand(3);
4152   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4153 
4154   // Find out which are the constants and which are the variables
4155   // in each conditional
4156   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4157                                                         ? &RHS1
4158                                                         : NULL;
4159   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4160                                                         ? &RHS2
4161                                                         : NULL;
4162   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4163   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4164   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4165   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4166 
4167   // We must detect cases where the original operations worked with 16- or
4168   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4169   // must work with sign-extended values but the select operations return
4170   // the original non-extended value.
4171   SDValue V2TmpReg = V2Tmp;
4172   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4173     V2TmpReg = V2Tmp->getOperand(0);
4174 
4175   // Check that the registers and the constants have the correct values
4176   // in both conditionals
4177   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4178       V2TmpReg != V2)
4179     return false;
4180 
4181   // Figure out which conditional is saturating the lower/upper bound.
4182   const SDValue *LowerCheckOp =
4183       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4184           ? &Op
4185           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2
4186                                                                        : NULL;
4187   const SDValue *UpperCheckOp =
4188       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4189           ? &Op
4190           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2) ? &Op2
4191                                                                        : NULL;
4192 
4193   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4194     return false;
4195 
4196   // Check that the constant in the lower-bound check is
4197   // the opposite of the constant in the upper-bound check
4198   // in 1's complement.
4199   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4200   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4201   int64_t PosVal = std::max(Val1, Val2);
4202 
4203   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4204        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4205       Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
4206 
4207     V = V2;
4208     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4209     return true;
4210   }
4211 
4212   return false;
4213 }
4214 
4215 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4216 
4217   EVT VT = Op.getValueType();
4218   SDLoc dl(Op);
4219 
4220   // Try to convert two saturating conditional selects into a single SSAT
4221   SDValue SatValue;
4222   uint64_t SatConstant;
4223   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4224       isSaturatingConditional(Op, SatValue, SatConstant))
4225     return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4226                        DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4227 
4228   SDValue LHS = Op.getOperand(0);
4229   SDValue RHS = Op.getOperand(1);
4230   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4231   SDValue TrueVal = Op.getOperand(2);
4232   SDValue FalseVal = Op.getOperand(3);
4233 
4234   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4235     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4236                                                     dl);
4237 
4238     // If softenSetCCOperands only returned one value, we should compare it to
4239     // zero.
4240     if (!RHS.getNode()) {
4241       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4242       CC = ISD::SETNE;
4243     }
4244   }
4245 
4246   if (LHS.getValueType() == MVT::i32) {
4247     // Try to generate VSEL on ARMv8.
4248     // The VSEL instruction can't use all the usual ARM condition
4249     // codes: it only has two bits to select the condition code, so it's
4250     // constrained to use only GE, GT, VS and EQ.
4251     //
4252     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4253     // swap the operands of the previous compare instruction (effectively
4254     // inverting the compare condition, swapping 'less' and 'greater') and
4255     // sometimes need to swap the operands to the VSEL (which inverts the
4256     // condition in the sense of firing whenever the previous condition didn't)
4257     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4258                                     TrueVal.getValueType() == MVT::f64)) {
4259       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4260       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4261           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4262         CC = ISD::getSetCCInverse(CC, true);
4263         std::swap(TrueVal, FalseVal);
4264       }
4265     }
4266 
4267     SDValue ARMcc;
4268     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4269     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4270     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4271   }
4272 
4273   ARMCC::CondCodes CondCode, CondCode2;
4274   FPCCToARMCC(CC, CondCode, CondCode2);
4275 
4276   // Try to generate VMAXNM/VMINNM on ARMv8.
4277   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4278                                   TrueVal.getValueType() == MVT::f64)) {
4279     bool swpCmpOps = false;
4280     bool swpVselOps = false;
4281     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4282 
4283     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4284         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4285       if (swpCmpOps)
4286         std::swap(LHS, RHS);
4287       if (swpVselOps)
4288         std::swap(TrueVal, FalseVal);
4289     }
4290   }
4291 
4292   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4293   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
4294   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4295   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4296   if (CondCode2 != ARMCC::AL) {
4297     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4298     // FIXME: Needs another CMP because flag can have but one use.
4299     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
4300     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4301   }
4302   return Result;
4303 }
4304 
4305 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4306 /// to morph to an integer compare sequence.
4307 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4308                            const ARMSubtarget *Subtarget) {
4309   SDNode *N = Op.getNode();
4310   if (!N->hasOneUse())
4311     // Otherwise it requires moving the value from fp to integer registers.
4312     return false;
4313   if (!N->getNumValues())
4314     return false;
4315   EVT VT = Op.getValueType();
4316   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4317     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4318     // vmrs are very slow, e.g. cortex-a8.
4319     return false;
4320 
4321   if (isFloatingPointZero(Op)) {
4322     SeenZero = true;
4323     return true;
4324   }
4325   return ISD::isNormalLoad(N);
4326 }
4327 
4328 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4329   if (isFloatingPointZero(Op))
4330     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4331 
4332   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4333     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4334                        Ld->getPointerInfo(), Ld->getAlignment(),
4335                        Ld->getMemOperand()->getFlags());
4336 
4337   llvm_unreachable("Unknown VFP cmp argument!");
4338 }
4339 
4340 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4341                            SDValue &RetVal1, SDValue &RetVal2) {
4342   SDLoc dl(Op);
4343 
4344   if (isFloatingPointZero(Op)) {
4345     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4346     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4347     return;
4348   }
4349 
4350   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4351     SDValue Ptr = Ld->getBasePtr();
4352     RetVal1 =
4353         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4354                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4355 
4356     EVT PtrType = Ptr.getValueType();
4357     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4358     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4359                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4360     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4361                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4362                           Ld->getMemOperand()->getFlags());
4363     return;
4364   }
4365 
4366   llvm_unreachable("Unknown VFP cmp argument!");
4367 }
4368 
4369 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4370 /// f32 and even f64 comparisons to integer ones.
4371 SDValue
4372 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4373   SDValue Chain = Op.getOperand(0);
4374   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4375   SDValue LHS = Op.getOperand(2);
4376   SDValue RHS = Op.getOperand(3);
4377   SDValue Dest = Op.getOperand(4);
4378   SDLoc dl(Op);
4379 
4380   bool LHSSeenZero = false;
4381   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4382   bool RHSSeenZero = false;
4383   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4384   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4385     // If unsafe fp math optimization is enabled and there are no other uses of
4386     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4387     // to an integer comparison.
4388     if (CC == ISD::SETOEQ)
4389       CC = ISD::SETEQ;
4390     else if (CC == ISD::SETUNE)
4391       CC = ISD::SETNE;
4392 
4393     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4394     SDValue ARMcc;
4395     if (LHS.getValueType() == MVT::f32) {
4396       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4397                         bitcastf32Toi32(LHS, DAG), Mask);
4398       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4399                         bitcastf32Toi32(RHS, DAG), Mask);
4400       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4401       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4402       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4403                          Chain, Dest, ARMcc, CCR, Cmp);
4404     }
4405 
4406     SDValue LHS1, LHS2;
4407     SDValue RHS1, RHS2;
4408     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4409     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4410     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4411     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4412     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4413     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4414     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4415     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4416     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4417   }
4418 
4419   return SDValue();
4420 }
4421 
4422 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4423   SDValue Chain = Op.getOperand(0);
4424   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4425   SDValue LHS = Op.getOperand(2);
4426   SDValue RHS = Op.getOperand(3);
4427   SDValue Dest = Op.getOperand(4);
4428   SDLoc dl(Op);
4429 
4430   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4431     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4432                                                     dl);
4433 
4434     // If softenSetCCOperands only returned one value, we should compare it to
4435     // zero.
4436     if (!RHS.getNode()) {
4437       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4438       CC = ISD::SETNE;
4439     }
4440   }
4441 
4442   if (LHS.getValueType() == MVT::i32) {
4443     SDValue ARMcc;
4444     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4445     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4446     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4447                        Chain, Dest, ARMcc, CCR, Cmp);
4448   }
4449 
4450   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4451 
4452   if (getTargetMachine().Options.UnsafeFPMath &&
4453       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4454        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4455     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4456       return Result;
4457   }
4458 
4459   ARMCC::CondCodes CondCode, CondCode2;
4460   FPCCToARMCC(CC, CondCode, CondCode2);
4461 
4462   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4463   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
4464   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4465   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4466   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4467   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4468   if (CondCode2 != ARMCC::AL) {
4469     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4470     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4471     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4472   }
4473   return Res;
4474 }
4475 
4476 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4477   SDValue Chain = Op.getOperand(0);
4478   SDValue Table = Op.getOperand(1);
4479   SDValue Index = Op.getOperand(2);
4480   SDLoc dl(Op);
4481 
4482   EVT PTy = getPointerTy(DAG.getDataLayout());
4483   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4484   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4485   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4486   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4487   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4488   if (Subtarget->isThumb2()) {
4489     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
4490     // which does another jump to the destination. This also makes it easier
4491     // to translate it to TBB / TBH later.
4492     // FIXME: This might not work if the function is extremely large.
4493     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4494                        Addr, Op.getOperand(2), JTI);
4495   }
4496   if (isPositionIndependent() || Subtarget->isROPI()) {
4497     Addr =
4498         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4499                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4500     Chain = Addr.getValue(1);
4501     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4502     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4503   } else {
4504     Addr =
4505         DAG.getLoad(PTy, dl, Chain, Addr,
4506                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4507     Chain = Addr.getValue(1);
4508     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4509   }
4510 }
4511 
4512 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4513   EVT VT = Op.getValueType();
4514   SDLoc dl(Op);
4515 
4516   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4517     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4518       return Op;
4519     return DAG.UnrollVectorOp(Op.getNode());
4520   }
4521 
4522   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4523          "Invalid type for custom lowering!");
4524   if (VT != MVT::v4i16)
4525     return DAG.UnrollVectorOp(Op.getNode());
4526 
4527   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4528   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4529 }
4530 
4531 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4532   EVT VT = Op.getValueType();
4533   if (VT.isVector())
4534     return LowerVectorFP_TO_INT(Op, DAG);
4535   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4536     RTLIB::Libcall LC;
4537     if (Op.getOpcode() == ISD::FP_TO_SINT)
4538       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4539                               Op.getValueType());
4540     else
4541       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4542                               Op.getValueType());
4543     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4544                        /*isSigned*/ false, SDLoc(Op)).first;
4545   }
4546 
4547   return Op;
4548 }
4549 
4550 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4551   EVT VT = Op.getValueType();
4552   SDLoc dl(Op);
4553 
4554   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4555     if (VT.getVectorElementType() == MVT::f32)
4556       return Op;
4557     return DAG.UnrollVectorOp(Op.getNode());
4558   }
4559 
4560   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4561          "Invalid type for custom lowering!");
4562   if (VT != MVT::v4f32)
4563     return DAG.UnrollVectorOp(Op.getNode());
4564 
4565   unsigned CastOpc;
4566   unsigned Opc;
4567   switch (Op.getOpcode()) {
4568   default: llvm_unreachable("Invalid opcode!");
4569   case ISD::SINT_TO_FP:
4570     CastOpc = ISD::SIGN_EXTEND;
4571     Opc = ISD::SINT_TO_FP;
4572     break;
4573   case ISD::UINT_TO_FP:
4574     CastOpc = ISD::ZERO_EXTEND;
4575     Opc = ISD::UINT_TO_FP;
4576     break;
4577   }
4578 
4579   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4580   return DAG.getNode(Opc, dl, VT, Op);
4581 }
4582 
4583 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4584   EVT VT = Op.getValueType();
4585   if (VT.isVector())
4586     return LowerVectorINT_TO_FP(Op, DAG);
4587   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4588     RTLIB::Libcall LC;
4589     if (Op.getOpcode() == ISD::SINT_TO_FP)
4590       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4591                               Op.getValueType());
4592     else
4593       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4594                               Op.getValueType());
4595     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4596                        /*isSigned*/ false, SDLoc(Op)).first;
4597   }
4598 
4599   return Op;
4600 }
4601 
4602 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4603   // Implement fcopysign with a fabs and a conditional fneg.
4604   SDValue Tmp0 = Op.getOperand(0);
4605   SDValue Tmp1 = Op.getOperand(1);
4606   SDLoc dl(Op);
4607   EVT VT = Op.getValueType();
4608   EVT SrcVT = Tmp1.getValueType();
4609   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4610     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4611   bool UseNEON = !InGPR && Subtarget->hasNEON();
4612 
4613   if (UseNEON) {
4614     // Use VBSL to copy the sign bit.
4615     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4616     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4617                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4618     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4619     if (VT == MVT::f64)
4620       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4621                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4622                          DAG.getConstant(32, dl, MVT::i32));
4623     else /*if (VT == MVT::f32)*/
4624       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4625     if (SrcVT == MVT::f32) {
4626       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4627       if (VT == MVT::f64)
4628         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4629                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4630                            DAG.getConstant(32, dl, MVT::i32));
4631     } else if (VT == MVT::f32)
4632       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4633                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4634                          DAG.getConstant(32, dl, MVT::i32));
4635     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4636     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4637 
4638     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4639                                             dl, MVT::i32);
4640     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4641     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4642                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4643 
4644     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4645                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4646                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4647     if (VT == MVT::f32) {
4648       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4649       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4650                         DAG.getConstant(0, dl, MVT::i32));
4651     } else {
4652       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4653     }
4654 
4655     return Res;
4656   }
4657 
4658   // Bitcast operand 1 to i32.
4659   if (SrcVT == MVT::f64)
4660     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4661                        Tmp1).getValue(1);
4662   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4663 
4664   // Or in the signbit with integer operations.
4665   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4666   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4667   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4668   if (VT == MVT::f32) {
4669     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4670                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4671     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4672                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4673   }
4674 
4675   // f64: Or the high part with signbit and then combine two parts.
4676   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4677                      Tmp0);
4678   SDValue Lo = Tmp0.getValue(0);
4679   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4680   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4681   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4682 }
4683 
4684 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4685   MachineFunction &MF = DAG.getMachineFunction();
4686   MachineFrameInfo &MFI = MF.getFrameInfo();
4687   MFI.setReturnAddressIsTaken(true);
4688 
4689   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4690     return SDValue();
4691 
4692   EVT VT = Op.getValueType();
4693   SDLoc dl(Op);
4694   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4695   if (Depth) {
4696     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4697     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4698     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4699                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4700                        MachinePointerInfo());
4701   }
4702 
4703   // Return LR, which contains the return address. Mark it an implicit live-in.
4704   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4705   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4706 }
4707 
4708 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4709   const ARMBaseRegisterInfo &ARI =
4710     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4711   MachineFunction &MF = DAG.getMachineFunction();
4712   MachineFrameInfo &MFI = MF.getFrameInfo();
4713   MFI.setFrameAddressIsTaken(true);
4714 
4715   EVT VT = Op.getValueType();
4716   SDLoc dl(Op);  // FIXME probably not meaningful
4717   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4718   unsigned FrameReg = ARI.getFrameRegister(MF);
4719   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4720   while (Depth--)
4721     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4722                             MachinePointerInfo());
4723   return FrameAddr;
4724 }
4725 
4726 // FIXME? Maybe this could be a TableGen attribute on some registers and
4727 // this table could be generated automatically from RegInfo.
4728 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4729                                               SelectionDAG &DAG) const {
4730   unsigned Reg = StringSwitch<unsigned>(RegName)
4731                        .Case("sp", ARM::SP)
4732                        .Default(0);
4733   if (Reg)
4734     return Reg;
4735   report_fatal_error(Twine("Invalid register name \""
4736                               + StringRef(RegName)  + "\"."));
4737 }
4738 
4739 // Result is 64 bit value so split into two 32 bit values and return as a
4740 // pair of values.
4741 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4742                                 SelectionDAG &DAG) {
4743   SDLoc DL(N);
4744 
4745   // This function is only supposed to be called for i64 type destination.
4746   assert(N->getValueType(0) == MVT::i64
4747           && "ExpandREAD_REGISTER called for non-i64 type result.");
4748 
4749   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4750                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4751                              N->getOperand(0),
4752                              N->getOperand(1));
4753 
4754   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4755                     Read.getValue(1)));
4756   Results.push_back(Read.getOperand(0));
4757 }
4758 
4759 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4760 /// When \p DstVT, the destination type of \p BC, is on the vector
4761 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4762 /// it might be possible to combine them, such that everything stays on the
4763 /// vector register bank.
4764 /// \p return The node that would replace \p BT, if the combine
4765 /// is possible.
4766 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4767                                                 SelectionDAG &DAG) {
4768   SDValue Op = BC->getOperand(0);
4769   EVT DstVT = BC->getValueType(0);
4770 
4771   // The only vector instruction that can produce a scalar (remember,
4772   // since the bitcast was about to be turned into VMOVDRR, the source
4773   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4774   // Moreover, we can do this combine only if there is one use.
4775   // Finally, if the destination type is not a vector, there is not
4776   // much point on forcing everything on the vector bank.
4777   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4778       !Op.hasOneUse())
4779     return SDValue();
4780 
4781   // If the index is not constant, we will introduce an additional
4782   // multiply that will stick.
4783   // Give up in that case.
4784   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4785   if (!Index)
4786     return SDValue();
4787   unsigned DstNumElt = DstVT.getVectorNumElements();
4788 
4789   // Compute the new index.
4790   const APInt &APIntIndex = Index->getAPIntValue();
4791   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4792   NewIndex *= APIntIndex;
4793   // Check if the new constant index fits into i32.
4794   if (NewIndex.getBitWidth() > 32)
4795     return SDValue();
4796 
4797   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4798   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4799   SDLoc dl(Op);
4800   SDValue ExtractSrc = Op.getOperand(0);
4801   EVT VecVT = EVT::getVectorVT(
4802       *DAG.getContext(), DstVT.getScalarType(),
4803       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4804   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4805   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4806                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4807 }
4808 
4809 /// ExpandBITCAST - If the target supports VFP, this function is called to
4810 /// expand a bit convert where either the source or destination type is i64 to
4811 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4812 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4813 /// vectors), since the legalizer won't know what to do with that.
4814 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4816   SDLoc dl(N);
4817   SDValue Op = N->getOperand(0);
4818 
4819   // This function is only supposed to be called for i64 types, either as the
4820   // source or destination of the bit convert.
4821   EVT SrcVT = Op.getValueType();
4822   EVT DstVT = N->getValueType(0);
4823   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4824          "ExpandBITCAST called for non-i64 type");
4825 
4826   // Turn i64->f64 into VMOVDRR.
4827   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4828     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4829     // if we can combine the bitcast with its source.
4830     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4831       return Val;
4832 
4833     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4834                              DAG.getConstant(0, dl, MVT::i32));
4835     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4836                              DAG.getConstant(1, dl, MVT::i32));
4837     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4838                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4839   }
4840 
4841   // Turn f64->i64 into VMOVRRD.
4842   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4843     SDValue Cvt;
4844     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4845         SrcVT.getVectorNumElements() > 1)
4846       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4847                         DAG.getVTList(MVT::i32, MVT::i32),
4848                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4849     else
4850       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4851                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4852     // Merge the pieces into a single i64 value.
4853     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4854   }
4855 
4856   return SDValue();
4857 }
4858 
4859 /// getZeroVector - Returns a vector of specified type with all zero elements.
4860 /// Zero vectors are used to represent vector negation and in those cases
4861 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4862 /// not support i64 elements, so sometimes the zero vectors will need to be
4863 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4864 /// zero vector.
4865 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4866   assert(VT.isVector() && "Expected a vector type");
4867   // The canonical modified immediate encoding of a zero vector is....0!
4868   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4869   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4870   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4871   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4872 }
4873 
4874 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4875 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4876 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4877                                                 SelectionDAG &DAG) const {
4878   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4879   EVT VT = Op.getValueType();
4880   unsigned VTBits = VT.getSizeInBits();
4881   SDLoc dl(Op);
4882   SDValue ShOpLo = Op.getOperand(0);
4883   SDValue ShOpHi = Op.getOperand(1);
4884   SDValue ShAmt  = Op.getOperand(2);
4885   SDValue ARMcc;
4886   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4887 
4888   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4889 
4890   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4891                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4892   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4893   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4894                                    DAG.getConstant(VTBits, dl, MVT::i32));
4895   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4896   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4897   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4898 
4899   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4900   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4901                           ISD::SETGE, ARMcc, DAG, dl);
4902   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4903   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4904                            CCR, Cmp);
4905 
4906   SDValue Ops[2] = { Lo, Hi };
4907   return DAG.getMergeValues(Ops, dl);
4908 }
4909 
4910 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4911 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4912 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4913                                                SelectionDAG &DAG) const {
4914   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4915   EVT VT = Op.getValueType();
4916   unsigned VTBits = VT.getSizeInBits();
4917   SDLoc dl(Op);
4918   SDValue ShOpLo = Op.getOperand(0);
4919   SDValue ShOpHi = Op.getOperand(1);
4920   SDValue ShAmt  = Op.getOperand(2);
4921   SDValue ARMcc;
4922 
4923   assert(Op.getOpcode() == ISD::SHL_PARTS);
4924   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4925                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4926   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4927   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4928                                    DAG.getConstant(VTBits, dl, MVT::i32));
4929   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4930   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4931 
4932   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4933   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4934   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4935                           ISD::SETGE, ARMcc, DAG, dl);
4936   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4937   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4938                            CCR, Cmp);
4939 
4940   SDValue Ops[2] = { Lo, Hi };
4941   return DAG.getMergeValues(Ops, dl);
4942 }
4943 
4944 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4945                                             SelectionDAG &DAG) const {
4946   // The rounding mode is in bits 23:22 of the FPSCR.
4947   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4948   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4949   // so that the shift + and get folded into a bitfield extract.
4950   SDLoc dl(Op);
4951   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4952                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4953                                               MVT::i32));
4954   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4955                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4956   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4957                               DAG.getConstant(22, dl, MVT::i32));
4958   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4959                      DAG.getConstant(3, dl, MVT::i32));
4960 }
4961 
4962 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4963                          const ARMSubtarget *ST) {
4964   SDLoc dl(N);
4965   EVT VT = N->getValueType(0);
4966   if (VT.isVector()) {
4967     assert(ST->hasNEON());
4968 
4969     // Compute the least significant set bit: LSB = X & -X
4970     SDValue X = N->getOperand(0);
4971     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4972     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4973 
4974     EVT ElemTy = VT.getVectorElementType();
4975 
4976     if (ElemTy == MVT::i8) {
4977       // Compute with: cttz(x) = ctpop(lsb - 1)
4978       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4979                                 DAG.getTargetConstant(1, dl, ElemTy));
4980       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4981       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4982     }
4983 
4984     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4985         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4986       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4987       unsigned NumBits = ElemTy.getSizeInBits();
4988       SDValue WidthMinus1 =
4989           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4990                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4991       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4992       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4993     }
4994 
4995     // Compute with: cttz(x) = ctpop(lsb - 1)
4996 
4997     // Since we can only compute the number of bits in a byte with vcnt.8, we
4998     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4999     // and i64.
5000 
5001     // Compute LSB - 1.
5002     SDValue Bits;
5003     if (ElemTy == MVT::i64) {
5004       // Load constant 0xffff'ffff'ffff'ffff to register.
5005       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5006                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5007       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5008     } else {
5009       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5010                                 DAG.getTargetConstant(1, dl, ElemTy));
5011       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5012     }
5013 
5014     // Count #bits with vcnt.8.
5015     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5016     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5017     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5018 
5019     // Gather the #bits with vpaddl (pairwise add.)
5020     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5021     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5022         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5023         Cnt8);
5024     if (ElemTy == MVT::i16)
5025       return Cnt16;
5026 
5027     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5028     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5029         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5030         Cnt16);
5031     if (ElemTy == MVT::i32)
5032       return Cnt32;
5033 
5034     assert(ElemTy == MVT::i64);
5035     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5036         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5037         Cnt32);
5038     return Cnt64;
5039   }
5040 
5041   if (!ST->hasV6T2Ops())
5042     return SDValue();
5043 
5044   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5045   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5046 }
5047 
5048 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5049 /// for each 16-bit element from operand, repeated.  The basic idea is to
5050 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5051 ///
5052 /// Trace for v4i16:
5053 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5054 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5055 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5056 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5057 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5058 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5059 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5060 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5061 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5062   EVT VT = N->getValueType(0);
5063   SDLoc DL(N);
5064 
5065   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5066   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5067   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5068   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5069   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5070   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5071 }
5072 
5073 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5074 /// bit-count for each 16-bit element from the operand.  We need slightly
5075 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5076 /// 64/128-bit registers.
5077 ///
5078 /// Trace for v4i16:
5079 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5080 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5081 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5082 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5083 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5084   EVT VT = N->getValueType(0);
5085   SDLoc DL(N);
5086 
5087   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5088   if (VT.is64BitVector()) {
5089     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5090     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5091                        DAG.getIntPtrConstant(0, DL));
5092   } else {
5093     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5094                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5095     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5096   }
5097 }
5098 
5099 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5100 /// bit-count for each 32-bit element from the operand.  The idea here is
5101 /// to split the vector into 16-bit elements, leverage the 16-bit count
5102 /// routine, and then combine the results.
5103 ///
5104 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5105 /// input    = [v0    v1    ] (vi: 32-bit elements)
5106 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5107 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5108 /// vrev: N0 = [k1 k0 k3 k2 ]
5109 ///            [k0 k1 k2 k3 ]
5110 ///       N1 =+[k1 k0 k3 k2 ]
5111 ///            [k0 k2 k1 k3 ]
5112 ///       N2 =+[k1 k3 k0 k2 ]
5113 ///            [k0    k2    k1    k3    ]
5114 /// Extended =+[k1    k3    k0    k2    ]
5115 ///            [k0    k2    ]
5116 /// Extracted=+[k1    k3    ]
5117 ///
5118 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5119   EVT VT = N->getValueType(0);
5120   SDLoc DL(N);
5121 
5122   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5123 
5124   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5125   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5126   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5127   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5128   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5129 
5130   if (VT.is64BitVector()) {
5131     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5132     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5133                        DAG.getIntPtrConstant(0, DL));
5134   } else {
5135     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5136                                     DAG.getIntPtrConstant(0, DL));
5137     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5138   }
5139 }
5140 
5141 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5142                           const ARMSubtarget *ST) {
5143   EVT VT = N->getValueType(0);
5144 
5145   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5146   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5147           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5148          "Unexpected type for custom ctpop lowering");
5149 
5150   if (VT.getVectorElementType() == MVT::i32)
5151     return lowerCTPOP32BitElements(N, DAG);
5152   else
5153     return lowerCTPOP16BitElements(N, DAG);
5154 }
5155 
5156 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5157                           const ARMSubtarget *ST) {
5158   EVT VT = N->getValueType(0);
5159   SDLoc dl(N);
5160 
5161   if (!VT.isVector())
5162     return SDValue();
5163 
5164   // Lower vector shifts on NEON to use VSHL.
5165   assert(ST->hasNEON() && "unexpected vector shift");
5166 
5167   // Left shifts translate directly to the vshiftu intrinsic.
5168   if (N->getOpcode() == ISD::SHL)
5169     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5170                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5171                                        MVT::i32),
5172                        N->getOperand(0), N->getOperand(1));
5173 
5174   assert((N->getOpcode() == ISD::SRA ||
5175           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5176 
5177   // NEON uses the same intrinsics for both left and right shifts.  For
5178   // right shifts, the shift amounts are negative, so negate the vector of
5179   // shift amounts.
5180   EVT ShiftVT = N->getOperand(1).getValueType();
5181   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5182                                      getZeroVector(ShiftVT, DAG, dl),
5183                                      N->getOperand(1));
5184   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5185                              Intrinsic::arm_neon_vshifts :
5186                              Intrinsic::arm_neon_vshiftu);
5187   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5188                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5189                      N->getOperand(0), NegatedCount);
5190 }
5191 
5192 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5193                                 const ARMSubtarget *ST) {
5194   EVT VT = N->getValueType(0);
5195   SDLoc dl(N);
5196 
5197   // We can get here for a node like i32 = ISD::SHL i32, i64
5198   if (VT != MVT::i64)
5199     return SDValue();
5200 
5201   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5202          "Unknown shift to lower!");
5203 
5204   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5205   if (!isOneConstant(N->getOperand(1)))
5206     return SDValue();
5207 
5208   // If we are in thumb mode, we don't have RRX.
5209   if (ST->isThumb1Only()) return SDValue();
5210 
5211   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5212   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5213                            DAG.getConstant(0, dl, MVT::i32));
5214   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5215                            DAG.getConstant(1, dl, MVT::i32));
5216 
5217   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5218   // captures the result into a carry flag.
5219   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5220   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5221 
5222   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5223   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5224 
5225   // Merge the pieces into a single i64 value.
5226  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5227 }
5228 
5229 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5230   SDValue TmpOp0, TmpOp1;
5231   bool Invert = false;
5232   bool Swap = false;
5233   unsigned Opc = 0;
5234 
5235   SDValue Op0 = Op.getOperand(0);
5236   SDValue Op1 = Op.getOperand(1);
5237   SDValue CC = Op.getOperand(2);
5238   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5239   EVT VT = Op.getValueType();
5240   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5241   SDLoc dl(Op);
5242 
5243   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5244       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5245     // Special-case integer 64-bit equality comparisons. They aren't legal,
5246     // but they can be lowered with a few vector instructions.
5247     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5248     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5249     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5250     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5251     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5252                               DAG.getCondCode(ISD::SETEQ));
5253     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5254     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5255     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5256     if (SetCCOpcode == ISD::SETNE)
5257       Merged = DAG.getNOT(dl, Merged, CmpVT);
5258     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5259     return Merged;
5260   }
5261 
5262   if (CmpVT.getVectorElementType() == MVT::i64)
5263     // 64-bit comparisons are not legal in general.
5264     return SDValue();
5265 
5266   if (Op1.getValueType().isFloatingPoint()) {
5267     switch (SetCCOpcode) {
5268     default: llvm_unreachable("Illegal FP comparison");
5269     case ISD::SETUNE:
5270     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5271     case ISD::SETOEQ:
5272     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5273     case ISD::SETOLT:
5274     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5275     case ISD::SETOGT:
5276     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5277     case ISD::SETOLE:
5278     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5279     case ISD::SETOGE:
5280     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5281     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5282     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5283     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5284     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5285     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5286     case ISD::SETONE:
5287       // Expand this to (OLT | OGT).
5288       TmpOp0 = Op0;
5289       TmpOp1 = Op1;
5290       Opc = ISD::OR;
5291       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5292       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5293       break;
5294     case ISD::SETUO:
5295       Invert = true;
5296       LLVM_FALLTHROUGH;
5297     case ISD::SETO:
5298       // Expand this to (OLT | OGE).
5299       TmpOp0 = Op0;
5300       TmpOp1 = Op1;
5301       Opc = ISD::OR;
5302       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5303       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5304       break;
5305     }
5306   } else {
5307     // Integer comparisons.
5308     switch (SetCCOpcode) {
5309     default: llvm_unreachable("Illegal integer comparison");
5310     case ISD::SETNE:  Invert = true;
5311     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5312     case ISD::SETLT:  Swap = true;
5313     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5314     case ISD::SETLE:  Swap = true;
5315     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5316     case ISD::SETULT: Swap = true;
5317     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5318     case ISD::SETULE: Swap = true;
5319     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5320     }
5321 
5322     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5323     if (Opc == ARMISD::VCEQ) {
5324 
5325       SDValue AndOp;
5326       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5327         AndOp = Op0;
5328       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5329         AndOp = Op1;
5330 
5331       // Ignore bitconvert.
5332       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5333         AndOp = AndOp.getOperand(0);
5334 
5335       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5336         Opc = ARMISD::VTST;
5337         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5338         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5339         Invert = !Invert;
5340       }
5341     }
5342   }
5343 
5344   if (Swap)
5345     std::swap(Op0, Op1);
5346 
5347   // If one of the operands is a constant vector zero, attempt to fold the
5348   // comparison to a specialized compare-against-zero form.
5349   SDValue SingleOp;
5350   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5351     SingleOp = Op0;
5352   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5353     if (Opc == ARMISD::VCGE)
5354       Opc = ARMISD::VCLEZ;
5355     else if (Opc == ARMISD::VCGT)
5356       Opc = ARMISD::VCLTZ;
5357     SingleOp = Op1;
5358   }
5359 
5360   SDValue Result;
5361   if (SingleOp.getNode()) {
5362     switch (Opc) {
5363     case ARMISD::VCEQ:
5364       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5365     case ARMISD::VCGE:
5366       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5367     case ARMISD::VCLEZ:
5368       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5369     case ARMISD::VCGT:
5370       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5371     case ARMISD::VCLTZ:
5372       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5373     default:
5374       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5375     }
5376   } else {
5377      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5378   }
5379 
5380   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5381 
5382   if (Invert)
5383     Result = DAG.getNOT(dl, Result, VT);
5384 
5385   return Result;
5386 }
5387 
5388 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5389   SDValue LHS = Op.getOperand(0);
5390   SDValue RHS = Op.getOperand(1);
5391   SDValue Carry = Op.getOperand(2);
5392   SDValue Cond = Op.getOperand(3);
5393   SDLoc DL(Op);
5394 
5395   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5396 
5397   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5398   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5399   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5400 
5401   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5402   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5403   SDValue ARMcc = DAG.getConstant(
5404       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5405   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5406   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5407                                    Cmp.getValue(1), SDValue());
5408   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5409                      CCR, Chain.getValue(1));
5410 }
5411 
5412 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5413 /// valid vector constant for a NEON instruction with a "modified immediate"
5414 /// operand (e.g., VMOV).  If so, return the encoded value.
5415 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5416                                  unsigned SplatBitSize, SelectionDAG &DAG,
5417                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5418                                  NEONModImmType type) {
5419   unsigned OpCmode, Imm;
5420 
5421   // SplatBitSize is set to the smallest size that splats the vector, so a
5422   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5423   // immediate instructions others than VMOV do not support the 8-bit encoding
5424   // of a zero vector, and the default encoding of zero is supposed to be the
5425   // 32-bit version.
5426   if (SplatBits == 0)
5427     SplatBitSize = 32;
5428 
5429   switch (SplatBitSize) {
5430   case 8:
5431     if (type != VMOVModImm)
5432       return SDValue();
5433     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5434     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5435     OpCmode = 0xe;
5436     Imm = SplatBits;
5437     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5438     break;
5439 
5440   case 16:
5441     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5442     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5443     if ((SplatBits & ~0xff) == 0) {
5444       // Value = 0x00nn: Op=x, Cmode=100x.
5445       OpCmode = 0x8;
5446       Imm = SplatBits;
5447       break;
5448     }
5449     if ((SplatBits & ~0xff00) == 0) {
5450       // Value = 0xnn00: Op=x, Cmode=101x.
5451       OpCmode = 0xa;
5452       Imm = SplatBits >> 8;
5453       break;
5454     }
5455     return SDValue();
5456 
5457   case 32:
5458     // NEON's 32-bit VMOV supports splat values where:
5459     // * only one byte is nonzero, or
5460     // * the least significant byte is 0xff and the second byte is nonzero, or
5461     // * the least significant 2 bytes are 0xff and the third is nonzero.
5462     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5463     if ((SplatBits & ~0xff) == 0) {
5464       // Value = 0x000000nn: Op=x, Cmode=000x.
5465       OpCmode = 0;
5466       Imm = SplatBits;
5467       break;
5468     }
5469     if ((SplatBits & ~0xff00) == 0) {
5470       // Value = 0x0000nn00: Op=x, Cmode=001x.
5471       OpCmode = 0x2;
5472       Imm = SplatBits >> 8;
5473       break;
5474     }
5475     if ((SplatBits & ~0xff0000) == 0) {
5476       // Value = 0x00nn0000: Op=x, Cmode=010x.
5477       OpCmode = 0x4;
5478       Imm = SplatBits >> 16;
5479       break;
5480     }
5481     if ((SplatBits & ~0xff000000) == 0) {
5482       // Value = 0xnn000000: Op=x, Cmode=011x.
5483       OpCmode = 0x6;
5484       Imm = SplatBits >> 24;
5485       break;
5486     }
5487 
5488     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5489     if (type == OtherModImm) return SDValue();
5490 
5491     if ((SplatBits & ~0xffff) == 0 &&
5492         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5493       // Value = 0x0000nnff: Op=x, Cmode=1100.
5494       OpCmode = 0xc;
5495       Imm = SplatBits >> 8;
5496       break;
5497     }
5498 
5499     if ((SplatBits & ~0xffffff) == 0 &&
5500         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5501       // Value = 0x00nnffff: Op=x, Cmode=1101.
5502       OpCmode = 0xd;
5503       Imm = SplatBits >> 16;
5504       break;
5505     }
5506 
5507     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5508     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5509     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5510     // and fall through here to test for a valid 64-bit splat.  But, then the
5511     // caller would also need to check and handle the change in size.
5512     return SDValue();
5513 
5514   case 64: {
5515     if (type != VMOVModImm)
5516       return SDValue();
5517     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5518     uint64_t BitMask = 0xff;
5519     uint64_t Val = 0;
5520     unsigned ImmMask = 1;
5521     Imm = 0;
5522     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5523       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5524         Val |= BitMask;
5525         Imm |= ImmMask;
5526       } else if ((SplatBits & BitMask) != 0) {
5527         return SDValue();
5528       }
5529       BitMask <<= 8;
5530       ImmMask <<= 1;
5531     }
5532 
5533     if (DAG.getDataLayout().isBigEndian())
5534       // swap higher and lower 32 bit word
5535       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5536 
5537     // Op=1, Cmode=1110.
5538     OpCmode = 0x1e;
5539     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5540     break;
5541   }
5542 
5543   default:
5544     llvm_unreachable("unexpected size for isNEONModifiedImm");
5545   }
5546 
5547   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5548   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5549 }
5550 
5551 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5552                                            const ARMSubtarget *ST) const {
5553   if (!ST->hasVFP3())
5554     return SDValue();
5555 
5556   bool IsDouble = Op.getValueType() == MVT::f64;
5557   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5558 
5559   // Use the default (constant pool) lowering for double constants when we have
5560   // an SP-only FPU
5561   if (IsDouble && Subtarget->isFPOnlySP())
5562     return SDValue();
5563 
5564   // Try splatting with a VMOV.f32...
5565   const APFloat &FPVal = CFP->getValueAPF();
5566   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5567 
5568   if (ImmVal != -1) {
5569     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5570       // We have code in place to select a valid ConstantFP already, no need to
5571       // do any mangling.
5572       return Op;
5573     }
5574 
5575     // It's a float and we are trying to use NEON operations where
5576     // possible. Lower it to a splat followed by an extract.
5577     SDLoc DL(Op);
5578     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5579     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5580                                       NewVal);
5581     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5582                        DAG.getConstant(0, DL, MVT::i32));
5583   }
5584 
5585   // The rest of our options are NEON only, make sure that's allowed before
5586   // proceeding..
5587   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5588     return SDValue();
5589 
5590   EVT VMovVT;
5591   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5592 
5593   // It wouldn't really be worth bothering for doubles except for one very
5594   // important value, which does happen to match: 0.0. So make sure we don't do
5595   // anything stupid.
5596   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5597     return SDValue();
5598 
5599   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5600   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5601                                      VMovVT, false, VMOVModImm);
5602   if (NewVal != SDValue()) {
5603     SDLoc DL(Op);
5604     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5605                                       NewVal);
5606     if (IsDouble)
5607       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5608 
5609     // It's a float: cast and extract a vector element.
5610     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5611                                        VecConstant);
5612     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5613                        DAG.getConstant(0, DL, MVT::i32));
5614   }
5615 
5616   // Finally, try a VMVN.i32
5617   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5618                              false, VMVNModImm);
5619   if (NewVal != SDValue()) {
5620     SDLoc DL(Op);
5621     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5622 
5623     if (IsDouble)
5624       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5625 
5626     // It's a float: cast and extract a vector element.
5627     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5628                                        VecConstant);
5629     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5630                        DAG.getConstant(0, DL, MVT::i32));
5631   }
5632 
5633   return SDValue();
5634 }
5635 
5636 // check if an VEXT instruction can handle the shuffle mask when the
5637 // vector sources of the shuffle are the same.
5638 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5639   unsigned NumElts = VT.getVectorNumElements();
5640 
5641   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5642   if (M[0] < 0)
5643     return false;
5644 
5645   Imm = M[0];
5646 
5647   // If this is a VEXT shuffle, the immediate value is the index of the first
5648   // element.  The other shuffle indices must be the successive elements after
5649   // the first one.
5650   unsigned ExpectedElt = Imm;
5651   for (unsigned i = 1; i < NumElts; ++i) {
5652     // Increment the expected index.  If it wraps around, just follow it
5653     // back to index zero and keep going.
5654     ++ExpectedElt;
5655     if (ExpectedElt == NumElts)
5656       ExpectedElt = 0;
5657 
5658     if (M[i] < 0) continue; // ignore UNDEF indices
5659     if (ExpectedElt != static_cast<unsigned>(M[i]))
5660       return false;
5661   }
5662 
5663   return true;
5664 }
5665 
5666 
5667 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5668                        bool &ReverseVEXT, unsigned &Imm) {
5669   unsigned NumElts = VT.getVectorNumElements();
5670   ReverseVEXT = false;
5671 
5672   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5673   if (M[0] < 0)
5674     return false;
5675 
5676   Imm = M[0];
5677 
5678   // If this is a VEXT shuffle, the immediate value is the index of the first
5679   // element.  The other shuffle indices must be the successive elements after
5680   // the first one.
5681   unsigned ExpectedElt = Imm;
5682   for (unsigned i = 1; i < NumElts; ++i) {
5683     // Increment the expected index.  If it wraps around, it may still be
5684     // a VEXT but the source vectors must be swapped.
5685     ExpectedElt += 1;
5686     if (ExpectedElt == NumElts * 2) {
5687       ExpectedElt = 0;
5688       ReverseVEXT = true;
5689     }
5690 
5691     if (M[i] < 0) continue; // ignore UNDEF indices
5692     if (ExpectedElt != static_cast<unsigned>(M[i]))
5693       return false;
5694   }
5695 
5696   // Adjust the index value if the source operands will be swapped.
5697   if (ReverseVEXT)
5698     Imm -= NumElts;
5699 
5700   return true;
5701 }
5702 
5703 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5704 /// instruction with the specified blocksize.  (The order of the elements
5705 /// within each block of the vector is reversed.)
5706 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5707   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5708          "Only possible block sizes for VREV are: 16, 32, 64");
5709 
5710   unsigned EltSz = VT.getScalarSizeInBits();
5711   if (EltSz == 64)
5712     return false;
5713 
5714   unsigned NumElts = VT.getVectorNumElements();
5715   unsigned BlockElts = M[0] + 1;
5716   // If the first shuffle index is UNDEF, be optimistic.
5717   if (M[0] < 0)
5718     BlockElts = BlockSize / EltSz;
5719 
5720   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5721     return false;
5722 
5723   for (unsigned i = 0; i < NumElts; ++i) {
5724     if (M[i] < 0) continue; // ignore UNDEF indices
5725     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5726       return false;
5727   }
5728 
5729   return true;
5730 }
5731 
5732 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5733   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5734   // range, then 0 is placed into the resulting vector. So pretty much any mask
5735   // of 8 elements can work here.
5736   return VT == MVT::v8i8 && M.size() == 8;
5737 }
5738 
5739 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5740 // checking that pairs of elements in the shuffle mask represent the same index
5741 // in each vector, incrementing the expected index by 2 at each step.
5742 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5743 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5744 //  v2={e,f,g,h}
5745 // WhichResult gives the offset for each element in the mask based on which
5746 // of the two results it belongs to.
5747 //
5748 // The transpose can be represented either as:
5749 // result1 = shufflevector v1, v2, result1_shuffle_mask
5750 // result2 = shufflevector v1, v2, result2_shuffle_mask
5751 // where v1/v2 and the shuffle masks have the same number of elements
5752 // (here WhichResult (see below) indicates which result is being checked)
5753 //
5754 // or as:
5755 // results = shufflevector v1, v2, shuffle_mask
5756 // where both results are returned in one vector and the shuffle mask has twice
5757 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5758 // want to check the low half and high half of the shuffle mask as if it were
5759 // the other case
5760 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5761   unsigned EltSz = VT.getScalarSizeInBits();
5762   if (EltSz == 64)
5763     return false;
5764 
5765   unsigned NumElts = VT.getVectorNumElements();
5766   if (M.size() != NumElts && M.size() != NumElts*2)
5767     return false;
5768 
5769   // If the mask is twice as long as the input vector then we need to check the
5770   // upper and lower parts of the mask with a matching value for WhichResult
5771   // FIXME: A mask with only even values will be rejected in case the first
5772   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5773   // M[0] is used to determine WhichResult
5774   for (unsigned i = 0; i < M.size(); i += NumElts) {
5775     if (M.size() == NumElts * 2)
5776       WhichResult = i / NumElts;
5777     else
5778       WhichResult = M[i] == 0 ? 0 : 1;
5779     for (unsigned j = 0; j < NumElts; j += 2) {
5780       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5781           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5782         return false;
5783     }
5784   }
5785 
5786   if (M.size() == NumElts*2)
5787     WhichResult = 0;
5788 
5789   return true;
5790 }
5791 
5792 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5793 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5794 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5795 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5796   unsigned EltSz = VT.getScalarSizeInBits();
5797   if (EltSz == 64)
5798     return false;
5799 
5800   unsigned NumElts = VT.getVectorNumElements();
5801   if (M.size() != NumElts && M.size() != NumElts*2)
5802     return false;
5803 
5804   for (unsigned i = 0; i < M.size(); i += NumElts) {
5805     if (M.size() == NumElts * 2)
5806       WhichResult = i / NumElts;
5807     else
5808       WhichResult = M[i] == 0 ? 0 : 1;
5809     for (unsigned j = 0; j < NumElts; j += 2) {
5810       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5811           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5812         return false;
5813     }
5814   }
5815 
5816   if (M.size() == NumElts*2)
5817     WhichResult = 0;
5818 
5819   return true;
5820 }
5821 
5822 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5823 // that the mask elements are either all even and in steps of size 2 or all odd
5824 // and in steps of size 2.
5825 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5826 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5827 //  v2={e,f,g,h}
5828 // Requires similar checks to that of isVTRNMask with
5829 // respect the how results are returned.
5830 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5831   unsigned EltSz = VT.getScalarSizeInBits();
5832   if (EltSz == 64)
5833     return false;
5834 
5835   unsigned NumElts = VT.getVectorNumElements();
5836   if (M.size() != NumElts && M.size() != NumElts*2)
5837     return false;
5838 
5839   for (unsigned i = 0; i < M.size(); i += NumElts) {
5840     WhichResult = M[i] == 0 ? 0 : 1;
5841     for (unsigned j = 0; j < NumElts; ++j) {
5842       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5843         return false;
5844     }
5845   }
5846 
5847   if (M.size() == NumElts*2)
5848     WhichResult = 0;
5849 
5850   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5851   if (VT.is64BitVector() && EltSz == 32)
5852     return false;
5853 
5854   return true;
5855 }
5856 
5857 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5858 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5859 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5860 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5861   unsigned EltSz = VT.getScalarSizeInBits();
5862   if (EltSz == 64)
5863     return false;
5864 
5865   unsigned NumElts = VT.getVectorNumElements();
5866   if (M.size() != NumElts && M.size() != NumElts*2)
5867     return false;
5868 
5869   unsigned Half = NumElts / 2;
5870   for (unsigned i = 0; i < M.size(); i += NumElts) {
5871     WhichResult = M[i] == 0 ? 0 : 1;
5872     for (unsigned j = 0; j < NumElts; j += Half) {
5873       unsigned Idx = WhichResult;
5874       for (unsigned k = 0; k < Half; ++k) {
5875         int MIdx = M[i + j + k];
5876         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5877           return false;
5878         Idx += 2;
5879       }
5880     }
5881   }
5882 
5883   if (M.size() == NumElts*2)
5884     WhichResult = 0;
5885 
5886   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5887   if (VT.is64BitVector() && EltSz == 32)
5888     return false;
5889 
5890   return true;
5891 }
5892 
5893 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5894 // that pairs of elements of the shufflemask represent the same index in each
5895 // vector incrementing sequentially through the vectors.
5896 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5897 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5898 //  v2={e,f,g,h}
5899 // Requires similar checks to that of isVTRNMask with respect the how results
5900 // are returned.
5901 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5902   unsigned EltSz = VT.getScalarSizeInBits();
5903   if (EltSz == 64)
5904     return false;
5905 
5906   unsigned NumElts = VT.getVectorNumElements();
5907   if (M.size() != NumElts && M.size() != NumElts*2)
5908     return false;
5909 
5910   for (unsigned i = 0; i < M.size(); i += NumElts) {
5911     WhichResult = M[i] == 0 ? 0 : 1;
5912     unsigned Idx = WhichResult * NumElts / 2;
5913     for (unsigned j = 0; j < NumElts; j += 2) {
5914       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5915           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5916         return false;
5917       Idx += 1;
5918     }
5919   }
5920 
5921   if (M.size() == NumElts*2)
5922     WhichResult = 0;
5923 
5924   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5925   if (VT.is64BitVector() && EltSz == 32)
5926     return false;
5927 
5928   return true;
5929 }
5930 
5931 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5932 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5933 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5934 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5935   unsigned EltSz = VT.getScalarSizeInBits();
5936   if (EltSz == 64)
5937     return false;
5938 
5939   unsigned NumElts = VT.getVectorNumElements();
5940   if (M.size() != NumElts && M.size() != NumElts*2)
5941     return false;
5942 
5943   for (unsigned i = 0; i < M.size(); i += NumElts) {
5944     WhichResult = M[i] == 0 ? 0 : 1;
5945     unsigned Idx = WhichResult * NumElts / 2;
5946     for (unsigned j = 0; j < NumElts; j += 2) {
5947       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5948           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5949         return false;
5950       Idx += 1;
5951     }
5952   }
5953 
5954   if (M.size() == NumElts*2)
5955     WhichResult = 0;
5956 
5957   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5958   if (VT.is64BitVector() && EltSz == 32)
5959     return false;
5960 
5961   return true;
5962 }
5963 
5964 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5965 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5966 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5967                                            unsigned &WhichResult,
5968                                            bool &isV_UNDEF) {
5969   isV_UNDEF = false;
5970   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5971     return ARMISD::VTRN;
5972   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5973     return ARMISD::VUZP;
5974   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5975     return ARMISD::VZIP;
5976 
5977   isV_UNDEF = true;
5978   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5979     return ARMISD::VTRN;
5980   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5981     return ARMISD::VUZP;
5982   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5983     return ARMISD::VZIP;
5984 
5985   return 0;
5986 }
5987 
5988 /// \return true if this is a reverse operation on an vector.
5989 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5990   unsigned NumElts = VT.getVectorNumElements();
5991   // Make sure the mask has the right size.
5992   if (NumElts != M.size())
5993       return false;
5994 
5995   // Look for <15, ..., 3, -1, 1, 0>.
5996   for (unsigned i = 0; i != NumElts; ++i)
5997     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5998       return false;
5999 
6000   return true;
6001 }
6002 
6003 // If N is an integer constant that can be moved into a register in one
6004 // instruction, return an SDValue of such a constant (will become a MOV
6005 // instruction).  Otherwise return null.
6006 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6007                                      const ARMSubtarget *ST, const SDLoc &dl) {
6008   uint64_t Val;
6009   if (!isa<ConstantSDNode>(N))
6010     return SDValue();
6011   Val = cast<ConstantSDNode>(N)->getZExtValue();
6012 
6013   if (ST->isThumb1Only()) {
6014     if (Val <= 255 || ~Val <= 255)
6015       return DAG.getConstant(Val, dl, MVT::i32);
6016   } else {
6017     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6018       return DAG.getConstant(Val, dl, MVT::i32);
6019   }
6020   return SDValue();
6021 }
6022 
6023 // If this is a case we can't handle, return null and let the default
6024 // expansion code take care of it.
6025 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6026                                              const ARMSubtarget *ST) const {
6027   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6028   SDLoc dl(Op);
6029   EVT VT = Op.getValueType();
6030 
6031   APInt SplatBits, SplatUndef;
6032   unsigned SplatBitSize;
6033   bool HasAnyUndefs;
6034   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6035     if (SplatBitSize <= 64) {
6036       // Check if an immediate VMOV works.
6037       EVT VmovVT;
6038       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6039                                       SplatUndef.getZExtValue(), SplatBitSize,
6040                                       DAG, dl, VmovVT, VT.is128BitVector(),
6041                                       VMOVModImm);
6042       if (Val.getNode()) {
6043         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6044         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6045       }
6046 
6047       // Try an immediate VMVN.
6048       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6049       Val = isNEONModifiedImm(NegatedImm,
6050                                       SplatUndef.getZExtValue(), SplatBitSize,
6051                                       DAG, dl, VmovVT, VT.is128BitVector(),
6052                                       VMVNModImm);
6053       if (Val.getNode()) {
6054         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6055         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6056       }
6057 
6058       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6059       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6060         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6061         if (ImmVal != -1) {
6062           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6063           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6064         }
6065       }
6066     }
6067   }
6068 
6069   // Scan through the operands to see if only one value is used.
6070   //
6071   // As an optimisation, even if more than one value is used it may be more
6072   // profitable to splat with one value then change some lanes.
6073   //
6074   // Heuristically we decide to do this if the vector has a "dominant" value,
6075   // defined as splatted to more than half of the lanes.
6076   unsigned NumElts = VT.getVectorNumElements();
6077   bool isOnlyLowElement = true;
6078   bool usesOnlyOneValue = true;
6079   bool hasDominantValue = false;
6080   bool isConstant = true;
6081 
6082   // Map of the number of times a particular SDValue appears in the
6083   // element list.
6084   DenseMap<SDValue, unsigned> ValueCounts;
6085   SDValue Value;
6086   for (unsigned i = 0; i < NumElts; ++i) {
6087     SDValue V = Op.getOperand(i);
6088     if (V.isUndef())
6089       continue;
6090     if (i > 0)
6091       isOnlyLowElement = false;
6092     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6093       isConstant = false;
6094 
6095     ValueCounts.insert(std::make_pair(V, 0));
6096     unsigned &Count = ValueCounts[V];
6097 
6098     // Is this value dominant? (takes up more than half of the lanes)
6099     if (++Count > (NumElts / 2)) {
6100       hasDominantValue = true;
6101       Value = V;
6102     }
6103   }
6104   if (ValueCounts.size() != 1)
6105     usesOnlyOneValue = false;
6106   if (!Value.getNode() && ValueCounts.size() > 0)
6107     Value = ValueCounts.begin()->first;
6108 
6109   if (ValueCounts.size() == 0)
6110     return DAG.getUNDEF(VT);
6111 
6112   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6113   // Keep going if we are hitting this case.
6114   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6115     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6116 
6117   unsigned EltSize = VT.getScalarSizeInBits();
6118 
6119   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6120   // i32 and try again.
6121   if (hasDominantValue && EltSize <= 32) {
6122     if (!isConstant) {
6123       SDValue N;
6124 
6125       // If we are VDUPing a value that comes directly from a vector, that will
6126       // cause an unnecessary move to and from a GPR, where instead we could
6127       // just use VDUPLANE. We can only do this if the lane being extracted
6128       // is at a constant index, as the VDUP from lane instructions only have
6129       // constant-index forms.
6130       ConstantSDNode *constIndex;
6131       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6132           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6133         // We need to create a new undef vector to use for the VDUPLANE if the
6134         // size of the vector from which we get the value is different than the
6135         // size of the vector that we need to create. We will insert the element
6136         // such that the register coalescer will remove unnecessary copies.
6137         if (VT != Value->getOperand(0).getValueType()) {
6138           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6139                              VT.getVectorNumElements();
6140           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6141                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6142                         Value, DAG.getConstant(index, dl, MVT::i32)),
6143                            DAG.getConstant(index, dl, MVT::i32));
6144         } else
6145           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6146                         Value->getOperand(0), Value->getOperand(1));
6147       } else
6148         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6149 
6150       if (!usesOnlyOneValue) {
6151         // The dominant value was splatted as 'N', but we now have to insert
6152         // all differing elements.
6153         for (unsigned I = 0; I < NumElts; ++I) {
6154           if (Op.getOperand(I) == Value)
6155             continue;
6156           SmallVector<SDValue, 3> Ops;
6157           Ops.push_back(N);
6158           Ops.push_back(Op.getOperand(I));
6159           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6160           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6161         }
6162       }
6163       return N;
6164     }
6165     if (VT.getVectorElementType().isFloatingPoint()) {
6166       SmallVector<SDValue, 8> Ops;
6167       for (unsigned i = 0; i < NumElts; ++i)
6168         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6169                                   Op.getOperand(i)));
6170       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6171       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6172       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6173       if (Val.getNode())
6174         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6175     }
6176     if (usesOnlyOneValue) {
6177       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6178       if (isConstant && Val.getNode())
6179         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6180     }
6181   }
6182 
6183   // If all elements are constants and the case above didn't get hit, fall back
6184   // to the default expansion, which will generate a load from the constant
6185   // pool.
6186   if (isConstant)
6187     return SDValue();
6188 
6189   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6190   if (NumElts >= 4) {
6191     SDValue shuffle = ReconstructShuffle(Op, DAG);
6192     if (shuffle != SDValue())
6193       return shuffle;
6194   }
6195 
6196   // Vectors with 32- or 64-bit elements can be built by directly assigning
6197   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6198   // will be legalized.
6199   if (EltSize >= 32) {
6200     // Do the expansion with floating-point types, since that is what the VFP
6201     // registers are defined to use, and since i64 is not legal.
6202     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6203     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6204     SmallVector<SDValue, 8> Ops;
6205     for (unsigned i = 0; i < NumElts; ++i)
6206       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6207     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6208     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6209   }
6210 
6211   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6212   // know the default expansion would otherwise fall back on something even
6213   // worse. For a vector with one or two non-undef values, that's
6214   // scalar_to_vector for the elements followed by a shuffle (provided the
6215   // shuffle is valid for the target) and materialization element by element
6216   // on the stack followed by a load for everything else.
6217   if (!isConstant && !usesOnlyOneValue) {
6218     SDValue Vec = DAG.getUNDEF(VT);
6219     for (unsigned i = 0 ; i < NumElts; ++i) {
6220       SDValue V = Op.getOperand(i);
6221       if (V.isUndef())
6222         continue;
6223       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6224       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6225     }
6226     return Vec;
6227   }
6228 
6229   return SDValue();
6230 }
6231 
6232 // Gather data to see if the operation can be modelled as a
6233 // shuffle in combination with VEXTs.
6234 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6235                                               SelectionDAG &DAG) const {
6236   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6237   SDLoc dl(Op);
6238   EVT VT = Op.getValueType();
6239   unsigned NumElts = VT.getVectorNumElements();
6240 
6241   struct ShuffleSourceInfo {
6242     SDValue Vec;
6243     unsigned MinElt;
6244     unsigned MaxElt;
6245 
6246     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6247     // be compatible with the shuffle we intend to construct. As a result
6248     // ShuffleVec will be some sliding window into the original Vec.
6249     SDValue ShuffleVec;
6250 
6251     // Code should guarantee that element i in Vec starts at element "WindowBase
6252     // + i * WindowScale in ShuffleVec".
6253     int WindowBase;
6254     int WindowScale;
6255 
6256     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6257     ShuffleSourceInfo(SDValue Vec)
6258         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
6259           WindowScale(1) {}
6260   };
6261 
6262   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6263   // node.
6264   SmallVector<ShuffleSourceInfo, 2> Sources;
6265   for (unsigned i = 0; i < NumElts; ++i) {
6266     SDValue V = Op.getOperand(i);
6267     if (V.isUndef())
6268       continue;
6269     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6270       // A shuffle can only come from building a vector from various
6271       // elements of other vectors.
6272       return SDValue();
6273     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6274       // Furthermore, shuffles require a constant mask, whereas extractelts
6275       // accept variable indices.
6276       return SDValue();
6277     }
6278 
6279     // Add this element source to the list if it's not already there.
6280     SDValue SourceVec = V.getOperand(0);
6281     auto Source = find(Sources, SourceVec);
6282     if (Source == Sources.end())
6283       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6284 
6285     // Update the minimum and maximum lane number seen.
6286     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6287     Source->MinElt = std::min(Source->MinElt, EltNo);
6288     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6289   }
6290 
6291   // Currently only do something sane when at most two source vectors
6292   // are involved.
6293   if (Sources.size() > 2)
6294     return SDValue();
6295 
6296   // Find out the smallest element size among result and two sources, and use
6297   // it as element size to build the shuffle_vector.
6298   EVT SmallestEltTy = VT.getVectorElementType();
6299   for (auto &Source : Sources) {
6300     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6301     if (SrcEltTy.bitsLT(SmallestEltTy))
6302       SmallestEltTy = SrcEltTy;
6303   }
6304   unsigned ResMultiplier =
6305       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6306   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6307   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6308 
6309   // If the source vector is too wide or too narrow, we may nevertheless be able
6310   // to construct a compatible shuffle either by concatenating it with UNDEF or
6311   // extracting a suitable range of elements.
6312   for (auto &Src : Sources) {
6313     EVT SrcVT = Src.ShuffleVec.getValueType();
6314 
6315     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6316       continue;
6317 
6318     // This stage of the search produces a source with the same element type as
6319     // the original, but with a total width matching the BUILD_VECTOR output.
6320     EVT EltVT = SrcVT.getVectorElementType();
6321     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6322     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6323 
6324     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6325       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6326         return SDValue();
6327       // We can pad out the smaller vector for free, so if it's part of a
6328       // shuffle...
6329       Src.ShuffleVec =
6330           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6331                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6332       continue;
6333     }
6334 
6335     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6336       return SDValue();
6337 
6338     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6339       // Span too large for a VEXT to cope
6340       return SDValue();
6341     }
6342 
6343     if (Src.MinElt >= NumSrcElts) {
6344       // The extraction can just take the second half
6345       Src.ShuffleVec =
6346           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6347                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6348       Src.WindowBase = -NumSrcElts;
6349     } else if (Src.MaxElt < NumSrcElts) {
6350       // The extraction can just take the first half
6351       Src.ShuffleVec =
6352           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6353                       DAG.getConstant(0, dl, MVT::i32));
6354     } else {
6355       // An actual VEXT is needed
6356       SDValue VEXTSrc1 =
6357           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6358                       DAG.getConstant(0, dl, MVT::i32));
6359       SDValue VEXTSrc2 =
6360           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6361                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6362 
6363       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6364                                    VEXTSrc2,
6365                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6366       Src.WindowBase = -Src.MinElt;
6367     }
6368   }
6369 
6370   // Another possible incompatibility occurs from the vector element types. We
6371   // can fix this by bitcasting the source vectors to the same type we intend
6372   // for the shuffle.
6373   for (auto &Src : Sources) {
6374     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6375     if (SrcEltTy == SmallestEltTy)
6376       continue;
6377     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6378     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6379     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6380     Src.WindowBase *= Src.WindowScale;
6381   }
6382 
6383   // Final sanity check before we try to actually produce a shuffle.
6384   DEBUG(
6385     for (auto Src : Sources)
6386       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6387   );
6388 
6389   // The stars all align, our next step is to produce the mask for the shuffle.
6390   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6391   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6392   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6393     SDValue Entry = Op.getOperand(i);
6394     if (Entry.isUndef())
6395       continue;
6396 
6397     auto Src = find(Sources, Entry.getOperand(0));
6398     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6399 
6400     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6401     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6402     // segment.
6403     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6404     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6405                                VT.getScalarSizeInBits());
6406     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6407 
6408     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6409     // starting at the appropriate offset.
6410     int *LaneMask = &Mask[i * ResMultiplier];
6411 
6412     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6413     ExtractBase += NumElts * (Src - Sources.begin());
6414     for (int j = 0; j < LanesDefined; ++j)
6415       LaneMask[j] = ExtractBase + j;
6416   }
6417 
6418   // Final check before we try to produce nonsense...
6419   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6420     return SDValue();
6421 
6422   // We can't handle more than two sources. This should have already
6423   // been checked before this point.
6424   assert(Sources.size() <= 2 && "Too many sources!");
6425 
6426   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6427   for (unsigned i = 0; i < Sources.size(); ++i)
6428     ShuffleOps[i] = Sources[i].ShuffleVec;
6429 
6430   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6431                                          ShuffleOps[1], Mask);
6432   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6433 }
6434 
6435 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6436 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6437 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6438 /// are assumed to be legal.
6439 bool
6440 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6441                                       EVT VT) const {
6442   if (VT.getVectorNumElements() == 4 &&
6443       (VT.is128BitVector() || VT.is64BitVector())) {
6444     unsigned PFIndexes[4];
6445     for (unsigned i = 0; i != 4; ++i) {
6446       if (M[i] < 0)
6447         PFIndexes[i] = 8;
6448       else
6449         PFIndexes[i] = M[i];
6450     }
6451 
6452     // Compute the index in the perfect shuffle table.
6453     unsigned PFTableIndex =
6454       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6455     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6456     unsigned Cost = (PFEntry >> 30);
6457 
6458     if (Cost <= 4)
6459       return true;
6460   }
6461 
6462   bool ReverseVEXT, isV_UNDEF;
6463   unsigned Imm, WhichResult;
6464 
6465   unsigned EltSize = VT.getScalarSizeInBits();
6466   return (EltSize >= 32 ||
6467           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6468           isVREVMask(M, VT, 64) ||
6469           isVREVMask(M, VT, 32) ||
6470           isVREVMask(M, VT, 16) ||
6471           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6472           isVTBLMask(M, VT) ||
6473           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6474           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6475 }
6476 
6477 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6478 /// the specified operations to build the shuffle.
6479 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6480                                       SDValue RHS, SelectionDAG &DAG,
6481                                       const SDLoc &dl) {
6482   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6483   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6484   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6485 
6486   enum {
6487     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6488     OP_VREV,
6489     OP_VDUP0,
6490     OP_VDUP1,
6491     OP_VDUP2,
6492     OP_VDUP3,
6493     OP_VEXT1,
6494     OP_VEXT2,
6495     OP_VEXT3,
6496     OP_VUZPL, // VUZP, left result
6497     OP_VUZPR, // VUZP, right result
6498     OP_VZIPL, // VZIP, left result
6499     OP_VZIPR, // VZIP, right result
6500     OP_VTRNL, // VTRN, left result
6501     OP_VTRNR  // VTRN, right result
6502   };
6503 
6504   if (OpNum == OP_COPY) {
6505     if (LHSID == (1*9+2)*9+3) return LHS;
6506     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6507     return RHS;
6508   }
6509 
6510   SDValue OpLHS, OpRHS;
6511   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6512   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6513   EVT VT = OpLHS.getValueType();
6514 
6515   switch (OpNum) {
6516   default: llvm_unreachable("Unknown shuffle opcode!");
6517   case OP_VREV:
6518     // VREV divides the vector in half and swaps within the half.
6519     if (VT.getVectorElementType() == MVT::i32 ||
6520         VT.getVectorElementType() == MVT::f32)
6521       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6522     // vrev <4 x i16> -> VREV32
6523     if (VT.getVectorElementType() == MVT::i16)
6524       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6525     // vrev <4 x i8> -> VREV16
6526     assert(VT.getVectorElementType() == MVT::i8);
6527     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6528   case OP_VDUP0:
6529   case OP_VDUP1:
6530   case OP_VDUP2:
6531   case OP_VDUP3:
6532     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6533                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6534   case OP_VEXT1:
6535   case OP_VEXT2:
6536   case OP_VEXT3:
6537     return DAG.getNode(ARMISD::VEXT, dl, VT,
6538                        OpLHS, OpRHS,
6539                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6540   case OP_VUZPL:
6541   case OP_VUZPR:
6542     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6543                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6544   case OP_VZIPL:
6545   case OP_VZIPR:
6546     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6547                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6548   case OP_VTRNL:
6549   case OP_VTRNR:
6550     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6551                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6552   }
6553 }
6554 
6555 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6556                                        ArrayRef<int> ShuffleMask,
6557                                        SelectionDAG &DAG) {
6558   // Check to see if we can use the VTBL instruction.
6559   SDValue V1 = Op.getOperand(0);
6560   SDValue V2 = Op.getOperand(1);
6561   SDLoc DL(Op);
6562 
6563   SmallVector<SDValue, 8> VTBLMask;
6564   for (ArrayRef<int>::iterator
6565          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6566     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6567 
6568   if (V2.getNode()->isUndef())
6569     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6570                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6571 
6572   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6573                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6574 }
6575 
6576 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6577                                                       SelectionDAG &DAG) {
6578   SDLoc DL(Op);
6579   SDValue OpLHS = Op.getOperand(0);
6580   EVT VT = OpLHS.getValueType();
6581 
6582   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6583          "Expect an v8i16/v16i8 type");
6584   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6585   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6586   // extract the first 8 bytes into the top double word and the last 8 bytes
6587   // into the bottom double word. The v8i16 case is similar.
6588   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6589   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6590                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6591 }
6592 
6593 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6594   SDValue V1 = Op.getOperand(0);
6595   SDValue V2 = Op.getOperand(1);
6596   SDLoc dl(Op);
6597   EVT VT = Op.getValueType();
6598   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6599 
6600   // Convert shuffles that are directly supported on NEON to target-specific
6601   // DAG nodes, instead of keeping them as shuffles and matching them again
6602   // during code selection.  This is more efficient and avoids the possibility
6603   // of inconsistencies between legalization and selection.
6604   // FIXME: floating-point vectors should be canonicalized to integer vectors
6605   // of the same time so that they get CSEd properly.
6606   ArrayRef<int> ShuffleMask = SVN->getMask();
6607 
6608   unsigned EltSize = VT.getScalarSizeInBits();
6609   if (EltSize <= 32) {
6610     if (SVN->isSplat()) {
6611       int Lane = SVN->getSplatIndex();
6612       // If this is undef splat, generate it via "just" vdup, if possible.
6613       if (Lane == -1) Lane = 0;
6614 
6615       // Test if V1 is a SCALAR_TO_VECTOR.
6616       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6617         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6618       }
6619       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6620       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6621       // reaches it).
6622       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6623           !isa<ConstantSDNode>(V1.getOperand(0))) {
6624         bool IsScalarToVector = true;
6625         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6626           if (!V1.getOperand(i).isUndef()) {
6627             IsScalarToVector = false;
6628             break;
6629           }
6630         if (IsScalarToVector)
6631           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6632       }
6633       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6634                          DAG.getConstant(Lane, dl, MVT::i32));
6635     }
6636 
6637     bool ReverseVEXT;
6638     unsigned Imm;
6639     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6640       if (ReverseVEXT)
6641         std::swap(V1, V2);
6642       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6643                          DAG.getConstant(Imm, dl, MVT::i32));
6644     }
6645 
6646     if (isVREVMask(ShuffleMask, VT, 64))
6647       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6648     if (isVREVMask(ShuffleMask, VT, 32))
6649       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6650     if (isVREVMask(ShuffleMask, VT, 16))
6651       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6652 
6653     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6654       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6655                          DAG.getConstant(Imm, dl, MVT::i32));
6656     }
6657 
6658     // Check for Neon shuffles that modify both input vectors in place.
6659     // If both results are used, i.e., if there are two shuffles with the same
6660     // source operands and with masks corresponding to both results of one of
6661     // these operations, DAG memoization will ensure that a single node is
6662     // used for both shuffles.
6663     unsigned WhichResult;
6664     bool isV_UNDEF;
6665     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6666             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6667       if (isV_UNDEF)
6668         V2 = V1;
6669       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6670           .getValue(WhichResult);
6671     }
6672 
6673     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6674     // shuffles that produce a result larger than their operands with:
6675     //   shuffle(concat(v1, undef), concat(v2, undef))
6676     // ->
6677     //   shuffle(concat(v1, v2), undef)
6678     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6679     //
6680     // This is useful in the general case, but there are special cases where
6681     // native shuffles produce larger results: the two-result ops.
6682     //
6683     // Look through the concat when lowering them:
6684     //   shuffle(concat(v1, v2), undef)
6685     // ->
6686     //   concat(VZIP(v1, v2):0, :1)
6687     //
6688     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6689       SDValue SubV1 = V1->getOperand(0);
6690       SDValue SubV2 = V1->getOperand(1);
6691       EVT SubVT = SubV1.getValueType();
6692 
6693       // We expect these to have been canonicalized to -1.
6694       assert(all_of(ShuffleMask, [&](int i) {
6695         return i < (int)VT.getVectorNumElements();
6696       }) && "Unexpected shuffle index into UNDEF operand!");
6697 
6698       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6699               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6700         if (isV_UNDEF)
6701           SubV2 = SubV1;
6702         assert((WhichResult == 0) &&
6703                "In-place shuffle of concat can only have one result!");
6704         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6705                                   SubV1, SubV2);
6706         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6707                            Res.getValue(1));
6708       }
6709     }
6710   }
6711 
6712   // If the shuffle is not directly supported and it has 4 elements, use
6713   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6714   unsigned NumElts = VT.getVectorNumElements();
6715   if (NumElts == 4) {
6716     unsigned PFIndexes[4];
6717     for (unsigned i = 0; i != 4; ++i) {
6718       if (ShuffleMask[i] < 0)
6719         PFIndexes[i] = 8;
6720       else
6721         PFIndexes[i] = ShuffleMask[i];
6722     }
6723 
6724     // Compute the index in the perfect shuffle table.
6725     unsigned PFTableIndex =
6726       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6727     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6728     unsigned Cost = (PFEntry >> 30);
6729 
6730     if (Cost <= 4)
6731       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6732   }
6733 
6734   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6735   if (EltSize >= 32) {
6736     // Do the expansion with floating-point types, since that is what the VFP
6737     // registers are defined to use, and since i64 is not legal.
6738     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6739     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6740     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6741     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6742     SmallVector<SDValue, 8> Ops;
6743     for (unsigned i = 0; i < NumElts; ++i) {
6744       if (ShuffleMask[i] < 0)
6745         Ops.push_back(DAG.getUNDEF(EltVT));
6746       else
6747         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6748                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6749                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6750                                                   dl, MVT::i32)));
6751     }
6752     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6753     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6754   }
6755 
6756   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6757     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6758 
6759   if (VT == MVT::v8i8)
6760     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6761       return NewOp;
6762 
6763   return SDValue();
6764 }
6765 
6766 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6767   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6768   SDValue Lane = Op.getOperand(2);
6769   if (!isa<ConstantSDNode>(Lane))
6770     return SDValue();
6771 
6772   return Op;
6773 }
6774 
6775 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6776   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6777   SDValue Lane = Op.getOperand(1);
6778   if (!isa<ConstantSDNode>(Lane))
6779     return SDValue();
6780 
6781   SDValue Vec = Op.getOperand(0);
6782   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
6783     SDLoc dl(Op);
6784     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6785   }
6786 
6787   return Op;
6788 }
6789 
6790 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6791   // The only time a CONCAT_VECTORS operation can have legal types is when
6792   // two 64-bit vectors are concatenated to a 128-bit vector.
6793   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6794          "unexpected CONCAT_VECTORS");
6795   SDLoc dl(Op);
6796   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6797   SDValue Op0 = Op.getOperand(0);
6798   SDValue Op1 = Op.getOperand(1);
6799   if (!Op0.isUndef())
6800     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6801                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6802                       DAG.getIntPtrConstant(0, dl));
6803   if (!Op1.isUndef())
6804     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6805                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6806                       DAG.getIntPtrConstant(1, dl));
6807   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6808 }
6809 
6810 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6811 /// element has been zero/sign-extended, depending on the isSigned parameter,
6812 /// from an integer type half its size.
6813 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6814                                    bool isSigned) {
6815   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6816   EVT VT = N->getValueType(0);
6817   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6818     SDNode *BVN = N->getOperand(0).getNode();
6819     if (BVN->getValueType(0) != MVT::v4i32 ||
6820         BVN->getOpcode() != ISD::BUILD_VECTOR)
6821       return false;
6822     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6823     unsigned HiElt = 1 - LoElt;
6824     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6825     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6826     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6827     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6828     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6829       return false;
6830     if (isSigned) {
6831       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6832           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6833         return true;
6834     } else {
6835       if (Hi0->isNullValue() && Hi1->isNullValue())
6836         return true;
6837     }
6838     return false;
6839   }
6840 
6841   if (N->getOpcode() != ISD::BUILD_VECTOR)
6842     return false;
6843 
6844   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6845     SDNode *Elt = N->getOperand(i).getNode();
6846     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6847       unsigned EltSize = VT.getScalarSizeInBits();
6848       unsigned HalfSize = EltSize / 2;
6849       if (isSigned) {
6850         if (!isIntN(HalfSize, C->getSExtValue()))
6851           return false;
6852       } else {
6853         if (!isUIntN(HalfSize, C->getZExtValue()))
6854           return false;
6855       }
6856       continue;
6857     }
6858     return false;
6859   }
6860 
6861   return true;
6862 }
6863 
6864 /// isSignExtended - Check if a node is a vector value that is sign-extended
6865 /// or a constant BUILD_VECTOR with sign-extended elements.
6866 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6867   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6868     return true;
6869   if (isExtendedBUILD_VECTOR(N, DAG, true))
6870     return true;
6871   return false;
6872 }
6873 
6874 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6875 /// or a constant BUILD_VECTOR with zero-extended elements.
6876 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6877   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6878     return true;
6879   if (isExtendedBUILD_VECTOR(N, DAG, false))
6880     return true;
6881   return false;
6882 }
6883 
6884 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6885   if (OrigVT.getSizeInBits() >= 64)
6886     return OrigVT;
6887 
6888   assert(OrigVT.isSimple() && "Expecting a simple value type");
6889 
6890   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6891   switch (OrigSimpleTy) {
6892   default: llvm_unreachable("Unexpected Vector Type");
6893   case MVT::v2i8:
6894   case MVT::v2i16:
6895      return MVT::v2i32;
6896   case MVT::v4i8:
6897     return  MVT::v4i16;
6898   }
6899 }
6900 
6901 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6902 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6903 /// We insert the required extension here to get the vector to fill a D register.
6904 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6905                                             const EVT &OrigTy,
6906                                             const EVT &ExtTy,
6907                                             unsigned ExtOpcode) {
6908   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6909   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6910   // 64-bits we need to insert a new extension so that it will be 64-bits.
6911   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6912   if (OrigTy.getSizeInBits() >= 64)
6913     return N;
6914 
6915   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6916   EVT NewVT = getExtensionTo64Bits(OrigTy);
6917 
6918   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6919 }
6920 
6921 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6922 /// does not do any sign/zero extension. If the original vector is less
6923 /// than 64 bits, an appropriate extension will be added after the load to
6924 /// reach a total size of 64 bits. We have to add the extension separately
6925 /// because ARM does not have a sign/zero extending load for vectors.
6926 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6927   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6928 
6929   // The load already has the right type.
6930   if (ExtendedTy == LD->getMemoryVT())
6931     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6932                        LD->getBasePtr(), LD->getPointerInfo(),
6933                        LD->getAlignment(), LD->getMemOperand()->getFlags());
6934 
6935   // We need to create a zextload/sextload. We cannot just create a load
6936   // followed by a zext/zext node because LowerMUL is also run during normal
6937   // operation legalization where we can't create illegal types.
6938   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6939                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6940                         LD->getMemoryVT(), LD->getAlignment(),
6941                         LD->getMemOperand()->getFlags());
6942 }
6943 
6944 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6945 /// extending load, or BUILD_VECTOR with extended elements, return the
6946 /// unextended value. The unextended vector should be 64 bits so that it can
6947 /// be used as an operand to a VMULL instruction. If the original vector size
6948 /// before extension is less than 64 bits we add a an extension to resize
6949 /// the vector to 64 bits.
6950 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6951   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6952     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6953                                         N->getOperand(0)->getValueType(0),
6954                                         N->getValueType(0),
6955                                         N->getOpcode());
6956 
6957   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6958     return SkipLoadExtensionForVMULL(LD, DAG);
6959 
6960   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6961   // have been legalized as a BITCAST from v4i32.
6962   if (N->getOpcode() == ISD::BITCAST) {
6963     SDNode *BVN = N->getOperand(0).getNode();
6964     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6965            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6966     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6967     return DAG.getBuildVector(
6968         MVT::v2i32, SDLoc(N),
6969         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
6970   }
6971   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6972   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6973   EVT VT = N->getValueType(0);
6974   unsigned EltSize = VT.getScalarSizeInBits() / 2;
6975   unsigned NumElts = VT.getVectorNumElements();
6976   MVT TruncVT = MVT::getIntegerVT(EltSize);
6977   SmallVector<SDValue, 8> Ops;
6978   SDLoc dl(N);
6979   for (unsigned i = 0; i != NumElts; ++i) {
6980     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6981     const APInt &CInt = C->getAPIntValue();
6982     // Element types smaller than 32 bits are not legal, so use i32 elements.
6983     // The values are implicitly truncated so sext vs. zext doesn't matter.
6984     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6985   }
6986   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
6987 }
6988 
6989 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6990   unsigned Opcode = N->getOpcode();
6991   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6992     SDNode *N0 = N->getOperand(0).getNode();
6993     SDNode *N1 = N->getOperand(1).getNode();
6994     return N0->hasOneUse() && N1->hasOneUse() &&
6995       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6996   }
6997   return false;
6998 }
6999 
7000 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7001   unsigned Opcode = N->getOpcode();
7002   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7003     SDNode *N0 = N->getOperand(0).getNode();
7004     SDNode *N1 = N->getOperand(1).getNode();
7005     return N0->hasOneUse() && N1->hasOneUse() &&
7006       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7007   }
7008   return false;
7009 }
7010 
7011 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7012   // Multiplications are only custom-lowered for 128-bit vectors so that
7013   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7014   EVT VT = Op.getValueType();
7015   assert(VT.is128BitVector() && VT.isInteger() &&
7016          "unexpected type for custom-lowering ISD::MUL");
7017   SDNode *N0 = Op.getOperand(0).getNode();
7018   SDNode *N1 = Op.getOperand(1).getNode();
7019   unsigned NewOpc = 0;
7020   bool isMLA = false;
7021   bool isN0SExt = isSignExtended(N0, DAG);
7022   bool isN1SExt = isSignExtended(N1, DAG);
7023   if (isN0SExt && isN1SExt)
7024     NewOpc = ARMISD::VMULLs;
7025   else {
7026     bool isN0ZExt = isZeroExtended(N0, DAG);
7027     bool isN1ZExt = isZeroExtended(N1, DAG);
7028     if (isN0ZExt && isN1ZExt)
7029       NewOpc = ARMISD::VMULLu;
7030     else if (isN1SExt || isN1ZExt) {
7031       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7032       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7033       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7034         NewOpc = ARMISD::VMULLs;
7035         isMLA = true;
7036       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7037         NewOpc = ARMISD::VMULLu;
7038         isMLA = true;
7039       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7040         std::swap(N0, N1);
7041         NewOpc = ARMISD::VMULLu;
7042         isMLA = true;
7043       }
7044     }
7045 
7046     if (!NewOpc) {
7047       if (VT == MVT::v2i64)
7048         // Fall through to expand this.  It is not legal.
7049         return SDValue();
7050       else
7051         // Other vector multiplications are legal.
7052         return Op;
7053     }
7054   }
7055 
7056   // Legalize to a VMULL instruction.
7057   SDLoc DL(Op);
7058   SDValue Op0;
7059   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7060   if (!isMLA) {
7061     Op0 = SkipExtensionForVMULL(N0, DAG);
7062     assert(Op0.getValueType().is64BitVector() &&
7063            Op1.getValueType().is64BitVector() &&
7064            "unexpected types for extended operands to VMULL");
7065     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7066   }
7067 
7068   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7069   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7070   //   vmull q0, d4, d6
7071   //   vmlal q0, d5, d6
7072   // is faster than
7073   //   vaddl q0, d4, d5
7074   //   vmovl q1, d6
7075   //   vmul  q0, q0, q1
7076   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7077   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7078   EVT Op1VT = Op1.getValueType();
7079   return DAG.getNode(N0->getOpcode(), DL, VT,
7080                      DAG.getNode(NewOpc, DL, VT,
7081                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7082                      DAG.getNode(NewOpc, DL, VT,
7083                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7084 }
7085 
7086 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7087                               SelectionDAG &DAG) {
7088   // TODO: Should this propagate fast-math-flags?
7089 
7090   // Convert to float
7091   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7092   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7093   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7094   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7095   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7096   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7097   // Get reciprocal estimate.
7098   // float4 recip = vrecpeq_f32(yf);
7099   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7100                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7101                    Y);
7102   // Because char has a smaller range than uchar, we can actually get away
7103   // without any newton steps.  This requires that we use a weird bias
7104   // of 0xb000, however (again, this has been exhaustively tested).
7105   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7106   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7107   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7108   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7109   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7110   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7111   // Convert back to short.
7112   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7113   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7114   return X;
7115 }
7116 
7117 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7118                                SelectionDAG &DAG) {
7119   // TODO: Should this propagate fast-math-flags?
7120 
7121   SDValue N2;
7122   // Convert to float.
7123   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7124   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7125   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7126   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7127   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7128   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7129 
7130   // Use reciprocal estimate and one refinement step.
7131   // float4 recip = vrecpeq_f32(yf);
7132   // recip *= vrecpsq_f32(yf, recip);
7133   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7134                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7135                    N1);
7136   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7137                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7138                    N1, N2);
7139   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7140   // Because short has a smaller range than ushort, we can actually get away
7141   // with only a single newton step.  This requires that we use a weird bias
7142   // of 89, however (again, this has been exhaustively tested).
7143   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7144   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7145   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7146   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7147   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7148   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7149   // Convert back to integer and return.
7150   // return vmovn_s32(vcvt_s32_f32(result));
7151   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7152   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7153   return N0;
7154 }
7155 
7156 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7157   EVT VT = Op.getValueType();
7158   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7159          "unexpected type for custom-lowering ISD::SDIV");
7160 
7161   SDLoc dl(Op);
7162   SDValue N0 = Op.getOperand(0);
7163   SDValue N1 = Op.getOperand(1);
7164   SDValue N2, N3;
7165 
7166   if (VT == MVT::v8i8) {
7167     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7168     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7169 
7170     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7171                      DAG.getIntPtrConstant(4, dl));
7172     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7173                      DAG.getIntPtrConstant(4, dl));
7174     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7175                      DAG.getIntPtrConstant(0, dl));
7176     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7177                      DAG.getIntPtrConstant(0, dl));
7178 
7179     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7180     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7181 
7182     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7183     N0 = LowerCONCAT_VECTORS(N0, DAG);
7184 
7185     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7186     return N0;
7187   }
7188   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7189 }
7190 
7191 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7192   // TODO: Should this propagate fast-math-flags?
7193   EVT VT = Op.getValueType();
7194   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7195          "unexpected type for custom-lowering ISD::UDIV");
7196 
7197   SDLoc dl(Op);
7198   SDValue N0 = Op.getOperand(0);
7199   SDValue N1 = Op.getOperand(1);
7200   SDValue N2, N3;
7201 
7202   if (VT == MVT::v8i8) {
7203     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7204     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7205 
7206     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7207                      DAG.getIntPtrConstant(4, dl));
7208     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7209                      DAG.getIntPtrConstant(4, dl));
7210     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7211                      DAG.getIntPtrConstant(0, dl));
7212     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7213                      DAG.getIntPtrConstant(0, dl));
7214 
7215     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7216     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7217 
7218     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7219     N0 = LowerCONCAT_VECTORS(N0, DAG);
7220 
7221     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7222                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7223                                      MVT::i32),
7224                      N0);
7225     return N0;
7226   }
7227 
7228   // v4i16 sdiv ... Convert to float.
7229   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7230   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7231   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7232   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7233   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7234   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7235 
7236   // Use reciprocal estimate and two refinement steps.
7237   // float4 recip = vrecpeq_f32(yf);
7238   // recip *= vrecpsq_f32(yf, recip);
7239   // recip *= vrecpsq_f32(yf, recip);
7240   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7241                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7242                    BN1);
7243   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7244                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7245                    BN1, N2);
7246   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7247   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7248                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7249                    BN1, N2);
7250   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7251   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7252   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7253   // and that it will never cause us to return an answer too large).
7254   // float4 result = as_float4(as_int4(xf*recip) + 2);
7255   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7256   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7257   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7258   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7259   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7260   // Convert back to integer and return.
7261   // return vmovn_u32(vcvt_s32_f32(result));
7262   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7263   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7264   return N0;
7265 }
7266 
7267 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7268   EVT VT = Op.getNode()->getValueType(0);
7269   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7270 
7271   unsigned Opc;
7272   bool ExtraOp = false;
7273   switch (Op.getOpcode()) {
7274   default: llvm_unreachable("Invalid code");
7275   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7276   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7277   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7278   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7279   }
7280 
7281   if (!ExtraOp)
7282     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7283                        Op.getOperand(1));
7284   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7285                      Op.getOperand(1), Op.getOperand(2));
7286 }
7287 
7288 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7289   assert(Subtarget->isTargetDarwin());
7290 
7291   // For iOS, we want to call an alternative entry point: __sincos_stret,
7292   // return values are passed via sret.
7293   SDLoc dl(Op);
7294   SDValue Arg = Op.getOperand(0);
7295   EVT ArgVT = Arg.getValueType();
7296   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7297   auto PtrVT = getPointerTy(DAG.getDataLayout());
7298 
7299   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7300   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7301 
7302   // Pair of floats / doubles used to pass the result.
7303   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
7304   auto &DL = DAG.getDataLayout();
7305 
7306   ArgListTy Args;
7307   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7308   SDValue SRet;
7309   if (ShouldUseSRet) {
7310     // Create stack object for sret.
7311     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7312     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7313     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7314     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7315 
7316     ArgListEntry Entry;
7317     Entry.Node = SRet;
7318     Entry.Ty = RetTy->getPointerTo();
7319     Entry.isSExt = false;
7320     Entry.isZExt = false;
7321     Entry.isSRet = true;
7322     Args.push_back(Entry);
7323     RetTy = Type::getVoidTy(*DAG.getContext());
7324   }
7325 
7326   ArgListEntry Entry;
7327   Entry.Node = Arg;
7328   Entry.Ty = ArgTy;
7329   Entry.isSExt = false;
7330   Entry.isZExt = false;
7331   Args.push_back(Entry);
7332 
7333   const char *LibcallName =
7334       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
7335   RTLIB::Libcall LC =
7336       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
7337   CallingConv::ID CC = getLibcallCallingConv(LC);
7338   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7339 
7340   TargetLowering::CallLoweringInfo CLI(DAG);
7341   CLI.setDebugLoc(dl)
7342       .setChain(DAG.getEntryNode())
7343       .setCallee(CC, RetTy, Callee, std::move(Args))
7344       .setDiscardResult(ShouldUseSRet);
7345   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7346 
7347   if (!ShouldUseSRet)
7348     return CallResult.first;
7349 
7350   SDValue LoadSin =
7351       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7352 
7353   // Address of cos field.
7354   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7355                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7356   SDValue LoadCos =
7357       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7358 
7359   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7360   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7361                      LoadSin.getValue(0), LoadCos.getValue(0));
7362 }
7363 
7364 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7365                                                   bool Signed,
7366                                                   SDValue &Chain) const {
7367   EVT VT = Op.getValueType();
7368   assert((VT == MVT::i32 || VT == MVT::i64) &&
7369          "unexpected type for custom lowering DIV");
7370   SDLoc dl(Op);
7371 
7372   const auto &DL = DAG.getDataLayout();
7373   const auto &TLI = DAG.getTargetLoweringInfo();
7374 
7375   const char *Name = nullptr;
7376   if (Signed)
7377     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7378   else
7379     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7380 
7381   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7382 
7383   ARMTargetLowering::ArgListTy Args;
7384 
7385   for (auto AI : {1, 0}) {
7386     ArgListEntry Arg;
7387     Arg.Node = Op.getOperand(AI);
7388     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7389     Args.push_back(Arg);
7390   }
7391 
7392   CallLoweringInfo CLI(DAG);
7393   CLI.setDebugLoc(dl)
7394     .setChain(Chain)
7395     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7396                ES, std::move(Args));
7397 
7398   return LowerCallTo(CLI).first;
7399 }
7400 
7401 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7402                                             bool Signed) const {
7403   assert(Op.getValueType() == MVT::i32 &&
7404          "unexpected type for custom lowering DIV");
7405   SDLoc dl(Op);
7406 
7407   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7408                                DAG.getEntryNode(), Op.getOperand(1));
7409 
7410   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7411 }
7412 
7413 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7414   SDLoc DL(N);
7415   SDValue Op = N->getOperand(1);
7416   if (N->getValueType(0) == MVT::i32)
7417     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7418   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7419                            DAG.getConstant(0, DL, MVT::i32));
7420   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7421                            DAG.getConstant(1, DL, MVT::i32));
7422   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7423                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7424 }
7425 
7426 void ARMTargetLowering::ExpandDIV_Windows(
7427     SDValue Op, SelectionDAG &DAG, bool Signed,
7428     SmallVectorImpl<SDValue> &Results) const {
7429   const auto &DL = DAG.getDataLayout();
7430   const auto &TLI = DAG.getTargetLoweringInfo();
7431 
7432   assert(Op.getValueType() == MVT::i64 &&
7433          "unexpected type for custom lowering DIV");
7434   SDLoc dl(Op);
7435 
7436   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7437 
7438   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7439 
7440   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7441   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7442                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7443   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7444 
7445   Results.push_back(Lower);
7446   Results.push_back(Upper);
7447 }
7448 
7449 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7450   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7451     // Acquire/Release load/store is not legal for targets without a dmb or
7452     // equivalent available.
7453     return SDValue();
7454 
7455   // Monotonic load/store is legal for all targets.
7456   return Op;
7457 }
7458 
7459 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7460                                     SmallVectorImpl<SDValue> &Results,
7461                                     SelectionDAG &DAG,
7462                                     const ARMSubtarget *Subtarget) {
7463   SDLoc DL(N);
7464   // Under Power Management extensions, the cycle-count is:
7465   //    mrc p15, #0, <Rt>, c9, c13, #0
7466   SDValue Ops[] = { N->getOperand(0), // Chain
7467                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7468                     DAG.getConstant(15, DL, MVT::i32),
7469                     DAG.getConstant(0, DL, MVT::i32),
7470                     DAG.getConstant(9, DL, MVT::i32),
7471                     DAG.getConstant(13, DL, MVT::i32),
7472                     DAG.getConstant(0, DL, MVT::i32)
7473   };
7474 
7475   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7476                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7477   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7478                                 DAG.getConstant(0, DL, MVT::i32)));
7479   Results.push_back(Cycles32.getValue(1));
7480 }
7481 
7482 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7483   SDLoc dl(V.getNode());
7484   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7485   SDValue VHi = DAG.getAnyExtOrTrunc(
7486       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7487       dl, MVT::i32);
7488   SDValue RegClass =
7489       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7490   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7491   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7492   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7493   return SDValue(
7494       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7495 }
7496 
7497 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7498                                        SmallVectorImpl<SDValue> & Results,
7499                                        SelectionDAG &DAG) {
7500   assert(N->getValueType(0) == MVT::i64 &&
7501          "AtomicCmpSwap on types less than 64 should be legal");
7502   SDValue Ops[] = {N->getOperand(1),
7503                    createGPRPairNode(DAG, N->getOperand(2)),
7504                    createGPRPairNode(DAG, N->getOperand(3)),
7505                    N->getOperand(0)};
7506   SDNode *CmpSwap = DAG.getMachineNode(
7507       ARM::CMP_SWAP_64, SDLoc(N),
7508       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7509 
7510   MachineFunction &MF = DAG.getMachineFunction();
7511   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7512   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7513   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7514 
7515   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32,
7516                                                SDValue(CmpSwap, 0)));
7517   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32,
7518                                                SDValue(CmpSwap, 0)));
7519   Results.push_back(SDValue(CmpSwap, 2));
7520 }
7521 
7522 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7523   switch (Op.getOpcode()) {
7524   default: llvm_unreachable("Don't know how to custom lower this!");
7525   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7526   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
7527   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7528   case ISD::GlobalAddress:
7529     switch (Subtarget->getTargetTriple().getObjectFormat()) {
7530     default: llvm_unreachable("unknown object format");
7531     case Triple::COFF:
7532       return LowerGlobalAddressWindows(Op, DAG);
7533     case Triple::ELF:
7534       return LowerGlobalAddressELF(Op, DAG);
7535     case Triple::MachO:
7536       return LowerGlobalAddressDarwin(Op, DAG);
7537     }
7538   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7539   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7540   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7541   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7542   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7543   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7544   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7545   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7546   case ISD::SINT_TO_FP:
7547   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7548   case ISD::FP_TO_SINT:
7549   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7550   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7551   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7552   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7553   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7554   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7555   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7556   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7557                                                                Subtarget);
7558   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7559   case ISD::SHL:
7560   case ISD::SRL:
7561   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7562   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7563   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7564   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7565   case ISD::SRL_PARTS:
7566   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7567   case ISD::CTTZ:
7568   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7569   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7570   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7571   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7572   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7573   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7574   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7575   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7576   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7577   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7578   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7579   case ISD::MUL:           return LowerMUL(Op, DAG);
7580   case ISD::SDIV:
7581     if (Subtarget->isTargetWindows())
7582       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7583     return LowerSDIV(Op, DAG);
7584   case ISD::UDIV:
7585     if (Subtarget->isTargetWindows())
7586       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7587     return LowerUDIV(Op, DAG);
7588   case ISD::ADDC:
7589   case ISD::ADDE:
7590   case ISD::SUBC:
7591   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7592   case ISD::SADDO:
7593   case ISD::UADDO:
7594   case ISD::SSUBO:
7595   case ISD::USUBO:
7596     return LowerXALUO(Op, DAG);
7597   case ISD::ATOMIC_LOAD:
7598   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7599   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7600   case ISD::SDIVREM:
7601   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7602   case ISD::DYNAMIC_STACKALLOC:
7603     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7604       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7605     llvm_unreachable("Don't know how to custom lower this!");
7606   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7607   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7608   case ARMISD::WIN__DBZCHK: return SDValue();
7609   }
7610 }
7611 
7612 /// ReplaceNodeResults - Replace the results of node with an illegal result
7613 /// type with new values built out of custom code.
7614 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7615                                            SmallVectorImpl<SDValue> &Results,
7616                                            SelectionDAG &DAG) const {
7617   SDValue Res;
7618   switch (N->getOpcode()) {
7619   default:
7620     llvm_unreachable("Don't know how to custom expand this!");
7621   case ISD::READ_REGISTER:
7622     ExpandREAD_REGISTER(N, Results, DAG);
7623     break;
7624   case ISD::BITCAST:
7625     Res = ExpandBITCAST(N, DAG);
7626     break;
7627   case ISD::SRL:
7628   case ISD::SRA:
7629     Res = Expand64BitShift(N, DAG, Subtarget);
7630     break;
7631   case ISD::SREM:
7632   case ISD::UREM:
7633     Res = LowerREM(N, DAG);
7634     break;
7635   case ISD::SDIVREM:
7636   case ISD::UDIVREM:
7637     Res = LowerDivRem(SDValue(N, 0), DAG);
7638     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7639     Results.push_back(Res.getValue(0));
7640     Results.push_back(Res.getValue(1));
7641     return;
7642   case ISD::READCYCLECOUNTER:
7643     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7644     return;
7645   case ISD::UDIV:
7646   case ISD::SDIV:
7647     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7648     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7649                              Results);
7650   case ISD::ATOMIC_CMP_SWAP:
7651     ReplaceCMP_SWAP_64Results(N, Results, DAG);
7652     return;
7653   }
7654   if (Res.getNode())
7655     Results.push_back(Res);
7656 }
7657 
7658 //===----------------------------------------------------------------------===//
7659 //                           ARM Scheduler Hooks
7660 //===----------------------------------------------------------------------===//
7661 
7662 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7663 /// registers the function context.
7664 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7665                                                MachineBasicBlock *MBB,
7666                                                MachineBasicBlock *DispatchBB,
7667                                                int FI) const {
7668   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
7669          "ROPI/RWPI not currently supported with SjLj");
7670   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7671   DebugLoc dl = MI.getDebugLoc();
7672   MachineFunction *MF = MBB->getParent();
7673   MachineRegisterInfo *MRI = &MF->getRegInfo();
7674   MachineConstantPool *MCP = MF->getConstantPool();
7675   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7676   const Function *F = MF->getFunction();
7677 
7678   bool isThumb = Subtarget->isThumb();
7679   bool isThumb2 = Subtarget->isThumb2();
7680 
7681   unsigned PCLabelId = AFI->createPICLabelUId();
7682   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7683   ARMConstantPoolValue *CPV =
7684     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7685   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7686 
7687   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7688                                            : &ARM::GPRRegClass;
7689 
7690   // Grab constant pool and fixed stack memory operands.
7691   MachineMemOperand *CPMMO =
7692       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7693                                MachineMemOperand::MOLoad, 4, 4);
7694 
7695   MachineMemOperand *FIMMOSt =
7696       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7697                                MachineMemOperand::MOStore, 4, 4);
7698 
7699   // Load the address of the dispatch MBB into the jump buffer.
7700   if (isThumb2) {
7701     // Incoming value: jbuf
7702     //   ldr.n  r5, LCPI1_1
7703     //   orr    r5, r5, #1
7704     //   add    r5, pc
7705     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7706     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7707     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7708                    .addConstantPoolIndex(CPI)
7709                    .addMemOperand(CPMMO));
7710     // Set the low bit because of thumb mode.
7711     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7712     AddDefaultCC(
7713       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7714                      .addReg(NewVReg1, RegState::Kill)
7715                      .addImm(0x01)));
7716     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7717     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7718       .addReg(NewVReg2, RegState::Kill)
7719       .addImm(PCLabelId);
7720     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7721                    .addReg(NewVReg3, RegState::Kill)
7722                    .addFrameIndex(FI)
7723                    .addImm(36)  // &jbuf[1] :: pc
7724                    .addMemOperand(FIMMOSt));
7725   } else if (isThumb) {
7726     // Incoming value: jbuf
7727     //   ldr.n  r1, LCPI1_4
7728     //   add    r1, pc
7729     //   mov    r2, #1
7730     //   orrs   r1, r2
7731     //   add    r2, $jbuf, #+4 ; &jbuf[1]
7732     //   str    r1, [r2]
7733     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7734     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7735                    .addConstantPoolIndex(CPI)
7736                    .addMemOperand(CPMMO));
7737     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7738     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7739       .addReg(NewVReg1, RegState::Kill)
7740       .addImm(PCLabelId);
7741     // Set the low bit because of thumb mode.
7742     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7743     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7744                    .addReg(ARM::CPSR, RegState::Define)
7745                    .addImm(1));
7746     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7747     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7748                    .addReg(ARM::CPSR, RegState::Define)
7749                    .addReg(NewVReg2, RegState::Kill)
7750                    .addReg(NewVReg3, RegState::Kill));
7751     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7752     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7753             .addFrameIndex(FI)
7754             .addImm(36); // &jbuf[1] :: pc
7755     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7756                    .addReg(NewVReg4, RegState::Kill)
7757                    .addReg(NewVReg5, RegState::Kill)
7758                    .addImm(0)
7759                    .addMemOperand(FIMMOSt));
7760   } else {
7761     // Incoming value: jbuf
7762     //   ldr  r1, LCPI1_1
7763     //   add  r1, pc, r1
7764     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7765     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7766     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
7767                    .addConstantPoolIndex(CPI)
7768                    .addImm(0)
7769                    .addMemOperand(CPMMO));
7770     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7771     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7772                    .addReg(NewVReg1, RegState::Kill)
7773                    .addImm(PCLabelId));
7774     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7775                    .addReg(NewVReg2, RegState::Kill)
7776                    .addFrameIndex(FI)
7777                    .addImm(36)  // &jbuf[1] :: pc
7778                    .addMemOperand(FIMMOSt));
7779   }
7780 }
7781 
7782 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
7783                                               MachineBasicBlock *MBB) const {
7784   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7785   DebugLoc dl = MI.getDebugLoc();
7786   MachineFunction *MF = MBB->getParent();
7787   MachineRegisterInfo *MRI = &MF->getRegInfo();
7788   MachineFrameInfo &MFI = MF->getFrameInfo();
7789   int FI = MFI.getFunctionContextIndex();
7790 
7791   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7792                                                         : &ARM::GPRnopcRegClass;
7793 
7794   // Get a mapping of the call site numbers to all of the landing pads they're
7795   // associated with.
7796   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
7797   unsigned MaxCSNum = 0;
7798   MachineModuleInfo &MMI = MF->getMMI();
7799   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7800        ++BB) {
7801     if (!BB->isEHPad()) continue;
7802 
7803     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7804     // pad.
7805     for (MachineBasicBlock::iterator
7806            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7807       if (!II->isEHLabel()) continue;
7808 
7809       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7810       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
7811 
7812       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
7813       for (SmallVectorImpl<unsigned>::iterator
7814              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7815            CSI != CSE; ++CSI) {
7816         CallSiteNumToLPad[*CSI].push_back(&*BB);
7817         MaxCSNum = std::max(MaxCSNum, *CSI);
7818       }
7819       break;
7820     }
7821   }
7822 
7823   // Get an ordered list of the machine basic blocks for the jump table.
7824   std::vector<MachineBasicBlock*> LPadList;
7825   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
7826   LPadList.reserve(CallSiteNumToLPad.size());
7827   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7828     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7829     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7830            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7831       LPadList.push_back(*II);
7832       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7833     }
7834   }
7835 
7836   assert(!LPadList.empty() &&
7837          "No landing pad destinations for the dispatch jump table!");
7838 
7839   // Create the jump table and associated information.
7840   MachineJumpTableInfo *JTI =
7841     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7842   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7843 
7844   // Create the MBBs for the dispatch code.
7845 
7846   // Shove the dispatch's address into the return slot in the function context.
7847   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7848   DispatchBB->setIsEHPad();
7849 
7850   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7851   unsigned trap_opcode;
7852   if (Subtarget->isThumb())
7853     trap_opcode = ARM::tTRAP;
7854   else
7855     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7856 
7857   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7858   DispatchBB->addSuccessor(TrapBB);
7859 
7860   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7861   DispatchBB->addSuccessor(DispContBB);
7862 
7863   // Insert and MBBs.
7864   MF->insert(MF->end(), DispatchBB);
7865   MF->insert(MF->end(), DispContBB);
7866   MF->insert(MF->end(), TrapBB);
7867 
7868   // Insert code into the entry block that creates and registers the function
7869   // context.
7870   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7871 
7872   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7873       MachinePointerInfo::getFixedStack(*MF, FI),
7874       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7875 
7876   MachineInstrBuilder MIB;
7877   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7878 
7879   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7880   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7881 
7882   // Add a register mask with no preserved registers.  This results in all
7883   // registers being marked as clobbered. This can't work if the dispatch block
7884   // is in a Thumb1 function and is linked with ARM code which uses the FP
7885   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
7886   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
7887 
7888   bool IsPositionIndependent = isPositionIndependent();
7889   unsigned NumLPads = LPadList.size();
7890   if (Subtarget->isThumb2()) {
7891     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7892     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7893                    .addFrameIndex(FI)
7894                    .addImm(4)
7895                    .addMemOperand(FIMMOLd));
7896 
7897     if (NumLPads < 256) {
7898       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7899                      .addReg(NewVReg1)
7900                      .addImm(LPadList.size()));
7901     } else {
7902       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7903       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7904                      .addImm(NumLPads & 0xFFFF));
7905 
7906       unsigned VReg2 = VReg1;
7907       if ((NumLPads & 0xFFFF0000) != 0) {
7908         VReg2 = MRI->createVirtualRegister(TRC);
7909         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7910                        .addReg(VReg1)
7911                        .addImm(NumLPads >> 16));
7912       }
7913 
7914       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7915                      .addReg(NewVReg1)
7916                      .addReg(VReg2));
7917     }
7918 
7919     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7920       .addMBB(TrapBB)
7921       .addImm(ARMCC::HI)
7922       .addReg(ARM::CPSR);
7923 
7924     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7925     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7926                    .addJumpTableIndex(MJTI));
7927 
7928     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7929     AddDefaultCC(
7930       AddDefaultPred(
7931         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7932         .addReg(NewVReg3, RegState::Kill)
7933         .addReg(NewVReg1)
7934         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7935 
7936     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7937       .addReg(NewVReg4, RegState::Kill)
7938       .addReg(NewVReg1)
7939       .addJumpTableIndex(MJTI);
7940   } else if (Subtarget->isThumb()) {
7941     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7942     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7943                    .addFrameIndex(FI)
7944                    .addImm(1)
7945                    .addMemOperand(FIMMOLd));
7946 
7947     if (NumLPads < 256) {
7948       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7949                      .addReg(NewVReg1)
7950                      .addImm(NumLPads));
7951     } else {
7952       MachineConstantPool *ConstantPool = MF->getConstantPool();
7953       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7954       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7955 
7956       // MachineConstantPool wants an explicit alignment.
7957       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7958       if (Align == 0)
7959         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7960       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7961 
7962       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7963       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7964                      .addReg(VReg1, RegState::Define)
7965                      .addConstantPoolIndex(Idx));
7966       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7967                      .addReg(NewVReg1)
7968                      .addReg(VReg1));
7969     }
7970 
7971     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7972       .addMBB(TrapBB)
7973       .addImm(ARMCC::HI)
7974       .addReg(ARM::CPSR);
7975 
7976     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7977     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7978                    .addReg(ARM::CPSR, RegState::Define)
7979                    .addReg(NewVReg1)
7980                    .addImm(2));
7981 
7982     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7983     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7984                    .addJumpTableIndex(MJTI));
7985 
7986     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7987     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7988                    .addReg(ARM::CPSR, RegState::Define)
7989                    .addReg(NewVReg2, RegState::Kill)
7990                    .addReg(NewVReg3));
7991 
7992     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
7993         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
7994 
7995     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7996     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7997                    .addReg(NewVReg4, RegState::Kill)
7998                    .addImm(0)
7999                    .addMemOperand(JTMMOLd));
8000 
8001     unsigned NewVReg6 = NewVReg5;
8002     if (IsPositionIndependent) {
8003       NewVReg6 = MRI->createVirtualRegister(TRC);
8004       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8005                      .addReg(ARM::CPSR, RegState::Define)
8006                      .addReg(NewVReg5, RegState::Kill)
8007                      .addReg(NewVReg3));
8008     }
8009 
8010     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8011       .addReg(NewVReg6, RegState::Kill)
8012       .addJumpTableIndex(MJTI);
8013   } else {
8014     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8015     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8016                    .addFrameIndex(FI)
8017                    .addImm(4)
8018                    .addMemOperand(FIMMOLd));
8019 
8020     if (NumLPads < 256) {
8021       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8022                      .addReg(NewVReg1)
8023                      .addImm(NumLPads));
8024     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8025       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8026       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8027                      .addImm(NumLPads & 0xFFFF));
8028 
8029       unsigned VReg2 = VReg1;
8030       if ((NumLPads & 0xFFFF0000) != 0) {
8031         VReg2 = MRI->createVirtualRegister(TRC);
8032         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8033                        .addReg(VReg1)
8034                        .addImm(NumLPads >> 16));
8035       }
8036 
8037       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8038                      .addReg(NewVReg1)
8039                      .addReg(VReg2));
8040     } else {
8041       MachineConstantPool *ConstantPool = MF->getConstantPool();
8042       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8043       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8044 
8045       // MachineConstantPool wants an explicit alignment.
8046       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8047       if (Align == 0)
8048         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8049       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8050 
8051       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8052       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8053                      .addReg(VReg1, RegState::Define)
8054                      .addConstantPoolIndex(Idx)
8055                      .addImm(0));
8056       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8057                      .addReg(NewVReg1)
8058                      .addReg(VReg1, RegState::Kill));
8059     }
8060 
8061     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8062       .addMBB(TrapBB)
8063       .addImm(ARMCC::HI)
8064       .addReg(ARM::CPSR);
8065 
8066     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8067     AddDefaultCC(
8068       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8069                      .addReg(NewVReg1)
8070                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
8071     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8072     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8073                    .addJumpTableIndex(MJTI));
8074 
8075     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8076         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8077     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8078     AddDefaultPred(
8079       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8080       .addReg(NewVReg3, RegState::Kill)
8081       .addReg(NewVReg4)
8082       .addImm(0)
8083       .addMemOperand(JTMMOLd));
8084 
8085     if (IsPositionIndependent) {
8086       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8087         .addReg(NewVReg5, RegState::Kill)
8088         .addReg(NewVReg4)
8089         .addJumpTableIndex(MJTI);
8090     } else {
8091       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8092         .addReg(NewVReg5, RegState::Kill)
8093         .addJumpTableIndex(MJTI);
8094     }
8095   }
8096 
8097   // Add the jump table entries as successors to the MBB.
8098   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8099   for (std::vector<MachineBasicBlock*>::iterator
8100          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8101     MachineBasicBlock *CurMBB = *I;
8102     if (SeenMBBs.insert(CurMBB).second)
8103       DispContBB->addSuccessor(CurMBB);
8104   }
8105 
8106   // N.B. the order the invoke BBs are processed in doesn't matter here.
8107   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8108   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8109   for (MachineBasicBlock *BB : InvokeBBs) {
8110 
8111     // Remove the landing pad successor from the invoke block and replace it
8112     // with the new dispatch block.
8113     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8114                                                   BB->succ_end());
8115     while (!Successors.empty()) {
8116       MachineBasicBlock *SMBB = Successors.pop_back_val();
8117       if (SMBB->isEHPad()) {
8118         BB->removeSuccessor(SMBB);
8119         MBBLPads.push_back(SMBB);
8120       }
8121     }
8122 
8123     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8124     BB->normalizeSuccProbs();
8125 
8126     // Find the invoke call and mark all of the callee-saved registers as
8127     // 'implicit defined' so that they're spilled. This prevents code from
8128     // moving instructions to before the EH block, where they will never be
8129     // executed.
8130     for (MachineBasicBlock::reverse_iterator
8131            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8132       if (!II->isCall()) continue;
8133 
8134       DenseMap<unsigned, bool> DefRegs;
8135       for (MachineInstr::mop_iterator
8136              OI = II->operands_begin(), OE = II->operands_end();
8137            OI != OE; ++OI) {
8138         if (!OI->isReg()) continue;
8139         DefRegs[OI->getReg()] = true;
8140       }
8141 
8142       MachineInstrBuilder MIB(*MF, &*II);
8143 
8144       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8145         unsigned Reg = SavedRegs[i];
8146         if (Subtarget->isThumb2() &&
8147             !ARM::tGPRRegClass.contains(Reg) &&
8148             !ARM::hGPRRegClass.contains(Reg))
8149           continue;
8150         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8151           continue;
8152         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8153           continue;
8154         if (!DefRegs[Reg])
8155           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8156       }
8157 
8158       break;
8159     }
8160   }
8161 
8162   // Mark all former landing pads as non-landing pads. The dispatch is the only
8163   // landing pad now.
8164   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8165          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8166     (*I)->setIsEHPad(false);
8167 
8168   // The instruction is gone now.
8169   MI.eraseFromParent();
8170 }
8171 
8172 static
8173 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8174   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8175        E = MBB->succ_end(); I != E; ++I)
8176     if (*I != Succ)
8177       return *I;
8178   llvm_unreachable("Expecting a BB with two successors!");
8179 }
8180 
8181 /// Return the load opcode for a given load size. If load size >= 8,
8182 /// neon opcode will be returned.
8183 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8184   if (LdSize >= 8)
8185     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8186                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8187   if (IsThumb1)
8188     return LdSize == 4 ? ARM::tLDRi
8189                        : LdSize == 2 ? ARM::tLDRHi
8190                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8191   if (IsThumb2)
8192     return LdSize == 4 ? ARM::t2LDR_POST
8193                        : LdSize == 2 ? ARM::t2LDRH_POST
8194                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8195   return LdSize == 4 ? ARM::LDR_POST_IMM
8196                      : LdSize == 2 ? ARM::LDRH_POST
8197                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8198 }
8199 
8200 /// Return the store opcode for a given store size. If store size >= 8,
8201 /// neon opcode will be returned.
8202 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8203   if (StSize >= 8)
8204     return StSize == 16 ? ARM::VST1q32wb_fixed
8205                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8206   if (IsThumb1)
8207     return StSize == 4 ? ARM::tSTRi
8208                        : StSize == 2 ? ARM::tSTRHi
8209                                      : StSize == 1 ? ARM::tSTRBi : 0;
8210   if (IsThumb2)
8211     return StSize == 4 ? ARM::t2STR_POST
8212                        : StSize == 2 ? ARM::t2STRH_POST
8213                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8214   return StSize == 4 ? ARM::STR_POST_IMM
8215                      : StSize == 2 ? ARM::STRH_POST
8216                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8217 }
8218 
8219 /// Emit a post-increment load operation with given size. The instructions
8220 /// will be added to BB at Pos.
8221 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8222                        const TargetInstrInfo *TII, const DebugLoc &dl,
8223                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8224                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8225   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8226   assert(LdOpc != 0 && "Should have a load opcode");
8227   if (LdSize >= 8) {
8228     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8229                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
8230                        .addImm(0));
8231   } else if (IsThumb1) {
8232     // load + update AddrIn
8233     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8234                        .addReg(AddrIn).addImm(0));
8235     MachineInstrBuilder MIB =
8236         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
8237     MIB = AddDefaultT1CC(MIB);
8238     MIB.addReg(AddrIn).addImm(LdSize);
8239     AddDefaultPred(MIB);
8240   } else if (IsThumb2) {
8241     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8242                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
8243                        .addImm(LdSize));
8244   } else { // arm
8245     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8246                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
8247                        .addReg(0).addImm(LdSize));
8248   }
8249 }
8250 
8251 /// Emit a post-increment store operation with given size. The instructions
8252 /// will be added to BB at Pos.
8253 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8254                        const TargetInstrInfo *TII, const DebugLoc &dl,
8255                        unsigned StSize, unsigned Data, unsigned AddrIn,
8256                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8257   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8258   assert(StOpc != 0 && "Should have a store opcode");
8259   if (StSize >= 8) {
8260     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8261                        .addReg(AddrIn).addImm(0).addReg(Data));
8262   } else if (IsThumb1) {
8263     // store + update AddrIn
8264     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
8265                        .addReg(AddrIn).addImm(0));
8266     MachineInstrBuilder MIB =
8267         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
8268     MIB = AddDefaultT1CC(MIB);
8269     MIB.addReg(AddrIn).addImm(StSize);
8270     AddDefaultPred(MIB);
8271   } else if (IsThumb2) {
8272     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8273                        .addReg(Data).addReg(AddrIn).addImm(StSize));
8274   } else { // arm
8275     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8276                        .addReg(Data).addReg(AddrIn).addReg(0)
8277                        .addImm(StSize));
8278   }
8279 }
8280 
8281 MachineBasicBlock *
8282 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8283                                    MachineBasicBlock *BB) const {
8284   // This pseudo instruction has 3 operands: dst, src, size
8285   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8286   // Otherwise, we will generate unrolled scalar copies.
8287   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8288   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8289   MachineFunction::iterator It = ++BB->getIterator();
8290 
8291   unsigned dest = MI.getOperand(0).getReg();
8292   unsigned src = MI.getOperand(1).getReg();
8293   unsigned SizeVal = MI.getOperand(2).getImm();
8294   unsigned Align = MI.getOperand(3).getImm();
8295   DebugLoc dl = MI.getDebugLoc();
8296 
8297   MachineFunction *MF = BB->getParent();
8298   MachineRegisterInfo &MRI = MF->getRegInfo();
8299   unsigned UnitSize = 0;
8300   const TargetRegisterClass *TRC = nullptr;
8301   const TargetRegisterClass *VecTRC = nullptr;
8302 
8303   bool IsThumb1 = Subtarget->isThumb1Only();
8304   bool IsThumb2 = Subtarget->isThumb2();
8305   bool IsThumb = Subtarget->isThumb();
8306 
8307   if (Align & 1) {
8308     UnitSize = 1;
8309   } else if (Align & 2) {
8310     UnitSize = 2;
8311   } else {
8312     // Check whether we can use NEON instructions.
8313     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
8314         Subtarget->hasNEON()) {
8315       if ((Align % 16 == 0) && SizeVal >= 16)
8316         UnitSize = 16;
8317       else if ((Align % 8 == 0) && SizeVal >= 8)
8318         UnitSize = 8;
8319     }
8320     // Can't use NEON instructions.
8321     if (UnitSize == 0)
8322       UnitSize = 4;
8323   }
8324 
8325   // Select the correct opcode and register class for unit size load/store
8326   bool IsNeon = UnitSize >= 8;
8327   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8328   if (IsNeon)
8329     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8330                             : UnitSize == 8 ? &ARM::DPRRegClass
8331                                             : nullptr;
8332 
8333   unsigned BytesLeft = SizeVal % UnitSize;
8334   unsigned LoopSize = SizeVal - BytesLeft;
8335 
8336   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8337     // Use LDR and STR to copy.
8338     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8339     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8340     unsigned srcIn = src;
8341     unsigned destIn = dest;
8342     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8343       unsigned srcOut = MRI.createVirtualRegister(TRC);
8344       unsigned destOut = MRI.createVirtualRegister(TRC);
8345       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8346       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8347                  IsThumb1, IsThumb2);
8348       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8349                  IsThumb1, IsThumb2);
8350       srcIn = srcOut;
8351       destIn = destOut;
8352     }
8353 
8354     // Handle the leftover bytes with LDRB and STRB.
8355     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8356     // [destOut] = STRB_POST(scratch, destIn, 1)
8357     for (unsigned i = 0; i < BytesLeft; i++) {
8358       unsigned srcOut = MRI.createVirtualRegister(TRC);
8359       unsigned destOut = MRI.createVirtualRegister(TRC);
8360       unsigned scratch = MRI.createVirtualRegister(TRC);
8361       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8362                  IsThumb1, IsThumb2);
8363       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8364                  IsThumb1, IsThumb2);
8365       srcIn = srcOut;
8366       destIn = destOut;
8367     }
8368     MI.eraseFromParent(); // The instruction is gone now.
8369     return BB;
8370   }
8371 
8372   // Expand the pseudo op to a loop.
8373   // thisMBB:
8374   //   ...
8375   //   movw varEnd, # --> with thumb2
8376   //   movt varEnd, #
8377   //   ldrcp varEnd, idx --> without thumb2
8378   //   fallthrough --> loopMBB
8379   // loopMBB:
8380   //   PHI varPhi, varEnd, varLoop
8381   //   PHI srcPhi, src, srcLoop
8382   //   PHI destPhi, dst, destLoop
8383   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8384   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8385   //   subs varLoop, varPhi, #UnitSize
8386   //   bne loopMBB
8387   //   fallthrough --> exitMBB
8388   // exitMBB:
8389   //   epilogue to handle left-over bytes
8390   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8391   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8392   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8393   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8394   MF->insert(It, loopMBB);
8395   MF->insert(It, exitMBB);
8396 
8397   // Transfer the remainder of BB and its successor edges to exitMBB.
8398   exitMBB->splice(exitMBB->begin(), BB,
8399                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8400   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8401 
8402   // Load an immediate to varEnd.
8403   unsigned varEnd = MRI.createVirtualRegister(TRC);
8404   if (Subtarget->useMovt(*MF)) {
8405     unsigned Vtmp = varEnd;
8406     if ((LoopSize & 0xFFFF0000) != 0)
8407       Vtmp = MRI.createVirtualRegister(TRC);
8408     AddDefaultPred(BuildMI(BB, dl,
8409                            TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16),
8410                            Vtmp).addImm(LoopSize & 0xFFFF));
8411 
8412     if ((LoopSize & 0xFFFF0000) != 0)
8413       AddDefaultPred(BuildMI(BB, dl,
8414                              TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16),
8415                              varEnd)
8416                          .addReg(Vtmp)
8417                          .addImm(LoopSize >> 16));
8418   } else {
8419     MachineConstantPool *ConstantPool = MF->getConstantPool();
8420     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8421     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8422 
8423     // MachineConstantPool wants an explicit alignment.
8424     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8425     if (Align == 0)
8426       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8427     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8428 
8429     if (IsThumb)
8430       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
8431           varEnd, RegState::Define).addConstantPoolIndex(Idx));
8432     else
8433       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
8434           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
8435   }
8436   BB->addSuccessor(loopMBB);
8437 
8438   // Generate the loop body:
8439   //   varPhi = PHI(varLoop, varEnd)
8440   //   srcPhi = PHI(srcLoop, src)
8441   //   destPhi = PHI(destLoop, dst)
8442   MachineBasicBlock *entryBB = BB;
8443   BB = loopMBB;
8444   unsigned varLoop = MRI.createVirtualRegister(TRC);
8445   unsigned varPhi = MRI.createVirtualRegister(TRC);
8446   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8447   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8448   unsigned destLoop = MRI.createVirtualRegister(TRC);
8449   unsigned destPhi = MRI.createVirtualRegister(TRC);
8450 
8451   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8452     .addReg(varLoop).addMBB(loopMBB)
8453     .addReg(varEnd).addMBB(entryBB);
8454   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8455     .addReg(srcLoop).addMBB(loopMBB)
8456     .addReg(src).addMBB(entryBB);
8457   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8458     .addReg(destLoop).addMBB(loopMBB)
8459     .addReg(dest).addMBB(entryBB);
8460 
8461   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8462   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8463   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8464   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8465              IsThumb1, IsThumb2);
8466   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8467              IsThumb1, IsThumb2);
8468 
8469   // Decrement loop variable by UnitSize.
8470   if (IsThumb1) {
8471     MachineInstrBuilder MIB =
8472         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
8473     MIB = AddDefaultT1CC(MIB);
8474     MIB.addReg(varPhi).addImm(UnitSize);
8475     AddDefaultPred(MIB);
8476   } else {
8477     MachineInstrBuilder MIB =
8478         BuildMI(*BB, BB->end(), dl,
8479                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8480     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
8481     MIB->getOperand(5).setReg(ARM::CPSR);
8482     MIB->getOperand(5).setIsDef(true);
8483   }
8484   BuildMI(*BB, BB->end(), dl,
8485           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8486       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8487 
8488   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8489   BB->addSuccessor(loopMBB);
8490   BB->addSuccessor(exitMBB);
8491 
8492   // Add epilogue to handle BytesLeft.
8493   BB = exitMBB;
8494   auto StartOfExit = exitMBB->begin();
8495 
8496   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8497   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8498   unsigned srcIn = srcLoop;
8499   unsigned destIn = destLoop;
8500   for (unsigned i = 0; i < BytesLeft; i++) {
8501     unsigned srcOut = MRI.createVirtualRegister(TRC);
8502     unsigned destOut = MRI.createVirtualRegister(TRC);
8503     unsigned scratch = MRI.createVirtualRegister(TRC);
8504     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8505                IsThumb1, IsThumb2);
8506     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8507                IsThumb1, IsThumb2);
8508     srcIn = srcOut;
8509     destIn = destOut;
8510   }
8511 
8512   MI.eraseFromParent(); // The instruction is gone now.
8513   return BB;
8514 }
8515 
8516 MachineBasicBlock *
8517 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8518                                        MachineBasicBlock *MBB) const {
8519   const TargetMachine &TM = getTargetMachine();
8520   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8521   DebugLoc DL = MI.getDebugLoc();
8522 
8523   assert(Subtarget->isTargetWindows() &&
8524          "__chkstk is only supported on Windows");
8525   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8526 
8527   // __chkstk takes the number of words to allocate on the stack in R4, and
8528   // returns the stack adjustment in number of bytes in R4.  This will not
8529   // clober any other registers (other than the obvious lr).
8530   //
8531   // Although, technically, IP should be considered a register which may be
8532   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8533   // thumb-2 environment, so there is no interworking required.  As a result, we
8534   // do not expect a veneer to be emitted by the linker, clobbering IP.
8535   //
8536   // Each module receives its own copy of __chkstk, so no import thunk is
8537   // required, again, ensuring that IP is not clobbered.
8538   //
8539   // Finally, although some linkers may theoretically provide a trampoline for
8540   // out of range calls (which is quite common due to a 32M range limitation of
8541   // branches for Thumb), we can generate the long-call version via
8542   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8543   // IP.
8544 
8545   switch (TM.getCodeModel()) {
8546   case CodeModel::Small:
8547   case CodeModel::Medium:
8548   case CodeModel::Default:
8549   case CodeModel::Kernel:
8550     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8551       .addImm((unsigned)ARMCC::AL).addReg(0)
8552       .addExternalSymbol("__chkstk")
8553       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8554       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8555       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
8556     break;
8557   case CodeModel::Large:
8558   case CodeModel::JITDefault: {
8559     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8560     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8561 
8562     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8563       .addExternalSymbol("__chkstk");
8564     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8565       .addImm((unsigned)ARMCC::AL).addReg(0)
8566       .addReg(Reg, RegState::Kill)
8567       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8568       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8569       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
8570     break;
8571   }
8572   }
8573 
8574   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
8575                                       ARM::SP)
8576                          .addReg(ARM::SP, RegState::Kill)
8577                          .addReg(ARM::R4, RegState::Kill)
8578                          .setMIFlags(MachineInstr::FrameSetup)));
8579 
8580   MI.eraseFromParent();
8581   return MBB;
8582 }
8583 
8584 MachineBasicBlock *
8585 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8586                                        MachineBasicBlock *MBB) const {
8587   DebugLoc DL = MI.getDebugLoc();
8588   MachineFunction *MF = MBB->getParent();
8589   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8590 
8591   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8592   MF->insert(++MBB->getIterator(), ContBB);
8593   ContBB->splice(ContBB->begin(), MBB,
8594                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8595   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8596   MBB->addSuccessor(ContBB);
8597 
8598   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8599   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
8600   MF->push_back(TrapBB);
8601   MBB->addSuccessor(TrapBB);
8602 
8603   AddDefaultPred(BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
8604                      .addReg(MI.getOperand(0).getReg())
8605                      .addImm(0));
8606   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
8607       .addMBB(TrapBB)
8608       .addImm(ARMCC::EQ)
8609       .addReg(ARM::CPSR);
8610 
8611   MI.eraseFromParent();
8612   return ContBB;
8613 }
8614 
8615 MachineBasicBlock *
8616 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8617                                                MachineBasicBlock *BB) const {
8618   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8619   DebugLoc dl = MI.getDebugLoc();
8620   bool isThumb2 = Subtarget->isThumb2();
8621   switch (MI.getOpcode()) {
8622   default: {
8623     MI.dump();
8624     llvm_unreachable("Unexpected instr type to insert");
8625   }
8626 
8627   // Thumb1 post-indexed loads are really just single-register LDMs.
8628   case ARM::tLDR_postidx: {
8629     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8630       .addOperand(MI.getOperand(1)) // Rn_wb
8631       .addOperand(MI.getOperand(2)) // Rn
8632       .addOperand(MI.getOperand(3)) // PredImm
8633       .addOperand(MI.getOperand(4)) // PredReg
8634       .addOperand(MI.getOperand(0)); // Rt
8635     MI.eraseFromParent();
8636     return BB;
8637   }
8638 
8639   // The Thumb2 pre-indexed stores have the same MI operands, they just
8640   // define them differently in the .td files from the isel patterns, so
8641   // they need pseudos.
8642   case ARM::t2STR_preidx:
8643     MI.setDesc(TII->get(ARM::t2STR_PRE));
8644     return BB;
8645   case ARM::t2STRB_preidx:
8646     MI.setDesc(TII->get(ARM::t2STRB_PRE));
8647     return BB;
8648   case ARM::t2STRH_preidx:
8649     MI.setDesc(TII->get(ARM::t2STRH_PRE));
8650     return BB;
8651 
8652   case ARM::STRi_preidx:
8653   case ARM::STRBi_preidx: {
8654     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
8655                                                          : ARM::STRB_PRE_IMM;
8656     // Decode the offset.
8657     unsigned Offset = MI.getOperand(4).getImm();
8658     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8659     Offset = ARM_AM::getAM2Offset(Offset);
8660     if (isSub)
8661       Offset = -Offset;
8662 
8663     MachineMemOperand *MMO = *MI.memoperands_begin();
8664     BuildMI(*BB, MI, dl, TII->get(NewOpc))
8665         .addOperand(MI.getOperand(0)) // Rn_wb
8666         .addOperand(MI.getOperand(1)) // Rt
8667         .addOperand(MI.getOperand(2)) // Rn
8668         .addImm(Offset)               // offset (skip GPR==zero_reg)
8669         .addOperand(MI.getOperand(5)) // pred
8670         .addOperand(MI.getOperand(6))
8671         .addMemOperand(MMO);
8672     MI.eraseFromParent();
8673     return BB;
8674   }
8675   case ARM::STRr_preidx:
8676   case ARM::STRBr_preidx:
8677   case ARM::STRH_preidx: {
8678     unsigned NewOpc;
8679     switch (MI.getOpcode()) {
8680     default: llvm_unreachable("unexpected opcode!");
8681     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8682     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8683     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8684     }
8685     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8686     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
8687       MIB.addOperand(MI.getOperand(i));
8688     MI.eraseFromParent();
8689     return BB;
8690   }
8691 
8692   case ARM::tMOVCCr_pseudo: {
8693     // To "insert" a SELECT_CC instruction, we actually have to insert the
8694     // diamond control-flow pattern.  The incoming instruction knows the
8695     // destination vreg to set, the condition code register to branch on, the
8696     // true/false values to select between, and a branch opcode to use.
8697     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8698     MachineFunction::iterator It = ++BB->getIterator();
8699 
8700     //  thisMBB:
8701     //  ...
8702     //   TrueVal = ...
8703     //   cmpTY ccX, r1, r2
8704     //   bCC copy1MBB
8705     //   fallthrough --> copy0MBB
8706     MachineBasicBlock *thisMBB  = BB;
8707     MachineFunction *F = BB->getParent();
8708     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8709     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
8710     F->insert(It, copy0MBB);
8711     F->insert(It, sinkMBB);
8712 
8713     // Transfer the remainder of BB and its successor edges to sinkMBB.
8714     sinkMBB->splice(sinkMBB->begin(), BB,
8715                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8716     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8717 
8718     BB->addSuccessor(copy0MBB);
8719     BB->addSuccessor(sinkMBB);
8720 
8721     BuildMI(BB, dl, TII->get(ARM::tBcc))
8722         .addMBB(sinkMBB)
8723         .addImm(MI.getOperand(3).getImm())
8724         .addReg(MI.getOperand(4).getReg());
8725 
8726     //  copy0MBB:
8727     //   %FalseValue = ...
8728     //   # fallthrough to sinkMBB
8729     BB = copy0MBB;
8730 
8731     // Update machine-CFG edges
8732     BB->addSuccessor(sinkMBB);
8733 
8734     //  sinkMBB:
8735     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8736     //  ...
8737     BB = sinkMBB;
8738     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
8739         .addReg(MI.getOperand(1).getReg())
8740         .addMBB(copy0MBB)
8741         .addReg(MI.getOperand(2).getReg())
8742         .addMBB(thisMBB);
8743 
8744     MI.eraseFromParent(); // The pseudo instruction is gone now.
8745     return BB;
8746   }
8747 
8748   case ARM::BCCi64:
8749   case ARM::BCCZi64: {
8750     // If there is an unconditional branch to the other successor, remove it.
8751     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8752 
8753     // Compare both parts that make up the double comparison separately for
8754     // equality.
8755     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
8756 
8757     unsigned LHS1 = MI.getOperand(1).getReg();
8758     unsigned LHS2 = MI.getOperand(2).getReg();
8759     if (RHSisZero) {
8760       AddDefaultPred(BuildMI(BB, dl,
8761                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8762                      .addReg(LHS1).addImm(0));
8763       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8764         .addReg(LHS2).addImm(0)
8765         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8766     } else {
8767       unsigned RHS1 = MI.getOperand(3).getReg();
8768       unsigned RHS2 = MI.getOperand(4).getReg();
8769       AddDefaultPred(BuildMI(BB, dl,
8770                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8771                      .addReg(LHS1).addReg(RHS1));
8772       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8773         .addReg(LHS2).addReg(RHS2)
8774         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8775     }
8776 
8777     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
8778     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8779     if (MI.getOperand(0).getImm() == ARMCC::NE)
8780       std::swap(destMBB, exitMBB);
8781 
8782     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8783       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8784     if (isThumb2)
8785       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
8786     else
8787       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8788 
8789     MI.eraseFromParent(); // The pseudo instruction is gone now.
8790     return BB;
8791   }
8792 
8793   case ARM::Int_eh_sjlj_setjmp:
8794   case ARM::Int_eh_sjlj_setjmp_nofp:
8795   case ARM::tInt_eh_sjlj_setjmp:
8796   case ARM::t2Int_eh_sjlj_setjmp:
8797   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8798     return BB;
8799 
8800   case ARM::Int_eh_sjlj_setup_dispatch:
8801     EmitSjLjDispatchBlock(MI, BB);
8802     return BB;
8803 
8804   case ARM::ABS:
8805   case ARM::t2ABS: {
8806     // To insert an ABS instruction, we have to insert the
8807     // diamond control-flow pattern.  The incoming instruction knows the
8808     // source vreg to test against 0, the destination vreg to set,
8809     // the condition code register to branch on, the
8810     // true/false values to select between, and a branch opcode to use.
8811     // It transforms
8812     //     V1 = ABS V0
8813     // into
8814     //     V2 = MOVS V0
8815     //     BCC                      (branch to SinkBB if V0 >= 0)
8816     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8817     //     SinkBB: V1 = PHI(V2, V3)
8818     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8819     MachineFunction::iterator BBI = ++BB->getIterator();
8820     MachineFunction *Fn = BB->getParent();
8821     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8822     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8823     Fn->insert(BBI, RSBBB);
8824     Fn->insert(BBI, SinkBB);
8825 
8826     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
8827     unsigned int ABSDstReg = MI.getOperand(0).getReg();
8828     bool ABSSrcKIll = MI.getOperand(1).isKill();
8829     bool isThumb2 = Subtarget->isThumb2();
8830     MachineRegisterInfo &MRI = Fn->getRegInfo();
8831     // In Thumb mode S must not be specified if source register is the SP or
8832     // PC and if destination register is the SP, so restrict register class
8833     unsigned NewRsbDstReg =
8834       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
8835 
8836     // Transfer the remainder of BB and its successor edges to sinkMBB.
8837     SinkBB->splice(SinkBB->begin(), BB,
8838                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
8839     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
8840 
8841     BB->addSuccessor(RSBBB);
8842     BB->addSuccessor(SinkBB);
8843 
8844     // fall through to SinkMBB
8845     RSBBB->addSuccessor(SinkBB);
8846 
8847     // insert a cmp at the end of BB
8848     AddDefaultPred(BuildMI(BB, dl,
8849                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8850                    .addReg(ABSSrcReg).addImm(0));
8851 
8852     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
8853     BuildMI(BB, dl,
8854       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
8855       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
8856 
8857     // insert rsbri in RSBBB
8858     // Note: BCC and rsbri will be converted into predicated rsbmi
8859     // by if-conversion pass
8860     BuildMI(*RSBBB, RSBBB->begin(), dl,
8861       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
8862       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
8863       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
8864 
8865     // insert PHI in SinkBB,
8866     // reuse ABSDstReg to not change uses of ABS instruction
8867     BuildMI(*SinkBB, SinkBB->begin(), dl,
8868       TII->get(ARM::PHI), ABSDstReg)
8869       .addReg(NewRsbDstReg).addMBB(RSBBB)
8870       .addReg(ABSSrcReg).addMBB(BB);
8871 
8872     // remove ABS instruction
8873     MI.eraseFromParent();
8874 
8875     // return last added BB
8876     return SinkBB;
8877   }
8878   case ARM::COPY_STRUCT_BYVAL_I32:
8879     ++NumLoopByVals;
8880     return EmitStructByval(MI, BB);
8881   case ARM::WIN__CHKSTK:
8882     return EmitLowered__chkstk(MI, BB);
8883   case ARM::WIN__DBZCHK:
8884     return EmitLowered__dbzchk(MI, BB);
8885   }
8886 }
8887 
8888 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
8889 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
8890 /// instead of as a custom inserter because we need the use list from the SDNode.
8891 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
8892                                     MachineInstr &MI, const SDNode *Node) {
8893   bool isThumb1 = Subtarget->isThumb1Only();
8894 
8895   DebugLoc DL = MI.getDebugLoc();
8896   MachineFunction *MF = MI.getParent()->getParent();
8897   MachineRegisterInfo &MRI = MF->getRegInfo();
8898   MachineInstrBuilder MIB(*MF, MI);
8899 
8900   // If the new dst/src is unused mark it as dead.
8901   if (!Node->hasAnyUseOfValue(0)) {
8902     MI.getOperand(0).setIsDead(true);
8903   }
8904   if (!Node->hasAnyUseOfValue(1)) {
8905     MI.getOperand(1).setIsDead(true);
8906   }
8907 
8908   // The MEMCPY both defines and kills the scratch registers.
8909   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
8910     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
8911                                                          : &ARM::GPRRegClass);
8912     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
8913   }
8914 }
8915 
8916 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
8917                                                       SDNode *Node) const {
8918   if (MI.getOpcode() == ARM::MEMCPY) {
8919     attachMEMCPYScratchRegs(Subtarget, MI, Node);
8920     return;
8921   }
8922 
8923   const MCInstrDesc *MCID = &MI.getDesc();
8924   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8925   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8926   // operand is still set to noreg. If needed, set the optional operand's
8927   // register to CPSR, and remove the redundant implicit def.
8928   //
8929   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8930 
8931   // Rename pseudo opcodes.
8932   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
8933   if (NewOpc) {
8934     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8935     MCID = &TII->get(NewOpc);
8936 
8937     assert(MCID->getNumOperands() == MI.getDesc().getNumOperands() + 1 &&
8938            "converted opcode should be the same except for cc_out");
8939 
8940     MI.setDesc(*MCID);
8941 
8942     // Add the optional cc_out operand
8943     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8944   }
8945   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8946 
8947   // Any ARM instruction that sets the 's' bit should specify an optional
8948   // "cc_out" operand in the last operand position.
8949   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8950     assert(!NewOpc && "Optional cc_out operand required");
8951     return;
8952   }
8953   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8954   // since we already have an optional CPSR def.
8955   bool definesCPSR = false;
8956   bool deadCPSR = false;
8957   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
8958        ++i) {
8959     const MachineOperand &MO = MI.getOperand(i);
8960     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8961       definesCPSR = true;
8962       if (MO.isDead())
8963         deadCPSR = true;
8964       MI.RemoveOperand(i);
8965       break;
8966     }
8967   }
8968   if (!definesCPSR) {
8969     assert(!NewOpc && "Optional cc_out operand required");
8970     return;
8971   }
8972   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8973   if (deadCPSR) {
8974     assert(!MI.getOperand(ccOutIdx).getReg() &&
8975            "expect uninitialized optional cc_out operand");
8976     return;
8977   }
8978 
8979   // If this instruction was defined with an optional CPSR def and its dag node
8980   // had a live implicit CPSR def, then activate the optional CPSR def.
8981   MachineOperand &MO = MI.getOperand(ccOutIdx);
8982   MO.setReg(ARM::CPSR);
8983   MO.setIsDef(true);
8984 }
8985 
8986 //===----------------------------------------------------------------------===//
8987 //                           ARM Optimization Hooks
8988 //===----------------------------------------------------------------------===//
8989 
8990 // Helper function that checks if N is a null or all ones constant.
8991 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8992   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
8993 }
8994 
8995 // Return true if N is conditionally 0 or all ones.
8996 // Detects these expressions where cc is an i1 value:
8997 //
8998 //   (select cc 0, y)   [AllOnes=0]
8999 //   (select cc y, 0)   [AllOnes=0]
9000 //   (zext cc)          [AllOnes=0]
9001 //   (sext cc)          [AllOnes=0/1]
9002 //   (select cc -1, y)  [AllOnes=1]
9003 //   (select cc y, -1)  [AllOnes=1]
9004 //
9005 // Invert is set when N is the null/all ones constant when CC is false.
9006 // OtherOp is set to the alternative value of N.
9007 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9008                                        SDValue &CC, bool &Invert,
9009                                        SDValue &OtherOp,
9010                                        SelectionDAG &DAG) {
9011   switch (N->getOpcode()) {
9012   default: return false;
9013   case ISD::SELECT: {
9014     CC = N->getOperand(0);
9015     SDValue N1 = N->getOperand(1);
9016     SDValue N2 = N->getOperand(2);
9017     if (isZeroOrAllOnes(N1, AllOnes)) {
9018       Invert = false;
9019       OtherOp = N2;
9020       return true;
9021     }
9022     if (isZeroOrAllOnes(N2, AllOnes)) {
9023       Invert = true;
9024       OtherOp = N1;
9025       return true;
9026     }
9027     return false;
9028   }
9029   case ISD::ZERO_EXTEND:
9030     // (zext cc) can never be the all ones value.
9031     if (AllOnes)
9032       return false;
9033     LLVM_FALLTHROUGH;
9034   case ISD::SIGN_EXTEND: {
9035     SDLoc dl(N);
9036     EVT VT = N->getValueType(0);
9037     CC = N->getOperand(0);
9038     if (CC.getValueType() != MVT::i1)
9039       return false;
9040     Invert = !AllOnes;
9041     if (AllOnes)
9042       // When looking for an AllOnes constant, N is an sext, and the 'other'
9043       // value is 0.
9044       OtherOp = DAG.getConstant(0, dl, VT);
9045     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9046       // When looking for a 0 constant, N can be zext or sext.
9047       OtherOp = DAG.getConstant(1, dl, VT);
9048     else
9049       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9050                                 VT);
9051     return true;
9052   }
9053   }
9054 }
9055 
9056 // Combine a constant select operand into its use:
9057 //
9058 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9059 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9060 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9061 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9062 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9063 //
9064 // The transform is rejected if the select doesn't have a constant operand that
9065 // is null, or all ones when AllOnes is set.
9066 //
9067 // Also recognize sext/zext from i1:
9068 //
9069 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9070 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9071 //
9072 // These transformations eventually create predicated instructions.
9073 //
9074 // @param N       The node to transform.
9075 // @param Slct    The N operand that is a select.
9076 // @param OtherOp The other N operand (x above).
9077 // @param DCI     Context.
9078 // @param AllOnes Require the select constant to be all ones instead of null.
9079 // @returns The new node, or SDValue() on failure.
9080 static
9081 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9082                             TargetLowering::DAGCombinerInfo &DCI,
9083                             bool AllOnes = false) {
9084   SelectionDAG &DAG = DCI.DAG;
9085   EVT VT = N->getValueType(0);
9086   SDValue NonConstantVal;
9087   SDValue CCOp;
9088   bool SwapSelectOps;
9089   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9090                                   NonConstantVal, DAG))
9091     return SDValue();
9092 
9093   // Slct is now know to be the desired identity constant when CC is true.
9094   SDValue TrueVal = OtherOp;
9095   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9096                                  OtherOp, NonConstantVal);
9097   // Unless SwapSelectOps says CC should be false.
9098   if (SwapSelectOps)
9099     std::swap(TrueVal, FalseVal);
9100 
9101   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9102                      CCOp, TrueVal, FalseVal);
9103 }
9104 
9105 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9106 static
9107 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9108                                        TargetLowering::DAGCombinerInfo &DCI) {
9109   SDValue N0 = N->getOperand(0);
9110   SDValue N1 = N->getOperand(1);
9111   if (N0.getNode()->hasOneUse())
9112     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9113       return Result;
9114   if (N1.getNode()->hasOneUse())
9115     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9116       return Result;
9117   return SDValue();
9118 }
9119 
9120 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
9121 // (only after legalization).
9122 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9123                                  TargetLowering::DAGCombinerInfo &DCI,
9124                                  const ARMSubtarget *Subtarget) {
9125 
9126   // Only perform optimization if after legalize, and if NEON is available. We
9127   // also expected both operands to be BUILD_VECTORs.
9128   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9129       || N0.getOpcode() != ISD::BUILD_VECTOR
9130       || N1.getOpcode() != ISD::BUILD_VECTOR)
9131     return SDValue();
9132 
9133   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9134   EVT VT = N->getValueType(0);
9135   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9136     return SDValue();
9137 
9138   // Check that the vector operands are of the right form.
9139   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9140   // operands, where N is the size of the formed vector.
9141   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9142   // index such that we have a pair wise add pattern.
9143 
9144   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9145   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9146     return SDValue();
9147   SDValue Vec = N0->getOperand(0)->getOperand(0);
9148   SDNode *V = Vec.getNode();
9149   unsigned nextIndex = 0;
9150 
9151   // For each operands to the ADD which are BUILD_VECTORs,
9152   // check to see if each of their operands are an EXTRACT_VECTOR with
9153   // the same vector and appropriate index.
9154   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9155     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9156         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9157 
9158       SDValue ExtVec0 = N0->getOperand(i);
9159       SDValue ExtVec1 = N1->getOperand(i);
9160 
9161       // First operand is the vector, verify its the same.
9162       if (V != ExtVec0->getOperand(0).getNode() ||
9163           V != ExtVec1->getOperand(0).getNode())
9164         return SDValue();
9165 
9166       // Second is the constant, verify its correct.
9167       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9168       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9169 
9170       // For the constant, we want to see all the even or all the odd.
9171       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9172           || C1->getZExtValue() != nextIndex+1)
9173         return SDValue();
9174 
9175       // Increment index.
9176       nextIndex+=2;
9177     } else
9178       return SDValue();
9179   }
9180 
9181   // Create VPADDL node.
9182   SelectionDAG &DAG = DCI.DAG;
9183   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9184 
9185   SDLoc dl(N);
9186 
9187   // Build operand list.
9188   SmallVector<SDValue, 8> Ops;
9189   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9190                                 TLI.getPointerTy(DAG.getDataLayout())));
9191 
9192   // Input is the vector.
9193   Ops.push_back(Vec);
9194 
9195   // Get widened type and narrowed type.
9196   MVT widenType;
9197   unsigned numElem = VT.getVectorNumElements();
9198 
9199   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9200   switch (inputLaneType.getSimpleVT().SimpleTy) {
9201     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9202     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9203     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9204     default:
9205       llvm_unreachable("Invalid vector element type for padd optimization.");
9206   }
9207 
9208   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9209   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9210   return DAG.getNode(ExtOp, dl, VT, tmp);
9211 }
9212 
9213 static SDValue findMUL_LOHI(SDValue V) {
9214   if (V->getOpcode() == ISD::UMUL_LOHI ||
9215       V->getOpcode() == ISD::SMUL_LOHI)
9216     return V;
9217   return SDValue();
9218 }
9219 
9220 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
9221                                      TargetLowering::DAGCombinerInfo &DCI,
9222                                      const ARMSubtarget *Subtarget) {
9223 
9224   // Look for multiply add opportunities.
9225   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9226   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9227   // a glue link from the first add to the second add.
9228   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9229   // a S/UMLAL instruction.
9230   //                  UMUL_LOHI
9231   //                 / :lo    \ :hi
9232   //                /          \          [no multiline comment]
9233   //    loAdd ->  ADDE         |
9234   //                 \ :glue  /
9235   //                  \      /
9236   //                    ADDC   <- hiAdd
9237   //
9238   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
9239   SDValue AddcOp0 = AddcNode->getOperand(0);
9240   SDValue AddcOp1 = AddcNode->getOperand(1);
9241 
9242   // Check if the two operands are from the same mul_lohi node.
9243   if (AddcOp0.getNode() == AddcOp1.getNode())
9244     return SDValue();
9245 
9246   assert(AddcNode->getNumValues() == 2 &&
9247          AddcNode->getValueType(0) == MVT::i32 &&
9248          "Expect ADDC with two result values. First: i32");
9249 
9250   // Check that we have a glued ADDC node.
9251   if (AddcNode->getValueType(1) != MVT::Glue)
9252     return SDValue();
9253 
9254   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
9255   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
9256       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
9257       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
9258       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
9259     return SDValue();
9260 
9261   // Look for the glued ADDE.
9262   SDNode* AddeNode = AddcNode->getGluedUser();
9263   if (!AddeNode)
9264     return SDValue();
9265 
9266   // Make sure it is really an ADDE.
9267   if (AddeNode->getOpcode() != ISD::ADDE)
9268     return SDValue();
9269 
9270   assert(AddeNode->getNumOperands() == 3 &&
9271          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
9272          "ADDE node has the wrong inputs");
9273 
9274   // Check for the triangle shape.
9275   SDValue AddeOp0 = AddeNode->getOperand(0);
9276   SDValue AddeOp1 = AddeNode->getOperand(1);
9277 
9278   // Make sure that the ADDE operands are not coming from the same node.
9279   if (AddeOp0.getNode() == AddeOp1.getNode())
9280     return SDValue();
9281 
9282   // Find the MUL_LOHI node walking up ADDE's operands.
9283   bool IsLeftOperandMUL = false;
9284   SDValue MULOp = findMUL_LOHI(AddeOp0);
9285   if (MULOp == SDValue())
9286    MULOp = findMUL_LOHI(AddeOp1);
9287   else
9288     IsLeftOperandMUL = true;
9289   if (MULOp == SDValue())
9290     return SDValue();
9291 
9292   // Figure out the right opcode.
9293   unsigned Opc = MULOp->getOpcode();
9294   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9295 
9296   // Figure out the high and low input values to the MLAL node.
9297   SDValue* HiAdd = nullptr;
9298   SDValue* LoMul = nullptr;
9299   SDValue* LowAdd = nullptr;
9300 
9301   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
9302   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
9303     return SDValue();
9304 
9305   if (IsLeftOperandMUL)
9306     HiAdd = &AddeOp1;
9307   else
9308     HiAdd = &AddeOp0;
9309 
9310 
9311   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
9312   // whose low result is fed to the ADDC we are checking.
9313 
9314   if (AddcOp0 == MULOp.getValue(0)) {
9315     LoMul = &AddcOp0;
9316     LowAdd = &AddcOp1;
9317   }
9318   if (AddcOp1 == MULOp.getValue(0)) {
9319     LoMul = &AddcOp1;
9320     LowAdd = &AddcOp0;
9321   }
9322 
9323   if (!LoMul)
9324     return SDValue();
9325 
9326   // Create the merged node.
9327   SelectionDAG &DAG = DCI.DAG;
9328 
9329   // Build operand list.
9330   SmallVector<SDValue, 8> Ops;
9331   Ops.push_back(LoMul->getOperand(0));
9332   Ops.push_back(LoMul->getOperand(1));
9333   Ops.push_back(*LowAdd);
9334   Ops.push_back(*HiAdd);
9335 
9336   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
9337                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9338 
9339   // Replace the ADDs' nodes uses by the MLA node's values.
9340   SDValue HiMLALResult(MLALNode.getNode(), 1);
9341   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9342 
9343   SDValue LoMLALResult(MLALNode.getNode(), 0);
9344   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9345 
9346   // Return original node to notify the driver to stop replacing.
9347   SDValue resNode(AddcNode, 0);
9348   return resNode;
9349 }
9350 
9351 static SDValue AddCombineTo64bitUMAAL(SDNode *AddcNode,
9352                                       TargetLowering::DAGCombinerInfo &DCI,
9353                                       const ARMSubtarget *Subtarget) {
9354   // UMAAL is similar to UMLAL except that it adds two unsigned values.
9355   // While trying to combine for the other MLAL nodes, first search for the
9356   // chance to use UMAAL. Check if Addc uses another addc node which can first
9357   // be combined into a UMLAL. The other pattern is AddcNode being combined
9358   // into an UMLAL and then using another addc is handled in ISelDAGToDAG.
9359 
9360   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP() ||
9361       (Subtarget->isThumb() && !Subtarget->hasThumb2()))
9362     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
9363 
9364   SDNode *PrevAddc = nullptr;
9365   if (AddcNode->getOperand(0).getOpcode() == ISD::ADDC)
9366     PrevAddc = AddcNode->getOperand(0).getNode();
9367   else if (AddcNode->getOperand(1).getOpcode() == ISD::ADDC)
9368     PrevAddc = AddcNode->getOperand(1).getNode();
9369 
9370   // If there's no addc chains, just return a search for any MLAL.
9371   if (PrevAddc == nullptr)
9372     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
9373 
9374   // Try to convert the addc operand to an MLAL and if that fails try to
9375   // combine AddcNode.
9376   SDValue MLAL = AddCombineTo64bitMLAL(PrevAddc, DCI, Subtarget);
9377   if (MLAL != SDValue(PrevAddc, 0))
9378     return AddCombineTo64bitMLAL(AddcNode, DCI, Subtarget);
9379 
9380   // Find the converted UMAAL or quit if it doesn't exist.
9381   SDNode *UmlalNode = nullptr;
9382   SDValue AddHi;
9383   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
9384     UmlalNode = AddcNode->getOperand(0).getNode();
9385     AddHi = AddcNode->getOperand(1);
9386   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
9387     UmlalNode = AddcNode->getOperand(1).getNode();
9388     AddHi = AddcNode->getOperand(0);
9389   } else {
9390     return SDValue();
9391   }
9392 
9393   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
9394   // the ADDC as well as Zero.
9395   auto *Zero = dyn_cast<ConstantSDNode>(UmlalNode->getOperand(3));
9396 
9397   if (!Zero || Zero->getZExtValue() != 0)
9398     return SDValue();
9399 
9400   // Check that we have a glued ADDC node.
9401   if (AddcNode->getValueType(1) != MVT::Glue)
9402     return SDValue();
9403 
9404   // Look for the glued ADDE.
9405   SDNode* AddeNode = AddcNode->getGluedUser();
9406   if (!AddeNode)
9407     return SDValue();
9408 
9409   if ((AddeNode->getOperand(0).getNode() == Zero &&
9410        AddeNode->getOperand(1).getNode() == UmlalNode) ||
9411       (AddeNode->getOperand(0).getNode() == UmlalNode &&
9412        AddeNode->getOperand(1).getNode() == Zero)) {
9413 
9414     SelectionDAG &DAG = DCI.DAG;
9415     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9416                       UmlalNode->getOperand(2), AddHi };
9417     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9418                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9419 
9420     // Replace the ADDs' nodes uses by the UMAAL node's values.
9421     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9422     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9423 
9424     // Return original node to notify the driver to stop replacing.
9425     return SDValue(AddcNode, 0);
9426   }
9427   return SDValue();
9428 }
9429 
9430 /// PerformADDCCombine - Target-specific dag combine transform from
9431 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL or
9432 /// ISD::ADDC, ISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
9433 static SDValue PerformADDCCombine(SDNode *N,
9434                                  TargetLowering::DAGCombinerInfo &DCI,
9435                                  const ARMSubtarget *Subtarget) {
9436 
9437   if (Subtarget->isThumb1Only()) return SDValue();
9438 
9439   // Only perform the checks after legalize when the pattern is available.
9440   if (DCI.isBeforeLegalize()) return SDValue();
9441 
9442   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
9443 }
9444 
9445 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
9446 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
9447 /// called with the default operands, and if that fails, with commuted
9448 /// operands.
9449 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
9450                                           TargetLowering::DAGCombinerInfo &DCI,
9451                                           const ARMSubtarget *Subtarget){
9452 
9453   // Attempt to create vpaddl for this add.
9454   if (SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget))
9455     return Result;
9456 
9457   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9458   if (N0.getNode()->hasOneUse())
9459     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
9460       return Result;
9461   return SDValue();
9462 }
9463 
9464 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
9465 ///
9466 static SDValue PerformADDCombine(SDNode *N,
9467                                  TargetLowering::DAGCombinerInfo &DCI,
9468                                  const ARMSubtarget *Subtarget) {
9469   SDValue N0 = N->getOperand(0);
9470   SDValue N1 = N->getOperand(1);
9471 
9472   // First try with the default operand order.
9473   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
9474     return Result;
9475 
9476   // If that didn't work, try again with the operands commuted.
9477   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
9478 }
9479 
9480 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
9481 ///
9482 static SDValue PerformSUBCombine(SDNode *N,
9483                                  TargetLowering::DAGCombinerInfo &DCI) {
9484   SDValue N0 = N->getOperand(0);
9485   SDValue N1 = N->getOperand(1);
9486 
9487   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
9488   if (N1.getNode()->hasOneUse())
9489     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
9490       return Result;
9491 
9492   return SDValue();
9493 }
9494 
9495 /// PerformVMULCombine
9496 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
9497 /// special multiplier accumulator forwarding.
9498 ///   vmul d3, d0, d2
9499 ///   vmla d3, d1, d2
9500 /// is faster than
9501 ///   vadd d3, d0, d1
9502 ///   vmul d3, d3, d2
9503 //  However, for (A + B) * (A + B),
9504 //    vadd d2, d0, d1
9505 //    vmul d3, d0, d2
9506 //    vmla d3, d1, d2
9507 //  is slower than
9508 //    vadd d2, d0, d1
9509 //    vmul d3, d2, d2
9510 static SDValue PerformVMULCombine(SDNode *N,
9511                                   TargetLowering::DAGCombinerInfo &DCI,
9512                                   const ARMSubtarget *Subtarget) {
9513   if (!Subtarget->hasVMLxForwarding())
9514     return SDValue();
9515 
9516   SelectionDAG &DAG = DCI.DAG;
9517   SDValue N0 = N->getOperand(0);
9518   SDValue N1 = N->getOperand(1);
9519   unsigned Opcode = N0.getOpcode();
9520   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9521       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
9522     Opcode = N1.getOpcode();
9523     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9524         Opcode != ISD::FADD && Opcode != ISD::FSUB)
9525       return SDValue();
9526     std::swap(N0, N1);
9527   }
9528 
9529   if (N0 == N1)
9530     return SDValue();
9531 
9532   EVT VT = N->getValueType(0);
9533   SDLoc DL(N);
9534   SDValue N00 = N0->getOperand(0);
9535   SDValue N01 = N0->getOperand(1);
9536   return DAG.getNode(Opcode, DL, VT,
9537                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
9538                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
9539 }
9540 
9541 static SDValue PerformMULCombine(SDNode *N,
9542                                  TargetLowering::DAGCombinerInfo &DCI,
9543                                  const ARMSubtarget *Subtarget) {
9544   SelectionDAG &DAG = DCI.DAG;
9545 
9546   if (Subtarget->isThumb1Only())
9547     return SDValue();
9548 
9549   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9550     return SDValue();
9551 
9552   EVT VT = N->getValueType(0);
9553   if (VT.is64BitVector() || VT.is128BitVector())
9554     return PerformVMULCombine(N, DCI, Subtarget);
9555   if (VT != MVT::i32)
9556     return SDValue();
9557 
9558   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9559   if (!C)
9560     return SDValue();
9561 
9562   int64_t MulAmt = C->getSExtValue();
9563   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
9564 
9565   ShiftAmt = ShiftAmt & (32 - 1);
9566   SDValue V = N->getOperand(0);
9567   SDLoc DL(N);
9568 
9569   SDValue Res;
9570   MulAmt >>= ShiftAmt;
9571 
9572   if (MulAmt >= 0) {
9573     if (isPowerOf2_32(MulAmt - 1)) {
9574       // (mul x, 2^N + 1) => (add (shl x, N), x)
9575       Res = DAG.getNode(ISD::ADD, DL, VT,
9576                         V,
9577                         DAG.getNode(ISD::SHL, DL, VT,
9578                                     V,
9579                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
9580                                                     MVT::i32)));
9581     } else if (isPowerOf2_32(MulAmt + 1)) {
9582       // (mul x, 2^N - 1) => (sub (shl x, N), x)
9583       Res = DAG.getNode(ISD::SUB, DL, VT,
9584                         DAG.getNode(ISD::SHL, DL, VT,
9585                                     V,
9586                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
9587                                                     MVT::i32)),
9588                         V);
9589     } else
9590       return SDValue();
9591   } else {
9592     uint64_t MulAmtAbs = -MulAmt;
9593     if (isPowerOf2_32(MulAmtAbs + 1)) {
9594       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9595       Res = DAG.getNode(ISD::SUB, DL, VT,
9596                         V,
9597                         DAG.getNode(ISD::SHL, DL, VT,
9598                                     V,
9599                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
9600                                                     MVT::i32)));
9601     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
9602       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9603       Res = DAG.getNode(ISD::ADD, DL, VT,
9604                         V,
9605                         DAG.getNode(ISD::SHL, DL, VT,
9606                                     V,
9607                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
9608                                                     MVT::i32)));
9609       Res = DAG.getNode(ISD::SUB, DL, VT,
9610                         DAG.getConstant(0, DL, MVT::i32), Res);
9611 
9612     } else
9613       return SDValue();
9614   }
9615 
9616   if (ShiftAmt != 0)
9617     Res = DAG.getNode(ISD::SHL, DL, VT,
9618                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
9619 
9620   // Do not add new nodes to DAG combiner worklist.
9621   DCI.CombineTo(N, Res, false);
9622   return SDValue();
9623 }
9624 
9625 static SDValue PerformANDCombine(SDNode *N,
9626                                  TargetLowering::DAGCombinerInfo &DCI,
9627                                  const ARMSubtarget *Subtarget) {
9628 
9629   // Attempt to use immediate-form VBIC
9630   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9631   SDLoc dl(N);
9632   EVT VT = N->getValueType(0);
9633   SelectionDAG &DAG = DCI.DAG;
9634 
9635   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9636     return SDValue();
9637 
9638   APInt SplatBits, SplatUndef;
9639   unsigned SplatBitSize;
9640   bool HasAnyUndefs;
9641   if (BVN &&
9642       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9643     if (SplatBitSize <= 64) {
9644       EVT VbicVT;
9645       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
9646                                       SplatUndef.getZExtValue(), SplatBitSize,
9647                                       DAG, dl, VbicVT, VT.is128BitVector(),
9648                                       OtherModImm);
9649       if (Val.getNode()) {
9650         SDValue Input =
9651           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
9652         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
9653         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
9654       }
9655     }
9656   }
9657 
9658   if (!Subtarget->isThumb1Only()) {
9659     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
9660     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
9661       return Result;
9662   }
9663 
9664   return SDValue();
9665 }
9666 
9667 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
9668 static SDValue PerformORCombine(SDNode *N,
9669                                 TargetLowering::DAGCombinerInfo &DCI,
9670                                 const ARMSubtarget *Subtarget) {
9671   // Attempt to use immediate-form VORR
9672   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
9673   SDLoc dl(N);
9674   EVT VT = N->getValueType(0);
9675   SelectionDAG &DAG = DCI.DAG;
9676 
9677   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9678     return SDValue();
9679 
9680   APInt SplatBits, SplatUndef;
9681   unsigned SplatBitSize;
9682   bool HasAnyUndefs;
9683   if (BVN && Subtarget->hasNEON() &&
9684       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
9685     if (SplatBitSize <= 64) {
9686       EVT VorrVT;
9687       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
9688                                       SplatUndef.getZExtValue(), SplatBitSize,
9689                                       DAG, dl, VorrVT, VT.is128BitVector(),
9690                                       OtherModImm);
9691       if (Val.getNode()) {
9692         SDValue Input =
9693           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
9694         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
9695         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
9696       }
9697     }
9698   }
9699 
9700   if (!Subtarget->isThumb1Only()) {
9701     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
9702     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9703       return Result;
9704   }
9705 
9706   // The code below optimizes (or (and X, Y), Z).
9707   // The AND operand needs to have a single user to make these optimizations
9708   // profitable.
9709   SDValue N0 = N->getOperand(0);
9710   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
9711     return SDValue();
9712   SDValue N1 = N->getOperand(1);
9713 
9714   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
9715   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
9716       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
9717     APInt SplatUndef;
9718     unsigned SplatBitSize;
9719     bool HasAnyUndefs;
9720 
9721     APInt SplatBits0, SplatBits1;
9722     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
9723     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
9724     // Ensure that the second operand of both ands are constants
9725     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
9726                                       HasAnyUndefs) && !HasAnyUndefs) {
9727         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
9728                                           HasAnyUndefs) && !HasAnyUndefs) {
9729             // Ensure that the bit width of the constants are the same and that
9730             // the splat arguments are logical inverses as per the pattern we
9731             // are trying to simplify.
9732             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
9733                 SplatBits0 == ~SplatBits1) {
9734                 // Canonicalize the vector type to make instruction selection
9735                 // simpler.
9736                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
9737                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
9738                                              N0->getOperand(1),
9739                                              N0->getOperand(0),
9740                                              N1->getOperand(0));
9741                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
9742             }
9743         }
9744     }
9745   }
9746 
9747   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
9748   // reasonable.
9749 
9750   // BFI is only available on V6T2+
9751   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
9752     return SDValue();
9753 
9754   SDLoc DL(N);
9755   // 1) or (and A, mask), val => ARMbfi A, val, mask
9756   //      iff (val & mask) == val
9757   //
9758   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9759   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
9760   //          && mask == ~mask2
9761   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
9762   //          && ~mask == mask2
9763   //  (i.e., copy a bitfield value into another bitfield of the same width)
9764 
9765   if (VT != MVT::i32)
9766     return SDValue();
9767 
9768   SDValue N00 = N0.getOperand(0);
9769 
9770   // The value and the mask need to be constants so we can verify this is
9771   // actually a bitfield set. If the mask is 0xffff, we can do better
9772   // via a movt instruction, so don't use BFI in that case.
9773   SDValue MaskOp = N0.getOperand(1);
9774   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
9775   if (!MaskC)
9776     return SDValue();
9777   unsigned Mask = MaskC->getZExtValue();
9778   if (Mask == 0xffff)
9779     return SDValue();
9780   SDValue Res;
9781   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
9782   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9783   if (N1C) {
9784     unsigned Val = N1C->getZExtValue();
9785     if ((Val & ~Mask) != Val)
9786       return SDValue();
9787 
9788     if (ARM::isBitFieldInvertedMask(Mask)) {
9789       Val >>= countTrailingZeros(~Mask);
9790 
9791       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
9792                         DAG.getConstant(Val, DL, MVT::i32),
9793                         DAG.getConstant(Mask, DL, MVT::i32));
9794 
9795       // Do not add new nodes to DAG combiner worklist.
9796       DCI.CombineTo(N, Res, false);
9797       return SDValue();
9798     }
9799   } else if (N1.getOpcode() == ISD::AND) {
9800     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
9801     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9802     if (!N11C)
9803       return SDValue();
9804     unsigned Mask2 = N11C->getZExtValue();
9805 
9806     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
9807     // as is to match.
9808     if (ARM::isBitFieldInvertedMask(Mask) &&
9809         (Mask == ~Mask2)) {
9810       // The pack halfword instruction works better for masks that fit it,
9811       // so use that when it's available.
9812       if (Subtarget->hasT2ExtractPack() &&
9813           (Mask == 0xffff || Mask == 0xffff0000))
9814         return SDValue();
9815       // 2a
9816       unsigned amt = countTrailingZeros(Mask2);
9817       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
9818                         DAG.getConstant(amt, DL, MVT::i32));
9819       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
9820                         DAG.getConstant(Mask, DL, MVT::i32));
9821       // Do not add new nodes to DAG combiner worklist.
9822       DCI.CombineTo(N, Res, false);
9823       return SDValue();
9824     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
9825                (~Mask == Mask2)) {
9826       // The pack halfword instruction works better for masks that fit it,
9827       // so use that when it's available.
9828       if (Subtarget->hasT2ExtractPack() &&
9829           (Mask2 == 0xffff || Mask2 == 0xffff0000))
9830         return SDValue();
9831       // 2b
9832       unsigned lsb = countTrailingZeros(Mask);
9833       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
9834                         DAG.getConstant(lsb, DL, MVT::i32));
9835       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
9836                         DAG.getConstant(Mask2, DL, MVT::i32));
9837       // Do not add new nodes to DAG combiner worklist.
9838       DCI.CombineTo(N, Res, false);
9839       return SDValue();
9840     }
9841   }
9842 
9843   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
9844       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
9845       ARM::isBitFieldInvertedMask(~Mask)) {
9846     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
9847     // where lsb(mask) == #shamt and masked bits of B are known zero.
9848     SDValue ShAmt = N00.getOperand(1);
9849     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
9850     unsigned LSB = countTrailingZeros(Mask);
9851     if (ShAmtC != LSB)
9852       return SDValue();
9853 
9854     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
9855                       DAG.getConstant(~Mask, DL, MVT::i32));
9856 
9857     // Do not add new nodes to DAG combiner worklist.
9858     DCI.CombineTo(N, Res, false);
9859   }
9860 
9861   return SDValue();
9862 }
9863 
9864 static SDValue PerformXORCombine(SDNode *N,
9865                                  TargetLowering::DAGCombinerInfo &DCI,
9866                                  const ARMSubtarget *Subtarget) {
9867   EVT VT = N->getValueType(0);
9868   SelectionDAG &DAG = DCI.DAG;
9869 
9870   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
9871     return SDValue();
9872 
9873   if (!Subtarget->isThumb1Only()) {
9874     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
9875     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
9876       return Result;
9877   }
9878 
9879   return SDValue();
9880 }
9881 
9882 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
9883 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
9884 // their position in "to" (Rd).
9885 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
9886   assert(N->getOpcode() == ARMISD::BFI);
9887 
9888   SDValue From = N->getOperand(1);
9889   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
9890   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
9891 
9892   // If the Base came from a SHR #C, we can deduce that it is really testing bit
9893   // #C in the base of the SHR.
9894   if (From->getOpcode() == ISD::SRL &&
9895       isa<ConstantSDNode>(From->getOperand(1))) {
9896     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
9897     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
9898     FromMask <<= Shift.getLimitedValue(31);
9899     From = From->getOperand(0);
9900   }
9901 
9902   return From;
9903 }
9904 
9905 // If A and B contain one contiguous set of bits, does A | B == A . B?
9906 //
9907 // Neither A nor B must be zero.
9908 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
9909   unsigned LastActiveBitInA =  A.countTrailingZeros();
9910   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
9911   return LastActiveBitInA - 1 == FirstActiveBitInB;
9912 }
9913 
9914 static SDValue FindBFIToCombineWith(SDNode *N) {
9915   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
9916   // if one exists.
9917   APInt ToMask, FromMask;
9918   SDValue From = ParseBFI(N, ToMask, FromMask);
9919   SDValue To = N->getOperand(0);
9920 
9921   // Now check for a compatible BFI to merge with. We can pass through BFIs that
9922   // aren't compatible, but not if they set the same bit in their destination as
9923   // we do (or that of any BFI we're going to combine with).
9924   SDValue V = To;
9925   APInt CombinedToMask = ToMask;
9926   while (V.getOpcode() == ARMISD::BFI) {
9927     APInt NewToMask, NewFromMask;
9928     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
9929     if (NewFrom != From) {
9930       // This BFI has a different base. Keep going.
9931       CombinedToMask |= NewToMask;
9932       V = V.getOperand(0);
9933       continue;
9934     }
9935 
9936     // Do the written bits conflict with any we've seen so far?
9937     if ((NewToMask & CombinedToMask).getBoolValue())
9938       // Conflicting bits - bail out because going further is unsafe.
9939       return SDValue();
9940 
9941     // Are the new bits contiguous when combined with the old bits?
9942     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
9943         BitsProperlyConcatenate(FromMask, NewFromMask))
9944       return V;
9945     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
9946         BitsProperlyConcatenate(NewFromMask, FromMask))
9947       return V;
9948 
9949     // We've seen a write to some bits, so track it.
9950     CombinedToMask |= NewToMask;
9951     // Keep going...
9952     V = V.getOperand(0);
9953   }
9954 
9955   return SDValue();
9956 }
9957 
9958 static SDValue PerformBFICombine(SDNode *N,
9959                                  TargetLowering::DAGCombinerInfo &DCI) {
9960   SDValue N1 = N->getOperand(1);
9961   if (N1.getOpcode() == ISD::AND) {
9962     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
9963     // the bits being cleared by the AND are not demanded by the BFI.
9964     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
9965     if (!N11C)
9966       return SDValue();
9967     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9968     unsigned LSB = countTrailingZeros(~InvMask);
9969     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
9970     assert(Width <
9971                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
9972            "undefined behavior");
9973     unsigned Mask = (1u << Width) - 1;
9974     unsigned Mask2 = N11C->getZExtValue();
9975     if ((Mask & (~Mask2)) == 0)
9976       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
9977                              N->getOperand(0), N1.getOperand(0),
9978                              N->getOperand(2));
9979   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
9980     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
9981     // Keep track of any consecutive bits set that all come from the same base
9982     // value. We can combine these together into a single BFI.
9983     SDValue CombineBFI = FindBFIToCombineWith(N);
9984     if (CombineBFI == SDValue())
9985       return SDValue();
9986 
9987     // We've found a BFI.
9988     APInt ToMask1, FromMask1;
9989     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
9990 
9991     APInt ToMask2, FromMask2;
9992     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
9993     assert(From1 == From2);
9994     (void)From2;
9995 
9996     // First, unlink CombineBFI.
9997     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
9998     // Then create a new BFI, combining the two together.
9999     APInt NewFromMask = FromMask1 | FromMask2;
10000     APInt NewToMask = ToMask1 | ToMask2;
10001 
10002     EVT VT = N->getValueType(0);
10003     SDLoc dl(N);
10004 
10005     if (NewFromMask[0] == 0)
10006       From1 = DCI.DAG.getNode(
10007         ISD::SRL, dl, VT, From1,
10008         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10009     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10010                            DCI.DAG.getConstant(~NewToMask, dl, VT));
10011   }
10012   return SDValue();
10013 }
10014 
10015 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10016 /// ARMISD::VMOVRRD.
10017 static SDValue PerformVMOVRRDCombine(SDNode *N,
10018                                      TargetLowering::DAGCombinerInfo &DCI,
10019                                      const ARMSubtarget *Subtarget) {
10020   // vmovrrd(vmovdrr x, y) -> x,y
10021   SDValue InDouble = N->getOperand(0);
10022   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10023     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10024 
10025   // vmovrrd(load f64) -> (load i32), (load i32)
10026   SDNode *InNode = InDouble.getNode();
10027   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10028       InNode->getValueType(0) == MVT::f64 &&
10029       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10030       !cast<LoadSDNode>(InNode)->isVolatile()) {
10031     // TODO: Should this be done for non-FrameIndex operands?
10032     LoadSDNode *LD = cast<LoadSDNode>(InNode);
10033 
10034     SelectionDAG &DAG = DCI.DAG;
10035     SDLoc DL(LD);
10036     SDValue BasePtr = LD->getBasePtr();
10037     SDValue NewLD1 =
10038         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10039                     LD->getAlignment(), LD->getMemOperand()->getFlags());
10040 
10041     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10042                                     DAG.getConstant(4, DL, MVT::i32));
10043     SDValue NewLD2 = DAG.getLoad(
10044         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10045         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10046 
10047     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10048     if (DCI.DAG.getDataLayout().isBigEndian())
10049       std::swap (NewLD1, NewLD2);
10050     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10051     return Result;
10052   }
10053 
10054   return SDValue();
10055 }
10056 
10057 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10058 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
10059 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10060   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10061   SDValue Op0 = N->getOperand(0);
10062   SDValue Op1 = N->getOperand(1);
10063   if (Op0.getOpcode() == ISD::BITCAST)
10064     Op0 = Op0.getOperand(0);
10065   if (Op1.getOpcode() == ISD::BITCAST)
10066     Op1 = Op1.getOperand(0);
10067   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
10068       Op0.getNode() == Op1.getNode() &&
10069       Op0.getResNo() == 0 && Op1.getResNo() == 1)
10070     return DAG.getNode(ISD::BITCAST, SDLoc(N),
10071                        N->getValueType(0), Op0.getOperand(0));
10072   return SDValue();
10073 }
10074 
10075 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
10076 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
10077 /// i64 vector to have f64 elements, since the value can then be loaded
10078 /// directly into a VFP register.
10079 static bool hasNormalLoadOperand(SDNode *N) {
10080   unsigned NumElts = N->getValueType(0).getVectorNumElements();
10081   for (unsigned i = 0; i < NumElts; ++i) {
10082     SDNode *Elt = N->getOperand(i).getNode();
10083     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
10084       return true;
10085   }
10086   return false;
10087 }
10088 
10089 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
10090 /// ISD::BUILD_VECTOR.
10091 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
10092                                           TargetLowering::DAGCombinerInfo &DCI,
10093                                           const ARMSubtarget *Subtarget) {
10094   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
10095   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
10096   // into a pair of GPRs, which is fine when the value is used as a scalar,
10097   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
10098   SelectionDAG &DAG = DCI.DAG;
10099   if (N->getNumOperands() == 2)
10100     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
10101       return RV;
10102 
10103   // Load i64 elements as f64 values so that type legalization does not split
10104   // them up into i32 values.
10105   EVT VT = N->getValueType(0);
10106   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
10107     return SDValue();
10108   SDLoc dl(N);
10109   SmallVector<SDValue, 8> Ops;
10110   unsigned NumElts = VT.getVectorNumElements();
10111   for (unsigned i = 0; i < NumElts; ++i) {
10112     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
10113     Ops.push_back(V);
10114     // Make the DAGCombiner fold the bitcast.
10115     DCI.AddToWorklist(V.getNode());
10116   }
10117   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
10118   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
10119   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10120 }
10121 
10122 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
10123 static SDValue
10124 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10125   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
10126   // At that time, we may have inserted bitcasts from integer to float.
10127   // If these bitcasts have survived DAGCombine, change the lowering of this
10128   // BUILD_VECTOR in something more vector friendly, i.e., that does not
10129   // force to use floating point types.
10130 
10131   // Make sure we can change the type of the vector.
10132   // This is possible iff:
10133   // 1. The vector is only used in a bitcast to a integer type. I.e.,
10134   //    1.1. Vector is used only once.
10135   //    1.2. Use is a bit convert to an integer type.
10136   // 2. The size of its operands are 32-bits (64-bits are not legal).
10137   EVT VT = N->getValueType(0);
10138   EVT EltVT = VT.getVectorElementType();
10139 
10140   // Check 1.1. and 2.
10141   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
10142     return SDValue();
10143 
10144   // By construction, the input type must be float.
10145   assert(EltVT == MVT::f32 && "Unexpected type!");
10146 
10147   // Check 1.2.
10148   SDNode *Use = *N->use_begin();
10149   if (Use->getOpcode() != ISD::BITCAST ||
10150       Use->getValueType(0).isFloatingPoint())
10151     return SDValue();
10152 
10153   // Check profitability.
10154   // Model is, if more than half of the relevant operands are bitcast from
10155   // i32, turn the build_vector into a sequence of insert_vector_elt.
10156   // Relevant operands are everything that is not statically
10157   // (i.e., at compile time) bitcasted.
10158   unsigned NumOfBitCastedElts = 0;
10159   unsigned NumElts = VT.getVectorNumElements();
10160   unsigned NumOfRelevantElts = NumElts;
10161   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
10162     SDValue Elt = N->getOperand(Idx);
10163     if (Elt->getOpcode() == ISD::BITCAST) {
10164       // Assume only bit cast to i32 will go away.
10165       if (Elt->getOperand(0).getValueType() == MVT::i32)
10166         ++NumOfBitCastedElts;
10167     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
10168       // Constants are statically casted, thus do not count them as
10169       // relevant operands.
10170       --NumOfRelevantElts;
10171   }
10172 
10173   // Check if more than half of the elements require a non-free bitcast.
10174   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
10175     return SDValue();
10176 
10177   SelectionDAG &DAG = DCI.DAG;
10178   // Create the new vector type.
10179   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
10180   // Check if the type is legal.
10181   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10182   if (!TLI.isTypeLegal(VecVT))
10183     return SDValue();
10184 
10185   // Combine:
10186   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
10187   // => BITCAST INSERT_VECTOR_ELT
10188   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
10189   //                      (BITCAST EN), N.
10190   SDValue Vec = DAG.getUNDEF(VecVT);
10191   SDLoc dl(N);
10192   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
10193     SDValue V = N->getOperand(Idx);
10194     if (V.isUndef())
10195       continue;
10196     if (V.getOpcode() == ISD::BITCAST &&
10197         V->getOperand(0).getValueType() == MVT::i32)
10198       // Fold obvious case.
10199       V = V.getOperand(0);
10200     else {
10201       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
10202       // Make the DAGCombiner fold the bitcasts.
10203       DCI.AddToWorklist(V.getNode());
10204     }
10205     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
10206     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
10207   }
10208   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
10209   // Make the DAGCombiner fold the bitcasts.
10210   DCI.AddToWorklist(Vec.getNode());
10211   return Vec;
10212 }
10213 
10214 /// PerformInsertEltCombine - Target-specific dag combine xforms for
10215 /// ISD::INSERT_VECTOR_ELT.
10216 static SDValue PerformInsertEltCombine(SDNode *N,
10217                                        TargetLowering::DAGCombinerInfo &DCI) {
10218   // Bitcast an i64 load inserted into a vector to f64.
10219   // Otherwise, the i64 value will be legalized to a pair of i32 values.
10220   EVT VT = N->getValueType(0);
10221   SDNode *Elt = N->getOperand(1).getNode();
10222   if (VT.getVectorElementType() != MVT::i64 ||
10223       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
10224     return SDValue();
10225 
10226   SelectionDAG &DAG = DCI.DAG;
10227   SDLoc dl(N);
10228   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10229                                  VT.getVectorNumElements());
10230   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
10231   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
10232   // Make the DAGCombiner fold the bitcasts.
10233   DCI.AddToWorklist(Vec.getNode());
10234   DCI.AddToWorklist(V.getNode());
10235   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
10236                                Vec, V, N->getOperand(2));
10237   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
10238 }
10239 
10240 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
10241 /// ISD::VECTOR_SHUFFLE.
10242 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
10243   // The LLVM shufflevector instruction does not require the shuffle mask
10244   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
10245   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
10246   // operands do not match the mask length, they are extended by concatenating
10247   // them with undef vectors.  That is probably the right thing for other
10248   // targets, but for NEON it is better to concatenate two double-register
10249   // size vector operands into a single quad-register size vector.  Do that
10250   // transformation here:
10251   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
10252   //   shuffle(concat(v1, v2), undef)
10253   SDValue Op0 = N->getOperand(0);
10254   SDValue Op1 = N->getOperand(1);
10255   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
10256       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
10257       Op0.getNumOperands() != 2 ||
10258       Op1.getNumOperands() != 2)
10259     return SDValue();
10260   SDValue Concat0Op1 = Op0.getOperand(1);
10261   SDValue Concat1Op1 = Op1.getOperand(1);
10262   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
10263     return SDValue();
10264   // Skip the transformation if any of the types are illegal.
10265   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10266   EVT VT = N->getValueType(0);
10267   if (!TLI.isTypeLegal(VT) ||
10268       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
10269       !TLI.isTypeLegal(Concat1Op1.getValueType()))
10270     return SDValue();
10271 
10272   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10273                                   Op0.getOperand(0), Op1.getOperand(0));
10274   // Translate the shuffle mask.
10275   SmallVector<int, 16> NewMask;
10276   unsigned NumElts = VT.getVectorNumElements();
10277   unsigned HalfElts = NumElts/2;
10278   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10279   for (unsigned n = 0; n < NumElts; ++n) {
10280     int MaskElt = SVN->getMaskElt(n);
10281     int NewElt = -1;
10282     if (MaskElt < (int)HalfElts)
10283       NewElt = MaskElt;
10284     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
10285       NewElt = HalfElts + MaskElt - NumElts;
10286     NewMask.push_back(NewElt);
10287   }
10288   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
10289                               DAG.getUNDEF(VT), NewMask);
10290 }
10291 
10292 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
10293 /// NEON load/store intrinsics, and generic vector load/stores, to merge
10294 /// base address updates.
10295 /// For generic load/stores, the memory type is assumed to be a vector.
10296 /// The caller is assumed to have checked legality.
10297 static SDValue CombineBaseUpdate(SDNode *N,
10298                                  TargetLowering::DAGCombinerInfo &DCI) {
10299   SelectionDAG &DAG = DCI.DAG;
10300   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
10301                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
10302   const bool isStore = N->getOpcode() == ISD::STORE;
10303   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
10304   SDValue Addr = N->getOperand(AddrOpIdx);
10305   MemSDNode *MemN = cast<MemSDNode>(N);
10306   SDLoc dl(N);
10307 
10308   // Search for a use of the address operand that is an increment.
10309   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10310          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10311     SDNode *User = *UI;
10312     if (User->getOpcode() != ISD::ADD ||
10313         UI.getUse().getResNo() != Addr.getResNo())
10314       continue;
10315 
10316     // Check that the add is independent of the load/store.  Otherwise, folding
10317     // it would create a cycle.
10318     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
10319       continue;
10320 
10321     // Find the new opcode for the updating load/store.
10322     bool isLoadOp = true;
10323     bool isLaneOp = false;
10324     unsigned NewOpc = 0;
10325     unsigned NumVecs = 0;
10326     if (isIntrinsic) {
10327       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10328       switch (IntNo) {
10329       default: llvm_unreachable("unexpected intrinsic for Neon base update");
10330       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
10331         NumVecs = 1; break;
10332       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
10333         NumVecs = 2; break;
10334       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
10335         NumVecs = 3; break;
10336       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
10337         NumVecs = 4; break;
10338       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
10339         NumVecs = 2; isLaneOp = true; break;
10340       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
10341         NumVecs = 3; isLaneOp = true; break;
10342       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
10343         NumVecs = 4; isLaneOp = true; break;
10344       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
10345         NumVecs = 1; isLoadOp = false; break;
10346       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
10347         NumVecs = 2; isLoadOp = false; break;
10348       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
10349         NumVecs = 3; isLoadOp = false; break;
10350       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
10351         NumVecs = 4; isLoadOp = false; break;
10352       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
10353         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
10354       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
10355         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
10356       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
10357         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
10358       }
10359     } else {
10360       isLaneOp = true;
10361       switch (N->getOpcode()) {
10362       default: llvm_unreachable("unexpected opcode for Neon base update");
10363       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
10364       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
10365       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
10366       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
10367         NumVecs = 1; isLaneOp = false; break;
10368       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
10369         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
10370       }
10371     }
10372 
10373     // Find the size of memory referenced by the load/store.
10374     EVT VecTy;
10375     if (isLoadOp) {
10376       VecTy = N->getValueType(0);
10377     } else if (isIntrinsic) {
10378       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
10379     } else {
10380       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
10381       VecTy = N->getOperand(1).getValueType();
10382     }
10383 
10384     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10385     if (isLaneOp)
10386       NumBytes /= VecTy.getVectorNumElements();
10387 
10388     // If the increment is a constant, it must match the memory ref size.
10389     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10390     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10391       uint64_t IncVal = CInc->getZExtValue();
10392       if (IncVal != NumBytes)
10393         continue;
10394     } else if (NumBytes >= 3 * 16) {
10395       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
10396       // separate instructions that make it harder to use a non-constant update.
10397       continue;
10398     }
10399 
10400     // OK, we found an ADD we can fold into the base update.
10401     // Now, create a _UPD node, taking care of not breaking alignment.
10402 
10403     EVT AlignedVecTy = VecTy;
10404     unsigned Alignment = MemN->getAlignment();
10405 
10406     // If this is a less-than-standard-aligned load/store, change the type to
10407     // match the standard alignment.
10408     // The alignment is overlooked when selecting _UPD variants; and it's
10409     // easier to introduce bitcasts here than fix that.
10410     // There are 3 ways to get to this base-update combine:
10411     // - intrinsics: they are assumed to be properly aligned (to the standard
10412     //   alignment of the memory type), so we don't need to do anything.
10413     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
10414     //   intrinsics, so, likewise, there's nothing to do.
10415     // - generic load/store instructions: the alignment is specified as an
10416     //   explicit operand, rather than implicitly as the standard alignment
10417     //   of the memory type (like the intrisics).  We need to change the
10418     //   memory type to match the explicit alignment.  That way, we don't
10419     //   generate non-standard-aligned ARMISD::VLDx nodes.
10420     if (isa<LSBaseSDNode>(N)) {
10421       if (Alignment == 0)
10422         Alignment = 1;
10423       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
10424         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
10425         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
10426         assert(!isLaneOp && "Unexpected generic load/store lane.");
10427         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
10428         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
10429       }
10430       // Don't set an explicit alignment on regular load/stores that we want
10431       // to transform to VLD/VST 1_UPD nodes.
10432       // This matches the behavior of regular load/stores, which only get an
10433       // explicit alignment if the MMO alignment is larger than the standard
10434       // alignment of the memory type.
10435       // Intrinsics, however, always get an explicit alignment, set to the
10436       // alignment of the MMO.
10437       Alignment = 1;
10438     }
10439 
10440     // Create the new updating load/store node.
10441     // First, create an SDVTList for the new updating node's results.
10442     EVT Tys[6];
10443     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
10444     unsigned n;
10445     for (n = 0; n < NumResultVecs; ++n)
10446       Tys[n] = AlignedVecTy;
10447     Tys[n++] = MVT::i32;
10448     Tys[n] = MVT::Other;
10449     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
10450 
10451     // Then, gather the new node's operands.
10452     SmallVector<SDValue, 8> Ops;
10453     Ops.push_back(N->getOperand(0)); // incoming chain
10454     Ops.push_back(N->getOperand(AddrOpIdx));
10455     Ops.push_back(Inc);
10456 
10457     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
10458       // Try to match the intrinsic's signature
10459       Ops.push_back(StN->getValue());
10460     } else {
10461       // Loads (and of course intrinsics) match the intrinsics' signature,
10462       // so just add all but the alignment operand.
10463       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
10464         Ops.push_back(N->getOperand(i));
10465     }
10466 
10467     // For all node types, the alignment operand is always the last one.
10468     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
10469 
10470     // If this is a non-standard-aligned STORE, the penultimate operand is the
10471     // stored value.  Bitcast it to the aligned type.
10472     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
10473       SDValue &StVal = Ops[Ops.size()-2];
10474       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
10475     }
10476 
10477     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
10478                                            Ops, AlignedVecTy,
10479                                            MemN->getMemOperand());
10480 
10481     // Update the uses.
10482     SmallVector<SDValue, 5> NewResults;
10483     for (unsigned i = 0; i < NumResultVecs; ++i)
10484       NewResults.push_back(SDValue(UpdN.getNode(), i));
10485 
10486     // If this is an non-standard-aligned LOAD, the first result is the loaded
10487     // value.  Bitcast it to the expected result type.
10488     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
10489       SDValue &LdVal = NewResults[0];
10490       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
10491     }
10492 
10493     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
10494     DCI.CombineTo(N, NewResults);
10495     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10496 
10497     break;
10498   }
10499   return SDValue();
10500 }
10501 
10502 static SDValue PerformVLDCombine(SDNode *N,
10503                                  TargetLowering::DAGCombinerInfo &DCI) {
10504   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10505     return SDValue();
10506 
10507   return CombineBaseUpdate(N, DCI);
10508 }
10509 
10510 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
10511 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
10512 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
10513 /// return true.
10514 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10515   SelectionDAG &DAG = DCI.DAG;
10516   EVT VT = N->getValueType(0);
10517   // vldN-dup instructions only support 64-bit vectors for N > 1.
10518   if (!VT.is64BitVector())
10519     return false;
10520 
10521   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
10522   SDNode *VLD = N->getOperand(0).getNode();
10523   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
10524     return false;
10525   unsigned NumVecs = 0;
10526   unsigned NewOpc = 0;
10527   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
10528   if (IntNo == Intrinsic::arm_neon_vld2lane) {
10529     NumVecs = 2;
10530     NewOpc = ARMISD::VLD2DUP;
10531   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
10532     NumVecs = 3;
10533     NewOpc = ARMISD::VLD3DUP;
10534   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
10535     NumVecs = 4;
10536     NewOpc = ARMISD::VLD4DUP;
10537   } else {
10538     return false;
10539   }
10540 
10541   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
10542   // numbers match the load.
10543   unsigned VLDLaneNo =
10544     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
10545   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10546        UI != UE; ++UI) {
10547     // Ignore uses of the chain result.
10548     if (UI.getUse().getResNo() == NumVecs)
10549       continue;
10550     SDNode *User = *UI;
10551     if (User->getOpcode() != ARMISD::VDUPLANE ||
10552         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
10553       return false;
10554   }
10555 
10556   // Create the vldN-dup node.
10557   EVT Tys[5];
10558   unsigned n;
10559   for (n = 0; n < NumVecs; ++n)
10560     Tys[n] = VT;
10561   Tys[n] = MVT::Other;
10562   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
10563   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
10564   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
10565   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
10566                                            Ops, VLDMemInt->getMemoryVT(),
10567                                            VLDMemInt->getMemOperand());
10568 
10569   // Update the uses.
10570   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
10571        UI != UE; ++UI) {
10572     unsigned ResNo = UI.getUse().getResNo();
10573     // Ignore uses of the chain result.
10574     if (ResNo == NumVecs)
10575       continue;
10576     SDNode *User = *UI;
10577     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
10578   }
10579 
10580   // Now the vldN-lane intrinsic is dead except for its chain result.
10581   // Update uses of the chain.
10582   std::vector<SDValue> VLDDupResults;
10583   for (unsigned n = 0; n < NumVecs; ++n)
10584     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
10585   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
10586   DCI.CombineTo(VLD, VLDDupResults);
10587 
10588   return true;
10589 }
10590 
10591 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
10592 /// ARMISD::VDUPLANE.
10593 static SDValue PerformVDUPLANECombine(SDNode *N,
10594                                       TargetLowering::DAGCombinerInfo &DCI) {
10595   SDValue Op = N->getOperand(0);
10596 
10597   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
10598   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
10599   if (CombineVLDDUP(N, DCI))
10600     return SDValue(N, 0);
10601 
10602   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
10603   // redundant.  Ignore bit_converts for now; element sizes are checked below.
10604   while (Op.getOpcode() == ISD::BITCAST)
10605     Op = Op.getOperand(0);
10606   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
10607     return SDValue();
10608 
10609   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
10610   unsigned EltSize = Op.getScalarValueSizeInBits();
10611   // The canonical VMOV for a zero vector uses a 32-bit element size.
10612   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10613   unsigned EltBits;
10614   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
10615     EltSize = 8;
10616   EVT VT = N->getValueType(0);
10617   if (EltSize > VT.getScalarSizeInBits())
10618     return SDValue();
10619 
10620   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
10621 }
10622 
10623 static SDValue PerformLOADCombine(SDNode *N,
10624                                   TargetLowering::DAGCombinerInfo &DCI) {
10625   EVT VT = N->getValueType(0);
10626 
10627   // If this is a legal vector load, try to combine it into a VLD1_UPD.
10628   if (ISD::isNormalLoad(N) && VT.isVector() &&
10629       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10630     return CombineBaseUpdate(N, DCI);
10631 
10632   return SDValue();
10633 }
10634 
10635 /// PerformSTORECombine - Target-specific dag combine xforms for
10636 /// ISD::STORE.
10637 static SDValue PerformSTORECombine(SDNode *N,
10638                                    TargetLowering::DAGCombinerInfo &DCI) {
10639   StoreSDNode *St = cast<StoreSDNode>(N);
10640   if (St->isVolatile())
10641     return SDValue();
10642 
10643   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
10644   // pack all of the elements in one place.  Next, store to memory in fewer
10645   // chunks.
10646   SDValue StVal = St->getValue();
10647   EVT VT = StVal.getValueType();
10648   if (St->isTruncatingStore() && VT.isVector()) {
10649     SelectionDAG &DAG = DCI.DAG;
10650     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10651     EVT StVT = St->getMemoryVT();
10652     unsigned NumElems = VT.getVectorNumElements();
10653     assert(StVT != VT && "Cannot truncate to the same type");
10654     unsigned FromEltSz = VT.getScalarSizeInBits();
10655     unsigned ToEltSz = StVT.getScalarSizeInBits();
10656 
10657     // From, To sizes and ElemCount must be pow of two
10658     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
10659 
10660     // We are going to use the original vector elt for storing.
10661     // Accumulated smaller vector elements must be a multiple of the store size.
10662     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
10663 
10664     unsigned SizeRatio  = FromEltSz / ToEltSz;
10665     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
10666 
10667     // Create a type on which we perform the shuffle.
10668     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
10669                                      NumElems*SizeRatio);
10670     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
10671 
10672     SDLoc DL(St);
10673     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
10674     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
10675     for (unsigned i = 0; i < NumElems; ++i)
10676       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
10677                           ? (i + 1) * SizeRatio - 1
10678                           : i * SizeRatio;
10679 
10680     // Can't shuffle using an illegal type.
10681     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
10682 
10683     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
10684                                 DAG.getUNDEF(WideVec.getValueType()),
10685                                 ShuffleVec);
10686     // At this point all of the data is stored at the bottom of the
10687     // register. We now need to save it to mem.
10688 
10689     // Find the largest store unit
10690     MVT StoreType = MVT::i8;
10691     for (MVT Tp : MVT::integer_valuetypes()) {
10692       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
10693         StoreType = Tp;
10694     }
10695     // Didn't find a legal store type.
10696     if (!TLI.isTypeLegal(StoreType))
10697       return SDValue();
10698 
10699     // Bitcast the original vector into a vector of store-size units
10700     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
10701             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
10702     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
10703     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
10704     SmallVector<SDValue, 8> Chains;
10705     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
10706                                         TLI.getPointerTy(DAG.getDataLayout()));
10707     SDValue BasePtr = St->getBasePtr();
10708 
10709     // Perform one or more big stores into memory.
10710     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
10711     for (unsigned I = 0; I < E; I++) {
10712       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
10713                                    StoreType, ShuffWide,
10714                                    DAG.getIntPtrConstant(I, DL));
10715       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
10716                                 St->getPointerInfo(), St->getAlignment(),
10717                                 St->getMemOperand()->getFlags());
10718       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
10719                             Increment);
10720       Chains.push_back(Ch);
10721     }
10722     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10723   }
10724 
10725   if (!ISD::isNormalStore(St))
10726     return SDValue();
10727 
10728   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
10729   // ARM stores of arguments in the same cache line.
10730   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
10731       StVal.getNode()->hasOneUse()) {
10732     SelectionDAG  &DAG = DCI.DAG;
10733     bool isBigEndian = DAG.getDataLayout().isBigEndian();
10734     SDLoc DL(St);
10735     SDValue BasePtr = St->getBasePtr();
10736     SDValue NewST1 = DAG.getStore(
10737         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
10738         BasePtr, St->getPointerInfo(), St->getAlignment(),
10739         St->getMemOperand()->getFlags());
10740 
10741     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10742                                     DAG.getConstant(4, DL, MVT::i32));
10743     return DAG.getStore(NewST1.getValue(0), DL,
10744                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
10745                         OffsetPtr, St->getPointerInfo(),
10746                         std::min(4U, St->getAlignment() / 2),
10747                         St->getMemOperand()->getFlags());
10748   }
10749 
10750   if (StVal.getValueType() == MVT::i64 &&
10751       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10752 
10753     // Bitcast an i64 store extracted from a vector to f64.
10754     // Otherwise, the i64 value will be legalized to a pair of i32 values.
10755     SelectionDAG &DAG = DCI.DAG;
10756     SDLoc dl(StVal);
10757     SDValue IntVec = StVal.getOperand(0);
10758     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10759                                    IntVec.getValueType().getVectorNumElements());
10760     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
10761     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10762                                  Vec, StVal.getOperand(1));
10763     dl = SDLoc(N);
10764     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
10765     // Make the DAGCombiner fold the bitcasts.
10766     DCI.AddToWorklist(Vec.getNode());
10767     DCI.AddToWorklist(ExtElt.getNode());
10768     DCI.AddToWorklist(V.getNode());
10769     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
10770                         St->getPointerInfo(), St->getAlignment(),
10771                         St->getMemOperand()->getFlags(), St->getAAInfo());
10772   }
10773 
10774   // If this is a legal vector store, try to combine it into a VST1_UPD.
10775   if (ISD::isNormalStore(N) && VT.isVector() &&
10776       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
10777     return CombineBaseUpdate(N, DCI);
10778 
10779   return SDValue();
10780 }
10781 
10782 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
10783 /// can replace combinations of VMUL and VCVT (floating-point to integer)
10784 /// when the VMUL has a constant operand that is a power of 2.
10785 ///
10786 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10787 ///  vmul.f32        d16, d17, d16
10788 ///  vcvt.s32.f32    d16, d16
10789 /// becomes:
10790 ///  vcvt.s32.f32    d16, d16, #3
10791 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
10792                                   const ARMSubtarget *Subtarget) {
10793   if (!Subtarget->hasNEON())
10794     return SDValue();
10795 
10796   SDValue Op = N->getOperand(0);
10797   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
10798       Op.getOpcode() != ISD::FMUL)
10799     return SDValue();
10800 
10801   SDValue ConstVec = Op->getOperand(1);
10802   if (!isa<BuildVectorSDNode>(ConstVec))
10803     return SDValue();
10804 
10805   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
10806   uint32_t FloatBits = FloatTy.getSizeInBits();
10807   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
10808   uint32_t IntBits = IntTy.getSizeInBits();
10809   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10810   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10811     // These instructions only exist converting from f32 to i32. We can handle
10812     // smaller integers by generating an extra truncate, but larger ones would
10813     // be lossy. We also can't handle more then 4 lanes, since these intructions
10814     // only support v2i32/v4i32 types.
10815     return SDValue();
10816   }
10817 
10818   BitVector UndefElements;
10819   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10820   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10821   if (C == -1 || C == 0 || C > 32)
10822     return SDValue();
10823 
10824   SDLoc dl(N);
10825   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
10826   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
10827     Intrinsic::arm_neon_vcvtfp2fxu;
10828   SDValue FixConv = DAG.getNode(
10829       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10830       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
10831       DAG.getConstant(C, dl, MVT::i32));
10832 
10833   if (IntBits < FloatBits)
10834     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
10835 
10836   return FixConv;
10837 }
10838 
10839 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
10840 /// can replace combinations of VCVT (integer to floating-point) and VDIV
10841 /// when the VDIV has a constant operand that is a power of 2.
10842 ///
10843 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
10844 ///  vcvt.f32.s32    d16, d16
10845 ///  vdiv.f32        d16, d17, d16
10846 /// becomes:
10847 ///  vcvt.f32.s32    d16, d16, #3
10848 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
10849                                   const ARMSubtarget *Subtarget) {
10850   if (!Subtarget->hasNEON())
10851     return SDValue();
10852 
10853   SDValue Op = N->getOperand(0);
10854   unsigned OpOpcode = Op.getNode()->getOpcode();
10855   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
10856       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
10857     return SDValue();
10858 
10859   SDValue ConstVec = N->getOperand(1);
10860   if (!isa<BuildVectorSDNode>(ConstVec))
10861     return SDValue();
10862 
10863   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
10864   uint32_t FloatBits = FloatTy.getSizeInBits();
10865   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
10866   uint32_t IntBits = IntTy.getSizeInBits();
10867   unsigned NumLanes = Op.getValueType().getVectorNumElements();
10868   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
10869     // These instructions only exist converting from i32 to f32. We can handle
10870     // smaller integers by generating an extra extend, but larger ones would
10871     // be lossy. We also can't handle more then 4 lanes, since these intructions
10872     // only support v2i32/v4i32 types.
10873     return SDValue();
10874   }
10875 
10876   BitVector UndefElements;
10877   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
10878   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
10879   if (C == -1 || C == 0 || C > 32)
10880     return SDValue();
10881 
10882   SDLoc dl(N);
10883   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
10884   SDValue ConvInput = Op.getOperand(0);
10885   if (IntBits < FloatBits)
10886     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
10887                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
10888                             ConvInput);
10889 
10890   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
10891     Intrinsic::arm_neon_vcvtfxu2fp;
10892   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
10893                      Op.getValueType(),
10894                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
10895                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
10896 }
10897 
10898 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
10899 /// operand of a vector shift operation, where all the elements of the
10900 /// build_vector must have the same constant integer value.
10901 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
10902   // Ignore bit_converts.
10903   while (Op.getOpcode() == ISD::BITCAST)
10904     Op = Op.getOperand(0);
10905   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
10906   APInt SplatBits, SplatUndef;
10907   unsigned SplatBitSize;
10908   bool HasAnyUndefs;
10909   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
10910                                       HasAnyUndefs, ElementBits) ||
10911       SplatBitSize > ElementBits)
10912     return false;
10913   Cnt = SplatBits.getSExtValue();
10914   return true;
10915 }
10916 
10917 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
10918 /// operand of a vector shift left operation.  That value must be in the range:
10919 ///   0 <= Value < ElementBits for a left shift; or
10920 ///   0 <= Value <= ElementBits for a long left shift.
10921 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
10922   assert(VT.isVector() && "vector shift count is not a vector type");
10923   int64_t ElementBits = VT.getScalarSizeInBits();
10924   if (! getVShiftImm(Op, ElementBits, Cnt))
10925     return false;
10926   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
10927 }
10928 
10929 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
10930 /// operand of a vector shift right operation.  For a shift opcode, the value
10931 /// is positive, but for an intrinsic the value count must be negative. The
10932 /// absolute value must be in the range:
10933 ///   1 <= |Value| <= ElementBits for a right shift; or
10934 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
10935 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
10936                          int64_t &Cnt) {
10937   assert(VT.isVector() && "vector shift count is not a vector type");
10938   int64_t ElementBits = VT.getScalarSizeInBits();
10939   if (! getVShiftImm(Op, ElementBits, Cnt))
10940     return false;
10941   if (!isIntrinsic)
10942     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
10943   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
10944     Cnt = -Cnt;
10945     return true;
10946   }
10947   return false;
10948 }
10949 
10950 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
10951 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
10952   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
10953   switch (IntNo) {
10954   default:
10955     // Don't do anything for most intrinsics.
10956     break;
10957 
10958   // Vector shifts: check for immediate versions and lower them.
10959   // Note: This is done during DAG combining instead of DAG legalizing because
10960   // the build_vectors for 64-bit vector element shift counts are generally
10961   // not legal, and it is hard to see their values after they get legalized to
10962   // loads from a constant pool.
10963   case Intrinsic::arm_neon_vshifts:
10964   case Intrinsic::arm_neon_vshiftu:
10965   case Intrinsic::arm_neon_vrshifts:
10966   case Intrinsic::arm_neon_vrshiftu:
10967   case Intrinsic::arm_neon_vrshiftn:
10968   case Intrinsic::arm_neon_vqshifts:
10969   case Intrinsic::arm_neon_vqshiftu:
10970   case Intrinsic::arm_neon_vqshiftsu:
10971   case Intrinsic::arm_neon_vqshiftns:
10972   case Intrinsic::arm_neon_vqshiftnu:
10973   case Intrinsic::arm_neon_vqshiftnsu:
10974   case Intrinsic::arm_neon_vqrshiftns:
10975   case Intrinsic::arm_neon_vqrshiftnu:
10976   case Intrinsic::arm_neon_vqrshiftnsu: {
10977     EVT VT = N->getOperand(1).getValueType();
10978     int64_t Cnt;
10979     unsigned VShiftOpc = 0;
10980 
10981     switch (IntNo) {
10982     case Intrinsic::arm_neon_vshifts:
10983     case Intrinsic::arm_neon_vshiftu:
10984       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
10985         VShiftOpc = ARMISD::VSHL;
10986         break;
10987       }
10988       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
10989         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
10990                      ARMISD::VSHRs : ARMISD::VSHRu);
10991         break;
10992       }
10993       return SDValue();
10994 
10995     case Intrinsic::arm_neon_vrshifts:
10996     case Intrinsic::arm_neon_vrshiftu:
10997       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
10998         break;
10999       return SDValue();
11000 
11001     case Intrinsic::arm_neon_vqshifts:
11002     case Intrinsic::arm_neon_vqshiftu:
11003       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11004         break;
11005       return SDValue();
11006 
11007     case Intrinsic::arm_neon_vqshiftsu:
11008       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11009         break;
11010       llvm_unreachable("invalid shift count for vqshlu intrinsic");
11011 
11012     case Intrinsic::arm_neon_vrshiftn:
11013     case Intrinsic::arm_neon_vqshiftns:
11014     case Intrinsic::arm_neon_vqshiftnu:
11015     case Intrinsic::arm_neon_vqshiftnsu:
11016     case Intrinsic::arm_neon_vqrshiftns:
11017     case Intrinsic::arm_neon_vqrshiftnu:
11018     case Intrinsic::arm_neon_vqrshiftnsu:
11019       // Narrowing shifts require an immediate right shift.
11020       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11021         break;
11022       llvm_unreachable("invalid shift count for narrowing vector shift "
11023                        "intrinsic");
11024 
11025     default:
11026       llvm_unreachable("unhandled vector shift");
11027     }
11028 
11029     switch (IntNo) {
11030     case Intrinsic::arm_neon_vshifts:
11031     case Intrinsic::arm_neon_vshiftu:
11032       // Opcode already set above.
11033       break;
11034     case Intrinsic::arm_neon_vrshifts:
11035       VShiftOpc = ARMISD::VRSHRs; break;
11036     case Intrinsic::arm_neon_vrshiftu:
11037       VShiftOpc = ARMISD::VRSHRu; break;
11038     case Intrinsic::arm_neon_vrshiftn:
11039       VShiftOpc = ARMISD::VRSHRN; break;
11040     case Intrinsic::arm_neon_vqshifts:
11041       VShiftOpc = ARMISD::VQSHLs; break;
11042     case Intrinsic::arm_neon_vqshiftu:
11043       VShiftOpc = ARMISD::VQSHLu; break;
11044     case Intrinsic::arm_neon_vqshiftsu:
11045       VShiftOpc = ARMISD::VQSHLsu; break;
11046     case Intrinsic::arm_neon_vqshiftns:
11047       VShiftOpc = ARMISD::VQSHRNs; break;
11048     case Intrinsic::arm_neon_vqshiftnu:
11049       VShiftOpc = ARMISD::VQSHRNu; break;
11050     case Intrinsic::arm_neon_vqshiftnsu:
11051       VShiftOpc = ARMISD::VQSHRNsu; break;
11052     case Intrinsic::arm_neon_vqrshiftns:
11053       VShiftOpc = ARMISD::VQRSHRNs; break;
11054     case Intrinsic::arm_neon_vqrshiftnu:
11055       VShiftOpc = ARMISD::VQRSHRNu; break;
11056     case Intrinsic::arm_neon_vqrshiftnsu:
11057       VShiftOpc = ARMISD::VQRSHRNsu; break;
11058     }
11059 
11060     SDLoc dl(N);
11061     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11062                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
11063   }
11064 
11065   case Intrinsic::arm_neon_vshiftins: {
11066     EVT VT = N->getOperand(1).getValueType();
11067     int64_t Cnt;
11068     unsigned VShiftOpc = 0;
11069 
11070     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
11071       VShiftOpc = ARMISD::VSLI;
11072     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
11073       VShiftOpc = ARMISD::VSRI;
11074     else {
11075       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
11076     }
11077 
11078     SDLoc dl(N);
11079     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11080                        N->getOperand(1), N->getOperand(2),
11081                        DAG.getConstant(Cnt, dl, MVT::i32));
11082   }
11083 
11084   case Intrinsic::arm_neon_vqrshifts:
11085   case Intrinsic::arm_neon_vqrshiftu:
11086     // No immediate versions of these to check for.
11087     break;
11088   }
11089 
11090   return SDValue();
11091 }
11092 
11093 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
11094 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
11095 /// combining instead of DAG legalizing because the build_vectors for 64-bit
11096 /// vector element shift counts are generally not legal, and it is hard to see
11097 /// their values after they get legalized to loads from a constant pool.
11098 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
11099                                    const ARMSubtarget *ST) {
11100   EVT VT = N->getValueType(0);
11101   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
11102     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
11103     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
11104     SDValue N1 = N->getOperand(1);
11105     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11106       SDValue N0 = N->getOperand(0);
11107       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
11108           DAG.MaskedValueIsZero(N0.getOperand(0),
11109                                 APInt::getHighBitsSet(32, 16)))
11110         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
11111     }
11112   }
11113 
11114   // Nothing to be done for scalar shifts.
11115   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11116   if (!VT.isVector() || !TLI.isTypeLegal(VT))
11117     return SDValue();
11118 
11119   assert(ST->hasNEON() && "unexpected vector shift");
11120   int64_t Cnt;
11121 
11122   switch (N->getOpcode()) {
11123   default: llvm_unreachable("unexpected shift opcode");
11124 
11125   case ISD::SHL:
11126     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
11127       SDLoc dl(N);
11128       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
11129                          DAG.getConstant(Cnt, dl, MVT::i32));
11130     }
11131     break;
11132 
11133   case ISD::SRA:
11134   case ISD::SRL:
11135     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
11136       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
11137                             ARMISD::VSHRs : ARMISD::VSHRu);
11138       SDLoc dl(N);
11139       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
11140                          DAG.getConstant(Cnt, dl, MVT::i32));
11141     }
11142   }
11143   return SDValue();
11144 }
11145 
11146 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
11147 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
11148 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
11149                                     const ARMSubtarget *ST) {
11150   SDValue N0 = N->getOperand(0);
11151 
11152   // Check for sign- and zero-extensions of vector extract operations of 8-
11153   // and 16-bit vector elements.  NEON supports these directly.  They are
11154   // handled during DAG combining because type legalization will promote them
11155   // to 32-bit types and it is messy to recognize the operations after that.
11156   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11157     SDValue Vec = N0.getOperand(0);
11158     SDValue Lane = N0.getOperand(1);
11159     EVT VT = N->getValueType(0);
11160     EVT EltVT = N0.getValueType();
11161     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11162 
11163     if (VT == MVT::i32 &&
11164         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
11165         TLI.isTypeLegal(Vec.getValueType()) &&
11166         isa<ConstantSDNode>(Lane)) {
11167 
11168       unsigned Opc = 0;
11169       switch (N->getOpcode()) {
11170       default: llvm_unreachable("unexpected opcode");
11171       case ISD::SIGN_EXTEND:
11172         Opc = ARMISD::VGETLANEs;
11173         break;
11174       case ISD::ZERO_EXTEND:
11175       case ISD::ANY_EXTEND:
11176         Opc = ARMISD::VGETLANEu;
11177         break;
11178       }
11179       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
11180     }
11181   }
11182 
11183   return SDValue();
11184 }
11185 
11186 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
11187                              APInt &KnownOne) {
11188   if (Op.getOpcode() == ARMISD::BFI) {
11189     // Conservatively, we can recurse down the first operand
11190     // and just mask out all affected bits.
11191     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
11192 
11193     // The operand to BFI is already a mask suitable for removing the bits it
11194     // sets.
11195     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
11196     const APInt &Mask = CI->getAPIntValue();
11197     KnownZero &= Mask;
11198     KnownOne &= Mask;
11199     return;
11200   }
11201   if (Op.getOpcode() == ARMISD::CMOV) {
11202     APInt KZ2(KnownZero.getBitWidth(), 0);
11203     APInt KO2(KnownOne.getBitWidth(), 0);
11204     computeKnownBits(DAG, Op.getOperand(1), KnownZero, KnownOne);
11205     computeKnownBits(DAG, Op.getOperand(2), KZ2, KO2);
11206 
11207     KnownZero &= KZ2;
11208     KnownOne &= KO2;
11209     return;
11210   }
11211   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
11212 }
11213 
11214 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
11215   // If we have a CMOV, OR and AND combination such as:
11216   //   if (x & CN)
11217   //     y |= CM;
11218   //
11219   // And:
11220   //   * CN is a single bit;
11221   //   * All bits covered by CM are known zero in y
11222   //
11223   // Then we can convert this into a sequence of BFI instructions. This will
11224   // always be a win if CM is a single bit, will always be no worse than the
11225   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
11226   // three bits (due to the extra IT instruction).
11227 
11228   SDValue Op0 = CMOV->getOperand(0);
11229   SDValue Op1 = CMOV->getOperand(1);
11230   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
11231   auto CC = CCNode->getAPIntValue().getLimitedValue();
11232   SDValue CmpZ = CMOV->getOperand(4);
11233 
11234   // The compare must be against zero.
11235   if (!isNullConstant(CmpZ->getOperand(1)))
11236     return SDValue();
11237 
11238   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
11239   SDValue And = CmpZ->getOperand(0);
11240   if (And->getOpcode() != ISD::AND)
11241     return SDValue();
11242   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
11243   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
11244     return SDValue();
11245   SDValue X = And->getOperand(0);
11246 
11247   if (CC == ARMCC::EQ) {
11248     // We're performing an "equal to zero" compare. Swap the operands so we
11249     // canonicalize on a "not equal to zero" compare.
11250     std::swap(Op0, Op1);
11251   } else {
11252     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
11253   }
11254 
11255   if (Op1->getOpcode() != ISD::OR)
11256     return SDValue();
11257 
11258   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
11259   if (!OrC)
11260     return SDValue();
11261   SDValue Y = Op1->getOperand(0);
11262 
11263   if (Op0 != Y)
11264     return SDValue();
11265 
11266   // Now, is it profitable to continue?
11267   APInt OrCI = OrC->getAPIntValue();
11268   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
11269   if (OrCI.countPopulation() > Heuristic)
11270     return SDValue();
11271 
11272   // Lastly, can we determine that the bits defined by OrCI
11273   // are zero in Y?
11274   APInt KnownZero, KnownOne;
11275   computeKnownBits(DAG, Y, KnownZero, KnownOne);
11276   if ((OrCI & KnownZero) != OrCI)
11277     return SDValue();
11278 
11279   // OK, we can do the combine.
11280   SDValue V = Y;
11281   SDLoc dl(X);
11282   EVT VT = X.getValueType();
11283   unsigned BitInX = AndC->getAPIntValue().logBase2();
11284 
11285   if (BitInX != 0) {
11286     // We must shift X first.
11287     X = DAG.getNode(ISD::SRL, dl, VT, X,
11288                     DAG.getConstant(BitInX, dl, VT));
11289   }
11290 
11291   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
11292        BitInY < NumActiveBits; ++BitInY) {
11293     if (OrCI[BitInY] == 0)
11294       continue;
11295     APInt Mask(VT.getSizeInBits(), 0);
11296     Mask.setBit(BitInY);
11297     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
11298                     // Confusingly, the operand is an *inverted* mask.
11299                     DAG.getConstant(~Mask, dl, VT));
11300   }
11301 
11302   return V;
11303 }
11304 
11305 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
11306 SDValue
11307 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
11308   SDValue Cmp = N->getOperand(4);
11309   if (Cmp.getOpcode() != ARMISD::CMPZ)
11310     // Only looking at NE cases.
11311     return SDValue();
11312 
11313   EVT VT = N->getValueType(0);
11314   SDLoc dl(N);
11315   SDValue LHS = Cmp.getOperand(0);
11316   SDValue RHS = Cmp.getOperand(1);
11317   SDValue Chain = N->getOperand(0);
11318   SDValue BB = N->getOperand(1);
11319   SDValue ARMcc = N->getOperand(2);
11320   ARMCC::CondCodes CC =
11321     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11322 
11323   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
11324   // -> (brcond Chain BB CC CPSR Cmp)
11325   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
11326       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
11327       LHS->getOperand(0)->hasOneUse()) {
11328     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
11329     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
11330     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11331     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11332     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
11333         (LHS01C && LHS01C->getZExtValue() == 1) &&
11334         (LHS1C && LHS1C->getZExtValue() == 1) &&
11335         (RHSC && RHSC->getZExtValue() == 0)) {
11336       return DAG.getNode(
11337           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
11338           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
11339     }
11340   }
11341 
11342   return SDValue();
11343 }
11344 
11345 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
11346 SDValue
11347 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
11348   SDValue Cmp = N->getOperand(4);
11349   if (Cmp.getOpcode() != ARMISD::CMPZ)
11350     // Only looking at EQ and NE cases.
11351     return SDValue();
11352 
11353   EVT VT = N->getValueType(0);
11354   SDLoc dl(N);
11355   SDValue LHS = Cmp.getOperand(0);
11356   SDValue RHS = Cmp.getOperand(1);
11357   SDValue FalseVal = N->getOperand(0);
11358   SDValue TrueVal = N->getOperand(1);
11359   SDValue ARMcc = N->getOperand(2);
11360   ARMCC::CondCodes CC =
11361     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11362 
11363   // BFI is only available on V6T2+.
11364   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
11365     SDValue R = PerformCMOVToBFICombine(N, DAG);
11366     if (R)
11367       return R;
11368   }
11369 
11370   // Simplify
11371   //   mov     r1, r0
11372   //   cmp     r1, x
11373   //   mov     r0, y
11374   //   moveq   r0, x
11375   // to
11376   //   cmp     r0, x
11377   //   movne   r0, y
11378   //
11379   //   mov     r1, r0
11380   //   cmp     r1, x
11381   //   mov     r0, x
11382   //   movne   r0, y
11383   // to
11384   //   cmp     r0, x
11385   //   movne   r0, y
11386   /// FIXME: Turn this into a target neutral optimization?
11387   SDValue Res;
11388   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
11389     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
11390                       N->getOperand(3), Cmp);
11391   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
11392     SDValue ARMcc;
11393     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
11394     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
11395                       N->getOperand(3), NewCmp);
11396   }
11397 
11398   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
11399   // -> (cmov F T CC CPSR Cmp)
11400   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
11401     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
11402     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11403     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11404     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
11405         (LHS1C && LHS1C->getZExtValue() == 1) &&
11406         (RHSC && RHSC->getZExtValue() == 0)) {
11407       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
11408                          LHS->getOperand(2), LHS->getOperand(3),
11409                          LHS->getOperand(4));
11410     }
11411   }
11412 
11413   if (Res.getNode()) {
11414     APInt KnownZero, KnownOne;
11415     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
11416     // Capture demanded bits information that would be otherwise lost.
11417     if (KnownZero == 0xfffffffe)
11418       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11419                         DAG.getValueType(MVT::i1));
11420     else if (KnownZero == 0xffffff00)
11421       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11422                         DAG.getValueType(MVT::i8));
11423     else if (KnownZero == 0xffff0000)
11424       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11425                         DAG.getValueType(MVT::i16));
11426   }
11427 
11428   return Res;
11429 }
11430 
11431 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
11432                                              DAGCombinerInfo &DCI) const {
11433   switch (N->getOpcode()) {
11434   default: break;
11435   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
11436   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
11437   case ISD::SUB:        return PerformSUBCombine(N, DCI);
11438   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
11439   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
11440   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
11441   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
11442   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
11443   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
11444   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
11445   case ISD::STORE:      return PerformSTORECombine(N, DCI);
11446   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
11447   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
11448   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
11449   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
11450   case ISD::FP_TO_SINT:
11451   case ISD::FP_TO_UINT:
11452     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
11453   case ISD::FDIV:
11454     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
11455   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
11456   case ISD::SHL:
11457   case ISD::SRA:
11458   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
11459   case ISD::SIGN_EXTEND:
11460   case ISD::ZERO_EXTEND:
11461   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
11462   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
11463   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
11464   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
11465   case ARMISD::VLD2DUP:
11466   case ARMISD::VLD3DUP:
11467   case ARMISD::VLD4DUP:
11468     return PerformVLDCombine(N, DCI);
11469   case ARMISD::BUILD_VECTOR:
11470     return PerformARMBUILD_VECTORCombine(N, DCI);
11471   case ISD::INTRINSIC_VOID:
11472   case ISD::INTRINSIC_W_CHAIN:
11473     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11474     case Intrinsic::arm_neon_vld1:
11475     case Intrinsic::arm_neon_vld2:
11476     case Intrinsic::arm_neon_vld3:
11477     case Intrinsic::arm_neon_vld4:
11478     case Intrinsic::arm_neon_vld2lane:
11479     case Intrinsic::arm_neon_vld3lane:
11480     case Intrinsic::arm_neon_vld4lane:
11481     case Intrinsic::arm_neon_vst1:
11482     case Intrinsic::arm_neon_vst2:
11483     case Intrinsic::arm_neon_vst3:
11484     case Intrinsic::arm_neon_vst4:
11485     case Intrinsic::arm_neon_vst2lane:
11486     case Intrinsic::arm_neon_vst3lane:
11487     case Intrinsic::arm_neon_vst4lane:
11488       return PerformVLDCombine(N, DCI);
11489     default: break;
11490     }
11491     break;
11492   }
11493   return SDValue();
11494 }
11495 
11496 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
11497                                                           EVT VT) const {
11498   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
11499 }
11500 
11501 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
11502                                                        unsigned,
11503                                                        unsigned,
11504                                                        bool *Fast) const {
11505   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
11506   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
11507 
11508   switch (VT.getSimpleVT().SimpleTy) {
11509   default:
11510     return false;
11511   case MVT::i8:
11512   case MVT::i16:
11513   case MVT::i32: {
11514     // Unaligned access can use (for example) LRDB, LRDH, LDR
11515     if (AllowsUnaligned) {
11516       if (Fast)
11517         *Fast = Subtarget->hasV7Ops();
11518       return true;
11519     }
11520     return false;
11521   }
11522   case MVT::f64:
11523   case MVT::v2f64: {
11524     // For any little-endian targets with neon, we can support unaligned ld/st
11525     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
11526     // A big-endian target may also explicitly support unaligned accesses
11527     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
11528       if (Fast)
11529         *Fast = true;
11530       return true;
11531     }
11532     return false;
11533   }
11534   }
11535 }
11536 
11537 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
11538                        unsigned AlignCheck) {
11539   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
11540           (DstAlign == 0 || DstAlign % AlignCheck == 0));
11541 }
11542 
11543 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
11544                                            unsigned DstAlign, unsigned SrcAlign,
11545                                            bool IsMemset, bool ZeroMemset,
11546                                            bool MemcpyStrSrc,
11547                                            MachineFunction &MF) const {
11548   const Function *F = MF.getFunction();
11549 
11550   // See if we can use NEON instructions for this...
11551   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
11552       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
11553     bool Fast;
11554     if (Size >= 16 &&
11555         (memOpAlign(SrcAlign, DstAlign, 16) ||
11556          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
11557       return MVT::v2f64;
11558     } else if (Size >= 8 &&
11559                (memOpAlign(SrcAlign, DstAlign, 8) ||
11560                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
11561                  Fast))) {
11562       return MVT::f64;
11563     }
11564   }
11565 
11566   // Lowering to i32/i16 if the size permits.
11567   if (Size >= 4)
11568     return MVT::i32;
11569   else if (Size >= 2)
11570     return MVT::i16;
11571 
11572   // Let the target-independent logic figure it out.
11573   return MVT::Other;
11574 }
11575 
11576 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
11577   if (Val.getOpcode() != ISD::LOAD)
11578     return false;
11579 
11580   EVT VT1 = Val.getValueType();
11581   if (!VT1.isSimple() || !VT1.isInteger() ||
11582       !VT2.isSimple() || !VT2.isInteger())
11583     return false;
11584 
11585   switch (VT1.getSimpleVT().SimpleTy) {
11586   default: break;
11587   case MVT::i1:
11588   case MVT::i8:
11589   case MVT::i16:
11590     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
11591     return true;
11592   }
11593 
11594   return false;
11595 }
11596 
11597 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
11598   EVT VT = ExtVal.getValueType();
11599 
11600   if (!isTypeLegal(VT))
11601     return false;
11602 
11603   // Don't create a loadext if we can fold the extension into a wide/long
11604   // instruction.
11605   // If there's more than one user instruction, the loadext is desirable no
11606   // matter what.  There can be two uses by the same instruction.
11607   if (ExtVal->use_empty() ||
11608       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
11609     return true;
11610 
11611   SDNode *U = *ExtVal->use_begin();
11612   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
11613        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
11614     return false;
11615 
11616   return true;
11617 }
11618 
11619 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
11620   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
11621     return false;
11622 
11623   if (!isTypeLegal(EVT::getEVT(Ty1)))
11624     return false;
11625 
11626   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
11627 
11628   // Assuming the caller doesn't have a zeroext or signext return parameter,
11629   // truncation all the way down to i1 is valid.
11630   return true;
11631 }
11632 
11633 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
11634                                                 const AddrMode &AM, Type *Ty,
11635                                                 unsigned AS) const {
11636   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
11637     if (Subtarget->hasFPAO())
11638       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
11639     return 0;
11640   }
11641   return -1;
11642 }
11643 
11644 
11645 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
11646   if (V < 0)
11647     return false;
11648 
11649   unsigned Scale = 1;
11650   switch (VT.getSimpleVT().SimpleTy) {
11651   default: return false;
11652   case MVT::i1:
11653   case MVT::i8:
11654     // Scale == 1;
11655     break;
11656   case MVT::i16:
11657     // Scale == 2;
11658     Scale = 2;
11659     break;
11660   case MVT::i32:
11661     // Scale == 4;
11662     Scale = 4;
11663     break;
11664   }
11665 
11666   if ((V & (Scale - 1)) != 0)
11667     return false;
11668   V /= Scale;
11669   return V == (V & ((1LL << 5) - 1));
11670 }
11671 
11672 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
11673                                       const ARMSubtarget *Subtarget) {
11674   bool isNeg = false;
11675   if (V < 0) {
11676     isNeg = true;
11677     V = - V;
11678   }
11679 
11680   switch (VT.getSimpleVT().SimpleTy) {
11681   default: return false;
11682   case MVT::i1:
11683   case MVT::i8:
11684   case MVT::i16:
11685   case MVT::i32:
11686     // + imm12 or - imm8
11687     if (isNeg)
11688       return V == (V & ((1LL << 8) - 1));
11689     return V == (V & ((1LL << 12) - 1));
11690   case MVT::f32:
11691   case MVT::f64:
11692     // Same as ARM mode. FIXME: NEON?
11693     if (!Subtarget->hasVFP2())
11694       return false;
11695     if ((V & 3) != 0)
11696       return false;
11697     V >>= 2;
11698     return V == (V & ((1LL << 8) - 1));
11699   }
11700 }
11701 
11702 /// isLegalAddressImmediate - Return true if the integer value can be used
11703 /// as the offset of the target addressing mode for load / store of the
11704 /// given type.
11705 static bool isLegalAddressImmediate(int64_t V, EVT VT,
11706                                     const ARMSubtarget *Subtarget) {
11707   if (V == 0)
11708     return true;
11709 
11710   if (!VT.isSimple())
11711     return false;
11712 
11713   if (Subtarget->isThumb1Only())
11714     return isLegalT1AddressImmediate(V, VT);
11715   else if (Subtarget->isThumb2())
11716     return isLegalT2AddressImmediate(V, VT, Subtarget);
11717 
11718   // ARM mode.
11719   if (V < 0)
11720     V = - V;
11721   switch (VT.getSimpleVT().SimpleTy) {
11722   default: return false;
11723   case MVT::i1:
11724   case MVT::i8:
11725   case MVT::i32:
11726     // +- imm12
11727     return V == (V & ((1LL << 12) - 1));
11728   case MVT::i16:
11729     // +- imm8
11730     return V == (V & ((1LL << 8) - 1));
11731   case MVT::f32:
11732   case MVT::f64:
11733     if (!Subtarget->hasVFP2()) // FIXME: NEON?
11734       return false;
11735     if ((V & 3) != 0)
11736       return false;
11737     V >>= 2;
11738     return V == (V & ((1LL << 8) - 1));
11739   }
11740 }
11741 
11742 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
11743                                                       EVT VT) const {
11744   int Scale = AM.Scale;
11745   if (Scale < 0)
11746     return false;
11747 
11748   switch (VT.getSimpleVT().SimpleTy) {
11749   default: return false;
11750   case MVT::i1:
11751   case MVT::i8:
11752   case MVT::i16:
11753   case MVT::i32:
11754     if (Scale == 1)
11755       return true;
11756     // r + r << imm
11757     Scale = Scale & ~1;
11758     return Scale == 2 || Scale == 4 || Scale == 8;
11759   case MVT::i64:
11760     // r + r
11761     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11762       return true;
11763     return false;
11764   case MVT::isVoid:
11765     // Note, we allow "void" uses (basically, uses that aren't loads or
11766     // stores), because arm allows folding a scale into many arithmetic
11767     // operations.  This should be made more precise and revisited later.
11768 
11769     // Allow r << imm, but the imm has to be a multiple of two.
11770     if (Scale & 1) return false;
11771     return isPowerOf2_32(Scale);
11772   }
11773 }
11774 
11775 /// isLegalAddressingMode - Return true if the addressing mode represented
11776 /// by AM is legal for this target, for a load/store of the specified type.
11777 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
11778                                               const AddrMode &AM, Type *Ty,
11779                                               unsigned AS) const {
11780   EVT VT = getValueType(DL, Ty, true);
11781   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
11782     return false;
11783 
11784   // Can never fold addr of global into load/store.
11785   if (AM.BaseGV)
11786     return false;
11787 
11788   switch (AM.Scale) {
11789   case 0:  // no scale reg, must be "r+i" or "r", or "i".
11790     break;
11791   case 1:
11792     if (Subtarget->isThumb1Only())
11793       return false;
11794     LLVM_FALLTHROUGH;
11795   default:
11796     // ARM doesn't support any R+R*scale+imm addr modes.
11797     if (AM.BaseOffs)
11798       return false;
11799 
11800     if (!VT.isSimple())
11801       return false;
11802 
11803     if (Subtarget->isThumb2())
11804       return isLegalT2ScaledAddressingMode(AM, VT);
11805 
11806     int Scale = AM.Scale;
11807     switch (VT.getSimpleVT().SimpleTy) {
11808     default: return false;
11809     case MVT::i1:
11810     case MVT::i8:
11811     case MVT::i32:
11812       if (Scale < 0) Scale = -Scale;
11813       if (Scale == 1)
11814         return true;
11815       // r + r << imm
11816       return isPowerOf2_32(Scale & ~1);
11817     case MVT::i16:
11818     case MVT::i64:
11819       // r + r
11820       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
11821         return true;
11822       return false;
11823 
11824     case MVT::isVoid:
11825       // Note, we allow "void" uses (basically, uses that aren't loads or
11826       // stores), because arm allows folding a scale into many arithmetic
11827       // operations.  This should be made more precise and revisited later.
11828 
11829       // Allow r << imm, but the imm has to be a multiple of two.
11830       if (Scale & 1) return false;
11831       return isPowerOf2_32(Scale);
11832     }
11833   }
11834   return true;
11835 }
11836 
11837 /// isLegalICmpImmediate - Return true if the specified immediate is legal
11838 /// icmp immediate, that is the target has icmp instructions which can compare
11839 /// a register against the immediate without having to materialize the
11840 /// immediate into a register.
11841 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
11842   // Thumb2 and ARM modes can use cmn for negative immediates.
11843   if (!Subtarget->isThumb())
11844     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
11845   if (Subtarget->isThumb2())
11846     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
11847   // Thumb1 doesn't have cmn, and only 8-bit immediates.
11848   return Imm >= 0 && Imm <= 255;
11849 }
11850 
11851 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
11852 /// *or sub* immediate, that is the target has add or sub instructions which can
11853 /// add a register with the immediate without having to materialize the
11854 /// immediate into a register.
11855 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
11856   // Same encoding for add/sub, just flip the sign.
11857   int64_t AbsImm = std::abs(Imm);
11858   if (!Subtarget->isThumb())
11859     return ARM_AM::getSOImmVal(AbsImm) != -1;
11860   if (Subtarget->isThumb2())
11861     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
11862   // Thumb1 only has 8-bit unsigned immediate.
11863   return AbsImm >= 0 && AbsImm <= 255;
11864 }
11865 
11866 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
11867                                       bool isSEXTLoad, SDValue &Base,
11868                                       SDValue &Offset, bool &isInc,
11869                                       SelectionDAG &DAG) {
11870   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11871     return false;
11872 
11873   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
11874     // AddressingMode 3
11875     Base = Ptr->getOperand(0);
11876     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11877       int RHSC = (int)RHS->getZExtValue();
11878       if (RHSC < 0 && RHSC > -256) {
11879         assert(Ptr->getOpcode() == ISD::ADD);
11880         isInc = false;
11881         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11882         return true;
11883       }
11884     }
11885     isInc = (Ptr->getOpcode() == ISD::ADD);
11886     Offset = Ptr->getOperand(1);
11887     return true;
11888   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
11889     // AddressingMode 2
11890     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11891       int RHSC = (int)RHS->getZExtValue();
11892       if (RHSC < 0 && RHSC > -0x1000) {
11893         assert(Ptr->getOpcode() == ISD::ADD);
11894         isInc = false;
11895         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11896         Base = Ptr->getOperand(0);
11897         return true;
11898       }
11899     }
11900 
11901     if (Ptr->getOpcode() == ISD::ADD) {
11902       isInc = true;
11903       ARM_AM::ShiftOpc ShOpcVal=
11904         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
11905       if (ShOpcVal != ARM_AM::no_shift) {
11906         Base = Ptr->getOperand(1);
11907         Offset = Ptr->getOperand(0);
11908       } else {
11909         Base = Ptr->getOperand(0);
11910         Offset = Ptr->getOperand(1);
11911       }
11912       return true;
11913     }
11914 
11915     isInc = (Ptr->getOpcode() == ISD::ADD);
11916     Base = Ptr->getOperand(0);
11917     Offset = Ptr->getOperand(1);
11918     return true;
11919   }
11920 
11921   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
11922   return false;
11923 }
11924 
11925 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
11926                                      bool isSEXTLoad, SDValue &Base,
11927                                      SDValue &Offset, bool &isInc,
11928                                      SelectionDAG &DAG) {
11929   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
11930     return false;
11931 
11932   Base = Ptr->getOperand(0);
11933   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
11934     int RHSC = (int)RHS->getZExtValue();
11935     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
11936       assert(Ptr->getOpcode() == ISD::ADD);
11937       isInc = false;
11938       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
11939       return true;
11940     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
11941       isInc = Ptr->getOpcode() == ISD::ADD;
11942       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
11943       return true;
11944     }
11945   }
11946 
11947   return false;
11948 }
11949 
11950 /// getPreIndexedAddressParts - returns true by value, base pointer and
11951 /// offset pointer and addressing mode by reference if the node's address
11952 /// can be legally represented as pre-indexed load / store address.
11953 bool
11954 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
11955                                              SDValue &Offset,
11956                                              ISD::MemIndexedMode &AM,
11957                                              SelectionDAG &DAG) const {
11958   if (Subtarget->isThumb1Only())
11959     return false;
11960 
11961   EVT VT;
11962   SDValue Ptr;
11963   bool isSEXTLoad = false;
11964   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
11965     Ptr = LD->getBasePtr();
11966     VT  = LD->getMemoryVT();
11967     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
11968   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
11969     Ptr = ST->getBasePtr();
11970     VT  = ST->getMemoryVT();
11971   } else
11972     return false;
11973 
11974   bool isInc;
11975   bool isLegal = false;
11976   if (Subtarget->isThumb2())
11977     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11978                                        Offset, isInc, DAG);
11979   else
11980     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
11981                                         Offset, isInc, DAG);
11982   if (!isLegal)
11983     return false;
11984 
11985   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
11986   return true;
11987 }
11988 
11989 /// getPostIndexedAddressParts - returns true by value, base pointer and
11990 /// offset pointer and addressing mode by reference if this node can be
11991 /// combined with a load / store to form a post-indexed load / store.
11992 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
11993                                                    SDValue &Base,
11994                                                    SDValue &Offset,
11995                                                    ISD::MemIndexedMode &AM,
11996                                                    SelectionDAG &DAG) const {
11997   EVT VT;
11998   SDValue Ptr;
11999   bool isSEXTLoad = false, isNonExt;
12000   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12001     VT  = LD->getMemoryVT();
12002     Ptr = LD->getBasePtr();
12003     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12004     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
12005   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12006     VT  = ST->getMemoryVT();
12007     Ptr = ST->getBasePtr();
12008     isNonExt = !ST->isTruncatingStore();
12009   } else
12010     return false;
12011 
12012   if (Subtarget->isThumb1Only()) {
12013     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
12014     // must be non-extending/truncating, i32, with an offset of 4.
12015     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
12016     if (Op->getOpcode() != ISD::ADD || !isNonExt)
12017       return false;
12018     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12019     if (!RHS || RHS->getZExtValue() != 4)
12020       return false;
12021 
12022     Offset = Op->getOperand(1);
12023     Base = Op->getOperand(0);
12024     AM = ISD::POST_INC;
12025     return true;
12026   }
12027 
12028   bool isInc;
12029   bool isLegal = false;
12030   if (Subtarget->isThumb2())
12031     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12032                                        isInc, DAG);
12033   else
12034     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12035                                         isInc, DAG);
12036   if (!isLegal)
12037     return false;
12038 
12039   if (Ptr != Base) {
12040     // Swap base ptr and offset to catch more post-index load / store when
12041     // it's legal. In Thumb2 mode, offset must be an immediate.
12042     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
12043         !Subtarget->isThumb2())
12044       std::swap(Base, Offset);
12045 
12046     // Post-indexed load / store update the base pointer.
12047     if (Ptr != Base)
12048       return false;
12049   }
12050 
12051   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
12052   return true;
12053 }
12054 
12055 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12056                                                       APInt &KnownZero,
12057                                                       APInt &KnownOne,
12058                                                       const SelectionDAG &DAG,
12059                                                       unsigned Depth) const {
12060   unsigned BitWidth = KnownOne.getBitWidth();
12061   KnownZero = KnownOne = APInt(BitWidth, 0);
12062   switch (Op.getOpcode()) {
12063   default: break;
12064   case ARMISD::ADDC:
12065   case ARMISD::ADDE:
12066   case ARMISD::SUBC:
12067   case ARMISD::SUBE:
12068     // These nodes' second result is a boolean
12069     if (Op.getResNo() == 0)
12070       break;
12071     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12072     break;
12073   case ARMISD::CMOV: {
12074     // Bits are known zero/one if known on the LHS and RHS.
12075     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
12076     if (KnownZero == 0 && KnownOne == 0) return;
12077 
12078     APInt KnownZeroRHS, KnownOneRHS;
12079     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
12080     KnownZero &= KnownZeroRHS;
12081     KnownOne  &= KnownOneRHS;
12082     return;
12083   }
12084   case ISD::INTRINSIC_W_CHAIN: {
12085     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
12086     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12087     switch (IntID) {
12088     default: return;
12089     case Intrinsic::arm_ldaex:
12090     case Intrinsic::arm_ldrex: {
12091       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
12092       unsigned MemBits = VT.getScalarSizeInBits();
12093       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
12094       return;
12095     }
12096     }
12097   }
12098   }
12099 }
12100 
12101 //===----------------------------------------------------------------------===//
12102 //                           ARM Inline Assembly Support
12103 //===----------------------------------------------------------------------===//
12104 
12105 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
12106   // Looking for "rev" which is V6+.
12107   if (!Subtarget->hasV6Ops())
12108     return false;
12109 
12110   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12111   std::string AsmStr = IA->getAsmString();
12112   SmallVector<StringRef, 4> AsmPieces;
12113   SplitString(AsmStr, AsmPieces, ";\n");
12114 
12115   switch (AsmPieces.size()) {
12116   default: return false;
12117   case 1:
12118     AsmStr = AsmPieces[0];
12119     AsmPieces.clear();
12120     SplitString(AsmStr, AsmPieces, " \t,");
12121 
12122     // rev $0, $1
12123     if (AsmPieces.size() == 3 &&
12124         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
12125         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
12126       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12127       if (Ty && Ty->getBitWidth() == 32)
12128         return IntrinsicLowering::LowerToByteSwap(CI);
12129     }
12130     break;
12131   }
12132 
12133   return false;
12134 }
12135 
12136 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
12137   // At this point, we have to lower this constraint to something else, so we
12138   // lower it to an "r" or "w". However, by doing this we will force the result
12139   // to be in register, while the X constraint is much more permissive.
12140   //
12141   // Although we are correct (we are free to emit anything, without
12142   // constraints), we might break use cases that would expect us to be more
12143   // efficient and emit something else.
12144   if (!Subtarget->hasVFP2())
12145     return "r";
12146   if (ConstraintVT.isFloatingPoint())
12147     return "w";
12148   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
12149      (ConstraintVT.getSizeInBits() == 64 ||
12150       ConstraintVT.getSizeInBits() == 128))
12151     return "w";
12152 
12153   return "r";
12154 }
12155 
12156 /// getConstraintType - Given a constraint letter, return the type of
12157 /// constraint it is for this target.
12158 ARMTargetLowering::ConstraintType
12159 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
12160   if (Constraint.size() == 1) {
12161     switch (Constraint[0]) {
12162     default:  break;
12163     case 'l': return C_RegisterClass;
12164     case 'w': return C_RegisterClass;
12165     case 'h': return C_RegisterClass;
12166     case 'x': return C_RegisterClass;
12167     case 't': return C_RegisterClass;
12168     case 'j': return C_Other; // Constant for movw.
12169       // An address with a single base register. Due to the way we
12170       // currently handle addresses it is the same as an 'r' memory constraint.
12171     case 'Q': return C_Memory;
12172     }
12173   } else if (Constraint.size() == 2) {
12174     switch (Constraint[0]) {
12175     default: break;
12176     // All 'U+' constraints are addresses.
12177     case 'U': return C_Memory;
12178     }
12179   }
12180   return TargetLowering::getConstraintType(Constraint);
12181 }
12182 
12183 /// Examine constraint type and operand type and determine a weight value.
12184 /// This object must already have been set up with the operand type
12185 /// and the current alternative constraint selected.
12186 TargetLowering::ConstraintWeight
12187 ARMTargetLowering::getSingleConstraintMatchWeight(
12188     AsmOperandInfo &info, const char *constraint) const {
12189   ConstraintWeight weight = CW_Invalid;
12190   Value *CallOperandVal = info.CallOperandVal;
12191     // If we don't have a value, we can't do a match,
12192     // but allow it at the lowest weight.
12193   if (!CallOperandVal)
12194     return CW_Default;
12195   Type *type = CallOperandVal->getType();
12196   // Look at the constraint type.
12197   switch (*constraint) {
12198   default:
12199     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12200     break;
12201   case 'l':
12202     if (type->isIntegerTy()) {
12203       if (Subtarget->isThumb())
12204         weight = CW_SpecificReg;
12205       else
12206         weight = CW_Register;
12207     }
12208     break;
12209   case 'w':
12210     if (type->isFloatingPointTy())
12211       weight = CW_Register;
12212     break;
12213   }
12214   return weight;
12215 }
12216 
12217 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
12218 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
12219     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
12220   if (Constraint.size() == 1) {
12221     // GCC ARM Constraint Letters
12222     switch (Constraint[0]) {
12223     case 'l': // Low regs or general regs.
12224       if (Subtarget->isThumb())
12225         return RCPair(0U, &ARM::tGPRRegClass);
12226       return RCPair(0U, &ARM::GPRRegClass);
12227     case 'h': // High regs or no regs.
12228       if (Subtarget->isThumb())
12229         return RCPair(0U, &ARM::hGPRRegClass);
12230       break;
12231     case 'r':
12232       if (Subtarget->isThumb1Only())
12233         return RCPair(0U, &ARM::tGPRRegClass);
12234       return RCPair(0U, &ARM::GPRRegClass);
12235     case 'w':
12236       if (VT == MVT::Other)
12237         break;
12238       if (VT == MVT::f32)
12239         return RCPair(0U, &ARM::SPRRegClass);
12240       if (VT.getSizeInBits() == 64)
12241         return RCPair(0U, &ARM::DPRRegClass);
12242       if (VT.getSizeInBits() == 128)
12243         return RCPair(0U, &ARM::QPRRegClass);
12244       break;
12245     case 'x':
12246       if (VT == MVT::Other)
12247         break;
12248       if (VT == MVT::f32)
12249         return RCPair(0U, &ARM::SPR_8RegClass);
12250       if (VT.getSizeInBits() == 64)
12251         return RCPair(0U, &ARM::DPR_8RegClass);
12252       if (VT.getSizeInBits() == 128)
12253         return RCPair(0U, &ARM::QPR_8RegClass);
12254       break;
12255     case 't':
12256       if (VT == MVT::f32)
12257         return RCPair(0U, &ARM::SPRRegClass);
12258       break;
12259     }
12260   }
12261   if (StringRef("{cc}").equals_lower(Constraint))
12262     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
12263 
12264   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12265 }
12266 
12267 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12268 /// vector.  If it is invalid, don't add anything to Ops.
12269 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12270                                                      std::string &Constraint,
12271                                                      std::vector<SDValue>&Ops,
12272                                                      SelectionDAG &DAG) const {
12273   SDValue Result;
12274 
12275   // Currently only support length 1 constraints.
12276   if (Constraint.length() != 1) return;
12277 
12278   char ConstraintLetter = Constraint[0];
12279   switch (ConstraintLetter) {
12280   default: break;
12281   case 'j':
12282   case 'I': case 'J': case 'K': case 'L':
12283   case 'M': case 'N': case 'O':
12284     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
12285     if (!C)
12286       return;
12287 
12288     int64_t CVal64 = C->getSExtValue();
12289     int CVal = (int) CVal64;
12290     // None of these constraints allow values larger than 32 bits.  Check
12291     // that the value fits in an int.
12292     if (CVal != CVal64)
12293       return;
12294 
12295     switch (ConstraintLetter) {
12296       case 'j':
12297         // Constant suitable for movw, must be between 0 and
12298         // 65535.
12299         if (Subtarget->hasV6T2Ops())
12300           if (CVal >= 0 && CVal <= 65535)
12301             break;
12302         return;
12303       case 'I':
12304         if (Subtarget->isThumb1Only()) {
12305           // This must be a constant between 0 and 255, for ADD
12306           // immediates.
12307           if (CVal >= 0 && CVal <= 255)
12308             break;
12309         } else if (Subtarget->isThumb2()) {
12310           // A constant that can be used as an immediate value in a
12311           // data-processing instruction.
12312           if (ARM_AM::getT2SOImmVal(CVal) != -1)
12313             break;
12314         } else {
12315           // A constant that can be used as an immediate value in a
12316           // data-processing instruction.
12317           if (ARM_AM::getSOImmVal(CVal) != -1)
12318             break;
12319         }
12320         return;
12321 
12322       case 'J':
12323         if (Subtarget->isThumb1Only()) {
12324           // This must be a constant between -255 and -1, for negated ADD
12325           // immediates. This can be used in GCC with an "n" modifier that
12326           // prints the negated value, for use with SUB instructions. It is
12327           // not useful otherwise but is implemented for compatibility.
12328           if (CVal >= -255 && CVal <= -1)
12329             break;
12330         } else {
12331           // This must be a constant between -4095 and 4095. It is not clear
12332           // what this constraint is intended for. Implemented for
12333           // compatibility with GCC.
12334           if (CVal >= -4095 && CVal <= 4095)
12335             break;
12336         }
12337         return;
12338 
12339       case 'K':
12340         if (Subtarget->isThumb1Only()) {
12341           // A 32-bit value where only one byte has a nonzero value. Exclude
12342           // zero to match GCC. This constraint is used by GCC internally for
12343           // constants that can be loaded with a move/shift combination.
12344           // It is not useful otherwise but is implemented for compatibility.
12345           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
12346             break;
12347         } else if (Subtarget->isThumb2()) {
12348           // A constant whose bitwise inverse can be used as an immediate
12349           // value in a data-processing instruction. This can be used in GCC
12350           // with a "B" modifier that prints the inverted value, for use with
12351           // BIC and MVN instructions. It is not useful otherwise but is
12352           // implemented for compatibility.
12353           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
12354             break;
12355         } else {
12356           // A constant whose bitwise inverse can be used as an immediate
12357           // value in a data-processing instruction. This can be used in GCC
12358           // with a "B" modifier that prints the inverted value, for use with
12359           // BIC and MVN instructions. It is not useful otherwise but is
12360           // implemented for compatibility.
12361           if (ARM_AM::getSOImmVal(~CVal) != -1)
12362             break;
12363         }
12364         return;
12365 
12366       case 'L':
12367         if (Subtarget->isThumb1Only()) {
12368           // This must be a constant between -7 and 7,
12369           // for 3-operand ADD/SUB immediate instructions.
12370           if (CVal >= -7 && CVal < 7)
12371             break;
12372         } else if (Subtarget->isThumb2()) {
12373           // A constant whose negation can be used as an immediate value in a
12374           // data-processing instruction. This can be used in GCC with an "n"
12375           // modifier that prints the negated value, for use with SUB
12376           // instructions. It is not useful otherwise but is implemented for
12377           // compatibility.
12378           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
12379             break;
12380         } else {
12381           // A constant whose negation can be used as an immediate value in a
12382           // data-processing instruction. This can be used in GCC with an "n"
12383           // modifier that prints the negated value, for use with SUB
12384           // instructions. It is not useful otherwise but is implemented for
12385           // compatibility.
12386           if (ARM_AM::getSOImmVal(-CVal) != -1)
12387             break;
12388         }
12389         return;
12390 
12391       case 'M':
12392         if (Subtarget->isThumb1Only()) {
12393           // This must be a multiple of 4 between 0 and 1020, for
12394           // ADD sp + immediate.
12395           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
12396             break;
12397         } else {
12398           // A power of two or a constant between 0 and 32.  This is used in
12399           // GCC for the shift amount on shifted register operands, but it is
12400           // useful in general for any shift amounts.
12401           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
12402             break;
12403         }
12404         return;
12405 
12406       case 'N':
12407         if (Subtarget->isThumb()) {  // FIXME thumb2
12408           // This must be a constant between 0 and 31, for shift amounts.
12409           if (CVal >= 0 && CVal <= 31)
12410             break;
12411         }
12412         return;
12413 
12414       case 'O':
12415         if (Subtarget->isThumb()) {  // FIXME thumb2
12416           // This must be a multiple of 4 between -508 and 508, for
12417           // ADD/SUB sp = sp + immediate.
12418           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
12419             break;
12420         }
12421         return;
12422     }
12423     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
12424     break;
12425   }
12426 
12427   if (Result.getNode()) {
12428     Ops.push_back(Result);
12429     return;
12430   }
12431   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12432 }
12433 
12434 static RTLIB::Libcall getDivRemLibcall(
12435     const SDNode *N, MVT::SimpleValueType SVT) {
12436   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12437           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
12438          "Unhandled Opcode in getDivRemLibcall");
12439   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12440                   N->getOpcode() == ISD::SREM;
12441   RTLIB::Libcall LC;
12442   switch (SVT) {
12443   default: llvm_unreachable("Unexpected request for libcall!");
12444   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
12445   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
12446   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
12447   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
12448   }
12449   return LC;
12450 }
12451 
12452 static TargetLowering::ArgListTy getDivRemArgList(
12453     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
12454   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12455           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
12456          "Unhandled Opcode in getDivRemArgList");
12457   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
12458                   N->getOpcode() == ISD::SREM;
12459   TargetLowering::ArgListTy Args;
12460   TargetLowering::ArgListEntry Entry;
12461   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12462     EVT ArgVT = N->getOperand(i).getValueType();
12463     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
12464     Entry.Node = N->getOperand(i);
12465     Entry.Ty = ArgTy;
12466     Entry.isSExt = isSigned;
12467     Entry.isZExt = !isSigned;
12468     Args.push_back(Entry);
12469   }
12470   if (Subtarget->isTargetWindows() && Args.size() >= 2)
12471     std::swap(Args[0], Args[1]);
12472   return Args;
12473 }
12474 
12475 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
12476   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
12477           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
12478           Subtarget->isTargetWindows()) &&
12479          "Register-based DivRem lowering only");
12480   unsigned Opcode = Op->getOpcode();
12481   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
12482          "Invalid opcode for Div/Rem lowering");
12483   bool isSigned = (Opcode == ISD::SDIVREM);
12484   EVT VT = Op->getValueType(0);
12485   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
12486   SDLoc dl(Op);
12487 
12488   // If the target has hardware divide, use divide + multiply + subtract:
12489   //     div = a / b
12490   //     rem = a - b * div
12491   //     return {div, rem}
12492   // This should be lowered into UDIV/SDIV + MLS later on.
12493   if (Subtarget->hasDivide() && Op->getValueType(0).isSimple() &&
12494       Op->getSimpleValueType(0) == MVT::i32) {
12495     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
12496     const SDValue Dividend = Op->getOperand(0);
12497     const SDValue Divisor = Op->getOperand(1);
12498     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
12499     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
12500     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
12501 
12502     SDValue Values[2] = {Div, Rem};
12503     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
12504   }
12505 
12506   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
12507                                        VT.getSimpleVT().SimpleTy);
12508   SDValue InChain = DAG.getEntryNode();
12509 
12510   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
12511                                                     DAG.getContext(),
12512                                                     Subtarget);
12513 
12514   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12515                                          getPointerTy(DAG.getDataLayout()));
12516 
12517   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
12518 
12519   if (Subtarget->isTargetWindows())
12520     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
12521 
12522   TargetLowering::CallLoweringInfo CLI(DAG);
12523   CLI.setDebugLoc(dl).setChain(InChain)
12524     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
12525     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
12526 
12527   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
12528   return CallInfo.first;
12529 }
12530 
12531 // Lowers REM using divmod helpers
12532 // see RTABI section 4.2/4.3
12533 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
12534   // Build return types (div and rem)
12535   std::vector<Type*> RetTyParams;
12536   Type *RetTyElement;
12537 
12538   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
12539   default: llvm_unreachable("Unexpected request for libcall!");
12540   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
12541   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
12542   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
12543   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
12544   }
12545 
12546   RetTyParams.push_back(RetTyElement);
12547   RetTyParams.push_back(RetTyElement);
12548   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
12549   Type *RetTy = StructType::get(*DAG.getContext(), ret);
12550 
12551   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
12552                                                              SimpleTy);
12553   SDValue InChain = DAG.getEntryNode();
12554   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
12555                                                     Subtarget);
12556   bool isSigned = N->getOpcode() == ISD::SREM;
12557   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
12558                                          getPointerTy(DAG.getDataLayout()));
12559 
12560   if (Subtarget->isTargetWindows())
12561     InChain = WinDBZCheckDenominator(DAG, N, InChain);
12562 
12563   // Lower call
12564   CallLoweringInfo CLI(DAG);
12565   CLI.setChain(InChain)
12566      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
12567      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
12568   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
12569 
12570   // Return second (rem) result operand (first contains div)
12571   SDNode *ResNode = CallResult.first.getNode();
12572   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
12573   return ResNode->getOperand(1);
12574 }
12575 
12576 SDValue
12577 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
12578   assert(Subtarget->isTargetWindows() && "unsupported target platform");
12579   SDLoc DL(Op);
12580 
12581   // Get the inputs.
12582   SDValue Chain = Op.getOperand(0);
12583   SDValue Size  = Op.getOperand(1);
12584 
12585   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
12586                               DAG.getConstant(2, DL, MVT::i32));
12587 
12588   SDValue Flag;
12589   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
12590   Flag = Chain.getValue(1);
12591 
12592   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12593   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
12594 
12595   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
12596   Chain = NewSP.getValue(1);
12597 
12598   SDValue Ops[2] = { NewSP, Chain };
12599   return DAG.getMergeValues(Ops, DL);
12600 }
12601 
12602 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
12603   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
12604          "Unexpected type for custom-lowering FP_EXTEND");
12605 
12606   RTLIB::Libcall LC;
12607   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
12608 
12609   SDValue SrcVal = Op.getOperand(0);
12610   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
12611                      SDLoc(Op)).first;
12612 }
12613 
12614 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
12615   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
12616          Subtarget->isFPOnlySP() &&
12617          "Unexpected type for custom-lowering FP_ROUND");
12618 
12619   RTLIB::Libcall LC;
12620   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
12621 
12622   SDValue SrcVal = Op.getOperand(0);
12623   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
12624                      SDLoc(Op)).first;
12625 }
12626 
12627 bool
12628 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12629   // The ARM target isn't yet aware of offsets.
12630   return false;
12631 }
12632 
12633 bool ARM::isBitFieldInvertedMask(unsigned v) {
12634   if (v == 0xffffffff)
12635     return false;
12636 
12637   // there can be 1's on either or both "outsides", all the "inside"
12638   // bits must be 0's
12639   return isShiftedMask_32(~v);
12640 }
12641 
12642 /// isFPImmLegal - Returns true if the target can instruction select the
12643 /// specified FP immediate natively. If false, the legalizer will
12644 /// materialize the FP immediate as a load from a constant pool.
12645 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12646   if (!Subtarget->hasVFP3())
12647     return false;
12648   if (VT == MVT::f32)
12649     return ARM_AM::getFP32Imm(Imm) != -1;
12650   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
12651     return ARM_AM::getFP64Imm(Imm) != -1;
12652   return false;
12653 }
12654 
12655 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
12656 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
12657 /// specified in the intrinsic calls.
12658 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12659                                            const CallInst &I,
12660                                            unsigned Intrinsic) const {
12661   switch (Intrinsic) {
12662   case Intrinsic::arm_neon_vld1:
12663   case Intrinsic::arm_neon_vld2:
12664   case Intrinsic::arm_neon_vld3:
12665   case Intrinsic::arm_neon_vld4:
12666   case Intrinsic::arm_neon_vld2lane:
12667   case Intrinsic::arm_neon_vld3lane:
12668   case Intrinsic::arm_neon_vld4lane: {
12669     Info.opc = ISD::INTRINSIC_W_CHAIN;
12670     // Conservatively set memVT to the entire set of vectors loaded.
12671     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12672     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
12673     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
12674     Info.ptrVal = I.getArgOperand(0);
12675     Info.offset = 0;
12676     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
12677     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
12678     Info.vol = false; // volatile loads with NEON intrinsics not supported
12679     Info.readMem = true;
12680     Info.writeMem = false;
12681     return true;
12682   }
12683   case Intrinsic::arm_neon_vst1:
12684   case Intrinsic::arm_neon_vst2:
12685   case Intrinsic::arm_neon_vst3:
12686   case Intrinsic::arm_neon_vst4:
12687   case Intrinsic::arm_neon_vst2lane:
12688   case Intrinsic::arm_neon_vst3lane:
12689   case Intrinsic::arm_neon_vst4lane: {
12690     Info.opc = ISD::INTRINSIC_VOID;
12691     // Conservatively set memVT to the entire set of vectors stored.
12692     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12693     unsigned NumElts = 0;
12694     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
12695       Type *ArgTy = I.getArgOperand(ArgI)->getType();
12696       if (!ArgTy->isVectorTy())
12697         break;
12698       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
12699     }
12700     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
12701     Info.ptrVal = I.getArgOperand(0);
12702     Info.offset = 0;
12703     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
12704     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
12705     Info.vol = false; // volatile stores with NEON intrinsics not supported
12706     Info.readMem = false;
12707     Info.writeMem = true;
12708     return true;
12709   }
12710   case Intrinsic::arm_ldaex:
12711   case Intrinsic::arm_ldrex: {
12712     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12713     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
12714     Info.opc = ISD::INTRINSIC_W_CHAIN;
12715     Info.memVT = MVT::getVT(PtrTy->getElementType());
12716     Info.ptrVal = I.getArgOperand(0);
12717     Info.offset = 0;
12718     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
12719     Info.vol = true;
12720     Info.readMem = true;
12721     Info.writeMem = false;
12722     return true;
12723   }
12724   case Intrinsic::arm_stlex:
12725   case Intrinsic::arm_strex: {
12726     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
12727     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
12728     Info.opc = ISD::INTRINSIC_W_CHAIN;
12729     Info.memVT = MVT::getVT(PtrTy->getElementType());
12730     Info.ptrVal = I.getArgOperand(1);
12731     Info.offset = 0;
12732     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
12733     Info.vol = true;
12734     Info.readMem = false;
12735     Info.writeMem = true;
12736     return true;
12737   }
12738   case Intrinsic::arm_stlexd:
12739   case Intrinsic::arm_strexd: {
12740     Info.opc = ISD::INTRINSIC_W_CHAIN;
12741     Info.memVT = MVT::i64;
12742     Info.ptrVal = I.getArgOperand(2);
12743     Info.offset = 0;
12744     Info.align = 8;
12745     Info.vol = true;
12746     Info.readMem = false;
12747     Info.writeMem = true;
12748     return true;
12749   }
12750   case Intrinsic::arm_ldaexd:
12751   case Intrinsic::arm_ldrexd: {
12752     Info.opc = ISD::INTRINSIC_W_CHAIN;
12753     Info.memVT = MVT::i64;
12754     Info.ptrVal = I.getArgOperand(0);
12755     Info.offset = 0;
12756     Info.align = 8;
12757     Info.vol = true;
12758     Info.readMem = true;
12759     Info.writeMem = false;
12760     return true;
12761   }
12762   default:
12763     break;
12764   }
12765 
12766   return false;
12767 }
12768 
12769 /// \brief Returns true if it is beneficial to convert a load of a constant
12770 /// to just the constant itself.
12771 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12772                                                           Type *Ty) const {
12773   assert(Ty->isIntegerTy());
12774 
12775   unsigned Bits = Ty->getPrimitiveSizeInBits();
12776   if (Bits == 0 || Bits > 32)
12777     return false;
12778   return true;
12779 }
12780 
12781 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
12782                                         ARM_MB::MemBOpt Domain) const {
12783   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12784 
12785   // First, if the target has no DMB, see what fallback we can use.
12786   if (!Subtarget->hasDataBarrier()) {
12787     // Some ARMv6 cpus can support data barriers with an mcr instruction.
12788     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
12789     // here.
12790     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
12791       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
12792       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
12793                         Builder.getInt32(0), Builder.getInt32(7),
12794                         Builder.getInt32(10), Builder.getInt32(5)};
12795       return Builder.CreateCall(MCR, args);
12796     } else {
12797       // Instead of using barriers, atomic accesses on these subtargets use
12798       // libcalls.
12799       llvm_unreachable("makeDMB on a target so old that it has no barriers");
12800     }
12801   } else {
12802     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
12803     // Only a full system barrier exists in the M-class architectures.
12804     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
12805     Constant *CDomain = Builder.getInt32(Domain);
12806     return Builder.CreateCall(DMB, CDomain);
12807   }
12808 }
12809 
12810 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
12811 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
12812                                          AtomicOrdering Ord, bool IsStore,
12813                                          bool IsLoad) const {
12814   switch (Ord) {
12815   case AtomicOrdering::NotAtomic:
12816   case AtomicOrdering::Unordered:
12817     llvm_unreachable("Invalid fence: unordered/non-atomic");
12818   case AtomicOrdering::Monotonic:
12819   case AtomicOrdering::Acquire:
12820     return nullptr; // Nothing to do
12821   case AtomicOrdering::SequentiallyConsistent:
12822     if (!IsStore)
12823       return nullptr; // Nothing to do
12824     /*FALLTHROUGH*/
12825   case AtomicOrdering::Release:
12826   case AtomicOrdering::AcquireRelease:
12827     if (Subtarget->preferISHSTBarriers())
12828       return makeDMB(Builder, ARM_MB::ISHST);
12829     // FIXME: add a comment with a link to documentation justifying this.
12830     else
12831       return makeDMB(Builder, ARM_MB::ISH);
12832   }
12833   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
12834 }
12835 
12836 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
12837                                           AtomicOrdering Ord, bool IsStore,
12838                                           bool IsLoad) const {
12839   switch (Ord) {
12840   case AtomicOrdering::NotAtomic:
12841   case AtomicOrdering::Unordered:
12842     llvm_unreachable("Invalid fence: unordered/not-atomic");
12843   case AtomicOrdering::Monotonic:
12844   case AtomicOrdering::Release:
12845     return nullptr; // Nothing to do
12846   case AtomicOrdering::Acquire:
12847   case AtomicOrdering::AcquireRelease:
12848   case AtomicOrdering::SequentiallyConsistent:
12849     return makeDMB(Builder, ARM_MB::ISH);
12850   }
12851   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
12852 }
12853 
12854 // Loads and stores less than 64-bits are already atomic; ones above that
12855 // are doomed anyway, so defer to the default libcall and blame the OS when
12856 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12857 // anything for those.
12858 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
12859   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
12860   return (Size == 64) && !Subtarget->isMClass();
12861 }
12862 
12863 // Loads and stores less than 64-bits are already atomic; ones above that
12864 // are doomed anyway, so defer to the default libcall and blame the OS when
12865 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
12866 // anything for those.
12867 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
12868 // guarantee, see DDI0406C ARM architecture reference manual,
12869 // sections A8.8.72-74 LDRD)
12870 TargetLowering::AtomicExpansionKind
12871 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
12872   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
12873   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
12874                                                   : AtomicExpansionKind::None;
12875 }
12876 
12877 // For the real atomic operations, we have ldrex/strex up to 32 bits,
12878 // and up to 64 bits on the non-M profiles
12879 TargetLowering::AtomicExpansionKind
12880 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
12881   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
12882   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
12883              ? AtomicExpansionKind::LLSC
12884              : AtomicExpansionKind::None;
12885 }
12886 
12887 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
12888     AtomicCmpXchgInst *AI) const {
12889   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
12890   // implement cmpxchg without spilling. If the address being exchanged is also
12891   // on the stack and close enough to the spill slot, this can lead to a
12892   // situation where the monitor always gets cleared and the atomic operation
12893   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
12894   return getTargetMachine().getOptLevel() != 0;
12895 }
12896 
12897 bool ARMTargetLowering::shouldInsertFencesForAtomic(
12898     const Instruction *I) const {
12899   return InsertFencesForAtomic;
12900 }
12901 
12902 // This has so far only been implemented for MachO.
12903 bool ARMTargetLowering::useLoadStackGuardNode() const {
12904   return Subtarget->isTargetMachO();
12905 }
12906 
12907 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
12908                                                   unsigned &Cost) const {
12909   // If we do not have NEON, vector types are not natively supported.
12910   if (!Subtarget->hasNEON())
12911     return false;
12912 
12913   // Floating point values and vector values map to the same register file.
12914   // Therefore, although we could do a store extract of a vector type, this is
12915   // better to leave at float as we have more freedom in the addressing mode for
12916   // those.
12917   if (VectorTy->isFPOrFPVectorTy())
12918     return false;
12919 
12920   // If the index is unknown at compile time, this is very expensive to lower
12921   // and it is not possible to combine the store with the extract.
12922   if (!isa<ConstantInt>(Idx))
12923     return false;
12924 
12925   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
12926   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
12927   // We can do a store + vector extract on any vector that fits perfectly in a D
12928   // or Q register.
12929   if (BitWidth == 64 || BitWidth == 128) {
12930     Cost = 0;
12931     return true;
12932   }
12933   return false;
12934 }
12935 
12936 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
12937   return Subtarget->hasV6T2Ops();
12938 }
12939 
12940 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
12941   return Subtarget->hasV6T2Ops();
12942 }
12943 
12944 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
12945                                          AtomicOrdering Ord) const {
12946   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12947   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
12948   bool IsAcquire = isAcquireOrStronger(Ord);
12949 
12950   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
12951   // intrinsic must return {i32, i32} and we have to recombine them into a
12952   // single i64 here.
12953   if (ValTy->getPrimitiveSizeInBits() == 64) {
12954     Intrinsic::ID Int =
12955         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
12956     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
12957 
12958     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
12959     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
12960 
12961     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
12962     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
12963     if (!Subtarget->isLittle())
12964       std::swap (Lo, Hi);
12965     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
12966     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
12967     return Builder.CreateOr(
12968         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
12969   }
12970 
12971   Type *Tys[] = { Addr->getType() };
12972   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
12973   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
12974 
12975   return Builder.CreateTruncOrBitCast(
12976       Builder.CreateCall(Ldrex, Addr),
12977       cast<PointerType>(Addr->getType())->getElementType());
12978 }
12979 
12980 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
12981     IRBuilder<> &Builder) const {
12982   if (!Subtarget->hasV7Ops())
12983     return;
12984   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12985   Builder.CreateCall(llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
12986 }
12987 
12988 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
12989                                                Value *Addr,
12990                                                AtomicOrdering Ord) const {
12991   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
12992   bool IsRelease = isReleaseOrStronger(Ord);
12993 
12994   // Since the intrinsics must have legal type, the i64 intrinsics take two
12995   // parameters: "i32, i32". We must marshal Val into the appropriate form
12996   // before the call.
12997   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
12998     Intrinsic::ID Int =
12999         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
13000     Function *Strex = Intrinsic::getDeclaration(M, Int);
13001     Type *Int32Ty = Type::getInt32Ty(M->getContext());
13002 
13003     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
13004     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
13005     if (!Subtarget->isLittle())
13006       std::swap (Lo, Hi);
13007     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13008     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
13009   }
13010 
13011   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
13012   Type *Tys[] = { Addr->getType() };
13013   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
13014 
13015   return Builder.CreateCall(
13016       Strex, {Builder.CreateZExtOrBitCast(
13017                   Val, Strex->getFunctionType()->getParamType(0)),
13018               Addr});
13019 }
13020 
13021 /// \brief Lower an interleaved load into a vldN intrinsic.
13022 ///
13023 /// E.g. Lower an interleaved load (Factor = 2):
13024 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
13025 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
13026 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
13027 ///
13028 ///      Into:
13029 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
13030 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
13031 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
13032 bool ARMTargetLowering::lowerInterleavedLoad(
13033     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
13034     ArrayRef<unsigned> Indices, unsigned Factor) const {
13035   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13036          "Invalid interleave factor");
13037   assert(!Shuffles.empty() && "Empty shufflevector input");
13038   assert(Shuffles.size() == Indices.size() &&
13039          "Unmatched number of shufflevectors and indices");
13040 
13041   VectorType *VecTy = Shuffles[0]->getType();
13042   Type *EltTy = VecTy->getVectorElementType();
13043 
13044   const DataLayout &DL = LI->getModule()->getDataLayout();
13045   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
13046   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
13047 
13048   // Skip if we do not have NEON and skip illegal vector types and vector types
13049   // with i64/f64 elements (vldN doesn't support i64/f64 elements).
13050   if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128) || EltIs64Bits)
13051     return false;
13052 
13053   // A pointer vector can not be the return type of the ldN intrinsics. Need to
13054   // load integer vectors first and then convert to pointer vectors.
13055   if (EltTy->isPointerTy())
13056     VecTy =
13057         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
13058 
13059   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
13060                                             Intrinsic::arm_neon_vld3,
13061                                             Intrinsic::arm_neon_vld4};
13062 
13063   IRBuilder<> Builder(LI);
13064   SmallVector<Value *, 2> Ops;
13065 
13066   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
13067   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
13068   Ops.push_back(Builder.getInt32(LI->getAlignment()));
13069 
13070   Type *Tys[] = { VecTy, Int8Ptr };
13071   Function *VldnFunc =
13072       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
13073   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
13074 
13075   // Replace uses of each shufflevector with the corresponding vector loaded
13076   // by ldN.
13077   for (unsigned i = 0; i < Shuffles.size(); i++) {
13078     ShuffleVectorInst *SV = Shuffles[i];
13079     unsigned Index = Indices[i];
13080 
13081     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
13082 
13083     // Convert the integer vector to pointer vector if the element is pointer.
13084     if (EltTy->isPointerTy())
13085       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
13086 
13087     SV->replaceAllUsesWith(SubVec);
13088   }
13089 
13090   return true;
13091 }
13092 
13093 /// \brief Get a mask consisting of sequential integers starting from \p Start.
13094 ///
13095 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
13096 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
13097                                    unsigned NumElts) {
13098   SmallVector<Constant *, 16> Mask;
13099   for (unsigned i = 0; i < NumElts; i++)
13100     Mask.push_back(Builder.getInt32(Start + i));
13101 
13102   return ConstantVector::get(Mask);
13103 }
13104 
13105 /// \brief Lower an interleaved store into a vstN intrinsic.
13106 ///
13107 /// E.g. Lower an interleaved store (Factor = 3):
13108 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
13109 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
13110 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
13111 ///
13112 ///      Into:
13113 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
13114 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
13115 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
13116 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13117 ///
13118 /// Note that the new shufflevectors will be removed and we'll only generate one
13119 /// vst3 instruction in CodeGen.
13120 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
13121                                               ShuffleVectorInst *SVI,
13122                                               unsigned Factor) const {
13123   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13124          "Invalid interleave factor");
13125 
13126   VectorType *VecTy = SVI->getType();
13127   assert(VecTy->getVectorNumElements() % Factor == 0 &&
13128          "Invalid interleaved store");
13129 
13130   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
13131   Type *EltTy = VecTy->getVectorElementType();
13132   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
13133 
13134   const DataLayout &DL = SI->getModule()->getDataLayout();
13135   unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
13136   bool EltIs64Bits = DL.getTypeSizeInBits(EltTy) == 64;
13137 
13138   // Skip if we do not have NEON and skip illegal vector types and vector types
13139   // with i64/f64 elements (vstN doesn't support i64/f64 elements).
13140   if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128) ||
13141       EltIs64Bits)
13142     return false;
13143 
13144   Value *Op0 = SVI->getOperand(0);
13145   Value *Op1 = SVI->getOperand(1);
13146   IRBuilder<> Builder(SI);
13147 
13148   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
13149   // vectors to integer vectors.
13150   if (EltTy->isPointerTy()) {
13151     Type *IntTy = DL.getIntPtrType(EltTy);
13152 
13153     // Convert to the corresponding integer vector.
13154     Type *IntVecTy =
13155         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
13156     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
13157     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
13158 
13159     SubVecTy = VectorType::get(IntTy, NumSubElts);
13160   }
13161 
13162   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
13163                                              Intrinsic::arm_neon_vst3,
13164                                              Intrinsic::arm_neon_vst4};
13165   SmallVector<Value *, 6> Ops;
13166 
13167   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
13168   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
13169 
13170   Type *Tys[] = { Int8Ptr, SubVecTy };
13171   Function *VstNFunc = Intrinsic::getDeclaration(
13172       SI->getModule(), StoreInts[Factor - 2], Tys);
13173 
13174   // Split the shufflevector operands into sub vectors for the new vstN call.
13175   for (unsigned i = 0; i < Factor; i++)
13176     Ops.push_back(Builder.CreateShuffleVector(
13177         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
13178 
13179   Ops.push_back(Builder.getInt32(SI->getAlignment()));
13180   Builder.CreateCall(VstNFunc, Ops);
13181   return true;
13182 }
13183 
13184 enum HABaseType {
13185   HA_UNKNOWN = 0,
13186   HA_FLOAT,
13187   HA_DOUBLE,
13188   HA_VECT64,
13189   HA_VECT128
13190 };
13191 
13192 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
13193                                    uint64_t &Members) {
13194   if (auto *ST = dyn_cast<StructType>(Ty)) {
13195     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
13196       uint64_t SubMembers = 0;
13197       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
13198         return false;
13199       Members += SubMembers;
13200     }
13201   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
13202     uint64_t SubMembers = 0;
13203     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
13204       return false;
13205     Members += SubMembers * AT->getNumElements();
13206   } else if (Ty->isFloatTy()) {
13207     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
13208       return false;
13209     Members = 1;
13210     Base = HA_FLOAT;
13211   } else if (Ty->isDoubleTy()) {
13212     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
13213       return false;
13214     Members = 1;
13215     Base = HA_DOUBLE;
13216   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
13217     Members = 1;
13218     switch (Base) {
13219     case HA_FLOAT:
13220     case HA_DOUBLE:
13221       return false;
13222     case HA_VECT64:
13223       return VT->getBitWidth() == 64;
13224     case HA_VECT128:
13225       return VT->getBitWidth() == 128;
13226     case HA_UNKNOWN:
13227       switch (VT->getBitWidth()) {
13228       case 64:
13229         Base = HA_VECT64;
13230         return true;
13231       case 128:
13232         Base = HA_VECT128;
13233         return true;
13234       default:
13235         return false;
13236       }
13237     }
13238   }
13239 
13240   return (Members > 0 && Members <= 4);
13241 }
13242 
13243 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
13244 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
13245 /// passing according to AAPCS rules.
13246 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
13247     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13248   if (getEffectiveCallingConv(CallConv, isVarArg) !=
13249       CallingConv::ARM_AAPCS_VFP)
13250     return false;
13251 
13252   HABaseType Base = HA_UNKNOWN;
13253   uint64_t Members = 0;
13254   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
13255   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
13256 
13257   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
13258   return IsHA || IsIntArray;
13259 }
13260 
13261 unsigned ARMTargetLowering::getExceptionPointerRegister(
13262     const Constant *PersonalityFn) const {
13263   // Platforms which do not use SjLj EH may return values in these registers
13264   // via the personality function.
13265   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
13266 }
13267 
13268 unsigned ARMTargetLowering::getExceptionSelectorRegister(
13269     const Constant *PersonalityFn) const {
13270   // Platforms which do not use SjLj EH may return values in these registers
13271   // via the personality function.
13272   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
13273 }
13274 
13275 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13276   // Update IsSplitCSR in ARMFunctionInfo.
13277   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
13278   AFI->setIsSplitCSR(true);
13279 }
13280 
13281 void ARMTargetLowering::insertCopiesSplitCSR(
13282     MachineBasicBlock *Entry,
13283     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13284   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
13285   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13286   if (!IStart)
13287     return;
13288 
13289   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
13290   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13291   MachineBasicBlock::iterator MBBI = Entry->begin();
13292   for (const MCPhysReg *I = IStart; *I; ++I) {
13293     const TargetRegisterClass *RC = nullptr;
13294     if (ARM::GPRRegClass.contains(*I))
13295       RC = &ARM::GPRRegClass;
13296     else if (ARM::DPRRegClass.contains(*I))
13297       RC = &ARM::DPRRegClass;
13298     else
13299       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13300 
13301     unsigned NewVR = MRI->createVirtualRegister(RC);
13302     // Create copy from CSR to a virtual register.
13303     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13304     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13305     // nounwind. If we want to generalize this later, we may need to emit
13306     // CFI pseudo-instructions.
13307     assert(Entry->getParent()->getFunction()->hasFnAttribute(
13308                Attribute::NoUnwind) &&
13309            "Function should be nounwind in insertCopiesSplitCSR!");
13310     Entry->addLiveIn(*I);
13311     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13312         .addReg(*I);
13313 
13314     // Insert the copy-back instructions right before the terminator.
13315     for (auto *Exit : Exits)
13316       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13317               TII->get(TargetOpcode::COPY), *I)
13318           .addReg(NewVR);
13319   }
13320 }
13321