[ARM] Match fminnum/fmaxnum for vector vminnm/vmaxnm instead of an intrinsic
[oota-llvm.git] / lib / Target / ARM / ARMISelLowering.cpp
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/GlobalValue.h"
41 #include "llvm/IR/IRBuilder.h"
42 #include "llvm/IR/Instruction.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/IntrinsicInst.h"
45 #include "llvm/IR/Intrinsics.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/MC/MCSectionMachO.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include <utility>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "arm-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
61 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
62
63 static cl::opt<bool>
64 ARMInterworking("arm-interworking", cl::Hidden,
65   cl::desc("Enable / disable ARM interworking (for debugging only)"),
66   cl::init(true));
67
68 namespace {
69   class ARMCCState : public CCState {
70   public:
71     ARMCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
72                SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
73                ParmContext PC)
74         : CCState(CC, isVarArg, MF, locs, C) {
75       assert(((PC == Call) || (PC == Prologue)) &&
76              "ARMCCState users must specify whether their context is call"
77              "or prologue generation.");
78       CallOrPrologue = PC;
79     }
80   };
81 }
82
83 // The APCS parameter registers.
84 static const MCPhysReg GPRArgRegs[] = {
85   ARM::R0, ARM::R1, ARM::R2, ARM::R3
86 };
87
88 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
89                                        MVT PromotedBitwiseVT) {
90   if (VT != PromotedLdStVT) {
91     setOperationAction(ISD::LOAD, VT, Promote);
92     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
93
94     setOperationAction(ISD::STORE, VT, Promote);
95     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
96   }
97
98   MVT ElemTy = VT.getVectorElementType();
99   if (ElemTy != MVT::i64 && ElemTy != MVT::f64)
100     setOperationAction(ISD::SETCC, VT, Custom);
101   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
102   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
103   if (ElemTy == MVT::i32) {
104     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
105     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
106     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
107     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
108   } else {
109     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
110     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
111     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
112     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
113   }
114   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
115   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
116   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
117   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
118   setOperationAction(ISD::SELECT,            VT, Expand);
119   setOperationAction(ISD::SELECT_CC,         VT, Expand);
120   setOperationAction(ISD::VSELECT,           VT, Expand);
121   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
122   if (VT.isInteger()) {
123     setOperationAction(ISD::SHL, VT, Custom);
124     setOperationAction(ISD::SRA, VT, Custom);
125     setOperationAction(ISD::SRL, VT, Custom);
126   }
127
128   // Promote all bit-wise operations.
129   if (VT.isInteger() && VT != PromotedBitwiseVT) {
130     setOperationAction(ISD::AND, VT, Promote);
131     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
132     setOperationAction(ISD::OR,  VT, Promote);
133     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
134     setOperationAction(ISD::XOR, VT, Promote);
135     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
136   }
137
138   // Neon does not support vector divide/remainder operations.
139   setOperationAction(ISD::SDIV, VT, Expand);
140   setOperationAction(ISD::UDIV, VT, Expand);
141   setOperationAction(ISD::FDIV, VT, Expand);
142   setOperationAction(ISD::SREM, VT, Expand);
143   setOperationAction(ISD::UREM, VT, Expand);
144   setOperationAction(ISD::FREM, VT, Expand);
145
146   if (VT.isInteger()) {
147     setOperationAction(ISD::SABSDIFF, VT, Legal);
148     setOperationAction(ISD::UABSDIFF, VT, Legal);
149   }
150 }
151
152 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
153   addRegisterClass(VT, &ARM::DPRRegClass);
154   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
155 }
156
157 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
158   addRegisterClass(VT, &ARM::DPairRegClass);
159   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
160 }
161
162 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
163                                      const ARMSubtarget &STI)
164     : TargetLowering(TM), Subtarget(&STI) {
165   RegInfo = Subtarget->getRegisterInfo();
166   Itins = Subtarget->getInstrItineraryData();
167
168   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
169
170   if (Subtarget->isTargetMachO()) {
171     // Uses VFP for Thumb libfuncs if available.
172     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
173         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
174       static const struct {
175         const RTLIB::Libcall Op;
176         const char * const Name;
177         const ISD::CondCode Cond;
178       } LibraryCalls[] = {
179         // Single-precision floating-point arithmetic.
180         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
181         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
182         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
183         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
184
185         // Double-precision floating-point arithmetic.
186         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
187         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
188         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
189         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
190
191         // Single-precision comparisons.
192         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
193         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
194         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
195         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
196         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
197         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
198         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
199         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
200
201         // Double-precision comparisons.
202         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
203         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
204         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
205         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
206         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
207         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
208         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
209         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
210
211         // Floating-point to integer conversions.
212         // i64 conversions are done via library routines even when generating VFP
213         // instructions, so use the same ones.
214         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
215         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
216         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
217         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
218
219         // Conversions between floating types.
220         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
221         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
222
223         // Integer to floating-point conversions.
224         // i64 conversions are done via library routines even when generating VFP
225         // instructions, so use the same ones.
226         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
227         // e.g., __floatunsidf vs. __floatunssidfvfp.
228         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
229         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
230         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
231         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
232       };
233
234       for (const auto &LC : LibraryCalls) {
235         setLibcallName(LC.Op, LC.Name);
236         if (LC.Cond != ISD::SETCC_INVALID)
237           setCmpLibcallCC(LC.Op, LC.Cond);
238       }
239     }
240   }
241
242   // These libcalls are not available in 32-bit.
243   setLibcallName(RTLIB::SHL_I128, nullptr);
244   setLibcallName(RTLIB::SRL_I128, nullptr);
245   setLibcallName(RTLIB::SRA_I128, nullptr);
246
247   if (Subtarget->isAAPCS_ABI() && !Subtarget->isTargetMachO() &&
248       !Subtarget->isTargetWindows()) {
249     static const struct {
250       const RTLIB::Libcall Op;
251       const char * const Name;
252       const CallingConv::ID CC;
253       const ISD::CondCode Cond;
254     } LibraryCalls[] = {
255       // Double-precision floating-point arithmetic helper functions
256       // RTABI chapter 4.1.2, Table 2
257       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
258       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
259       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
260       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
261
262       // Double-precision floating-point comparison helper functions
263       // RTABI chapter 4.1.2, Table 3
264       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
265       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
266       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
267       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
268       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
269       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
270       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
271       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
272
273       // Single-precision floating-point arithmetic helper functions
274       // RTABI chapter 4.1.2, Table 4
275       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
276       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
277       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
278       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
279
280       // Single-precision floating-point comparison helper functions
281       // RTABI chapter 4.1.2, Table 5
282       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
283       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
284       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
285       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
286       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
287       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
288       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
289       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
290
291       // Floating-point to integer conversions.
292       // RTABI chapter 4.1.2, Table 6
293       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
294       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
295       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
296       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
297       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
298       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
299       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
300       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
301
302       // Conversions between floating types.
303       // RTABI chapter 4.1.2, Table 7
304       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
305       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
306       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
307
308       // Integer to floating-point conversions.
309       // RTABI chapter 4.1.2, Table 8
310       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
311       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
312       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
313       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
314       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
315       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
316       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
317       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
318
319       // Long long helper functions
320       // RTABI chapter 4.2, Table 9
321       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
322       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
323       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
324       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
325
326       // Integer division functions
327       // RTABI chapter 4.3.1
328       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
329       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
330       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
335       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
336
337       // Memory operations
338       // RTABI chapter 4.3.4
339       { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341       { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
342     };
343
344     for (const auto &LC : LibraryCalls) {
345       setLibcallName(LC.Op, LC.Name);
346       setLibcallCallingConv(LC.Op, LC.CC);
347       if (LC.Cond != ISD::SETCC_INVALID)
348         setCmpLibcallCC(LC.Op, LC.Cond);
349     }
350   }
351
352   if (Subtarget->isTargetWindows()) {
353     static const struct {
354       const RTLIB::Libcall Op;
355       const char * const Name;
356       const CallingConv::ID CC;
357     } LibraryCalls[] = {
358       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
359       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
360       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
361       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
362       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
363       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
364       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
365       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
366
367       { RTLIB::SDIV_I32, "__rt_sdiv",   CallingConv::ARM_AAPCS_VFP },
368       { RTLIB::UDIV_I32, "__rt_udiv",   CallingConv::ARM_AAPCS_VFP },
369       { RTLIB::SDIV_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS_VFP },
370       { RTLIB::UDIV_I64, "__rt_udiv64", CallingConv::ARM_AAPCS_VFP },
371     };
372
373     for (const auto &LC : LibraryCalls) {
374       setLibcallName(LC.Op, LC.Name);
375       setLibcallCallingConv(LC.Op, LC.CC);
376     }
377   }
378
379   // Use divmod compiler-rt calls for iOS 5.0 and later.
380   if (Subtarget->getTargetTriple().isiOS() &&
381       !Subtarget->getTargetTriple().isOSVersionLT(5, 0)) {
382     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
383     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
384   }
385
386   // The half <-> float conversion functions are always soft-float, but are
387   // needed for some targets which use a hard-float calling convention by
388   // default.
389   if (Subtarget->isAAPCS_ABI()) {
390     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
391     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
392     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
393   } else {
394     setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
395     setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
396     setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
397   }
398
399   if (Subtarget->isThumb1Only())
400     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
401   else
402     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
403   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
404       !Subtarget->isThumb1Only()) {
405     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
406     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
407   }
408
409   for (MVT VT : MVT::vector_valuetypes()) {
410     for (MVT InnerVT : MVT::vector_valuetypes()) {
411       setTruncStoreAction(VT, InnerVT, Expand);
412       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
413       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
414       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
415     }
416
417     setOperationAction(ISD::MULHS, VT, Expand);
418     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
419     setOperationAction(ISD::MULHU, VT, Expand);
420     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
421
422     setOperationAction(ISD::BSWAP, VT, Expand);
423   }
424
425   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
426   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
427
428   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
429   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
430
431   if (Subtarget->hasNEON()) {
432     addDRTypeForNEON(MVT::v2f32);
433     addDRTypeForNEON(MVT::v8i8);
434     addDRTypeForNEON(MVT::v4i16);
435     addDRTypeForNEON(MVT::v2i32);
436     addDRTypeForNEON(MVT::v1i64);
437
438     addQRTypeForNEON(MVT::v4f32);
439     addQRTypeForNEON(MVT::v2f64);
440     addQRTypeForNEON(MVT::v16i8);
441     addQRTypeForNEON(MVT::v8i16);
442     addQRTypeForNEON(MVT::v4i32);
443     addQRTypeForNEON(MVT::v2i64);
444
445     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
446     // neither Neon nor VFP support any arithmetic operations on it.
447     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
448     // supported for v4f32.
449     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
450     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
451     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
452     // FIXME: Code duplication: FDIV and FREM are expanded always, see
453     // ARMTargetLowering::addTypeForNEON method for details.
454     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
455     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
456     // FIXME: Create unittest.
457     // In another words, find a way when "copysign" appears in DAG with vector
458     // operands.
459     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
460     // FIXME: Code duplication: SETCC has custom operation action, see
461     // ARMTargetLowering::addTypeForNEON method for details.
462     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
463     // FIXME: Create unittest for FNEG and for FABS.
464     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
465     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
466     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
467     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
468     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
469     setOperationAction(ISD::FPOWI, MVT::v2f64, Expand);
470     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
471     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
472     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
473     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
474     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
475     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
476     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
477     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
478     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
479     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
480     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
481     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
482     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
483
484     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
485     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
486     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
487     setOperationAction(ISD::FPOWI, MVT::v4f32, Expand);
488     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
489     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
490     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
491     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
492     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
493     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
494     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
495     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
496     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
497     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
498     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
499
500     // Mark v2f32 intrinsics.
501     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
502     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
503     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
504     setOperationAction(ISD::FPOWI, MVT::v2f32, Expand);
505     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
506     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
507     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
508     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
509     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
510     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
511     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
512     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
513     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
514     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
515     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
516
517     // Neon does not support some operations on v1i64 and v2i64 types.
518     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
519     // Custom handling for some quad-vector types to detect VMULL.
520     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
521     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
522     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
523     // Custom handling for some vector types to avoid expensive expansions
524     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
525     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
526     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
527     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
528     setOperationAction(ISD::SETCC, MVT::v1i64, Expand);
529     setOperationAction(ISD::SETCC, MVT::v2i64, Expand);
530     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
531     // a destination type that is wider than the source, and nor does
532     // it have a FP_TO_[SU]INT instruction with a narrower destination than
533     // source.
534     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
535     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
536     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
537     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
538
539     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
540     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
541
542     // NEON does not have single instruction CTPOP for vectors with element
543     // types wider than 8-bits.  However, custom lowering can leverage the
544     // v8i8/v16i8 vcnt instruction.
545     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
546     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
547     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
548     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
549
550     // NEON does not have single instruction CTTZ for vectors.
551     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
552     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
553     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
554     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
555
556     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
557     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
558     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
559     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
560
561     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
563     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
564     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
565
566     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
567     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
568     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
569     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
570
571     // NEON only has FMA instructions as of VFP4.
572     if (!Subtarget->hasVFP4()) {
573       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
574       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
575     }
576
577     setTargetDAGCombine(ISD::INTRINSIC_VOID);
578     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
579     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
580     setTargetDAGCombine(ISD::SHL);
581     setTargetDAGCombine(ISD::SRL);
582     setTargetDAGCombine(ISD::SRA);
583     setTargetDAGCombine(ISD::SIGN_EXTEND);
584     setTargetDAGCombine(ISD::ZERO_EXTEND);
585     setTargetDAGCombine(ISD::ANY_EXTEND);
586     setTargetDAGCombine(ISD::SELECT_CC);
587     setTargetDAGCombine(ISD::BUILD_VECTOR);
588     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
589     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
590     setTargetDAGCombine(ISD::STORE);
591     setTargetDAGCombine(ISD::FP_TO_SINT);
592     setTargetDAGCombine(ISD::FP_TO_UINT);
593     setTargetDAGCombine(ISD::FDIV);
594     setTargetDAGCombine(ISD::LOAD);
595
596     // It is legal to extload from v4i8 to v4i16 or v4i32.
597     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
598                    MVT::v2i32}) {
599       for (MVT VT : MVT::integer_vector_valuetypes()) {
600         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
601         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
602         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
603       }
604     }
605   }
606
607   // ARM and Thumb2 support UMLAL/SMLAL.
608   if (!Subtarget->isThumb1Only())
609     setTargetDAGCombine(ISD::ADDC);
610
611   if (Subtarget->isFPOnlySP()) {
612     // When targeting a floating-point unit with only single-precision
613     // operations, f64 is legal for the few double-precision instructions which
614     // are present However, no double-precision operations other than moves,
615     // loads and stores are provided by the hardware.
616     setOperationAction(ISD::FADD,       MVT::f64, Expand);
617     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
618     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
619     setOperationAction(ISD::FMA,        MVT::f64, Expand);
620     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
621     setOperationAction(ISD::FREM,       MVT::f64, Expand);
622     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
623     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
624     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
625     setOperationAction(ISD::FABS,       MVT::f64, Expand);
626     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
627     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
628     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
629     setOperationAction(ISD::FPOWI,      MVT::f64, Expand);
630     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
631     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
632     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
633     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
634     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
635     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
636     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
637     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
638     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
639     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
640     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
641     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
642     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
643     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
644     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
645     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
646     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
647     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
648     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
649   }
650
651   computeRegisterProperties(Subtarget->getRegisterInfo());
652
653   // ARM does not have floating-point extending loads.
654   for (MVT VT : MVT::fp_valuetypes()) {
655     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
656     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
657   }
658
659   // ... or truncating stores
660   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
661   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
662   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
663
664   // ARM does not have i1 sign extending load.
665   for (MVT VT : MVT::integer_valuetypes())
666     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
667
668   // ARM supports all 4 flavors of integer indexed load / store.
669   if (!Subtarget->isThumb1Only()) {
670     for (unsigned im = (unsigned)ISD::PRE_INC;
671          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
672       setIndexedLoadAction(im,  MVT::i1,  Legal);
673       setIndexedLoadAction(im,  MVT::i8,  Legal);
674       setIndexedLoadAction(im,  MVT::i16, Legal);
675       setIndexedLoadAction(im,  MVT::i32, Legal);
676       setIndexedStoreAction(im, MVT::i1,  Legal);
677       setIndexedStoreAction(im, MVT::i8,  Legal);
678       setIndexedStoreAction(im, MVT::i16, Legal);
679       setIndexedStoreAction(im, MVT::i32, Legal);
680     }
681   }
682
683   setOperationAction(ISD::SADDO, MVT::i32, Custom);
684   setOperationAction(ISD::UADDO, MVT::i32, Custom);
685   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
686   setOperationAction(ISD::USUBO, MVT::i32, Custom);
687
688   // i64 operation support.
689   setOperationAction(ISD::MUL,     MVT::i64, Expand);
690   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
691   if (Subtarget->isThumb1Only()) {
692     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
693     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
694   }
695   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
696       || (Subtarget->isThumb2() && !Subtarget->hasThumb2DSP()))
697     setOperationAction(ISD::MULHS, MVT::i32, Expand);
698
699   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
700   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
701   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
702   setOperationAction(ISD::SRL,       MVT::i64, Custom);
703   setOperationAction(ISD::SRA,       MVT::i64, Custom);
704
705   if (!Subtarget->isThumb1Only()) {
706     // FIXME: We should do this for Thumb1 as well.
707     setOperationAction(ISD::ADDC,    MVT::i32, Custom);
708     setOperationAction(ISD::ADDE,    MVT::i32, Custom);
709     setOperationAction(ISD::SUBC,    MVT::i32, Custom);
710     setOperationAction(ISD::SUBE,    MVT::i32, Custom);
711   }
712
713   // ARM does not have ROTL.
714   setOperationAction(ISD::ROTL,  MVT::i32, Expand);
715   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
716   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
717   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
718     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
719
720   // These just redirect to CTTZ and CTLZ on ARM.
721   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i32  , Expand);
722   setOperationAction(ISD::CTLZ_ZERO_UNDEF  , MVT::i32  , Expand);
723
724   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
725
726   // Only ARMv6 has BSWAP.
727   if (!Subtarget->hasV6Ops())
728     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
729
730   if (!(Subtarget->hasDivide() && Subtarget->isThumb2()) &&
731       !(Subtarget->hasDivideInARMMode() && !Subtarget->isThumb())) {
732     // These are expanded into libcalls if the cpu doesn't have HW divider.
733     setOperationAction(ISD::SDIV,  MVT::i32, Expand);
734     setOperationAction(ISD::UDIV,  MVT::i32, Expand);
735   }
736
737   // FIXME: Also set divmod for SREM on EABI/androideabi
738   setOperationAction(ISD::SREM,  MVT::i32, Expand);
739   setOperationAction(ISD::UREM,  MVT::i32, Expand);
740   // Register based DivRem for AEABI (RTABI 4.2)
741   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) {
742     setLibcallName(RTLIB::SDIVREM_I8,  "__aeabi_idivmod");
743     setLibcallName(RTLIB::SDIVREM_I16, "__aeabi_idivmod");
744     setLibcallName(RTLIB::SDIVREM_I32, "__aeabi_idivmod");
745     setLibcallName(RTLIB::SDIVREM_I64, "__aeabi_ldivmod");
746     setLibcallName(RTLIB::UDIVREM_I8,  "__aeabi_uidivmod");
747     setLibcallName(RTLIB::UDIVREM_I16, "__aeabi_uidivmod");
748     setLibcallName(RTLIB::UDIVREM_I32, "__aeabi_uidivmod");
749     setLibcallName(RTLIB::UDIVREM_I64, "__aeabi_uldivmod");
750
751     setLibcallCallingConv(RTLIB::SDIVREM_I8, CallingConv::ARM_AAPCS);
752     setLibcallCallingConv(RTLIB::SDIVREM_I16, CallingConv::ARM_AAPCS);
753     setLibcallCallingConv(RTLIB::SDIVREM_I32, CallingConv::ARM_AAPCS);
754     setLibcallCallingConv(RTLIB::SDIVREM_I64, CallingConv::ARM_AAPCS);
755     setLibcallCallingConv(RTLIB::UDIVREM_I8, CallingConv::ARM_AAPCS);
756     setLibcallCallingConv(RTLIB::UDIVREM_I16, CallingConv::ARM_AAPCS);
757     setLibcallCallingConv(RTLIB::UDIVREM_I32, CallingConv::ARM_AAPCS);
758     setLibcallCallingConv(RTLIB::UDIVREM_I64, CallingConv::ARM_AAPCS);
759
760     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
761     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
762   } else {
763     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
764     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
765   }
766
767   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
768   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
769   setOperationAction(ISD::GLOBAL_OFFSET_TABLE, MVT::i32, Custom);
770   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
771   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
772
773   setOperationAction(ISD::TRAP, MVT::Other, Legal);
774
775   // Use the default implementation.
776   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
777   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
778   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
779   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
780   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
781   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
782
783   if (!Subtarget->isTargetMachO()) {
784     // Non-MachO platforms may return values in these registers via the
785     // personality function.
786     setExceptionPointerRegister(ARM::R0);
787     setExceptionSelectorRegister(ARM::R1);
788   }
789
790   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
791     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
792   else
793     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
794
795   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
796   // the default expansion. If we are targeting a single threaded system,
797   // then set them all for expand so we can lower them later into their
798   // non-atomic form.
799   if (TM.Options.ThreadModel == ThreadModel::Single)
800     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other, Expand);
801   else if (Subtarget->hasAnyDataBarrier() && !Subtarget->isThumb1Only()) {
802     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
803     // to ldrex/strex loops already.
804     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
805
806     // On v8, we have particularly efficient implementations of atomic fences
807     // if they can be combined with nearby atomic loads and stores.
808     if (!Subtarget->hasV8Ops()) {
809       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
810       setInsertFencesForAtomic(true);
811     }
812   } else {
813     // If there's anything we can use as a barrier, go through custom lowering
814     // for ATOMIC_FENCE.
815     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
816                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
817
818     // Set them all for expansion, which will force libcalls.
819     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
820     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
821     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
822     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
823     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
824     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
825     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
826     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
827     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
828     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
829     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
830     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
831     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
832     // Unordered/Monotonic case.
833     setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
834     setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
835   }
836
837   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
838
839   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
840   if (!Subtarget->hasV6Ops()) {
841     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
842     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
843   }
844   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
845
846   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
847       !Subtarget->isThumb1Only()) {
848     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
849     // iff target supports vfp2.
850     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
851     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
852   }
853
854   // We want to custom lower some of our intrinsics.
855   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
856   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
857   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
858   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
859   if (Subtarget->isTargetDarwin())
860     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
861
862   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
863   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
864   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
865   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
866   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
867   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
868   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
869   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
870   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
871
872   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
873   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
874   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
875   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
876   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
877
878   // We don't support sin/cos/fmod/copysign/pow
879   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
880   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
881   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
882   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
883   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
884   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
885   setOperationAction(ISD::FREM,      MVT::f64, Expand);
886   setOperationAction(ISD::FREM,      MVT::f32, Expand);
887   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
888       !Subtarget->isThumb1Only()) {
889     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
890     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
891   }
892   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
893   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
894
895   if (!Subtarget->hasVFP4()) {
896     setOperationAction(ISD::FMA, MVT::f64, Expand);
897     setOperationAction(ISD::FMA, MVT::f32, Expand);
898   }
899
900   // Various VFP goodness
901   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
902     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
903     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
904       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
905       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
906     }
907
908     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
909     if (!Subtarget->hasFP16()) {
910       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
911       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
912     }
913   }
914
915   // Combine sin / cos into one node or libcall if possible.
916   if (Subtarget->hasSinCos()) {
917     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
918     setLibcallName(RTLIB::SINCOS_F64, "sincos");
919     if (Subtarget->getTargetTriple().isiOS()) {
920       // For iOS, we don't want to the normal expansion of a libcall to
921       // sincos. We want to issue a libcall to __sincos_stret.
922       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
923       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
924     }
925   }
926
927   // FP-ARMv8 implements a lot of rounding-like FP operations.
928   if (Subtarget->hasFPARMv8()) {
929     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
930     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
931     setOperationAction(ISD::FROUND, MVT::f32, Legal);
932     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
933     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
934     setOperationAction(ISD::FRINT, MVT::f32, Legal);
935     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
936     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
937     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
938     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
939     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
940     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
941
942     if (!Subtarget->isFPOnlySP()) {
943       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
944       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
945       setOperationAction(ISD::FROUND, MVT::f64, Legal);
946       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
947       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
948       setOperationAction(ISD::FRINT, MVT::f64, Legal);
949       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
950       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
951     }
952   }
953
954   if (Subtarget->hasVFP3()) {
955     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
956     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
957     setOperationAction(ISD::FMINNAN, MVT::f64, Legal);
958     setOperationAction(ISD::FMAXNAN, MVT::f64, Legal);
959   }
960
961   // We have target-specific dag combine patterns for the following nodes:
962   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
963   setTargetDAGCombine(ISD::ADD);
964   setTargetDAGCombine(ISD::SUB);
965   setTargetDAGCombine(ISD::MUL);
966   setTargetDAGCombine(ISD::AND);
967   setTargetDAGCombine(ISD::OR);
968   setTargetDAGCombine(ISD::XOR);
969
970   if (Subtarget->hasV6Ops())
971     setTargetDAGCombine(ISD::SRL);
972
973   setStackPointerRegisterToSaveRestore(ARM::SP);
974
975   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
976       !Subtarget->hasVFP2())
977     setSchedulingPreference(Sched::RegPressure);
978   else
979     setSchedulingPreference(Sched::Hybrid);
980
981   //// temporary - rewrite interface to use type
982   MaxStoresPerMemset = 8;
983   MaxStoresPerMemsetOptSize = 4;
984   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
985   MaxStoresPerMemcpyOptSize = 2;
986   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
987   MaxStoresPerMemmoveOptSize = 2;
988
989   // On ARM arguments smaller than 4 bytes are extended, so all arguments
990   // are at least 4 bytes aligned.
991   setMinStackArgumentAlignment(4);
992
993   // Prefer likely predicted branches to selects on out-of-order cores.
994   PredictableSelectIsExpensive = Subtarget->isLikeA9();
995
996   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
997 }
998
999 bool ARMTargetLowering::useSoftFloat() const {
1000   return Subtarget->useSoftFloat();
1001 }
1002
1003 // FIXME: It might make sense to define the representative register class as the
1004 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1005 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1006 // SPR's representative would be DPR_VFP2. This should work well if register
1007 // pressure tracking were modified such that a register use would increment the
1008 // pressure of the register class's representative and all of it's super
1009 // classes' representatives transitively. We have not implemented this because
1010 // of the difficulty prior to coalescing of modeling operand register classes
1011 // due to the common occurrence of cross class copies and subregister insertions
1012 // and extractions.
1013 std::pair<const TargetRegisterClass *, uint8_t>
1014 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1015                                            MVT VT) const {
1016   const TargetRegisterClass *RRC = nullptr;
1017   uint8_t Cost = 1;
1018   switch (VT.SimpleTy) {
1019   default:
1020     return TargetLowering::findRepresentativeClass(TRI, VT);
1021   // Use DPR as representative register class for all floating point
1022   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1023   // the cost is 1 for both f32 and f64.
1024   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1025   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1026     RRC = &ARM::DPRRegClass;
1027     // When NEON is used for SP, only half of the register file is available
1028     // because operations that define both SP and DP results will be constrained
1029     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1030     // coalescing by double-counting the SP regs. See the FIXME above.
1031     if (Subtarget->useNEONForSinglePrecisionFP())
1032       Cost = 2;
1033     break;
1034   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1035   case MVT::v4f32: case MVT::v2f64:
1036     RRC = &ARM::DPRRegClass;
1037     Cost = 2;
1038     break;
1039   case MVT::v4i64:
1040     RRC = &ARM::DPRRegClass;
1041     Cost = 4;
1042     break;
1043   case MVT::v8i64:
1044     RRC = &ARM::DPRRegClass;
1045     Cost = 8;
1046     break;
1047   }
1048   return std::make_pair(RRC, Cost);
1049 }
1050
1051 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1052   switch ((ARMISD::NodeType)Opcode) {
1053   case ARMISD::FIRST_NUMBER:  break;
1054   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1055   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1056   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1057   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1058   case ARMISD::CALL:          return "ARMISD::CALL";
1059   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1060   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1061   case ARMISD::tCALL:         return "ARMISD::tCALL";
1062   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1063   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1064   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1065   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1066   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1067   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1068   case ARMISD::CMP:           return "ARMISD::CMP";
1069   case ARMISD::CMN:           return "ARMISD::CMN";
1070   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1071   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1072   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1073   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1074   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1075
1076   case ARMISD::CMOV:          return "ARMISD::CMOV";
1077
1078   case ARMISD::RBIT:          return "ARMISD::RBIT";
1079
1080   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1081   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1082   case ARMISD::RRX:           return "ARMISD::RRX";
1083
1084   case ARMISD::ADDC:          return "ARMISD::ADDC";
1085   case ARMISD::ADDE:          return "ARMISD::ADDE";
1086   case ARMISD::SUBC:          return "ARMISD::SUBC";
1087   case ARMISD::SUBE:          return "ARMISD::SUBE";
1088
1089   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1090   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1091
1092   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1093   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1094   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1095
1096   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1097
1098   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1099
1100   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1101
1102   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1103
1104   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1105
1106   case ARMISD::WIN__CHKSTK:   return "ARMISD:::WIN__CHKSTK";
1107
1108   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1109   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1110   case ARMISD::VCGE:          return "ARMISD::VCGE";
1111   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1112   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1113   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1114   case ARMISD::VCGT:          return "ARMISD::VCGT";
1115   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1116   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1117   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1118   case ARMISD::VTST:          return "ARMISD::VTST";
1119
1120   case ARMISD::VSHL:          return "ARMISD::VSHL";
1121   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1122   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1123   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1124   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1125   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1126   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1127   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1128   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1129   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1130   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1131   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1132   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1133   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1134   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1135   case ARMISD::VSLI:          return "ARMISD::VSLI";
1136   case ARMISD::VSRI:          return "ARMISD::VSRI";
1137   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1138   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1139   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1140   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1141   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1142   case ARMISD::VDUP:          return "ARMISD::VDUP";
1143   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1144   case ARMISD::VEXT:          return "ARMISD::VEXT";
1145   case ARMISD::VREV64:        return "ARMISD::VREV64";
1146   case ARMISD::VREV32:        return "ARMISD::VREV32";
1147   case ARMISD::VREV16:        return "ARMISD::VREV16";
1148   case ARMISD::VZIP:          return "ARMISD::VZIP";
1149   case ARMISD::VUZP:          return "ARMISD::VUZP";
1150   case ARMISD::VTRN:          return "ARMISD::VTRN";
1151   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1152   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1153   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1154   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1155   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1156   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1157   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1158   case ARMISD::BFI:           return "ARMISD::BFI";
1159   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1160   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1161   case ARMISD::VBSL:          return "ARMISD::VBSL";
1162   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1163   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1164   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1165   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1166   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1167   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1168   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1169   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1170   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1171   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1172   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1173   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1174   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1175   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1176   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1177   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1178   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1179   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1180   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1181   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1182   }
1183   return nullptr;
1184 }
1185
1186 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1187                                           EVT VT) const {
1188   if (!VT.isVector())
1189     return getPointerTy(DL);
1190   return VT.changeVectorElementTypeToInteger();
1191 }
1192
1193 /// getRegClassFor - Return the register class that should be used for the
1194 /// specified value type.
1195 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1196   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1197   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1198   // load / store 4 to 8 consecutive D registers.
1199   if (Subtarget->hasNEON()) {
1200     if (VT == MVT::v4i64)
1201       return &ARM::QQPRRegClass;
1202     if (VT == MVT::v8i64)
1203       return &ARM::QQQQPRRegClass;
1204   }
1205   return TargetLowering::getRegClassFor(VT);
1206 }
1207
1208 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1209 // source/dest is aligned and the copy size is large enough. We therefore want
1210 // to align such objects passed to memory intrinsics.
1211 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1212                                                unsigned &PrefAlign) const {
1213   if (!isa<MemIntrinsic>(CI))
1214     return false;
1215   MinSize = 8;
1216   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1217   // cycle faster than 4-byte aligned LDM.
1218   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1219   return true;
1220 }
1221
1222 // Create a fast isel object.
1223 FastISel *
1224 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1225                                   const TargetLibraryInfo *libInfo) const {
1226   return ARM::createFastISel(funcInfo, libInfo);
1227 }
1228
1229 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1230   unsigned NumVals = N->getNumValues();
1231   if (!NumVals)
1232     return Sched::RegPressure;
1233
1234   for (unsigned i = 0; i != NumVals; ++i) {
1235     EVT VT = N->getValueType(i);
1236     if (VT == MVT::Glue || VT == MVT::Other)
1237       continue;
1238     if (VT.isFloatingPoint() || VT.isVector())
1239       return Sched::ILP;
1240   }
1241
1242   if (!N->isMachineOpcode())
1243     return Sched::RegPressure;
1244
1245   // Load are scheduled for latency even if there instruction itinerary
1246   // is not available.
1247   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1248   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1249
1250   if (MCID.getNumDefs() == 0)
1251     return Sched::RegPressure;
1252   if (!Itins->isEmpty() &&
1253       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1254     return Sched::ILP;
1255
1256   return Sched::RegPressure;
1257 }
1258
1259 //===----------------------------------------------------------------------===//
1260 // Lowering Code
1261 //===----------------------------------------------------------------------===//
1262
1263 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1264 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1265   switch (CC) {
1266   default: llvm_unreachable("Unknown condition code!");
1267   case ISD::SETNE:  return ARMCC::NE;
1268   case ISD::SETEQ:  return ARMCC::EQ;
1269   case ISD::SETGT:  return ARMCC::GT;
1270   case ISD::SETGE:  return ARMCC::GE;
1271   case ISD::SETLT:  return ARMCC::LT;
1272   case ISD::SETLE:  return ARMCC::LE;
1273   case ISD::SETUGT: return ARMCC::HI;
1274   case ISD::SETUGE: return ARMCC::HS;
1275   case ISD::SETULT: return ARMCC::LO;
1276   case ISD::SETULE: return ARMCC::LS;
1277   }
1278 }
1279
1280 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1281 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1282                         ARMCC::CondCodes &CondCode2) {
1283   CondCode2 = ARMCC::AL;
1284   switch (CC) {
1285   default: llvm_unreachable("Unknown FP condition!");
1286   case ISD::SETEQ:
1287   case ISD::SETOEQ: CondCode = ARMCC::EQ; break;
1288   case ISD::SETGT:
1289   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1290   case ISD::SETGE:
1291   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1292   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1293   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1294   case ISD::SETONE: CondCode = ARMCC::MI; CondCode2 = ARMCC::GT; break;
1295   case ISD::SETO:   CondCode = ARMCC::VC; break;
1296   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1297   case ISD::SETUEQ: CondCode = ARMCC::EQ; CondCode2 = ARMCC::VS; break;
1298   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1299   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1300   case ISD::SETLT:
1301   case ISD::SETULT: CondCode = ARMCC::LT; break;
1302   case ISD::SETLE:
1303   case ISD::SETULE: CondCode = ARMCC::LE; break;
1304   case ISD::SETNE:
1305   case ISD::SETUNE: CondCode = ARMCC::NE; break;
1306   }
1307 }
1308
1309 //===----------------------------------------------------------------------===//
1310 //                      Calling Convention Implementation
1311 //===----------------------------------------------------------------------===//
1312
1313 #include "ARMGenCallingConv.inc"
1314
1315 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1316 /// account presence of floating point hardware and calling convention
1317 /// limitations, such as support for variadic functions.
1318 CallingConv::ID
1319 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1320                                            bool isVarArg) const {
1321   switch (CC) {
1322   default:
1323     llvm_unreachable("Unsupported calling convention");
1324   case CallingConv::ARM_AAPCS:
1325   case CallingConv::ARM_APCS:
1326   case CallingConv::GHC:
1327     return CC;
1328   case CallingConv::ARM_AAPCS_VFP:
1329     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1330   case CallingConv::C:
1331     if (!Subtarget->isAAPCS_ABI())
1332       return CallingConv::ARM_APCS;
1333     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1334              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1335              !isVarArg)
1336       return CallingConv::ARM_AAPCS_VFP;
1337     else
1338       return CallingConv::ARM_AAPCS;
1339   case CallingConv::Fast:
1340     if (!Subtarget->isAAPCS_ABI()) {
1341       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1342         return CallingConv::Fast;
1343       return CallingConv::ARM_APCS;
1344     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1345       return CallingConv::ARM_AAPCS_VFP;
1346     else
1347       return CallingConv::ARM_AAPCS;
1348   }
1349 }
1350
1351 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1352 /// CallingConvention.
1353 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1354                                                  bool Return,
1355                                                  bool isVarArg) const {
1356   switch (getEffectiveCallingConv(CC, isVarArg)) {
1357   default:
1358     llvm_unreachable("Unsupported calling convention");
1359   case CallingConv::ARM_APCS:
1360     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1361   case CallingConv::ARM_AAPCS:
1362     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1363   case CallingConv::ARM_AAPCS_VFP:
1364     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1365   case CallingConv::Fast:
1366     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1367   case CallingConv::GHC:
1368     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1369   }
1370 }
1371
1372 /// LowerCallResult - Lower the result values of a call into the
1373 /// appropriate copies out of appropriate physical registers.
1374 SDValue
1375 ARMTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1376                                    CallingConv::ID CallConv, bool isVarArg,
1377                                    const SmallVectorImpl<ISD::InputArg> &Ins,
1378                                    SDLoc dl, SelectionDAG &DAG,
1379                                    SmallVectorImpl<SDValue> &InVals,
1380                                    bool isThisReturn, SDValue ThisVal) const {
1381
1382   // Assign locations to each value returned by this call.
1383   SmallVector<CCValAssign, 16> RVLocs;
1384   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1385                     *DAG.getContext(), Call);
1386   CCInfo.AnalyzeCallResult(Ins,
1387                            CCAssignFnForNode(CallConv, /* Return*/ true,
1388                                              isVarArg));
1389
1390   // Copy all of the result registers out of their specified physreg.
1391   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1392     CCValAssign VA = RVLocs[i];
1393
1394     // Pass 'this' value directly from the argument to return value, to avoid
1395     // reg unit interference
1396     if (i == 0 && isThisReturn) {
1397       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1398              "unexpected return calling convention register assignment");
1399       InVals.push_back(ThisVal);
1400       continue;
1401     }
1402
1403     SDValue Val;
1404     if (VA.needsCustom()) {
1405       // Handle f64 or half of a v2f64.
1406       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1407                                       InFlag);
1408       Chain = Lo.getValue(1);
1409       InFlag = Lo.getValue(2);
1410       VA = RVLocs[++i]; // skip ahead to next loc
1411       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1412                                       InFlag);
1413       Chain = Hi.getValue(1);
1414       InFlag = Hi.getValue(2);
1415       if (!Subtarget->isLittle())
1416         std::swap (Lo, Hi);
1417       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1418
1419       if (VA.getLocVT() == MVT::v2f64) {
1420         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1421         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1422                           DAG.getConstant(0, dl, MVT::i32));
1423
1424         VA = RVLocs[++i]; // skip ahead to next loc
1425         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1426         Chain = Lo.getValue(1);
1427         InFlag = Lo.getValue(2);
1428         VA = RVLocs[++i]; // skip ahead to next loc
1429         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1430         Chain = Hi.getValue(1);
1431         InFlag = Hi.getValue(2);
1432         if (!Subtarget->isLittle())
1433           std::swap (Lo, Hi);
1434         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1435         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1436                           DAG.getConstant(1, dl, MVT::i32));
1437       }
1438     } else {
1439       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1440                                InFlag);
1441       Chain = Val.getValue(1);
1442       InFlag = Val.getValue(2);
1443     }
1444
1445     switch (VA.getLocInfo()) {
1446     default: llvm_unreachable("Unknown loc info!");
1447     case CCValAssign::Full: break;
1448     case CCValAssign::BCvt:
1449       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1450       break;
1451     }
1452
1453     InVals.push_back(Val);
1454   }
1455
1456   return Chain;
1457 }
1458
1459 /// LowerMemOpCallTo - Store the argument to the stack.
1460 SDValue
1461 ARMTargetLowering::LowerMemOpCallTo(SDValue Chain,
1462                                     SDValue StackPtr, SDValue Arg,
1463                                     SDLoc dl, SelectionDAG &DAG,
1464                                     const CCValAssign &VA,
1465                                     ISD::ArgFlagsTy Flags) const {
1466   unsigned LocMemOffset = VA.getLocMemOffset();
1467   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1468   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1469                        StackPtr, PtrOff);
1470   return DAG.getStore(Chain, dl, Arg, PtrOff,
1471                       MachinePointerInfo::getStack(LocMemOffset),
1472                       false, false, 0);
1473 }
1474
1475 void ARMTargetLowering::PassF64ArgInRegs(SDLoc dl, SelectionDAG &DAG,
1476                                          SDValue Chain, SDValue &Arg,
1477                                          RegsToPassVector &RegsToPass,
1478                                          CCValAssign &VA, CCValAssign &NextVA,
1479                                          SDValue &StackPtr,
1480                                          SmallVectorImpl<SDValue> &MemOpChains,
1481                                          ISD::ArgFlagsTy Flags) const {
1482
1483   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1484                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1485   unsigned id = Subtarget->isLittle() ? 0 : 1;
1486   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1487
1488   if (NextVA.isRegLoc())
1489     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1490   else {
1491     assert(NextVA.isMemLoc());
1492     if (!StackPtr.getNode())
1493       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1494                                     getPointerTy(DAG.getDataLayout()));
1495
1496     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1497                                            dl, DAG, NextVA,
1498                                            Flags));
1499   }
1500 }
1501
1502 /// LowerCall - Lowering a call into a callseq_start <-
1503 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1504 /// nodes.
1505 SDValue
1506 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1507                              SmallVectorImpl<SDValue> &InVals) const {
1508   SelectionDAG &DAG                     = CLI.DAG;
1509   SDLoc &dl                             = CLI.DL;
1510   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1511   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1512   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1513   SDValue Chain                         = CLI.Chain;
1514   SDValue Callee                        = CLI.Callee;
1515   bool &isTailCall                      = CLI.IsTailCall;
1516   CallingConv::ID CallConv              = CLI.CallConv;
1517   bool doesNotRet                       = CLI.DoesNotReturn;
1518   bool isVarArg                         = CLI.IsVarArg;
1519
1520   MachineFunction &MF = DAG.getMachineFunction();
1521   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1522   bool isThisReturn   = false;
1523   bool isSibCall      = false;
1524   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1525
1526   // Disable tail calls if they're not supported.
1527   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1528     isTailCall = false;
1529
1530   if (isTailCall) {
1531     // Check if it's really possible to do a tail call.
1532     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1533                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1534                                                    Outs, OutVals, Ins, DAG);
1535     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1536       report_fatal_error("failed to perform tail call elimination on a call "
1537                          "site marked musttail");
1538     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1539     // detected sibcalls.
1540     if (isTailCall) {
1541       ++NumTailCalls;
1542       isSibCall = true;
1543     }
1544   }
1545
1546   // Analyze operands of the call, assigning locations to each operand.
1547   SmallVector<CCValAssign, 16> ArgLocs;
1548   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1549                     *DAG.getContext(), Call);
1550   CCInfo.AnalyzeCallOperands(Outs,
1551                              CCAssignFnForNode(CallConv, /* Return*/ false,
1552                                                isVarArg));
1553
1554   // Get a count of how many bytes are to be pushed on the stack.
1555   unsigned NumBytes = CCInfo.getNextStackOffset();
1556
1557   // For tail calls, memory operands are available in our caller's stack.
1558   if (isSibCall)
1559     NumBytes = 0;
1560
1561   // Adjust the stack pointer for the new arguments...
1562   // These operations are automatically eliminated by the prolog/epilog pass
1563   if (!isSibCall)
1564     Chain = DAG.getCALLSEQ_START(Chain,
1565                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1566
1567   SDValue StackPtr =
1568       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1569
1570   RegsToPassVector RegsToPass;
1571   SmallVector<SDValue, 8> MemOpChains;
1572
1573   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1574   // of tail call optimization, arguments are handled later.
1575   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1576        i != e;
1577        ++i, ++realArgIdx) {
1578     CCValAssign &VA = ArgLocs[i];
1579     SDValue Arg = OutVals[realArgIdx];
1580     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1581     bool isByVal = Flags.isByVal();
1582
1583     // Promote the value if needed.
1584     switch (VA.getLocInfo()) {
1585     default: llvm_unreachable("Unknown loc info!");
1586     case CCValAssign::Full: break;
1587     case CCValAssign::SExt:
1588       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1589       break;
1590     case CCValAssign::ZExt:
1591       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1592       break;
1593     case CCValAssign::AExt:
1594       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1595       break;
1596     case CCValAssign::BCvt:
1597       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1598       break;
1599     }
1600
1601     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1602     if (VA.needsCustom()) {
1603       if (VA.getLocVT() == MVT::v2f64) {
1604         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1605                                   DAG.getConstant(0, dl, MVT::i32));
1606         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1607                                   DAG.getConstant(1, dl, MVT::i32));
1608
1609         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1610                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1611
1612         VA = ArgLocs[++i]; // skip ahead to next loc
1613         if (VA.isRegLoc()) {
1614           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1615                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1616         } else {
1617           assert(VA.isMemLoc());
1618
1619           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1620                                                  dl, DAG, VA, Flags));
1621         }
1622       } else {
1623         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1624                          StackPtr, MemOpChains, Flags);
1625       }
1626     } else if (VA.isRegLoc()) {
1627       if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i32) {
1628         assert(VA.getLocVT() == MVT::i32 &&
1629                "unexpected calling convention register assignment");
1630         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1631                "unexpected use of 'returned'");
1632         isThisReturn = true;
1633       }
1634       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1635     } else if (isByVal) {
1636       assert(VA.isMemLoc());
1637       unsigned offset = 0;
1638
1639       // True if this byval aggregate will be split between registers
1640       // and memory.
1641       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1642       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1643
1644       if (CurByValIdx < ByValArgsCount) {
1645
1646         unsigned RegBegin, RegEnd;
1647         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1648
1649         EVT PtrVT =
1650             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1651         unsigned int i, j;
1652         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1653           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1654           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1655           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1656                                      MachinePointerInfo(),
1657                                      false, false, false,
1658                                      DAG.InferPtrAlignment(AddArg));
1659           MemOpChains.push_back(Load.getValue(1));
1660           RegsToPass.push_back(std::make_pair(j, Load));
1661         }
1662
1663         // If parameter size outsides register area, "offset" value
1664         // helps us to calculate stack slot for remained part properly.
1665         offset = RegEnd - RegBegin;
1666
1667         CCInfo.nextInRegsParam();
1668       }
1669
1670       if (Flags.getByValSize() > 4*offset) {
1671         auto PtrVT = getPointerTy(DAG.getDataLayout());
1672         unsigned LocMemOffset = VA.getLocMemOffset();
1673         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1674         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1675         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1676         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1677         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1678                                            MVT::i32);
1679         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1680                                             MVT::i32);
1681
1682         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1683         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1684         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1685                                           Ops));
1686       }
1687     } else if (!isSibCall) {
1688       assert(VA.isMemLoc());
1689
1690       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1691                                              dl, DAG, VA, Flags));
1692     }
1693   }
1694
1695   if (!MemOpChains.empty())
1696     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1697
1698   // Build a sequence of copy-to-reg nodes chained together with token chain
1699   // and flag operands which copy the outgoing args into the appropriate regs.
1700   SDValue InFlag;
1701   // Tail call byval lowering might overwrite argument registers so in case of
1702   // tail call optimization the copies to registers are lowered later.
1703   if (!isTailCall)
1704     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1705       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1706                                RegsToPass[i].second, InFlag);
1707       InFlag = Chain.getValue(1);
1708     }
1709
1710   // For tail calls lower the arguments to the 'real' stack slot.
1711   if (isTailCall) {
1712     // Force all the incoming stack arguments to be loaded from the stack
1713     // before any new outgoing arguments are stored to the stack, because the
1714     // outgoing stack slots may alias the incoming argument stack slots, and
1715     // the alias isn't otherwise explicit. This is slightly more conservative
1716     // than necessary, because it means that each store effectively depends
1717     // on every argument instead of just those arguments it would clobber.
1718
1719     // Do not flag preceding copytoreg stuff together with the following stuff.
1720     InFlag = SDValue();
1721     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1722       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1723                                RegsToPass[i].second, InFlag);
1724       InFlag = Chain.getValue(1);
1725     }
1726     InFlag = SDValue();
1727   }
1728
1729   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1730   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1731   // node so that legalize doesn't hack it.
1732   bool isDirect = false;
1733   bool isARMFunc = false;
1734   bool isLocalARMFunc = false;
1735   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1736   auto PtrVt = getPointerTy(DAG.getDataLayout());
1737
1738   if (Subtarget->genLongCalls()) {
1739     assert((Subtarget->isTargetWindows() ||
1740             getTargetMachine().getRelocationModel() == Reloc::Static) &&
1741            "long-calls with non-static relocation model!");
1742     // Handle a global address or an external symbol. If it's not one of
1743     // those, the target's already in a register, so we don't need to do
1744     // anything extra.
1745     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1746       const GlobalValue *GV = G->getGlobal();
1747       // Create a constant pool entry for the callee address
1748       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1749       ARMConstantPoolValue *CPV =
1750         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
1751
1752       // Get the address of the callee into a register
1753       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1754       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1755       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1756                            MachinePointerInfo::getConstantPool(), false, false,
1757                            false, 0);
1758     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
1759       const char *Sym = S->getSymbol();
1760
1761       // Create a constant pool entry for the callee address
1762       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1763       ARMConstantPoolValue *CPV =
1764         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1765                                       ARMPCLabelIndex, 0);
1766       // Get the address of the callee into a register
1767       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1768       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1769       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1770                            MachinePointerInfo::getConstantPool(), false, false,
1771                            false, 0);
1772     }
1773   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1774     const GlobalValue *GV = G->getGlobal();
1775     isDirect = true;
1776     bool isDef = GV->isStrongDefinitionForLinker();
1777     bool isStub = (!isDef && Subtarget->isTargetMachO()) &&
1778                    getTargetMachine().getRelocationModel() != Reloc::Static;
1779     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1780     // ARM call to a local ARM function is predicable.
1781     isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
1782     // tBX takes a register source operand.
1783     if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1784       assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
1785       Callee = DAG.getNode(
1786           ARMISD::WrapperPIC, dl, PtrVt,
1787           DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
1788       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), Callee,
1789                            MachinePointerInfo::getGOT(), false, false, true, 0);
1790     } else if (Subtarget->isTargetCOFF()) {
1791       assert(Subtarget->isTargetWindows() &&
1792              "Windows is the only supported COFF target");
1793       unsigned TargetFlags = GV->hasDLLImportStorageClass()
1794                                  ? ARMII::MO_DLLIMPORT
1795                                  : ARMII::MO_NO_FLAG;
1796       Callee =
1797           DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0, TargetFlags);
1798       if (GV->hasDLLImportStorageClass())
1799         Callee =
1800             DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
1801                         DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
1802                         MachinePointerInfo::getGOT(), false, false, false, 0);
1803     } else {
1804       // On ELF targets for PIC code, direct calls should go through the PLT
1805       unsigned OpFlags = 0;
1806       if (Subtarget->isTargetELF() &&
1807           getTargetMachine().getRelocationModel() == Reloc::PIC_)
1808         OpFlags = ARMII::MO_PLT;
1809       Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, OpFlags);
1810     }
1811   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1812     isDirect = true;
1813     bool isStub = Subtarget->isTargetMachO() &&
1814                   getTargetMachine().getRelocationModel() != Reloc::Static;
1815     isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1816     // tBX takes a register source operand.
1817     const char *Sym = S->getSymbol();
1818     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
1819       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
1820       ARMConstantPoolValue *CPV =
1821         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
1822                                       ARMPCLabelIndex, 4);
1823       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
1824       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
1825       Callee = DAG.getLoad(PtrVt, dl, DAG.getEntryNode(), CPAddr,
1826                            MachinePointerInfo::getConstantPool(), false, false,
1827                            false, 0);
1828       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
1829       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
1830     } else {
1831       unsigned OpFlags = 0;
1832       // On ELF targets for PIC code, direct calls should go through the PLT
1833       if (Subtarget->isTargetELF() &&
1834                   getTargetMachine().getRelocationModel() == Reloc::PIC_)
1835         OpFlags = ARMII::MO_PLT;
1836       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, OpFlags);
1837     }
1838   }
1839
1840   // FIXME: handle tail calls differently.
1841   unsigned CallOpc;
1842   if (Subtarget->isThumb()) {
1843     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
1844       CallOpc = ARMISD::CALL_NOLINK;
1845     else
1846       CallOpc = isARMFunc ? ARMISD::CALL : ARMISD::tCALL;
1847   } else {
1848     if (!isDirect && !Subtarget->hasV5TOps())
1849       CallOpc = ARMISD::CALL_NOLINK;
1850     else if (doesNotRet && isDirect && Subtarget->hasRAS() &&
1851              // Emit regular call when code size is the priority
1852              !MF.getFunction()->optForMinSize())
1853       // "mov lr, pc; b _foo" to avoid confusing the RSP
1854       CallOpc = ARMISD::CALL_NOLINK;
1855     else
1856       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
1857   }
1858
1859   std::vector<SDValue> Ops;
1860   Ops.push_back(Chain);
1861   Ops.push_back(Callee);
1862
1863   // Add argument registers to the end of the list so that they are known live
1864   // into the call.
1865   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1866     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1867                                   RegsToPass[i].second.getValueType()));
1868
1869   // Add a register mask operand representing the call-preserved registers.
1870   if (!isTailCall) {
1871     const uint32_t *Mask;
1872     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
1873     if (isThisReturn) {
1874       // For 'this' returns, use the R0-preserving mask if applicable
1875       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
1876       if (!Mask) {
1877         // Set isThisReturn to false if the calling convention is not one that
1878         // allows 'returned' to be modeled in this way, so LowerCallResult does
1879         // not try to pass 'this' straight through
1880         isThisReturn = false;
1881         Mask = ARI->getCallPreservedMask(MF, CallConv);
1882       }
1883     } else
1884       Mask = ARI->getCallPreservedMask(MF, CallConv);
1885
1886     assert(Mask && "Missing call preserved mask for calling convention");
1887     Ops.push_back(DAG.getRegisterMask(Mask));
1888   }
1889
1890   if (InFlag.getNode())
1891     Ops.push_back(InFlag);
1892
1893   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1894   if (isTailCall) {
1895     MF.getFrameInfo()->setHasTailCall();
1896     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
1897   }
1898
1899   // Returns a chain and a flag for retval copy to use.
1900   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
1901   InFlag = Chain.getValue(1);
1902
1903   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
1904                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
1905   if (!Ins.empty())
1906     InFlag = Chain.getValue(1);
1907
1908   // Handle result values, copying them out of physregs into vregs that we
1909   // return.
1910   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
1911                          InVals, isThisReturn,
1912                          isThisReturn ? OutVals[0] : SDValue());
1913 }
1914
1915 /// HandleByVal - Every parameter *after* a byval parameter is passed
1916 /// on the stack.  Remember the next parameter register to allocate,
1917 /// and then confiscate the rest of the parameter registers to insure
1918 /// this.
1919 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
1920                                     unsigned Align) const {
1921   assert((State->getCallOrPrologue() == Prologue ||
1922           State->getCallOrPrologue() == Call) &&
1923          "unhandled ParmContext");
1924
1925   // Byval (as with any stack) slots are always at least 4 byte aligned.
1926   Align = std::max(Align, 4U);
1927
1928   unsigned Reg = State->AllocateReg(GPRArgRegs);
1929   if (!Reg)
1930     return;
1931
1932   unsigned AlignInRegs = Align / 4;
1933   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
1934   for (unsigned i = 0; i < Waste; ++i)
1935     Reg = State->AllocateReg(GPRArgRegs);
1936
1937   if (!Reg)
1938     return;
1939
1940   unsigned Excess = 4 * (ARM::R4 - Reg);
1941
1942   // Special case when NSAA != SP and parameter size greater than size of
1943   // all remained GPR regs. In that case we can't split parameter, we must
1944   // send it to stack. We also must set NCRN to R4, so waste all
1945   // remained registers.
1946   const unsigned NSAAOffset = State->getNextStackOffset();
1947   if (NSAAOffset != 0 && Size > Excess) {
1948     while (State->AllocateReg(GPRArgRegs))
1949       ;
1950     return;
1951   }
1952
1953   // First register for byval parameter is the first register that wasn't
1954   // allocated before this method call, so it would be "reg".
1955   // If parameter is small enough to be saved in range [reg, r4), then
1956   // the end (first after last) register would be reg + param-size-in-regs,
1957   // else parameter would be splitted between registers and stack,
1958   // end register would be r4 in this case.
1959   unsigned ByValRegBegin = Reg;
1960   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
1961   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
1962   // Note, first register is allocated in the beginning of function already,
1963   // allocate remained amount of registers we need.
1964   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
1965     State->AllocateReg(GPRArgRegs);
1966   // A byval parameter that is split between registers and memory needs its
1967   // size truncated here.
1968   // In the case where the entire structure fits in registers, we set the
1969   // size in memory to zero.
1970   Size = std::max<int>(Size - Excess, 0);
1971 }
1972
1973 /// MatchingStackOffset - Return true if the given stack call argument is
1974 /// already available in the same position (relatively) of the caller's
1975 /// incoming argument stack.
1976 static
1977 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
1978                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
1979                          const TargetInstrInfo *TII) {
1980   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
1981   int FI = INT_MAX;
1982   if (Arg.getOpcode() == ISD::CopyFromReg) {
1983     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
1984     if (!TargetRegisterInfo::isVirtualRegister(VR))
1985       return false;
1986     MachineInstr *Def = MRI->getVRegDef(VR);
1987     if (!Def)
1988       return false;
1989     if (!Flags.isByVal()) {
1990       if (!TII->isLoadFromStackSlot(Def, FI))
1991         return false;
1992     } else {
1993       return false;
1994     }
1995   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
1996     if (Flags.isByVal())
1997       // ByVal argument is passed in as a pointer but it's now being
1998       // dereferenced. e.g.
1999       // define @foo(%struct.X* %A) {
2000       //   tail call @bar(%struct.X* byval %A)
2001       // }
2002       return false;
2003     SDValue Ptr = Ld->getBasePtr();
2004     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2005     if (!FINode)
2006       return false;
2007     FI = FINode->getIndex();
2008   } else
2009     return false;
2010
2011   assert(FI != INT_MAX);
2012   if (!MFI->isFixedObjectIndex(FI))
2013     return false;
2014   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2015 }
2016
2017 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2018 /// for tail call optimization. Targets which want to do tail call
2019 /// optimization should implement this function.
2020 bool
2021 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2022                                                      CallingConv::ID CalleeCC,
2023                                                      bool isVarArg,
2024                                                      bool isCalleeStructRet,
2025                                                      bool isCallerStructRet,
2026                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2027                                     const SmallVectorImpl<SDValue> &OutVals,
2028                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2029                                                      SelectionDAG& DAG) const {
2030   const Function *CallerF = DAG.getMachineFunction().getFunction();
2031   CallingConv::ID CallerCC = CallerF->getCallingConv();
2032   bool CCMatch = CallerCC == CalleeCC;
2033
2034   // Look for obvious safe cases to perform tail call optimization that do not
2035   // require ABI changes. This is what gcc calls sibcall.
2036
2037   // Do not sibcall optimize vararg calls unless the call site is not passing
2038   // any arguments.
2039   if (isVarArg && !Outs.empty())
2040     return false;
2041
2042   // Exception-handling functions need a special set of instructions to indicate
2043   // a return to the hardware. Tail-calling another function would probably
2044   // break this.
2045   if (CallerF->hasFnAttribute("interrupt"))
2046     return false;
2047
2048   // Also avoid sibcall optimization if either caller or callee uses struct
2049   // return semantics.
2050   if (isCalleeStructRet || isCallerStructRet)
2051     return false;
2052
2053   // FIXME: Completely disable sibcall for Thumb1 since ThumbRegisterInfo::
2054   // emitEpilogue is not ready for them. Thumb tail calls also use t2B, as
2055   // the Thumb1 16-bit unconditional branch doesn't have sufficient relocation
2056   // support in the assembler and linker to be used. This would need to be
2057   // fixed to fully support tail calls in Thumb1.
2058   //
2059   // Doing this is tricky, since the LDM/POP instruction on Thumb doesn't take
2060   // LR.  This means if we need to reload LR, it takes an extra instructions,
2061   // which outweighs the value of the tail call; but here we don't know yet
2062   // whether LR is going to be used.  Probably the right approach is to
2063   // generate the tail call here and turn it back into CALL/RET in
2064   // emitEpilogue if LR is used.
2065
2066   // Thumb1 PIC calls to external symbols use BX, so they can be tail calls,
2067   // but we need to make sure there are enough registers; the only valid
2068   // registers are the 4 used for parameters.  We don't currently do this
2069   // case.
2070   if (Subtarget->isThumb1Only())
2071     return false;
2072
2073   // Externally-defined functions with weak linkage should not be
2074   // tail-called on ARM when the OS does not support dynamic
2075   // pre-emption of symbols, as the AAELF spec requires normal calls
2076   // to undefined weak functions to be replaced with a NOP or jump to the
2077   // next instruction. The behaviour of branch instructions in this
2078   // situation (as used for tail calls) is implementation-defined, so we
2079   // cannot rely on the linker replacing the tail call with a return.
2080   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2081     const GlobalValue *GV = G->getGlobal();
2082     const Triple &TT = getTargetMachine().getTargetTriple();
2083     if (GV->hasExternalWeakLinkage() &&
2084         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2085       return false;
2086   }
2087
2088   // If the calling conventions do not match, then we'd better make sure the
2089   // results are returned in the same way as what the caller expects.
2090   if (!CCMatch) {
2091     SmallVector<CCValAssign, 16> RVLocs1;
2092     ARMCCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2093                        *DAG.getContext(), Call);
2094     CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForNode(CalleeCC, true, isVarArg));
2095
2096     SmallVector<CCValAssign, 16> RVLocs2;
2097     ARMCCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2098                        *DAG.getContext(), Call);
2099     CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForNode(CallerCC, true, isVarArg));
2100
2101     if (RVLocs1.size() != RVLocs2.size())
2102       return false;
2103     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2104       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2105         return false;
2106       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2107         return false;
2108       if (RVLocs1[i].isRegLoc()) {
2109         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2110           return false;
2111       } else {
2112         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2113           return false;
2114       }
2115     }
2116   }
2117
2118   // If Caller's vararg or byval argument has been split between registers and
2119   // stack, do not perform tail call, since part of the argument is in caller's
2120   // local frame.
2121   const ARMFunctionInfo *AFI_Caller = DAG.getMachineFunction().
2122                                       getInfo<ARMFunctionInfo>();
2123   if (AFI_Caller->getArgRegsSaveSize())
2124     return false;
2125
2126   // If the callee takes no arguments then go on to check the results of the
2127   // call.
2128   if (!Outs.empty()) {
2129     // Check if stack adjustment is needed. For now, do not do this if any
2130     // argument is passed on the stack.
2131     SmallVector<CCValAssign, 16> ArgLocs;
2132     ARMCCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2133                       *DAG.getContext(), Call);
2134     CCInfo.AnalyzeCallOperands(Outs,
2135                                CCAssignFnForNode(CalleeCC, false, isVarArg));
2136     if (CCInfo.getNextStackOffset()) {
2137       MachineFunction &MF = DAG.getMachineFunction();
2138
2139       // Check if the arguments are already laid out in the right way as
2140       // the caller's fixed stack objects.
2141       MachineFrameInfo *MFI = MF.getFrameInfo();
2142       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2143       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2144       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2145            i != e;
2146            ++i, ++realArgIdx) {
2147         CCValAssign &VA = ArgLocs[i];
2148         EVT RegVT = VA.getLocVT();
2149         SDValue Arg = OutVals[realArgIdx];
2150         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2151         if (VA.getLocInfo() == CCValAssign::Indirect)
2152           return false;
2153         if (VA.needsCustom()) {
2154           // f64 and vector types are split into multiple registers or
2155           // register/stack-slot combinations.  The types will not match
2156           // the registers; give up on memory f64 refs until we figure
2157           // out what to do about this.
2158           if (!VA.isRegLoc())
2159             return false;
2160           if (!ArgLocs[++i].isRegLoc())
2161             return false;
2162           if (RegVT == MVT::v2f64) {
2163             if (!ArgLocs[++i].isRegLoc())
2164               return false;
2165             if (!ArgLocs[++i].isRegLoc())
2166               return false;
2167           }
2168         } else if (!VA.isRegLoc()) {
2169           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2170                                    MFI, MRI, TII))
2171             return false;
2172         }
2173       }
2174     }
2175   }
2176
2177   return true;
2178 }
2179
2180 bool
2181 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2182                                   MachineFunction &MF, bool isVarArg,
2183                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2184                                   LLVMContext &Context) const {
2185   SmallVector<CCValAssign, 16> RVLocs;
2186   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2187   return CCInfo.CheckReturn(Outs, CCAssignFnForNode(CallConv, /*Return=*/true,
2188                                                     isVarArg));
2189 }
2190
2191 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2192                                     SDLoc DL, SelectionDAG &DAG) {
2193   const MachineFunction &MF = DAG.getMachineFunction();
2194   const Function *F = MF.getFunction();
2195
2196   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2197
2198   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2199   // version of the "preferred return address". These offsets affect the return
2200   // instruction if this is a return from PL1 without hypervisor extensions.
2201   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2202   //    SWI:     0      "subs pc, lr, #0"
2203   //    ABORT:   +4     "subs pc, lr, #4"
2204   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2205   // UNDEF varies depending on where the exception came from ARM or Thumb
2206   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2207
2208   int64_t LROffset;
2209   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2210       IntKind == "ABORT")
2211     LROffset = 4;
2212   else if (IntKind == "SWI" || IntKind == "UNDEF")
2213     LROffset = 0;
2214   else
2215     report_fatal_error("Unsupported interrupt attribute. If present, value "
2216                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2217
2218   RetOps.insert(RetOps.begin() + 1,
2219                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2220
2221   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2222 }
2223
2224 SDValue
2225 ARMTargetLowering::LowerReturn(SDValue Chain,
2226                                CallingConv::ID CallConv, bool isVarArg,
2227                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2228                                const SmallVectorImpl<SDValue> &OutVals,
2229                                SDLoc dl, SelectionDAG &DAG) const {
2230
2231   // CCValAssign - represent the assignment of the return value to a location.
2232   SmallVector<CCValAssign, 16> RVLocs;
2233
2234   // CCState - Info about the registers and stack slots.
2235   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2236                     *DAG.getContext(), Call);
2237
2238   // Analyze outgoing return values.
2239   CCInfo.AnalyzeReturn(Outs, CCAssignFnForNode(CallConv, /* Return */ true,
2240                                                isVarArg));
2241
2242   SDValue Flag;
2243   SmallVector<SDValue, 4> RetOps;
2244   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2245   bool isLittleEndian = Subtarget->isLittle();
2246
2247   MachineFunction &MF = DAG.getMachineFunction();
2248   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2249   AFI->setReturnRegsCount(RVLocs.size());
2250
2251   // Copy the result values into the output registers.
2252   for (unsigned i = 0, realRVLocIdx = 0;
2253        i != RVLocs.size();
2254        ++i, ++realRVLocIdx) {
2255     CCValAssign &VA = RVLocs[i];
2256     assert(VA.isRegLoc() && "Can only return in registers!");
2257
2258     SDValue Arg = OutVals[realRVLocIdx];
2259
2260     switch (VA.getLocInfo()) {
2261     default: llvm_unreachable("Unknown loc info!");
2262     case CCValAssign::Full: break;
2263     case CCValAssign::BCvt:
2264       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2265       break;
2266     }
2267
2268     if (VA.needsCustom()) {
2269       if (VA.getLocVT() == MVT::v2f64) {
2270         // Extract the first half and return it in two registers.
2271         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2272                                    DAG.getConstant(0, dl, MVT::i32));
2273         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2274                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2275
2276         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2277                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2278                                  Flag);
2279         Flag = Chain.getValue(1);
2280         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2281         VA = RVLocs[++i]; // skip ahead to next loc
2282         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2283                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2284                                  Flag);
2285         Flag = Chain.getValue(1);
2286         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2287         VA = RVLocs[++i]; // skip ahead to next loc
2288
2289         // Extract the 2nd half and fall through to handle it as an f64 value.
2290         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2291                           DAG.getConstant(1, dl, MVT::i32));
2292       }
2293       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2294       // available.
2295       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2296                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2297       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2298                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2299                                Flag);
2300       Flag = Chain.getValue(1);
2301       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2302       VA = RVLocs[++i]; // skip ahead to next loc
2303       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2304                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2305                                Flag);
2306     } else
2307       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2308
2309     // Guarantee that all emitted copies are
2310     // stuck together, avoiding something bad.
2311     Flag = Chain.getValue(1);
2312     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2313   }
2314
2315   // Update chain and glue.
2316   RetOps[0] = Chain;
2317   if (Flag.getNode())
2318     RetOps.push_back(Flag);
2319
2320   // CPUs which aren't M-class use a special sequence to return from
2321   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2322   // though we use "subs pc, lr, #N").
2323   //
2324   // M-class CPUs actually use a normal return sequence with a special
2325   // (hardware-provided) value in LR, so the normal code path works.
2326   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2327       !Subtarget->isMClass()) {
2328     if (Subtarget->isThumb1Only())
2329       report_fatal_error("interrupt attribute is not supported in Thumb1");
2330     return LowerInterruptReturn(RetOps, dl, DAG);
2331   }
2332
2333   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2334 }
2335
2336 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2337   if (N->getNumValues() != 1)
2338     return false;
2339   if (!N->hasNUsesOfValue(1, 0))
2340     return false;
2341
2342   SDValue TCChain = Chain;
2343   SDNode *Copy = *N->use_begin();
2344   if (Copy->getOpcode() == ISD::CopyToReg) {
2345     // If the copy has a glue operand, we conservatively assume it isn't safe to
2346     // perform a tail call.
2347     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2348       return false;
2349     TCChain = Copy->getOperand(0);
2350   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2351     SDNode *VMov = Copy;
2352     // f64 returned in a pair of GPRs.
2353     SmallPtrSet<SDNode*, 2> Copies;
2354     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2355          UI != UE; ++UI) {
2356       if (UI->getOpcode() != ISD::CopyToReg)
2357         return false;
2358       Copies.insert(*UI);
2359     }
2360     if (Copies.size() > 2)
2361       return false;
2362
2363     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2364          UI != UE; ++UI) {
2365       SDValue UseChain = UI->getOperand(0);
2366       if (Copies.count(UseChain.getNode()))
2367         // Second CopyToReg
2368         Copy = *UI;
2369       else {
2370         // We are at the top of this chain.
2371         // If the copy has a glue operand, we conservatively assume it
2372         // isn't safe to perform a tail call.
2373         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2374           return false;
2375         // First CopyToReg
2376         TCChain = UseChain;
2377       }
2378     }
2379   } else if (Copy->getOpcode() == ISD::BITCAST) {
2380     // f32 returned in a single GPR.
2381     if (!Copy->hasOneUse())
2382       return false;
2383     Copy = *Copy->use_begin();
2384     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2385       return false;
2386     // If the copy has a glue operand, we conservatively assume it isn't safe to
2387     // perform a tail call.
2388     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2389       return false;
2390     TCChain = Copy->getOperand(0);
2391   } else {
2392     return false;
2393   }
2394
2395   bool HasRet = false;
2396   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2397        UI != UE; ++UI) {
2398     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2399         UI->getOpcode() != ARMISD::INTRET_FLAG)
2400       return false;
2401     HasRet = true;
2402   }
2403
2404   if (!HasRet)
2405     return false;
2406
2407   Chain = TCChain;
2408   return true;
2409 }
2410
2411 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2412   if (!Subtarget->supportsTailCall())
2413     return false;
2414
2415   auto Attr =
2416       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2417   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2418     return false;
2419
2420   return !Subtarget->isThumb1Only();
2421 }
2422
2423 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2424 // and pass the lower and high parts through.
2425 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2426   SDLoc DL(Op);
2427   SDValue WriteValue = Op->getOperand(2);
2428
2429   // This function is only supposed to be called for i64 type argument.
2430   assert(WriteValue.getValueType() == MVT::i64
2431           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2432
2433   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2434                            DAG.getConstant(0, DL, MVT::i32));
2435   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2436                            DAG.getConstant(1, DL, MVT::i32));
2437   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2438   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2439 }
2440
2441 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2442 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2443 // one of the above mentioned nodes. It has to be wrapped because otherwise
2444 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2445 // be used to form addressing mode. These wrapped nodes will be selected
2446 // into MOVi.
2447 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2448   EVT PtrVT = Op.getValueType();
2449   // FIXME there is no actual debug info here
2450   SDLoc dl(Op);
2451   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2452   SDValue Res;
2453   if (CP->isMachineConstantPoolEntry())
2454     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2455                                     CP->getAlignment());
2456   else
2457     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2458                                     CP->getAlignment());
2459   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2460 }
2461
2462 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2463   return MachineJumpTableInfo::EK_Inline;
2464 }
2465
2466 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2467                                              SelectionDAG &DAG) const {
2468   MachineFunction &MF = DAG.getMachineFunction();
2469   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2470   unsigned ARMPCLabelIndex = 0;
2471   SDLoc DL(Op);
2472   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2473   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2474   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2475   SDValue CPAddr;
2476   if (RelocM == Reloc::Static) {
2477     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2478   } else {
2479     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2480     ARMPCLabelIndex = AFI->createPICLabelUId();
2481     ARMConstantPoolValue *CPV =
2482       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2483                                       ARMCP::CPBlockAddress, PCAdj);
2484     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2485   }
2486   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2487   SDValue Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), CPAddr,
2488                                MachinePointerInfo::getConstantPool(),
2489                                false, false, false, 0);
2490   if (RelocM == Reloc::Static)
2491     return Result;
2492   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2493   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2494 }
2495
2496 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2497 SDValue
2498 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2499                                                  SelectionDAG &DAG) const {
2500   SDLoc dl(GA);
2501   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2502   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2503   MachineFunction &MF = DAG.getMachineFunction();
2504   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2505   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2506   ARMConstantPoolValue *CPV =
2507     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2508                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2509   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2510   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2511   Argument = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Argument,
2512                          MachinePointerInfo::getConstantPool(),
2513                          false, false, false, 0);
2514   SDValue Chain = Argument.getValue(1);
2515
2516   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2517   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2518
2519   // call __tls_get_addr.
2520   ArgListTy Args;
2521   ArgListEntry Entry;
2522   Entry.Node = Argument;
2523   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2524   Args.push_back(Entry);
2525
2526   // FIXME: is there useful debug info available here?
2527   TargetLowering::CallLoweringInfo CLI(DAG);
2528   CLI.setDebugLoc(dl).setChain(Chain)
2529     .setCallee(CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2530                DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args),
2531                0);
2532
2533   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2534   return CallResult.first;
2535 }
2536
2537 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2538 // "local exec" model.
2539 SDValue
2540 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2541                                         SelectionDAG &DAG,
2542                                         TLSModel::Model model) const {
2543   const GlobalValue *GV = GA->getGlobal();
2544   SDLoc dl(GA);
2545   SDValue Offset;
2546   SDValue Chain = DAG.getEntryNode();
2547   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2548   // Get the Thread Pointer
2549   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2550
2551   if (model == TLSModel::InitialExec) {
2552     MachineFunction &MF = DAG.getMachineFunction();
2553     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2554     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2555     // Initial exec model.
2556     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2557     ARMConstantPoolValue *CPV =
2558       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2559                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2560                                       true);
2561     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2562     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2563     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2564                          MachinePointerInfo::getConstantPool(),
2565                          false, false, false, 0);
2566     Chain = Offset.getValue(1);
2567
2568     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2569     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2570
2571     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2572                          MachinePointerInfo::getConstantPool(),
2573                          false, false, false, 0);
2574   } else {
2575     // local exec model
2576     assert(model == TLSModel::LocalExec);
2577     ARMConstantPoolValue *CPV =
2578       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2579     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2580     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2581     Offset = DAG.getLoad(PtrVT, dl, Chain, Offset,
2582                          MachinePointerInfo::getConstantPool(),
2583                          false, false, false, 0);
2584   }
2585
2586   // The address of the thread local variable is the add of the thread
2587   // pointer with the offset of the variable.
2588   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2589 }
2590
2591 SDValue
2592 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2593   // TODO: implement the "local dynamic" model
2594   assert(Subtarget->isTargetELF() &&
2595          "TLS not implemented for non-ELF targets");
2596   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2597   if (DAG.getTarget().Options.EmulatedTLS)
2598     return LowerToTLSEmulatedModel(GA, DAG);
2599
2600   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2601
2602   switch (model) {
2603     case TLSModel::GeneralDynamic:
2604     case TLSModel::LocalDynamic:
2605       return LowerToTLSGeneralDynamicModel(GA, DAG);
2606     case TLSModel::InitialExec:
2607     case TLSModel::LocalExec:
2608       return LowerToTLSExecModels(GA, DAG, model);
2609   }
2610   llvm_unreachable("bogus TLS model");
2611 }
2612
2613 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
2614                                                  SelectionDAG &DAG) const {
2615   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2616   SDLoc dl(Op);
2617   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2618   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2619     bool UseGOTOFF = GV->hasLocalLinkage() || GV->hasHiddenVisibility();
2620     ARMConstantPoolValue *CPV =
2621       ARMConstantPoolConstant::Create(GV,
2622                                       UseGOTOFF ? ARMCP::GOTOFF : ARMCP::GOT);
2623     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2624     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2625     SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
2626                                  CPAddr,
2627                                  MachinePointerInfo::getConstantPool(),
2628                                  false, false, false, 0);
2629     SDValue Chain = Result.getValue(1);
2630     SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(PtrVT);
2631     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result, GOT);
2632     if (!UseGOTOFF)
2633       Result = DAG.getLoad(PtrVT, dl, Chain, Result,
2634                            MachinePointerInfo::getGOT(),
2635                            false, false, false, 0);
2636     return Result;
2637   }
2638
2639   // If we have T2 ops, we can materialize the address directly via movt/movw
2640   // pair. This is always cheaper.
2641   if (Subtarget->useMovt(DAG.getMachineFunction())) {
2642     ++NumMovwMovt;
2643     // FIXME: Once remat is capable of dealing with instructions with register
2644     // operands, expand this into two nodes.
2645     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
2646                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
2647   } else {
2648     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
2649     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2650     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2651                        MachinePointerInfo::getConstantPool(),
2652                        false, false, false, 0);
2653   }
2654 }
2655
2656 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
2657                                                     SelectionDAG &DAG) const {
2658   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2659   SDLoc dl(Op);
2660   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2661   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2662
2663   if (Subtarget->useMovt(DAG.getMachineFunction()))
2664     ++NumMovwMovt;
2665
2666   // FIXME: Once remat is capable of dealing with instructions with register
2667   // operands, expand this into multiple nodes
2668   unsigned Wrapper =
2669       RelocM == Reloc::PIC_ ? ARMISD::WrapperPIC : ARMISD::Wrapper;
2670
2671   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
2672   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
2673
2674   if (Subtarget->GVIsIndirectSymbol(GV, RelocM))
2675     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
2676                          MachinePointerInfo::getGOT(), false, false, false, 0);
2677   return Result;
2678 }
2679
2680 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
2681                                                      SelectionDAG &DAG) const {
2682   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
2683   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
2684          "Windows on ARM expects to use movw/movt");
2685
2686   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2687   const ARMII::TOF TargetFlags =
2688     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
2689   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2690   SDValue Result;
2691   SDLoc DL(Op);
2692
2693   ++NumMovwMovt;
2694
2695   // FIXME: Once remat is capable of dealing with instructions with register
2696   // operands, expand this into two nodes.
2697   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
2698                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
2699                                                   TargetFlags));
2700   if (GV->hasDLLImportStorageClass())
2701     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
2702                          MachinePointerInfo::getGOT(), false, false, false, 0);
2703   return Result;
2704 }
2705
2706 SDValue ARMTargetLowering::LowerGLOBAL_OFFSET_TABLE(SDValue Op,
2707                                                     SelectionDAG &DAG) const {
2708   assert(Subtarget->isTargetELF() &&
2709          "GLOBAL OFFSET TABLE not implemented for non-ELF targets");
2710   MachineFunction &MF = DAG.getMachineFunction();
2711   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2712   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2713   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2714   SDLoc dl(Op);
2715   unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2716   ARMConstantPoolValue *CPV =
2717     ARMConstantPoolSymbol::Create(*DAG.getContext(), "_GLOBAL_OFFSET_TABLE_",
2718                                   ARMPCLabelIndex, PCAdj);
2719   SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2720   CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2721   SDValue Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2722                                MachinePointerInfo::getConstantPool(),
2723                                false, false, false, 0);
2724   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2725   return DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2726 }
2727
2728 SDValue
2729 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
2730   SDLoc dl(Op);
2731   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
2732   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
2733                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
2734                      Op.getOperand(1), Val);
2735 }
2736
2737 SDValue
2738 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
2739   SDLoc dl(Op);
2740   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
2741                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
2742 }
2743
2744 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
2745                                                       SelectionDAG &DAG) const {
2746   SDLoc dl(Op);
2747   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
2748                      Op.getOperand(0));
2749 }
2750
2751 SDValue
2752 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
2753                                           const ARMSubtarget *Subtarget) const {
2754   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2755   SDLoc dl(Op);
2756   switch (IntNo) {
2757   default: return SDValue();    // Don't custom lower most intrinsics.
2758   case Intrinsic::arm_rbit: {
2759     assert(Op.getOperand(1).getValueType() == MVT::i32 &&
2760            "RBIT intrinsic must have i32 type!");
2761     return DAG.getNode(ARMISD::RBIT, dl, MVT::i32, Op.getOperand(1));
2762   }
2763   case Intrinsic::arm_thread_pointer: {
2764     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2765     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2766   }
2767   case Intrinsic::eh_sjlj_lsda: {
2768     MachineFunction &MF = DAG.getMachineFunction();
2769     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2770     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2771     EVT PtrVT = getPointerTy(DAG.getDataLayout());
2772     Reloc::Model RelocM = getTargetMachine().getRelocationModel();
2773     SDValue CPAddr;
2774     unsigned PCAdj = (RelocM != Reloc::PIC_)
2775       ? 0 : (Subtarget->isThumb() ? 4 : 8);
2776     ARMConstantPoolValue *CPV =
2777       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
2778                                       ARMCP::CPLSDA, PCAdj);
2779     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2780     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2781     SDValue Result =
2782       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), CPAddr,
2783                   MachinePointerInfo::getConstantPool(),
2784                   false, false, false, 0);
2785
2786     if (RelocM == Reloc::PIC_) {
2787       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2788       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
2789     }
2790     return Result;
2791   }
2792   case Intrinsic::arm_neon_vmulls:
2793   case Intrinsic::arm_neon_vmullu: {
2794     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
2795       ? ARMISD::VMULLs : ARMISD::VMULLu;
2796     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2797                        Op.getOperand(1), Op.getOperand(2));
2798   }
2799   case Intrinsic::arm_neon_vminnm:
2800   case Intrinsic::arm_neon_vmaxnm: {
2801     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
2802       ? ISD::FMINNUM : ISD::FMAXNUM;
2803     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
2804                        Op.getOperand(1), Op.getOperand(2));
2805   }
2806   }
2807 }
2808
2809 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
2810                                  const ARMSubtarget *Subtarget) {
2811   // FIXME: handle "fence singlethread" more efficiently.
2812   SDLoc dl(Op);
2813   if (!Subtarget->hasDataBarrier()) {
2814     // Some ARMv6 cpus can support data barriers with an mcr instruction.
2815     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
2816     // here.
2817     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
2818            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
2819     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
2820                        DAG.getConstant(0, dl, MVT::i32));
2821   }
2822
2823   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
2824   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
2825   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
2826   if (Subtarget->isMClass()) {
2827     // Only a full system barrier exists in the M-class architectures.
2828     Domain = ARM_MB::SY;
2829   } else if (Subtarget->isSwift() && Ord == Release) {
2830     // Swift happens to implement ISHST barriers in a way that's compatible with
2831     // Release semantics but weaker than ISH so we'd be fools not to use
2832     // it. Beware: other processors probably don't!
2833     Domain = ARM_MB::ISHST;
2834   }
2835
2836   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
2837                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
2838                      DAG.getConstant(Domain, dl, MVT::i32));
2839 }
2840
2841 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
2842                              const ARMSubtarget *Subtarget) {
2843   // ARM pre v5TE and Thumb1 does not have preload instructions.
2844   if (!(Subtarget->isThumb2() ||
2845         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
2846     // Just preserve the chain.
2847     return Op.getOperand(0);
2848
2849   SDLoc dl(Op);
2850   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
2851   if (!isRead &&
2852       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
2853     // ARMv7 with MP extension has PLDW.
2854     return Op.getOperand(0);
2855
2856   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2857   if (Subtarget->isThumb()) {
2858     // Invert the bits.
2859     isRead = ~isRead & 1;
2860     isData = ~isData & 1;
2861   }
2862
2863   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
2864                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
2865                      DAG.getConstant(isData, dl, MVT::i32));
2866 }
2867
2868 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
2869   MachineFunction &MF = DAG.getMachineFunction();
2870   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
2871
2872   // vastart just stores the address of the VarArgsFrameIndex slot into the
2873   // memory location argument.
2874   SDLoc dl(Op);
2875   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2876   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2877   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2878   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2879                       MachinePointerInfo(SV), false, false, 0);
2880 }
2881
2882 SDValue
2883 ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA, CCValAssign &NextVA,
2884                                         SDValue &Root, SelectionDAG &DAG,
2885                                         SDLoc dl) const {
2886   MachineFunction &MF = DAG.getMachineFunction();
2887   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2888
2889   const TargetRegisterClass *RC;
2890   if (AFI->isThumb1OnlyFunction())
2891     RC = &ARM::tGPRRegClass;
2892   else
2893     RC = &ARM::GPRRegClass;
2894
2895   // Transform the arguments stored in physical registers into virtual ones.
2896   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2897   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2898
2899   SDValue ArgValue2;
2900   if (NextVA.isMemLoc()) {
2901     MachineFrameInfo *MFI = MF.getFrameInfo();
2902     int FI = MFI->CreateFixedObject(4, NextVA.getLocMemOffset(), true);
2903
2904     // Create load node to retrieve arguments from the stack.
2905     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2906     ArgValue2 = DAG.getLoad(MVT::i32, dl, Root, FIN,
2907                             MachinePointerInfo::getFixedStack(FI),
2908                             false, false, false, 0);
2909   } else {
2910     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
2911     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
2912   }
2913   if (!Subtarget->isLittle())
2914     std::swap (ArgValue, ArgValue2);
2915   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
2916 }
2917
2918 // The remaining GPRs hold either the beginning of variable-argument
2919 // data, or the beginning of an aggregate passed by value (usually
2920 // byval).  Either way, we allocate stack slots adjacent to the data
2921 // provided by our caller, and store the unallocated registers there.
2922 // If this is a variadic function, the va_list pointer will begin with
2923 // these values; otherwise, this reassembles a (byval) structure that
2924 // was split between registers and memory.
2925 // Return: The frame index registers were stored into.
2926 int
2927 ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
2928                                   SDLoc dl, SDValue &Chain,
2929                                   const Value *OrigArg,
2930                                   unsigned InRegsParamRecordIdx,
2931                                   int ArgOffset,
2932                                   unsigned ArgSize) const {
2933   // Currently, two use-cases possible:
2934   // Case #1. Non-var-args function, and we meet first byval parameter.
2935   //          Setup first unallocated register as first byval register;
2936   //          eat all remained registers
2937   //          (these two actions are performed by HandleByVal method).
2938   //          Then, here, we initialize stack frame with
2939   //          "store-reg" instructions.
2940   // Case #2. Var-args function, that doesn't contain byval parameters.
2941   //          The same: eat all remained unallocated registers,
2942   //          initialize stack frame.
2943
2944   MachineFunction &MF = DAG.getMachineFunction();
2945   MachineFrameInfo *MFI = MF.getFrameInfo();
2946   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2947   unsigned RBegin, REnd;
2948   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
2949     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
2950   } else {
2951     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
2952     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
2953     REnd = ARM::R4;
2954   }
2955
2956   if (REnd != RBegin)
2957     ArgOffset = -4 * (ARM::R4 - RBegin);
2958
2959   auto PtrVT = getPointerTy(DAG.getDataLayout());
2960   int FrameIndex = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2961   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
2962
2963   SmallVector<SDValue, 4> MemOps;
2964   const TargetRegisterClass *RC =
2965       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
2966
2967   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
2968     unsigned VReg = MF.addLiveIn(Reg, RC);
2969     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2970     SDValue Store =
2971         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2972                      MachinePointerInfo(OrigArg, 4 * i), false, false, 0);
2973     MemOps.push_back(Store);
2974     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
2975   }
2976
2977   if (!MemOps.empty())
2978     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2979   return FrameIndex;
2980 }
2981
2982 // Setup stack frame, the va_list pointer will start from.
2983 void
2984 ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
2985                                         SDLoc dl, SDValue &Chain,
2986                                         unsigned ArgOffset,
2987                                         unsigned TotalArgRegsSaveSize,
2988                                         bool ForceMutable) const {
2989   MachineFunction &MF = DAG.getMachineFunction();
2990   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2991
2992   // Try to store any remaining integer argument regs
2993   // to their spots on the stack so that they may be loaded by deferencing
2994   // the result of va_next.
2995   // If there is no regs to be stored, just point address after last
2996   // argument passed via stack.
2997   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
2998                                   CCInfo.getInRegsParamsCount(),
2999                                   CCInfo.getNextStackOffset(), 4);
3000   AFI->setVarArgsFrameIndex(FrameIndex);
3001 }
3002
3003 SDValue
3004 ARMTargetLowering::LowerFormalArguments(SDValue Chain,
3005                                         CallingConv::ID CallConv, bool isVarArg,
3006                                         const SmallVectorImpl<ISD::InputArg>
3007                                           &Ins,
3008                                         SDLoc dl, SelectionDAG &DAG,
3009                                         SmallVectorImpl<SDValue> &InVals)
3010                                           const {
3011   MachineFunction &MF = DAG.getMachineFunction();
3012   MachineFrameInfo *MFI = MF.getFrameInfo();
3013
3014   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3015
3016   // Assign locations to all of the incoming arguments.
3017   SmallVector<CCValAssign, 16> ArgLocs;
3018   ARMCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3019                     *DAG.getContext(), Prologue);
3020   CCInfo.AnalyzeFormalArguments(Ins,
3021                                 CCAssignFnForNode(CallConv, /* Return*/ false,
3022                                                   isVarArg));
3023
3024   SmallVector<SDValue, 16> ArgValues;
3025   SDValue ArgValue;
3026   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3027   unsigned CurArgIdx = 0;
3028
3029   // Initially ArgRegsSaveSize is zero.
3030   // Then we increase this value each time we meet byval parameter.
3031   // We also increase this value in case of varargs function.
3032   AFI->setArgRegsSaveSize(0);
3033
3034   // Calculate the amount of stack space that we need to allocate to store
3035   // byval and variadic arguments that are passed in registers.
3036   // We need to know this before we allocate the first byval or variadic
3037   // argument, as they will be allocated a stack slot below the CFA (Canonical
3038   // Frame Address, the stack pointer at entry to the function).
3039   unsigned ArgRegBegin = ARM::R4;
3040   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3041     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3042       break;
3043
3044     CCValAssign &VA = ArgLocs[i];
3045     unsigned Index = VA.getValNo();
3046     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3047     if (!Flags.isByVal())
3048       continue;
3049
3050     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3051     unsigned RBegin, REnd;
3052     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3053     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3054
3055     CCInfo.nextInRegsParam();
3056   }
3057   CCInfo.rewindByValRegsInfo();
3058
3059   int lastInsIndex = -1;
3060   if (isVarArg && MFI->hasVAStart()) {
3061     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3062     if (RegIdx != array_lengthof(GPRArgRegs))
3063       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3064   }
3065
3066   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3067   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3068   auto PtrVT = getPointerTy(DAG.getDataLayout());
3069
3070   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3071     CCValAssign &VA = ArgLocs[i];
3072     if (Ins[VA.getValNo()].isOrigArg()) {
3073       std::advance(CurOrigArg,
3074                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3075       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3076     }
3077     // Arguments stored in registers.
3078     if (VA.isRegLoc()) {
3079       EVT RegVT = VA.getLocVT();
3080
3081       if (VA.needsCustom()) {
3082         // f64 and vector types are split up into multiple registers or
3083         // combinations of registers and stack slots.
3084         if (VA.getLocVT() == MVT::v2f64) {
3085           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3086                                                    Chain, DAG, dl);
3087           VA = ArgLocs[++i]; // skip ahead to next loc
3088           SDValue ArgValue2;
3089           if (VA.isMemLoc()) {
3090             int FI = MFI->CreateFixedObject(8, VA.getLocMemOffset(), true);
3091             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3092             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3093                                     MachinePointerInfo::getFixedStack(FI),
3094                                     false, false, false, 0);
3095           } else {
3096             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3097                                              Chain, DAG, dl);
3098           }
3099           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3100           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3101                                  ArgValue, ArgValue1,
3102                                  DAG.getIntPtrConstant(0, dl));
3103           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3104                                  ArgValue, ArgValue2,
3105                                  DAG.getIntPtrConstant(1, dl));
3106         } else
3107           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3108
3109       } else {
3110         const TargetRegisterClass *RC;
3111
3112         if (RegVT == MVT::f32)
3113           RC = &ARM::SPRRegClass;
3114         else if (RegVT == MVT::f64)
3115           RC = &ARM::DPRRegClass;
3116         else if (RegVT == MVT::v2f64)
3117           RC = &ARM::QPRRegClass;
3118         else if (RegVT == MVT::i32)
3119           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3120                                            : &ARM::GPRRegClass;
3121         else
3122           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3123
3124         // Transform the arguments in physical registers into virtual ones.
3125         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3126         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3127       }
3128
3129       // If this is an 8 or 16-bit value, it is really passed promoted
3130       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3131       // truncate to the right size.
3132       switch (VA.getLocInfo()) {
3133       default: llvm_unreachable("Unknown loc info!");
3134       case CCValAssign::Full: break;
3135       case CCValAssign::BCvt:
3136         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3137         break;
3138       case CCValAssign::SExt:
3139         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3140                                DAG.getValueType(VA.getValVT()));
3141         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3142         break;
3143       case CCValAssign::ZExt:
3144         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3145                                DAG.getValueType(VA.getValVT()));
3146         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3147         break;
3148       }
3149
3150       InVals.push_back(ArgValue);
3151
3152     } else { // VA.isRegLoc()
3153
3154       // sanity check
3155       assert(VA.isMemLoc());
3156       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3157
3158       int index = VA.getValNo();
3159
3160       // Some Ins[] entries become multiple ArgLoc[] entries.
3161       // Process them only once.
3162       if (index != lastInsIndex)
3163         {
3164           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3165           // FIXME: For now, all byval parameter objects are marked mutable.
3166           // This can be changed with more analysis.
3167           // In case of tail call optimization mark all arguments mutable.
3168           // Since they could be overwritten by lowering of arguments in case of
3169           // a tail call.
3170           if (Flags.isByVal()) {
3171             assert(Ins[index].isOrigArg() &&
3172                    "Byval arguments cannot be implicit");
3173             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3174
3175             int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, CurOrigArg,
3176                                             CurByValIndex, VA.getLocMemOffset(),
3177                                             Flags.getByValSize());
3178             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3179             CCInfo.nextInRegsParam();
3180           } else {
3181             unsigned FIOffset = VA.getLocMemOffset();
3182             int FI = MFI->CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3183                                             FIOffset, true);
3184
3185             // Create load nodes to retrieve arguments from the stack.
3186             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3187             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3188                                          MachinePointerInfo::getFixedStack(FI),
3189                                          false, false, false, 0));
3190           }
3191           lastInsIndex = index;
3192         }
3193     }
3194   }
3195
3196   // varargs
3197   if (isVarArg && MFI->hasVAStart())
3198     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3199                          CCInfo.getNextStackOffset(),
3200                          TotalArgRegsSaveSize);
3201
3202   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3203
3204   return Chain;
3205 }
3206
3207 /// isFloatingPointZero - Return true if this is +0.0.
3208 static bool isFloatingPointZero(SDValue Op) {
3209   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3210     return CFP->getValueAPF().isPosZero();
3211   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3212     // Maybe this has already been legalized into the constant pool?
3213     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3214       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3215       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3216         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3217           return CFP->getValueAPF().isPosZero();
3218     }
3219   } else if (Op->getOpcode() == ISD::BITCAST &&
3220              Op->getValueType(0) == MVT::f64) {
3221     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3222     // created by LowerConstantFP().
3223     SDValue BitcastOp = Op->getOperand(0);
3224     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM) {
3225       SDValue MoveOp = BitcastOp->getOperand(0);
3226       if (MoveOp->getOpcode() == ISD::TargetConstant &&
3227           cast<ConstantSDNode>(MoveOp)->getZExtValue() == 0) {
3228         return true;
3229       }
3230     }
3231   }
3232   return false;
3233 }
3234
3235 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3236 /// the given operands.
3237 SDValue
3238 ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3239                              SDValue &ARMcc, SelectionDAG &DAG,
3240                              SDLoc dl) const {
3241   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3242     unsigned C = RHSC->getZExtValue();
3243     if (!isLegalICmpImmediate(C)) {
3244       // Constant does not fit, try adjusting it by one?
3245       switch (CC) {
3246       default: break;
3247       case ISD::SETLT:
3248       case ISD::SETGE:
3249         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3250           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3251           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3252         }
3253         break;
3254       case ISD::SETULT:
3255       case ISD::SETUGE:
3256         if (C != 0 && isLegalICmpImmediate(C-1)) {
3257           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3258           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3259         }
3260         break;
3261       case ISD::SETLE:
3262       case ISD::SETGT:
3263         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3264           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3265           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3266         }
3267         break;
3268       case ISD::SETULE:
3269       case ISD::SETUGT:
3270         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3271           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3272           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3273         }
3274         break;
3275       }
3276     }
3277   }
3278
3279   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3280   ARMISD::NodeType CompareType;
3281   switch (CondCode) {
3282   default:
3283     CompareType = ARMISD::CMP;
3284     break;
3285   case ARMCC::EQ:
3286   case ARMCC::NE:
3287     // Uses only Z Flag
3288     CompareType = ARMISD::CMPZ;
3289     break;
3290   }
3291   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3292   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3293 }
3294
3295 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3296 SDValue
3297 ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS, SelectionDAG &DAG,
3298                              SDLoc dl) const {
3299   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3300   SDValue Cmp;
3301   if (!isFloatingPointZero(RHS))
3302     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS);
3303   else
3304     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS);
3305   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3306 }
3307
3308 /// duplicateCmp - Glue values can have only one use, so this function
3309 /// duplicates a comparison node.
3310 SDValue
3311 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3312   unsigned Opc = Cmp.getOpcode();
3313   SDLoc DL(Cmp);
3314   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3315     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3316
3317   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3318   Cmp = Cmp.getOperand(0);
3319   Opc = Cmp.getOpcode();
3320   if (Opc == ARMISD::CMPFP)
3321     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3322   else {
3323     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3324     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0));
3325   }
3326   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3327 }
3328
3329 std::pair<SDValue, SDValue>
3330 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3331                                  SDValue &ARMcc) const {
3332   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3333
3334   SDValue Value, OverflowCmp;
3335   SDValue LHS = Op.getOperand(0);
3336   SDValue RHS = Op.getOperand(1);
3337   SDLoc dl(Op);
3338
3339   // FIXME: We are currently always generating CMPs because we don't support
3340   // generating CMN through the backend. This is not as good as the natural
3341   // CMP case because it causes a register dependency and cannot be folded
3342   // later.
3343
3344   switch (Op.getOpcode()) {
3345   default:
3346     llvm_unreachable("Unknown overflow instruction!");
3347   case ISD::SADDO:
3348     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3349     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3350     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3351     break;
3352   case ISD::UADDO:
3353     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3354     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3355     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3356     break;
3357   case ISD::SSUBO:
3358     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3359     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3360     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3361     break;
3362   case ISD::USUBO:
3363     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3364     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3365     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3366     break;
3367   } // switch (...)
3368
3369   return std::make_pair(Value, OverflowCmp);
3370 }
3371
3372
3373 SDValue
3374 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3375   // Let legalize expand this if it isn't a legal type yet.
3376   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3377     return SDValue();
3378
3379   SDValue Value, OverflowCmp;
3380   SDValue ARMcc;
3381   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3382   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3383   SDLoc dl(Op);
3384   // We use 0 and 1 as false and true values.
3385   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3386   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3387   EVT VT = Op.getValueType();
3388
3389   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3390                                  ARMcc, CCR, OverflowCmp);
3391
3392   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3393   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3394 }
3395
3396
3397 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3398   SDValue Cond = Op.getOperand(0);
3399   SDValue SelectTrue = Op.getOperand(1);
3400   SDValue SelectFalse = Op.getOperand(2);
3401   SDLoc dl(Op);
3402   unsigned Opc = Cond.getOpcode();
3403
3404   if (Cond.getResNo() == 1 &&
3405       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3406        Opc == ISD::USUBO)) {
3407     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3408       return SDValue();
3409
3410     SDValue Value, OverflowCmp;
3411     SDValue ARMcc;
3412     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3413     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3414     EVT VT = Op.getValueType();
3415
3416     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3417                    OverflowCmp, DAG);
3418   }
3419
3420   // Convert:
3421   //
3422   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3423   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3424   //
3425   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3426     const ConstantSDNode *CMOVTrue =
3427       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3428     const ConstantSDNode *CMOVFalse =
3429       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3430
3431     if (CMOVTrue && CMOVFalse) {
3432       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3433       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3434
3435       SDValue True;
3436       SDValue False;
3437       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3438         True = SelectTrue;
3439         False = SelectFalse;
3440       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3441         True = SelectFalse;
3442         False = SelectTrue;
3443       }
3444
3445       if (True.getNode() && False.getNode()) {
3446         EVT VT = Op.getValueType();
3447         SDValue ARMcc = Cond.getOperand(2);
3448         SDValue CCR = Cond.getOperand(3);
3449         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3450         assert(True.getValueType() == VT);
3451         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3452       }
3453     }
3454   }
3455
3456   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3457   // undefined bits before doing a full-word comparison with zero.
3458   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3459                      DAG.getConstant(1, dl, Cond.getValueType()));
3460
3461   return DAG.getSelectCC(dl, Cond,
3462                          DAG.getConstant(0, dl, Cond.getValueType()),
3463                          SelectTrue, SelectFalse, ISD::SETNE);
3464 }
3465
3466 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3467                                  bool &swpCmpOps, bool &swpVselOps) {
3468   // Start by selecting the GE condition code for opcodes that return true for
3469   // 'equality'
3470   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
3471       CC == ISD::SETULE)
3472     CondCode = ARMCC::GE;
3473
3474   // and GT for opcodes that return false for 'equality'.
3475   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
3476            CC == ISD::SETULT)
3477     CondCode = ARMCC::GT;
3478
3479   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
3480   // to swap the compare operands.
3481   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
3482       CC == ISD::SETULT)
3483     swpCmpOps = true;
3484
3485   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
3486   // If we have an unordered opcode, we need to swap the operands to the VSEL
3487   // instruction (effectively negating the condition).
3488   //
3489   // This also has the effect of swapping which one of 'less' or 'greater'
3490   // returns true, so we also swap the compare operands. It also switches
3491   // whether we return true for 'equality', so we compensate by picking the
3492   // opposite condition code to our original choice.
3493   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
3494       CC == ISD::SETUGT) {
3495     swpCmpOps = !swpCmpOps;
3496     swpVselOps = !swpVselOps;
3497     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
3498   }
3499
3500   // 'ordered' is 'anything but unordered', so use the VS condition code and
3501   // swap the VSEL operands.
3502   if (CC == ISD::SETO) {
3503     CondCode = ARMCC::VS;
3504     swpVselOps = true;
3505   }
3506
3507   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
3508   // code and swap the VSEL operands.
3509   if (CC == ISD::SETUNE) {
3510     CondCode = ARMCC::EQ;
3511     swpVselOps = true;
3512   }
3513 }
3514
3515 SDValue ARMTargetLowering::getCMOV(SDLoc dl, EVT VT, SDValue FalseVal,
3516                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
3517                                    SDValue Cmp, SelectionDAG &DAG) const {
3518   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
3519     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3520                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
3521     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
3522                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
3523
3524     SDValue TrueLow = TrueVal.getValue(0);
3525     SDValue TrueHigh = TrueVal.getValue(1);
3526     SDValue FalseLow = FalseVal.getValue(0);
3527     SDValue FalseHigh = FalseVal.getValue(1);
3528
3529     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
3530                               ARMcc, CCR, Cmp);
3531     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
3532                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
3533
3534     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
3535   } else {
3536     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
3537                        Cmp);
3538   }
3539 }
3540
3541 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3542   EVT VT = Op.getValueType();
3543   SDValue LHS = Op.getOperand(0);
3544   SDValue RHS = Op.getOperand(1);
3545   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3546   SDValue TrueVal = Op.getOperand(2);
3547   SDValue FalseVal = Op.getOperand(3);
3548   SDLoc dl(Op);
3549
3550   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3551     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3552                                                     dl);
3553
3554     // If softenSetCCOperands only returned one value, we should compare it to
3555     // zero.
3556     if (!RHS.getNode()) {
3557       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3558       CC = ISD::SETNE;
3559     }
3560   }
3561
3562   if (LHS.getValueType() == MVT::i32) {
3563     // Try to generate VSEL on ARMv8.
3564     // The VSEL instruction can't use all the usual ARM condition
3565     // codes: it only has two bits to select the condition code, so it's
3566     // constrained to use only GE, GT, VS and EQ.
3567     //
3568     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
3569     // swap the operands of the previous compare instruction (effectively
3570     // inverting the compare condition, swapping 'less' and 'greater') and
3571     // sometimes need to swap the operands to the VSEL (which inverts the
3572     // condition in the sense of firing whenever the previous condition didn't)
3573     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3574                                     TrueVal.getValueType() == MVT::f64)) {
3575       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3576       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
3577           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
3578         CC = ISD::getSetCCInverse(CC, true);
3579         std::swap(TrueVal, FalseVal);
3580       }
3581     }
3582
3583     SDValue ARMcc;
3584     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3585     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3586     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3587   }
3588
3589   ARMCC::CondCodes CondCode, CondCode2;
3590   FPCCToARMCC(CC, CondCode, CondCode2);
3591
3592   // Try to generate VMAXNM/VMINNM on ARMv8.
3593   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
3594                                   TrueVal.getValueType() == MVT::f64)) {
3595     // We can use VMAXNM/VMINNM for a compare followed by a select with the
3596     // same operands, as follows:
3597     //   c = fcmp [?gt, ?ge, ?lt, ?le] a, b
3598     //   select c, a, b
3599     // In NoNaNsFPMath the CC will have been changed from, e.g., 'ogt' to 'gt'.
3600     bool swapSides = false;
3601     if (!getTargetMachine().Options.NoNaNsFPMath) {
3602       // transformability may depend on which way around we compare
3603       switch (CC) {
3604       default:
3605         break;
3606       case ISD::SETOGT:
3607       case ISD::SETOGE:
3608       case ISD::SETOLT:
3609       case ISD::SETOLE:
3610         // the non-NaN should be RHS
3611         swapSides = DAG.isKnownNeverNaN(LHS) && !DAG.isKnownNeverNaN(RHS);
3612         break;
3613       case ISD::SETUGT:
3614       case ISD::SETUGE:
3615       case ISD::SETULT:
3616       case ISD::SETULE:
3617         // the non-NaN should be LHS
3618         swapSides = DAG.isKnownNeverNaN(RHS) && !DAG.isKnownNeverNaN(LHS);
3619         break;
3620       }
3621     }
3622     swapSides = swapSides || (LHS == FalseVal && RHS == TrueVal);
3623     if (swapSides) {
3624       CC = ISD::getSetCCSwappedOperands(CC);
3625       std::swap(LHS, RHS);
3626     }
3627     if (LHS == TrueVal && RHS == FalseVal) {
3628       bool canTransform = true;
3629       // FIXME: FastMathFlags::noSignedZeros() doesn't appear reachable from here
3630       if (!getTargetMachine().Options.UnsafeFPMath &&
3631           !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
3632         const ConstantFPSDNode *Zero;
3633         switch (CC) {
3634         default:
3635           break;
3636         case ISD::SETOGT:
3637         case ISD::SETUGT:
3638         case ISD::SETGT:
3639           // RHS must not be -0
3640           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3641                          !Zero->isNegative();
3642           break;
3643         case ISD::SETOGE:
3644         case ISD::SETUGE:
3645         case ISD::SETGE:
3646           // LHS must not be -0
3647           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3648                          !Zero->isNegative();
3649           break;
3650         case ISD::SETOLT:
3651         case ISD::SETULT:
3652         case ISD::SETLT:
3653           // RHS must not be +0
3654           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(RHS)) &&
3655                           Zero->isNegative();
3656           break;
3657         case ISD::SETOLE:
3658         case ISD::SETULE:
3659         case ISD::SETLE:
3660           // LHS must not be +0
3661           canTransform = (Zero = dyn_cast<ConstantFPSDNode>(LHS)) &&
3662                           Zero->isNegative();
3663           break;
3664         }
3665       }
3666       if (canTransform) {
3667         // Note: If one of the elements in a pair is a number and the other
3668         // element is NaN, the corresponding result element is the number.
3669         // This is consistent with the IEEE 754-2008 standard.
3670         // Therefore, a > b ? a : b <=> vmax(a,b), if b is constant and a is NaN
3671         switch (CC) {
3672         default:
3673           break;
3674         case ISD::SETOGT:
3675         case ISD::SETOGE:
3676           if (!DAG.isKnownNeverNaN(RHS))
3677             break;
3678           return DAG.getNode(ISD::FMAXNUM, dl, VT, LHS, RHS);
3679         case ISD::SETUGT:
3680         case ISD::SETUGE:
3681           if (!DAG.isKnownNeverNaN(LHS))
3682             break;
3683         case ISD::SETGT:
3684         case ISD::SETGE:
3685           return DAG.getNode(ISD::FMAXNUM, dl, VT, LHS, RHS);
3686         case ISD::SETOLT:
3687         case ISD::SETOLE:
3688           if (!DAG.isKnownNeverNaN(RHS))
3689             break;
3690           return DAG.getNode(ISD::FMINNUM, dl, VT, LHS, RHS);
3691         case ISD::SETULT:
3692         case ISD::SETULE:
3693           if (!DAG.isKnownNeverNaN(LHS))
3694             break;
3695         case ISD::SETLT:
3696         case ISD::SETLE:
3697           return DAG.getNode(ISD::FMINNUM, dl, VT, LHS, RHS);
3698         }
3699       }
3700     }
3701
3702     bool swpCmpOps = false;
3703     bool swpVselOps = false;
3704     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
3705
3706     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
3707         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
3708       if (swpCmpOps)
3709         std::swap(LHS, RHS);
3710       if (swpVselOps)
3711         std::swap(TrueVal, FalseVal);
3712     }
3713   }
3714
3715   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3716   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3717   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3718   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
3719   if (CondCode2 != ARMCC::AL) {
3720     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
3721     // FIXME: Needs another CMP because flag can have but one use.
3722     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl);
3723     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
3724   }
3725   return Result;
3726 }
3727
3728 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
3729 /// to morph to an integer compare sequence.
3730 static bool canChangeToInt(SDValue Op, bool &SeenZero,
3731                            const ARMSubtarget *Subtarget) {
3732   SDNode *N = Op.getNode();
3733   if (!N->hasOneUse())
3734     // Otherwise it requires moving the value from fp to integer registers.
3735     return false;
3736   if (!N->getNumValues())
3737     return false;
3738   EVT VT = Op.getValueType();
3739   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
3740     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
3741     // vmrs are very slow, e.g. cortex-a8.
3742     return false;
3743
3744   if (isFloatingPointZero(Op)) {
3745     SeenZero = true;
3746     return true;
3747   }
3748   return ISD::isNormalLoad(N);
3749 }
3750
3751 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
3752   if (isFloatingPointZero(Op))
3753     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
3754
3755   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
3756     return DAG.getLoad(MVT::i32, SDLoc(Op),
3757                        Ld->getChain(), Ld->getBasePtr(), Ld->getPointerInfo(),
3758                        Ld->isVolatile(), Ld->isNonTemporal(),
3759                        Ld->isInvariant(), Ld->getAlignment());
3760
3761   llvm_unreachable("Unknown VFP cmp argument!");
3762 }
3763
3764 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
3765                            SDValue &RetVal1, SDValue &RetVal2) {
3766   SDLoc dl(Op);
3767
3768   if (isFloatingPointZero(Op)) {
3769     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
3770     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
3771     return;
3772   }
3773
3774   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
3775     SDValue Ptr = Ld->getBasePtr();
3776     RetVal1 = DAG.getLoad(MVT::i32, dl,
3777                           Ld->getChain(), Ptr,
3778                           Ld->getPointerInfo(),
3779                           Ld->isVolatile(), Ld->isNonTemporal(),
3780                           Ld->isInvariant(), Ld->getAlignment());
3781
3782     EVT PtrType = Ptr.getValueType();
3783     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
3784     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
3785                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
3786     RetVal2 = DAG.getLoad(MVT::i32, dl,
3787                           Ld->getChain(), NewPtr,
3788                           Ld->getPointerInfo().getWithOffset(4),
3789                           Ld->isVolatile(), Ld->isNonTemporal(),
3790                           Ld->isInvariant(), NewAlign);
3791     return;
3792   }
3793
3794   llvm_unreachable("Unknown VFP cmp argument!");
3795 }
3796
3797 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
3798 /// f32 and even f64 comparisons to integer ones.
3799 SDValue
3800 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
3801   SDValue Chain = Op.getOperand(0);
3802   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3803   SDValue LHS = Op.getOperand(2);
3804   SDValue RHS = Op.getOperand(3);
3805   SDValue Dest = Op.getOperand(4);
3806   SDLoc dl(Op);
3807
3808   bool LHSSeenZero = false;
3809   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
3810   bool RHSSeenZero = false;
3811   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
3812   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
3813     // If unsafe fp math optimization is enabled and there are no other uses of
3814     // the CMP operands, and the condition code is EQ or NE, we can optimize it
3815     // to an integer comparison.
3816     if (CC == ISD::SETOEQ)
3817       CC = ISD::SETEQ;
3818     else if (CC == ISD::SETUNE)
3819       CC = ISD::SETNE;
3820
3821     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
3822     SDValue ARMcc;
3823     if (LHS.getValueType() == MVT::f32) {
3824       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3825                         bitcastf32Toi32(LHS, DAG), Mask);
3826       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
3827                         bitcastf32Toi32(RHS, DAG), Mask);
3828       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3829       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3830       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3831                          Chain, Dest, ARMcc, CCR, Cmp);
3832     }
3833
3834     SDValue LHS1, LHS2;
3835     SDValue RHS1, RHS2;
3836     expandf64Toi32(LHS, DAG, LHS1, LHS2);
3837     expandf64Toi32(RHS, DAG, RHS1, RHS2);
3838     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
3839     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
3840     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3841     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3842     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3843     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
3844     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
3845   }
3846
3847   return SDValue();
3848 }
3849
3850 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3851   SDValue Chain = Op.getOperand(0);
3852   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3853   SDValue LHS = Op.getOperand(2);
3854   SDValue RHS = Op.getOperand(3);
3855   SDValue Dest = Op.getOperand(4);
3856   SDLoc dl(Op);
3857
3858   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
3859     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
3860                                                     dl);
3861
3862     // If softenSetCCOperands only returned one value, we should compare it to
3863     // zero.
3864     if (!RHS.getNode()) {
3865       RHS = DAG.getConstant(0, dl, LHS.getValueType());
3866       CC = ISD::SETNE;
3867     }
3868   }
3869
3870   if (LHS.getValueType() == MVT::i32) {
3871     SDValue ARMcc;
3872     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
3873     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3874     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
3875                        Chain, Dest, ARMcc, CCR, Cmp);
3876   }
3877
3878   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3879
3880   if (getTargetMachine().Options.UnsafeFPMath &&
3881       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
3882        CC == ISD::SETNE || CC == ISD::SETUNE)) {
3883     SDValue Result = OptimizeVFPBrcond(Op, DAG);
3884     if (Result.getNode())
3885       return Result;
3886   }
3887
3888   ARMCC::CondCodes CondCode, CondCode2;
3889   FPCCToARMCC(CC, CondCode, CondCode2);
3890
3891   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3892   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl);
3893   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3894   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
3895   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
3896   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3897   if (CondCode2 != ARMCC::AL) {
3898     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
3899     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
3900     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
3901   }
3902   return Res;
3903 }
3904
3905 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
3906   SDValue Chain = Op.getOperand(0);
3907   SDValue Table = Op.getOperand(1);
3908   SDValue Index = Op.getOperand(2);
3909   SDLoc dl(Op);
3910
3911   EVT PTy = getPointerTy(DAG.getDataLayout());
3912   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
3913   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
3914   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
3915   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
3916   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3917   if (Subtarget->isThumb2()) {
3918     // Thumb2 uses a two-level jump. That is, it jumps into the jump table
3919     // which does another jump to the destination. This also makes it easier
3920     // to translate it to TBB / TBH later.
3921     // FIXME: This might not work if the function is extremely large.
3922     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
3923                        Addr, Op.getOperand(2), JTI);
3924   }
3925   if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
3926     Addr = DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
3927                        MachinePointerInfo::getJumpTable(),
3928                        false, false, false, 0);
3929     Chain = Addr.getValue(1);
3930     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
3931     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3932   } else {
3933     Addr = DAG.getLoad(PTy, dl, Chain, Addr,
3934                        MachinePointerInfo::getJumpTable(),
3935                        false, false, false, 0);
3936     Chain = Addr.getValue(1);
3937     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
3938   }
3939 }
3940
3941 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
3942   EVT VT = Op.getValueType();
3943   SDLoc dl(Op);
3944
3945   if (Op.getValueType().getVectorElementType() == MVT::i32) {
3946     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
3947       return Op;
3948     return DAG.UnrollVectorOp(Op.getNode());
3949   }
3950
3951   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
3952          "Invalid type for custom lowering!");
3953   if (VT != MVT::v4i16)
3954     return DAG.UnrollVectorOp(Op.getNode());
3955
3956   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
3957   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
3958 }
3959
3960 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
3961   EVT VT = Op.getValueType();
3962   if (VT.isVector())
3963     return LowerVectorFP_TO_INT(Op, DAG);
3964   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
3965     RTLIB::Libcall LC;
3966     if (Op.getOpcode() == ISD::FP_TO_SINT)
3967       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
3968                               Op.getValueType());
3969     else
3970       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
3971                               Op.getValueType());
3972     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
3973                        /*isSigned*/ false, SDLoc(Op)).first;
3974   }
3975
3976   return Op;
3977 }
3978
3979 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
3980   EVT VT = Op.getValueType();
3981   SDLoc dl(Op);
3982
3983   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
3984     if (VT.getVectorElementType() == MVT::f32)
3985       return Op;
3986     return DAG.UnrollVectorOp(Op.getNode());
3987   }
3988
3989   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
3990          "Invalid type for custom lowering!");
3991   if (VT != MVT::v4f32)
3992     return DAG.UnrollVectorOp(Op.getNode());
3993
3994   unsigned CastOpc;
3995   unsigned Opc;
3996   switch (Op.getOpcode()) {
3997   default: llvm_unreachable("Invalid opcode!");
3998   case ISD::SINT_TO_FP:
3999     CastOpc = ISD::SIGN_EXTEND;
4000     Opc = ISD::SINT_TO_FP;
4001     break;
4002   case ISD::UINT_TO_FP:
4003     CastOpc = ISD::ZERO_EXTEND;
4004     Opc = ISD::UINT_TO_FP;
4005     break;
4006   }
4007
4008   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4009   return DAG.getNode(Opc, dl, VT, Op);
4010 }
4011
4012 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4013   EVT VT = Op.getValueType();
4014   if (VT.isVector())
4015     return LowerVectorINT_TO_FP(Op, DAG);
4016   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4017     RTLIB::Libcall LC;
4018     if (Op.getOpcode() == ISD::SINT_TO_FP)
4019       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4020                               Op.getValueType());
4021     else
4022       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4023                               Op.getValueType());
4024     return makeLibCall(DAG, LC, Op.getValueType(), &Op.getOperand(0), 1,
4025                        /*isSigned*/ false, SDLoc(Op)).first;
4026   }
4027
4028   return Op;
4029 }
4030
4031 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4032   // Implement fcopysign with a fabs and a conditional fneg.
4033   SDValue Tmp0 = Op.getOperand(0);
4034   SDValue Tmp1 = Op.getOperand(1);
4035   SDLoc dl(Op);
4036   EVT VT = Op.getValueType();
4037   EVT SrcVT = Tmp1.getValueType();
4038   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4039     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4040   bool UseNEON = !InGPR && Subtarget->hasNEON();
4041
4042   if (UseNEON) {
4043     // Use VBSL to copy the sign bit.
4044     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4045     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4046                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4047     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4048     if (VT == MVT::f64)
4049       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4050                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4051                          DAG.getConstant(32, dl, MVT::i32));
4052     else /*if (VT == MVT::f32)*/
4053       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4054     if (SrcVT == MVT::f32) {
4055       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4056       if (VT == MVT::f64)
4057         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4058                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4059                            DAG.getConstant(32, dl, MVT::i32));
4060     } else if (VT == MVT::f32)
4061       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4062                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4063                          DAG.getConstant(32, dl, MVT::i32));
4064     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4065     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4066
4067     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4068                                             dl, MVT::i32);
4069     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4070     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4071                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4072
4073     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4074                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4075                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4076     if (VT == MVT::f32) {
4077       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4078       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4079                         DAG.getConstant(0, dl, MVT::i32));
4080     } else {
4081       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4082     }
4083
4084     return Res;
4085   }
4086
4087   // Bitcast operand 1 to i32.
4088   if (SrcVT == MVT::f64)
4089     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4090                        Tmp1).getValue(1);
4091   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4092
4093   // Or in the signbit with integer operations.
4094   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4095   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4096   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4097   if (VT == MVT::f32) {
4098     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4099                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4100     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4101                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4102   }
4103
4104   // f64: Or the high part with signbit and then combine two parts.
4105   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4106                      Tmp0);
4107   SDValue Lo = Tmp0.getValue(0);
4108   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4109   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4110   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4111 }
4112
4113 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4114   MachineFunction &MF = DAG.getMachineFunction();
4115   MachineFrameInfo *MFI = MF.getFrameInfo();
4116   MFI->setReturnAddressIsTaken(true);
4117
4118   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4119     return SDValue();
4120
4121   EVT VT = Op.getValueType();
4122   SDLoc dl(Op);
4123   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4124   if (Depth) {
4125     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4126     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4127     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4128                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4129                        MachinePointerInfo(), false, false, false, 0);
4130   }
4131
4132   // Return LR, which contains the return address. Mark it an implicit live-in.
4133   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4134   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4135 }
4136
4137 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4138   const ARMBaseRegisterInfo &ARI =
4139     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4140   MachineFunction &MF = DAG.getMachineFunction();
4141   MachineFrameInfo *MFI = MF.getFrameInfo();
4142   MFI->setFrameAddressIsTaken(true);
4143
4144   EVT VT = Op.getValueType();
4145   SDLoc dl(Op);  // FIXME probably not meaningful
4146   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4147   unsigned FrameReg = ARI.getFrameRegister(MF);
4148   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4149   while (Depth--)
4150     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4151                             MachinePointerInfo(),
4152                             false, false, false, 0);
4153   return FrameAddr;
4154 }
4155
4156 // FIXME? Maybe this could be a TableGen attribute on some registers and
4157 // this table could be generated automatically from RegInfo.
4158 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4159                                               SelectionDAG &DAG) const {
4160   unsigned Reg = StringSwitch<unsigned>(RegName)
4161                        .Case("sp", ARM::SP)
4162                        .Default(0);
4163   if (Reg)
4164     return Reg;
4165   report_fatal_error(Twine("Invalid register name \""
4166                               + StringRef(RegName)  + "\"."));
4167 }
4168
4169 // Result is 64 bit value so split into two 32 bit values and return as a
4170 // pair of values.
4171 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4172                                 SelectionDAG &DAG) {
4173   SDLoc DL(N);
4174
4175   // This function is only supposed to be called for i64 type destination.
4176   assert(N->getValueType(0) == MVT::i64
4177           && "ExpandREAD_REGISTER called for non-i64 type result.");
4178
4179   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4180                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4181                              N->getOperand(0),
4182                              N->getOperand(1));
4183
4184   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4185                     Read.getValue(1)));
4186   Results.push_back(Read.getOperand(0));
4187 }
4188
4189 /// ExpandBITCAST - If the target supports VFP, this function is called to
4190 /// expand a bit convert where either the source or destination type is i64 to
4191 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4192 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4193 /// vectors), since the legalizer won't know what to do with that.
4194 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4196   SDLoc dl(N);
4197   SDValue Op = N->getOperand(0);
4198
4199   // This function is only supposed to be called for i64 types, either as the
4200   // source or destination of the bit convert.
4201   EVT SrcVT = Op.getValueType();
4202   EVT DstVT = N->getValueType(0);
4203   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4204          "ExpandBITCAST called for non-i64 type");
4205
4206   // Turn i64->f64 into VMOVDRR.
4207   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4208     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4209                              DAG.getConstant(0, dl, MVT::i32));
4210     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4211                              DAG.getConstant(1, dl, MVT::i32));
4212     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4213                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4214   }
4215
4216   // Turn f64->i64 into VMOVRRD.
4217   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4218     SDValue Cvt;
4219     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4220         SrcVT.getVectorNumElements() > 1)
4221       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4222                         DAG.getVTList(MVT::i32, MVT::i32),
4223                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4224     else
4225       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4226                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4227     // Merge the pieces into a single i64 value.
4228     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4229   }
4230
4231   return SDValue();
4232 }
4233
4234 /// getZeroVector - Returns a vector of specified type with all zero elements.
4235 /// Zero vectors are used to represent vector negation and in those cases
4236 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4237 /// not support i64 elements, so sometimes the zero vectors will need to be
4238 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4239 /// zero vector.
4240 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, SDLoc dl) {
4241   assert(VT.isVector() && "Expected a vector type");
4242   // The canonical modified immediate encoding of a zero vector is....0!
4243   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4244   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4245   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4246   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4247 }
4248
4249 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4250 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4251 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4252                                                 SelectionDAG &DAG) const {
4253   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4254   EVT VT = Op.getValueType();
4255   unsigned VTBits = VT.getSizeInBits();
4256   SDLoc dl(Op);
4257   SDValue ShOpLo = Op.getOperand(0);
4258   SDValue ShOpHi = Op.getOperand(1);
4259   SDValue ShAmt  = Op.getOperand(2);
4260   SDValue ARMcc;
4261   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4262
4263   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4264
4265   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4266                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4267   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4268   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4269                                    DAG.getConstant(VTBits, dl, MVT::i32));
4270   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4271   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4272   SDValue TrueVal = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4273
4274   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4275   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4276                           ISD::SETGE, ARMcc, DAG, dl);
4277   SDValue Hi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4278   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc,
4279                            CCR, Cmp);
4280
4281   SDValue Ops[2] = { Lo, Hi };
4282   return DAG.getMergeValues(Ops, dl);
4283 }
4284
4285 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4286 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4287 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4288                                                SelectionDAG &DAG) const {
4289   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4290   EVT VT = Op.getValueType();
4291   unsigned VTBits = VT.getSizeInBits();
4292   SDLoc dl(Op);
4293   SDValue ShOpLo = Op.getOperand(0);
4294   SDValue ShOpHi = Op.getOperand(1);
4295   SDValue ShAmt  = Op.getOperand(2);
4296   SDValue ARMcc;
4297
4298   assert(Op.getOpcode() == ISD::SHL_PARTS);
4299   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4300                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4301   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4302   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4303                                    DAG.getConstant(VTBits, dl, MVT::i32));
4304   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4305   SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4306
4307   SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4308   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4309   SDValue Cmp = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4310                           ISD::SETGE, ARMcc, DAG, dl);
4311   SDValue Lo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4312   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, Tmp3, ARMcc,
4313                            CCR, Cmp);
4314
4315   SDValue Ops[2] = { Lo, Hi };
4316   return DAG.getMergeValues(Ops, dl);
4317 }
4318
4319 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4320                                             SelectionDAG &DAG) const {
4321   // The rounding mode is in bits 23:22 of the FPSCR.
4322   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4323   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4324   // so that the shift + and get folded into a bitfield extract.
4325   SDLoc dl(Op);
4326   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::i32,
4327                               DAG.getConstant(Intrinsic::arm_get_fpscr, dl,
4328                                               MVT::i32));
4329   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4330                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4331   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4332                               DAG.getConstant(22, dl, MVT::i32));
4333   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4334                      DAG.getConstant(3, dl, MVT::i32));
4335 }
4336
4337 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4338                          const ARMSubtarget *ST) {
4339   SDLoc dl(N);
4340   EVT VT = N->getValueType(0);
4341   if (VT.isVector()) {
4342     assert(ST->hasNEON());
4343
4344     // Compute the least significant set bit: LSB = X & -X
4345     SDValue X = N->getOperand(0);
4346     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4347     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4348
4349     EVT ElemTy = VT.getVectorElementType();
4350
4351     if (ElemTy == MVT::i8) {
4352       // Compute with: cttz(x) = ctpop(lsb - 1)
4353       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4354                                 DAG.getTargetConstant(1, dl, ElemTy));
4355       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4356       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4357     }
4358
4359     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4360         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4361       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4362       unsigned NumBits = ElemTy.getSizeInBits();
4363       SDValue WidthMinus1 =
4364           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4365                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4366       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4367       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4368     }
4369
4370     // Compute with: cttz(x) = ctpop(lsb - 1)
4371
4372     // Since we can only compute the number of bits in a byte with vcnt.8, we
4373     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4374     // and i64.
4375
4376     // Compute LSB - 1.
4377     SDValue Bits;
4378     if (ElemTy == MVT::i64) {
4379       // Load constant 0xffff'ffff'ffff'ffff to register.
4380       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4381                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
4382       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
4383     } else {
4384       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4385                                 DAG.getTargetConstant(1, dl, ElemTy));
4386       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4387     }
4388
4389     // Count #bits with vcnt.8.
4390     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4391     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
4392     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
4393
4394     // Gather the #bits with vpaddl (pairwise add.)
4395     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4396     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
4397         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4398         Cnt8);
4399     if (ElemTy == MVT::i16)
4400       return Cnt16;
4401
4402     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
4403     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
4404         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4405         Cnt16);
4406     if (ElemTy == MVT::i32)
4407       return Cnt32;
4408
4409     assert(ElemTy == MVT::i64);
4410     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4411         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
4412         Cnt32);
4413     return Cnt64;
4414   }
4415
4416   if (!ST->hasV6T2Ops())
4417     return SDValue();
4418
4419   SDValue rbit = DAG.getNode(ARMISD::RBIT, dl, VT, N->getOperand(0));
4420   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
4421 }
4422
4423 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
4424 /// for each 16-bit element from operand, repeated.  The basic idea is to
4425 /// leverage vcnt to get the 8-bit counts, gather and add the results.
4426 ///
4427 /// Trace for v4i16:
4428 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
4429 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
4430 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
4431 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
4432 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
4433 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
4434 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
4435 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
4436 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
4437   EVT VT = N->getValueType(0);
4438   SDLoc DL(N);
4439
4440   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
4441   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
4442   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
4443   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
4444   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
4445   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
4446 }
4447
4448 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
4449 /// bit-count for each 16-bit element from the operand.  We need slightly
4450 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
4451 /// 64/128-bit registers.
4452 ///
4453 /// Trace for v4i16:
4454 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
4455 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
4456 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
4457 /// v4i16:Extracted = [k0    k1    k2    k3    ]
4458 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
4459   EVT VT = N->getValueType(0);
4460   SDLoc DL(N);
4461
4462   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
4463   if (VT.is64BitVector()) {
4464     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
4465     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
4466                        DAG.getIntPtrConstant(0, DL));
4467   } else {
4468     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
4469                                     BitCounts, DAG.getIntPtrConstant(0, DL));
4470     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
4471   }
4472 }
4473
4474 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
4475 /// bit-count for each 32-bit element from the operand.  The idea here is
4476 /// to split the vector into 16-bit elements, leverage the 16-bit count
4477 /// routine, and then combine the results.
4478 ///
4479 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
4480 /// input    = [v0    v1    ] (vi: 32-bit elements)
4481 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
4482 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
4483 /// vrev: N0 = [k1 k0 k3 k2 ]
4484 ///            [k0 k1 k2 k3 ]
4485 ///       N1 =+[k1 k0 k3 k2 ]
4486 ///            [k0 k2 k1 k3 ]
4487 ///       N2 =+[k1 k3 k0 k2 ]
4488 ///            [k0    k2    k1    k3    ]
4489 /// Extended =+[k1    k3    k0    k2    ]
4490 ///            [k0    k2    ]
4491 /// Extracted=+[k1    k3    ]
4492 ///
4493 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
4494   EVT VT = N->getValueType(0);
4495   SDLoc DL(N);
4496
4497   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
4498
4499   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
4500   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
4501   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
4502   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
4503   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
4504
4505   if (VT.is64BitVector()) {
4506     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
4507     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
4508                        DAG.getIntPtrConstant(0, DL));
4509   } else {
4510     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
4511                                     DAG.getIntPtrConstant(0, DL));
4512     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
4513   }
4514 }
4515
4516 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
4517                           const ARMSubtarget *ST) {
4518   EVT VT = N->getValueType(0);
4519
4520   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
4521   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
4522           VT == MVT::v4i16 || VT == MVT::v8i16) &&
4523          "Unexpected type for custom ctpop lowering");
4524
4525   if (VT.getVectorElementType() == MVT::i32)
4526     return lowerCTPOP32BitElements(N, DAG);
4527   else
4528     return lowerCTPOP16BitElements(N, DAG);
4529 }
4530
4531 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
4532                           const ARMSubtarget *ST) {
4533   EVT VT = N->getValueType(0);
4534   SDLoc dl(N);
4535
4536   if (!VT.isVector())
4537     return SDValue();
4538
4539   // Lower vector shifts on NEON to use VSHL.
4540   assert(ST->hasNEON() && "unexpected vector shift");
4541
4542   // Left shifts translate directly to the vshiftu intrinsic.
4543   if (N->getOpcode() == ISD::SHL)
4544     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4545                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
4546                                        MVT::i32),
4547                        N->getOperand(0), N->getOperand(1));
4548
4549   assert((N->getOpcode() == ISD::SRA ||
4550           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
4551
4552   // NEON uses the same intrinsics for both left and right shifts.  For
4553   // right shifts, the shift amounts are negative, so negate the vector of
4554   // shift amounts.
4555   EVT ShiftVT = N->getOperand(1).getValueType();
4556   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
4557                                      getZeroVector(ShiftVT, DAG, dl),
4558                                      N->getOperand(1));
4559   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
4560                              Intrinsic::arm_neon_vshifts :
4561                              Intrinsic::arm_neon_vshiftu);
4562   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
4563                      DAG.getConstant(vshiftInt, dl, MVT::i32),
4564                      N->getOperand(0), NegatedCount);
4565 }
4566
4567 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
4568                                 const ARMSubtarget *ST) {
4569   EVT VT = N->getValueType(0);
4570   SDLoc dl(N);
4571
4572   // We can get here for a node like i32 = ISD::SHL i32, i64
4573   if (VT != MVT::i64)
4574     return SDValue();
4575
4576   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
4577          "Unknown shift to lower!");
4578
4579   // We only lower SRA, SRL of 1 here, all others use generic lowering.
4580   if (!isa<ConstantSDNode>(N->getOperand(1)) ||
4581       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() != 1)
4582     return SDValue();
4583
4584   // If we are in thumb mode, we don't have RRX.
4585   if (ST->isThumb1Only()) return SDValue();
4586
4587   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
4588   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4589                            DAG.getConstant(0, dl, MVT::i32));
4590   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
4591                            DAG.getConstant(1, dl, MVT::i32));
4592
4593   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
4594   // captures the result into a carry flag.
4595   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
4596   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
4597
4598   // The low part is an ARMISD::RRX operand, which shifts the carry in.
4599   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
4600
4601   // Merge the pieces into a single i64 value.
4602  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4603 }
4604
4605 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
4606   SDValue TmpOp0, TmpOp1;
4607   bool Invert = false;
4608   bool Swap = false;
4609   unsigned Opc = 0;
4610
4611   SDValue Op0 = Op.getOperand(0);
4612   SDValue Op1 = Op.getOperand(1);
4613   SDValue CC = Op.getOperand(2);
4614   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
4615   EVT VT = Op.getValueType();
4616   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4617   SDLoc dl(Op);
4618
4619   if (Op1.getValueType().isFloatingPoint()) {
4620     switch (SetCCOpcode) {
4621     default: llvm_unreachable("Illegal FP comparison");
4622     case ISD::SETUNE:
4623     case ISD::SETNE:  Invert = true; // Fallthrough
4624     case ISD::SETOEQ:
4625     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4626     case ISD::SETOLT:
4627     case ISD::SETLT: Swap = true; // Fallthrough
4628     case ISD::SETOGT:
4629     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4630     case ISD::SETOLE:
4631     case ISD::SETLE:  Swap = true; // Fallthrough
4632     case ISD::SETOGE:
4633     case ISD::SETGE: Opc = ARMISD::VCGE; break;
4634     case ISD::SETUGE: Swap = true; // Fallthrough
4635     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
4636     case ISD::SETUGT: Swap = true; // Fallthrough
4637     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
4638     case ISD::SETUEQ: Invert = true; // Fallthrough
4639     case ISD::SETONE:
4640       // Expand this to (OLT | OGT).
4641       TmpOp0 = Op0;
4642       TmpOp1 = Op1;
4643       Opc = ISD::OR;
4644       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4645       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
4646       break;
4647     case ISD::SETUO: Invert = true; // Fallthrough
4648     case ISD::SETO:
4649       // Expand this to (OLT | OGE).
4650       TmpOp0 = Op0;
4651       TmpOp1 = Op1;
4652       Opc = ISD::OR;
4653       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
4654       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
4655       break;
4656     }
4657   } else {
4658     // Integer comparisons.
4659     switch (SetCCOpcode) {
4660     default: llvm_unreachable("Illegal integer comparison");
4661     case ISD::SETNE:  Invert = true;
4662     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
4663     case ISD::SETLT:  Swap = true;
4664     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
4665     case ISD::SETLE:  Swap = true;
4666     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
4667     case ISD::SETULT: Swap = true;
4668     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
4669     case ISD::SETULE: Swap = true;
4670     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
4671     }
4672
4673     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
4674     if (Opc == ARMISD::VCEQ) {
4675
4676       SDValue AndOp;
4677       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4678         AndOp = Op0;
4679       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
4680         AndOp = Op1;
4681
4682       // Ignore bitconvert.
4683       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
4684         AndOp = AndOp.getOperand(0);
4685
4686       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
4687         Opc = ARMISD::VTST;
4688         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
4689         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
4690         Invert = !Invert;
4691       }
4692     }
4693   }
4694
4695   if (Swap)
4696     std::swap(Op0, Op1);
4697
4698   // If one of the operands is a constant vector zero, attempt to fold the
4699   // comparison to a specialized compare-against-zero form.
4700   SDValue SingleOp;
4701   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
4702     SingleOp = Op0;
4703   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
4704     if (Opc == ARMISD::VCGE)
4705       Opc = ARMISD::VCLEZ;
4706     else if (Opc == ARMISD::VCGT)
4707       Opc = ARMISD::VCLTZ;
4708     SingleOp = Op1;
4709   }
4710
4711   SDValue Result;
4712   if (SingleOp.getNode()) {
4713     switch (Opc) {
4714     case ARMISD::VCEQ:
4715       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
4716     case ARMISD::VCGE:
4717       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
4718     case ARMISD::VCLEZ:
4719       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
4720     case ARMISD::VCGT:
4721       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
4722     case ARMISD::VCLTZ:
4723       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
4724     default:
4725       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4726     }
4727   } else {
4728      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
4729   }
4730
4731   Result = DAG.getSExtOrTrunc(Result, dl, VT);
4732
4733   if (Invert)
4734     Result = DAG.getNOT(dl, Result, VT);
4735
4736   return Result;
4737 }
4738
4739 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
4740 /// valid vector constant for a NEON instruction with a "modified immediate"
4741 /// operand (e.g., VMOV).  If so, return the encoded value.
4742 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
4743                                  unsigned SplatBitSize, SelectionDAG &DAG,
4744                                  SDLoc dl, EVT &VT, bool is128Bits,
4745                                  NEONModImmType type) {
4746   unsigned OpCmode, Imm;
4747
4748   // SplatBitSize is set to the smallest size that splats the vector, so a
4749   // zero vector will always have SplatBitSize == 8.  However, NEON modified
4750   // immediate instructions others than VMOV do not support the 8-bit encoding
4751   // of a zero vector, and the default encoding of zero is supposed to be the
4752   // 32-bit version.
4753   if (SplatBits == 0)
4754     SplatBitSize = 32;
4755
4756   switch (SplatBitSize) {
4757   case 8:
4758     if (type != VMOVModImm)
4759       return SDValue();
4760     // Any 1-byte value is OK.  Op=0, Cmode=1110.
4761     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
4762     OpCmode = 0xe;
4763     Imm = SplatBits;
4764     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
4765     break;
4766
4767   case 16:
4768     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
4769     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
4770     if ((SplatBits & ~0xff) == 0) {
4771       // Value = 0x00nn: Op=x, Cmode=100x.
4772       OpCmode = 0x8;
4773       Imm = SplatBits;
4774       break;
4775     }
4776     if ((SplatBits & ~0xff00) == 0) {
4777       // Value = 0xnn00: Op=x, Cmode=101x.
4778       OpCmode = 0xa;
4779       Imm = SplatBits >> 8;
4780       break;
4781     }
4782     return SDValue();
4783
4784   case 32:
4785     // NEON's 32-bit VMOV supports splat values where:
4786     // * only one byte is nonzero, or
4787     // * the least significant byte is 0xff and the second byte is nonzero, or
4788     // * the least significant 2 bytes are 0xff and the third is nonzero.
4789     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
4790     if ((SplatBits & ~0xff) == 0) {
4791       // Value = 0x000000nn: Op=x, Cmode=000x.
4792       OpCmode = 0;
4793       Imm = SplatBits;
4794       break;
4795     }
4796     if ((SplatBits & ~0xff00) == 0) {
4797       // Value = 0x0000nn00: Op=x, Cmode=001x.
4798       OpCmode = 0x2;
4799       Imm = SplatBits >> 8;
4800       break;
4801     }
4802     if ((SplatBits & ~0xff0000) == 0) {
4803       // Value = 0x00nn0000: Op=x, Cmode=010x.
4804       OpCmode = 0x4;
4805       Imm = SplatBits >> 16;
4806       break;
4807     }
4808     if ((SplatBits & ~0xff000000) == 0) {
4809       // Value = 0xnn000000: Op=x, Cmode=011x.
4810       OpCmode = 0x6;
4811       Imm = SplatBits >> 24;
4812       break;
4813     }
4814
4815     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
4816     if (type == OtherModImm) return SDValue();
4817
4818     if ((SplatBits & ~0xffff) == 0 &&
4819         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
4820       // Value = 0x0000nnff: Op=x, Cmode=1100.
4821       OpCmode = 0xc;
4822       Imm = SplatBits >> 8;
4823       break;
4824     }
4825
4826     if ((SplatBits & ~0xffffff) == 0 &&
4827         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
4828       // Value = 0x00nnffff: Op=x, Cmode=1101.
4829       OpCmode = 0xd;
4830       Imm = SplatBits >> 16;
4831       break;
4832     }
4833
4834     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
4835     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
4836     // VMOV.I32.  A (very) minor optimization would be to replicate the value
4837     // and fall through here to test for a valid 64-bit splat.  But, then the
4838     // caller would also need to check and handle the change in size.
4839     return SDValue();
4840
4841   case 64: {
4842     if (type != VMOVModImm)
4843       return SDValue();
4844     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
4845     uint64_t BitMask = 0xff;
4846     uint64_t Val = 0;
4847     unsigned ImmMask = 1;
4848     Imm = 0;
4849     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
4850       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
4851         Val |= BitMask;
4852         Imm |= ImmMask;
4853       } else if ((SplatBits & BitMask) != 0) {
4854         return SDValue();
4855       }
4856       BitMask <<= 8;
4857       ImmMask <<= 1;
4858     }
4859
4860     if (DAG.getDataLayout().isBigEndian())
4861       // swap higher and lower 32 bit word
4862       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
4863
4864     // Op=1, Cmode=1110.
4865     OpCmode = 0x1e;
4866     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
4867     break;
4868   }
4869
4870   default:
4871     llvm_unreachable("unexpected size for isNEONModifiedImm");
4872   }
4873
4874   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
4875   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
4876 }
4877
4878 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
4879                                            const ARMSubtarget *ST) const {
4880   if (!ST->hasVFP3())
4881     return SDValue();
4882
4883   bool IsDouble = Op.getValueType() == MVT::f64;
4884   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
4885
4886   // Use the default (constant pool) lowering for double constants when we have
4887   // an SP-only FPU
4888   if (IsDouble && Subtarget->isFPOnlySP())
4889     return SDValue();
4890
4891   // Try splatting with a VMOV.f32...
4892   APFloat FPVal = CFP->getValueAPF();
4893   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
4894
4895   if (ImmVal != -1) {
4896     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
4897       // We have code in place to select a valid ConstantFP already, no need to
4898       // do any mangling.
4899       return Op;
4900     }
4901
4902     // It's a float and we are trying to use NEON operations where
4903     // possible. Lower it to a splat followed by an extract.
4904     SDLoc DL(Op);
4905     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
4906     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
4907                                       NewVal);
4908     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
4909                        DAG.getConstant(0, DL, MVT::i32));
4910   }
4911
4912   // The rest of our options are NEON only, make sure that's allowed before
4913   // proceeding..
4914   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
4915     return SDValue();
4916
4917   EVT VMovVT;
4918   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
4919
4920   // It wouldn't really be worth bothering for doubles except for one very
4921   // important value, which does happen to match: 0.0. So make sure we don't do
4922   // anything stupid.
4923   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
4924     return SDValue();
4925
4926   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
4927   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
4928                                      VMovVT, false, VMOVModImm);
4929   if (NewVal != SDValue()) {
4930     SDLoc DL(Op);
4931     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
4932                                       NewVal);
4933     if (IsDouble)
4934       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4935
4936     // It's a float: cast and extract a vector element.
4937     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4938                                        VecConstant);
4939     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4940                        DAG.getConstant(0, DL, MVT::i32));
4941   }
4942
4943   // Finally, try a VMVN.i32
4944   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
4945                              false, VMVNModImm);
4946   if (NewVal != SDValue()) {
4947     SDLoc DL(Op);
4948     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
4949
4950     if (IsDouble)
4951       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
4952
4953     // It's a float: cast and extract a vector element.
4954     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
4955                                        VecConstant);
4956     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
4957                        DAG.getConstant(0, DL, MVT::i32));
4958   }
4959
4960   return SDValue();
4961 }
4962
4963 // check if an VEXT instruction can handle the shuffle mask when the
4964 // vector sources of the shuffle are the same.
4965 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4966   unsigned NumElts = VT.getVectorNumElements();
4967
4968   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
4969   if (M[0] < 0)
4970     return false;
4971
4972   Imm = M[0];
4973
4974   // If this is a VEXT shuffle, the immediate value is the index of the first
4975   // element.  The other shuffle indices must be the successive elements after
4976   // the first one.
4977   unsigned ExpectedElt = Imm;
4978   for (unsigned i = 1; i < NumElts; ++i) {
4979     // Increment the expected index.  If it wraps around, just follow it
4980     // back to index zero and keep going.
4981     ++ExpectedElt;
4982     if (ExpectedElt == NumElts)
4983       ExpectedElt = 0;
4984
4985     if (M[i] < 0) continue; // ignore UNDEF indices
4986     if (ExpectedElt != static_cast<unsigned>(M[i]))
4987       return false;
4988   }
4989
4990   return true;
4991 }
4992
4993
4994 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
4995                        bool &ReverseVEXT, unsigned &Imm) {
4996   unsigned NumElts = VT.getVectorNumElements();
4997   ReverseVEXT = false;
4998
4999   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5000   if (M[0] < 0)
5001     return false;
5002
5003   Imm = M[0];
5004
5005   // If this is a VEXT shuffle, the immediate value is the index of the first
5006   // element.  The other shuffle indices must be the successive elements after
5007   // the first one.
5008   unsigned ExpectedElt = Imm;
5009   for (unsigned i = 1; i < NumElts; ++i) {
5010     // Increment the expected index.  If it wraps around, it may still be
5011     // a VEXT but the source vectors must be swapped.
5012     ExpectedElt += 1;
5013     if (ExpectedElt == NumElts * 2) {
5014       ExpectedElt = 0;
5015       ReverseVEXT = true;
5016     }
5017
5018     if (M[i] < 0) continue; // ignore UNDEF indices
5019     if (ExpectedElt != static_cast<unsigned>(M[i]))
5020       return false;
5021   }
5022
5023   // Adjust the index value if the source operands will be swapped.
5024   if (ReverseVEXT)
5025     Imm -= NumElts;
5026
5027   return true;
5028 }
5029
5030 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5031 /// instruction with the specified blocksize.  (The order of the elements
5032 /// within each block of the vector is reversed.)
5033 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5034   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5035          "Only possible block sizes for VREV are: 16, 32, 64");
5036
5037   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5038   if (EltSz == 64)
5039     return false;
5040
5041   unsigned NumElts = VT.getVectorNumElements();
5042   unsigned BlockElts = M[0] + 1;
5043   // If the first shuffle index is UNDEF, be optimistic.
5044   if (M[0] < 0)
5045     BlockElts = BlockSize / EltSz;
5046
5047   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5048     return false;
5049
5050   for (unsigned i = 0; i < NumElts; ++i) {
5051     if (M[i] < 0) continue; // ignore UNDEF indices
5052     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5053       return false;
5054   }
5055
5056   return true;
5057 }
5058
5059 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5060   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5061   // range, then 0 is placed into the resulting vector. So pretty much any mask
5062   // of 8 elements can work here.
5063   return VT == MVT::v8i8 && M.size() == 8;
5064 }
5065
5066 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5067 // checking that pairs of elements in the shuffle mask represent the same index
5068 // in each vector, incrementing the expected index by 2 at each step.
5069 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5070 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5071 //  v2={e,f,g,h}
5072 // WhichResult gives the offset for each element in the mask based on which
5073 // of the two results it belongs to.
5074 //
5075 // The transpose can be represented either as:
5076 // result1 = shufflevector v1, v2, result1_shuffle_mask
5077 // result2 = shufflevector v1, v2, result2_shuffle_mask
5078 // where v1/v2 and the shuffle masks have the same number of elements
5079 // (here WhichResult (see below) indicates which result is being checked)
5080 //
5081 // or as:
5082 // results = shufflevector v1, v2, shuffle_mask
5083 // where both results are returned in one vector and the shuffle mask has twice
5084 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5085 // want to check the low half and high half of the shuffle mask as if it were
5086 // the other case
5087 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5088   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5089   if (EltSz == 64)
5090     return false;
5091
5092   unsigned NumElts = VT.getVectorNumElements();
5093   if (M.size() != NumElts && M.size() != NumElts*2)
5094     return false;
5095
5096   // If the mask is twice as long as the result then we need to check the upper
5097   // and lower parts of the mask
5098   for (unsigned i = 0; i < M.size(); i += NumElts) {
5099     WhichResult = M[i] == 0 ? 0 : 1;
5100     for (unsigned j = 0; j < NumElts; j += 2) {
5101       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5102           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5103         return false;
5104     }
5105   }
5106
5107   if (M.size() == NumElts*2)
5108     WhichResult = 0;
5109
5110   return true;
5111 }
5112
5113 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5114 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5115 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5116 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5117   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5118   if (EltSz == 64)
5119     return false;
5120
5121   unsigned NumElts = VT.getVectorNumElements();
5122   if (M.size() != NumElts && M.size() != NumElts*2)
5123     return false;
5124
5125   for (unsigned i = 0; i < M.size(); i += NumElts) {
5126     WhichResult = M[i] == 0 ? 0 : 1;
5127     for (unsigned j = 0; j < NumElts; j += 2) {
5128       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5129           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5130         return false;
5131     }
5132   }
5133
5134   if (M.size() == NumElts*2)
5135     WhichResult = 0;
5136
5137   return true;
5138 }
5139
5140 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5141 // that the mask elements are either all even and in steps of size 2 or all odd
5142 // and in steps of size 2.
5143 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5144 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5145 //  v2={e,f,g,h}
5146 // Requires similar checks to that of isVTRNMask with
5147 // respect the how results are returned.
5148 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5149   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5150   if (EltSz == 64)
5151     return false;
5152
5153   unsigned NumElts = VT.getVectorNumElements();
5154   if (M.size() != NumElts && M.size() != NumElts*2)
5155     return false;
5156
5157   for (unsigned i = 0; i < M.size(); i += NumElts) {
5158     WhichResult = M[i] == 0 ? 0 : 1;
5159     for (unsigned j = 0; j < NumElts; ++j) {
5160       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5161         return false;
5162     }
5163   }
5164
5165   if (M.size() == NumElts*2)
5166     WhichResult = 0;
5167
5168   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5169   if (VT.is64BitVector() && EltSz == 32)
5170     return false;
5171
5172   return true;
5173 }
5174
5175 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5176 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5177 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5178 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5179   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5180   if (EltSz == 64)
5181     return false;
5182
5183   unsigned NumElts = VT.getVectorNumElements();
5184   if (M.size() != NumElts && M.size() != NumElts*2)
5185     return false;
5186
5187   unsigned Half = NumElts / 2;
5188   for (unsigned i = 0; i < M.size(); i += NumElts) {
5189     WhichResult = M[i] == 0 ? 0 : 1;
5190     for (unsigned j = 0; j < NumElts; j += Half) {
5191       unsigned Idx = WhichResult;
5192       for (unsigned k = 0; k < Half; ++k) {
5193         int MIdx = M[i + j + k];
5194         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5195           return false;
5196         Idx += 2;
5197       }
5198     }
5199   }
5200
5201   if (M.size() == NumElts*2)
5202     WhichResult = 0;
5203
5204   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5205   if (VT.is64BitVector() && EltSz == 32)
5206     return false;
5207
5208   return true;
5209 }
5210
5211 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5212 // that pairs of elements of the shufflemask represent the same index in each
5213 // vector incrementing sequentially through the vectors.
5214 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5215 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5216 //  v2={e,f,g,h}
5217 // Requires similar checks to that of isVTRNMask with respect the how results
5218 // are returned.
5219 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5220   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5221   if (EltSz == 64)
5222     return false;
5223
5224   unsigned NumElts = VT.getVectorNumElements();
5225   if (M.size() != NumElts && M.size() != NumElts*2)
5226     return false;
5227
5228   for (unsigned i = 0; i < M.size(); i += NumElts) {
5229     WhichResult = M[i] == 0 ? 0 : 1;
5230     unsigned Idx = WhichResult * NumElts / 2;
5231     for (unsigned j = 0; j < NumElts; j += 2) {
5232       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5233           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5234         return false;
5235       Idx += 1;
5236     }
5237   }
5238
5239   if (M.size() == NumElts*2)
5240     WhichResult = 0;
5241
5242   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5243   if (VT.is64BitVector() && EltSz == 32)
5244     return false;
5245
5246   return true;
5247 }
5248
5249 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5250 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5251 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5252 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5253   unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5254   if (EltSz == 64)
5255     return false;
5256
5257   unsigned NumElts = VT.getVectorNumElements();
5258   if (M.size() != NumElts && M.size() != NumElts*2)
5259     return false;
5260
5261   for (unsigned i = 0; i < M.size(); i += NumElts) {
5262     WhichResult = M[i] == 0 ? 0 : 1;
5263     unsigned Idx = WhichResult * NumElts / 2;
5264     for (unsigned j = 0; j < NumElts; j += 2) {
5265       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5266           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5267         return false;
5268       Idx += 1;
5269     }
5270   }
5271
5272   if (M.size() == NumElts*2)
5273     WhichResult = 0;
5274
5275   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5276   if (VT.is64BitVector() && EltSz == 32)
5277     return false;
5278
5279   return true;
5280 }
5281
5282 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5283 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5284 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5285                                            unsigned &WhichResult,
5286                                            bool &isV_UNDEF) {
5287   isV_UNDEF = false;
5288   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5289     return ARMISD::VTRN;
5290   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5291     return ARMISD::VUZP;
5292   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5293     return ARMISD::VZIP;
5294
5295   isV_UNDEF = true;
5296   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5297     return ARMISD::VTRN;
5298   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5299     return ARMISD::VUZP;
5300   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5301     return ARMISD::VZIP;
5302
5303   return 0;
5304 }
5305
5306 /// \return true if this is a reverse operation on an vector.
5307 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
5308   unsigned NumElts = VT.getVectorNumElements();
5309   // Make sure the mask has the right size.
5310   if (NumElts != M.size())
5311       return false;
5312
5313   // Look for <15, ..., 3, -1, 1, 0>.
5314   for (unsigned i = 0; i != NumElts; ++i)
5315     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
5316       return false;
5317
5318   return true;
5319 }
5320
5321 // If N is an integer constant that can be moved into a register in one
5322 // instruction, return an SDValue of such a constant (will become a MOV
5323 // instruction).  Otherwise return null.
5324 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
5325                                      const ARMSubtarget *ST, SDLoc dl) {
5326   uint64_t Val;
5327   if (!isa<ConstantSDNode>(N))
5328     return SDValue();
5329   Val = cast<ConstantSDNode>(N)->getZExtValue();
5330
5331   if (ST->isThumb1Only()) {
5332     if (Val <= 255 || ~Val <= 255)
5333       return DAG.getConstant(Val, dl, MVT::i32);
5334   } else {
5335     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
5336       return DAG.getConstant(Val, dl, MVT::i32);
5337   }
5338   return SDValue();
5339 }
5340
5341 // If this is a case we can't handle, return null and let the default
5342 // expansion code take care of it.
5343 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
5344                                              const ARMSubtarget *ST) const {
5345   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5346   SDLoc dl(Op);
5347   EVT VT = Op.getValueType();
5348
5349   APInt SplatBits, SplatUndef;
5350   unsigned SplatBitSize;
5351   bool HasAnyUndefs;
5352   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5353     if (SplatBitSize <= 64) {
5354       // Check if an immediate VMOV works.
5355       EVT VmovVT;
5356       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
5357                                       SplatUndef.getZExtValue(), SplatBitSize,
5358                                       DAG, dl, VmovVT, VT.is128BitVector(),
5359                                       VMOVModImm);
5360       if (Val.getNode()) {
5361         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
5362         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5363       }
5364
5365       // Try an immediate VMVN.
5366       uint64_t NegatedImm = (~SplatBits).getZExtValue();
5367       Val = isNEONModifiedImm(NegatedImm,
5368                                       SplatUndef.getZExtValue(), SplatBitSize,
5369                                       DAG, dl, VmovVT, VT.is128BitVector(),
5370                                       VMVNModImm);
5371       if (Val.getNode()) {
5372         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
5373         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5374       }
5375
5376       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
5377       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
5378         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
5379         if (ImmVal != -1) {
5380           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
5381           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
5382         }
5383       }
5384     }
5385   }
5386
5387   // Scan through the operands to see if only one value is used.
5388   //
5389   // As an optimisation, even if more than one value is used it may be more
5390   // profitable to splat with one value then change some lanes.
5391   //
5392   // Heuristically we decide to do this if the vector has a "dominant" value,
5393   // defined as splatted to more than half of the lanes.
5394   unsigned NumElts = VT.getVectorNumElements();
5395   bool isOnlyLowElement = true;
5396   bool usesOnlyOneValue = true;
5397   bool hasDominantValue = false;
5398   bool isConstant = true;
5399
5400   // Map of the number of times a particular SDValue appears in the
5401   // element list.
5402   DenseMap<SDValue, unsigned> ValueCounts;
5403   SDValue Value;
5404   for (unsigned i = 0; i < NumElts; ++i) {
5405     SDValue V = Op.getOperand(i);
5406     if (V.getOpcode() == ISD::UNDEF)
5407       continue;
5408     if (i > 0)
5409       isOnlyLowElement = false;
5410     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5411       isConstant = false;
5412
5413     ValueCounts.insert(std::make_pair(V, 0));
5414     unsigned &Count = ValueCounts[V];
5415
5416     // Is this value dominant? (takes up more than half of the lanes)
5417     if (++Count > (NumElts / 2)) {
5418       hasDominantValue = true;
5419       Value = V;
5420     }
5421   }
5422   if (ValueCounts.size() != 1)
5423     usesOnlyOneValue = false;
5424   if (!Value.getNode() && ValueCounts.size() > 0)
5425     Value = ValueCounts.begin()->first;
5426
5427   if (ValueCounts.size() == 0)
5428     return DAG.getUNDEF(VT);
5429
5430   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
5431   // Keep going if we are hitting this case.
5432   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
5433     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5434
5435   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5436
5437   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
5438   // i32 and try again.
5439   if (hasDominantValue && EltSize <= 32) {
5440     if (!isConstant) {
5441       SDValue N;
5442
5443       // If we are VDUPing a value that comes directly from a vector, that will
5444       // cause an unnecessary move to and from a GPR, where instead we could
5445       // just use VDUPLANE. We can only do this if the lane being extracted
5446       // is at a constant index, as the VDUP from lane instructions only have
5447       // constant-index forms.
5448       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5449           isa<ConstantSDNode>(Value->getOperand(1))) {
5450         // We need to create a new undef vector to use for the VDUPLANE if the
5451         // size of the vector from which we get the value is different than the
5452         // size of the vector that we need to create. We will insert the element
5453         // such that the register coalescer will remove unnecessary copies.
5454         if (VT != Value->getOperand(0).getValueType()) {
5455           ConstantSDNode *constIndex;
5456           constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1));
5457           assert(constIndex && "The index is not a constant!");
5458           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
5459                              VT.getVectorNumElements();
5460           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5461                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
5462                         Value, DAG.getConstant(index, dl, MVT::i32)),
5463                            DAG.getConstant(index, dl, MVT::i32));
5464         } else
5465           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5466                         Value->getOperand(0), Value->getOperand(1));
5467       } else
5468         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
5469
5470       if (!usesOnlyOneValue) {
5471         // The dominant value was splatted as 'N', but we now have to insert
5472         // all differing elements.
5473         for (unsigned I = 0; I < NumElts; ++I) {
5474           if (Op.getOperand(I) == Value)
5475             continue;
5476           SmallVector<SDValue, 3> Ops;
5477           Ops.push_back(N);
5478           Ops.push_back(Op.getOperand(I));
5479           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
5480           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
5481         }
5482       }
5483       return N;
5484     }
5485     if (VT.getVectorElementType().isFloatingPoint()) {
5486       SmallVector<SDValue, 8> Ops;
5487       for (unsigned i = 0; i < NumElts; ++i)
5488         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
5489                                   Op.getOperand(i)));
5490       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
5491       SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5492       Val = LowerBUILD_VECTOR(Val, DAG, ST);
5493       if (Val.getNode())
5494         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5495     }
5496     if (usesOnlyOneValue) {
5497       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
5498       if (isConstant && Val.getNode())
5499         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
5500     }
5501   }
5502
5503   // If all elements are constants and the case above didn't get hit, fall back
5504   // to the default expansion, which will generate a load from the constant
5505   // pool.
5506   if (isConstant)
5507     return SDValue();
5508
5509   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5510   if (NumElts >= 4) {
5511     SDValue shuffle = ReconstructShuffle(Op, DAG);
5512     if (shuffle != SDValue())
5513       return shuffle;
5514   }
5515
5516   // Vectors with 32- or 64-bit elements can be built by directly assigning
5517   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
5518   // will be legalized.
5519   if (EltSize >= 32) {
5520     // Do the expansion with floating-point types, since that is what the VFP
5521     // registers are defined to use, and since i64 is not legal.
5522     EVT EltVT = EVT::getFloatingPointVT(EltSize);
5523     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
5524     SmallVector<SDValue, 8> Ops;
5525     for (unsigned i = 0; i < NumElts; ++i)
5526       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
5527     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
5528     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5529   }
5530
5531   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5532   // know the default expansion would otherwise fall back on something even
5533   // worse. For a vector with one or two non-undef values, that's
5534   // scalar_to_vector for the elements followed by a shuffle (provided the
5535   // shuffle is valid for the target) and materialization element by element
5536   // on the stack followed by a load for everything else.
5537   if (!isConstant && !usesOnlyOneValue) {
5538     SDValue Vec = DAG.getUNDEF(VT);
5539     for (unsigned i = 0 ; i < NumElts; ++i) {
5540       SDValue V = Op.getOperand(i);
5541       if (V.getOpcode() == ISD::UNDEF)
5542         continue;
5543       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
5544       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5545     }
5546     return Vec;
5547   }
5548
5549   return SDValue();
5550 }
5551
5552 /// getExtFactor - Determine the adjustment factor for the position when
5553 /// generating an "extract from vector registers" instruction.
5554 static unsigned getExtFactor(SDValue &V) {
5555   EVT EltType = V.getValueType().getVectorElementType();
5556   return EltType.getSizeInBits() / 8;
5557 }
5558
5559 // Gather data to see if the operation can be modelled as a
5560 // shuffle in combination with VEXTs.
5561 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
5562                                               SelectionDAG &DAG) const {
5563   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5564   SDLoc dl(Op);
5565   EVT VT = Op.getValueType();
5566   unsigned NumElts = VT.getVectorNumElements();
5567
5568   struct ShuffleSourceInfo {
5569     SDValue Vec;
5570     unsigned MinElt;
5571     unsigned MaxElt;
5572
5573     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5574     // be compatible with the shuffle we intend to construct. As a result
5575     // ShuffleVec will be some sliding window into the original Vec.
5576     SDValue ShuffleVec;
5577
5578     // Code should guarantee that element i in Vec starts at element "WindowBase
5579     // + i * WindowScale in ShuffleVec".
5580     int WindowBase;
5581     int WindowScale;
5582
5583     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5584     ShuffleSourceInfo(SDValue Vec)
5585         : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5586           WindowScale(1) {}
5587   };
5588
5589   // First gather all vectors used as an immediate source for this BUILD_VECTOR
5590   // node.
5591   SmallVector<ShuffleSourceInfo, 2> Sources;
5592   for (unsigned i = 0; i < NumElts; ++i) {
5593     SDValue V = Op.getOperand(i);
5594     if (V.getOpcode() == ISD::UNDEF)
5595       continue;
5596     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
5597       // A shuffle can only come from building a vector from various
5598       // elements of other vectors.
5599       return SDValue();
5600     }
5601
5602     // Add this element source to the list if it's not already there.
5603     SDValue SourceVec = V.getOperand(0);
5604     auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5605     if (Source == Sources.end())
5606       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5607
5608     // Update the minimum and maximum lane number seen.
5609     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5610     Source->MinElt = std::min(Source->MinElt, EltNo);
5611     Source->MaxElt = std::max(Source->MaxElt, EltNo);
5612   }
5613
5614   // Currently only do something sane when at most two source vectors
5615   // are involved.
5616   if (Sources.size() > 2)
5617     return SDValue();
5618
5619   // Find out the smallest element size among result and two sources, and use
5620   // it as element size to build the shuffle_vector.
5621   EVT SmallestEltTy = VT.getVectorElementType();
5622   for (auto &Source : Sources) {
5623     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5624     if (SrcEltTy.bitsLT(SmallestEltTy))
5625       SmallestEltTy = SrcEltTy;
5626   }
5627   unsigned ResMultiplier =
5628       VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
5629   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5630   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5631
5632   // If the source vector is too wide or too narrow, we may nevertheless be able
5633   // to construct a compatible shuffle either by concatenating it with UNDEF or
5634   // extracting a suitable range of elements.
5635   for (auto &Src : Sources) {
5636     EVT SrcVT = Src.ShuffleVec.getValueType();
5637
5638     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5639       continue;
5640
5641     // This stage of the search produces a source with the same element type as
5642     // the original, but with a total width matching the BUILD_VECTOR output.
5643     EVT EltVT = SrcVT.getVectorElementType();
5644     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5645     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5646
5647     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5648       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
5649         return SDValue();
5650       // We can pad out the smaller vector for free, so if it's part of a
5651       // shuffle...
5652       Src.ShuffleVec =
5653           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5654                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5655       continue;
5656     }
5657
5658     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
5659       return SDValue();
5660
5661     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5662       // Span too large for a VEXT to cope
5663       return SDValue();
5664     }
5665
5666     if (Src.MinElt >= NumSrcElts) {
5667       // The extraction can just take the second half
5668       Src.ShuffleVec =
5669           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5670                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5671       Src.WindowBase = -NumSrcElts;
5672     } else if (Src.MaxElt < NumSrcElts) {
5673       // The extraction can just take the first half
5674       Src.ShuffleVec =
5675           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5676                       DAG.getConstant(0, dl, MVT::i32));
5677     } else {
5678       // An actual VEXT is needed
5679       SDValue VEXTSrc1 =
5680           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5681                       DAG.getConstant(0, dl, MVT::i32));
5682       SDValue VEXTSrc2 =
5683           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5684                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
5685       unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5686
5687       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
5688                                    VEXTSrc2,
5689                                    DAG.getConstant(Imm, dl, MVT::i32));
5690       Src.WindowBase = -Src.MinElt;
5691     }
5692   }
5693
5694   // Another possible incompatibility occurs from the vector element types. We
5695   // can fix this by bitcasting the source vectors to the same type we intend
5696   // for the shuffle.
5697   for (auto &Src : Sources) {
5698     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5699     if (SrcEltTy == SmallestEltTy)
5700       continue;
5701     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5702     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5703     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5704     Src.WindowBase *= Src.WindowScale;
5705   }
5706
5707   // Final sanity check before we try to actually produce a shuffle.
5708   DEBUG(
5709     for (auto Src : Sources)
5710       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5711   );
5712
5713   // The stars all align, our next step is to produce the mask for the shuffle.
5714   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5715   int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
5716   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5717     SDValue Entry = Op.getOperand(i);
5718     if (Entry.getOpcode() == ISD::UNDEF)
5719       continue;
5720
5721     auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5722     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5723
5724     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5725     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5726     // segment.
5727     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5728     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5729                                VT.getVectorElementType().getSizeInBits());
5730     int LanesDefined = BitsDefined / BitsPerShuffleLane;
5731
5732     // This source is expected to fill ResMultiplier lanes of the final shuffle,
5733     // starting at the appropriate offset.
5734     int *LaneMask = &Mask[i * ResMultiplier];
5735
5736     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5737     ExtractBase += NumElts * (Src - Sources.begin());
5738     for (int j = 0; j < LanesDefined; ++j)
5739       LaneMask[j] = ExtractBase + j;
5740   }
5741
5742   // Final check before we try to produce nonsense...
5743   if (!isShuffleMaskLegal(Mask, ShuffleVT))
5744     return SDValue();
5745
5746   // We can't handle more than two sources. This should have already
5747   // been checked before this point.
5748   assert(Sources.size() <= 2 && "Too many sources!");
5749
5750   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5751   for (unsigned i = 0; i < Sources.size(); ++i)
5752     ShuffleOps[i] = Sources[i].ShuffleVec;
5753
5754   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5755                                          ShuffleOps[1], &Mask[0]);
5756   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5757 }
5758
5759 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5760 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5761 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5762 /// are assumed to be legal.
5763 bool
5764 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5765                                       EVT VT) const {
5766   if (VT.getVectorNumElements() == 4 &&
5767       (VT.is128BitVector() || VT.is64BitVector())) {
5768     unsigned PFIndexes[4];
5769     for (unsigned i = 0; i != 4; ++i) {
5770       if (M[i] < 0)
5771         PFIndexes[i] = 8;
5772       else
5773         PFIndexes[i] = M[i];
5774     }
5775
5776     // Compute the index in the perfect shuffle table.
5777     unsigned PFTableIndex =
5778       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5779     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5780     unsigned Cost = (PFEntry >> 30);
5781
5782     if (Cost <= 4)
5783       return true;
5784   }
5785
5786   bool ReverseVEXT, isV_UNDEF;
5787   unsigned Imm, WhichResult;
5788
5789   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5790   return (EltSize >= 32 ||
5791           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
5792           isVREVMask(M, VT, 64) ||
5793           isVREVMask(M, VT, 32) ||
5794           isVREVMask(M, VT, 16) ||
5795           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
5796           isVTBLMask(M, VT) ||
5797           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
5798           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
5799 }
5800
5801 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5802 /// the specified operations to build the shuffle.
5803 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5804                                       SDValue RHS, SelectionDAG &DAG,
5805                                       SDLoc dl) {
5806   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5807   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5808   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5809
5810   enum {
5811     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5812     OP_VREV,
5813     OP_VDUP0,
5814     OP_VDUP1,
5815     OP_VDUP2,
5816     OP_VDUP3,
5817     OP_VEXT1,
5818     OP_VEXT2,
5819     OP_VEXT3,
5820     OP_VUZPL, // VUZP, left result
5821     OP_VUZPR, // VUZP, right result
5822     OP_VZIPL, // VZIP, left result
5823     OP_VZIPR, // VZIP, right result
5824     OP_VTRNL, // VTRN, left result
5825     OP_VTRNR  // VTRN, right result
5826   };
5827
5828   if (OpNum == OP_COPY) {
5829     if (LHSID == (1*9+2)*9+3) return LHS;
5830     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5831     return RHS;
5832   }
5833
5834   SDValue OpLHS, OpRHS;
5835   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5836   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5837   EVT VT = OpLHS.getValueType();
5838
5839   switch (OpNum) {
5840   default: llvm_unreachable("Unknown shuffle opcode!");
5841   case OP_VREV:
5842     // VREV divides the vector in half and swaps within the half.
5843     if (VT.getVectorElementType() == MVT::i32 ||
5844         VT.getVectorElementType() == MVT::f32)
5845       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
5846     // vrev <4 x i16> -> VREV32
5847     if (VT.getVectorElementType() == MVT::i16)
5848       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
5849     // vrev <4 x i8> -> VREV16
5850     assert(VT.getVectorElementType() == MVT::i8);
5851     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
5852   case OP_VDUP0:
5853   case OP_VDUP1:
5854   case OP_VDUP2:
5855   case OP_VDUP3:
5856     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
5857                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
5858   case OP_VEXT1:
5859   case OP_VEXT2:
5860   case OP_VEXT3:
5861     return DAG.getNode(ARMISD::VEXT, dl, VT,
5862                        OpLHS, OpRHS,
5863                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
5864   case OP_VUZPL:
5865   case OP_VUZPR:
5866     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
5867                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
5868   case OP_VZIPL:
5869   case OP_VZIPR:
5870     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
5871                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
5872   case OP_VTRNL:
5873   case OP_VTRNR:
5874     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
5875                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
5876   }
5877 }
5878
5879 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
5880                                        ArrayRef<int> ShuffleMask,
5881                                        SelectionDAG &DAG) {
5882   // Check to see if we can use the VTBL instruction.
5883   SDValue V1 = Op.getOperand(0);
5884   SDValue V2 = Op.getOperand(1);
5885   SDLoc DL(Op);
5886
5887   SmallVector<SDValue, 8> VTBLMask;
5888   for (ArrayRef<int>::iterator
5889          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
5890     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
5891
5892   if (V2.getNode()->getOpcode() == ISD::UNDEF)
5893     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
5894                        DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5895
5896   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
5897                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i8, VTBLMask));
5898 }
5899
5900 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
5901                                                       SelectionDAG &DAG) {
5902   SDLoc DL(Op);
5903   SDValue OpLHS = Op.getOperand(0);
5904   EVT VT = OpLHS.getValueType();
5905
5906   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
5907          "Expect an v8i16/v16i8 type");
5908   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
5909   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
5910   // extract the first 8 bytes into the top double word and the last 8 bytes
5911   // into the bottom double word. The v8i16 case is similar.
5912   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
5913   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
5914                      DAG.getConstant(ExtractNum, DL, MVT::i32));
5915 }
5916
5917 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
5918   SDValue V1 = Op.getOperand(0);
5919   SDValue V2 = Op.getOperand(1);
5920   SDLoc dl(Op);
5921   EVT VT = Op.getValueType();
5922   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5923
5924   // Convert shuffles that are directly supported on NEON to target-specific
5925   // DAG nodes, instead of keeping them as shuffles and matching them again
5926   // during code selection.  This is more efficient and avoids the possibility
5927   // of inconsistencies between legalization and selection.
5928   // FIXME: floating-point vectors should be canonicalized to integer vectors
5929   // of the same time so that they get CSEd properly.
5930   ArrayRef<int> ShuffleMask = SVN->getMask();
5931
5932   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5933   if (EltSize <= 32) {
5934     if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0], VT)) {
5935       int Lane = SVN->getSplatIndex();
5936       // If this is undef splat, generate it via "just" vdup, if possible.
5937       if (Lane == -1) Lane = 0;
5938
5939       // Test if V1 is a SCALAR_TO_VECTOR.
5940       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5941         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5942       }
5943       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
5944       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
5945       // reaches it).
5946       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
5947           !isa<ConstantSDNode>(V1.getOperand(0))) {
5948         bool IsScalarToVector = true;
5949         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
5950           if (V1.getOperand(i).getOpcode() != ISD::UNDEF) {
5951             IsScalarToVector = false;
5952             break;
5953           }
5954         if (IsScalarToVector)
5955           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
5956       }
5957       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
5958                          DAG.getConstant(Lane, dl, MVT::i32));
5959     }
5960
5961     bool ReverseVEXT;
5962     unsigned Imm;
5963     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
5964       if (ReverseVEXT)
5965         std::swap(V1, V2);
5966       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
5967                          DAG.getConstant(Imm, dl, MVT::i32));
5968     }
5969
5970     if (isVREVMask(ShuffleMask, VT, 64))
5971       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
5972     if (isVREVMask(ShuffleMask, VT, 32))
5973       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
5974     if (isVREVMask(ShuffleMask, VT, 16))
5975       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
5976
5977     if (V2->getOpcode() == ISD::UNDEF &&
5978         isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
5979       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
5980                          DAG.getConstant(Imm, dl, MVT::i32));
5981     }
5982
5983     // Check for Neon shuffles that modify both input vectors in place.
5984     // If both results are used, i.e., if there are two shuffles with the same
5985     // source operands and with masks corresponding to both results of one of
5986     // these operations, DAG memoization will ensure that a single node is
5987     // used for both shuffles.
5988     unsigned WhichResult;
5989     bool isV_UNDEF;
5990     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
5991             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
5992       if (isV_UNDEF)
5993         V2 = V1;
5994       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
5995           .getValue(WhichResult);
5996     }
5997
5998     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
5999     // shuffles that produce a result larger than their operands with:
6000     //   shuffle(concat(v1, undef), concat(v2, undef))
6001     // ->
6002     //   shuffle(concat(v1, v2), undef)
6003     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6004     //
6005     // This is useful in the general case, but there are special cases where
6006     // native shuffles produce larger results: the two-result ops.
6007     //
6008     // Look through the concat when lowering them:
6009     //   shuffle(concat(v1, v2), undef)
6010     // ->
6011     //   concat(VZIP(v1, v2):0, :1)
6012     //
6013     if (V1->getOpcode() == ISD::CONCAT_VECTORS &&
6014         V2->getOpcode() == ISD::UNDEF) {
6015       SDValue SubV1 = V1->getOperand(0);
6016       SDValue SubV2 = V1->getOperand(1);
6017       EVT SubVT = SubV1.getValueType();
6018
6019       // We expect these to have been canonicalized to -1.
6020       assert(std::all_of(ShuffleMask.begin(), ShuffleMask.end(), [&](int i) {
6021         return i < (int)VT.getVectorNumElements();
6022       }) && "Unexpected shuffle index into UNDEF operand!");
6023
6024       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6025               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6026         if (isV_UNDEF)
6027           SubV2 = SubV1;
6028         assert((WhichResult == 0) &&
6029                "In-place shuffle of concat can only have one result!");
6030         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6031                                   SubV1, SubV2);
6032         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6033                            Res.getValue(1));
6034       }
6035     }
6036   }
6037
6038   // If the shuffle is not directly supported and it has 4 elements, use
6039   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6040   unsigned NumElts = VT.getVectorNumElements();
6041   if (NumElts == 4) {
6042     unsigned PFIndexes[4];
6043     for (unsigned i = 0; i != 4; ++i) {
6044       if (ShuffleMask[i] < 0)
6045         PFIndexes[i] = 8;
6046       else
6047         PFIndexes[i] = ShuffleMask[i];
6048     }
6049
6050     // Compute the index in the perfect shuffle table.
6051     unsigned PFTableIndex =
6052       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6053     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6054     unsigned Cost = (PFEntry >> 30);
6055
6056     if (Cost <= 4)
6057       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6058   }
6059
6060   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6061   if (EltSize >= 32) {
6062     // Do the expansion with floating-point types, since that is what the VFP
6063     // registers are defined to use, and since i64 is not legal.
6064     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6065     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6066     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6067     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6068     SmallVector<SDValue, 8> Ops;
6069     for (unsigned i = 0; i < NumElts; ++i) {
6070       if (ShuffleMask[i] < 0)
6071         Ops.push_back(DAG.getUNDEF(EltVT));
6072       else
6073         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6074                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6075                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6076                                                   dl, MVT::i32)));
6077     }
6078     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6079     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6080   }
6081
6082   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6083     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6084
6085   if (VT == MVT::v8i8) {
6086     SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG);
6087     if (NewOp.getNode())
6088       return NewOp;
6089   }
6090
6091   return SDValue();
6092 }
6093
6094 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6095   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6096   SDValue Lane = Op.getOperand(2);
6097   if (!isa<ConstantSDNode>(Lane))
6098     return SDValue();
6099
6100   return Op;
6101 }
6102
6103 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6104   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6105   SDValue Lane = Op.getOperand(1);
6106   if (!isa<ConstantSDNode>(Lane))
6107     return SDValue();
6108
6109   SDValue Vec = Op.getOperand(0);
6110   if (Op.getValueType() == MVT::i32 &&
6111       Vec.getValueType().getVectorElementType().getSizeInBits() < 32) {
6112     SDLoc dl(Op);
6113     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6114   }
6115
6116   return Op;
6117 }
6118
6119 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6120   // The only time a CONCAT_VECTORS operation can have legal types is when
6121   // two 64-bit vectors are concatenated to a 128-bit vector.
6122   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6123          "unexpected CONCAT_VECTORS");
6124   SDLoc dl(Op);
6125   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6126   SDValue Op0 = Op.getOperand(0);
6127   SDValue Op1 = Op.getOperand(1);
6128   if (Op0.getOpcode() != ISD::UNDEF)
6129     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6130                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6131                       DAG.getIntPtrConstant(0, dl));
6132   if (Op1.getOpcode() != ISD::UNDEF)
6133     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6134                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6135                       DAG.getIntPtrConstant(1, dl));
6136   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6137 }
6138
6139 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6140 /// element has been zero/sign-extended, depending on the isSigned parameter,
6141 /// from an integer type half its size.
6142 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6143                                    bool isSigned) {
6144   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6145   EVT VT = N->getValueType(0);
6146   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6147     SDNode *BVN = N->getOperand(0).getNode();
6148     if (BVN->getValueType(0) != MVT::v4i32 ||
6149         BVN->getOpcode() != ISD::BUILD_VECTOR)
6150       return false;
6151     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6152     unsigned HiElt = 1 - LoElt;
6153     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6154     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6155     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6156     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6157     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6158       return false;
6159     if (isSigned) {
6160       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6161           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6162         return true;
6163     } else {
6164       if (Hi0->isNullValue() && Hi1->isNullValue())
6165         return true;
6166     }
6167     return false;
6168   }
6169
6170   if (N->getOpcode() != ISD::BUILD_VECTOR)
6171     return false;
6172
6173   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6174     SDNode *Elt = N->getOperand(i).getNode();
6175     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6176       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6177       unsigned HalfSize = EltSize / 2;
6178       if (isSigned) {
6179         if (!isIntN(HalfSize, C->getSExtValue()))
6180           return false;
6181       } else {
6182         if (!isUIntN(HalfSize, C->getZExtValue()))
6183           return false;
6184       }
6185       continue;
6186     }
6187     return false;
6188   }
6189
6190   return true;
6191 }
6192
6193 /// isSignExtended - Check if a node is a vector value that is sign-extended
6194 /// or a constant BUILD_VECTOR with sign-extended elements.
6195 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6196   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6197     return true;
6198   if (isExtendedBUILD_VECTOR(N, DAG, true))
6199     return true;
6200   return false;
6201 }
6202
6203 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6204 /// or a constant BUILD_VECTOR with zero-extended elements.
6205 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6206   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6207     return true;
6208   if (isExtendedBUILD_VECTOR(N, DAG, false))
6209     return true;
6210   return false;
6211 }
6212
6213 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6214   if (OrigVT.getSizeInBits() >= 64)
6215     return OrigVT;
6216
6217   assert(OrigVT.isSimple() && "Expecting a simple value type");
6218
6219   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6220   switch (OrigSimpleTy) {
6221   default: llvm_unreachable("Unexpected Vector Type");
6222   case MVT::v2i8:
6223   case MVT::v2i16:
6224      return MVT::v2i32;
6225   case MVT::v4i8:
6226     return  MVT::v4i16;
6227   }
6228 }
6229
6230 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6231 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6232 /// We insert the required extension here to get the vector to fill a D register.
6233 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6234                                             const EVT &OrigTy,
6235                                             const EVT &ExtTy,
6236                                             unsigned ExtOpcode) {
6237   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6238   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6239   // 64-bits we need to insert a new extension so that it will be 64-bits.
6240   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6241   if (OrigTy.getSizeInBits() >= 64)
6242     return N;
6243
6244   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6245   EVT NewVT = getExtensionTo64Bits(OrigTy);
6246
6247   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6248 }
6249
6250 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6251 /// does not do any sign/zero extension. If the original vector is less
6252 /// than 64 bits, an appropriate extension will be added after the load to
6253 /// reach a total size of 64 bits. We have to add the extension separately
6254 /// because ARM does not have a sign/zero extending load for vectors.
6255 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6256   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6257
6258   // The load already has the right type.
6259   if (ExtendedTy == LD->getMemoryVT())
6260     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6261                 LD->getBasePtr(), LD->getPointerInfo(), LD->isVolatile(),
6262                 LD->isNonTemporal(), LD->isInvariant(),
6263                 LD->getAlignment());
6264
6265   // We need to create a zextload/sextload. We cannot just create a load
6266   // followed by a zext/zext node because LowerMUL is also run during normal
6267   // operation legalization where we can't create illegal types.
6268   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6269                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6270                         LD->getMemoryVT(), LD->isVolatile(), LD->isInvariant(),
6271                         LD->isNonTemporal(), LD->getAlignment());
6272 }
6273
6274 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6275 /// extending load, or BUILD_VECTOR with extended elements, return the
6276 /// unextended value. The unextended vector should be 64 bits so that it can
6277 /// be used as an operand to a VMULL instruction. If the original vector size
6278 /// before extension is less than 64 bits we add a an extension to resize
6279 /// the vector to 64 bits.
6280 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6281   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6282     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6283                                         N->getOperand(0)->getValueType(0),
6284                                         N->getValueType(0),
6285                                         N->getOpcode());
6286
6287   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N))
6288     return SkipLoadExtensionForVMULL(LD, DAG);
6289
6290   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
6291   // have been legalized as a BITCAST from v4i32.
6292   if (N->getOpcode() == ISD::BITCAST) {
6293     SDNode *BVN = N->getOperand(0).getNode();
6294     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
6295            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
6296     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6297     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), MVT::v2i32,
6298                        BVN->getOperand(LowElt), BVN->getOperand(LowElt+2));
6299   }
6300   // Construct a new BUILD_VECTOR with elements truncated to half the size.
6301   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
6302   EVT VT = N->getValueType(0);
6303   unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
6304   unsigned NumElts = VT.getVectorNumElements();
6305   MVT TruncVT = MVT::getIntegerVT(EltSize);
6306   SmallVector<SDValue, 8> Ops;
6307   SDLoc dl(N);
6308   for (unsigned i = 0; i != NumElts; ++i) {
6309     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
6310     const APInt &CInt = C->getAPIntValue();
6311     // Element types smaller than 32 bits are not legal, so use i32 elements.
6312     // The values are implicitly truncated so sext vs. zext doesn't matter.
6313     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
6314   }
6315   return DAG.getNode(ISD::BUILD_VECTOR, dl,
6316                      MVT::getVectorVT(TruncVT, NumElts), Ops);
6317 }
6318
6319 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
6320   unsigned Opcode = N->getOpcode();
6321   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6322     SDNode *N0 = N->getOperand(0).getNode();
6323     SDNode *N1 = N->getOperand(1).getNode();
6324     return N0->hasOneUse() && N1->hasOneUse() &&
6325       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
6326   }
6327   return false;
6328 }
6329
6330 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
6331   unsigned Opcode = N->getOpcode();
6332   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
6333     SDNode *N0 = N->getOperand(0).getNode();
6334     SDNode *N1 = N->getOperand(1).getNode();
6335     return N0->hasOneUse() && N1->hasOneUse() &&
6336       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
6337   }
6338   return false;
6339 }
6340
6341 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
6342   // Multiplications are only custom-lowered for 128-bit vectors so that
6343   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
6344   EVT VT = Op.getValueType();
6345   assert(VT.is128BitVector() && VT.isInteger() &&
6346          "unexpected type for custom-lowering ISD::MUL");
6347   SDNode *N0 = Op.getOperand(0).getNode();
6348   SDNode *N1 = Op.getOperand(1).getNode();
6349   unsigned NewOpc = 0;
6350   bool isMLA = false;
6351   bool isN0SExt = isSignExtended(N0, DAG);
6352   bool isN1SExt = isSignExtended(N1, DAG);
6353   if (isN0SExt && isN1SExt)
6354     NewOpc = ARMISD::VMULLs;
6355   else {
6356     bool isN0ZExt = isZeroExtended(N0, DAG);
6357     bool isN1ZExt = isZeroExtended(N1, DAG);
6358     if (isN0ZExt && isN1ZExt)
6359       NewOpc = ARMISD::VMULLu;
6360     else if (isN1SExt || isN1ZExt) {
6361       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
6362       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
6363       if (isN1SExt && isAddSubSExt(N0, DAG)) {
6364         NewOpc = ARMISD::VMULLs;
6365         isMLA = true;
6366       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
6367         NewOpc = ARMISD::VMULLu;
6368         isMLA = true;
6369       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
6370         std::swap(N0, N1);
6371         NewOpc = ARMISD::VMULLu;
6372         isMLA = true;
6373       }
6374     }
6375
6376     if (!NewOpc) {
6377       if (VT == MVT::v2i64)
6378         // Fall through to expand this.  It is not legal.
6379         return SDValue();
6380       else
6381         // Other vector multiplications are legal.
6382         return Op;
6383     }
6384   }
6385
6386   // Legalize to a VMULL instruction.
6387   SDLoc DL(Op);
6388   SDValue Op0;
6389   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
6390   if (!isMLA) {
6391     Op0 = SkipExtensionForVMULL(N0, DAG);
6392     assert(Op0.getValueType().is64BitVector() &&
6393            Op1.getValueType().is64BitVector() &&
6394            "unexpected types for extended operands to VMULL");
6395     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
6396   }
6397
6398   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
6399   // isel lowering to take advantage of no-stall back to back vmul + vmla.
6400   //   vmull q0, d4, d6
6401   //   vmlal q0, d5, d6
6402   // is faster than
6403   //   vaddl q0, d4, d5
6404   //   vmovl q1, d6
6405   //   vmul  q0, q0, q1
6406   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
6407   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
6408   EVT Op1VT = Op1.getValueType();
6409   return DAG.getNode(N0->getOpcode(), DL, VT,
6410                      DAG.getNode(NewOpc, DL, VT,
6411                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
6412                      DAG.getNode(NewOpc, DL, VT,
6413                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
6414 }
6415
6416 static SDValue
6417 LowerSDIV_v4i8(SDValue X, SDValue Y, SDLoc dl, SelectionDAG &DAG) {
6418   // Convert to float
6419   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
6420   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
6421   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
6422   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
6423   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
6424   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
6425   // Get reciprocal estimate.
6426   // float4 recip = vrecpeq_f32(yf);
6427   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6428                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6429                    Y);
6430   // Because char has a smaller range than uchar, we can actually get away
6431   // without any newton steps.  This requires that we use a weird bias
6432   // of 0xb000, however (again, this has been exhaustively tested).
6433   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
6434   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
6435   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
6436   Y = DAG.getConstant(0xb000, dl, MVT::i32);
6437   Y = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Y, Y, Y, Y);
6438   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
6439   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
6440   // Convert back to short.
6441   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
6442   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
6443   return X;
6444 }
6445
6446 static SDValue
6447 LowerSDIV_v4i16(SDValue N0, SDValue N1, SDLoc dl, SelectionDAG &DAG) {
6448   SDValue N2;
6449   // Convert to float.
6450   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
6451   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
6452   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
6453   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
6454   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6455   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6456
6457   // Use reciprocal estimate and one refinement step.
6458   // float4 recip = vrecpeq_f32(yf);
6459   // recip *= vrecpsq_f32(yf, recip);
6460   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6461                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6462                    N1);
6463   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6464                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6465                    N1, N2);
6466   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6467   // Because short has a smaller range than ushort, we can actually get away
6468   // with only a single newton step.  This requires that we use a weird bias
6469   // of 89, however (again, this has been exhaustively tested).
6470   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
6471   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6472   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6473   N1 = DAG.getConstant(0x89, dl, MVT::i32);
6474   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6475   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6476   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6477   // Convert back to integer and return.
6478   // return vmovn_s32(vcvt_s32_f32(result));
6479   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6480   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6481   return N0;
6482 }
6483
6484 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
6485   EVT VT = Op.getValueType();
6486   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6487          "unexpected type for custom-lowering ISD::SDIV");
6488
6489   SDLoc dl(Op);
6490   SDValue N0 = Op.getOperand(0);
6491   SDValue N1 = Op.getOperand(1);
6492   SDValue N2, N3;
6493
6494   if (VT == MVT::v8i8) {
6495     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
6496     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
6497
6498     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6499                      DAG.getIntPtrConstant(4, dl));
6500     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6501                      DAG.getIntPtrConstant(4, dl));
6502     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6503                      DAG.getIntPtrConstant(0, dl));
6504     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6505                      DAG.getIntPtrConstant(0, dl));
6506
6507     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
6508     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
6509
6510     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6511     N0 = LowerCONCAT_VECTORS(N0, DAG);
6512
6513     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
6514     return N0;
6515   }
6516   return LowerSDIV_v4i16(N0, N1, dl, DAG);
6517 }
6518
6519 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
6520   EVT VT = Op.getValueType();
6521   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
6522          "unexpected type for custom-lowering ISD::UDIV");
6523
6524   SDLoc dl(Op);
6525   SDValue N0 = Op.getOperand(0);
6526   SDValue N1 = Op.getOperand(1);
6527   SDValue N2, N3;
6528
6529   if (VT == MVT::v8i8) {
6530     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
6531     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
6532
6533     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6534                      DAG.getIntPtrConstant(4, dl));
6535     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6536                      DAG.getIntPtrConstant(4, dl));
6537     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
6538                      DAG.getIntPtrConstant(0, dl));
6539     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
6540                      DAG.getIntPtrConstant(0, dl));
6541
6542     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
6543     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
6544
6545     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
6546     N0 = LowerCONCAT_VECTORS(N0, DAG);
6547
6548     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
6549                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
6550                                      MVT::i32),
6551                      N0);
6552     return N0;
6553   }
6554
6555   // v4i16 sdiv ... Convert to float.
6556   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
6557   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
6558   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
6559   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
6560   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
6561   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
6562
6563   // Use reciprocal estimate and two refinement steps.
6564   // float4 recip = vrecpeq_f32(yf);
6565   // recip *= vrecpsq_f32(yf, recip);
6566   // recip *= vrecpsq_f32(yf, recip);
6567   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6568                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
6569                    BN1);
6570   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6571                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6572                    BN1, N2);
6573   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6574   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
6575                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
6576                    BN1, N2);
6577   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
6578   // Simply multiplying by the reciprocal estimate can leave us a few ulps
6579   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
6580   // and that it will never cause us to return an answer too large).
6581   // float4 result = as_float4(as_int4(xf*recip) + 2);
6582   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
6583   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
6584   N1 = DAG.getConstant(2, dl, MVT::i32);
6585   N1 = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, N1, N1, N1, N1);
6586   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
6587   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
6588   // Convert back to integer and return.
6589   // return vmovn_u32(vcvt_s32_f32(result));
6590   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
6591   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
6592   return N0;
6593 }
6594
6595 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
6596   EVT VT = Op.getNode()->getValueType(0);
6597   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
6598
6599   unsigned Opc;
6600   bool ExtraOp = false;
6601   switch (Op.getOpcode()) {
6602   default: llvm_unreachable("Invalid code");
6603   case ISD::ADDC: Opc = ARMISD::ADDC; break;
6604   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
6605   case ISD::SUBC: Opc = ARMISD::SUBC; break;
6606   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
6607   }
6608
6609   if (!ExtraOp)
6610     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6611                        Op.getOperand(1));
6612   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
6613                      Op.getOperand(1), Op.getOperand(2));
6614 }
6615
6616 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
6617   assert(Subtarget->isTargetDarwin());
6618
6619   // For iOS, we want to call an alternative entry point: __sincos_stret,
6620   // return values are passed via sret.
6621   SDLoc dl(Op);
6622   SDValue Arg = Op.getOperand(0);
6623   EVT ArgVT = Arg.getValueType();
6624   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
6625   auto PtrVT = getPointerTy(DAG.getDataLayout());
6626
6627   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6628
6629   // Pair of floats / doubles used to pass the result.
6630   StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
6631
6632   // Create stack object for sret.
6633   auto &DL = DAG.getDataLayout();
6634   const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
6635   const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
6636   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign, false);
6637   SDValue SRet = DAG.getFrameIndex(FrameIdx, getPointerTy(DL));
6638
6639   ArgListTy Args;
6640   ArgListEntry Entry;
6641
6642   Entry.Node = SRet;
6643   Entry.Ty = RetTy->getPointerTo();
6644   Entry.isSExt = false;
6645   Entry.isZExt = false;
6646   Entry.isSRet = true;
6647   Args.push_back(Entry);
6648
6649   Entry.Node = Arg;
6650   Entry.Ty = ArgTy;
6651   Entry.isSExt = false;
6652   Entry.isZExt = false;
6653   Args.push_back(Entry);
6654
6655   const char *LibcallName  = (ArgVT == MVT::f64)
6656   ? "__sincos_stret" : "__sincosf_stret";
6657   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
6658
6659   TargetLowering::CallLoweringInfo CLI(DAG);
6660   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
6661     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()), Callee,
6662                std::move(Args), 0)
6663     .setDiscardResult();
6664
6665   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6666
6667   SDValue LoadSin = DAG.getLoad(ArgVT, dl, CallResult.second, SRet,
6668                                 MachinePointerInfo(), false, false, false, 0);
6669
6670   // Address of cos field.
6671   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
6672                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
6673   SDValue LoadCos = DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add,
6674                                 MachinePointerInfo(), false, false, false, 0);
6675
6676   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
6677   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
6678                      LoadSin.getValue(0), LoadCos.getValue(0));
6679 }
6680
6681 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
6682   // Monotonic load/store is legal for all targets
6683   if (cast<AtomicSDNode>(Op)->getOrdering() <= Monotonic)
6684     return Op;
6685
6686   // Acquire/Release load/store is not legal for targets without a
6687   // dmb or equivalent available.
6688   return SDValue();
6689 }
6690
6691 static void ReplaceREADCYCLECOUNTER(SDNode *N,
6692                                     SmallVectorImpl<SDValue> &Results,
6693                                     SelectionDAG &DAG,
6694                                     const ARMSubtarget *Subtarget) {
6695   SDLoc DL(N);
6696   SDValue Cycles32, OutChain;
6697
6698   if (Subtarget->hasPerfMon()) {
6699     // Under Power Management extensions, the cycle-count is:
6700     //    mrc p15, #0, <Rt>, c9, c13, #0
6701     SDValue Ops[] = { N->getOperand(0), // Chain
6702                       DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
6703                       DAG.getConstant(15, DL, MVT::i32),
6704                       DAG.getConstant(0, DL, MVT::i32),
6705                       DAG.getConstant(9, DL, MVT::i32),
6706                       DAG.getConstant(13, DL, MVT::i32),
6707                       DAG.getConstant(0, DL, MVT::i32)
6708     };
6709
6710     Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
6711                            DAG.getVTList(MVT::i32, MVT::Other), Ops);
6712     OutChain = Cycles32.getValue(1);
6713   } else {
6714     // Intrinsic is defined to return 0 on unsupported platforms. Technically
6715     // there are older ARM CPUs that have implementation-specific ways of
6716     // obtaining this information (FIXME!).
6717     Cycles32 = DAG.getConstant(0, DL, MVT::i32);
6718     OutChain = DAG.getEntryNode();
6719   }
6720
6721
6722   SDValue Cycles64 = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64,
6723                                  Cycles32, DAG.getConstant(0, DL, MVT::i32));
6724   Results.push_back(Cycles64);
6725   Results.push_back(OutChain);
6726 }
6727
6728 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6729   switch (Op.getOpcode()) {
6730   default: llvm_unreachable("Don't know how to custom lower this!");
6731   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
6732   case ISD::ConstantPool:  return LowerConstantPool(Op, DAG);
6733   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
6734   case ISD::GlobalAddress:
6735     switch (Subtarget->getTargetTriple().getObjectFormat()) {
6736     default: llvm_unreachable("unknown object format");
6737     case Triple::COFF:
6738       return LowerGlobalAddressWindows(Op, DAG);
6739     case Triple::ELF:
6740       return LowerGlobalAddressELF(Op, DAG);
6741     case Triple::MachO:
6742       return LowerGlobalAddressDarwin(Op, DAG);
6743     }
6744   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6745   case ISD::SELECT:        return LowerSELECT(Op, DAG);
6746   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
6747   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
6748   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
6749   case ISD::VASTART:       return LowerVASTART(Op, DAG);
6750   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
6751   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
6752   case ISD::SINT_TO_FP:
6753   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
6754   case ISD::FP_TO_SINT:
6755   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
6756   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
6757   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
6758   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
6759   case ISD::GLOBAL_OFFSET_TABLE: return LowerGLOBAL_OFFSET_TABLE(Op, DAG);
6760   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
6761   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
6762   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
6763   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
6764                                                                Subtarget);
6765   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
6766   case ISD::SHL:
6767   case ISD::SRL:
6768   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
6769   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
6770   case ISD::SRL_PARTS:
6771   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
6772   case ISD::CTTZ:
6773   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
6774   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
6775   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
6776   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
6777   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
6778   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6779   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6780   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6781   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
6782   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
6783   case ISD::MUL:           return LowerMUL(Op, DAG);
6784   case ISD::SDIV:          return LowerSDIV(Op, DAG);
6785   case ISD::UDIV:          return LowerUDIV(Op, DAG);
6786   case ISD::ADDC:
6787   case ISD::ADDE:
6788   case ISD::SUBC:
6789   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
6790   case ISD::SADDO:
6791   case ISD::UADDO:
6792   case ISD::SSUBO:
6793   case ISD::USUBO:
6794     return LowerXALUO(Op, DAG);
6795   case ISD::ATOMIC_LOAD:
6796   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
6797   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
6798   case ISD::SDIVREM:
6799   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
6800   case ISD::DYNAMIC_STACKALLOC:
6801     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
6802       return LowerDYNAMIC_STACKALLOC(Op, DAG);
6803     llvm_unreachable("Don't know how to custom lower this!");
6804   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
6805   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
6806   }
6807 }
6808
6809 /// ReplaceNodeResults - Replace the results of node with an illegal result
6810 /// type with new values built out of custom code.
6811 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
6812                                            SmallVectorImpl<SDValue>&Results,
6813                                            SelectionDAG &DAG) const {
6814   SDValue Res;
6815   switch (N->getOpcode()) {
6816   default:
6817     llvm_unreachable("Don't know how to custom expand this!");
6818   case ISD::READ_REGISTER:
6819     ExpandREAD_REGISTER(N, Results, DAG);
6820     break;
6821   case ISD::BITCAST:
6822     Res = ExpandBITCAST(N, DAG);
6823     break;
6824   case ISD::SRL:
6825   case ISD::SRA:
6826     Res = Expand64BitShift(N, DAG, Subtarget);
6827     break;
6828   case ISD::READCYCLECOUNTER:
6829     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
6830     return;
6831   }
6832   if (Res.getNode())
6833     Results.push_back(Res);
6834 }
6835
6836 //===----------------------------------------------------------------------===//
6837 //                           ARM Scheduler Hooks
6838 //===----------------------------------------------------------------------===//
6839
6840 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
6841 /// registers the function context.
6842 void ARMTargetLowering::
6843 SetupEntryBlockForSjLj(MachineInstr *MI, MachineBasicBlock *MBB,
6844                        MachineBasicBlock *DispatchBB, int FI) const {
6845   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6846   DebugLoc dl = MI->getDebugLoc();
6847   MachineFunction *MF = MBB->getParent();
6848   MachineRegisterInfo *MRI = &MF->getRegInfo();
6849   MachineConstantPool *MCP = MF->getConstantPool();
6850   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
6851   const Function *F = MF->getFunction();
6852
6853   bool isThumb = Subtarget->isThumb();
6854   bool isThumb2 = Subtarget->isThumb2();
6855
6856   unsigned PCLabelId = AFI->createPICLabelUId();
6857   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
6858   ARMConstantPoolValue *CPV =
6859     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
6860   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
6861
6862   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
6863                                            : &ARM::GPRRegClass;
6864
6865   // Grab constant pool and fixed stack memory operands.
6866   MachineMemOperand *CPMMO =
6867     MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(),
6868                              MachineMemOperand::MOLoad, 4, 4);
6869
6870   MachineMemOperand *FIMMOSt =
6871     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
6872                              MachineMemOperand::MOStore, 4, 4);
6873
6874   // Load the address of the dispatch MBB into the jump buffer.
6875   if (isThumb2) {
6876     // Incoming value: jbuf
6877     //   ldr.n  r5, LCPI1_1
6878     //   orr    r5, r5, #1
6879     //   add    r5, pc
6880     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
6881     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6882     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
6883                    .addConstantPoolIndex(CPI)
6884                    .addMemOperand(CPMMO));
6885     // Set the low bit because of thumb mode.
6886     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6887     AddDefaultCC(
6888       AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
6889                      .addReg(NewVReg1, RegState::Kill)
6890                      .addImm(0x01)));
6891     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6892     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
6893       .addReg(NewVReg2, RegState::Kill)
6894       .addImm(PCLabelId);
6895     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
6896                    .addReg(NewVReg3, RegState::Kill)
6897                    .addFrameIndex(FI)
6898                    .addImm(36)  // &jbuf[1] :: pc
6899                    .addMemOperand(FIMMOSt));
6900   } else if (isThumb) {
6901     // Incoming value: jbuf
6902     //   ldr.n  r1, LCPI1_4
6903     //   add    r1, pc
6904     //   mov    r2, #1
6905     //   orrs   r1, r2
6906     //   add    r2, $jbuf, #+4 ; &jbuf[1]
6907     //   str    r1, [r2]
6908     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6909     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
6910                    .addConstantPoolIndex(CPI)
6911                    .addMemOperand(CPMMO));
6912     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6913     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
6914       .addReg(NewVReg1, RegState::Kill)
6915       .addImm(PCLabelId);
6916     // Set the low bit because of thumb mode.
6917     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
6918     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
6919                    .addReg(ARM::CPSR, RegState::Define)
6920                    .addImm(1));
6921     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
6922     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
6923                    .addReg(ARM::CPSR, RegState::Define)
6924                    .addReg(NewVReg2, RegState::Kill)
6925                    .addReg(NewVReg3, RegState::Kill));
6926     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
6927     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
6928             .addFrameIndex(FI)
6929             .addImm(36); // &jbuf[1] :: pc
6930     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
6931                    .addReg(NewVReg4, RegState::Kill)
6932                    .addReg(NewVReg5, RegState::Kill)
6933                    .addImm(0)
6934                    .addMemOperand(FIMMOSt));
6935   } else {
6936     // Incoming value: jbuf
6937     //   ldr  r1, LCPI1_1
6938     //   add  r1, pc, r1
6939     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
6940     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
6941     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12),  NewVReg1)
6942                    .addConstantPoolIndex(CPI)
6943                    .addImm(0)
6944                    .addMemOperand(CPMMO));
6945     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
6946     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
6947                    .addReg(NewVReg1, RegState::Kill)
6948                    .addImm(PCLabelId));
6949     AddDefaultPred(BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
6950                    .addReg(NewVReg2, RegState::Kill)
6951                    .addFrameIndex(FI)
6952                    .addImm(36)  // &jbuf[1] :: pc
6953                    .addMemOperand(FIMMOSt));
6954   }
6955 }
6956
6957 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr *MI,
6958                                               MachineBasicBlock *MBB) const {
6959   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
6960   DebugLoc dl = MI->getDebugLoc();
6961   MachineFunction *MF = MBB->getParent();
6962   MachineRegisterInfo *MRI = &MF->getRegInfo();
6963   MachineFrameInfo *MFI = MF->getFrameInfo();
6964   int FI = MFI->getFunctionContextIndex();
6965
6966   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
6967                                                         : &ARM::GPRnopcRegClass;
6968
6969   // Get a mapping of the call site numbers to all of the landing pads they're
6970   // associated with.
6971   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2> > CallSiteNumToLPad;
6972   unsigned MaxCSNum = 0;
6973   MachineModuleInfo &MMI = MF->getMMI();
6974   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
6975        ++BB) {
6976     if (!BB->isLandingPad()) continue;
6977
6978     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
6979     // pad.
6980     for (MachineBasicBlock::iterator
6981            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
6982       if (!II->isEHLabel()) continue;
6983
6984       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
6985       if (!MMI.hasCallSiteLandingPad(Sym)) continue;
6986
6987       SmallVectorImpl<unsigned> &CallSiteIdxs = MMI.getCallSiteLandingPad(Sym);
6988       for (SmallVectorImpl<unsigned>::iterator
6989              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
6990            CSI != CSE; ++CSI) {
6991         CallSiteNumToLPad[*CSI].push_back(BB);
6992         MaxCSNum = std::max(MaxCSNum, *CSI);
6993       }
6994       break;
6995     }
6996   }
6997
6998   // Get an ordered list of the machine basic blocks for the jump table.
6999   std::vector<MachineBasicBlock*> LPadList;
7000   SmallPtrSet<MachineBasicBlock*, 64> InvokeBBs;
7001   LPadList.reserve(CallSiteNumToLPad.size());
7002   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7003     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7004     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7005            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7006       LPadList.push_back(*II);
7007       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7008     }
7009   }
7010
7011   assert(!LPadList.empty() &&
7012          "No landing pad destinations for the dispatch jump table!");
7013
7014   // Create the jump table and associated information.
7015   MachineJumpTableInfo *JTI =
7016     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7017   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7018   Reloc::Model RelocM = getTargetMachine().getRelocationModel();
7019
7020   // Create the MBBs for the dispatch code.
7021
7022   // Shove the dispatch's address into the return slot in the function context.
7023   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7024   DispatchBB->setIsLandingPad();
7025
7026   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7027   unsigned trap_opcode;
7028   if (Subtarget->isThumb())
7029     trap_opcode = ARM::tTRAP;
7030   else
7031     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7032
7033   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7034   DispatchBB->addSuccessor(TrapBB);
7035
7036   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7037   DispatchBB->addSuccessor(DispContBB);
7038
7039   // Insert and MBBs.
7040   MF->insert(MF->end(), DispatchBB);
7041   MF->insert(MF->end(), DispContBB);
7042   MF->insert(MF->end(), TrapBB);
7043
7044   // Insert code into the entry block that creates and registers the function
7045   // context.
7046   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7047
7048   MachineMemOperand *FIMMOLd =
7049     MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(FI),
7050                              MachineMemOperand::MOLoad |
7051                              MachineMemOperand::MOVolatile, 4, 4);
7052
7053   MachineInstrBuilder MIB;
7054   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7055
7056   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7057   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7058
7059   // Add a register mask with no preserved registers.  This results in all
7060   // registers being marked as clobbered.
7061   MIB.addRegMask(RI.getNoPreservedMask());
7062
7063   unsigned NumLPads = LPadList.size();
7064   if (Subtarget->isThumb2()) {
7065     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7066     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
7067                    .addFrameIndex(FI)
7068                    .addImm(4)
7069                    .addMemOperand(FIMMOLd));
7070
7071     if (NumLPads < 256) {
7072       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
7073                      .addReg(NewVReg1)
7074                      .addImm(LPadList.size()));
7075     } else {
7076       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7077       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
7078                      .addImm(NumLPads & 0xFFFF));
7079
7080       unsigned VReg2 = VReg1;
7081       if ((NumLPads & 0xFFFF0000) != 0) {
7082         VReg2 = MRI->createVirtualRegister(TRC);
7083         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
7084                        .addReg(VReg1)
7085                        .addImm(NumLPads >> 16));
7086       }
7087
7088       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
7089                      .addReg(NewVReg1)
7090                      .addReg(VReg2));
7091     }
7092
7093     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
7094       .addMBB(TrapBB)
7095       .addImm(ARMCC::HI)
7096       .addReg(ARM::CPSR);
7097
7098     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7099     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT),NewVReg3)
7100                    .addJumpTableIndex(MJTI));
7101
7102     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7103     AddDefaultCC(
7104       AddDefaultPred(
7105         BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
7106         .addReg(NewVReg3, RegState::Kill)
7107         .addReg(NewVReg1)
7108         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7109
7110     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
7111       .addReg(NewVReg4, RegState::Kill)
7112       .addReg(NewVReg1)
7113       .addJumpTableIndex(MJTI);
7114   } else if (Subtarget->isThumb()) {
7115     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7116     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
7117                    .addFrameIndex(FI)
7118                    .addImm(1)
7119                    .addMemOperand(FIMMOLd));
7120
7121     if (NumLPads < 256) {
7122       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
7123                      .addReg(NewVReg1)
7124                      .addImm(NumLPads));
7125     } else {
7126       MachineConstantPool *ConstantPool = MF->getConstantPool();
7127       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7128       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7129
7130       // MachineConstantPool wants an explicit alignment.
7131       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7132       if (Align == 0)
7133         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7134       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7135
7136       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7137       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
7138                      .addReg(VReg1, RegState::Define)
7139                      .addConstantPoolIndex(Idx));
7140       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
7141                      .addReg(NewVReg1)
7142                      .addReg(VReg1));
7143     }
7144
7145     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
7146       .addMBB(TrapBB)
7147       .addImm(ARMCC::HI)
7148       .addReg(ARM::CPSR);
7149
7150     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7151     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
7152                    .addReg(ARM::CPSR, RegState::Define)
7153                    .addReg(NewVReg1)
7154                    .addImm(2));
7155
7156     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7157     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
7158                    .addJumpTableIndex(MJTI));
7159
7160     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7161     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
7162                    .addReg(ARM::CPSR, RegState::Define)
7163                    .addReg(NewVReg2, RegState::Kill)
7164                    .addReg(NewVReg3));
7165
7166     MachineMemOperand *JTMMOLd =
7167       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7168                                MachineMemOperand::MOLoad, 4, 4);
7169
7170     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7171     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
7172                    .addReg(NewVReg4, RegState::Kill)
7173                    .addImm(0)
7174                    .addMemOperand(JTMMOLd));
7175
7176     unsigned NewVReg6 = NewVReg5;
7177     if (RelocM == Reloc::PIC_) {
7178       NewVReg6 = MRI->createVirtualRegister(TRC);
7179       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
7180                      .addReg(ARM::CPSR, RegState::Define)
7181                      .addReg(NewVReg5, RegState::Kill)
7182                      .addReg(NewVReg3));
7183     }
7184
7185     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
7186       .addReg(NewVReg6, RegState::Kill)
7187       .addJumpTableIndex(MJTI);
7188   } else {
7189     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7190     AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
7191                    .addFrameIndex(FI)
7192                    .addImm(4)
7193                    .addMemOperand(FIMMOLd));
7194
7195     if (NumLPads < 256) {
7196       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
7197                      .addReg(NewVReg1)
7198                      .addImm(NumLPads));
7199     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
7200       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7201       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
7202                      .addImm(NumLPads & 0xFFFF));
7203
7204       unsigned VReg2 = VReg1;
7205       if ((NumLPads & 0xFFFF0000) != 0) {
7206         VReg2 = MRI->createVirtualRegister(TRC);
7207         AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
7208                        .addReg(VReg1)
7209                        .addImm(NumLPads >> 16));
7210       }
7211
7212       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7213                      .addReg(NewVReg1)
7214                      .addReg(VReg2));
7215     } else {
7216       MachineConstantPool *ConstantPool = MF->getConstantPool();
7217       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7218       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
7219
7220       // MachineConstantPool wants an explicit alignment.
7221       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7222       if (Align == 0)
7223         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7224       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7225
7226       unsigned VReg1 = MRI->createVirtualRegister(TRC);
7227       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
7228                      .addReg(VReg1, RegState::Define)
7229                      .addConstantPoolIndex(Idx)
7230                      .addImm(0));
7231       AddDefaultPred(BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
7232                      .addReg(NewVReg1)
7233                      .addReg(VReg1, RegState::Kill));
7234     }
7235
7236     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
7237       .addMBB(TrapBB)
7238       .addImm(ARMCC::HI)
7239       .addReg(ARM::CPSR);
7240
7241     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7242     AddDefaultCC(
7243       AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
7244                      .addReg(NewVReg1)
7245                      .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))));
7246     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7247     AddDefaultPred(BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
7248                    .addJumpTableIndex(MJTI));
7249
7250     MachineMemOperand *JTMMOLd =
7251       MF->getMachineMemOperand(MachinePointerInfo::getJumpTable(),
7252                                MachineMemOperand::MOLoad, 4, 4);
7253     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7254     AddDefaultPred(
7255       BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
7256       .addReg(NewVReg3, RegState::Kill)
7257       .addReg(NewVReg4)
7258       .addImm(0)
7259       .addMemOperand(JTMMOLd));
7260
7261     if (RelocM == Reloc::PIC_) {
7262       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
7263         .addReg(NewVReg5, RegState::Kill)
7264         .addReg(NewVReg4)
7265         .addJumpTableIndex(MJTI);
7266     } else {
7267       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
7268         .addReg(NewVReg5, RegState::Kill)
7269         .addJumpTableIndex(MJTI);
7270     }
7271   }
7272
7273   // Add the jump table entries as successors to the MBB.
7274   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
7275   for (std::vector<MachineBasicBlock*>::iterator
7276          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
7277     MachineBasicBlock *CurMBB = *I;
7278     if (SeenMBBs.insert(CurMBB).second)
7279       DispContBB->addSuccessor(CurMBB);
7280   }
7281
7282   // N.B. the order the invoke BBs are processed in doesn't matter here.
7283   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
7284   SmallVector<MachineBasicBlock*, 64> MBBLPads;
7285   for (MachineBasicBlock *BB : InvokeBBs) {
7286
7287     // Remove the landing pad successor from the invoke block and replace it
7288     // with the new dispatch block.
7289     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
7290                                                   BB->succ_end());
7291     while (!Successors.empty()) {
7292       MachineBasicBlock *SMBB = Successors.pop_back_val();
7293       if (SMBB->isLandingPad()) {
7294         BB->removeSuccessor(SMBB);
7295         MBBLPads.push_back(SMBB);
7296       }
7297     }
7298
7299     BB->addSuccessor(DispatchBB);
7300
7301     // Find the invoke call and mark all of the callee-saved registers as
7302     // 'implicit defined' so that they're spilled. This prevents code from
7303     // moving instructions to before the EH block, where they will never be
7304     // executed.
7305     for (MachineBasicBlock::reverse_iterator
7306            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
7307       if (!II->isCall()) continue;
7308
7309       DenseMap<unsigned, bool> DefRegs;
7310       for (MachineInstr::mop_iterator
7311              OI = II->operands_begin(), OE = II->operands_end();
7312            OI != OE; ++OI) {
7313         if (!OI->isReg()) continue;
7314         DefRegs[OI->getReg()] = true;
7315       }
7316
7317       MachineInstrBuilder MIB(*MF, &*II);
7318
7319       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
7320         unsigned Reg = SavedRegs[i];
7321         if (Subtarget->isThumb2() &&
7322             !ARM::tGPRRegClass.contains(Reg) &&
7323             !ARM::hGPRRegClass.contains(Reg))
7324           continue;
7325         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
7326           continue;
7327         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
7328           continue;
7329         if (!DefRegs[Reg])
7330           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
7331       }
7332
7333       break;
7334     }
7335   }
7336
7337   // Mark all former landing pads as non-landing pads. The dispatch is the only
7338   // landing pad now.
7339   for (SmallVectorImpl<MachineBasicBlock*>::iterator
7340          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
7341     (*I)->setIsLandingPad(false);
7342
7343   // The instruction is gone now.
7344   MI->eraseFromParent();
7345 }
7346
7347 static
7348 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
7349   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
7350        E = MBB->succ_end(); I != E; ++I)
7351     if (*I != Succ)
7352       return *I;
7353   llvm_unreachable("Expecting a BB with two successors!");
7354 }
7355
7356 /// Return the load opcode for a given load size. If load size >= 8,
7357 /// neon opcode will be returned.
7358 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
7359   if (LdSize >= 8)
7360     return LdSize == 16 ? ARM::VLD1q32wb_fixed
7361                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
7362   if (IsThumb1)
7363     return LdSize == 4 ? ARM::tLDRi
7364                        : LdSize == 2 ? ARM::tLDRHi
7365                                      : LdSize == 1 ? ARM::tLDRBi : 0;
7366   if (IsThumb2)
7367     return LdSize == 4 ? ARM::t2LDR_POST
7368                        : LdSize == 2 ? ARM::t2LDRH_POST
7369                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
7370   return LdSize == 4 ? ARM::LDR_POST_IMM
7371                      : LdSize == 2 ? ARM::LDRH_POST
7372                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
7373 }
7374
7375 /// Return the store opcode for a given store size. If store size >= 8,
7376 /// neon opcode will be returned.
7377 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
7378   if (StSize >= 8)
7379     return StSize == 16 ? ARM::VST1q32wb_fixed
7380                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
7381   if (IsThumb1)
7382     return StSize == 4 ? ARM::tSTRi
7383                        : StSize == 2 ? ARM::tSTRHi
7384                                      : StSize == 1 ? ARM::tSTRBi : 0;
7385   if (IsThumb2)
7386     return StSize == 4 ? ARM::t2STR_POST
7387                        : StSize == 2 ? ARM::t2STRH_POST
7388                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
7389   return StSize == 4 ? ARM::STR_POST_IMM
7390                      : StSize == 2 ? ARM::STRH_POST
7391                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
7392 }
7393
7394 /// Emit a post-increment load operation with given size. The instructions
7395 /// will be added to BB at Pos.
7396 static void emitPostLd(MachineBasicBlock *BB, MachineInstr *Pos,
7397                        const TargetInstrInfo *TII, DebugLoc dl,
7398                        unsigned LdSize, unsigned Data, unsigned AddrIn,
7399                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7400   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
7401   assert(LdOpc != 0 && "Should have a load opcode");
7402   if (LdSize >= 8) {
7403     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7404                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7405                        .addImm(0));
7406   } else if (IsThumb1) {
7407     // load + update AddrIn
7408     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7409                        .addReg(AddrIn).addImm(0));
7410     MachineInstrBuilder MIB =
7411         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7412     MIB = AddDefaultT1CC(MIB);
7413     MIB.addReg(AddrIn).addImm(LdSize);
7414     AddDefaultPred(MIB);
7415   } else if (IsThumb2) {
7416     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7417                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7418                        .addImm(LdSize));
7419   } else { // arm
7420     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
7421                        .addReg(AddrOut, RegState::Define).addReg(AddrIn)
7422                        .addReg(0).addImm(LdSize));
7423   }
7424 }
7425
7426 /// Emit a post-increment store operation with given size. The instructions
7427 /// will be added to BB at Pos.
7428 static void emitPostSt(MachineBasicBlock *BB, MachineInstr *Pos,
7429                        const TargetInstrInfo *TII, DebugLoc dl,
7430                        unsigned StSize, unsigned Data, unsigned AddrIn,
7431                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
7432   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
7433   assert(StOpc != 0 && "Should have a store opcode");
7434   if (StSize >= 8) {
7435     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7436                        .addReg(AddrIn).addImm(0).addReg(Data));
7437   } else if (IsThumb1) {
7438     // store + update AddrIn
7439     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc)).addReg(Data)
7440                        .addReg(AddrIn).addImm(0));
7441     MachineInstrBuilder MIB =
7442         BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut);
7443     MIB = AddDefaultT1CC(MIB);
7444     MIB.addReg(AddrIn).addImm(StSize);
7445     AddDefaultPred(MIB);
7446   } else if (IsThumb2) {
7447     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7448                        .addReg(Data).addReg(AddrIn).addImm(StSize));
7449   } else { // arm
7450     AddDefaultPred(BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
7451                        .addReg(Data).addReg(AddrIn).addReg(0)
7452                        .addImm(StSize));
7453   }
7454 }
7455
7456 MachineBasicBlock *
7457 ARMTargetLowering::EmitStructByval(MachineInstr *MI,
7458                                    MachineBasicBlock *BB) const {
7459   // This pseudo instruction has 3 operands: dst, src, size
7460   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
7461   // Otherwise, we will generate unrolled scalar copies.
7462   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7463   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7464   MachineFunction::iterator It = BB;
7465   ++It;
7466
7467   unsigned dest = MI->getOperand(0).getReg();
7468   unsigned src = MI->getOperand(1).getReg();
7469   unsigned SizeVal = MI->getOperand(2).getImm();
7470   unsigned Align = MI->getOperand(3).getImm();
7471   DebugLoc dl = MI->getDebugLoc();
7472
7473   MachineFunction *MF = BB->getParent();
7474   MachineRegisterInfo &MRI = MF->getRegInfo();
7475   unsigned UnitSize = 0;
7476   const TargetRegisterClass *TRC = nullptr;
7477   const TargetRegisterClass *VecTRC = nullptr;
7478
7479   bool IsThumb1 = Subtarget->isThumb1Only();
7480   bool IsThumb2 = Subtarget->isThumb2();
7481
7482   if (Align & 1) {
7483     UnitSize = 1;
7484   } else if (Align & 2) {
7485     UnitSize = 2;
7486   } else {
7487     // Check whether we can use NEON instructions.
7488     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
7489         Subtarget->hasNEON()) {
7490       if ((Align % 16 == 0) && SizeVal >= 16)
7491         UnitSize = 16;
7492       else if ((Align % 8 == 0) && SizeVal >= 8)
7493         UnitSize = 8;
7494     }
7495     // Can't use NEON instructions.
7496     if (UnitSize == 0)
7497       UnitSize = 4;
7498   }
7499
7500   // Select the correct opcode and register class for unit size load/store
7501   bool IsNeon = UnitSize >= 8;
7502   TRC = (IsThumb1 || IsThumb2) ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
7503   if (IsNeon)
7504     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
7505                             : UnitSize == 8 ? &ARM::DPRRegClass
7506                                             : nullptr;
7507
7508   unsigned BytesLeft = SizeVal % UnitSize;
7509   unsigned LoopSize = SizeVal - BytesLeft;
7510
7511   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
7512     // Use LDR and STR to copy.
7513     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
7514     // [destOut] = STR_POST(scratch, destIn, UnitSize)
7515     unsigned srcIn = src;
7516     unsigned destIn = dest;
7517     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
7518       unsigned srcOut = MRI.createVirtualRegister(TRC);
7519       unsigned destOut = MRI.createVirtualRegister(TRC);
7520       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7521       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
7522                  IsThumb1, IsThumb2);
7523       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
7524                  IsThumb1, IsThumb2);
7525       srcIn = srcOut;
7526       destIn = destOut;
7527     }
7528
7529     // Handle the leftover bytes with LDRB and STRB.
7530     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
7531     // [destOut] = STRB_POST(scratch, destIn, 1)
7532     for (unsigned i = 0; i < BytesLeft; i++) {
7533       unsigned srcOut = MRI.createVirtualRegister(TRC);
7534       unsigned destOut = MRI.createVirtualRegister(TRC);
7535       unsigned scratch = MRI.createVirtualRegister(TRC);
7536       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
7537                  IsThumb1, IsThumb2);
7538       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
7539                  IsThumb1, IsThumb2);
7540       srcIn = srcOut;
7541       destIn = destOut;
7542     }
7543     MI->eraseFromParent();   // The instruction is gone now.
7544     return BB;
7545   }
7546
7547   // Expand the pseudo op to a loop.
7548   // thisMBB:
7549   //   ...
7550   //   movw varEnd, # --> with thumb2
7551   //   movt varEnd, #
7552   //   ldrcp varEnd, idx --> without thumb2
7553   //   fallthrough --> loopMBB
7554   // loopMBB:
7555   //   PHI varPhi, varEnd, varLoop
7556   //   PHI srcPhi, src, srcLoop
7557   //   PHI destPhi, dst, destLoop
7558   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7559   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
7560   //   subs varLoop, varPhi, #UnitSize
7561   //   bne loopMBB
7562   //   fallthrough --> exitMBB
7563   // exitMBB:
7564   //   epilogue to handle left-over bytes
7565   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7566   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7567   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7568   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
7569   MF->insert(It, loopMBB);
7570   MF->insert(It, exitMBB);
7571
7572   // Transfer the remainder of BB and its successor edges to exitMBB.
7573   exitMBB->splice(exitMBB->begin(), BB,
7574                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
7575   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7576
7577   // Load an immediate to varEnd.
7578   unsigned varEnd = MRI.createVirtualRegister(TRC);
7579   if (Subtarget->useMovt(*MF)) {
7580     unsigned Vtmp = varEnd;
7581     if ((LoopSize & 0xFFFF0000) != 0)
7582       Vtmp = MRI.createVirtualRegister(TRC);
7583     AddDefaultPred(BuildMI(BB, dl,
7584                            TII->get(IsThumb2 ? ARM::t2MOVi16 : ARM::MOVi16),
7585                            Vtmp).addImm(LoopSize & 0xFFFF));
7586
7587     if ((LoopSize & 0xFFFF0000) != 0)
7588       AddDefaultPred(BuildMI(BB, dl,
7589                              TII->get(IsThumb2 ? ARM::t2MOVTi16 : ARM::MOVTi16),
7590                              varEnd)
7591                          .addReg(Vtmp)
7592                          .addImm(LoopSize >> 16));
7593   } else {
7594     MachineConstantPool *ConstantPool = MF->getConstantPool();
7595     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
7596     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
7597
7598     // MachineConstantPool wants an explicit alignment.
7599     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
7600     if (Align == 0)
7601       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
7602     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
7603
7604     if (IsThumb1)
7605       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci)).addReg(
7606           varEnd, RegState::Define).addConstantPoolIndex(Idx));
7607     else
7608       AddDefaultPred(BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp)).addReg(
7609           varEnd, RegState::Define).addConstantPoolIndex(Idx).addImm(0));
7610   }
7611   BB->addSuccessor(loopMBB);
7612
7613   // Generate the loop body:
7614   //   varPhi = PHI(varLoop, varEnd)
7615   //   srcPhi = PHI(srcLoop, src)
7616   //   destPhi = PHI(destLoop, dst)
7617   MachineBasicBlock *entryBB = BB;
7618   BB = loopMBB;
7619   unsigned varLoop = MRI.createVirtualRegister(TRC);
7620   unsigned varPhi = MRI.createVirtualRegister(TRC);
7621   unsigned srcLoop = MRI.createVirtualRegister(TRC);
7622   unsigned srcPhi = MRI.createVirtualRegister(TRC);
7623   unsigned destLoop = MRI.createVirtualRegister(TRC);
7624   unsigned destPhi = MRI.createVirtualRegister(TRC);
7625
7626   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
7627     .addReg(varLoop).addMBB(loopMBB)
7628     .addReg(varEnd).addMBB(entryBB);
7629   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
7630     .addReg(srcLoop).addMBB(loopMBB)
7631     .addReg(src).addMBB(entryBB);
7632   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
7633     .addReg(destLoop).addMBB(loopMBB)
7634     .addReg(dest).addMBB(entryBB);
7635
7636   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
7637   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
7638   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
7639   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
7640              IsThumb1, IsThumb2);
7641   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
7642              IsThumb1, IsThumb2);
7643
7644   // Decrement loop variable by UnitSize.
7645   if (IsThumb1) {
7646     MachineInstrBuilder MIB =
7647         BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop);
7648     MIB = AddDefaultT1CC(MIB);
7649     MIB.addReg(varPhi).addImm(UnitSize);
7650     AddDefaultPred(MIB);
7651   } else {
7652     MachineInstrBuilder MIB =
7653         BuildMI(*BB, BB->end(), dl,
7654                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
7655     AddDefaultCC(AddDefaultPred(MIB.addReg(varPhi).addImm(UnitSize)));
7656     MIB->getOperand(5).setReg(ARM::CPSR);
7657     MIB->getOperand(5).setIsDef(true);
7658   }
7659   BuildMI(*BB, BB->end(), dl,
7660           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
7661       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
7662
7663   // loopMBB can loop back to loopMBB or fall through to exitMBB.
7664   BB->addSuccessor(loopMBB);
7665   BB->addSuccessor(exitMBB);
7666
7667   // Add epilogue to handle BytesLeft.
7668   BB = exitMBB;
7669   MachineInstr *StartOfExit = exitMBB->begin();
7670
7671   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
7672   //   [destOut] = STRB_POST(scratch, destLoop, 1)
7673   unsigned srcIn = srcLoop;
7674   unsigned destIn = destLoop;
7675   for (unsigned i = 0; i < BytesLeft; i++) {
7676     unsigned srcOut = MRI.createVirtualRegister(TRC);
7677     unsigned destOut = MRI.createVirtualRegister(TRC);
7678     unsigned scratch = MRI.createVirtualRegister(TRC);
7679     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
7680                IsThumb1, IsThumb2);
7681     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
7682                IsThumb1, IsThumb2);
7683     srcIn = srcOut;
7684     destIn = destOut;
7685   }
7686
7687   MI->eraseFromParent();   // The instruction is gone now.
7688   return BB;
7689 }
7690
7691 MachineBasicBlock *
7692 ARMTargetLowering::EmitLowered__chkstk(MachineInstr *MI,
7693                                        MachineBasicBlock *MBB) const {
7694   const TargetMachine &TM = getTargetMachine();
7695   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
7696   DebugLoc DL = MI->getDebugLoc();
7697
7698   assert(Subtarget->isTargetWindows() &&
7699          "__chkstk is only supported on Windows");
7700   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
7701
7702   // __chkstk takes the number of words to allocate on the stack in R4, and
7703   // returns the stack adjustment in number of bytes in R4.  This will not
7704   // clober any other registers (other than the obvious lr).
7705   //
7706   // Although, technically, IP should be considered a register which may be
7707   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
7708   // thumb-2 environment, so there is no interworking required.  As a result, we
7709   // do not expect a veneer to be emitted by the linker, clobbering IP.
7710   //
7711   // Each module receives its own copy of __chkstk, so no import thunk is
7712   // required, again, ensuring that IP is not clobbered.
7713   //
7714   // Finally, although some linkers may theoretically provide a trampoline for
7715   // out of range calls (which is quite common due to a 32M range limitation of
7716   // branches for Thumb), we can generate the long-call version via
7717   // -mcmodel=large, alleviating the need for the trampoline which may clobber
7718   // IP.
7719
7720   switch (TM.getCodeModel()) {
7721   case CodeModel::Small:
7722   case CodeModel::Medium:
7723   case CodeModel::Default:
7724   case CodeModel::Kernel:
7725     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
7726       .addImm((unsigned)ARMCC::AL).addReg(0)
7727       .addExternalSymbol("__chkstk")
7728       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7729       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7730       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7731     break;
7732   case CodeModel::Large:
7733   case CodeModel::JITDefault: {
7734     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
7735     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
7736
7737     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
7738       .addExternalSymbol("__chkstk");
7739     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
7740       .addImm((unsigned)ARMCC::AL).addReg(0)
7741       .addReg(Reg, RegState::Kill)
7742       .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
7743       .addReg(ARM::R4, RegState::Implicit | RegState::Define)
7744       .addReg(ARM::R12, RegState::Implicit | RegState::Define | RegState::Dead);
7745     break;
7746   }
7747   }
7748
7749   AddDefaultCC(AddDefaultPred(BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr),
7750                                       ARM::SP)
7751                               .addReg(ARM::SP).addReg(ARM::R4)));
7752
7753   MI->eraseFromParent();
7754   return MBB;
7755 }
7756
7757 MachineBasicBlock *
7758 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7759                                                MachineBasicBlock *BB) const {
7760   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7761   DebugLoc dl = MI->getDebugLoc();
7762   bool isThumb2 = Subtarget->isThumb2();
7763   switch (MI->getOpcode()) {
7764   default: {
7765     MI->dump();
7766     llvm_unreachable("Unexpected instr type to insert");
7767   }
7768   // The Thumb2 pre-indexed stores have the same MI operands, they just
7769   // define them differently in the .td files from the isel patterns, so
7770   // they need pseudos.
7771   case ARM::t2STR_preidx:
7772     MI->setDesc(TII->get(ARM::t2STR_PRE));
7773     return BB;
7774   case ARM::t2STRB_preidx:
7775     MI->setDesc(TII->get(ARM::t2STRB_PRE));
7776     return BB;
7777   case ARM::t2STRH_preidx:
7778     MI->setDesc(TII->get(ARM::t2STRH_PRE));
7779     return BB;
7780
7781   case ARM::STRi_preidx:
7782   case ARM::STRBi_preidx: {
7783     unsigned NewOpc = MI->getOpcode() == ARM::STRi_preidx ?
7784       ARM::STR_PRE_IMM : ARM::STRB_PRE_IMM;
7785     // Decode the offset.
7786     unsigned Offset = MI->getOperand(4).getImm();
7787     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
7788     Offset = ARM_AM::getAM2Offset(Offset);
7789     if (isSub)
7790       Offset = -Offset;
7791
7792     MachineMemOperand *MMO = *MI->memoperands_begin();
7793     BuildMI(*BB, MI, dl, TII->get(NewOpc))
7794       .addOperand(MI->getOperand(0))  // Rn_wb
7795       .addOperand(MI->getOperand(1))  // Rt
7796       .addOperand(MI->getOperand(2))  // Rn
7797       .addImm(Offset)                 // offset (skip GPR==zero_reg)
7798       .addOperand(MI->getOperand(5))  // pred
7799       .addOperand(MI->getOperand(6))
7800       .addMemOperand(MMO);
7801     MI->eraseFromParent();
7802     return BB;
7803   }
7804   case ARM::STRr_preidx:
7805   case ARM::STRBr_preidx:
7806   case ARM::STRH_preidx: {
7807     unsigned NewOpc;
7808     switch (MI->getOpcode()) {
7809     default: llvm_unreachable("unexpected opcode!");
7810     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
7811     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
7812     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
7813     }
7814     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
7815     for (unsigned i = 0; i < MI->getNumOperands(); ++i)
7816       MIB.addOperand(MI->getOperand(i));
7817     MI->eraseFromParent();
7818     return BB;
7819   }
7820
7821   case ARM::tMOVCCr_pseudo: {
7822     // To "insert" a SELECT_CC instruction, we actually have to insert the
7823     // diamond control-flow pattern.  The incoming instruction knows the
7824     // destination vreg to set, the condition code register to branch on, the
7825     // true/false values to select between, and a branch opcode to use.
7826     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7827     MachineFunction::iterator It = BB;
7828     ++It;
7829
7830     //  thisMBB:
7831     //  ...
7832     //   TrueVal = ...
7833     //   cmpTY ccX, r1, r2
7834     //   bCC copy1MBB
7835     //   fallthrough --> copy0MBB
7836     MachineBasicBlock *thisMBB  = BB;
7837     MachineFunction *F = BB->getParent();
7838     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7839     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
7840     F->insert(It, copy0MBB);
7841     F->insert(It, sinkMBB);
7842
7843     // Transfer the remainder of BB and its successor edges to sinkMBB.
7844     sinkMBB->splice(sinkMBB->begin(), BB,
7845                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7846     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7847
7848     BB->addSuccessor(copy0MBB);
7849     BB->addSuccessor(sinkMBB);
7850
7851     BuildMI(BB, dl, TII->get(ARM::tBcc)).addMBB(sinkMBB)
7852       .addImm(MI->getOperand(3).getImm()).addReg(MI->getOperand(4).getReg());
7853
7854     //  copy0MBB:
7855     //   %FalseValue = ...
7856     //   # fallthrough to sinkMBB
7857     BB = copy0MBB;
7858
7859     // Update machine-CFG edges
7860     BB->addSuccessor(sinkMBB);
7861
7862     //  sinkMBB:
7863     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7864     //  ...
7865     BB = sinkMBB;
7866     BuildMI(*BB, BB->begin(), dl,
7867             TII->get(ARM::PHI), MI->getOperand(0).getReg())
7868       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7869       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7870
7871     MI->eraseFromParent();   // The pseudo instruction is gone now.
7872     return BB;
7873   }
7874
7875   case ARM::BCCi64:
7876   case ARM::BCCZi64: {
7877     // If there is an unconditional branch to the other successor, remove it.
7878     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
7879
7880     // Compare both parts that make up the double comparison separately for
7881     // equality.
7882     bool RHSisZero = MI->getOpcode() == ARM::BCCZi64;
7883
7884     unsigned LHS1 = MI->getOperand(1).getReg();
7885     unsigned LHS2 = MI->getOperand(2).getReg();
7886     if (RHSisZero) {
7887       AddDefaultPred(BuildMI(BB, dl,
7888                              TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7889                      .addReg(LHS1).addImm(0));
7890       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7891         .addReg(LHS2).addImm(0)
7892         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7893     } else {
7894       unsigned RHS1 = MI->getOperand(3).getReg();
7895       unsigned RHS2 = MI->getOperand(4).getReg();
7896       AddDefaultPred(BuildMI(BB, dl,
7897                              TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7898                      .addReg(LHS1).addReg(RHS1));
7899       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
7900         .addReg(LHS2).addReg(RHS2)
7901         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
7902     }
7903
7904     MachineBasicBlock *destMBB = MI->getOperand(RHSisZero ? 3 : 5).getMBB();
7905     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
7906     if (MI->getOperand(0).getImm() == ARMCC::NE)
7907       std::swap(destMBB, exitMBB);
7908
7909     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
7910       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
7911     if (isThumb2)
7912       AddDefaultPred(BuildMI(BB, dl, TII->get(ARM::t2B)).addMBB(exitMBB));
7913     else
7914       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
7915
7916     MI->eraseFromParent();   // The pseudo instruction is gone now.
7917     return BB;
7918   }
7919
7920   case ARM::Int_eh_sjlj_setjmp:
7921   case ARM::Int_eh_sjlj_setjmp_nofp:
7922   case ARM::tInt_eh_sjlj_setjmp:
7923   case ARM::t2Int_eh_sjlj_setjmp:
7924   case ARM::t2Int_eh_sjlj_setjmp_nofp:
7925     return BB;
7926
7927   case ARM::Int_eh_sjlj_setup_dispatch:
7928     EmitSjLjDispatchBlock(MI, BB);
7929     return BB;
7930
7931   case ARM::ABS:
7932   case ARM::t2ABS: {
7933     // To insert an ABS instruction, we have to insert the
7934     // diamond control-flow pattern.  The incoming instruction knows the
7935     // source vreg to test against 0, the destination vreg to set,
7936     // the condition code register to branch on, the
7937     // true/false values to select between, and a branch opcode to use.
7938     // It transforms
7939     //     V1 = ABS V0
7940     // into
7941     //     V2 = MOVS V0
7942     //     BCC                      (branch to SinkBB if V0 >= 0)
7943     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
7944     //     SinkBB: V1 = PHI(V2, V3)
7945     const BasicBlock *LLVM_BB = BB->getBasicBlock();
7946     MachineFunction::iterator BBI = BB;
7947     ++BBI;
7948     MachineFunction *Fn = BB->getParent();
7949     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
7950     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
7951     Fn->insert(BBI, RSBBB);
7952     Fn->insert(BBI, SinkBB);
7953
7954     unsigned int ABSSrcReg = MI->getOperand(1).getReg();
7955     unsigned int ABSDstReg = MI->getOperand(0).getReg();
7956     bool ABSSrcKIll = MI->getOperand(1).isKill();
7957     bool isThumb2 = Subtarget->isThumb2();
7958     MachineRegisterInfo &MRI = Fn->getRegInfo();
7959     // In Thumb mode S must not be specified if source register is the SP or
7960     // PC and if destination register is the SP, so restrict register class
7961     unsigned NewRsbDstReg =
7962       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
7963
7964     // Transfer the remainder of BB and its successor edges to sinkMBB.
7965     SinkBB->splice(SinkBB->begin(), BB,
7966                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
7967     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
7968
7969     BB->addSuccessor(RSBBB);
7970     BB->addSuccessor(SinkBB);
7971
7972     // fall through to SinkMBB
7973     RSBBB->addSuccessor(SinkBB);
7974
7975     // insert a cmp at the end of BB
7976     AddDefaultPred(BuildMI(BB, dl,
7977                            TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
7978                    .addReg(ABSSrcReg).addImm(0));
7979
7980     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
7981     BuildMI(BB, dl,
7982       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
7983       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
7984
7985     // insert rsbri in RSBBB
7986     // Note: BCC and rsbri will be converted into predicated rsbmi
7987     // by if-conversion pass
7988     BuildMI(*RSBBB, RSBBB->begin(), dl,
7989       TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
7990       .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
7991       .addImm(0).addImm((unsigned)ARMCC::AL).addReg(0).addReg(0);
7992
7993     // insert PHI in SinkBB,
7994     // reuse ABSDstReg to not change uses of ABS instruction
7995     BuildMI(*SinkBB, SinkBB->begin(), dl,
7996       TII->get(ARM::PHI), ABSDstReg)
7997       .addReg(NewRsbDstReg).addMBB(RSBBB)
7998       .addReg(ABSSrcReg).addMBB(BB);
7999
8000     // remove ABS instruction
8001     MI->eraseFromParent();
8002
8003     // return last added BB
8004     return SinkBB;
8005   }
8006   case ARM::COPY_STRUCT_BYVAL_I32:
8007     ++NumLoopByVals;
8008     return EmitStructByval(MI, BB);
8009   case ARM::WIN__CHKSTK:
8010     return EmitLowered__chkstk(MI, BB);
8011   }
8012 }
8013
8014 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
8015                                                       SDNode *Node) const {
8016   const MCInstrDesc *MCID = &MI->getDesc();
8017   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
8018   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
8019   // operand is still set to noreg. If needed, set the optional operand's
8020   // register to CPSR, and remove the redundant implicit def.
8021   //
8022   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
8023
8024   // Rename pseudo opcodes.
8025   unsigned NewOpc = convertAddSubFlagsOpcode(MI->getOpcode());
8026   if (NewOpc) {
8027     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
8028     MCID = &TII->get(NewOpc);
8029
8030     assert(MCID->getNumOperands() == MI->getDesc().getNumOperands() + 1 &&
8031            "converted opcode should be the same except for cc_out");
8032
8033     MI->setDesc(*MCID);
8034
8035     // Add the optional cc_out operand
8036     MI->addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
8037   }
8038   unsigned ccOutIdx = MCID->getNumOperands() - 1;
8039
8040   // Any ARM instruction that sets the 's' bit should specify an optional
8041   // "cc_out" operand in the last operand position.
8042   if (!MI->hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
8043     assert(!NewOpc && "Optional cc_out operand required");
8044     return;
8045   }
8046   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
8047   // since we already have an optional CPSR def.
8048   bool definesCPSR = false;
8049   bool deadCPSR = false;
8050   for (unsigned i = MCID->getNumOperands(), e = MI->getNumOperands();
8051        i != e; ++i) {
8052     const MachineOperand &MO = MI->getOperand(i);
8053     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
8054       definesCPSR = true;
8055       if (MO.isDead())
8056         deadCPSR = true;
8057       MI->RemoveOperand(i);
8058       break;
8059     }
8060   }
8061   if (!definesCPSR) {
8062     assert(!NewOpc && "Optional cc_out operand required");
8063     return;
8064   }
8065   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
8066   if (deadCPSR) {
8067     assert(!MI->getOperand(ccOutIdx).getReg() &&
8068            "expect uninitialized optional cc_out operand");
8069     return;
8070   }
8071
8072   // If this instruction was defined with an optional CPSR def and its dag node
8073   // had a live implicit CPSR def, then activate the optional CPSR def.
8074   MachineOperand &MO = MI->getOperand(ccOutIdx);
8075   MO.setReg(ARM::CPSR);
8076   MO.setIsDef(true);
8077 }
8078
8079 //===----------------------------------------------------------------------===//
8080 //                           ARM Optimization Hooks
8081 //===----------------------------------------------------------------------===//
8082
8083 // Helper function that checks if N is a null or all ones constant.
8084 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
8085   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
8086   if (!C)
8087     return false;
8088   return AllOnes ? C->isAllOnesValue() : C->isNullValue();
8089 }
8090
8091 // Return true if N is conditionally 0 or all ones.
8092 // Detects these expressions where cc is an i1 value:
8093 //
8094 //   (select cc 0, y)   [AllOnes=0]
8095 //   (select cc y, 0)   [AllOnes=0]
8096 //   (zext cc)          [AllOnes=0]
8097 //   (sext cc)          [AllOnes=0/1]
8098 //   (select cc -1, y)  [AllOnes=1]
8099 //   (select cc y, -1)  [AllOnes=1]
8100 //
8101 // Invert is set when N is the null/all ones constant when CC is false.
8102 // OtherOp is set to the alternative value of N.
8103 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
8104                                        SDValue &CC, bool &Invert,
8105                                        SDValue &OtherOp,
8106                                        SelectionDAG &DAG) {
8107   switch (N->getOpcode()) {
8108   default: return false;
8109   case ISD::SELECT: {
8110     CC = N->getOperand(0);
8111     SDValue N1 = N->getOperand(1);
8112     SDValue N2 = N->getOperand(2);
8113     if (isZeroOrAllOnes(N1, AllOnes)) {
8114       Invert = false;
8115       OtherOp = N2;
8116       return true;
8117     }
8118     if (isZeroOrAllOnes(N2, AllOnes)) {
8119       Invert = true;
8120       OtherOp = N1;
8121       return true;
8122     }
8123     return false;
8124   }
8125   case ISD::ZERO_EXTEND:
8126     // (zext cc) can never be the all ones value.
8127     if (AllOnes)
8128       return false;
8129     // Fall through.
8130   case ISD::SIGN_EXTEND: {
8131     SDLoc dl(N);
8132     EVT VT = N->getValueType(0);
8133     CC = N->getOperand(0);
8134     if (CC.getValueType() != MVT::i1)
8135       return false;
8136     Invert = !AllOnes;
8137     if (AllOnes)
8138       // When looking for an AllOnes constant, N is an sext, and the 'other'
8139       // value is 0.
8140       OtherOp = DAG.getConstant(0, dl, VT);
8141     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8142       // When looking for a 0 constant, N can be zext or sext.
8143       OtherOp = DAG.getConstant(1, dl, VT);
8144     else
8145       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
8146                                 VT);
8147     return true;
8148   }
8149   }
8150 }
8151
8152 // Combine a constant select operand into its use:
8153 //
8154 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
8155 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
8156 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
8157 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
8158 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
8159 //
8160 // The transform is rejected if the select doesn't have a constant operand that
8161 // is null, or all ones when AllOnes is set.
8162 //
8163 // Also recognize sext/zext from i1:
8164 //
8165 //   (add (zext cc), x) -> (select cc (add x, 1), x)
8166 //   (add (sext cc), x) -> (select cc (add x, -1), x)
8167 //
8168 // These transformations eventually create predicated instructions.
8169 //
8170 // @param N       The node to transform.
8171 // @param Slct    The N operand that is a select.
8172 // @param OtherOp The other N operand (x above).
8173 // @param DCI     Context.
8174 // @param AllOnes Require the select constant to be all ones instead of null.
8175 // @returns The new node, or SDValue() on failure.
8176 static
8177 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
8178                             TargetLowering::DAGCombinerInfo &DCI,
8179                             bool AllOnes = false) {
8180   SelectionDAG &DAG = DCI.DAG;
8181   EVT VT = N->getValueType(0);
8182   SDValue NonConstantVal;
8183   SDValue CCOp;
8184   bool SwapSelectOps;
8185   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
8186                                   NonConstantVal, DAG))
8187     return SDValue();
8188
8189   // Slct is now know to be the desired identity constant when CC is true.
8190   SDValue TrueVal = OtherOp;
8191   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
8192                                  OtherOp, NonConstantVal);
8193   // Unless SwapSelectOps says CC should be false.
8194   if (SwapSelectOps)
8195     std::swap(TrueVal, FalseVal);
8196
8197   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
8198                      CCOp, TrueVal, FalseVal);
8199 }
8200
8201 // Attempt combineSelectAndUse on each operand of a commutative operator N.
8202 static
8203 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
8204                                        TargetLowering::DAGCombinerInfo &DCI) {
8205   SDValue N0 = N->getOperand(0);
8206   SDValue N1 = N->getOperand(1);
8207   if (N0.getNode()->hasOneUse()) {
8208     SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes);
8209     if (Result.getNode())
8210       return Result;
8211   }
8212   if (N1.getNode()->hasOneUse()) {
8213     SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes);
8214     if (Result.getNode())
8215       return Result;
8216   }
8217   return SDValue();
8218 }
8219
8220 // AddCombineToVPADDL- For pair-wise add on neon, use the vpaddl instruction
8221 // (only after legalization).
8222 static SDValue AddCombineToVPADDL(SDNode *N, SDValue N0, SDValue N1,
8223                                  TargetLowering::DAGCombinerInfo &DCI,
8224                                  const ARMSubtarget *Subtarget) {
8225
8226   // Only perform optimization if after legalize, and if NEON is available. We
8227   // also expected both operands to be BUILD_VECTORs.
8228   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
8229       || N0.getOpcode() != ISD::BUILD_VECTOR
8230       || N1.getOpcode() != ISD::BUILD_VECTOR)
8231     return SDValue();
8232
8233   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
8234   EVT VT = N->getValueType(0);
8235   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
8236     return SDValue();
8237
8238   // Check that the vector operands are of the right form.
8239   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
8240   // operands, where N is the size of the formed vector.
8241   // Each EXTRACT_VECTOR should have the same input vector and odd or even
8242   // index such that we have a pair wise add pattern.
8243
8244   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
8245   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8246     return SDValue();
8247   SDValue Vec = N0->getOperand(0)->getOperand(0);
8248   SDNode *V = Vec.getNode();
8249   unsigned nextIndex = 0;
8250
8251   // For each operands to the ADD which are BUILD_VECTORs,
8252   // check to see if each of their operands are an EXTRACT_VECTOR with
8253   // the same vector and appropriate index.
8254   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
8255     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
8256         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8257
8258       SDValue ExtVec0 = N0->getOperand(i);
8259       SDValue ExtVec1 = N1->getOperand(i);
8260
8261       // First operand is the vector, verify its the same.
8262       if (V != ExtVec0->getOperand(0).getNode() ||
8263           V != ExtVec1->getOperand(0).getNode())
8264         return SDValue();
8265
8266       // Second is the constant, verify its correct.
8267       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
8268       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
8269
8270       // For the constant, we want to see all the even or all the odd.
8271       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
8272           || C1->getZExtValue() != nextIndex+1)
8273         return SDValue();
8274
8275       // Increment index.
8276       nextIndex+=2;
8277     } else
8278       return SDValue();
8279   }
8280
8281   // Create VPADDL node.
8282   SelectionDAG &DAG = DCI.DAG;
8283   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8284
8285   SDLoc dl(N);
8286
8287   // Build operand list.
8288   SmallVector<SDValue, 8> Ops;
8289   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
8290                                 TLI.getPointerTy(DAG.getDataLayout())));
8291
8292   // Input is the vector.
8293   Ops.push_back(Vec);
8294
8295   // Get widened type and narrowed type.
8296   MVT widenType;
8297   unsigned numElem = VT.getVectorNumElements();
8298   
8299   EVT inputLaneType = Vec.getValueType().getVectorElementType();
8300   switch (inputLaneType.getSimpleVT().SimpleTy) {
8301     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
8302     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
8303     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
8304     default:
8305       llvm_unreachable("Invalid vector element type for padd optimization.");
8306   }
8307
8308   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
8309   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
8310   return DAG.getNode(ExtOp, dl, VT, tmp);
8311 }
8312
8313 static SDValue findMUL_LOHI(SDValue V) {
8314   if (V->getOpcode() == ISD::UMUL_LOHI ||
8315       V->getOpcode() == ISD::SMUL_LOHI)
8316     return V;
8317   return SDValue();
8318 }
8319
8320 static SDValue AddCombineTo64bitMLAL(SDNode *AddcNode,
8321                                      TargetLowering::DAGCombinerInfo &DCI,
8322                                      const ARMSubtarget *Subtarget) {
8323
8324   if (Subtarget->isThumb1Only()) return SDValue();
8325
8326   // Only perform the checks after legalize when the pattern is available.
8327   if (DCI.isBeforeLegalize()) return SDValue();
8328
8329   // Look for multiply add opportunities.
8330   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
8331   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
8332   // a glue link from the first add to the second add.
8333   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
8334   // a S/UMLAL instruction.
8335   //                  UMUL_LOHI
8336   //                 / :lo    \ :hi
8337   //                /          \          [no multiline comment]
8338   //    loAdd ->  ADDE         |
8339   //                 \ :glue  /
8340   //                  \      /
8341   //                    ADDC   <- hiAdd
8342   //
8343   assert(AddcNode->getOpcode() == ISD::ADDC && "Expect an ADDC");
8344   SDValue AddcOp0 = AddcNode->getOperand(0);
8345   SDValue AddcOp1 = AddcNode->getOperand(1);
8346
8347   // Check if the two operands are from the same mul_lohi node.
8348   if (AddcOp0.getNode() == AddcOp1.getNode())
8349     return SDValue();
8350
8351   assert(AddcNode->getNumValues() == 2 &&
8352          AddcNode->getValueType(0) == MVT::i32 &&
8353          "Expect ADDC with two result values. First: i32");
8354
8355   // Check that we have a glued ADDC node.
8356   if (AddcNode->getValueType(1) != MVT::Glue)
8357     return SDValue();
8358
8359   // Check that the ADDC adds the low result of the S/UMUL_LOHI.
8360   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
8361       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
8362       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
8363       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
8364     return SDValue();
8365
8366   // Look for the glued ADDE.
8367   SDNode* AddeNode = AddcNode->getGluedUser();
8368   if (!AddeNode)
8369     return SDValue();
8370
8371   // Make sure it is really an ADDE.
8372   if (AddeNode->getOpcode() != ISD::ADDE)
8373     return SDValue();
8374
8375   assert(AddeNode->getNumOperands() == 3 &&
8376          AddeNode->getOperand(2).getValueType() == MVT::Glue &&
8377          "ADDE node has the wrong inputs");
8378
8379   // Check for the triangle shape.
8380   SDValue AddeOp0 = AddeNode->getOperand(0);
8381   SDValue AddeOp1 = AddeNode->getOperand(1);
8382
8383   // Make sure that the ADDE operands are not coming from the same node.
8384   if (AddeOp0.getNode() == AddeOp1.getNode())
8385     return SDValue();
8386
8387   // Find the MUL_LOHI node walking up ADDE's operands.
8388   bool IsLeftOperandMUL = false;
8389   SDValue MULOp = findMUL_LOHI(AddeOp0);
8390   if (MULOp == SDValue())
8391    MULOp = findMUL_LOHI(AddeOp1);
8392   else
8393     IsLeftOperandMUL = true;
8394   if (MULOp == SDValue())
8395     return SDValue();
8396
8397   // Figure out the right opcode.
8398   unsigned Opc = MULOp->getOpcode();
8399   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
8400
8401   // Figure out the high and low input values to the MLAL node.
8402   SDValue* HiAdd = nullptr;
8403   SDValue* LoMul = nullptr;
8404   SDValue* LowAdd = nullptr;
8405
8406   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
8407   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
8408     return SDValue();
8409
8410   if (IsLeftOperandMUL)
8411     HiAdd = &AddeOp1;
8412   else
8413     HiAdd = &AddeOp0;
8414
8415
8416   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
8417   // whose low result is fed to the ADDC we are checking.
8418
8419   if (AddcOp0 == MULOp.getValue(0)) {
8420     LoMul = &AddcOp0;
8421     LowAdd = &AddcOp1;
8422   }
8423   if (AddcOp1 == MULOp.getValue(0)) {
8424     LoMul = &AddcOp1;
8425     LowAdd = &AddcOp0;
8426   }
8427
8428   if (!LoMul)
8429     return SDValue();
8430
8431   // Create the merged node.
8432   SelectionDAG &DAG = DCI.DAG;
8433
8434   // Build operand list.
8435   SmallVector<SDValue, 8> Ops;
8436   Ops.push_back(LoMul->getOperand(0));
8437   Ops.push_back(LoMul->getOperand(1));
8438   Ops.push_back(*LowAdd);
8439   Ops.push_back(*HiAdd);
8440
8441   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
8442                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
8443
8444   // Replace the ADDs' nodes uses by the MLA node's values.
8445   SDValue HiMLALResult(MLALNode.getNode(), 1);
8446   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
8447
8448   SDValue LoMLALResult(MLALNode.getNode(), 0);
8449   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
8450
8451   // Return original node to notify the driver to stop replacing.
8452   SDValue resNode(AddcNode, 0);
8453   return resNode;
8454 }
8455
8456 /// PerformADDCCombine - Target-specific dag combine transform from
8457 /// ISD::ADDC, ISD::ADDE, and ISD::MUL_LOHI to MLAL.
8458 static SDValue PerformADDCCombine(SDNode *N,
8459                                  TargetLowering::DAGCombinerInfo &DCI,
8460                                  const ARMSubtarget *Subtarget) {
8461
8462   return AddCombineTo64bitMLAL(N, DCI, Subtarget);
8463
8464 }
8465
8466 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
8467 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
8468 /// called with the default operands, and if that fails, with commuted
8469 /// operands.
8470 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
8471                                           TargetLowering::DAGCombinerInfo &DCI,
8472                                           const ARMSubtarget *Subtarget){
8473
8474   // Attempt to create vpaddl for this add.
8475   SDValue Result = AddCombineToVPADDL(N, N0, N1, DCI, Subtarget);
8476   if (Result.getNode())
8477     return Result;
8478
8479   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
8480   if (N0.getNode()->hasOneUse()) {
8481     SDValue Result = combineSelectAndUse(N, N0, N1, DCI);
8482     if (Result.getNode()) return Result;
8483   }
8484   return SDValue();
8485 }
8486
8487 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
8488 ///
8489 static SDValue PerformADDCombine(SDNode *N,
8490                                  TargetLowering::DAGCombinerInfo &DCI,
8491                                  const ARMSubtarget *Subtarget) {
8492   SDValue N0 = N->getOperand(0);
8493   SDValue N1 = N->getOperand(1);
8494
8495   // First try with the default operand order.
8496   SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget);
8497   if (Result.getNode())
8498     return Result;
8499
8500   // If that didn't work, try again with the operands commuted.
8501   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
8502 }
8503
8504 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
8505 ///
8506 static SDValue PerformSUBCombine(SDNode *N,
8507                                  TargetLowering::DAGCombinerInfo &DCI) {
8508   SDValue N0 = N->getOperand(0);
8509   SDValue N1 = N->getOperand(1);
8510
8511   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
8512   if (N1.getNode()->hasOneUse()) {
8513     SDValue Result = combineSelectAndUse(N, N1, N0, DCI);
8514     if (Result.getNode()) return Result;
8515   }
8516
8517   return SDValue();
8518 }
8519
8520 /// PerformVMULCombine
8521 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
8522 /// special multiplier accumulator forwarding.
8523 ///   vmul d3, d0, d2
8524 ///   vmla d3, d1, d2
8525 /// is faster than
8526 ///   vadd d3, d0, d1
8527 ///   vmul d3, d3, d2
8528 //  However, for (A + B) * (A + B),
8529 //    vadd d2, d0, d1
8530 //    vmul d3, d0, d2
8531 //    vmla d3, d1, d2
8532 //  is slower than
8533 //    vadd d2, d0, d1
8534 //    vmul d3, d2, d2
8535 static SDValue PerformVMULCombine(SDNode *N,
8536                                   TargetLowering::DAGCombinerInfo &DCI,
8537                                   const ARMSubtarget *Subtarget) {
8538   if (!Subtarget->hasVMLxForwarding())
8539     return SDValue();
8540
8541   SelectionDAG &DAG = DCI.DAG;
8542   SDValue N0 = N->getOperand(0);
8543   SDValue N1 = N->getOperand(1);
8544   unsigned Opcode = N0.getOpcode();
8545   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8546       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
8547     Opcode = N1.getOpcode();
8548     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
8549         Opcode != ISD::FADD && Opcode != ISD::FSUB)
8550       return SDValue();
8551     std::swap(N0, N1);
8552   }
8553
8554   if (N0 == N1)
8555     return SDValue();
8556
8557   EVT VT = N->getValueType(0);
8558   SDLoc DL(N);
8559   SDValue N00 = N0->getOperand(0);
8560   SDValue N01 = N0->getOperand(1);
8561   return DAG.getNode(Opcode, DL, VT,
8562                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
8563                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
8564 }
8565
8566 static SDValue PerformMULCombine(SDNode *N,
8567                                  TargetLowering::DAGCombinerInfo &DCI,
8568                                  const ARMSubtarget *Subtarget) {
8569   SelectionDAG &DAG = DCI.DAG;
8570
8571   if (Subtarget->isThumb1Only())
8572     return SDValue();
8573
8574   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8575     return SDValue();
8576
8577   EVT VT = N->getValueType(0);
8578   if (VT.is64BitVector() || VT.is128BitVector())
8579     return PerformVMULCombine(N, DCI, Subtarget);
8580   if (VT != MVT::i32)
8581     return SDValue();
8582
8583   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8584   if (!C)
8585     return SDValue();
8586
8587   int64_t MulAmt = C->getSExtValue();
8588   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
8589
8590   ShiftAmt = ShiftAmt & (32 - 1);
8591   SDValue V = N->getOperand(0);
8592   SDLoc DL(N);
8593
8594   SDValue Res;
8595   MulAmt >>= ShiftAmt;
8596
8597   if (MulAmt >= 0) {
8598     if (isPowerOf2_32(MulAmt - 1)) {
8599       // (mul x, 2^N + 1) => (add (shl x, N), x)
8600       Res = DAG.getNode(ISD::ADD, DL, VT,
8601                         V,
8602                         DAG.getNode(ISD::SHL, DL, VT,
8603                                     V,
8604                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
8605                                                     MVT::i32)));
8606     } else if (isPowerOf2_32(MulAmt + 1)) {
8607       // (mul x, 2^N - 1) => (sub (shl x, N), x)
8608       Res = DAG.getNode(ISD::SUB, DL, VT,
8609                         DAG.getNode(ISD::SHL, DL, VT,
8610                                     V,
8611                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
8612                                                     MVT::i32)),
8613                         V);
8614     } else
8615       return SDValue();
8616   } else {
8617     uint64_t MulAmtAbs = -MulAmt;
8618     if (isPowerOf2_32(MulAmtAbs + 1)) {
8619       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8620       Res = DAG.getNode(ISD::SUB, DL, VT,
8621                         V,
8622                         DAG.getNode(ISD::SHL, DL, VT,
8623                                     V,
8624                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
8625                                                     MVT::i32)));
8626     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
8627       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8628       Res = DAG.getNode(ISD::ADD, DL, VT,
8629                         V,
8630                         DAG.getNode(ISD::SHL, DL, VT,
8631                                     V,
8632                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
8633                                                     MVT::i32)));
8634       Res = DAG.getNode(ISD::SUB, DL, VT,
8635                         DAG.getConstant(0, DL, MVT::i32), Res);
8636
8637     } else
8638       return SDValue();
8639   }
8640
8641   if (ShiftAmt != 0)
8642     Res = DAG.getNode(ISD::SHL, DL, VT,
8643                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
8644
8645   // Do not add new nodes to DAG combiner worklist.
8646   DCI.CombineTo(N, Res, false);
8647   return SDValue();
8648 }
8649
8650 static SDValue PerformANDCombine(SDNode *N,
8651                                  TargetLowering::DAGCombinerInfo &DCI,
8652                                  const ARMSubtarget *Subtarget) {
8653
8654   // Attempt to use immediate-form VBIC
8655   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8656   SDLoc dl(N);
8657   EVT VT = N->getValueType(0);
8658   SelectionDAG &DAG = DCI.DAG;
8659
8660   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8661     return SDValue();
8662
8663   APInt SplatBits, SplatUndef;
8664   unsigned SplatBitSize;
8665   bool HasAnyUndefs;
8666   if (BVN &&
8667       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8668     if (SplatBitSize <= 64) {
8669       EVT VbicVT;
8670       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
8671                                       SplatUndef.getZExtValue(), SplatBitSize,
8672                                       DAG, dl, VbicVT, VT.is128BitVector(),
8673                                       OtherModImm);
8674       if (Val.getNode()) {
8675         SDValue Input =
8676           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
8677         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
8678         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
8679       }
8680     }
8681   }
8682
8683   if (!Subtarget->isThumb1Only()) {
8684     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
8685     SDValue Result = combineSelectAndUseCommutative(N, true, DCI);
8686     if (Result.getNode())
8687       return Result;
8688   }
8689
8690   return SDValue();
8691 }
8692
8693 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
8694 static SDValue PerformORCombine(SDNode *N,
8695                                 TargetLowering::DAGCombinerInfo &DCI,
8696                                 const ARMSubtarget *Subtarget) {
8697   // Attempt to use immediate-form VORR
8698   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
8699   SDLoc dl(N);
8700   EVT VT = N->getValueType(0);
8701   SelectionDAG &DAG = DCI.DAG;
8702
8703   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8704     return SDValue();
8705
8706   APInt SplatBits, SplatUndef;
8707   unsigned SplatBitSize;
8708   bool HasAnyUndefs;
8709   if (BVN && Subtarget->hasNEON() &&
8710       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
8711     if (SplatBitSize <= 64) {
8712       EVT VorrVT;
8713       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
8714                                       SplatUndef.getZExtValue(), SplatBitSize,
8715                                       DAG, dl, VorrVT, VT.is128BitVector(),
8716                                       OtherModImm);
8717       if (Val.getNode()) {
8718         SDValue Input =
8719           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
8720         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
8721         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
8722       }
8723     }
8724   }
8725
8726   if (!Subtarget->isThumb1Only()) {
8727     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
8728     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8729     if (Result.getNode())
8730       return Result;
8731   }
8732
8733   // The code below optimizes (or (and X, Y), Z).
8734   // The AND operand needs to have a single user to make these optimizations
8735   // profitable.
8736   SDValue N0 = N->getOperand(0);
8737   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
8738     return SDValue();
8739   SDValue N1 = N->getOperand(1);
8740
8741   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
8742   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
8743       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
8744     APInt SplatUndef;
8745     unsigned SplatBitSize;
8746     bool HasAnyUndefs;
8747
8748     APInt SplatBits0, SplatBits1;
8749     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
8750     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
8751     // Ensure that the second operand of both ands are constants
8752     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
8753                                       HasAnyUndefs) && !HasAnyUndefs) {
8754         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
8755                                           HasAnyUndefs) && !HasAnyUndefs) {
8756             // Ensure that the bit width of the constants are the same and that
8757             // the splat arguments are logical inverses as per the pattern we
8758             // are trying to simplify.
8759             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
8760                 SplatBits0 == ~SplatBits1) {
8761                 // Canonicalize the vector type to make instruction selection
8762                 // simpler.
8763                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
8764                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
8765                                              N0->getOperand(1),
8766                                              N0->getOperand(0),
8767                                              N1->getOperand(0));
8768                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
8769             }
8770         }
8771     }
8772   }
8773
8774   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
8775   // reasonable.
8776
8777   // BFI is only available on V6T2+
8778   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
8779     return SDValue();
8780
8781   SDLoc DL(N);
8782   // 1) or (and A, mask), val => ARMbfi A, val, mask
8783   //      iff (val & mask) == val
8784   //
8785   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8786   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
8787   //          && mask == ~mask2
8788   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
8789   //          && ~mask == mask2
8790   //  (i.e., copy a bitfield value into another bitfield of the same width)
8791
8792   if (VT != MVT::i32)
8793     return SDValue();
8794
8795   SDValue N00 = N0.getOperand(0);
8796
8797   // The value and the mask need to be constants so we can verify this is
8798   // actually a bitfield set. If the mask is 0xffff, we can do better
8799   // via a movt instruction, so don't use BFI in that case.
8800   SDValue MaskOp = N0.getOperand(1);
8801   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
8802   if (!MaskC)
8803     return SDValue();
8804   unsigned Mask = MaskC->getZExtValue();
8805   if (Mask == 0xffff)
8806     return SDValue();
8807   SDValue Res;
8808   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
8809   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
8810   if (N1C) {
8811     unsigned Val = N1C->getZExtValue();
8812     if ((Val & ~Mask) != Val)
8813       return SDValue();
8814
8815     if (ARM::isBitFieldInvertedMask(Mask)) {
8816       Val >>= countTrailingZeros(~Mask);
8817
8818       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
8819                         DAG.getConstant(Val, DL, MVT::i32),
8820                         DAG.getConstant(Mask, DL, MVT::i32));
8821
8822       // Do not add new nodes to DAG combiner worklist.
8823       DCI.CombineTo(N, Res, false);
8824       return SDValue();
8825     }
8826   } else if (N1.getOpcode() == ISD::AND) {
8827     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
8828     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8829     if (!N11C)
8830       return SDValue();
8831     unsigned Mask2 = N11C->getZExtValue();
8832
8833     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
8834     // as is to match.
8835     if (ARM::isBitFieldInvertedMask(Mask) &&
8836         (Mask == ~Mask2)) {
8837       // The pack halfword instruction works better for masks that fit it,
8838       // so use that when it's available.
8839       if (Subtarget->hasT2ExtractPack() &&
8840           (Mask == 0xffff || Mask == 0xffff0000))
8841         return SDValue();
8842       // 2a
8843       unsigned amt = countTrailingZeros(Mask2);
8844       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
8845                         DAG.getConstant(amt, DL, MVT::i32));
8846       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
8847                         DAG.getConstant(Mask, DL, MVT::i32));
8848       // Do not add new nodes to DAG combiner worklist.
8849       DCI.CombineTo(N, Res, false);
8850       return SDValue();
8851     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
8852                (~Mask == Mask2)) {
8853       // The pack halfword instruction works better for masks that fit it,
8854       // so use that when it's available.
8855       if (Subtarget->hasT2ExtractPack() &&
8856           (Mask2 == 0xffff || Mask2 == 0xffff0000))
8857         return SDValue();
8858       // 2b
8859       unsigned lsb = countTrailingZeros(Mask);
8860       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
8861                         DAG.getConstant(lsb, DL, MVT::i32));
8862       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
8863                         DAG.getConstant(Mask2, DL, MVT::i32));
8864       // Do not add new nodes to DAG combiner worklist.
8865       DCI.CombineTo(N, Res, false);
8866       return SDValue();
8867     }
8868   }
8869
8870   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
8871       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
8872       ARM::isBitFieldInvertedMask(~Mask)) {
8873     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
8874     // where lsb(mask) == #shamt and masked bits of B are known zero.
8875     SDValue ShAmt = N00.getOperand(1);
8876     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
8877     unsigned LSB = countTrailingZeros(Mask);
8878     if (ShAmtC != LSB)
8879       return SDValue();
8880
8881     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
8882                       DAG.getConstant(~Mask, DL, MVT::i32));
8883
8884     // Do not add new nodes to DAG combiner worklist.
8885     DCI.CombineTo(N, Res, false);
8886   }
8887
8888   return SDValue();
8889 }
8890
8891 static SDValue PerformXORCombine(SDNode *N,
8892                                  TargetLowering::DAGCombinerInfo &DCI,
8893                                  const ARMSubtarget *Subtarget) {
8894   EVT VT = N->getValueType(0);
8895   SelectionDAG &DAG = DCI.DAG;
8896
8897   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8898     return SDValue();
8899
8900   if (!Subtarget->isThumb1Only()) {
8901     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
8902     SDValue Result = combineSelectAndUseCommutative(N, false, DCI);
8903     if (Result.getNode())
8904       return Result;
8905   }
8906
8907   return SDValue();
8908 }
8909
8910 /// PerformBFICombine - (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
8911 /// the bits being cleared by the AND are not demanded by the BFI.
8912 static SDValue PerformBFICombine(SDNode *N,
8913                                  TargetLowering::DAGCombinerInfo &DCI) {
8914   SDValue N1 = N->getOperand(1);
8915   if (N1.getOpcode() == ISD::AND) {
8916     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
8917     if (!N11C)
8918       return SDValue();
8919     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
8920     unsigned LSB = countTrailingZeros(~InvMask);
8921     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
8922     assert(Width <
8923                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
8924            "undefined behavior");
8925     unsigned Mask = (1u << Width) - 1;
8926     unsigned Mask2 = N11C->getZExtValue();
8927     if ((Mask & (~Mask2)) == 0)
8928       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
8929                              N->getOperand(0), N1.getOperand(0),
8930                              N->getOperand(2));
8931   }
8932   return SDValue();
8933 }
8934
8935 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
8936 /// ARMISD::VMOVRRD.
8937 static SDValue PerformVMOVRRDCombine(SDNode *N,
8938                                      TargetLowering::DAGCombinerInfo &DCI,
8939                                      const ARMSubtarget *Subtarget) {
8940   // vmovrrd(vmovdrr x, y) -> x,y
8941   SDValue InDouble = N->getOperand(0);
8942   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
8943     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
8944
8945   // vmovrrd(load f64) -> (load i32), (load i32)
8946   SDNode *InNode = InDouble.getNode();
8947   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
8948       InNode->getValueType(0) == MVT::f64 &&
8949       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
8950       !cast<LoadSDNode>(InNode)->isVolatile()) {
8951     // TODO: Should this be done for non-FrameIndex operands?
8952     LoadSDNode *LD = cast<LoadSDNode>(InNode);
8953
8954     SelectionDAG &DAG = DCI.DAG;
8955     SDLoc DL(LD);
8956     SDValue BasePtr = LD->getBasePtr();
8957     SDValue NewLD1 = DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr,
8958                                  LD->getPointerInfo(), LD->isVolatile(),
8959                                  LD->isNonTemporal(), LD->isInvariant(),
8960                                  LD->getAlignment());
8961
8962     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
8963                                     DAG.getConstant(4, DL, MVT::i32));
8964     SDValue NewLD2 = DAG.getLoad(MVT::i32, DL, NewLD1.getValue(1), OffsetPtr,
8965                                  LD->getPointerInfo(), LD->isVolatile(),
8966                                  LD->isNonTemporal(), LD->isInvariant(),
8967                                  std::min(4U, LD->getAlignment() / 2));
8968
8969     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
8970     if (DCI.DAG.getDataLayout().isBigEndian())
8971       std::swap (NewLD1, NewLD2);
8972     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
8973     return Result;
8974   }
8975
8976   return SDValue();
8977 }
8978
8979 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
8980 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
8981 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
8982   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
8983   SDValue Op0 = N->getOperand(0);
8984   SDValue Op1 = N->getOperand(1);
8985   if (Op0.getOpcode() == ISD::BITCAST)
8986     Op0 = Op0.getOperand(0);
8987   if (Op1.getOpcode() == ISD::BITCAST)
8988     Op1 = Op1.getOperand(0);
8989   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
8990       Op0.getNode() == Op1.getNode() &&
8991       Op0.getResNo() == 0 && Op1.getResNo() == 1)
8992     return DAG.getNode(ISD::BITCAST, SDLoc(N),
8993                        N->getValueType(0), Op0.getOperand(0));
8994   return SDValue();
8995 }
8996
8997 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
8998 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
8999 /// i64 vector to have f64 elements, since the value can then be loaded
9000 /// directly into a VFP register.
9001 static bool hasNormalLoadOperand(SDNode *N) {
9002   unsigned NumElts = N->getValueType(0).getVectorNumElements();
9003   for (unsigned i = 0; i < NumElts; ++i) {
9004     SDNode *Elt = N->getOperand(i).getNode();
9005     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
9006       return true;
9007   }
9008   return false;
9009 }
9010
9011 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
9012 /// ISD::BUILD_VECTOR.
9013 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
9014                                           TargetLowering::DAGCombinerInfo &DCI,
9015                                           const ARMSubtarget *Subtarget) {
9016   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
9017   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
9018   // into a pair of GPRs, which is fine when the value is used as a scalar,
9019   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
9020   SelectionDAG &DAG = DCI.DAG;
9021   if (N->getNumOperands() == 2) {
9022     SDValue RV = PerformVMOVDRRCombine(N, DAG);
9023     if (RV.getNode())
9024       return RV;
9025   }
9026
9027   // Load i64 elements as f64 values so that type legalization does not split
9028   // them up into i32 values.
9029   EVT VT = N->getValueType(0);
9030   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
9031     return SDValue();
9032   SDLoc dl(N);
9033   SmallVector<SDValue, 8> Ops;
9034   unsigned NumElts = VT.getVectorNumElements();
9035   for (unsigned i = 0; i < NumElts; ++i) {
9036     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
9037     Ops.push_back(V);
9038     // Make the DAGCombiner fold the bitcast.
9039     DCI.AddToWorklist(V.getNode());
9040   }
9041   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
9042   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, FloatVT, Ops);
9043   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9044 }
9045
9046 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
9047 static SDValue
9048 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9049   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
9050   // At that time, we may have inserted bitcasts from integer to float.
9051   // If these bitcasts have survived DAGCombine, change the lowering of this
9052   // BUILD_VECTOR in something more vector friendly, i.e., that does not
9053   // force to use floating point types.
9054
9055   // Make sure we can change the type of the vector.
9056   // This is possible iff:
9057   // 1. The vector is only used in a bitcast to a integer type. I.e.,
9058   //    1.1. Vector is used only once.
9059   //    1.2. Use is a bit convert to an integer type.
9060   // 2. The size of its operands are 32-bits (64-bits are not legal).
9061   EVT VT = N->getValueType(0);
9062   EVT EltVT = VT.getVectorElementType();
9063
9064   // Check 1.1. and 2.
9065   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
9066     return SDValue();
9067
9068   // By construction, the input type must be float.
9069   assert(EltVT == MVT::f32 && "Unexpected type!");
9070
9071   // Check 1.2.
9072   SDNode *Use = *N->use_begin();
9073   if (Use->getOpcode() != ISD::BITCAST ||
9074       Use->getValueType(0).isFloatingPoint())
9075     return SDValue();
9076
9077   // Check profitability.
9078   // Model is, if more than half of the relevant operands are bitcast from
9079   // i32, turn the build_vector into a sequence of insert_vector_elt.
9080   // Relevant operands are everything that is not statically
9081   // (i.e., at compile time) bitcasted.
9082   unsigned NumOfBitCastedElts = 0;
9083   unsigned NumElts = VT.getVectorNumElements();
9084   unsigned NumOfRelevantElts = NumElts;
9085   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
9086     SDValue Elt = N->getOperand(Idx);
9087     if (Elt->getOpcode() == ISD::BITCAST) {
9088       // Assume only bit cast to i32 will go away.
9089       if (Elt->getOperand(0).getValueType() == MVT::i32)
9090         ++NumOfBitCastedElts;
9091     } else if (Elt.getOpcode() == ISD::UNDEF || isa<ConstantSDNode>(Elt))
9092       // Constants are statically casted, thus do not count them as
9093       // relevant operands.
9094       --NumOfRelevantElts;
9095   }
9096
9097   // Check if more than half of the elements require a non-free bitcast.
9098   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
9099     return SDValue();
9100
9101   SelectionDAG &DAG = DCI.DAG;
9102   // Create the new vector type.
9103   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
9104   // Check if the type is legal.
9105   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9106   if (!TLI.isTypeLegal(VecVT))
9107     return SDValue();
9108
9109   // Combine:
9110   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
9111   // => BITCAST INSERT_VECTOR_ELT
9112   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
9113   //                      (BITCAST EN), N.
9114   SDValue Vec = DAG.getUNDEF(VecVT);
9115   SDLoc dl(N);
9116   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
9117     SDValue V = N->getOperand(Idx);
9118     if (V.getOpcode() == ISD::UNDEF)
9119       continue;
9120     if (V.getOpcode() == ISD::BITCAST &&
9121         V->getOperand(0).getValueType() == MVT::i32)
9122       // Fold obvious case.
9123       V = V.getOperand(0);
9124     else {
9125       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
9126       // Make the DAGCombiner fold the bitcasts.
9127       DCI.AddToWorklist(V.getNode());
9128     }
9129     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
9130     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
9131   }
9132   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
9133   // Make the DAGCombiner fold the bitcasts.
9134   DCI.AddToWorklist(Vec.getNode());
9135   return Vec;
9136 }
9137
9138 /// PerformInsertEltCombine - Target-specific dag combine xforms for
9139 /// ISD::INSERT_VECTOR_ELT.
9140 static SDValue PerformInsertEltCombine(SDNode *N,
9141                                        TargetLowering::DAGCombinerInfo &DCI) {
9142   // Bitcast an i64 load inserted into a vector to f64.
9143   // Otherwise, the i64 value will be legalized to a pair of i32 values.
9144   EVT VT = N->getValueType(0);
9145   SDNode *Elt = N->getOperand(1).getNode();
9146   if (VT.getVectorElementType() != MVT::i64 ||
9147       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
9148     return SDValue();
9149
9150   SelectionDAG &DAG = DCI.DAG;
9151   SDLoc dl(N);
9152   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9153                                  VT.getVectorNumElements());
9154   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
9155   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
9156   // Make the DAGCombiner fold the bitcasts.
9157   DCI.AddToWorklist(Vec.getNode());
9158   DCI.AddToWorklist(V.getNode());
9159   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
9160                                Vec, V, N->getOperand(2));
9161   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
9162 }
9163
9164 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
9165 /// ISD::VECTOR_SHUFFLE.
9166 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
9167   // The LLVM shufflevector instruction does not require the shuffle mask
9168   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
9169   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
9170   // operands do not match the mask length, they are extended by concatenating
9171   // them with undef vectors.  That is probably the right thing for other
9172   // targets, but for NEON it is better to concatenate two double-register
9173   // size vector operands into a single quad-register size vector.  Do that
9174   // transformation here:
9175   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
9176   //   shuffle(concat(v1, v2), undef)
9177   SDValue Op0 = N->getOperand(0);
9178   SDValue Op1 = N->getOperand(1);
9179   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
9180       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
9181       Op0.getNumOperands() != 2 ||
9182       Op1.getNumOperands() != 2)
9183     return SDValue();
9184   SDValue Concat0Op1 = Op0.getOperand(1);
9185   SDValue Concat1Op1 = Op1.getOperand(1);
9186   if (Concat0Op1.getOpcode() != ISD::UNDEF ||
9187       Concat1Op1.getOpcode() != ISD::UNDEF)
9188     return SDValue();
9189   // Skip the transformation if any of the types are illegal.
9190   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9191   EVT VT = N->getValueType(0);
9192   if (!TLI.isTypeLegal(VT) ||
9193       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
9194       !TLI.isTypeLegal(Concat1Op1.getValueType()))
9195     return SDValue();
9196
9197   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
9198                                   Op0.getOperand(0), Op1.getOperand(0));
9199   // Translate the shuffle mask.
9200   SmallVector<int, 16> NewMask;
9201   unsigned NumElts = VT.getVectorNumElements();
9202   unsigned HalfElts = NumElts/2;
9203   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9204   for (unsigned n = 0; n < NumElts; ++n) {
9205     int MaskElt = SVN->getMaskElt(n);
9206     int NewElt = -1;
9207     if (MaskElt < (int)HalfElts)
9208       NewElt = MaskElt;
9209     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
9210       NewElt = HalfElts + MaskElt - NumElts;
9211     NewMask.push_back(NewElt);
9212   }
9213   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
9214                               DAG.getUNDEF(VT), NewMask.data());
9215 }
9216
9217 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
9218 /// NEON load/store intrinsics, and generic vector load/stores, to merge
9219 /// base address updates.
9220 /// For generic load/stores, the memory type is assumed to be a vector.
9221 /// The caller is assumed to have checked legality.
9222 static SDValue CombineBaseUpdate(SDNode *N,
9223                                  TargetLowering::DAGCombinerInfo &DCI) {
9224   SelectionDAG &DAG = DCI.DAG;
9225   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
9226                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
9227   const bool isStore = N->getOpcode() == ISD::STORE;
9228   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
9229   SDValue Addr = N->getOperand(AddrOpIdx);
9230   MemSDNode *MemN = cast<MemSDNode>(N);
9231   SDLoc dl(N);
9232
9233   // Search for a use of the address operand that is an increment.
9234   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9235          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9236     SDNode *User = *UI;
9237     if (User->getOpcode() != ISD::ADD ||
9238         UI.getUse().getResNo() != Addr.getResNo())
9239       continue;
9240
9241     // Check that the add is independent of the load/store.  Otherwise, folding
9242     // it would create a cycle.
9243     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9244       continue;
9245
9246     // Find the new opcode for the updating load/store.
9247     bool isLoadOp = true;
9248     bool isLaneOp = false;
9249     unsigned NewOpc = 0;
9250     unsigned NumVecs = 0;
9251     if (isIntrinsic) {
9252       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9253       switch (IntNo) {
9254       default: llvm_unreachable("unexpected intrinsic for Neon base update");
9255       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
9256         NumVecs = 1; break;
9257       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
9258         NumVecs = 2; break;
9259       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
9260         NumVecs = 3; break;
9261       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
9262         NumVecs = 4; break;
9263       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
9264         NumVecs = 2; isLaneOp = true; break;
9265       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
9266         NumVecs = 3; isLaneOp = true; break;
9267       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
9268         NumVecs = 4; isLaneOp = true; break;
9269       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
9270         NumVecs = 1; isLoadOp = false; break;
9271       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
9272         NumVecs = 2; isLoadOp = false; break;
9273       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
9274         NumVecs = 3; isLoadOp = false; break;
9275       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
9276         NumVecs = 4; isLoadOp = false; break;
9277       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
9278         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
9279       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
9280         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
9281       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
9282         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
9283       }
9284     } else {
9285       isLaneOp = true;
9286       switch (N->getOpcode()) {
9287       default: llvm_unreachable("unexpected opcode for Neon base update");
9288       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
9289       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
9290       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
9291       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
9292         NumVecs = 1; isLaneOp = false; break;
9293       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
9294         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
9295       }
9296     }
9297
9298     // Find the size of memory referenced by the load/store.
9299     EVT VecTy;
9300     if (isLoadOp) {
9301       VecTy = N->getValueType(0);
9302     } else if (isIntrinsic) {
9303       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
9304     } else {
9305       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
9306       VecTy = N->getOperand(1).getValueType();
9307     }
9308
9309     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9310     if (isLaneOp)
9311       NumBytes /= VecTy.getVectorNumElements();
9312
9313     // If the increment is a constant, it must match the memory ref size.
9314     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9315     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9316       uint64_t IncVal = CInc->getZExtValue();
9317       if (IncVal != NumBytes)
9318         continue;
9319     } else if (NumBytes >= 3 * 16) {
9320       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
9321       // separate instructions that make it harder to use a non-constant update.
9322       continue;
9323     }
9324
9325     // OK, we found an ADD we can fold into the base update.
9326     // Now, create a _UPD node, taking care of not breaking alignment.
9327
9328     EVT AlignedVecTy = VecTy;
9329     unsigned Alignment = MemN->getAlignment();
9330
9331     // If this is a less-than-standard-aligned load/store, change the type to
9332     // match the standard alignment.
9333     // The alignment is overlooked when selecting _UPD variants; and it's
9334     // easier to introduce bitcasts here than fix that.
9335     // There are 3 ways to get to this base-update combine:
9336     // - intrinsics: they are assumed to be properly aligned (to the standard
9337     //   alignment of the memory type), so we don't need to do anything.
9338     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
9339     //   intrinsics, so, likewise, there's nothing to do.
9340     // - generic load/store instructions: the alignment is specified as an
9341     //   explicit operand, rather than implicitly as the standard alignment
9342     //   of the memory type (like the intrisics).  We need to change the
9343     //   memory type to match the explicit alignment.  That way, we don't
9344     //   generate non-standard-aligned ARMISD::VLDx nodes.
9345     if (isa<LSBaseSDNode>(N)) {
9346       if (Alignment == 0)
9347         Alignment = 1;
9348       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
9349         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
9350         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
9351         assert(!isLaneOp && "Unexpected generic load/store lane.");
9352         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
9353         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
9354       }
9355       // Don't set an explicit alignment on regular load/stores that we want
9356       // to transform to VLD/VST 1_UPD nodes.
9357       // This matches the behavior of regular load/stores, which only get an
9358       // explicit alignment if the MMO alignment is larger than the standard
9359       // alignment of the memory type.
9360       // Intrinsics, however, always get an explicit alignment, set to the
9361       // alignment of the MMO.
9362       Alignment = 1;
9363     }
9364
9365     // Create the new updating load/store node.
9366     // First, create an SDVTList for the new updating node's results.
9367     EVT Tys[6];
9368     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
9369     unsigned n;
9370     for (n = 0; n < NumResultVecs; ++n)
9371       Tys[n] = AlignedVecTy;
9372     Tys[n++] = MVT::i32;
9373     Tys[n] = MVT::Other;
9374     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
9375
9376     // Then, gather the new node's operands.
9377     SmallVector<SDValue, 8> Ops;
9378     Ops.push_back(N->getOperand(0)); // incoming chain
9379     Ops.push_back(N->getOperand(AddrOpIdx));
9380     Ops.push_back(Inc);
9381
9382     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
9383       // Try to match the intrinsic's signature
9384       Ops.push_back(StN->getValue());
9385     } else {
9386       // Loads (and of course intrinsics) match the intrinsics' signature,
9387       // so just add all but the alignment operand.
9388       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
9389         Ops.push_back(N->getOperand(i));
9390     }
9391
9392     // For all node types, the alignment operand is always the last one.
9393     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
9394
9395     // If this is a non-standard-aligned STORE, the penultimate operand is the
9396     // stored value.  Bitcast it to the aligned type.
9397     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
9398       SDValue &StVal = Ops[Ops.size()-2];
9399       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
9400     }
9401
9402     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys,
9403                                            Ops, AlignedVecTy,
9404                                            MemN->getMemOperand());
9405
9406     // Update the uses.
9407     SmallVector<SDValue, 5> NewResults;
9408     for (unsigned i = 0; i < NumResultVecs; ++i)
9409       NewResults.push_back(SDValue(UpdN.getNode(), i));
9410
9411     // If this is an non-standard-aligned LOAD, the first result is the loaded
9412     // value.  Bitcast it to the expected result type.
9413     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
9414       SDValue &LdVal = NewResults[0];
9415       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
9416     }
9417
9418     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
9419     DCI.CombineTo(N, NewResults);
9420     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9421
9422     break;
9423   }
9424   return SDValue();
9425 }
9426
9427 static SDValue PerformVLDCombine(SDNode *N,
9428                                  TargetLowering::DAGCombinerInfo &DCI) {
9429   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9430     return SDValue();
9431
9432   return CombineBaseUpdate(N, DCI);
9433 }
9434
9435 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
9436 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
9437 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
9438 /// return true.
9439 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
9440   SelectionDAG &DAG = DCI.DAG;
9441   EVT VT = N->getValueType(0);
9442   // vldN-dup instructions only support 64-bit vectors for N > 1.
9443   if (!VT.is64BitVector())
9444     return false;
9445
9446   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
9447   SDNode *VLD = N->getOperand(0).getNode();
9448   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
9449     return false;
9450   unsigned NumVecs = 0;
9451   unsigned NewOpc = 0;
9452   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
9453   if (IntNo == Intrinsic::arm_neon_vld2lane) {
9454     NumVecs = 2;
9455     NewOpc = ARMISD::VLD2DUP;
9456   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
9457     NumVecs = 3;
9458     NewOpc = ARMISD::VLD3DUP;
9459   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
9460     NumVecs = 4;
9461     NewOpc = ARMISD::VLD4DUP;
9462   } else {
9463     return false;
9464   }
9465
9466   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
9467   // numbers match the load.
9468   unsigned VLDLaneNo =
9469     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
9470   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9471        UI != UE; ++UI) {
9472     // Ignore uses of the chain result.
9473     if (UI.getUse().getResNo() == NumVecs)
9474       continue;
9475     SDNode *User = *UI;
9476     if (User->getOpcode() != ARMISD::VDUPLANE ||
9477         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
9478       return false;
9479   }
9480
9481   // Create the vldN-dup node.
9482   EVT Tys[5];
9483   unsigned n;
9484   for (n = 0; n < NumVecs; ++n)
9485     Tys[n] = VT;
9486   Tys[n] = MVT::Other;
9487   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
9488   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
9489   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
9490   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
9491                                            Ops, VLDMemInt->getMemoryVT(),
9492                                            VLDMemInt->getMemOperand());
9493
9494   // Update the uses.
9495   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
9496        UI != UE; ++UI) {
9497     unsigned ResNo = UI.getUse().getResNo();
9498     // Ignore uses of the chain result.
9499     if (ResNo == NumVecs)
9500       continue;
9501     SDNode *User = *UI;
9502     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
9503   }
9504
9505   // Now the vldN-lane intrinsic is dead except for its chain result.
9506   // Update uses of the chain.
9507   std::vector<SDValue> VLDDupResults;
9508   for (unsigned n = 0; n < NumVecs; ++n)
9509     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
9510   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
9511   DCI.CombineTo(VLD, VLDDupResults);
9512
9513   return true;
9514 }
9515
9516 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
9517 /// ARMISD::VDUPLANE.
9518 static SDValue PerformVDUPLANECombine(SDNode *N,
9519                                       TargetLowering::DAGCombinerInfo &DCI) {
9520   SDValue Op = N->getOperand(0);
9521
9522   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
9523   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
9524   if (CombineVLDDUP(N, DCI))
9525     return SDValue(N, 0);
9526
9527   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
9528   // redundant.  Ignore bit_converts for now; element sizes are checked below.
9529   while (Op.getOpcode() == ISD::BITCAST)
9530     Op = Op.getOperand(0);
9531   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
9532     return SDValue();
9533
9534   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
9535   unsigned EltSize = Op.getValueType().getVectorElementType().getSizeInBits();
9536   // The canonical VMOV for a zero vector uses a 32-bit element size.
9537   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9538   unsigned EltBits;
9539   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
9540     EltSize = 8;
9541   EVT VT = N->getValueType(0);
9542   if (EltSize > VT.getVectorElementType().getSizeInBits())
9543     return SDValue();
9544
9545   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
9546 }
9547
9548 static SDValue PerformLOADCombine(SDNode *N,
9549                                   TargetLowering::DAGCombinerInfo &DCI) {
9550   EVT VT = N->getValueType(0);
9551
9552   // If this is a legal vector load, try to combine it into a VLD1_UPD.
9553   if (ISD::isNormalLoad(N) && VT.isVector() &&
9554       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9555     return CombineBaseUpdate(N, DCI);
9556
9557   return SDValue();
9558 }
9559
9560 /// PerformSTORECombine - Target-specific dag combine xforms for
9561 /// ISD::STORE.
9562 static SDValue PerformSTORECombine(SDNode *N,
9563                                    TargetLowering::DAGCombinerInfo &DCI) {
9564   StoreSDNode *St = cast<StoreSDNode>(N);
9565   if (St->isVolatile())
9566     return SDValue();
9567
9568   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
9569   // pack all of the elements in one place.  Next, store to memory in fewer
9570   // chunks.
9571   SDValue StVal = St->getValue();
9572   EVT VT = StVal.getValueType();
9573   if (St->isTruncatingStore() && VT.isVector()) {
9574     SelectionDAG &DAG = DCI.DAG;
9575     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9576     EVT StVT = St->getMemoryVT();
9577     unsigned NumElems = VT.getVectorNumElements();
9578     assert(StVT != VT && "Cannot truncate to the same type");
9579     unsigned FromEltSz = VT.getVectorElementType().getSizeInBits();
9580     unsigned ToEltSz = StVT.getVectorElementType().getSizeInBits();
9581
9582     // From, To sizes and ElemCount must be pow of two
9583     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
9584
9585     // We are going to use the original vector elt for storing.
9586     // Accumulated smaller vector elements must be a multiple of the store size.
9587     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
9588
9589     unsigned SizeRatio  = FromEltSz / ToEltSz;
9590     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
9591
9592     // Create a type on which we perform the shuffle.
9593     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
9594                                      NumElems*SizeRatio);
9595     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
9596
9597     SDLoc DL(St);
9598     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
9599     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
9600     for (unsigned i = 0; i < NumElems; ++i)
9601       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
9602                           ? (i + 1) * SizeRatio - 1
9603                           : i * SizeRatio;
9604
9605     // Can't shuffle using an illegal type.
9606     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
9607
9608     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
9609                                 DAG.getUNDEF(WideVec.getValueType()),
9610                                 ShuffleVec.data());
9611     // At this point all of the data is stored at the bottom of the
9612     // register. We now need to save it to mem.
9613
9614     // Find the largest store unit
9615     MVT StoreType = MVT::i8;
9616     for (MVT Tp : MVT::integer_valuetypes()) {
9617       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
9618         StoreType = Tp;
9619     }
9620     // Didn't find a legal store type.
9621     if (!TLI.isTypeLegal(StoreType))
9622       return SDValue();
9623
9624     // Bitcast the original vector into a vector of store-size units
9625     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
9626             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
9627     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
9628     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
9629     SmallVector<SDValue, 8> Chains;
9630     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
9631                                         TLI.getPointerTy(DAG.getDataLayout()));
9632     SDValue BasePtr = St->getBasePtr();
9633
9634     // Perform one or more big stores into memory.
9635     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
9636     for (unsigned I = 0; I < E; I++) {
9637       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
9638                                    StoreType, ShuffWide,
9639                                    DAG.getIntPtrConstant(I, DL));
9640       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
9641                                 St->getPointerInfo(), St->isVolatile(),
9642                                 St->isNonTemporal(), St->getAlignment());
9643       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
9644                             Increment);
9645       Chains.push_back(Ch);
9646     }
9647     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
9648   }
9649
9650   if (!ISD::isNormalStore(St))
9651     return SDValue();
9652
9653   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
9654   // ARM stores of arguments in the same cache line.
9655   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
9656       StVal.getNode()->hasOneUse()) {
9657     SelectionDAG  &DAG = DCI.DAG;
9658     bool isBigEndian = DAG.getDataLayout().isBigEndian();
9659     SDLoc DL(St);
9660     SDValue BasePtr = St->getBasePtr();
9661     SDValue NewST1 = DAG.getStore(St->getChain(), DL,
9662                                   StVal.getNode()->getOperand(isBigEndian ? 1 : 0 ),
9663                                   BasePtr, St->getPointerInfo(), St->isVolatile(),
9664                                   St->isNonTemporal(), St->getAlignment());
9665
9666     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
9667                                     DAG.getConstant(4, DL, MVT::i32));
9668     return DAG.getStore(NewST1.getValue(0), DL,
9669                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
9670                         OffsetPtr, St->getPointerInfo(), St->isVolatile(),
9671                         St->isNonTemporal(),
9672                         std::min(4U, St->getAlignment() / 2));
9673   }
9674
9675   if (StVal.getValueType() == MVT::i64 &&
9676       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9677
9678     // Bitcast an i64 store extracted from a vector to f64.
9679     // Otherwise, the i64 value will be legalized to a pair of i32 values.
9680     SelectionDAG &DAG = DCI.DAG;
9681     SDLoc dl(StVal);
9682     SDValue IntVec = StVal.getOperand(0);
9683     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
9684                                    IntVec.getValueType().getVectorNumElements());
9685     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
9686     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9687                                  Vec, StVal.getOperand(1));
9688     dl = SDLoc(N);
9689     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
9690     // Make the DAGCombiner fold the bitcasts.
9691     DCI.AddToWorklist(Vec.getNode());
9692     DCI.AddToWorklist(ExtElt.getNode());
9693     DCI.AddToWorklist(V.getNode());
9694     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
9695                         St->getPointerInfo(), St->isVolatile(),
9696                         St->isNonTemporal(), St->getAlignment(),
9697                         St->getAAInfo());
9698   }
9699
9700   // If this is a legal vector store, try to combine it into a VST1_UPD.
9701   if (ISD::isNormalStore(N) && VT.isVector() &&
9702       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
9703     return CombineBaseUpdate(N, DCI);
9704
9705   return SDValue();
9706 }
9707
9708 // isConstVecPow2 - Return true if each vector element is a power of 2, all
9709 // elements are the same constant, C, and Log2(C) ranges from 1 to 32.
9710 static bool isConstVecPow2(SDValue ConstVec, bool isSigned, uint64_t &C)
9711 {
9712   integerPart cN;
9713   integerPart c0 = 0;
9714   for (unsigned I = 0, E = ConstVec.getValueType().getVectorNumElements();
9715        I != E; I++) {
9716     ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(ConstVec.getOperand(I));
9717     if (!C)
9718       return false;
9719
9720     bool isExact;
9721     APFloat APF = C->getValueAPF();
9722     if (APF.convertToInteger(&cN, 64, isSigned, APFloat::rmTowardZero, &isExact)
9723         != APFloat::opOK || !isExact)
9724       return false;
9725
9726     c0 = (I == 0) ? cN : c0;
9727     if (!isPowerOf2_64(cN) || c0 != cN || Log2_64(c0) < 1 || Log2_64(c0) > 32)
9728       return false;
9729   }
9730   C = c0;
9731   return true;
9732 }
9733
9734 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
9735 /// can replace combinations of VMUL and VCVT (floating-point to integer)
9736 /// when the VMUL has a constant operand that is a power of 2.
9737 ///
9738 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9739 ///  vmul.f32        d16, d17, d16
9740 ///  vcvt.s32.f32    d16, d16
9741 /// becomes:
9742 ///  vcvt.s32.f32    d16, d16, #3
9743 static SDValue PerformVCVTCombine(SDNode *N,
9744                                   TargetLowering::DAGCombinerInfo &DCI,
9745                                   const ARMSubtarget *Subtarget) {
9746   SelectionDAG &DAG = DCI.DAG;
9747   SDValue Op = N->getOperand(0);
9748
9749   if (!Subtarget->hasNEON() || !Op.getValueType().isVector() ||
9750       Op.getOpcode() != ISD::FMUL)
9751     return SDValue();
9752
9753   uint64_t C;
9754   SDValue N0 = Op->getOperand(0);
9755   SDValue ConstVec = Op->getOperand(1);
9756   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
9757
9758   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9759       !isConstVecPow2(ConstVec, isSigned, C))
9760     return SDValue();
9761
9762   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
9763   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
9764   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9765   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32 ||
9766       NumLanes > 4) {
9767     // These instructions only exist converting from f32 to i32. We can handle
9768     // smaller integers by generating an extra truncate, but larger ones would
9769     // be lossy. We also can't handle more then 4 lanes, since these intructions
9770     // only support v2i32/v4i32 types.
9771     return SDValue();
9772   }
9773
9774   SDLoc dl(N);
9775   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
9776     Intrinsic::arm_neon_vcvtfp2fxu;
9777   SDValue FixConv =  DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9778                                  NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9779                                  DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9780                                  N0,
9781                                  DAG.getConstant(Log2_64(C), dl, MVT::i32));
9782
9783   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9784     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
9785
9786   return FixConv;
9787 }
9788
9789 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
9790 /// can replace combinations of VCVT (integer to floating-point) and VDIV
9791 /// when the VDIV has a constant operand that is a power of 2.
9792 ///
9793 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
9794 ///  vcvt.f32.s32    d16, d16
9795 ///  vdiv.f32        d16, d17, d16
9796 /// becomes:
9797 ///  vcvt.f32.s32    d16, d16, #3
9798 static SDValue PerformVDIVCombine(SDNode *N,
9799                                   TargetLowering::DAGCombinerInfo &DCI,
9800                                   const ARMSubtarget *Subtarget) {
9801   SelectionDAG &DAG = DCI.DAG;
9802   SDValue Op = N->getOperand(0);
9803   unsigned OpOpcode = Op.getNode()->getOpcode();
9804
9805   if (!Subtarget->hasNEON() || !N->getValueType(0).isVector() ||
9806       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
9807     return SDValue();
9808
9809   uint64_t C;
9810   SDValue ConstVec = N->getOperand(1);
9811   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
9812
9813   if (ConstVec.getOpcode() != ISD::BUILD_VECTOR ||
9814       !isConstVecPow2(ConstVec, isSigned, C))
9815     return SDValue();
9816
9817   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
9818   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
9819   if (FloatTy.getSizeInBits() != 32 || IntTy.getSizeInBits() > 32) {
9820     // These instructions only exist converting from i32 to f32. We can handle
9821     // smaller integers by generating an extra extend, but larger ones would
9822     // be lossy.
9823     return SDValue();
9824   }
9825
9826   SDLoc dl(N);
9827   SDValue ConvInput = Op.getOperand(0);
9828   unsigned NumLanes = Op.getValueType().getVectorNumElements();
9829   if (IntTy.getSizeInBits() < FloatTy.getSizeInBits())
9830     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
9831                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
9832                             ConvInput);
9833
9834   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
9835     Intrinsic::arm_neon_vcvtfxu2fp;
9836   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
9837                      Op.getValueType(),
9838                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
9839                      ConvInput, DAG.getConstant(Log2_64(C), dl, MVT::i32));
9840 }
9841
9842 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
9843 /// operand of a vector shift operation, where all the elements of the
9844 /// build_vector must have the same constant integer value.
9845 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
9846   // Ignore bit_converts.
9847   while (Op.getOpcode() == ISD::BITCAST)
9848     Op = Op.getOperand(0);
9849   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
9850   APInt SplatBits, SplatUndef;
9851   unsigned SplatBitSize;
9852   bool HasAnyUndefs;
9853   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
9854                                       HasAnyUndefs, ElementBits) ||
9855       SplatBitSize > ElementBits)
9856     return false;
9857   Cnt = SplatBits.getSExtValue();
9858   return true;
9859 }
9860
9861 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
9862 /// operand of a vector shift left operation.  That value must be in the range:
9863 ///   0 <= Value < ElementBits for a left shift; or
9864 ///   0 <= Value <= ElementBits for a long left shift.
9865 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
9866   assert(VT.isVector() && "vector shift count is not a vector type");
9867   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9868   if (! getVShiftImm(Op, ElementBits, Cnt))
9869     return false;
9870   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
9871 }
9872
9873 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
9874 /// operand of a vector shift right operation.  For a shift opcode, the value
9875 /// is positive, but for an intrinsic the value count must be negative. The
9876 /// absolute value must be in the range:
9877 ///   1 <= |Value| <= ElementBits for a right shift; or
9878 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
9879 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
9880                          int64_t &Cnt) {
9881   assert(VT.isVector() && "vector shift count is not a vector type");
9882   int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
9883   if (! getVShiftImm(Op, ElementBits, Cnt))
9884     return false;
9885   if (!isIntrinsic)
9886     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
9887   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
9888     Cnt = -Cnt;
9889     return true;
9890   }
9891   return false;
9892 }
9893
9894 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
9895 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
9896   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
9897   switch (IntNo) {
9898   default:
9899     // Don't do anything for most intrinsics.
9900     break;
9901
9902   case Intrinsic::arm_neon_vabds:
9903     if (!N->getValueType(0).isInteger())
9904       return SDValue();
9905     return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
9906                        N->getOperand(1), N->getOperand(2));
9907   case Intrinsic::arm_neon_vabdu:
9908     return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
9909                        N->getOperand(1), N->getOperand(2));
9910
9911   // Vector shifts: check for immediate versions and lower them.
9912   // Note: This is done during DAG combining instead of DAG legalizing because
9913   // the build_vectors for 64-bit vector element shift counts are generally
9914   // not legal, and it is hard to see their values after they get legalized to
9915   // loads from a constant pool.
9916   case Intrinsic::arm_neon_vshifts:
9917   case Intrinsic::arm_neon_vshiftu:
9918   case Intrinsic::arm_neon_vrshifts:
9919   case Intrinsic::arm_neon_vrshiftu:
9920   case Intrinsic::arm_neon_vrshiftn:
9921   case Intrinsic::arm_neon_vqshifts:
9922   case Intrinsic::arm_neon_vqshiftu:
9923   case Intrinsic::arm_neon_vqshiftsu:
9924   case Intrinsic::arm_neon_vqshiftns:
9925   case Intrinsic::arm_neon_vqshiftnu:
9926   case Intrinsic::arm_neon_vqshiftnsu:
9927   case Intrinsic::arm_neon_vqrshiftns:
9928   case Intrinsic::arm_neon_vqrshiftnu:
9929   case Intrinsic::arm_neon_vqrshiftnsu: {
9930     EVT VT = N->getOperand(1).getValueType();
9931     int64_t Cnt;
9932     unsigned VShiftOpc = 0;
9933
9934     switch (IntNo) {
9935     case Intrinsic::arm_neon_vshifts:
9936     case Intrinsic::arm_neon_vshiftu:
9937       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
9938         VShiftOpc = ARMISD::VSHL;
9939         break;
9940       }
9941       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
9942         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
9943                      ARMISD::VSHRs : ARMISD::VSHRu);
9944         break;
9945       }
9946       return SDValue();
9947
9948     case Intrinsic::arm_neon_vrshifts:
9949     case Intrinsic::arm_neon_vrshiftu:
9950       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
9951         break;
9952       return SDValue();
9953
9954     case Intrinsic::arm_neon_vqshifts:
9955     case Intrinsic::arm_neon_vqshiftu:
9956       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9957         break;
9958       return SDValue();
9959
9960     case Intrinsic::arm_neon_vqshiftsu:
9961       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
9962         break;
9963       llvm_unreachable("invalid shift count for vqshlu intrinsic");
9964
9965     case Intrinsic::arm_neon_vrshiftn:
9966     case Intrinsic::arm_neon_vqshiftns:
9967     case Intrinsic::arm_neon_vqshiftnu:
9968     case Intrinsic::arm_neon_vqshiftnsu:
9969     case Intrinsic::arm_neon_vqrshiftns:
9970     case Intrinsic::arm_neon_vqrshiftnu:
9971     case Intrinsic::arm_neon_vqrshiftnsu:
9972       // Narrowing shifts require an immediate right shift.
9973       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
9974         break;
9975       llvm_unreachable("invalid shift count for narrowing vector shift "
9976                        "intrinsic");
9977
9978     default:
9979       llvm_unreachable("unhandled vector shift");
9980     }
9981
9982     switch (IntNo) {
9983     case Intrinsic::arm_neon_vshifts:
9984     case Intrinsic::arm_neon_vshiftu:
9985       // Opcode already set above.
9986       break;
9987     case Intrinsic::arm_neon_vrshifts:
9988       VShiftOpc = ARMISD::VRSHRs; break;
9989     case Intrinsic::arm_neon_vrshiftu:
9990       VShiftOpc = ARMISD::VRSHRu; break;
9991     case Intrinsic::arm_neon_vrshiftn:
9992       VShiftOpc = ARMISD::VRSHRN; break;
9993     case Intrinsic::arm_neon_vqshifts:
9994       VShiftOpc = ARMISD::VQSHLs; break;
9995     case Intrinsic::arm_neon_vqshiftu:
9996       VShiftOpc = ARMISD::VQSHLu; break;
9997     case Intrinsic::arm_neon_vqshiftsu:
9998       VShiftOpc = ARMISD::VQSHLsu; break;
9999     case Intrinsic::arm_neon_vqshiftns:
10000       VShiftOpc = ARMISD::VQSHRNs; break;
10001     case Intrinsic::arm_neon_vqshiftnu:
10002       VShiftOpc = ARMISD::VQSHRNu; break;
10003     case Intrinsic::arm_neon_vqshiftnsu:
10004       VShiftOpc = ARMISD::VQSHRNsu; break;
10005     case Intrinsic::arm_neon_vqrshiftns:
10006       VShiftOpc = ARMISD::VQRSHRNs; break;
10007     case Intrinsic::arm_neon_vqrshiftnu:
10008       VShiftOpc = ARMISD::VQRSHRNu; break;
10009     case Intrinsic::arm_neon_vqrshiftnsu:
10010       VShiftOpc = ARMISD::VQRSHRNsu; break;
10011     }
10012
10013     SDLoc dl(N);
10014     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10015                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
10016   }
10017
10018   case Intrinsic::arm_neon_vshiftins: {
10019     EVT VT = N->getOperand(1).getValueType();
10020     int64_t Cnt;
10021     unsigned VShiftOpc = 0;
10022
10023     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
10024       VShiftOpc = ARMISD::VSLI;
10025     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
10026       VShiftOpc = ARMISD::VSRI;
10027     else {
10028       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
10029     }
10030
10031     SDLoc dl(N);
10032     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
10033                        N->getOperand(1), N->getOperand(2),
10034                        DAG.getConstant(Cnt, dl, MVT::i32));
10035   }
10036
10037   case Intrinsic::arm_neon_vqrshifts:
10038   case Intrinsic::arm_neon_vqrshiftu:
10039     // No immediate versions of these to check for.
10040     break;
10041   }
10042
10043   return SDValue();
10044 }
10045
10046 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
10047 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
10048 /// combining instead of DAG legalizing because the build_vectors for 64-bit
10049 /// vector element shift counts are generally not legal, and it is hard to see
10050 /// their values after they get legalized to loads from a constant pool.
10051 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
10052                                    const ARMSubtarget *ST) {
10053   EVT VT = N->getValueType(0);
10054   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
10055     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
10056     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
10057     SDValue N1 = N->getOperand(1);
10058     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
10059       SDValue N0 = N->getOperand(0);
10060       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
10061           DAG.MaskedValueIsZero(N0.getOperand(0),
10062                                 APInt::getHighBitsSet(32, 16)))
10063         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
10064     }
10065   }
10066
10067   // Nothing to be done for scalar shifts.
10068   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10069   if (!VT.isVector() || !TLI.isTypeLegal(VT))
10070     return SDValue();
10071
10072   assert(ST->hasNEON() && "unexpected vector shift");
10073   int64_t Cnt;
10074
10075   switch (N->getOpcode()) {
10076   default: llvm_unreachable("unexpected shift opcode");
10077
10078   case ISD::SHL:
10079     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
10080       SDLoc dl(N);
10081       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
10082                          DAG.getConstant(Cnt, dl, MVT::i32));
10083     }
10084     break;
10085
10086   case ISD::SRA:
10087   case ISD::SRL:
10088     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
10089       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
10090                             ARMISD::VSHRs : ARMISD::VSHRu);
10091       SDLoc dl(N);
10092       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
10093                          DAG.getConstant(Cnt, dl, MVT::i32));
10094     }
10095   }
10096   return SDValue();
10097 }
10098
10099 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
10100 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
10101 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
10102                                     const ARMSubtarget *ST) {
10103   SDValue N0 = N->getOperand(0);
10104
10105   // Check for sign- and zero-extensions of vector extract operations of 8-
10106   // and 16-bit vector elements.  NEON supports these directly.  They are
10107   // handled during DAG combining because type legalization will promote them
10108   // to 32-bit types and it is messy to recognize the operations after that.
10109   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
10110     SDValue Vec = N0.getOperand(0);
10111     SDValue Lane = N0.getOperand(1);
10112     EVT VT = N->getValueType(0);
10113     EVT EltVT = N0.getValueType();
10114     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10115
10116     if (VT == MVT::i32 &&
10117         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
10118         TLI.isTypeLegal(Vec.getValueType()) &&
10119         isa<ConstantSDNode>(Lane)) {
10120
10121       unsigned Opc = 0;
10122       switch (N->getOpcode()) {
10123       default: llvm_unreachable("unexpected opcode");
10124       case ISD::SIGN_EXTEND:
10125         Opc = ARMISD::VGETLANEs;
10126         break;
10127       case ISD::ZERO_EXTEND:
10128       case ISD::ANY_EXTEND:
10129         Opc = ARMISD::VGETLANEu;
10130         break;
10131       }
10132       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
10133     }
10134   }
10135
10136   return SDValue();
10137 }
10138
10139 /// PerformSELECT_CCCombine - Target-specific DAG combining for ISD::SELECT_CC
10140 /// to match f32 max/min patterns to use NEON vmax/vmin instructions.
10141 static SDValue PerformSELECT_CCCombine(SDNode *N, SelectionDAG &DAG,
10142                                        const ARMSubtarget *ST) {
10143   // If the target supports NEON, try to use vmax/vmin instructions for f32
10144   // selects like "x < y ? x : y".  Unless the NoNaNsFPMath option is set,
10145   // be careful about NaNs:  NEON's vmax/vmin return NaN if either operand is
10146   // a NaN; only do the transformation when it matches that behavior.
10147
10148   // For now only do this when using NEON for FP operations; if using VFP, it
10149   // is not obvious that the benefit outweighs the cost of switching to the
10150   // NEON pipeline.
10151   if (!ST->hasNEON() || !ST->useNEONForSinglePrecisionFP() ||
10152       N->getValueType(0) != MVT::f32)
10153     return SDValue();
10154
10155   SDValue CondLHS = N->getOperand(0);
10156   SDValue CondRHS = N->getOperand(1);
10157   SDValue LHS = N->getOperand(2);
10158   SDValue RHS = N->getOperand(3);
10159   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
10160
10161   unsigned Opcode = 0;
10162   bool IsReversed;
10163   if (DAG.isEqualTo(LHS, CondLHS) && DAG.isEqualTo(RHS, CondRHS)) {
10164     IsReversed = false; // x CC y ? x : y
10165   } else if (DAG.isEqualTo(LHS, CondRHS) && DAG.isEqualTo(RHS, CondLHS)) {
10166     IsReversed = true ; // x CC y ? y : x
10167   } else {
10168     return SDValue();
10169   }
10170
10171   bool IsUnordered;
10172   switch (CC) {
10173   default: break;
10174   case ISD::SETOLT:
10175   case ISD::SETOLE:
10176   case ISD::SETLT:
10177   case ISD::SETLE:
10178   case ISD::SETULT:
10179   case ISD::SETULE:
10180     // If LHS is NaN, an ordered comparison will be false and the result will
10181     // be the RHS, but vmin(NaN, RHS) = NaN.  Avoid this by checking that LHS
10182     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10183     IsUnordered = (CC == ISD::SETULT || CC == ISD::SETULE);
10184     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10185       break;
10186     // For less-than-or-equal comparisons, "+0 <= -0" will be true but vmin
10187     // will return -0, so vmin can only be used for unsafe math or if one of
10188     // the operands is known to be nonzero.
10189     if ((CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE) &&
10190         !DAG.getTarget().Options.UnsafeFPMath &&
10191         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10192       break;
10193     Opcode = IsReversed ? ISD::FMAXNAN : ISD::FMINNAN;
10194     break;
10195
10196   case ISD::SETOGT:
10197   case ISD::SETOGE:
10198   case ISD::SETGT:
10199   case ISD::SETGE:
10200   case ISD::SETUGT:
10201   case ISD::SETUGE:
10202     // If LHS is NaN, an ordered comparison will be false and the result will
10203     // be the RHS, but vmax(NaN, RHS) = NaN.  Avoid this by checking that LHS
10204     // != NaN.  Likewise, for unordered comparisons, check for RHS != NaN.
10205     IsUnordered = (CC == ISD::SETUGT || CC == ISD::SETUGE);
10206     if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
10207       break;
10208     // For greater-than-or-equal comparisons, "-0 >= +0" will be true but vmax
10209     // will return +0, so vmax can only be used for unsafe math or if one of
10210     // the operands is known to be nonzero.
10211     if ((CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE) &&
10212         !DAG.getTarget().Options.UnsafeFPMath &&
10213         !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10214       break;
10215     Opcode = IsReversed ? ISD::FMINNAN : ISD::FMAXNAN;
10216     break;
10217   }
10218
10219   if (!Opcode)
10220     return SDValue();
10221   return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
10222 }
10223
10224 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
10225 SDValue
10226 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
10227   SDValue Cmp = N->getOperand(4);
10228   if (Cmp.getOpcode() != ARMISD::CMPZ)
10229     // Only looking at EQ and NE cases.
10230     return SDValue();
10231
10232   EVT VT = N->getValueType(0);
10233   SDLoc dl(N);
10234   SDValue LHS = Cmp.getOperand(0);
10235   SDValue RHS = Cmp.getOperand(1);
10236   SDValue FalseVal = N->getOperand(0);
10237   SDValue TrueVal = N->getOperand(1);
10238   SDValue ARMcc = N->getOperand(2);
10239   ARMCC::CondCodes CC =
10240     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
10241
10242   // Simplify
10243   //   mov     r1, r0
10244   //   cmp     r1, x
10245   //   mov     r0, y
10246   //   moveq   r0, x
10247   // to
10248   //   cmp     r0, x
10249   //   movne   r0, y
10250   //
10251   //   mov     r1, r0
10252   //   cmp     r1, x
10253   //   mov     r0, x
10254   //   movne   r0, y
10255   // to
10256   //   cmp     r0, x
10257   //   movne   r0, y
10258   /// FIXME: Turn this into a target neutral optimization?
10259   SDValue Res;
10260   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
10261     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
10262                       N->getOperand(3), Cmp);
10263   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
10264     SDValue ARMcc;
10265     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
10266     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
10267                       N->getOperand(3), NewCmp);
10268   }
10269
10270   if (Res.getNode()) {
10271     APInt KnownZero, KnownOne;
10272     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
10273     // Capture demanded bits information that would be otherwise lost.
10274     if (KnownZero == 0xfffffffe)
10275       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10276                         DAG.getValueType(MVT::i1));
10277     else if (KnownZero == 0xffffff00)
10278       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10279                         DAG.getValueType(MVT::i8));
10280     else if (KnownZero == 0xffff0000)
10281       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
10282                         DAG.getValueType(MVT::i16));
10283   }
10284
10285   return Res;
10286 }
10287
10288 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
10289                                              DAGCombinerInfo &DCI) const {
10290   switch (N->getOpcode()) {
10291   default: break;
10292   case ISD::ADDC:       return PerformADDCCombine(N, DCI, Subtarget);
10293   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
10294   case ISD::SUB:        return PerformSUBCombine(N, DCI);
10295   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
10296   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
10297   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
10298   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
10299   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
10300   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
10301   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
10302   case ISD::STORE:      return PerformSTORECombine(N, DCI);
10303   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
10304   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
10305   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
10306   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
10307   case ISD::FP_TO_SINT:
10308   case ISD::FP_TO_UINT: return PerformVCVTCombine(N, DCI, Subtarget);
10309   case ISD::FDIV:       return PerformVDIVCombine(N, DCI, Subtarget);
10310   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
10311   case ISD::SHL:
10312   case ISD::SRA:
10313   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
10314   case ISD::SIGN_EXTEND:
10315   case ISD::ZERO_EXTEND:
10316   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
10317   case ISD::SELECT_CC:  return PerformSELECT_CCCombine(N, DCI.DAG, Subtarget);
10318   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
10319   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
10320   case ARMISD::VLD2DUP:
10321   case ARMISD::VLD3DUP:
10322   case ARMISD::VLD4DUP:
10323     return PerformVLDCombine(N, DCI);
10324   case ARMISD::BUILD_VECTOR:
10325     return PerformARMBUILD_VECTORCombine(N, DCI);
10326   case ISD::INTRINSIC_VOID:
10327   case ISD::INTRINSIC_W_CHAIN:
10328     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10329     case Intrinsic::arm_neon_vld1:
10330     case Intrinsic::arm_neon_vld2:
10331     case Intrinsic::arm_neon_vld3:
10332     case Intrinsic::arm_neon_vld4:
10333     case Intrinsic::arm_neon_vld2lane:
10334     case Intrinsic::arm_neon_vld3lane:
10335     case Intrinsic::arm_neon_vld4lane:
10336     case Intrinsic::arm_neon_vst1:
10337     case Intrinsic::arm_neon_vst2:
10338     case Intrinsic::arm_neon_vst3:
10339     case Intrinsic::arm_neon_vst4:
10340     case Intrinsic::arm_neon_vst2lane:
10341     case Intrinsic::arm_neon_vst3lane:
10342     case Intrinsic::arm_neon_vst4lane:
10343       return PerformVLDCombine(N, DCI);
10344     default: break;
10345     }
10346     break;
10347   }
10348   return SDValue();
10349 }
10350
10351 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
10352                                                           EVT VT) const {
10353   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
10354 }
10355
10356 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
10357                                                        unsigned,
10358                                                        unsigned,
10359                                                        bool *Fast) const {
10360   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
10361   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
10362
10363   switch (VT.getSimpleVT().SimpleTy) {
10364   default:
10365     return false;
10366   case MVT::i8:
10367   case MVT::i16:
10368   case MVT::i32: {
10369     // Unaligned access can use (for example) LRDB, LRDH, LDR
10370     if (AllowsUnaligned) {
10371       if (Fast)
10372         *Fast = Subtarget->hasV7Ops();
10373       return true;
10374     }
10375     return false;
10376   }
10377   case MVT::f64:
10378   case MVT::v2f64: {
10379     // For any little-endian targets with neon, we can support unaligned ld/st
10380     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
10381     // A big-endian target may also explicitly support unaligned accesses
10382     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
10383       if (Fast)
10384         *Fast = true;
10385       return true;
10386     }
10387     return false;
10388   }
10389   }
10390 }
10391
10392 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
10393                        unsigned AlignCheck) {
10394   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
10395           (DstAlign == 0 || DstAlign % AlignCheck == 0));
10396 }
10397
10398 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
10399                                            unsigned DstAlign, unsigned SrcAlign,
10400                                            bool IsMemset, bool ZeroMemset,
10401                                            bool MemcpyStrSrc,
10402                                            MachineFunction &MF) const {
10403   const Function *F = MF.getFunction();
10404
10405   // See if we can use NEON instructions for this...
10406   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
10407       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10408     bool Fast;
10409     if (Size >= 16 &&
10410         (memOpAlign(SrcAlign, DstAlign, 16) ||
10411          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
10412       return MVT::v2f64;
10413     } else if (Size >= 8 &&
10414                (memOpAlign(SrcAlign, DstAlign, 8) ||
10415                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
10416                  Fast))) {
10417       return MVT::f64;
10418     }
10419   }
10420
10421   // Lowering to i32/i16 if the size permits.
10422   if (Size >= 4)
10423     return MVT::i32;
10424   else if (Size >= 2)
10425     return MVT::i16;
10426
10427   // Let the target-independent logic figure it out.
10428   return MVT::Other;
10429 }
10430
10431 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
10432   if (Val.getOpcode() != ISD::LOAD)
10433     return false;
10434
10435   EVT VT1 = Val.getValueType();
10436   if (!VT1.isSimple() || !VT1.isInteger() ||
10437       !VT2.isSimple() || !VT2.isInteger())
10438     return false;
10439
10440   switch (VT1.getSimpleVT().SimpleTy) {
10441   default: break;
10442   case MVT::i1:
10443   case MVT::i8:
10444   case MVT::i16:
10445     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
10446     return true;
10447   }
10448
10449   return false;
10450 }
10451
10452 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
10453   EVT VT = ExtVal.getValueType();
10454
10455   if (!isTypeLegal(VT))
10456     return false;
10457
10458   // Don't create a loadext if we can fold the extension into a wide/long
10459   // instruction.
10460   // If there's more than one user instruction, the loadext is desirable no
10461   // matter what.  There can be two uses by the same instruction.
10462   if (ExtVal->use_empty() ||
10463       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
10464     return true;
10465
10466   SDNode *U = *ExtVal->use_begin();
10467   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
10468        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
10469     return false;
10470
10471   return true;
10472 }
10473
10474 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
10475   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
10476     return false;
10477
10478   if (!isTypeLegal(EVT::getEVT(Ty1)))
10479     return false;
10480
10481   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
10482
10483   // Assuming the caller doesn't have a zeroext or signext return parameter,
10484   // truncation all the way down to i1 is valid.
10485   return true;
10486 }
10487
10488
10489 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
10490   if (V < 0)
10491     return false;
10492
10493   unsigned Scale = 1;
10494   switch (VT.getSimpleVT().SimpleTy) {
10495   default: return false;
10496   case MVT::i1:
10497   case MVT::i8:
10498     // Scale == 1;
10499     break;
10500   case MVT::i16:
10501     // Scale == 2;
10502     Scale = 2;
10503     break;
10504   case MVT::i32:
10505     // Scale == 4;
10506     Scale = 4;
10507     break;
10508   }
10509
10510   if ((V & (Scale - 1)) != 0)
10511     return false;
10512   V /= Scale;
10513   return V == (V & ((1LL << 5) - 1));
10514 }
10515
10516 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
10517                                       const ARMSubtarget *Subtarget) {
10518   bool isNeg = false;
10519   if (V < 0) {
10520     isNeg = true;
10521     V = - V;
10522   }
10523
10524   switch (VT.getSimpleVT().SimpleTy) {
10525   default: return false;
10526   case MVT::i1:
10527   case MVT::i8:
10528   case MVT::i16:
10529   case MVT::i32:
10530     // + imm12 or - imm8
10531     if (isNeg)
10532       return V == (V & ((1LL << 8) - 1));
10533     return V == (V & ((1LL << 12) - 1));
10534   case MVT::f32:
10535   case MVT::f64:
10536     // Same as ARM mode. FIXME: NEON?
10537     if (!Subtarget->hasVFP2())
10538       return false;
10539     if ((V & 3) != 0)
10540       return false;
10541     V >>= 2;
10542     return V == (V & ((1LL << 8) - 1));
10543   }
10544 }
10545
10546 /// isLegalAddressImmediate - Return true if the integer value can be used
10547 /// as the offset of the target addressing mode for load / store of the
10548 /// given type.
10549 static bool isLegalAddressImmediate(int64_t V, EVT VT,
10550                                     const ARMSubtarget *Subtarget) {
10551   if (V == 0)
10552     return true;
10553
10554   if (!VT.isSimple())
10555     return false;
10556
10557   if (Subtarget->isThumb1Only())
10558     return isLegalT1AddressImmediate(V, VT);
10559   else if (Subtarget->isThumb2())
10560     return isLegalT2AddressImmediate(V, VT, Subtarget);
10561
10562   // ARM mode.
10563   if (V < 0)
10564     V = - V;
10565   switch (VT.getSimpleVT().SimpleTy) {
10566   default: return false;
10567   case MVT::i1:
10568   case MVT::i8:
10569   case MVT::i32:
10570     // +- imm12
10571     return V == (V & ((1LL << 12) - 1));
10572   case MVT::i16:
10573     // +- imm8
10574     return V == (V & ((1LL << 8) - 1));
10575   case MVT::f32:
10576   case MVT::f64:
10577     if (!Subtarget->hasVFP2()) // FIXME: NEON?
10578       return false;
10579     if ((V & 3) != 0)
10580       return false;
10581     V >>= 2;
10582     return V == (V & ((1LL << 8) - 1));
10583   }
10584 }
10585
10586 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
10587                                                       EVT VT) const {
10588   int Scale = AM.Scale;
10589   if (Scale < 0)
10590     return false;
10591
10592   switch (VT.getSimpleVT().SimpleTy) {
10593   default: return false;
10594   case MVT::i1:
10595   case MVT::i8:
10596   case MVT::i16:
10597   case MVT::i32:
10598     if (Scale == 1)
10599       return true;
10600     // r + r << imm
10601     Scale = Scale & ~1;
10602     return Scale == 2 || Scale == 4 || Scale == 8;
10603   case MVT::i64:
10604     // r + r
10605     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10606       return true;
10607     return false;
10608   case MVT::isVoid:
10609     // Note, we allow "void" uses (basically, uses that aren't loads or
10610     // stores), because arm allows folding a scale into many arithmetic
10611     // operations.  This should be made more precise and revisited later.
10612
10613     // Allow r << imm, but the imm has to be a multiple of two.
10614     if (Scale & 1) return false;
10615     return isPowerOf2_32(Scale);
10616   }
10617 }
10618
10619 /// isLegalAddressingMode - Return true if the addressing mode represented
10620 /// by AM is legal for this target, for a load/store of the specified type.
10621 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
10622                                               const AddrMode &AM, Type *Ty,
10623                                               unsigned AS) const {
10624   EVT VT = getValueType(DL, Ty, true);
10625   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
10626     return false;
10627
10628   // Can never fold addr of global into load/store.
10629   if (AM.BaseGV)
10630     return false;
10631
10632   switch (AM.Scale) {
10633   case 0:  // no scale reg, must be "r+i" or "r", or "i".
10634     break;
10635   case 1:
10636     if (Subtarget->isThumb1Only())
10637       return false;
10638     // FALL THROUGH.
10639   default:
10640     // ARM doesn't support any R+R*scale+imm addr modes.
10641     if (AM.BaseOffs)
10642       return false;
10643
10644     if (!VT.isSimple())
10645       return false;
10646
10647     if (Subtarget->isThumb2())
10648       return isLegalT2ScaledAddressingMode(AM, VT);
10649
10650     int Scale = AM.Scale;
10651     switch (VT.getSimpleVT().SimpleTy) {
10652     default: return false;
10653     case MVT::i1:
10654     case MVT::i8:
10655     case MVT::i32:
10656       if (Scale < 0) Scale = -Scale;
10657       if (Scale == 1)
10658         return true;
10659       // r + r << imm
10660       return isPowerOf2_32(Scale & ~1);
10661     case MVT::i16:
10662     case MVT::i64:
10663       // r + r
10664       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
10665         return true;
10666       return false;
10667
10668     case MVT::isVoid:
10669       // Note, we allow "void" uses (basically, uses that aren't loads or
10670       // stores), because arm allows folding a scale into many arithmetic
10671       // operations.  This should be made more precise and revisited later.
10672
10673       // Allow r << imm, but the imm has to be a multiple of two.
10674       if (Scale & 1) return false;
10675       return isPowerOf2_32(Scale);
10676     }
10677   }
10678   return true;
10679 }
10680
10681 /// isLegalICmpImmediate - Return true if the specified immediate is legal
10682 /// icmp immediate, that is the target has icmp instructions which can compare
10683 /// a register against the immediate without having to materialize the
10684 /// immediate into a register.
10685 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
10686   // Thumb2 and ARM modes can use cmn for negative immediates.
10687   if (!Subtarget->isThumb())
10688     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
10689   if (Subtarget->isThumb2())
10690     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
10691   // Thumb1 doesn't have cmn, and only 8-bit immediates.
10692   return Imm >= 0 && Imm <= 255;
10693 }
10694
10695 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
10696 /// *or sub* immediate, that is the target has add or sub instructions which can
10697 /// add a register with the immediate without having to materialize the
10698 /// immediate into a register.
10699 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
10700   // Same encoding for add/sub, just flip the sign.
10701   int64_t AbsImm = std::abs(Imm);
10702   if (!Subtarget->isThumb())
10703     return ARM_AM::getSOImmVal(AbsImm) != -1;
10704   if (Subtarget->isThumb2())
10705     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
10706   // Thumb1 only has 8-bit unsigned immediate.
10707   return AbsImm >= 0 && AbsImm <= 255;
10708 }
10709
10710 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
10711                                       bool isSEXTLoad, SDValue &Base,
10712                                       SDValue &Offset, bool &isInc,
10713                                       SelectionDAG &DAG) {
10714   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10715     return false;
10716
10717   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
10718     // AddressingMode 3
10719     Base = Ptr->getOperand(0);
10720     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10721       int RHSC = (int)RHS->getZExtValue();
10722       if (RHSC < 0 && RHSC > -256) {
10723         assert(Ptr->getOpcode() == ISD::ADD);
10724         isInc = false;
10725         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10726         return true;
10727       }
10728     }
10729     isInc = (Ptr->getOpcode() == ISD::ADD);
10730     Offset = Ptr->getOperand(1);
10731     return true;
10732   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
10733     // AddressingMode 2
10734     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10735       int RHSC = (int)RHS->getZExtValue();
10736       if (RHSC < 0 && RHSC > -0x1000) {
10737         assert(Ptr->getOpcode() == ISD::ADD);
10738         isInc = false;
10739         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10740         Base = Ptr->getOperand(0);
10741         return true;
10742       }
10743     }
10744
10745     if (Ptr->getOpcode() == ISD::ADD) {
10746       isInc = true;
10747       ARM_AM::ShiftOpc ShOpcVal=
10748         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
10749       if (ShOpcVal != ARM_AM::no_shift) {
10750         Base = Ptr->getOperand(1);
10751         Offset = Ptr->getOperand(0);
10752       } else {
10753         Base = Ptr->getOperand(0);
10754         Offset = Ptr->getOperand(1);
10755       }
10756       return true;
10757     }
10758
10759     isInc = (Ptr->getOpcode() == ISD::ADD);
10760     Base = Ptr->getOperand(0);
10761     Offset = Ptr->getOperand(1);
10762     return true;
10763   }
10764
10765   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
10766   return false;
10767 }
10768
10769 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
10770                                      bool isSEXTLoad, SDValue &Base,
10771                                      SDValue &Offset, bool &isInc,
10772                                      SelectionDAG &DAG) {
10773   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
10774     return false;
10775
10776   Base = Ptr->getOperand(0);
10777   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
10778     int RHSC = (int)RHS->getZExtValue();
10779     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
10780       assert(Ptr->getOpcode() == ISD::ADD);
10781       isInc = false;
10782       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
10783       return true;
10784     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
10785       isInc = Ptr->getOpcode() == ISD::ADD;
10786       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
10787       return true;
10788     }
10789   }
10790
10791   return false;
10792 }
10793
10794 /// getPreIndexedAddressParts - returns true by value, base pointer and
10795 /// offset pointer and addressing mode by reference if the node's address
10796 /// can be legally represented as pre-indexed load / store address.
10797 bool
10798 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10799                                              SDValue &Offset,
10800                                              ISD::MemIndexedMode &AM,
10801                                              SelectionDAG &DAG) const {
10802   if (Subtarget->isThumb1Only())
10803     return false;
10804
10805   EVT VT;
10806   SDValue Ptr;
10807   bool isSEXTLoad = false;
10808   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10809     Ptr = LD->getBasePtr();
10810     VT  = LD->getMemoryVT();
10811     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10812   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10813     Ptr = ST->getBasePtr();
10814     VT  = ST->getMemoryVT();
10815   } else
10816     return false;
10817
10818   bool isInc;
10819   bool isLegal = false;
10820   if (Subtarget->isThumb2())
10821     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10822                                        Offset, isInc, DAG);
10823   else
10824     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
10825                                         Offset, isInc, DAG);
10826   if (!isLegal)
10827     return false;
10828
10829   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
10830   return true;
10831 }
10832
10833 /// getPostIndexedAddressParts - returns true by value, base pointer and
10834 /// offset pointer and addressing mode by reference if this node can be
10835 /// combined with a load / store to form a post-indexed load / store.
10836 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
10837                                                    SDValue &Base,
10838                                                    SDValue &Offset,
10839                                                    ISD::MemIndexedMode &AM,
10840                                                    SelectionDAG &DAG) const {
10841   if (Subtarget->isThumb1Only())
10842     return false;
10843
10844   EVT VT;
10845   SDValue Ptr;
10846   bool isSEXTLoad = false;
10847   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10848     VT  = LD->getMemoryVT();
10849     Ptr = LD->getBasePtr();
10850     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
10851   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10852     VT  = ST->getMemoryVT();
10853     Ptr = ST->getBasePtr();
10854   } else
10855     return false;
10856
10857   bool isInc;
10858   bool isLegal = false;
10859   if (Subtarget->isThumb2())
10860     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10861                                        isInc, DAG);
10862   else
10863     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
10864                                         isInc, DAG);
10865   if (!isLegal)
10866     return false;
10867
10868   if (Ptr != Base) {
10869     // Swap base ptr and offset to catch more post-index load / store when
10870     // it's legal. In Thumb2 mode, offset must be an immediate.
10871     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
10872         !Subtarget->isThumb2())
10873       std::swap(Base, Offset);
10874
10875     // Post-indexed load / store update the base pointer.
10876     if (Ptr != Base)
10877       return false;
10878   }
10879
10880   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
10881   return true;
10882 }
10883
10884 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
10885                                                       APInt &KnownZero,
10886                                                       APInt &KnownOne,
10887                                                       const SelectionDAG &DAG,
10888                                                       unsigned Depth) const {
10889   unsigned BitWidth = KnownOne.getBitWidth();
10890   KnownZero = KnownOne = APInt(BitWidth, 0);
10891   switch (Op.getOpcode()) {
10892   default: break;
10893   case ARMISD::ADDC:
10894   case ARMISD::ADDE:
10895   case ARMISD::SUBC:
10896   case ARMISD::SUBE:
10897     // These nodes' second result is a boolean
10898     if (Op.getResNo() == 0)
10899       break;
10900     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
10901     break;
10902   case ARMISD::CMOV: {
10903     // Bits are known zero/one if known on the LHS and RHS.
10904     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
10905     if (KnownZero == 0 && KnownOne == 0) return;
10906
10907     APInt KnownZeroRHS, KnownOneRHS;
10908     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
10909     KnownZero &= KnownZeroRHS;
10910     KnownOne  &= KnownOneRHS;
10911     return;
10912   }
10913   case ISD::INTRINSIC_W_CHAIN: {
10914     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
10915     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
10916     switch (IntID) {
10917     default: return;
10918     case Intrinsic::arm_ldaex:
10919     case Intrinsic::arm_ldrex: {
10920       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
10921       unsigned MemBits = VT.getScalarType().getSizeInBits();
10922       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
10923       return;
10924     }
10925     }
10926   }
10927   }
10928 }
10929
10930 //===----------------------------------------------------------------------===//
10931 //                           ARM Inline Assembly Support
10932 //===----------------------------------------------------------------------===//
10933
10934 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
10935   // Looking for "rev" which is V6+.
10936   if (!Subtarget->hasV6Ops())
10937     return false;
10938
10939   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10940   std::string AsmStr = IA->getAsmString();
10941   SmallVector<StringRef, 4> AsmPieces;
10942   SplitString(AsmStr, AsmPieces, ";\n");
10943
10944   switch (AsmPieces.size()) {
10945   default: return false;
10946   case 1:
10947     AsmStr = AsmPieces[0];
10948     AsmPieces.clear();
10949     SplitString(AsmStr, AsmPieces, " \t,");
10950
10951     // rev $0, $1
10952     if (AsmPieces.size() == 3 &&
10953         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
10954         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
10955       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10956       if (Ty && Ty->getBitWidth() == 32)
10957         return IntrinsicLowering::LowerToByteSwap(CI);
10958     }
10959     break;
10960   }
10961
10962   return false;
10963 }
10964
10965 /// getConstraintType - Given a constraint letter, return the type of
10966 /// constraint it is for this target.
10967 ARMTargetLowering::ConstraintType
10968 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
10969   if (Constraint.size() == 1) {
10970     switch (Constraint[0]) {
10971     default:  break;
10972     case 'l': return C_RegisterClass;
10973     case 'w': return C_RegisterClass;
10974     case 'h': return C_RegisterClass;
10975     case 'x': return C_RegisterClass;
10976     case 't': return C_RegisterClass;
10977     case 'j': return C_Other; // Constant for movw.
10978       // An address with a single base register. Due to the way we
10979       // currently handle addresses it is the same as an 'r' memory constraint.
10980     case 'Q': return C_Memory;
10981     }
10982   } else if (Constraint.size() == 2) {
10983     switch (Constraint[0]) {
10984     default: break;
10985     // All 'U+' constraints are addresses.
10986     case 'U': return C_Memory;
10987     }
10988   }
10989   return TargetLowering::getConstraintType(Constraint);
10990 }
10991
10992 /// Examine constraint type and operand type and determine a weight value.
10993 /// This object must already have been set up with the operand type
10994 /// and the current alternative constraint selected.
10995 TargetLowering::ConstraintWeight
10996 ARMTargetLowering::getSingleConstraintMatchWeight(
10997     AsmOperandInfo &info, const char *constraint) const {
10998   ConstraintWeight weight = CW_Invalid;
10999   Value *CallOperandVal = info.CallOperandVal;
11000     // If we don't have a value, we can't do a match,
11001     // but allow it at the lowest weight.
11002   if (!CallOperandVal)
11003     return CW_Default;
11004   Type *type = CallOperandVal->getType();
11005   // Look at the constraint type.
11006   switch (*constraint) {
11007   default:
11008     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11009     break;
11010   case 'l':
11011     if (type->isIntegerTy()) {
11012       if (Subtarget->isThumb())
11013         weight = CW_SpecificReg;
11014       else
11015         weight = CW_Register;
11016     }
11017     break;
11018   case 'w':
11019     if (type->isFloatingPointTy())
11020       weight = CW_Register;
11021     break;
11022   }
11023   return weight;
11024 }
11025
11026 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
11027 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
11028     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
11029   if (Constraint.size() == 1) {
11030     // GCC ARM Constraint Letters
11031     switch (Constraint[0]) {
11032     case 'l': // Low regs or general regs.
11033       if (Subtarget->isThumb())
11034         return RCPair(0U, &ARM::tGPRRegClass);
11035       return RCPair(0U, &ARM::GPRRegClass);
11036     case 'h': // High regs or no regs.
11037       if (Subtarget->isThumb())
11038         return RCPair(0U, &ARM::hGPRRegClass);
11039       break;
11040     case 'r':
11041       if (Subtarget->isThumb1Only())
11042         return RCPair(0U, &ARM::tGPRRegClass);
11043       return RCPair(0U, &ARM::GPRRegClass);
11044     case 'w':
11045       if (VT == MVT::Other)
11046         break;
11047       if (VT == MVT::f32)
11048         return RCPair(0U, &ARM::SPRRegClass);
11049       if (VT.getSizeInBits() == 64)
11050         return RCPair(0U, &ARM::DPRRegClass);
11051       if (VT.getSizeInBits() == 128)
11052         return RCPair(0U, &ARM::QPRRegClass);
11053       break;
11054     case 'x':
11055       if (VT == MVT::Other)
11056         break;
11057       if (VT == MVT::f32)
11058         return RCPair(0U, &ARM::SPR_8RegClass);
11059       if (VT.getSizeInBits() == 64)
11060         return RCPair(0U, &ARM::DPR_8RegClass);
11061       if (VT.getSizeInBits() == 128)
11062         return RCPair(0U, &ARM::QPR_8RegClass);
11063       break;
11064     case 't':
11065       if (VT == MVT::f32)
11066         return RCPair(0U, &ARM::SPRRegClass);
11067       break;
11068     }
11069   }
11070   if (StringRef("{cc}").equals_lower(Constraint))
11071     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
11072
11073   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11074 }
11075
11076 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11077 /// vector.  If it is invalid, don't add anything to Ops.
11078 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11079                                                      std::string &Constraint,
11080                                                      std::vector<SDValue>&Ops,
11081                                                      SelectionDAG &DAG) const {
11082   SDValue Result;
11083
11084   // Currently only support length 1 constraints.
11085   if (Constraint.length() != 1) return;
11086
11087   char ConstraintLetter = Constraint[0];
11088   switch (ConstraintLetter) {
11089   default: break;
11090   case 'j':
11091   case 'I': case 'J': case 'K': case 'L':
11092   case 'M': case 'N': case 'O':
11093     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
11094     if (!C)
11095       return;
11096
11097     int64_t CVal64 = C->getSExtValue();
11098     int CVal = (int) CVal64;
11099     // None of these constraints allow values larger than 32 bits.  Check
11100     // that the value fits in an int.
11101     if (CVal != CVal64)
11102       return;
11103
11104     switch (ConstraintLetter) {
11105       case 'j':
11106         // Constant suitable for movw, must be between 0 and
11107         // 65535.
11108         if (Subtarget->hasV6T2Ops())
11109           if (CVal >= 0 && CVal <= 65535)
11110             break;
11111         return;
11112       case 'I':
11113         if (Subtarget->isThumb1Only()) {
11114           // This must be a constant between 0 and 255, for ADD
11115           // immediates.
11116           if (CVal >= 0 && CVal <= 255)
11117             break;
11118         } else if (Subtarget->isThumb2()) {
11119           // A constant that can be used as an immediate value in a
11120           // data-processing instruction.
11121           if (ARM_AM::getT2SOImmVal(CVal) != -1)
11122             break;
11123         } else {
11124           // A constant that can be used as an immediate value in a
11125           // data-processing instruction.
11126           if (ARM_AM::getSOImmVal(CVal) != -1)
11127             break;
11128         }
11129         return;
11130
11131       case 'J':
11132         if (Subtarget->isThumb()) {  // FIXME thumb2
11133           // This must be a constant between -255 and -1, for negated ADD
11134           // immediates. This can be used in GCC with an "n" modifier that
11135           // prints the negated value, for use with SUB instructions. It is
11136           // not useful otherwise but is implemented for compatibility.
11137           if (CVal >= -255 && CVal <= -1)
11138             break;
11139         } else {
11140           // This must be a constant between -4095 and 4095. It is not clear
11141           // what this constraint is intended for. Implemented for
11142           // compatibility with GCC.
11143           if (CVal >= -4095 && CVal <= 4095)
11144             break;
11145         }
11146         return;
11147
11148       case 'K':
11149         if (Subtarget->isThumb1Only()) {
11150           // A 32-bit value where only one byte has a nonzero value. Exclude
11151           // zero to match GCC. This constraint is used by GCC internally for
11152           // constants that can be loaded with a move/shift combination.
11153           // It is not useful otherwise but is implemented for compatibility.
11154           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
11155             break;
11156         } else if (Subtarget->isThumb2()) {
11157           // A constant whose bitwise inverse can be used as an immediate
11158           // value in a data-processing instruction. This can be used in GCC
11159           // with a "B" modifier that prints the inverted value, for use with
11160           // BIC and MVN instructions. It is not useful otherwise but is
11161           // implemented for compatibility.
11162           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
11163             break;
11164         } else {
11165           // A constant whose bitwise inverse can be used as an immediate
11166           // value in a data-processing instruction. This can be used in GCC
11167           // with a "B" modifier that prints the inverted value, for use with
11168           // BIC and MVN instructions. It is not useful otherwise but is
11169           // implemented for compatibility.
11170           if (ARM_AM::getSOImmVal(~CVal) != -1)
11171             break;
11172         }
11173         return;
11174
11175       case 'L':
11176         if (Subtarget->isThumb1Only()) {
11177           // This must be a constant between -7 and 7,
11178           // for 3-operand ADD/SUB immediate instructions.
11179           if (CVal >= -7 && CVal < 7)
11180             break;
11181         } else if (Subtarget->isThumb2()) {
11182           // A constant whose negation can be used as an immediate value in a
11183           // data-processing instruction. This can be used in GCC with an "n"
11184           // modifier that prints the negated value, for use with SUB
11185           // instructions. It is not useful otherwise but is implemented for
11186           // compatibility.
11187           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
11188             break;
11189         } else {
11190           // A constant whose negation can be used as an immediate value in a
11191           // data-processing instruction. This can be used in GCC with an "n"
11192           // modifier that prints the negated value, for use with SUB
11193           // instructions. It is not useful otherwise but is implemented for
11194           // compatibility.
11195           if (ARM_AM::getSOImmVal(-CVal) != -1)
11196             break;
11197         }
11198         return;
11199
11200       case 'M':
11201         if (Subtarget->isThumb()) { // FIXME thumb2
11202           // This must be a multiple of 4 between 0 and 1020, for
11203           // ADD sp + immediate.
11204           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
11205             break;
11206         } else {
11207           // A power of two or a constant between 0 and 32.  This is used in
11208           // GCC for the shift amount on shifted register operands, but it is
11209           // useful in general for any shift amounts.
11210           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
11211             break;
11212         }
11213         return;
11214
11215       case 'N':
11216         if (Subtarget->isThumb()) {  // FIXME thumb2
11217           // This must be a constant between 0 and 31, for shift amounts.
11218           if (CVal >= 0 && CVal <= 31)
11219             break;
11220         }
11221         return;
11222
11223       case 'O':
11224         if (Subtarget->isThumb()) {  // FIXME thumb2
11225           // This must be a multiple of 4 between -508 and 508, for
11226           // ADD/SUB sp = sp + immediate.
11227           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
11228             break;
11229         }
11230         return;
11231     }
11232     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
11233     break;
11234   }
11235
11236   if (Result.getNode()) {
11237     Ops.push_back(Result);
11238     return;
11239   }
11240   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11241 }
11242
11243 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
11244   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid()) &&
11245          "Register-based DivRem lowering only");
11246   unsigned Opcode = Op->getOpcode();
11247   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
11248          "Invalid opcode for Div/Rem lowering");
11249   bool isSigned = (Opcode == ISD::SDIVREM);
11250   EVT VT = Op->getValueType(0);
11251   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
11252
11253   RTLIB::Libcall LC;
11254   switch (VT.getSimpleVT().SimpleTy) {
11255   default: llvm_unreachable("Unexpected request for libcall!");
11256   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
11257   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
11258   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
11259   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
11260   }
11261
11262   SDValue InChain = DAG.getEntryNode();
11263
11264   TargetLowering::ArgListTy Args;
11265   TargetLowering::ArgListEntry Entry;
11266   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
11267     EVT ArgVT = Op->getOperand(i).getValueType();
11268     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11269     Entry.Node = Op->getOperand(i);
11270     Entry.Ty = ArgTy;
11271     Entry.isSExt = isSigned;
11272     Entry.isZExt = !isSigned;
11273     Args.push_back(Entry);
11274   }
11275
11276   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
11277                                          getPointerTy(DAG.getDataLayout()));
11278
11279   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
11280
11281   SDLoc dl(Op);
11282   TargetLowering::CallLoweringInfo CLI(DAG);
11283   CLI.setDebugLoc(dl).setChain(InChain)
11284     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args), 0)
11285     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
11286
11287   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
11288   return CallInfo.first;
11289 }
11290
11291 SDValue
11292 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
11293   assert(Subtarget->isTargetWindows() && "unsupported target platform");
11294   SDLoc DL(Op);
11295
11296   // Get the inputs.
11297   SDValue Chain = Op.getOperand(0);
11298   SDValue Size  = Op.getOperand(1);
11299
11300   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
11301                               DAG.getConstant(2, DL, MVT::i32));
11302
11303   SDValue Flag;
11304   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
11305   Flag = Chain.getValue(1);
11306
11307   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11308   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
11309
11310   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
11311   Chain = NewSP.getValue(1);
11312
11313   SDValue Ops[2] = { NewSP, Chain };
11314   return DAG.getMergeValues(Ops, DL);
11315 }
11316
11317 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
11318   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
11319          "Unexpected type for custom-lowering FP_EXTEND");
11320
11321   RTLIB::Libcall LC;
11322   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
11323
11324   SDValue SrcVal = Op.getOperand(0);
11325   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11326                      /*isSigned*/ false, SDLoc(Op)).first;
11327 }
11328
11329 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
11330   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
11331          Subtarget->isFPOnlySP() &&
11332          "Unexpected type for custom-lowering FP_ROUND");
11333
11334   RTLIB::Libcall LC;
11335   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
11336
11337   SDValue SrcVal = Op.getOperand(0);
11338   return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
11339                      /*isSigned*/ false, SDLoc(Op)).first;
11340 }
11341
11342 bool
11343 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
11344   // The ARM target isn't yet aware of offsets.
11345   return false;
11346 }
11347
11348 bool ARM::isBitFieldInvertedMask(unsigned v) {
11349   if (v == 0xffffffff)
11350     return false;
11351
11352   // there can be 1's on either or both "outsides", all the "inside"
11353   // bits must be 0's
11354   return isShiftedMask_32(~v);
11355 }
11356
11357 /// isFPImmLegal - Returns true if the target can instruction select the
11358 /// specified FP immediate natively. If false, the legalizer will
11359 /// materialize the FP immediate as a load from a constant pool.
11360 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
11361   if (!Subtarget->hasVFP3())
11362     return false;
11363   if (VT == MVT::f32)
11364     return ARM_AM::getFP32Imm(Imm) != -1;
11365   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
11366     return ARM_AM::getFP64Imm(Imm) != -1;
11367   return false;
11368 }
11369
11370 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
11371 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
11372 /// specified in the intrinsic calls.
11373 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
11374                                            const CallInst &I,
11375                                            unsigned Intrinsic) const {
11376   switch (Intrinsic) {
11377   case Intrinsic::arm_neon_vld1:
11378   case Intrinsic::arm_neon_vld2:
11379   case Intrinsic::arm_neon_vld3:
11380   case Intrinsic::arm_neon_vld4:
11381   case Intrinsic::arm_neon_vld2lane:
11382   case Intrinsic::arm_neon_vld3lane:
11383   case Intrinsic::arm_neon_vld4lane: {
11384     Info.opc = ISD::INTRINSIC_W_CHAIN;
11385     // Conservatively set memVT to the entire set of vectors loaded.
11386     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11387     uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
11388     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11389     Info.ptrVal = I.getArgOperand(0);
11390     Info.offset = 0;
11391     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11392     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11393     Info.vol = false; // volatile loads with NEON intrinsics not supported
11394     Info.readMem = true;
11395     Info.writeMem = false;
11396     return true;
11397   }
11398   case Intrinsic::arm_neon_vst1:
11399   case Intrinsic::arm_neon_vst2:
11400   case Intrinsic::arm_neon_vst3:
11401   case Intrinsic::arm_neon_vst4:
11402   case Intrinsic::arm_neon_vst2lane:
11403   case Intrinsic::arm_neon_vst3lane:
11404   case Intrinsic::arm_neon_vst4lane: {
11405     Info.opc = ISD::INTRINSIC_VOID;
11406     // Conservatively set memVT to the entire set of vectors stored.
11407     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11408     unsigned NumElts = 0;
11409     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
11410       Type *ArgTy = I.getArgOperand(ArgI)->getType();
11411       if (!ArgTy->isVectorTy())
11412         break;
11413       NumElts += DL.getTypeAllocSize(ArgTy) / 8;
11414     }
11415     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
11416     Info.ptrVal = I.getArgOperand(0);
11417     Info.offset = 0;
11418     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
11419     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
11420     Info.vol = false; // volatile stores with NEON intrinsics not supported
11421     Info.readMem = false;
11422     Info.writeMem = true;
11423     return true;
11424   }
11425   case Intrinsic::arm_ldaex:
11426   case Intrinsic::arm_ldrex: {
11427     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11428     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
11429     Info.opc = ISD::INTRINSIC_W_CHAIN;
11430     Info.memVT = MVT::getVT(PtrTy->getElementType());
11431     Info.ptrVal = I.getArgOperand(0);
11432     Info.offset = 0;
11433     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11434     Info.vol = true;
11435     Info.readMem = true;
11436     Info.writeMem = false;
11437     return true;
11438   }
11439   case Intrinsic::arm_stlex:
11440   case Intrinsic::arm_strex: {
11441     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
11442     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
11443     Info.opc = ISD::INTRINSIC_W_CHAIN;
11444     Info.memVT = MVT::getVT(PtrTy->getElementType());
11445     Info.ptrVal = I.getArgOperand(1);
11446     Info.offset = 0;
11447     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
11448     Info.vol = true;
11449     Info.readMem = false;
11450     Info.writeMem = true;
11451     return true;
11452   }
11453   case Intrinsic::arm_stlexd:
11454   case Intrinsic::arm_strexd: {
11455     Info.opc = ISD::INTRINSIC_W_CHAIN;
11456     Info.memVT = MVT::i64;
11457     Info.ptrVal = I.getArgOperand(2);
11458     Info.offset = 0;
11459     Info.align = 8;
11460     Info.vol = true;
11461     Info.readMem = false;
11462     Info.writeMem = true;
11463     return true;
11464   }
11465   case Intrinsic::arm_ldaexd:
11466   case Intrinsic::arm_ldrexd: {
11467     Info.opc = ISD::INTRINSIC_W_CHAIN;
11468     Info.memVT = MVT::i64;
11469     Info.ptrVal = I.getArgOperand(0);
11470     Info.offset = 0;
11471     Info.align = 8;
11472     Info.vol = true;
11473     Info.readMem = true;
11474     Info.writeMem = false;
11475     return true;
11476   }
11477   default:
11478     break;
11479   }
11480
11481   return false;
11482 }
11483
11484 /// \brief Returns true if it is beneficial to convert a load of a constant
11485 /// to just the constant itself.
11486 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
11487                                                           Type *Ty) const {
11488   assert(Ty->isIntegerTy());
11489
11490   unsigned Bits = Ty->getPrimitiveSizeInBits();
11491   if (Bits == 0 || Bits > 32)
11492     return false;
11493   return true;
11494 }
11495
11496 bool ARMTargetLowering::hasLoadLinkedStoreConditional() const { return true; }
11497
11498 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
11499                                         ARM_MB::MemBOpt Domain) const {
11500   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11501
11502   // First, if the target has no DMB, see what fallback we can use.
11503   if (!Subtarget->hasDataBarrier()) {
11504     // Some ARMv6 cpus can support data barriers with an mcr instruction.
11505     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
11506     // here.
11507     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
11508       Function *MCR = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
11509       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
11510                         Builder.getInt32(0), Builder.getInt32(7),
11511                         Builder.getInt32(10), Builder.getInt32(5)};
11512       return Builder.CreateCall(MCR, args);
11513     } else {
11514       // Instead of using barriers, atomic accesses on these subtargets use
11515       // libcalls.
11516       llvm_unreachable("makeDMB on a target so old that it has no barriers");
11517     }
11518   } else {
11519     Function *DMB = llvm::Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
11520     // Only a full system barrier exists in the M-class architectures.
11521     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
11522     Constant *CDomain = Builder.getInt32(Domain);
11523     return Builder.CreateCall(DMB, CDomain);
11524   }
11525 }
11526
11527 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
11528 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
11529                                          AtomicOrdering Ord, bool IsStore,
11530                                          bool IsLoad) const {
11531   if (!getInsertFencesForAtomic())
11532     return nullptr;
11533
11534   switch (Ord) {
11535   case NotAtomic:
11536   case Unordered:
11537     llvm_unreachable("Invalid fence: unordered/non-atomic");
11538   case Monotonic:
11539   case Acquire:
11540     return nullptr; // Nothing to do
11541   case SequentiallyConsistent:
11542     if (!IsStore)
11543       return nullptr; // Nothing to do
11544     /*FALLTHROUGH*/
11545   case Release:
11546   case AcquireRelease:
11547     if (Subtarget->isSwift())
11548       return makeDMB(Builder, ARM_MB::ISHST);
11549     // FIXME: add a comment with a link to documentation justifying this.
11550     else
11551       return makeDMB(Builder, ARM_MB::ISH);
11552   }
11553   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
11554 }
11555
11556 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
11557                                           AtomicOrdering Ord, bool IsStore,
11558                                           bool IsLoad) const {
11559   if (!getInsertFencesForAtomic())
11560     return nullptr;
11561
11562   switch (Ord) {
11563   case NotAtomic:
11564   case Unordered:
11565     llvm_unreachable("Invalid fence: unordered/not-atomic");
11566   case Monotonic:
11567   case Release:
11568     return nullptr; // Nothing to do
11569   case Acquire:
11570   case AcquireRelease:
11571   case SequentiallyConsistent:
11572     return makeDMB(Builder, ARM_MB::ISH);
11573   }
11574   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
11575 }
11576
11577 // Loads and stores less than 64-bits are already atomic; ones above that
11578 // are doomed anyway, so defer to the default libcall and blame the OS when
11579 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11580 // anything for those.
11581 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
11582   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
11583   return (Size == 64) && !Subtarget->isMClass();
11584 }
11585
11586 // Loads and stores less than 64-bits are already atomic; ones above that
11587 // are doomed anyway, so defer to the default libcall and blame the OS when
11588 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
11589 // anything for those.
11590 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
11591 // guarantee, see DDI0406C ARM architecture reference manual,
11592 // sections A8.8.72-74 LDRD)
11593 bool ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
11594   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
11595   return (Size == 64) && !Subtarget->isMClass();
11596 }
11597
11598 // For the real atomic operations, we have ldrex/strex up to 32 bits,
11599 // and up to 64 bits on the non-M profiles
11600 TargetLoweringBase::AtomicRMWExpansionKind
11601 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
11602   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
11603   return (Size <= (Subtarget->isMClass() ? 32U : 64U))
11604              ? AtomicRMWExpansionKind::LLSC
11605              : AtomicRMWExpansionKind::None;
11606 }
11607
11608 // This has so far only been implemented for MachO.
11609 bool ARMTargetLowering::useLoadStackGuardNode() const {
11610   return Subtarget->isTargetMachO();
11611 }
11612
11613 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
11614                                                   unsigned &Cost) const {
11615   // If we do not have NEON, vector types are not natively supported.
11616   if (!Subtarget->hasNEON())
11617     return false;
11618
11619   // Floating point values and vector values map to the same register file.
11620   // Therefore, although we could do a store extract of a vector type, this is
11621   // better to leave at float as we have more freedom in the addressing mode for
11622   // those.
11623   if (VectorTy->isFPOrFPVectorTy())
11624     return false;
11625
11626   // If the index is unknown at compile time, this is very expensive to lower
11627   // and it is not possible to combine the store with the extract.
11628   if (!isa<ConstantInt>(Idx))
11629     return false;
11630
11631   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
11632   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
11633   // We can do a store + vector extract on any vector that fits perfectly in a D
11634   // or Q register.
11635   if (BitWidth == 64 || BitWidth == 128) {
11636     Cost = 0;
11637     return true;
11638   }
11639   return false;
11640 }
11641
11642 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
11643                                          AtomicOrdering Ord) const {
11644   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11645   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
11646   bool IsAcquire = isAtLeastAcquire(Ord);
11647
11648   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
11649   // intrinsic must return {i32, i32} and we have to recombine them into a
11650   // single i64 here.
11651   if (ValTy->getPrimitiveSizeInBits() == 64) {
11652     Intrinsic::ID Int =
11653         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
11654     Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int);
11655
11656     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11657     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
11658
11659     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
11660     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
11661     if (!Subtarget->isLittle())
11662       std::swap (Lo, Hi);
11663     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
11664     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
11665     return Builder.CreateOr(
11666         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
11667   }
11668
11669   Type *Tys[] = { Addr->getType() };
11670   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
11671   Function *Ldrex = llvm::Intrinsic::getDeclaration(M, Int, Tys);
11672
11673   return Builder.CreateTruncOrBitCast(
11674       Builder.CreateCall(Ldrex, Addr),
11675       cast<PointerType>(Addr->getType())->getElementType());
11676 }
11677
11678 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
11679                                                Value *Addr,
11680                                                AtomicOrdering Ord) const {
11681   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
11682   bool IsRelease = isAtLeastRelease(Ord);
11683
11684   // Since the intrinsics must have legal type, the i64 intrinsics take two
11685   // parameters: "i32, i32". We must marshal Val into the appropriate form
11686   // before the call.
11687   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
11688     Intrinsic::ID Int =
11689         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
11690     Function *Strex = Intrinsic::getDeclaration(M, Int);
11691     Type *Int32Ty = Type::getInt32Ty(M->getContext());
11692
11693     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
11694     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
11695     if (!Subtarget->isLittle())
11696       std::swap (Lo, Hi);
11697     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
11698     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
11699   }
11700
11701   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
11702   Type *Tys[] = { Addr->getType() };
11703   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
11704
11705   return Builder.CreateCall(
11706       Strex, {Builder.CreateZExtOrBitCast(
11707                   Val, Strex->getFunctionType()->getParamType(0)),
11708               Addr});
11709 }
11710
11711 /// \brief Lower an interleaved load into a vldN intrinsic.
11712 ///
11713 /// E.g. Lower an interleaved load (Factor = 2):
11714 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
11715 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
11716 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
11717 ///
11718 ///      Into:
11719 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
11720 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
11721 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
11722 bool ARMTargetLowering::lowerInterleavedLoad(
11723     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
11724     ArrayRef<unsigned> Indices, unsigned Factor) const {
11725   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11726          "Invalid interleave factor");
11727   assert(!Shuffles.empty() && "Empty shufflevector input");
11728   assert(Shuffles.size() == Indices.size() &&
11729          "Unmatched number of shufflevectors and indices");
11730
11731   VectorType *VecTy = Shuffles[0]->getType();
11732   Type *EltTy = VecTy->getVectorElementType();
11733
11734   const DataLayout &DL = LI->getModule()->getDataLayout();
11735   unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
11736   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11737
11738   // Skip illegal vector types and vector types of i64/f64 element (vldN doesn't
11739   // support i64/f64 element).
11740   if ((VecSize != 64 && VecSize != 128) || EltIs64Bits)
11741     return false;
11742
11743   // A pointer vector can not be the return type of the ldN intrinsics. Need to
11744   // load integer vectors first and then convert to pointer vectors.
11745   if (EltTy->isPointerTy())
11746     VecTy =
11747         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
11748
11749   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
11750                                             Intrinsic::arm_neon_vld3,
11751                                             Intrinsic::arm_neon_vld4};
11752
11753   Function *VldnFunc =
11754       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], VecTy);
11755
11756   IRBuilder<> Builder(LI);
11757   SmallVector<Value *, 2> Ops;
11758
11759   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
11760   Ops.push_back(Builder.CreateBitCast(LI->getPointerOperand(), Int8Ptr));
11761   Ops.push_back(Builder.getInt32(LI->getAlignment()));
11762
11763   CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
11764
11765   // Replace uses of each shufflevector with the corresponding vector loaded
11766   // by ldN.
11767   for (unsigned i = 0; i < Shuffles.size(); i++) {
11768     ShuffleVectorInst *SV = Shuffles[i];
11769     unsigned Index = Indices[i];
11770
11771     Value *SubVec = Builder.CreateExtractValue(VldN, Index);
11772
11773     // Convert the integer vector to pointer vector if the element is pointer.
11774     if (EltTy->isPointerTy())
11775       SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
11776
11777     SV->replaceAllUsesWith(SubVec);
11778   }
11779
11780   return true;
11781 }
11782
11783 /// \brief Get a mask consisting of sequential integers starting from \p Start.
11784 ///
11785 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
11786 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
11787                                    unsigned NumElts) {
11788   SmallVector<Constant *, 16> Mask;
11789   for (unsigned i = 0; i < NumElts; i++)
11790     Mask.push_back(Builder.getInt32(Start + i));
11791
11792   return ConstantVector::get(Mask);
11793 }
11794
11795 /// \brief Lower an interleaved store into a vstN intrinsic.
11796 ///
11797 /// E.g. Lower an interleaved store (Factor = 3):
11798 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
11799 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
11800 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
11801 ///
11802 ///      Into:
11803 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
11804 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
11805 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
11806 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
11807 ///
11808 /// Note that the new shufflevectors will be removed and we'll only generate one
11809 /// vst3 instruction in CodeGen.
11810 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
11811                                               ShuffleVectorInst *SVI,
11812                                               unsigned Factor) const {
11813   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
11814          "Invalid interleave factor");
11815
11816   VectorType *VecTy = SVI->getType();
11817   assert(VecTy->getVectorNumElements() % Factor == 0 &&
11818          "Invalid interleaved store");
11819
11820   unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
11821   Type *EltTy = VecTy->getVectorElementType();
11822   VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
11823
11824   const DataLayout &DL = SI->getModule()->getDataLayout();
11825   unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
11826   bool EltIs64Bits = DL.getTypeAllocSizeInBits(EltTy) == 64;
11827
11828   // Skip illegal sub vector types and vector types of i64/f64 element (vstN
11829   // doesn't support i64/f64 element).
11830   if ((SubVecSize != 64 && SubVecSize != 128) || EltIs64Bits)
11831     return false;
11832
11833   Value *Op0 = SVI->getOperand(0);
11834   Value *Op1 = SVI->getOperand(1);
11835   IRBuilder<> Builder(SI);
11836
11837   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
11838   // vectors to integer vectors.
11839   if (EltTy->isPointerTy()) {
11840     Type *IntTy = DL.getIntPtrType(EltTy);
11841
11842     // Convert to the corresponding integer vector.
11843     Type *IntVecTy =
11844         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
11845     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
11846     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
11847
11848     SubVecTy = VectorType::get(IntTy, NumSubElts);
11849   }
11850
11851   static Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
11852                                        Intrinsic::arm_neon_vst3,
11853                                        Intrinsic::arm_neon_vst4};
11854   Function *VstNFunc = Intrinsic::getDeclaration(
11855       SI->getModule(), StoreInts[Factor - 2], SubVecTy);
11856
11857   SmallVector<Value *, 6> Ops;
11858
11859   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
11860   Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), Int8Ptr));
11861
11862   // Split the shufflevector operands into sub vectors for the new vstN call.
11863   for (unsigned i = 0; i < Factor; i++)
11864     Ops.push_back(Builder.CreateShuffleVector(
11865         Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
11866
11867   Ops.push_back(Builder.getInt32(SI->getAlignment()));
11868   Builder.CreateCall(VstNFunc, Ops);
11869   return true;
11870 }
11871
11872 enum HABaseType {
11873   HA_UNKNOWN = 0,
11874   HA_FLOAT,
11875   HA_DOUBLE,
11876   HA_VECT64,
11877   HA_VECT128
11878 };
11879
11880 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
11881                                    uint64_t &Members) {
11882   if (auto *ST = dyn_cast<StructType>(Ty)) {
11883     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
11884       uint64_t SubMembers = 0;
11885       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
11886         return false;
11887       Members += SubMembers;
11888     }
11889   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
11890     uint64_t SubMembers = 0;
11891     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
11892       return false;
11893     Members += SubMembers * AT->getNumElements();
11894   } else if (Ty->isFloatTy()) {
11895     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
11896       return false;
11897     Members = 1;
11898     Base = HA_FLOAT;
11899   } else if (Ty->isDoubleTy()) {
11900     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
11901       return false;
11902     Members = 1;
11903     Base = HA_DOUBLE;
11904   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
11905     Members = 1;
11906     switch (Base) {
11907     case HA_FLOAT:
11908     case HA_DOUBLE:
11909       return false;
11910     case HA_VECT64:
11911       return VT->getBitWidth() == 64;
11912     case HA_VECT128:
11913       return VT->getBitWidth() == 128;
11914     case HA_UNKNOWN:
11915       switch (VT->getBitWidth()) {
11916       case 64:
11917         Base = HA_VECT64;
11918         return true;
11919       case 128:
11920         Base = HA_VECT128;
11921         return true;
11922       default:
11923         return false;
11924       }
11925     }
11926   }
11927
11928   return (Members > 0 && Members <= 4);
11929 }
11930
11931 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
11932 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
11933 /// passing according to AAPCS rules.
11934 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
11935     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
11936   if (getEffectiveCallingConv(CallConv, isVarArg) !=
11937       CallingConv::ARM_AAPCS_VFP)
11938     return false;
11939
11940   HABaseType Base = HA_UNKNOWN;
11941   uint64_t Members = 0;
11942   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
11943   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
11944
11945   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
11946   return IsHA || IsIntArray;
11947 }